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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13df15048eacc1016bef69b88d083a155dfca25f | 584 | py | Python | stock_trading/admin.py | SaurabhPanja/herodha | bb78877cd7d29b80f446245b1b5feb6e16984489 | [
"MIT"
] | 3 | 2019-10-20T07:35:22.000Z | 2021-07-18T13:39:02.000Z | stock_trading/admin.py | SaurabhPanja/herodha | bb78877cd7d29b80f446245b1b5feb6e16984489 | [
"MIT"
] | 7 | 2020-06-05T23:51:41.000Z | 2022-02-10T09:18:21.000Z | stock_trading/admin.py | SaurabhPanja/herodha | bb78877cd7d29b80f446245b1b5feb6e16984489 | [
"MIT"
] | 3 | 2019-10-15T06:12:58.000Z | 2019-11-04T12:07:24.000Z | from django.contrib import admin
from .models import User, SellTransaction, BuyTransaction, Bookmark
admin.site.register(SellTransaction)
admin.site.register(BuyTransaction)
admin.site.register(Bookmark)
# Register your models here.
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
# form = CustomUserChangeForm
model = User
list_display = ['email', 'username',]
admin.site.register(User, CustomUserAdmin)
| 26.545455 | 67 | 0.799658 | 66 | 584 | 7.015152 | 0.439394 | 0.077754 | 0.146868 | 0.090713 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.121575 | 584 | 21 | 68 | 27.809524 | 0.902534 | 0.092466 | 0 | 0 | 0 | 0 | 0.024715 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.384615 | 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 |
13e810afa620c13d68c61f1e12f1a66b3a2213aa | 546 | py | Python | scipy/signal/__init__.py | GaelVaroquaux/scipy | aa80ab6a6d62a3923253bb6b296f41afa3d31845 | [
"BSD-3-Clause"
] | null | null | null | scipy/signal/__init__.py | GaelVaroquaux/scipy | aa80ab6a6d62a3923253bb6b296f41afa3d31845 | [
"BSD-3-Clause"
] | null | null | null | scipy/signal/__init__.py | GaelVaroquaux/scipy | aa80ab6a6d62a3923253bb6b296f41afa3d31845 | [
"BSD-3-Clause"
] | null | null | null | #
# signal - Signal Processing Tools
#
from info import __doc__
import sigtools
from waveforms import *
# The spline module (a C extension) provides:
# cspline2d, qspline2d, sepfir2d, symiirord1, symiirord2
from spline import *
from bsplines import *
from filter_design import *
from fir_filter_design import *
from ltisys import *
from windows import *
from signaltools import *
from spectral import *
from wavelets import *
__all__ = filter(lambda s: not s.startswith('_'), dir())
from numpy.testing import Tester
test = Tester().test
| 21 | 60 | 0.760073 | 71 | 546 | 5.676056 | 0.56338 | 0.198511 | 0.08933 | 0.109181 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010989 | 0.166667 | 546 | 25 | 61 | 21.84 | 0.874725 | 0.247253 | 0 | 0 | 0 | 0 | 0.002469 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.866667 | 0 | 0.866667 | 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 |
13e81901f67f7570368bde8b92fefb6c9a70c301 | 1,500 | py | Python | sympy/physics/quantum/constants.py | shipci/sympy | 4b59927bed992b980c9b3faac01becb36feef26b | [
"BSD-3-Clause"
] | 319 | 2016-09-22T15:54:48.000Z | 2022-03-18T02:36:58.000Z | sympy/physics/quantum/constants.py | shipci/sympy | 4b59927bed992b980c9b3faac01becb36feef26b | [
"BSD-3-Clause"
] | 9 | 2016-11-03T21:56:41.000Z | 2020-08-09T19:27:37.000Z | sympy/physics/quantum/constants.py | shipci/sympy | 4b59927bed992b980c9b3faac01becb36feef26b | [
"BSD-3-Clause"
] | 27 | 2016-10-06T16:05:32.000Z | 2022-03-18T02:37:00.000Z | """Constants (like hbar) related to quantum mechanics."""
from __future__ import print_function, division
from sympy.core.numbers import NumberSymbol
from sympy.core.singleton import Singleton
from sympy.core.compatibility import u, with_metaclass
from sympy.printing.pretty.stringpict import prettyForm
import sympy.mpmath.libmp as mlib
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
__all__ = [
'hbar'
]
class HBar(with_metaclass(Singleton, NumberSymbol)):
"""Reduced Plank's constant in numerical and symbolic form [1]_.
Examples
========
>>> from sympy.physics.quantum.constants import hbar
>>> hbar.evalf()
1.05457162000000e-34
References
==========
.. [1] http://en.wikipedia.org/wiki/Planck_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
__slots__ = []
def _as_mpf_val(self, prec):
return mlib.from_float(1.05457162e-34, prec)
def _sympyrepr(self, printer, *args):
return 'HBar()'
def _sympystr(self, printer, *args):
return 'hbar'
def _pretty(self, printer, *args):
if printer._use_unicode:
return prettyForm(u('\u210f'))
return prettyForm('hbar')
def _latex(self, printer, *args):
return r'\hbar'
# Create an instance for everyone to use.
hbar = HBar()
| 24.193548 | 78 | 0.59 | 161 | 1,500 | 5.304348 | 0.52795 | 0.052693 | 0.070258 | 0.07377 | 0.065574 | 0.065574 | 0 | 0 | 0 | 0 | 0 | 0.027592 | 0.202667 | 1,500 | 61 | 79 | 24.590164 | 0.686455 | 0.344667 | 0 | 0 | 0 | 0 | 0.031116 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.178571 | false | 0 | 0.214286 | 0.142857 | 0.821429 | 0.25 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
13ee1649758294ad34e713fc2cc036dd2e133326 | 282 | py | Python | mite/web/__init__.py | tonysimpson/mite | 2a99a7b05204de444006e57e2c66e9f87fbcc357 | [
"MIT"
] | 1 | 2017-11-19T21:43:55.000Z | 2017-11-19T21:43:55.000Z | mite/web/__init__.py | tonysimpson/mite | 2a99a7b05204de444006e57e2c66e9f87fbcc357 | [
"MIT"
] | null | null | null | mite/web/__init__.py | tonysimpson/mite | 2a99a7b05204de444006e57e2c66e9f87fbcc357 | [
"MIT"
] | null | null | null | import sys
from flask import Flask, Response
from .prometheus import PrometheusMetrics
app = Flask(__name__)
prometheus_metrics = PrometheusMetrics()
@app.route('/metrics')
def metrics():
text = prometheus_metrics.format()
return Response(text, mimetype='text/plain')
| 17.625 | 48 | 0.755319 | 32 | 282 | 6.46875 | 0.53125 | 0.193237 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.141844 | 282 | 15 | 49 | 18.8 | 0.855372 | 0 | 0 | 0 | 0 | 0 | 0.064286 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0 | 0.333333 | 0 | 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 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
13f7760283241b44387910bfaf8c44e55327fb13 | 4,116 | py | Python | userprofile/urls/es.py | jijo-paulose/django-profile | b3aaf225f5728474047d9e41f9d6a65b6de1f70f | [
"BSD-2-Clause"
] | 7 | 2015-01-08T11:11:08.000Z | 2019-07-01T08:12:38.000Z | userprofile/urls/es.py | jijo-paulose/django-profile | b3aaf225f5728474047d9e41f9d6a65b6de1f70f | [
"BSD-2-Clause"
] | 1 | 2016-03-08T21:27:45.000Z | 2016-03-08T21:27:45.000Z | userprofile/urls/es.py | jijo-paulose/django-profile | b3aaf225f5728474047d9e41f9d6a65b6de1f70f | [
"BSD-2-Clause"
] | 3 | 2016-03-10T16:08:36.000Z | 2019-09-18T16:28:35.000Z | from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from userprofile.views import *
from django.conf import settings
urlpatterns = patterns('',
# Private profile
url(r'^perfil/$', overview, name='profile_overview'),
url(r'^perfil/editar/ubicacion/$', location, name='profile_edit_location'),
url(r'^perfil/editar/personal/$', personal, name='profile_edit_personal'),
url(r'^perfil/eliminar/$', delete, name='profile_delete'),
url(r'^perfil/obtener_infopais/(?P<lat>[0-9\.\-]+)/(?P<lng>[0-9\.\-]+)/$',
fetch_geodata,
name='profile_geocountry_info'),
# Avatars
url(r'^perfil/editar/avatar/eliminar/$', avatardelete,
name='profile_avatar_delete'),
url(r'^perfil/editar/avatar/$', avatarchoose, name='profile_edit_avatar'),
url(r'^perfil/editar/avatar/recortar/$', avatarcrop,
name='profile_avatar_crop'),
url(r'^perfil/edit/avatar/recortar/listo/$', direct_to_template,
{ 'extra_context': {'section': 'avatar'},
'template': 'userprofile/avatar/done.html'},
name='profile_avatar_crop_done'),
# Account utilities
url(r'^email/validar/$', email_validation, name='email_validation'),
url(r'^email/validar/procesado/$', direct_to_template,
{'template': 'userprofile/account/email_validation_processed.html'},
name='email_validation_processed'),
url(r'^email/validar/(?P<key>.{70})/$', email_validation_process,
name='email_validation_process'),
url(r'^email/validar/reestablecer/$', email_validation_reset,
name='email_validation_reset'),
url(r'^email/validar/reestablecer/(?P<action>listo|fallo)/$',
direct_to_template,
{'template' : 'userprofile/account/email_validation_reset_response.html'},
name='email_validation_reset_response'),
url(r'^password/reestablecer/$',
'django.contrib.auth.views.password_reset',
{'template_name': 'userprofile/account/password_reset.html',
'email_template_name': 'userprofile/email/password_reset_email.txt' },
name='password_reset'),
url(r'^password/reestablecer/listo/$',
'django.contrib.auth.views.password_reset_done',
{'template_name': 'userprofile/account/password_reset_done.html'},
name='password_reset_done'),
url(r'^password/cambiar/$', 'django.contrib.auth.views.password_change',
{'template_name': 'userprofile/account/password_change.html'},
name='password_change'),
url(r'^password/cambiar/listo/$',
'django.contrib.auth.views.password_change_done',
{'template_name': 'userprofile/account/password_change_done.html'},
name='password_change_done'),
url(r'^reestablecer/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'django.contrib.auth.views.password_reset_confirm',
{'template_name': 'userprofile/account/password_reset_confirm.html'},
name="password_reset_confirm"),
url(r'^reestablecer/listo/$',
'django.contrib.auth.views.password_reset_complete',
{'template_name': 'userprofile/account/password_reset_complete.html'},
name="password_reset_complete"),
url(r'^entrar/$', 'django.contrib.auth.views.login',
{'template_name': 'userprofile/account/login.html'},
name='login'),
url(r'^salir/$', 'django.contrib.auth.views.logout',
{'template_name': 'userprofile/account/logout.html'},
name='logout'),
# Registration
url(r'^registro/$', register, name='signup'),
url(r'^registro/validar/$', direct_to_template,
{'template' : 'userprofile/account/validate.html'},
name='signup_validate'),
url(r'^registro/completo/$', direct_to_template,
{'extra_context': { 'email_validation_required': hasattr(settings, "REQUIRE_EMAIL_CONFIRMATION") and settings.REQUIRE_EMAIL_CONFIRMATION },
'template': 'userprofile/account/registration_done.html'},
name='signup_complete'),
# Users public profile
url(r'^perfil/(?P<username>.+)/$', public, name='profile_public'),
)
| 38.830189 | 147 | 0.677357 | 467 | 4,116 | 5.745182 | 0.214133 | 0.038763 | 0.037272 | 0.065598 | 0.317928 | 0.251584 | 0.081252 | 0.081252 | 0 | 0 | 0 | 0.002874 | 0.154519 | 4,116 | 105 | 148 | 39.2 | 0.768103 | 0.018222 | 0 | 0 | 0 | 0.013699 | 0.574969 | 0.440149 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.30137 | 0.054795 | 0 | 0.054795 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
b92fc8c4f12a3495c3c287978d0d7bbf37e3eae2 | 549 | py | Python | tests/test_compose/test_write/test_tag/test_th.py | schireson/htmxl | d4adef9fe0630f39c3664d3913bbbbe3db3ec069 | [
"MIT"
] | 2 | 2021-08-11T15:15:29.000Z | 2022-03-20T04:04:54.000Z | tests/test_compose/test_write/test_tag/test_th.py | schireson/htmxl | d4adef9fe0630f39c3664d3913bbbbe3db3ec069 | [
"MIT"
] | 5 | 2021-08-18T20:54:32.000Z | 2022-01-24T20:06:46.000Z | tests/test_compose/test_write/test_tag/test_th.py | schireson/htmxl | d4adef9fe0630f39c3664d3913bbbbe3db3ec069 | [
"MIT"
] | null | null | null | from tests.utils import WriteTests
class WriteTh(WriteTests):
fixture_dir = "tests/fixtures/templates/tags/th"
class TestColspanMergesCells(WriteTh):
template_file = "colspan_merges.html.jinja2"
expected_result_file = "colspan_merges.xlsx"
class TestRowspanMergesCells(WriteTh):
template_file = "rowspan_merges.html.jinja2"
expected_result_file = "rowspan_merges.xlsx"
class TestRowspanContainedRow(WriteTh):
template_file = "rowspan_contained_row.html.jinja2"
expected_result_file = "rowspan_contained_row.xlsx"
| 26.142857 | 55 | 0.788707 | 62 | 549 | 6.693548 | 0.451613 | 0.106024 | 0.137349 | 0.173494 | 0.26506 | 0.26506 | 0 | 0 | 0 | 0 | 0 | 0.00625 | 0.125683 | 549 | 20 | 56 | 27.45 | 0.858333 | 0 | 0 | 0 | 0 | 0 | 0.32969 | 0.260474 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.083333 | 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 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
b930c55fe27b75765321f96d389fdf468a4819f5 | 1,181 | py | Python | bismuthcore/Utils/export_json100k.py | bismuthfoundation/BismuthCore | cad565c8874dc65c4004c92a29a533190f73a51a | [
"MIT"
] | 2 | 2020-03-04T12:35:59.000Z | 2020-03-28T04:17:45.000Z | bismuthcore/Utils/export_json100k.py | bismuthfoundation/BismuthCore | cad565c8874dc65c4004c92a29a533190f73a51a | [
"MIT"
] | 1 | 2019-01-11T15:57:06.000Z | 2019-01-11T18:30:47.000Z | bismuthcore/Utils/export_json100k.py | bismuthfoundation/BismuthCore | cad565c8874dc65c4004c92a29a533190f73a51a | [
"MIT"
] | null | null | null | """
Export 100k tx to json format for benchmark
Test temp util
"""
import json
import sqlite3
import sys
from os import remove
sys.path.append('../')
from bismuthcore.transaction import Transaction
if __name__ == "__main__":
try:
remove('tx_dataset.json')
except:
pass
try:
remove('tx_tuple_dataset.json')
except:
pass
with sqlite3.connect('../../../Bismuth-temp/static/ledger.db', timeout=1) as ledger:
# TODO: use a default path and give custom db path to command line for more flexible use depending on context
ledger.text_factory = str
res = ledger.execute("select * from transactions where block_height > 700000 limit 100000")
with open("tx_dataset.json", "w") as fp:
for row in res:
tx = Transaction.from_legacy(row)
fp.write(tx.to_json() + "\n")
res = ledger.execute("select * from transactions where block_height > 700000 limit 100000")
with open("tx_tuple_dataset.json", "w") as fp:
for row in res:
tx = Transaction.from_legacy(row)
fp.write(json.dumps(tx.to_tuple()) + "\n")
| 28.804878 | 117 | 0.622354 | 156 | 1,181 | 4.576923 | 0.474359 | 0.061625 | 0.022409 | 0.058824 | 0.394958 | 0.394958 | 0.394958 | 0.394958 | 0.394958 | 0.394958 | 0 | 0.034803 | 0.27011 | 1,181 | 40 | 118 | 29.525 | 0.793503 | 0.142252 | 0 | 0.444444 | 0 | 0 | 0.25996 | 0.079681 | 0 | 0 | 0 | 0.025 | 0 | 1 | 0 | false | 0.074074 | 0.185185 | 0 | 0.185185 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
b93f18ef93d7e5da9a3f030989e1fad2e2b4d074 | 3,124 | py | Python | Core/Reddit.py | mickylindsay/VinnyBot | c62245c1631b2505ac724124bc666387b30129ac | [
"MIT"
] | 2 | 2020-01-01T15:08:38.000Z | 2020-06-24T03:09:42.000Z | Core/Reddit.py | mickylindsay/VinnyBot | c62245c1631b2505ac724124bc666387b30129ac | [
"MIT"
] | null | null | null | Core/Reddit.py | mickylindsay/VinnyBot | c62245c1631b2505ac724124bc666387b30129ac | [
"MIT"
] | null | null | null | import praw
import random
import itertools
from nsfw import isEnabled
def main():
print("--------------------")
print("asdf " + random_hot_post(''))
print("--------------------")
def random_hot_post(subreddit, limit, message):
r = praw.Reddit(user_agent='Discord Bot', client_id='byorb8K1SwaO1g', client_secret='qFBAtKZuQfvWcOhmO495ia7BH68')
if r.subreddit(subreddit).over18:
if not isEnabled(message):
return ":x: Error: Subreddit is NSFW and NSFW is not enabled in this channel. An admin can run the '~togglensfw' command to enable it :x:"
submissions = r.subreddit(subreddit).hot(limit=limit)
if submissions is None:
return None
num = random.randrange(1, limit) - 1
try:
hot_page = list(itertools.islice(submissions, limit))
if len(hot_page) == 0:
return 'Failed to find post matching parameters.'
random_page = hot_page[num]
except:
return None
if random_page.stickied:
return random_hot_post(subreddit, limit + 1, message)
if subreddit != 'shitpost':
return random_page.url
try:
linked_post = r.submission(url=random_page.url)
return linked_post.url
except:
return random_page.url
def getCosplay(message, client):
limit = 30
r = praw.Reddit(user_agent='Discord Bot', client_id='byorb8K1SwaO1g', client_secret='qFBAtKZuQfvWcOhmO495ia7BH68')
try:
searchTerms = message.content.split(" ")[1]
searchTerms.replace('_', ' ')
submissions = r.subreddit('cosplay').search(searchTerms, limit=limit)
except IndexError:
submissions = r.subreddit('cosplay').hot(limit=limit)
num = random.randrange(1, limit) - 1
try:
hot_page = list(itertools.islice(submissions, limit))
except:
return 'There was an error retrieving a post :cty:'
if len(hot_page) == 0:
return 'Failed to find post matching parameters.'
try:
random_page = hot_page[num]
except:
return 'Failed to find a post matching parameters.'
if random_page.stickied:
return getCosplay(message, client)
return random_page.url
def getCosplayGirl(message, client):
limit = 30
r = praw.Reddit(user_agent='Discord Bot', client_id='byorb8K1SwaO1g', client_secret='qFBAtKZuQfvWcOhmO495ia7BH68')
try:
searchTerms = message.content.split(" ")[1]
searchTerms.replace('_', ' ')
submissions = r.subreddit('cosplaygirls').search(searchTerms, limit=limit)
except IndexError:
submissions = r.subreddit('cosplaygirls').hot(limit=limit)
num = random.randrange(1, limit) - 1
try:
hot_page = list(itertools.islice(submissions, limit))
except:
return 'There was an error retrieving a post :cty:'
if len(hot_page) == 0:
return 'Failed to find post matching parameters.'
try:
random_page = hot_page[num]
except:
return 'Failed to find a post matching parameters.'
if random_page.stickied:
return getCosplay(message, client)
return random_page.url
| 28.925926 | 150 | 0.650768 | 371 | 3,124 | 5.374663 | 0.231806 | 0.055166 | 0.052658 | 0.045135 | 0.744734 | 0.692076 | 0.692076 | 0.676028 | 0.676028 | 0.611836 | 0 | 0.018813 | 0.234315 | 3,124 | 107 | 151 | 29.196262 | 0.814799 | 0 | 0 | 0.721519 | 0 | 0.012658 | 0.214469 | 0.025928 | 0 | 0 | 0 | 0 | 0 | 1 | 0.050633 | false | 0 | 0.050633 | 0 | 0.329114 | 0.037975 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
b942231006eb0a5aae5f3073e47e25dd1946c4a2 | 3,022 | py | Python | setup.py | 0xflotus/fluxgui | a3b55da976053fc978b29d191db52dfb8da2f8ee | [
"MIT"
] | 1 | 2018-11-11T17:10:57.000Z | 2018-11-11T17:10:57.000Z | setup.py | 0xflotus/fluxgui | a3b55da976053fc978b29d191db52dfb8da2f8ee | [
"MIT"
] | null | null | null | setup.py | 0xflotus/fluxgui | a3b55da976053fc978b29d191db52dfb8da2f8ee | [
"MIT"
] | 1 | 2018-03-21T07:04:29.000Z | 2018-03-21T07:04:29.000Z | #!/usr/bin/env python
from distutils.core import setup
import os
data_files = [
('share/icons/hicolor/16x16/apps', ['icons/hicolor/16x16/apps/fluxgui.svg']),
('share/icons/hicolor/22x22/apps', ['icons/hicolor/22x22/apps/fluxgui.svg']),
('share/icons/hicolor/24x24/apps', ['icons/hicolor/24x24/apps/fluxgui.svg']),
('share/icons/hicolor/32x32/apps', ['icons/hicolor/32x32/apps/fluxgui.svg']),
('share/icons/hicolor/48x48/apps', ['icons/hicolor/48x48/apps/fluxgui.svg']),
('share/icons/hicolor/64x64/apps', ['icons/hicolor/64x64/apps/fluxgui.svg']),
('share/icons/hicolor/96x96/apps', ['icons/hicolor/96x96/apps/fluxgui.svg']),
('share/icons/ubuntu-mono-dark/status/16', ['icons/ubuntu-mono-dark/status/16/fluxgui-panel.svg']),
('share/icons/ubuntu-mono-dark/status/22', ['icons/ubuntu-mono-dark/status/22/fluxgui-panel.svg']),
('share/icons/ubuntu-mono-dark/status/24', ['icons/ubuntu-mono-dark/status/24/fluxgui-panel.svg']),
('share/icons/ubuntu-mono-light/status/16', ['icons/ubuntu-mono-light/status/16/fluxgui-panel.svg']),
('share/icons/ubuntu-mono-light/status/22', ['icons/ubuntu-mono-light/status/22/fluxgui-panel.svg']),
('share/icons/ubuntu-mono-light/status/24', ['icons/ubuntu-mono-light/status/24/fluxgui-panel.svg']),
('share/icons/Adwaita/16x16/status', ['icons/Adwaita/16x16/status/fluxgui-panel.svg']),
('share/icons/breeze/status/22', ['icons/breeze/status/22/fluxgui-panel.svg']),
('share/icons/breeze-dark/status/22', ['icons/breeze-dark/status/22/fluxgui-panel.svg']),
('share/icons/elementary/status/24', ['icons/elementary/status/24/fluxgui-panel.svg']),
('share/icons/elementary-xfce/panel/22', ['icons/elementary-xfce/panel/22/fluxgui-panel.svg']),
('share/icons/elementary-xfce-dark/panel/22', ['icons/elementary-xfce-dark/panel/22/fluxgui-panel.svg']),
('share/applications', ['desktop/fluxgui.desktop'])]
scripts = ['fluxgui']
if (os.path.exists("xflux")):
scripts.append('xflux')
else:
print("""WARNING: if you are running 'python setup.py' manually, and not as
part of Debian package creation, then you need to download the 'xflux'
binary separately. You can do this by running
python ./download-xflux.py
before running 'setup.py'.""")
setup(name = "f.lux indicator applet",
version = "1.1.11~pre",
description = "f.lux indicator applet - better lighting for your computer",
author = "Kilian Valkhof, Michael and Lorna Herf, Josh Winters",
author_email = "kilian@kilianvalkhof.com",
url = "http://www.stereopsis.com/flux/",
license = "MIT license",
package_dir = {'fluxgui' : 'src/fluxgui'},
packages = ["fluxgui",],
package_data = {"fluxgui" : ["*.glade"] },
data_files=data_files,
scripts = scripts,
long_description = """f.lux indicator applet is an indicator applet to
control xflux, an application that makes the color of your computer's
display adapt to the time of day, warm at nights and like sunlight during
the day""",
)
| 52.103448 | 109 | 0.697551 | 423 | 3,022 | 4.966903 | 0.307329 | 0.090433 | 0.111376 | 0.114231 | 0.495002 | 0.437887 | 0.240838 | 0.143265 | 0.123751 | 0 | 0 | 0.041916 | 0.115817 | 3,022 | 57 | 110 | 53.017544 | 0.744386 | 0.006618 | 0 | 0 | 0 | 0 | 0.744 | 0.506333 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.040816 | 0 | 0.040816 | 0.020408 | 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 |
b94931090c0b381ceed02988dafe7587242b1557 | 1,280 | py | Python | Winter 2017/lec2/codingpractice.py | hyunjaemoon/pythonteaching | ee4da847cab548b9a39767d22b2586de927d8513 | [
"CECILL-B"
] | null | null | null | Winter 2017/lec2/codingpractice.py | hyunjaemoon/pythonteaching | ee4da847cab548b9a39767d22b2586de927d8513 | [
"CECILL-B"
] | null | null | null | Winter 2017/lec2/codingpractice.py | hyunjaemoon/pythonteaching | ee4da847cab548b9a39767d22b2586de927d8513 | [
"CECILL-B"
] | null | null | null |
def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add
>>> curried_add = lambda_curry2(add)
>>> add_three = curried_add(3)
>>> add_three(5)
8
"""
"*** YOUR CODE HERE ***"
return ______
def compose1(f, g):
"""Return the composition function which given x, computes f(g(x)).
>>> add_one = lambda x: x + 1 # adds one to x
>>> square = lambda x: x**2
>>> a1 = compose1(square, add_one) # (x + 1)^2
>>> a1(4)
25
>>> mul_three = lambda x: x * 3 # multiplies 3 to x
>>> a2 = compose1(mul_three, a1) # ((x + 1)^2) * 3
>>> a2(4)
75
>>> a2(5)
108
"""
return lambda x: f(g(x))
def composite_identity(f, g):
"""
Return a function with one parameter x that returns True if f(g(x)) is
equal to g(f(x)). You can assume the result of g(x) is a valid input for f
and vice versa.
>>> add_one = lambda x: x + 1 # adds one to x
>>> square = lambda x: x**2
>>> b1 = composite_identity(square, add_one)
>>> b1(0) # (0 + 1)^2 == 0^2 + 1
True
>>> b1(4) # (4 + 1)^2 != 4^2 + 1
False
"""
"*** YOUR CODE HERE ***"
| 27.826087 | 78 | 0.503906 | 192 | 1,280 | 3.255208 | 0.359375 | 0.0672 | 0.064 | 0.0416 | 0.128 | 0.128 | 0.128 | 0.128 | 0.128 | 0.128 | 0 | 0.061393 | 0.338281 | 1,280 | 45 | 79 | 28.444444 | 0.676505 | 0.735156 | 0 | 0.285714 | 0 | 0 | 0.22335 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.428571 | false | 0 | 0 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
b94d1d604d91064566630972c17d17b92ac0902f | 1,837 | py | Python | RQ1/periodic_activations.py | SuShu19/TiTIC | 7dd83a1527ee0e57e354eb7843c75ad2e53d69fc | [
"Apache-2.0"
] | null | null | null | RQ1/periodic_activations.py | SuShu19/TiTIC | 7dd83a1527ee0e57e354eb7843c75ad2e53d69fc | [
"Apache-2.0"
] | null | null | null | RQ1/periodic_activations.py | SuShu19/TiTIC | 7dd83a1527ee0e57e354eb7843c75ad2e53d69fc | [
"Apache-2.0"
] | null | null | null | import torch
from torch import nn
import numpy as np
import math
def t2v(tau, f, out_features, w, b, w0, b0, arg=None):
if arg:
v1 = f(torch.matmul(tau, w) + b, arg)
else:
#print(w.shape, t1.shape, b.shape)
v1 = f(torch.matmul(tau, w) + b)
v2 = torch.matmul(tau, w0) + b0
#print(v1.shape)
# return torch.cat([v1, v2], 1)
return torch.cat([v1, v2], 2)
class SineActivation(nn.Module):
def __init__(self, in_features, out_features):
super(SineActivation, self).__init__()
self.out_features = out_features
self.w0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.b0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.w = nn.parameter.Parameter(torch.randn(in_features, out_features-1))
self.b = nn.parameter.Parameter(torch.randn(in_features, out_features-1))
self.f = torch.sin
def forward(self, tau):
return t2v(tau, self.f, self.out_features, self.w, self.b, self.w0, self.b0)
class CosineActivation(nn.Module):
def __init__(self, in_features, out_features):
super(CosineActivation, self).__init__()
self.out_features = out_features
self.w0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.b0 = nn.parameter.Parameter(torch.randn(in_features, 1))
self.w = nn.parameter.Parameter(torch.randn(in_features, out_features-1))
self.b = nn.parameter.Parameter(torch.randn(in_features, out_features-1))
self.f = torch.cos
def forward(self, tau):
return t2v(tau, self.f, self.out_features, self.w, self.b, self.w0, self.b0)
if __name__ == "__main__":
sineact = SineActivation(1, 64)
cosact = CosineActivation(1, 64)
print(sineact(torch.Tensor([[7]])).shape)
print(cosact(torch.Tensor([[7]])).shape)
| 37.489796 | 84 | 0.656505 | 269 | 1,837 | 4.30855 | 0.193309 | 0.123382 | 0.131148 | 0.172563 | 0.698878 | 0.667817 | 0.667817 | 0.63503 | 0.63503 | 0.63503 | 0 | 0.028649 | 0.20196 | 1,837 | 49 | 85 | 37.489796 | 0.761937 | 0.042461 | 0 | 0.421053 | 0 | 0 | 0.004553 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.131579 | false | 0 | 0.105263 | 0.052632 | 0.368421 | 0.052632 | 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 |
b9825b70794b01d7fbb843dae656b4c1648d3f4b | 1,999 | py | Python | Lib/site-packages/boto3/exceptions.py | bopopescu/django-estore | c092ffa965b8ef68e71d27d34a17fde1beacd90e | [
"MIT"
] | 4 | 2015-10-20T15:18:40.000Z | 2018-01-17T10:03:19.000Z | venv/lib/python2.7/site-packages/boto3/exceptions.py | LockScreen/Backend | 42485a997f365172c7a63527f0df3b5707fd23f9 | [
"MIT"
] | null | null | null | venv/lib/python2.7/site-packages/boto3/exceptions.py | LockScreen/Backend | 42485a997f365172c7a63527f0df3b5707fd23f9 | [
"MIT"
] | 2 | 2019-04-29T14:16:10.000Z | 2020-07-23T12:04:17.000Z | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
class ResourceLoadException(Exception):
pass
class NoVersionFound(Exception):
pass
class RetriesExceededError(Exception):
def __init__(self, last_exception, msg='Max Retries Exceeded'):
super(RetriesExceededError, self).__init__(msg)
self.last_exception = last_exception
class S3TransferFailedError(Exception):
pass
class S3UploadFailedError(Exception):
pass
class DynamoDBOperationNotSupportedError(Exception):
"""Raised for operantions that are not supported for an operand"""
def __init__(self, operation, value):
msg = (
'%s operation cannot be applied to value %s of type %s directly. '
'Must use AttributeBase object methods (i.e. Attr().eq()). to '
'generate ConditionBase instances first.' %
(operation, value, type(value)))
Exception.__init__(self, msg)
# FIXME: Backward compatibility
DynanmoDBOperationNotSupportedError = DynamoDBOperationNotSupportedError
class DynamoDBNeedsConditionError(Exception):
"""Raised when input is not a condition"""
def __init__(self, value):
msg = (
'Expecting a ConditionBase object. Got %s of type %s. '
'Use AttributeBase object methods (i.e. Attr().eq()). to '
'generate ConditionBase instances.' % (value, type(value)))
Exception.__init__(self, msg)
class DynamoDBNeedsKeyConditionError(Exception):
pass
| 32.770492 | 78 | 0.708354 | 232 | 1,999 | 5.987069 | 0.5 | 0.043197 | 0.051836 | 0.011519 | 0.148308 | 0.148308 | 0.148308 | 0.099352 | 0.099352 | 0.099352 | 0 | 0.006285 | 0.204102 | 1,999 | 60 | 79 | 33.316667 | 0.86675 | 0.332666 | 0 | 0.3 | 0 | 0 | 0.248665 | 0 | 0 | 0 | 0 | 0.016667 | 0 | 1 | 0.1 | false | 0.166667 | 0 | 0 | 0.366667 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
b992f85554a1d8a02b573ab84d518b5c77b73dc2 | 2,109 | py | Python | vega/algorithms/nas/__init__.py | zjzh/vega | aa6e7b8c69024262fc483ee06113b4d1bd5156d8 | [
"Apache-2.0"
] | null | null | null | vega/algorithms/nas/__init__.py | zjzh/vega | aa6e7b8c69024262fc483ee06113b4d1bd5156d8 | [
"Apache-2.0"
] | null | null | null | vega/algorithms/nas/__init__.py | zjzh/vega | aa6e7b8c69024262fc483ee06113b4d1bd5156d8 | [
"Apache-2.0"
] | null | null | null | # -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Lazy import nas algorithms."""
from vega.common.class_factory import ClassFactory
ClassFactory.lazy_register("vega.algorithms.nas", {
"adelaide_ea": ["AdelaideCodec", "AdelaideMutate", "AdelaideRandom", "AdelaideEATrainerCallback"],
"auto_lane": ["AutoLaneNas", "AutoLaneNasCodec", "AutoLaneTrainerCallback"],
"backbone_nas": ["BackboneNasCodec", "BackboneNasSearchSpace", "BackboneNas"],
"cars": ["CARSAlgorithm", "CARSTrainerCallback", "CARSPolicyConfig"],
"darts_cnn": ["DartsCodec", "DartsFullTrainerCallback", "DartsNetworkTemplateConfig", "DartsTrainerCallback"],
"dnet_nas": ["DblockNasCodec", "DblockNas", "DnetNasCodec", "DnetNas"],
"esr_ea": ["ESRCodec", "ESRTrainerCallback", "ESRSearch"],
"fis": ["AutoGateGrdaS1TrainerCallback", "AutoGateGrdaS2TrainerCallback", "AutoGateS1TrainerCallback",
"AutoGateS2TrainerCallback", "AutoGroupTrainerCallback", "CtrTrainerCallback"],
"mfkd": ["MFKD1", "SimpleCnnMFKD"],
"modnas": ["ModNasAlgorithm", "ModNasTrainerCallback"],
"segmentation_ea": ["SegmentationCodec", "SegmentationEATrainerCallback", "SegmentationNas"],
"sgas": ["SGASTrainerCallback"],
"sm_nas": ["SmNasCodec", "SMNasM"],
"sp_nas": ["SpNasS", "SpNasP", "ReignitionCallback"],
"sr_ea": ["SRCodec", "SRMutate", "SRRandom"],
"mfasc": ["search_algorithm:MFASC"],
"opt_nas": ["OperatorSearchSpace", "OperatorReplaceCallback"],
"dag_block_nas": ["DAGBlockNas"],
})
| 50.214286 | 114 | 0.720721 | 199 | 2,109 | 7.557789 | 0.78392 | 0.039894 | 0.017287 | 0.021277 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007638 | 0.130868 | 2,109 | 41 | 115 | 51.439024 | 0.812875 | 0.30441 | 0 | 0 | 0 | 0 | 0.656077 | 0.239641 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.045455 | 0 | 0.045455 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
b99f8eafe24314fcf5c72b1fe45f17e88b0f9c67 | 7,077 | py | Python | plugins/cuckoo/komand_cuckoo/actions/cuckoo_status/schema.py | lukaszlaszuk/insightconnect-plugins | 8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892 | [
"MIT"
] | 46 | 2019-06-05T20:47:58.000Z | 2022-03-29T10:18:01.000Z | plugins/cuckoo/komand_cuckoo/actions/cuckoo_status/schema.py | lukaszlaszuk/insightconnect-plugins | 8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892 | [
"MIT"
] | 386 | 2019-06-07T20:20:39.000Z | 2022-03-30T17:35:01.000Z | plugins/cuckoo/komand_cuckoo/actions/cuckoo_status/schema.py | lukaszlaszuk/insightconnect-plugins | 8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892 | [
"MIT"
] | 43 | 2019-07-09T14:13:58.000Z | 2022-03-28T12:04:46.000Z | # GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Returns status of the cuckoo server"
class Input:
pass
class Output:
CPULOAD = "cpuload"
DISKSPACE = "diskspace"
HOSTNAME = "hostname"
MACHINES = "machines"
TASKS = "tasks"
VERSION = "version"
class CuckooStatusInput(komand.Input):
schema = json.loads("""
{}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
class CuckooStatusOutput(komand.Output):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"cpuload": {
"type": "array",
"title": "CPU Load",
"description": "CPU load for the past 1, 5 and 15 minutes respectively",
"items": {
"type": "number"
},
"order": 1
},
"diskspace": {
"$ref": "#/definitions/diskspace",
"title": "Diskspace",
"description": "Free, total and used diskspace of $CUCKOO/storage/analyses/, $CUCKOO/storage/binaries/, and specified tmppath",
"order": 2
},
"hostname": {
"type": "string",
"title": "Hostname",
"description": "Cuckoo hostname",
"order": 3
},
"machines": {
"$ref": "#/definitions/machines",
"title": "Machines",
"description": "Details about available and total analysis machines",
"order": 4
},
"tasks": {
"$ref": "#/definitions/tasks",
"title": "Tasks",
"description": "Details about analysis tasks",
"order": 5
},
"version": {
"type": "string",
"title": "Version",
"description": "Cuckoo version",
"order": 6
}
},
"required": [
"cpuload",
"diskspace",
"hostname",
"machines",
"tasks",
"version"
],
"definitions": {
"analyses": {
"type": "object",
"title": "analyses",
"properties": {
"free": {
"type": "integer",
"title": "Free",
"description": "Free diskspace",
"order": 2
},
"total": {
"type": "integer",
"title": "Total",
"description": "Total diskspace",
"order": 1
},
"used": {
"type": "integer",
"title": "Used",
"description": "Used diskspace",
"order": 3
}
}
},
"binaries": {
"type": "object",
"title": "binaries",
"properties": {
"free": {
"type": "integer",
"title": "Free",
"description": "Free diskspace",
"order": 2
},
"total": {
"type": "integer",
"title": "Total",
"description": "Total diskspace",
"order": 1
},
"used": {
"type": "integer",
"title": "Used",
"description": "Used diskspace",
"order": 3
}
}
},
"diskspace": {
"type": "object",
"title": "diskspace",
"properties": {
"analyses": {
"$ref": "#/definitions/analyses",
"title": "Analyses",
"order": 1
},
"binaries": {
"$ref": "#/definitions/binaries",
"title": "Binaries",
"order": 2
},
"temporary": {
"$ref": "#/definitions/temporary",
"title": "Temporary",
"order": 3
}
},
"definitions": {
"analyses": {
"type": "object",
"title": "analyses",
"properties": {
"free": {
"type": "integer",
"title": "Free",
"description": "Free diskspace",
"order": 2
},
"total": {
"type": "integer",
"title": "Total",
"description": "Total diskspace",
"order": 1
},
"used": {
"type": "integer",
"title": "Used",
"description": "Used diskspace",
"order": 3
}
}
},
"binaries": {
"type": "object",
"title": "binaries",
"properties": {
"free": {
"type": "integer",
"title": "Free",
"description": "Free diskspace",
"order": 2
},
"total": {
"type": "integer",
"title": "Total",
"description": "Total diskspace",
"order": 1
},
"used": {
"type": "integer",
"title": "Used",
"description": "Used diskspace",
"order": 3
}
}
},
"temporary": {
"type": "object",
"title": "temporary",
"properties": {
"free": {
"type": "integer",
"title": "Free",
"description": "Free diskspace",
"order": 2
},
"total": {
"type": "integer",
"title": "Total",
"description": "Total diskspace",
"order": 1
},
"used": {
"type": "integer",
"title": "Used",
"description": "Used diskspace",
"order": 3
}
}
}
}
},
"machines": {
"type": "object",
"title": "machines",
"properties": {
"available": {
"type": "integer",
"title": "Available",
"order": 1
},
"total": {
"type": "integer",
"title": "Total",
"order": 2
}
}
},
"tasks": {
"type": "object",
"title": "tasks",
"properties": {
"completed": {
"type": "integer",
"title": "Completed",
"order": 1
},
"pending": {
"type": "integer",
"title": "Pending",
"order": 2
},
"reported": {
"type": "integer",
"title": "Reported",
"order": 3
},
"running": {
"type": "integer",
"title": "Running",
"order": 4
},
"total": {
"type": "integer",
"title": "Total",
"order": 5
}
}
},
"temporary": {
"type": "object",
"title": "temporary",
"properties": {
"free": {
"type": "integer",
"title": "Free",
"description": "Free diskspace",
"order": 2
},
"total": {
"type": "integer",
"title": "Total",
"description": "Total diskspace",
"order": 1
},
"used": {
"type": "integer",
"title": "Used",
"description": "Used diskspace",
"order": 3
}
}
}
}
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
| 23.127451 | 133 | 0.403278 | 488 | 7,077 | 5.79918 | 0.163934 | 0.097173 | 0.141343 | 0.059364 | 0.498233 | 0.498233 | 0.476325 | 0.476325 | 0.476325 | 0.476325 | 0 | 0.0093 | 0.422637 | 7,077 | 305 | 134 | 23.203279 | 0.683309 | 0.005228 | 0 | 0.576792 | 1 | 0.003413 | 0.924979 | 0.028559 | 0 | 0 | 0 | 0 | 0 | 1 | 0.006826 | false | 0.003413 | 0.006826 | 0 | 0.061433 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
b9b72a7b0eff2f1080736f3c1b9adc48a9e7d140 | 1,612 | py | Python | authApp/models/user.py | lauraC4MP0/reto_carvajal_auth_ms | eb3d04602b16ba7f3e518e0be289e24c52c6ed91 | [
"MIT"
] | null | null | null | authApp/models/user.py | lauraC4MP0/reto_carvajal_auth_ms | eb3d04602b16ba7f3e518e0be289e24c52c6ed91 | [
"MIT"
] | null | null | null | authApp/models/user.py | lauraC4MP0/reto_carvajal_auth_ms | eb3d04602b16ba7f3e518e0be289e24c52c6ed91 | [
"MIT"
] | null | null | null | from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.contrib.auth.hashers import make_password
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a user with the given username and password.
"""
if not username:
raise ValueError('Users must have an username')
user = self.model(username=username)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username=username,password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
id = models.BigIntegerField('Id',primary_key=True)
username = models.CharField('Username', max_length = 15, unique=True)
name = models.CharField('Name', max_length = 30)
lastname=models.CharField('LastName',max_length=30)
email = models.EmailField('Email', max_length = 100)
phoneNumber=models.CharField('PhoneNumber',max_length=20)
password = models.CharField('Password', max_length = 256)
def save(self, **kwargs):
some_salt = 'mMUj0DrIK6vgtdIYepkIxN'
self.password = make_password(self.password, some_salt)
super().save(**kwargs)
objects = UserManager()
USERNAME_FIELD = 'username' | 38.380952 | 90 | 0.676179 | 183 | 1,612 | 5.852459 | 0.382514 | 0.05042 | 0.031746 | 0.039216 | 0.112045 | 0.112045 | 0.054155 | 0 | 0 | 0 | 0 | 0.0128 | 0.224566 | 1,612 | 42 | 91 | 38.380952 | 0.844 | 0.080645 | 0 | 0.125 | 0 | 0 | 0.071727 | 0.01532 | 0 | 0 | 0 | 0 | 0 | 1 | 0.09375 | false | 0.21875 | 0.09375 | 0 | 0.59375 | 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 |
b9b7778bc4a3296be2a52431b9f052859bac98c7 | 1,130 | py | Python | aux_funcs.py | mcmissile007/trader | 06070f0d786d08ffe4b8bbb5a08dcb2808cf16c4 | [
"MIT"
] | null | null | null | aux_funcs.py | mcmissile007/trader | 06070f0d786d08ffe4b8bbb5a08dcb2808cf16c4 | [
"MIT"
] | null | null | null | aux_funcs.py | mcmissile007/trader | 06070f0d786d08ffe4b8bbb5a08dcb2808cf16c4 | [
"MIT"
] | null | null | null | from datetime import datetime
def decideCurrentTimeFrame(last_signals):
current_timeframes = []
now = datetime.now()
minute = int(now.minute)
hour = int(now.hour)
day = int(now.day)
month = int(now.month)
year = int(now.year)
key = str(year) + "/" + str(month) + "/" + str(day)
key += " " + str(hour) + ":" + str(minute)
if key in last_signals:
return []
if minute == 0:
last_signals[key] = True
#check for signals in timesframes 300,900 y 1800
current_timeframes.append(300)
current_timeframes.append(900)
current_timeframes.append(1800)
else:
if minute % 5 == 0:
last_signals[key] = True
#check for signals in timesframes 300
current_timeframes.append(300)
if minute % 15 == 0:
#check for signals in timesframes 900
current_timeframes.append(900)
if minute == 30:
#check for signals in timesframes 1800
current_timeframes.append(1800)
return current_timeframes | 33.235294 | 58 | 0.566372 | 128 | 1,130 | 4.90625 | 0.273438 | 0.216561 | 0.219745 | 0.10828 | 0.248408 | 0.159236 | 0.159236 | 0.159236 | 0.159236 | 0.159236 | 0 | 0.064171 | 0.338053 | 1,130 | 34 | 59 | 33.235294 | 0.775401 | 0.138053 | 0 | 0.296296 | 0 | 0 | 0.004119 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.037037 | false | 0 | 0.037037 | 0 | 0.148148 | 0 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
b9ce571815a9800b79e7a948d91827dfada7dd6b | 1,065 | py | Python | src/cart/entities/shopping_cart.py | galvaof/li-cart | c59519c7e68b6df9bc41ca8a86a367d6e02d51d0 | [
"Unlicense"
] | null | null | null | src/cart/entities/shopping_cart.py | galvaof/li-cart | c59519c7e68b6df9bc41ca8a86a367d6e02d51d0 | [
"Unlicense"
] | null | null | null | src/cart/entities/shopping_cart.py | galvaof/li-cart | c59519c7e68b6df9bc41ca8a86a367d6e02d51d0 | [
"Unlicense"
] | null | null | null | from cart.services.inventory_services import InventoryService
class CartItem:
product_id: int
quantity: int
class ShoppingCart:
id: int
voucher: str
discount_ratio: float
@property
def items(self):
return tuple(self._items)
def __init__(self):
self._items = []
self.inventory = InventoryService()
self.voucher = None
self.discount_ratio = 0
def get_item(self, product_id):
if not self.has_item(product_id):
raise RuntimeError
return next(x for x in self.items if x.product_id ==
product_id)
def has_item(self, product_id):
return product_id in map(lambda x: x.product_id, self.items)
def add(self, item: CartItem):
if self.inventory.remaining(item.product_id) < item.quantity:
raise RuntimeError("Not enough inventory")
self._items.append(item)
def remove(self, item):
self._items.remove(item)
def clear_items(self):
self._items.clear() | 24.204545 | 69 | 0.620657 | 131 | 1,065 | 4.854962 | 0.351145 | 0.127358 | 0.037736 | 0.053459 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00133 | 0.293897 | 1,065 | 44 | 70 | 24.204545 | 0.844415 | 0 | 0 | 0 | 0 | 0 | 0.018762 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.225806 | false | 0 | 0.032258 | 0.064516 | 0.580645 | 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 |
b9d4ce6b860ca646286fd20c37ec4c5c1cd84007 | 4,367 | py | Python | tests/technical_bollinger_test.py | bopo/mooquant | 244a87d4cd8b4d918eec4f16905e0921c3b39f50 | [
"Apache-2.0"
] | 21 | 2017-09-07T16:08:21.000Z | 2020-10-15T13:42:21.000Z | tests/technical_bollinger_test.py | bopo/MooQuant | 244a87d4cd8b4d918eec4f16905e0921c3b39f50 | [
"Apache-2.0"
] | 209 | 2018-10-09T11:57:39.000Z | 2021-03-25T21:40:30.000Z | tests/technical_bollinger_test.py | bopo/MooQuant | 244a87d4cd8b4d918eec4f16905e0921c3b39f50 | [
"Apache-2.0"
] | 15 | 2018-11-17T20:14:37.000Z | 2022-02-04T23:55:29.000Z | # -*- coding: utf-8 -*-
# MooQuant
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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.
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <gabriel.becedillas@gmail.com>
"""
from mooquant import dataseries
from mooquant.technical import bollinger
from . import common
class TestCase(common.TestCase):
def testStockChartsBollinger(self):
# Test data from http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:bollinger_bands
prices = [86.1557, 89.0867, 88.7829, 90.3228, 89.0671, 91.1453, 89.4397, 89.1750, 86.9302, 87.6752, 86.9596, 89.4299, 89.3221, 88.7241, 87.4497, 87.2634, 89.4985, 87.9006, 89.1260, 90.7043, 92.9001, 92.9784, 91.8021, 92.6647, 92.6843, 92.3021, 92.7725, 92.5373, 92.9490, 93.2039, 91.0669, 89.8318, 89.7435, 90.3994, 90.7387, 88.0177, 88.0867, 88.8439, 90.7781, 90.5416, 91.3894, 90.6500]
expectedMiddle = [88.71, 89.05, 89.24, 89.39, 89.51, 89.69, 89.75, 89.91, 90.08, 90.38, 90.66, 90.86, 90.88, 90.91, 90.99, 91.15, 91.19, 91.12, 91.17, 91.25, 91.24, 91.17, 91.05]
expectedUpper = [91.29, 91.95, 92.61, 92.93, 93.31, 93.73, 93.90, 94.27, 94.57, 94.79, 95.04, 94.91, 94.90, 94.90, 94.86, 94.67, 94.56, 94.68, 94.58, 94.53, 94.53, 94.37, 94.15]
expectedLower = [86.12, 86.14, 85.87, 85.85, 85.70, 85.65, 85.59, 85.56, 85.60, 85.98, 86.27, 86.82, 86.87, 86.91, 87.12, 87.63, 87.83, 87.56, 87.76, 87.97, 87.95, 87.96, 87.95]
seqDS = dataseries.SequenceDataSeries()
bBands = bollinger.BollingerBands(seqDS, 20, 2)
for value in prices:
seqDS.append(value)
for i in range(19):
self.assertEqual(bBands.getMiddleBand()[i], None)
self.assertEqual(bBands.getUpperBand()[i], None)
self.assertEqual(bBands.getLowerBand()[i], None)
for i in range(19, len(seqDS)):
self.assertEqual(round(bBands.getMiddleBand()[i], 2), expectedMiddle[i-19])
self.assertEqual(round(bBands.getUpperBand()[i], 2), expectedUpper[i-19])
self.assertEqual(round(bBands.getLowerBand()[i], 2), expectedLower[i-19])
def testStockChartsBollinger_Bounded(self):
# Test data from http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:bollinger_bands
prices = [86.1557, 89.0867, 88.7829, 90.3228, 89.0671, 91.1453, 89.4397, 89.1750, 86.9302, 87.6752, 86.9596, 89.4299, 89.3221, 88.7241, 87.4497, 87.2634, 89.4985, 87.9006, 89.1260, 90.7043, 92.9001, 92.9784, 91.8021, 92.6647, 92.6843, 92.3021, 92.7725, 92.5373, 92.9490, 93.2039, 91.0669, 89.8318, 89.7435, 90.3994, 90.7387, 88.0177, 88.0867, 88.8439, 90.7781, 90.5416, 91.3894, 90.6500]
expectedMiddle = [91.24, 91.17, 91.05]
expectedUpper = [94.53, 94.37, 94.15]
expectedLower = [87.95, 87.96, 87.95]
seqDS = dataseries.SequenceDataSeries()
bBands = bollinger.BollingerBands(seqDS, 20, 2, 3)
for value in prices:
seqDS.append(value)
for i in range(3):
self.assertEqual(round(bBands.getMiddleBand()[i], 2), expectedMiddle[i])
self.assertEqual(round(bBands.getUpperBand()[i], 2), expectedUpper[i])
self.assertEqual(round(bBands.getLowerBand()[i], 2), expectedLower[i])
self.assertEqual(len(bBands.getMiddleBand()), 3)
self.assertEqual(len(bBands.getMiddleBand()[:]), 3)
self.assertEqual(len(bBands.getMiddleBand().getDateTimes()), 3)
self.assertEqual(len(bBands.getUpperBand()), 3)
self.assertEqual(len(bBands.getUpperBand()[:]), 3)
self.assertEqual(len(bBands.getUpperBand().getDateTimes()), 3)
self.assertEqual(len(bBands.getLowerBand()), 3)
self.assertEqual(len(bBands.getLowerBand()[:]), 3)
self.assertEqual(len(bBands.getLowerBand().getDateTimes()), 3)
| 55.278481 | 395 | 0.660179 | 675 | 4,367 | 4.260741 | 0.312593 | 0.09388 | 0.05007 | 0.075104 | 0.639082 | 0.615786 | 0.60605 | 0.57128 | 0.57128 | 0.457232 | 0 | 0.240984 | 0.180902 | 4,367 | 78 | 396 | 55.987179 | 0.563042 | 0.205175 | 0 | 0.186047 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.418605 | 1 | 0.046512 | false | 0 | 0.069767 | 0 | 0.139535 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
b9e2ae2347b453e32686bad3aecb00da54ed51ee | 2,848 | py | Python | pyy1/.pycharm_helpers/python_stubs/-1550516950/_symtable.py | pyy1988/pyy_test1 | 6bea878409e658aa87441384419be51aaab061e7 | [
"Apache-2.0"
] | null | null | null | pyy1/.pycharm_helpers/python_stubs/-1550516950/_symtable.py | pyy1988/pyy_test1 | 6bea878409e658aa87441384419be51aaab061e7 | [
"Apache-2.0"
] | null | null | null | pyy1/.pycharm_helpers/python_stubs/-1550516950/_symtable.py | pyy1988/pyy_test1 | 6bea878409e658aa87441384419be51aaab061e7 | [
"Apache-2.0"
] | null | null | null | # encoding: utf-8
# module _symtable
# from (built-in)
# by generator 1.145
# no doc
# no imports
# Variables with simple values
CELL = 5
DEF_BOUND = 134
DEF_FREE = 32
DEF_FREE_CLASS = 64
DEF_GLOBAL = 1
DEF_IMPORT = 128
DEF_LOCAL = 2
DEF_PARAM = 4
FREE = 4
GLOBAL_EXPLICIT = 2
GLOBAL_IMPLICIT = 3
LOCAL = 1
SCOPE_MASK = 15
SCOPE_OFF = 11
TYPE_CLASS = 1
TYPE_FUNCTION = 0
TYPE_MODULE = 2
USE = 16
# functions
def symtable(*args, **kwargs): # real signature unknown
""" Return symbol and scope dictionaries used internally by compiler. """
pass
# classes
class __loader__(object):
"""
Meta path import for built-in modules.
All methods are either class or static methods to avoid the need to
instantiate the class.
"""
@classmethod
def create_module(cls, *args, **kwargs): # real signature unknown
""" Create a built-in module """
pass
@classmethod
def exec_module(cls, *args, **kwargs): # real signature unknown
""" Exec a built-in module """
pass
@classmethod
def find_module(cls, *args, **kwargs): # real signature unknown
"""
Find the built-in module.
If 'path' is ever specified then the search is considered a failure.
This method is deprecated. Use find_spec() instead.
"""
pass
@classmethod
def find_spec(cls, *args, **kwargs): # real signature unknown
pass
@classmethod
def get_code(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have code objects. """
pass
@classmethod
def get_source(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have source code. """
pass
@classmethod
def is_package(cls, *args, **kwargs): # real signature unknown
""" Return False as built-in modules are never packages. """
pass
@classmethod
def load_module(cls, *args, **kwargs): # real signature unknown
"""
Load the specified module into sys.modules and return it.
This method is deprecated. Use loader.exec_module instead.
"""
pass
def module_repr(module): # reliably restored by inspect
"""
Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
# variables with complex values
__spec__ = None # (!) real value is ''
| 22.967742 | 101 | 0.61868 | 359 | 2,848 | 4.777159 | 0.387187 | 0.058309 | 0.081633 | 0.134111 | 0.321866 | 0.292711 | 0.230321 | 0.0793 | 0.0793 | 0.0793 | 0 | 0.015818 | 0.289677 | 2,848 | 123 | 102 | 23.154472 | 0.831933 | 0.454354 | 0 | 0.365385 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.211538 | false | 0.211538 | 0.019231 | 0 | 0.288462 | 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 |
b9e50c87aa136c29aeed2932fad8b23b00f7b960 | 603 | py | Python | src/utils/epoch_logger.py | alphagov-mirror/govuk-entity-personalisation | a674bca4c15691fe2c4e32ea213dfccf3cb0e8ec | [
"MIT"
] | 1 | 2021-02-15T17:35:59.000Z | 2021-02-15T17:35:59.000Z | src/utils/epoch_logger.py | alphagov-mirror/govuk-entity-personalisation | a674bca4c15691fe2c4e32ea213dfccf3cb0e8ec | [
"MIT"
] | 16 | 2020-11-30T14:41:31.000Z | 2021-09-09T15:33:46.000Z | src/utils/epoch_logger.py | alphagov-mirror/govuk-entity-personalisation | a674bca4c15691fe2c4e32ea213dfccf3cb0e8ec | [
"MIT"
] | 4 | 2020-12-14T17:36:31.000Z | 2021-04-10T20:12:46.000Z | from gensim.models.callbacks import CallbackAny2Vec
from datetime import datetime
class EpochLogger(CallbackAny2Vec):
"""
Callback to log information about training
Reference:
- https://colab.research.google.com/drive/1A4x2yNS3V1nDZFYoQavpoX7AEQ9Rqtve#scrollTo=m1An-k0q9PMr
"""
def __init__(self):
self.epoch = 0
def on_epoch_begin(self, model):
print(f'{datetime.now()}: Model training epoch #{self.epoch} began')
def on_epoch_end(self, model):
print(f'{datetime.now()}: Model training epoch #{self.epoch} ended')
self.epoch += 1
| 30.15 | 105 | 0.689884 | 71 | 603 | 5.746479 | 0.577465 | 0.088235 | 0.04902 | 0.073529 | 0.259804 | 0.259804 | 0.259804 | 0.259804 | 0.259804 | 0.259804 | 0 | 0.028926 | 0.197347 | 603 | 19 | 106 | 31.736842 | 0.81405 | 0.257048 | 0 | 0 | 0 | 0 | 0.273585 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.3 | false | 0 | 0.2 | 0 | 0.6 | 0.2 | 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 |
b9f70879cfaf2dc4de3fb20ae608378a0a8658a0 | 2,394 | py | Python | ucb_cs61A/lab/lab02/lab02_2015/lab02/lab02.py | tavaresdong/courses-notes | 7fb89103bca679f5ef9b14cbc777152daac1402e | [
"MIT"
] | null | null | null | ucb_cs61A/lab/lab02/lab02_2015/lab02/lab02.py | tavaresdong/courses-notes | 7fb89103bca679f5ef9b14cbc777152daac1402e | [
"MIT"
] | 1 | 2017-07-31T08:15:26.000Z | 2017-07-31T08:15:26.000Z | ucb_cs61A/lab/lab02/lab02_2015/lab02/lab02.py | tavaresdong/courses-notes | 7fb89103bca679f5ef9b14cbc777152daac1402e | [
"MIT"
] | 1 | 2019-10-06T16:52:31.000Z | 2019-10-06T16:52:31.000Z | """Lab 2: Higher Order Functions & Lambdas"""
from utils import letter_to_num, num_to_letter, looper, mirror_letter
def make_derivative(f, h=1e-5):
"""Returns a function that approximates the derivative of f.
Recall that f'(a) = (f(a + h) - f(a)) / h as h approaches 0. We will
approximate the derivative by choosing a very small value for h.
>>> square = lambda x: x*x
>>> derivative = make_derivative(square)
>>> result = derivative(3)
>>> round(result, 3) # approximately 2*3
6.0
"""
"*** YOUR CODE HERE ***"
def derivative(point):
return (f(point + h) - f(point)) / h
return derivative
# String Transformers
from operator import add, sub
def caesar_generator(num, op):
"""Returns a one-argument Caesar cipher function. The function should "rotate" a
letter by an integer amount 'num' using an operation 'op' (either add or
sub).
You may use the provided `letter_to_num` and `num_to_letter` functions,
which will map all lowercase letters a-z to 0-25 and all uppercase letters
A-Z to 26-51.
>>> letter_to_num('a')
0
>>> letter_to_num('c')
2
>>> num_to_letter(3)
'd'
>>> caesar2 = caesar_generator(2, add)
>>> caesar2('a')
'c'
>>> brutus3 = caesar_generator(3, sub)
>>> brutus3('d')
'a'
"""
"*** YOUR CODE HERE ***"
return lambda x : num_to_letter(op(letter_to_num(x), num))
# Encryption and Decryption
def make_encrypter(f1, f2, f3):
"""Generates an "encrypter" that applies a specific set of encryption
functions on the message
>>> caesar3 = caesar_generator(3, add)
>>> caesar2 = caesar_generator(2, add)
>>> encrypter = make_encrypter(caesar2, mirror_letter, caesar3)
>>> encrypter('abcd') # caesar2(mirror_letter(caesar3('a'))) -> 'y'
'yxwv'
"""
f1, f2, f3 = looper(f1), looper(f2), looper(f3)
"*** YOUR CODE HERE ***"
return lambda x : f1(f2(f3(x)))
def make_decrypter(f1, f2, f3):
"""Generates a "decrypter" function.
>>> brutus3 = caesar_generator(3, sub)
>>> brutus2 = caesar_generator(2, sub)
>>> decrypter = make_decrypter(brutus2, mirror_letter, brutus3)
>>> decrypter('yxwv') # brutus3(mirror_letter(brutus2('y'))) = 'a'
'abcd'
"""
f1, f2, f3 = looper(f1), looper(f2), looper(f3)
"*** YOUR CODE HERE ***"
return lambda x : f3(f2(f1(x)))
| 28.843373 | 84 | 0.62406 | 336 | 2,394 | 4.339286 | 0.330357 | 0.072016 | 0.037723 | 0.037037 | 0.163923 | 0.092593 | 0.075446 | 0.075446 | 0.075446 | 0.075446 | 0 | 0.035695 | 0.227652 | 2,394 | 82 | 85 | 29.195122 | 0.752839 | 0.625313 | 0 | 0.333333 | 0 | 0 | 0.124294 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.277778 | false | 0 | 0.111111 | 0.055556 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
6a190cd499dbb89c719d97cb729f8f182774c9c8 | 375 | py | Python | rackio/dao/core.py | crivero7/rackio-framework | d3362041b1fc4c3af7eb51ac06b1f0f1b5aa497c | [
"MIT"
] | null | null | null | rackio/dao/core.py | crivero7/rackio-framework | d3362041b1fc4c3af7eb51ac06b1f0f1b5aa497c | [
"MIT"
] | null | null | null | rackio/dao/core.py | crivero7/rackio-framework | d3362041b1fc4c3af7eb51ac06b1f0f1b5aa497c | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""rackio/dao/core.py
This module implements Core Data Object.
"""
from ..engine import CVTEngine
from ..logger import QueryLogger, LoggerEngine
class RackioDAO:
tag_engine = CVTEngine()
logger_engine = LoggerEngine()
query_logger = QueryLogger()
def get_app(self):
from ..core import Rackio
return Rackio() | 17.857143 | 46 | 0.666667 | 43 | 375 | 5.72093 | 0.651163 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003436 | 0.224 | 375 | 21 | 47 | 17.857143 | 0.841924 | 0.221333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0 | 0.333333 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
6a19141ebda644f3bac452ed368ebd79184e18dc | 1,085 | py | Python | from_json.py | IDEA-Research-Group/conformancechecking4spark | c8fb8d76ab86cc76654bba7cbd19d678e86ef8cd | [
"IJG"
] | null | null | null | from_json.py | IDEA-Research-Group/conformancechecking4spark | c8fb8d76ab86cc76654bba7cbd19d678e86ef8cd | [
"IJG"
] | null | null | null | from_json.py | IDEA-Research-Group/conformancechecking4spark | c8fb8d76ab86cc76654bba7cbd19d678e86ef8cd | [
"IJG"
] | null | null | null | from conformancechecking4spark.utils import create_default_spark_session
from conformancechecking4spark import log_rdd
from pyspark.sql import functions as f
import os
import config
from datetime import datetime
from pm4py.objects.log.exporter.xes import exporter as xes_exporter
from pm4py.objects.log.obj import EventStream, EventLog
spark_session = create_default_spark_session()
def timestamp_to_iso_str(ts):
return datetime.fromtimestamp(ts/1000).isoformat()
udf = f.udf(lambda x: timestamp_to_iso_str(x))
df = spark_session.read\
.json(os.path.join(config.ROOT_DIR, "data/logs_leche.json"), multiLine = "true")\
.filter(f.col("stage") == "Fabricacion")\
.filter(f.col("timestamp").isNotNull())\
.withColumn("timestamp", udf(f.col("timestamp")))
logs_formated = log_rdd.format_df(df, case_id="id", task_id="task", event_timestamp="timestamp").collect()
xes_exporter.apply(EventLog(EventStream(logs_formated)), os.path.join(config.ROOT_DIR, "data/logs_leche.xes"))
# x = xes_importer.apply(os.path.join(config.ROOT_DIR, "data/M2.xes"))
# print(type(x)) | 36.166667 | 110 | 0.770507 | 158 | 1,085 | 5.101266 | 0.43038 | 0.059553 | 0.037221 | 0.059553 | 0.122829 | 0.122829 | 0.122829 | 0.08933 | 0.08933 | 0 | 0 | 0.009165 | 0.094931 | 1,085 | 30 | 111 | 36.166667 | 0.811609 | 0.076498 | 0 | 0 | 0 | 0 | 0.101 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.052632 | false | 0 | 0.421053 | 0.052632 | 0.526316 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
6a1a707f8bc186fb2f5a1d9a31e01fab3f9ec3e2 | 748 | py | Python | demisto_sdk/commands/common/content/objects/pack_objects/widget/widget.py | cpforbes/demisto-sdk | 4fe122e6f614e605f96bd47aa089b215dc7c2c5f | [
"MIT"
] | null | null | null | demisto_sdk/commands/common/content/objects/pack_objects/widget/widget.py | cpforbes/demisto-sdk | 4fe122e6f614e605f96bd47aa089b215dc7c2c5f | [
"MIT"
] | null | null | null | demisto_sdk/commands/common/content/objects/pack_objects/widget/widget.py | cpforbes/demisto-sdk | 4fe122e6f614e605f96bd47aa089b215dc7c2c5f | [
"MIT"
] | null | null | null | from typing import Union
import demisto_client
from demisto_sdk.commands.common.constants import WIDGET
from demisto_sdk.commands.common.content.objects.pack_objects.abstract_pack_objects.json_content_object import \
JSONContentObject
from wcmatch.pathlib import Path
class Widget(JSONContentObject):
def __init__(self, path: Union[Path, str]):
super().__init__(path, WIDGET)
def upload(self, client: demisto_client):
"""
Upload the widget to demisto_client
Args:
client: The demisto_client object of the desired XSOAR machine to upload to.
Returns:
The result of the upload command from demisto_client
"""
return client.import_widget(file=self.path)
| 31.166667 | 112 | 0.720588 | 94 | 748 | 5.510638 | 0.425532 | 0.125483 | 0.054054 | 0.084942 | 0.108108 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.213904 | 748 | 23 | 113 | 32.521739 | 0.880952 | 0.252674 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.181818 | false | 0 | 0.545455 | 0 | 0.909091 | 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 |
6a23f1771f1ea86d89316c9cb32670b8ac9d18f1 | 500 | py | Python | primaseru/admin.py | Lukmanhakim112/ppdb | c6179478b4c1f0b6cec77a8a059a6e418f6263f1 | [
"MIT"
] | null | null | null | primaseru/admin.py | Lukmanhakim112/ppdb | c6179478b4c1f0b6cec77a8a059a6e418f6263f1 | [
"MIT"
] | null | null | null | primaseru/admin.py | Lukmanhakim112/ppdb | c6179478b4c1f0b6cec77a8a059a6e418f6263f1 | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import StudentProfile, FatherStudentProfile, MotherStudentProfile, StudentGuardianProfile, MajorStudent, PhotoProfile, StudentFile, RegisterSchedule
admin.site.register(StudentProfile)
admin.site.register(FatherStudentProfile)
admin.site.register(MotherStudentProfile)
admin.site.register(StudentGuardianProfile)
admin.site.register(MajorStudent)
admin.site.register(PhotoProfile)
admin.site.register(StudentFile)
admin.site.register(RegisterSchedule)
| 38.461538 | 161 | 0.868 | 48 | 500 | 9.041667 | 0.333333 | 0.165899 | 0.313364 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.05 | 500 | 12 | 162 | 41.666667 | 0.913684 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.2 | 0 | 0.2 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6a28afe94b3342e27b30213c63563d6b863351c6 | 4,615 | py | Python | api/models.py | AppointmentGuru/CodeGuru | d8871ff68b02cc5e9833a01b090572384be2bdaf | [
"MIT"
] | null | null | null | api/models.py | AppointmentGuru/CodeGuru | d8871ff68b02cc5e9833a01b090572384be2bdaf | [
"MIT"
] | null | null | null | api/models.py | AppointmentGuru/CodeGuru | d8871ff68b02cc5e9833a01b090572384be2bdaf | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.postgres.fields import ArrayField
"""
Chapter -> Section -> Code -> Code -> ...
"""
class Chapter(models.Model):
name = models.CharField(max_length=250, blank=True, null=True)
description = models.TextField(blank=True, null=True)
class Section(models.Model):
parent = models.ForeignKey('Chapter', blank=True, null=True)
name = models.CharField(max_length=250, blank=True, null=True)
description = models.TextField(blank=True, null=True)
class Code(models.Model):
section = models.ForeignKey('Section', blank=True, null=True)
parent = models.ForeignKey('Code', blank=True, null=True)
name = models.CharField(max_length=250, blank=True, null=True, db_index=True)
description = models.TextField(blank=True, null=True, db_index=True)
includes = ArrayField(models.TextField(), blank=True, null=True, help_text='The word \'Includes\' appears immediately under certain categories to further define, or give examples of, the content of the category.')
excludes1 = ArrayField(models.TextField(), blank=True, null=True, help_text='A type 1 Excludes note is a pure excludes. It means \'NOT CODED HERE!\' An Excludes1 note indicates that the code excluded should never be used at the same time as the code above the Excludes1 note. An Excludes1 is used when two conditions cannot occur together, such as a congenital form versus an acquired form of the same condition.')
excludes2 = ArrayField(models.TextField(), blank=True, null=True, help_text='A type 2 excludes note represents \'Not included here\'. An excludes2 note indicates that the condition excluded is not part of the condition it is excluded from but a patient may have both conditions at the same time. When an Excludes2 note appears under a code it is acceptable to use both the code and the excluded code together.')
inclusion_term = ArrayField(models.TextField(), blank=True, null=True, help_text='Certain conditions have both an underlying etiology and multiple body system manifestations due to the underlying etiology. For such conditions the ICD-10-CM has a coding convention that requires the underlying condition be sequenced first followed by the manifestation. Wherever such a combination exists there is a \'use additional code\' note at the etiology code, and a \'code first\' note at the manifestation code. These instructional notes indicate the proper sequencing order of the codes, etiology followed by manifestation. In most cases the manifestation codes will have in the code title, \'in diseases classified elsewhere.\' Codes with this title are a component of the etiology/ manifestation convention. The code title indicates that it is a manifestation code. \'In diseases classified elsewhere\' codes are never permitted to be used as first listed or principal diagnosis codes. They must be used in conjunction with an underlying condition code and they must be listed following the underlying condition.')
use_additional_code = ArrayField(models.TextField(), blank=True, null=True, help_text='A code also note instructs that 2 codes may be required to fully describe a condition but the sequencing of the two codes is discretionary, depending on the severity of the conditions and the reason for the encounter.')
class ProcessCode(models.Model):
name = models.CharField(max_length=7, blank=True, null=True, db_index=True)
practice_type_code = models.CharField(max_length=5, blank=True, null=True, db_index=True)
description = models.TextField(blank=True, null=True, db_index=True)
discovery_rate = models.DecimalField(decimal_places=2, max_digits=10, default=0, db_index=True)
class ICD10Code(models.Model):
'''Deprecated .. use above ^^ '''
def __str__(self):
return '{}: {}'.format(self.code, self.title)
parent = models.ForeignKey('ICD10Code', blank=True, null=True)
title = models.CharField(max_length=250, blank=True, null=True)
code = models.CharField(max_length=20, blank=True, null=True)
see = models.CharField(max_length=250, blank=True, null=True)
level = models.PositiveIntegerField(blank=True, null=True)
raw = models.TextField(default='{}')
@property
def path(self):
code_path = []
code = self
while code.parent:
if code.title is not None:
part = '[{}] {}'.format(code.code, code.title)
code_path.append(part)
code = code.parent
code_path.reverse()
return (" > ").join(code_path)
| 76.916667 | 1,117 | 0.742795 | 662 | 4,615 | 5.117825 | 0.302115 | 0.058442 | 0.084416 | 0.11039 | 0.286895 | 0.250295 | 0.250295 | 0.227273 | 0.227273 | 0.171783 | 0 | 0.01039 | 0.165764 | 4,615 | 59 | 1,118 | 78.220339 | 0.86961 | 0.010834 | 0 | 0.133333 | 0 | 0.155556 | 0.43082 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.044444 | false | 0 | 0.066667 | 0.022222 | 0.8 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
6a316af543b65c5417ab353e57bdde93cbdddc73 | 664 | py | Python | Algorithms/Minimum Path Sum.py | KushRabadia/Leetcode | f6af5bf0b9ef8daf9870570b52012297128aa9e1 | [
"MIT"
] | null | null | null | Algorithms/Minimum Path Sum.py | KushRabadia/Leetcode | f6af5bf0b9ef8daf9870570b52012297128aa9e1 | [
"MIT"
] | null | null | null | Algorithms/Minimum Path Sum.py | KushRabadia/Leetcode | f6af5bf0b9ef8daf9870570b52012297128aa9e1 | [
"MIT"
] | null | null | null | class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if len(grid) <= 0 or grid is None:
return 0
rows = len(grid)
cols = len(grid[0])
for r in range(rows):
for c in range(cols):
if r==0 and c==0:
continue
if r-1<0:
grid[r][c] = grid[r][c] + grid[r][c-1]
elif c-1<0:
grid[r][c] = grid[r][c] + grid[r-1][c]
else:
grid[r][c] = grid[r][c] + min(grid[r-1][c], grid[r][c-1])
return grid[rows-1][cols-1]
| 33.2 | 92 | 0.376506 | 94 | 664 | 2.659574 | 0.297872 | 0.2 | 0.192 | 0.2 | 0.24 | 0.204 | 0.152 | 0.152 | 0.152 | 0.152 | 0 | 0.042614 | 0.46988 | 664 | 19 | 93 | 34.947368 | 0.667614 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.058824 | false | 0 | 0 | 0 | 0.235294 | 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 |
6a31ece1ffcd44964e0cbcf7dfa05deed79fd220 | 685 | py | Python | daily-coding-problem/Amazon/problem_7.py | HouariZegai/problem-solving | 77f2b397cfc798e7a0933daf65b849a81192f9d8 | [
"MIT"
] | 1 | 2022-03-24T02:02:40.000Z | 2022-03-24T02:02:40.000Z | daily-coding-problem/Amazon/problem_7.py | HouariZegai/problem-solving | 77f2b397cfc798e7a0933daf65b849a81192f9d8 | [
"MIT"
] | null | null | null | daily-coding-problem/Amazon/problem_7.py | HouariZegai/problem-solving | 77f2b397cfc798e7a0933daf65b849a81192f9d8 | [
"MIT"
] | 1 | 2022-03-24T02:03:21.000Z | 2022-03-24T02:03:21.000Z | """ Asked by: Amazon [Medium]
Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less.
You must break it up so that words don't break across lines.
Each line has to have the maximum possible amount of words.
If there's no way to break the text up, then return null.
You can assume that there are no spaces at the ends of the string
and that there is exactly one space between each word.
For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10,
you should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"].
No string in the list has a length of more than 10.
""" | 45.666667 | 122 | 0.731387 | 132 | 685 | 3.795455 | 0.568182 | 0.053892 | 0.043912 | 0.047904 | 0.139721 | 0.139721 | 0.139721 | 0.139721 | 0.139721 | 0 | 0 | 0.007366 | 0.207299 | 685 | 15 | 123 | 45.666667 | 0.915285 | 0.986861 | 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 |
6a37c091ccab554ea5fd5aee771040f06549a64c | 375 | py | Python | apps/projects/signals.py | jfterpstra/onepercentclub-site | 43e8e01ac4d3d1ffdd5959ebd048ce95bb2dba0e | [
"BSD-3-Clause"
] | 7 | 2015-01-02T19:31:14.000Z | 2021-03-22T17:30:23.000Z | apps/projects/signals.py | jfterpstra/onepercentclub-site | 43e8e01ac4d3d1ffdd5959ebd048ce95bb2dba0e | [
"BSD-3-Clause"
] | 1 | 2015-03-06T08:34:59.000Z | 2015-03-06T08:34:59.000Z | apps/projects/signals.py | jfterpstra/onepercentclub-site | 43e8e01ac4d3d1ffdd5959ebd048ce95bb2dba0e | [
"BSD-3-Clause"
] | null | null | null | from django.dispatch import Signal
# This signal indicates that the supplied project has been funded.
#
# :param first_time_funded: Whether or not the project has reached the funded state before. For instance, a project
# can become "unfunded" when a donation that was pending fails.
#
project_funded = Signal(providing_args=["first_time_funded"])
| 41.666667 | 115 | 0.738667 | 52 | 375 | 5.211538 | 0.692308 | 0.073801 | 0.110701 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.202667 | 375 | 8 | 116 | 46.875 | 0.906355 | 0.709333 | 0 | 0 | 0 | 0 | 0.165049 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 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 |
6a4a54d27668c7970e5dabc84b44fa1b0c0b94fb | 8,757 | py | Python | tests/test_simplecalc.py | facundobatista/simplecalc | 8c0f72ef90be28d16f407ef439275a229dc5aa2e | [
"Apache-2.0"
] | 2 | 2020-03-21T14:38:49.000Z | 2020-10-12T12:55:17.000Z | tests/test_simplecalc.py | facundobatista/simplecalc | 8c0f72ef90be28d16f407ef439275a229dc5aa2e | [
"Apache-2.0"
] | null | null | null | tests/test_simplecalc.py | facundobatista/simplecalc | 8c0f72ef90be28d16f407ef439275a229dc5aa2e | [
"Apache-2.0"
] | null | null | null | # Copyright 2015-2018 Canonical Ltd.
# Copyright 2020 Facundo Batista
# All Rights Reserved
"""Tests for a simple calculator."""
import math
from decimal import Decimal
from unittest import TestCase
import simplecalc
class BaseTestCase(TestCase):
"""Common code for all test cases."""
def check(self, operations):
for inp, result in operations:
with self.subTest(inp=inp, result=result):
if isinstance(result, type) and issubclass(result, Exception):
self.assertRaises(result, simplecalc.calc, inp)
else:
try:
calculated = simplecalc.calc(inp)
except Exception as err:
self.fail("Calculator exploded with %s when %r" % (
err, inp))
else:
msg = "%r gave %r (should: %r)" % (inp, calculated, result)
if isinstance(result, str):
result = Decimal(result)
self.assertAlmostEqual(calculated, Decimal(result), places=17, msg=msg)
class SimpleIntegersTestCase(BaseTestCase):
"""Check the basic operations."""
def test_sum(self):
self.check([
('2 + 3', '5'),
('0 + 5', '5'),
('+2', '2'),
('2 + +2', '4'),
])
def test_subtract(self):
self.check([
('2 - 1', '1'),
('4-3', '1'),
('3 -7', '-4'),
('-7', '-7'),
('2 - -2', '4'),
])
def test_product(self):
self.check([
('2 * 5', '10'),
('-3 * 2', '-6'),
('3 * -2', '-6'),
('0 * 81256894562934562834652834562345', '0'),
('239846298462483 * 2429784263942', '582774761768877502456687986'),
('-7 * -2', '14'),
])
def test_division(self):
self.check([
('7 / 2', '3.5'),
('8 / 4', '2'),
('2 / 17', Decimal(2) / 17),
('2 / 124124124124', Decimal(2) / 124124124124),
])
def test_exponentiation(self):
self.check([
('2 ** 3', '8'),
('0 ** 2', '0'),
('13513515135153135 ** 0', '1'),
('-3 ** 2', '9'),
('-3 ** 3', '-27'),
('10 ** -1', '0.1'),
('2 ** -2', '0.25'),
('2 ** 1500', Decimal(2) ** 1500),
('2.5 ** 1500', Decimal('2.5') ** 1500),
])
class FloatTestCase(BaseTestCase):
"""Support floats."""
def test_simple_ops(self):
self.check([
('2 + 0.3', '2.3'),
('2.3 - 1.1', '1.2'),
('3.3 ** 0', '1'),
('144 ** 0.5', '12'),
('12 / 4.0', '3'),
])
def test_alternate_formats(self):
self.check([
('2 + .5', '2.5'),
('2 + 0,3', '2.3'),
('2 + ,3', '2.3'),
('1e2', '100'),
('1e+2', '100'),
('1e-2', '0.01'),
('1E2', '100'),
('1E+2', '100'),
('1E-2', '0.01'),
('1e2.3', ValueError),
('2,', '2'),
('2,e3', '2000'),
('2.', '2'),
('2.e3', '2000'),
])
class GroupingTestCase(BaseTestCase):
"""Different combination of parentheses."""
def test_simple(self):
self.check([
('(2 + 3)', '5'),
('3 - (2)', '1'),
('3 - (-2)', '5'),
('(2 + 3) * 3', '15'),
('2 + (3 * 5)', '17'),
])
def test_multiple(self):
self.check([
('((2 + 3) * 2) ** (1 + 0)', '10'),
])
class SpecialOperationsTestCase(BaseTestCase):
"""Some special operations."""
def test_factorial(self):
self.check([
('0!', '1'),
('1!', '1'),
('3!', '6'),
('2.3!', ValueError),
('-5!', ValueError),
('%d!' % (simplecalc.MAX_FACTORIAL_INP + 1,), ArithmeticError),
])
class FunctionsTestCase(BaseTestCase):
"""Allow to call functions."""
def test_frommath_operations(self):
self.check([
('acos(1)', '0'),
('acosh(2)', '1.316957896924816573402949871'),
('asin(0)', '0'),
('asinh(4)', '2.094712547261101232010105377'),
('atan(5)', '1.373400766945015893938375484'),
('atanh(0)', '0'),
('ceil(6.1)', '7'),
('cos(8)', '-0.1455000338086135380777363935'),
('cosh(9)', '4051.54202549259434817940928'),
('degrees(10)', '572.9577951308232286464772187'),
('exp(13)', '442413.3920089205033261027759'),
('factorial(16)', '20922789888000'),
('floor(1.7)', '1'),
('gamma(6)', '120'),
('radians(32)', '0.5585053606381854551798937791'),
('sin(33)', '0.9999118601072671808083214273'),
('sinh(34)', '291730871263727.4375'),
('sqrt(35)', '5.916079783099616042567328292'),
('tan(36)', '7.750470905699147650125269138'),
('tanh(37)', '1'),
('trunc(38)', '38'),
('hypot(4, 3)', '5'),
('hypot(4 3)', '5'),
('pow(2, 3)', '8'),
# without parens also
('acos 1', '0'),
('acosh 2', '1.316957896924816573402949871'),
('asin 0', '0'),
('asinh 4', '2.094712547261101232010105377'),
('atan 5', '1.373400766945015893938375484'),
('atanh 0', '0'),
('ceil 6.1', '7'),
('cos 8', '-0.1455000338086135380777363935'),
('cosh 9', '4051.54202549259434817940928'),
('degrees 10', '572.9577951308232286464772187'),
('exp 13', '442413.3920089205033261027759'),
('factorial 16', '20922789888000'),
('floor 1.7', '1'),
('gamma 6', '120'),
('radians 32', '0.5585053606381854551798937791'),
('sin 33', '0.9999118601072671808083214273'),
('sinh 34', '291730871263727.4375'),
('sqrt 35', '5.916079783099616042567328292'),
('tan 36', '7.750470905699147650125269138'),
('tanh 37', '1'),
('trunc 38', '38'),
('hypot 4, 3', '5'),
('hypot 4 3', '5'),
('pow 2, 3', '8'),
('(pow 2, 3) * 5', '40'),
])
def test_math_altered(self):
toobig = simplecalc.MAX_FACTORIAL_INP + 1
self.check([
('log(10)', '1'),
('ln(2.718281828459045)', '1'),
('log2(64)', '6'),
('log(64, 2)', '6'),
('distance(4, 3)', '5'),
('factorial(%d)' % (toobig,), ArithmeticError),
])
def test_frombuiltin(self):
self.check([
('int(2.3)', '2'),
('int(44, 5)', '24'),
('round(12.1234, 2)', '12.12'),
('abs(-55)', '55'),
])
class ValuesTestCase(BaseTestCase):
"""Allow to use some names."""
def test_basic(self):
self.check([
('e', Decimal(math.e)),
('pi', Decimal(math.pi)),
])
def test_in_operations(self):
self.check([
('sin(pi / 2)', '1'),
('ln(e)', '1'),
])
class ComparisonsTestCase(BaseTestCase):
"""Check comparisons."""
def test_notallowed(self):
self.check([
('2 + (5 < 6)', ValueError),
('1 < 2 < 3', ValueError),
('1 < 2 > 3', ValueError),
('1 < 2 == 3', ValueError),
])
def test_lessthan(self):
self.check([
('2 < 1', False),
('2 < 3', True),
('4 + 2 < 6', False),
('2 + (5 < 6)', ValueError),
])
def test_greaterthan(self):
self.check([
('7 > -8', True),
('7 > 8', False),
('0 > 0', False),
])
def test_lessequalthan(self):
self.check([
('2 <= 3', True),
('2 <= 2', True),
('2 <= 1', False),
])
def test_greaterequalthan(self):
self.check([
('2 >= 1', True),
('2 >= 2', True),
('2 >= 3', False),
])
def test_equality(self):
self.check([
('2 == 2', True),
('2 == 1', False),
('-2 == 2', False),
('2 = 2', True),
('2 === 2', True),
])
def test_different(self):
self.check([
('2 != 1', True),
('2 != 2', False),
('2 != 3', True),
('2 <> 2', False),
])
| 29.287625 | 95 | 0.410871 | 829 | 8,757 | 4.302774 | 0.25573 | 0.014017 | 0.076535 | 0.054948 | 0.404542 | 0.340342 | 0.324082 | 0.320157 | 0.308382 | 0.294645 | 0 | 0.237901 | 0.38415 | 8,757 | 298 | 96 | 29.385906 | 0.423512 | 0.039397 | 0 | 0.197531 | 0 | 0 | 0.249073 | 0.086572 | 0 | 0 | 0 | 0 | 0.00823 | 1 | 0.09465 | false | 0 | 0.016461 | 0 | 0.144033 | 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 |
dbe823d848d5486e3ac6d7d2500214da2ae58893 | 245 | py | Python | src/PlayFair/CheckButton.py | Paarzivall/Praca-Inzynierska | f6e7b0ba6a89ec7406d0553cbd6c9ac0db7651ee | [
"MIT"
] | null | null | null | src/PlayFair/CheckButton.py | Paarzivall/Praca-Inzynierska | f6e7b0ba6a89ec7406d0553cbd6c9ac0db7651ee | [
"MIT"
] | null | null | null | src/PlayFair/CheckButton.py | Paarzivall/Praca-Inzynierska | f6e7b0ba6a89ec7406d0553cbd6c9ac0db7651ee | [
"MIT"
] | null | null | null | import src.MainImages as main_img
class CheckButton(object):
def __init__(self):
self.image = main_img.try_open_button
self.position = (500, 450)
def draw(self, surface):
surface.blit(self.image, self.position) | 24.5 | 47 | 0.677551 | 33 | 245 | 4.787879 | 0.666667 | 0.088608 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031414 | 0.220408 | 245 | 10 | 47 | 24.5 | 0.795812 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.285714 | false | 0 | 0.142857 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
dbf69936a33ed64d8d0960ca2c562a62619d16e2 | 825 | py | Python | tests/roadmap/test_random_sampler.py | omron-sinicx/ctrm | 83e7fe4abb8ad8559bfb6e64170878575a03fd20 | [
"MIT"
] | 8 | 2022-01-25T08:04:32.000Z | 2022-02-20T10:47:40.000Z | tests/roadmap/test_random_sampler.py | omron-sinicx/ctrm | 83e7fe4abb8ad8559bfb6e64170878575a03fd20 | [
"MIT"
] | null | null | null | tests/roadmap/test_random_sampler.py | omron-sinicx/ctrm | 83e7fe4abb8ad8559bfb6e64170878575a03fd20 | [
"MIT"
] | null | null | null | import numpy as np
import pytest
from ctrm.environment import Instance, ObstacleSphere
from ctrm.roadmap import (
get_timed_roadmaps_fully_random,
get_timed_roadmaps_random,
get_timed_roadmaps_random_common,
)
@pytest.fixture
def ins():
return Instance(
2,
[np.array([0, 0]), np.array([1, 0])],
[np.array([1, 1]), np.array([0, 1])],
[0.5, 0.5],
[0.1, 0.1],
[0.1, 0.1],
[ObstacleSphere(pos=np.array([0.5, 0.5]), rad=0.2)],
2,
)
def test_get_timed_roadmaps_random(ins):
kwargs = {"ins": ins, "T": 3, "num": 10}
assert len(get_timed_roadmaps_random(**kwargs)) == ins.num_agents
assert len(get_timed_roadmaps_fully_random(**kwargs)) == ins.num_agents
assert len(get_timed_roadmaps_random_common(**kwargs)) == ins.num_agents
| 26.612903 | 76 | 0.637576 | 123 | 825 | 4.04065 | 0.300813 | 0.112676 | 0.225352 | 0.221328 | 0.452716 | 0.275654 | 0.197183 | 0.197183 | 0.197183 | 0.197183 | 0 | 0.047401 | 0.207273 | 825 | 30 | 77 | 27.5 | 0.712538 | 0 | 0 | 0.16 | 0 | 0 | 0.008485 | 0 | 0 | 0 | 0 | 0 | 0.12 | 1 | 0.08 | false | 0 | 0.16 | 0.04 | 0.28 | 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 |
e00872684bb202491e7ce3058256ccfc7e250169 | 969 | py | Python | barsystem/src/barsystem/migrations/0004_auto_20150430_1648.py | TkkrLab/barsystem | 17d138f19c8f6a61b14477f034d8519bb83e00fb | [
"MIT"
] | 1 | 2016-03-28T16:19:53.000Z | 2016-03-28T16:19:53.000Z | barsystem/src/barsystem/migrations/0004_auto_20150430_1648.py | TkkrLab/barsystem | 17d138f19c8f6a61b14477f034d8519bb83e00fb | [
"MIT"
] | 11 | 2015-09-22T20:34:34.000Z | 2017-04-12T13:55:27.000Z | barsystem/src/barsystem/migrations/0004_auto_20150430_1648.py | TkkrLab/barsystem | 17d138f19c8f6a61b14477f034d8519bb83e00fb | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('barsystem', '0003_product_active'),
]
operations = [
migrations.AlterField(
model_name='product',
name='bar_code',
field=models.CharField(default=None, max_length=100, blank=True),
),
migrations.AlterField(
model_name='product',
name='items',
field=models.IntegerField(default=None, blank=True),
),
migrations.AlterField(
model_name='product',
name='sort',
field=models.IntegerField(default=None, blank=True),
),
migrations.AlterField(
model_name='product',
name='stock_value',
field=models.DecimalField(default=None, decimal_places=4, max_digits=10, blank=True),
),
]
| 27.685714 | 97 | 0.582043 | 91 | 969 | 6.021978 | 0.494505 | 0.145985 | 0.182482 | 0.211679 | 0.465328 | 0.465328 | 0.392336 | 0.392336 | 0.30292 | 0.30292 | 0 | 0.0162 | 0.299278 | 969 | 34 | 98 | 28.5 | 0.790869 | 0.021672 | 0 | 0.5 | 0 | 0 | 0.088795 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.071429 | 0 | 0.178571 | 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 |
e01359ea7ce9ef9ed28c6bdeb820ddda6b87d448 | 8,929 | py | Python | orttraining/orttraining/eager/opgen/opgen/ast.py | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | orttraining/orttraining/eager/opgen/opgen/ast.py | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | orttraining/orttraining/eager/opgen/opgen/ast.py | lchang20/onnxruntime | 97b8f6f394ae02c73ed775f456fd85639c91ced1 | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import io
from typing import TextIO, List, Union
from opgen.lexer import Token
class Node(object):
def __init__(self):
self.tokens = []
def write(self, writer: TextIO):
raise NotImplementedError(self.write)
def __str__(self):
writer = io.StringIO()
self.write(writer)
return writer.getvalue()
#region Syntax List
class SyntaxListMember(Node):
def __init__(self, member: Node, trailing_separator: Token = None):
super().__init__()
self.member = member
self.trailing_separator = trailing_separator
def write(self, writer: TextIO):
self.member.write(writer)
if self.trailing_separator:
writer.write(self.trailing_separator.value)
writer.write(" ")
class SyntaxList(Node):
open_token: Token
members: List[SyntaxListMember]
close_token: Token
def __init__(self):
super().__init__()
self.open_token = None
self.members = []
self.close_token = None
def __iter__(self):
return self.members.__iter__()
def __getitem__(self, key):
return self.members.__getitem__(key)
def __len__(self):
return len(self.members)
def append(self, member: Node, trailing_separator: Token):
self.members.append(SyntaxListMember(member, trailing_separator))
def write(self, writer: TextIO):
if self.open_token:
writer.write(self.open_token.value)
for member in self.members:
member.write(writer)
if self.close_token:
writer.write(self.close_token.value)
#endregion
#region Expressions
class Expression(Node): pass
class LiteralExpression(Expression):
def __init__(self, token: Token):
super().__init__()
self.token = token
def write(self, writer: TextIO):
writer.write(self.token.value)
class ArrayExpression(Expression):
def __init__(self, elements: SyntaxList):
self.elements = elements
#endregion
#region Types
class Type(Node):
def _desugar_self(self) -> "Type":
return self
def desugar(self) -> "Type":
desugared = self
while True:
_desugared = desugared._desugar_self()
if _desugared == desugared:
return desugared
desugared = _desugared
class ExpressionType(Type):
def __init__(self, expression: Expression):
super().__init__()
self.expression = expression
def write(self, writer: TextIO):
self.expression.write(writer)
class ConcreteType(Type):
def __init__(self, identifier_tokens: Union[Token, List[Token]]):
super().__init__()
if isinstance(identifier_tokens, Token):
self.identifier_tokens = [identifier_tokens]
else:
self.identifier_tokens = identifier_tokens
def write(self, writer: TextIO):
for identifier_token in self.identifier_tokens:
writer.write(identifier_token.value)
class ConstType(Type):
def __init__(self, const_token: Token, inner_type: Type):
super().__init__()
self.const_token = const_token
self.inner_type = inner_type
def write(self, writer: TextIO):
writer.write(self.const_token.value)
writer.write(" ")
self.inner_type.write(writer)
def _desugar_self(self) -> Type:
return self.inner_type
class ReferenceType(Type):
def __init__(self, inner_type: Type, reference_token: Token):
super().__init__()
self.inner_type = inner_type
self.reference_token = reference_token
def write(self, writer: TextIO):
self.inner_type.write(writer)
writer.write(self.reference_token.value)
def _desugar_self(self) -> Type:
return self.inner_type
class ModifiedType(Type):
def __init__(self, base_type: Type):
super().__init__()
self.base_type = base_type
def _desugar_self(self) -> Type:
return self.base_type
class OptionalType(ModifiedType):
def __init__(self, base_type: Type, token: Token):
super().__init__(base_type)
self.token = token
def write(self, writer: TextIO):
self.base_type.write(writer)
writer.write(self.token.value)
class ArrayType(ModifiedType):
def __init__(
self,
base_type: Type,
open_token: Token,
length_token: Token,
close_token: Token):
super().__init__(base_type)
self.open_token = open_token
self.length_token = length_token
self.close_token = close_token
def write(self, writer: TextIO):
self.base_type.write(writer)
writer.write(self.open_token.value)
if self.length_token:
writer.write(self.length_token.value)
writer.write(self.close_token.value)
class TemplateType(Type):
def __init__(
self,
identifier_tokens: Union[Token, List[Token]],
type_arguments: SyntaxList):
super().__init__()
if isinstance(identifier_tokens, Token):
self.identifier_tokens = [identifier_tokens]
else:
self.identifier_tokens = identifier_tokens
self.type_arguments = type_arguments
def write(self, writer: TextIO):
for identifier_token in self.identifier_tokens:
writer.write(identifier_token.value)
self.type_arguments.write(writer)
class TupleMemberType(Type):
def __init__(self, element_type: Type, element_name: Token):
super().__init__()
self.element_type = element_type
self.element_name = element_name
def write(self, writer: TextIO):
self.element_type.write(writer)
def _desugar_self(self) -> Type:
return self.element_name
class TupleType(Type):
def __init__(self, elements: SyntaxList):
super().__init__()
self.elements = elements
def write(self, writer: TextIO):
self.elements.write(writer)
class AliasInfo(Node):
before_set: List[str]
after_set: List[str]
contained_types: List[Type]
tokens: List[Token]
def __init__(self):
super().__init__()
self.before_set = []
self.after_set = []
self.contained_types = []
self.tokens = []
self.is_writable = False
def __str__(self):
buffer = io.StringIO()
self.write(buffer)
return buffer.getvalue()
def __eq__(self, obj):
return isinstance(obj, AliasInfo) and str(self) == str(obj)
def __ne__(self, obj):
return not self.__eq__(obj)
def write(self, writer: TextIO):
writer.write("(")
writer.write("|".join(self.before_set))
if self.is_writable:
writer.write("!")
writer.write(" -> ")
writer.write("|".join(self.after_set))
writer.write(")")
class AliasInfoType(Type):
def __init__(self, inner_type: Type, alias_info: AliasInfo):
super().__init__()
self.inner_type = inner_type
self.alias_info = alias_info
self.inner_type.alias_info = alias_info
def write(self, writer: TextIO):
self.inner_type.write(writer)
self.alias_info.write(writer)
def _desugar_self(self) -> Type:
return self.inner_type
class KWArgsSentinelType(Type):
def __init__(self, token: Token):
super().__init__()
self.token = token
def write(self, writer: TextIO):
writer.write(self.token.value)
class TensorType(ConcreteType): pass
class IntType(ConcreteType): pass
class FloatType(ConcreteType): pass
class BoolType(ConcreteType): pass
class StrType(ConcreteType): pass
class ScalarType(ConcreteType): pass
class ScalarTypeType(ConcreteType): pass
class DimnameType(ConcreteType): pass
class GeneratorType(ConcreteType): pass
class TensorOptionsType(ConcreteType): pass
class LayoutType(ConcreteType): pass
class DeviceType(ConcreteType): pass
class MemoryFormatType(ConcreteType): pass
class QSchemeType(ConcreteType): pass
class StorageType(ConcreteType): pass
class ConstQuantizerPtrType(ConcreteType): pass
class StreamType(ConcreteType): pass
#region Decls
class Decl(Node): pass
class ParameterDecl(Decl):
def __init__(
self,
parameter_type: Type,
identifier: Token = None,
equals: Token = None,
default_value: Expression = None):
super().__init__()
self.parameter_type = parameter_type
self.identifier = identifier
self.equals = equals
self.default_value = default_value
def write(self, writer: TextIO):
self.parameter_type.write(writer)
if self.identifier:
writer.write(" ")
writer.write(self.identifier.value)
class FunctionDecl(Decl):
def __init__(
self,
identifier: Token,
parameters: SyntaxList,
return_type: Type = None,
semicolon: Token = None,
arrow: Token = None):
super().__init__()
self.is_leaf = False
self.identifier = identifier
self.return_type = return_type
self.parameters = parameters
self.semicolon = semicolon
self.arrow = arrow
def get_parameter(self, identifier: str) -> ParameterDecl:
for param in self.parameters:
id = param.member.identifier
if id and id.value == identifier:
return param.member
return None
class TranslationUnitDecl(Decl):
def __init__(self, decls: List[FunctionDecl]):
super().__init__()
self.decls = decls
def __iter__(self):
return self.decls.__iter__()
#endregion | 25.731988 | 69 | 0.70971 | 1,094 | 8,929 | 5.477148 | 0.130713 | 0.048064 | 0.038551 | 0.051068 | 0.404373 | 0.355808 | 0.285214 | 0.213785 | 0.194092 | 0.194092 | 0 | 0 | 0.181991 | 8,929 | 347 | 70 | 25.731988 | 0.820372 | 0.019711 | 0 | 0.377778 | 0 | 0 | 0.002287 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.203704 | false | 0.07037 | 0.011111 | 0.044444 | 0.455556 | 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 |
e01d31ae690a7e714bd7b6f8f97399563e0fc2ee | 489 | py | Python | mongoengine/__init__.py | alex/mongoengine | 3c1e7af5bb4e5d2360ea525ab54ee4c85e6d523e | [
"MIT"
] | 1 | 2015-11-08T12:46:12.000Z | 2015-11-08T12:46:12.000Z | mongoengine/__init__.py | alex/mongoengine | 3c1e7af5bb4e5d2360ea525ab54ee4c85e6d523e | [
"MIT"
] | null | null | null | mongoengine/__init__.py | alex/mongoengine | 3c1e7af5bb4e5d2360ea525ab54ee4c85e6d523e | [
"MIT"
] | null | null | null | import document
from document import *
import fields
from fields import *
import connection
from connection import *
import queryset
from queryset import *
__all__ = (document.__all__ + fields.__all__ + connection.__all__ +
queryset.__all__)
__author__ = 'Harry Marr'
VERSION = (0, 3, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
__version__ = get_version()
| 19.56 | 67 | 0.678937 | 60 | 489 | 5.033333 | 0.333333 | 0.119205 | 0.059603 | 0.10596 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.017995 | 0.204499 | 489 | 24 | 68 | 20.375 | 0.758355 | 0 | 0 | 0 | 0 | 0 | 0.040984 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.055556 | false | 0 | 0.444444 | 0 | 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 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
e02206fad8b2780bb2f890a64c63d8df73ea7aae | 11,478 | py | Python | lenstronomy/LensModel/profile_list_base.py | franyancr/lenstronomy | 3a7b33512a474bf1796d23276d9028b580580cf1 | [
"MIT"
] | null | null | null | lenstronomy/LensModel/profile_list_base.py | franyancr/lenstronomy | 3a7b33512a474bf1796d23276d9028b580580cf1 | [
"MIT"
] | null | null | null | lenstronomy/LensModel/profile_list_base.py | franyancr/lenstronomy | 3a7b33512a474bf1796d23276d9028b580580cf1 | [
"MIT"
] | null | null | null | import numpy as np
class ProfileListBase(object):
"""
class that manages the list of lens model class instances. This class is applicable for single plane and multi
plane lensing
"""
def __init__(self, lens_model_list, numerical_alpha_class=None, lens_redshift_list=None, z_source_convention=None):
"""
:param lens_model_list: list of strings with lens model names
:param numerical_alpha_class: an instance of a custom class for use in NumericalAlpha() lens model
deflection angles as a lens model. See the documentation in Profiles.numerical_deflections
"""
self.func_list = self._load_model_instances(lens_model_list, custom_class=numerical_alpha_class,
lens_redshift_list=lens_redshift_list,
z_source_convention=z_source_convention)
self._model_list = lens_model_list
def _load_model_instances(self, lens_model_list, custom_class=None, lens_redshift_list=None,
z_source_convention=None):
if lens_redshift_list is None:
lens_redshift_list = [None] * len(lens_model_list)
func_list = []
imported_classes = {}
for i, lens_type in enumerate(lens_model_list):
# those models require a new instance per profile as certain pre-computations are relevant per individual profile
if lens_type in ['NFW_MC', 'CHAMELEON', 'DOUBLE_CHAMELEON', 'TRIPLE_CHAMELEON', 'NFW_ELLIPSE_GAUSS_DEC',
'CTNFW_GAUSS_DEC', 'INTERPOL', 'INTERPOL_SCALED', 'NIE', 'NIE_SIMPLE']:
lensmodel_class = self._import_class(lens_type, custom_class, z_lens=lens_redshift_list[i],
z_source=z_source_convention)
else:
if lens_type not in imported_classes.keys():
lensmodel_class = self._import_class(lens_type, custom_class)
imported_classes.update({lens_type: lensmodel_class})
else:
lensmodel_class = imported_classes[lens_type]
func_list.append(lensmodel_class)
return func_list
@staticmethod
def _import_class(lens_type, custom_class, z_lens=None, z_source=None):
"""
:param lens_type: string, lens model type
:param custom_class: custom class
:param z_lens:
:param z_source:
:return: class instance of the lens model type
"""
if lens_type == 'SHIFT':
from lenstronomy.LensModel.Profiles.alpha_shift import Shift
return Shift()
elif lens_type == 'SHEAR':
from lenstronomy.LensModel.Profiles.shear import Shear
return Shear()
elif lens_type == 'SHEAR_GAMMA_PSI':
from lenstronomy.LensModel.Profiles.shear import ShearGammaPsi
return ShearGammaPsi()
elif lens_type == 'CONVERGENCE':
from lenstronomy.LensModel.Profiles.convergence import Convergence
return Convergence()
elif lens_type == 'FLEXION':
from lenstronomy.LensModel.Profiles.flexion import Flexion
return Flexion()
elif lens_type == 'FLEXIONFG':
from lenstronomy.LensModel.Profiles.flexionfg import Flexionfg
return Flexionfg()
elif lens_type == 'POINT_MASS':
from lenstronomy.LensModel.Profiles.point_mass import PointMass
return PointMass()
elif lens_type == 'SIS':
from lenstronomy.LensModel.Profiles.sis import SIS
return SIS()
elif lens_type == 'SIS_TRUNCATED':
from lenstronomy.LensModel.Profiles.sis_truncate import SIS_truncate
return SIS_truncate()
elif lens_type == 'SIE':
from lenstronomy.LensModel.Profiles.sie import SIE
return SIE()
elif lens_type == 'SPP':
from lenstronomy.LensModel.Profiles.spp import SPP
return SPP()
elif lens_type == 'NIE':
from lenstronomy.LensModel.Profiles.nie import NIE
return NIE()
elif lens_type == 'NIE_SIMPLE':
from lenstronomy.LensModel.Profiles.nie import NIE_simple
return NIE_simple()
elif lens_type == 'CHAMELEON':
from lenstronomy.LensModel.Profiles.chameleon import Chameleon
return Chameleon()
elif lens_type == 'DOUBLE_CHAMELEON':
from lenstronomy.LensModel.Profiles.chameleon import DoubleChameleon
return DoubleChameleon()
elif lens_type == 'TRIPLE_CHAMELEON':
from lenstronomy.LensModel.Profiles.chameleon import TripleChameleon
return TripleChameleon()
elif lens_type == 'SPEP':
from lenstronomy.LensModel.Profiles.spep import SPEP
return SPEP()
elif lens_type == 'SPEMD':
from lenstronomy.LensModel.Profiles.spemd import SPEMD
return SPEMD()
elif lens_type == 'SPEMD_SMOOTH':
from lenstronomy.LensModel.Profiles.spemd_smooth import SPEMD_SMOOTH
return SPEMD_SMOOTH()
elif lens_type == 'NFW':
from lenstronomy.LensModel.Profiles.nfw import NFW
return NFW()
elif lens_type == 'NFW_ELLIPSE':
from lenstronomy.LensModel.Profiles.nfw_ellipse import NFW_ELLIPSE
return NFW_ELLIPSE()
elif lens_type == 'NFW_ELLIPSE_GAUSS_DEC':
from lenstronomy.LensModel.Profiles.gauss_decomposition import NFWEllipseGaussDec
return NFWEllipseGaussDec()
elif lens_type == 'TNFW':
from lenstronomy.LensModel.Profiles.tnfw import TNFW
return TNFW()
elif lens_type == 'CNFW':
from lenstronomy.LensModel.Profiles.cnfw import CNFW
return CNFW()
elif lens_type == 'CTNFW_GAUSS_DEC':
from lenstronomy.LensModel.Profiles.gauss_decomposition import CTNFWGaussDec
return CTNFWGaussDec()
elif lens_type =='NFW_MC':
from lenstronomy.LensModel.Profiles.nfw_mass_concentration import NFWMC
return NFWMC(z_lens=z_lens, z_source=z_source)
elif lens_type == 'SERSIC':
from lenstronomy.LensModel.Profiles.sersic import Sersic
return Sersic()
elif lens_type == 'SERSIC_ELLIPSE_POTENTIAL':
from lenstronomy.LensModel.Profiles.sersic_ellipse_potential import SersicEllipse
return SersicEllipse()
elif lens_type == 'SERSIC_ELLIPSE_KAPPA':
from lenstronomy.LensModel.Profiles.sersic_ellipse_kappa import SersicEllipseKappa
return SersicEllipseKappa()
elif lens_type == 'SERSIC_ELLIPSE_GAUSS_DEC':
from lenstronomy.LensModel.Profiles.gauss_decomposition \
import SersicEllipseGaussDec
return SersicEllipseGaussDec()
elif lens_type == 'PJAFFE':
from lenstronomy.LensModel.Profiles.p_jaffe import PJaffe
return PJaffe()
elif lens_type == 'PJAFFE_ELLIPSE':
from lenstronomy.LensModel.Profiles.p_jaffe_ellipse import PJaffe_Ellipse
return PJaffe_Ellipse()
elif lens_type == 'HERNQUIST':
from lenstronomy.LensModel.Profiles.hernquist import Hernquist
return Hernquist()
elif lens_type == 'HERNQUIST_ELLIPSE':
from lenstronomy.LensModel.Profiles.hernquist_ellipse import Hernquist_Ellipse
return Hernquist_Ellipse()
elif lens_type == 'GAUSSIAN':
from lenstronomy.LensModel.Profiles.gaussian_potential import Gaussian
return Gaussian()
elif lens_type == 'GAUSSIAN_KAPPA':
from lenstronomy.LensModel.Profiles.gaussian_kappa import GaussianKappa
return GaussianKappa()
elif lens_type == 'GAUSSIAN_ELLIPSE_KAPPA':
from lenstronomy.LensModel.Profiles.gaussian_ellipse_kappa import GaussianEllipseKappa
return GaussianEllipseKappa()
elif lens_type == 'GAUSSIAN_ELLIPSE_POTENTIAL':
from lenstronomy.LensModel.Profiles.gaussian_ellipse_potential import GaussianEllipsePotential
return GaussianEllipsePotential()
elif lens_type == 'MULTI_GAUSSIAN_KAPPA':
from lenstronomy.LensModel.Profiles.multi_gaussian_kappa import MultiGaussianKappa
return MultiGaussianKappa()
elif lens_type == 'MULTI_GAUSSIAN_KAPPA_ELLIPSE':
from lenstronomy.LensModel.Profiles.multi_gaussian_kappa import MultiGaussianKappaEllipse
return MultiGaussianKappaEllipse()
elif lens_type == 'INTERPOL':
from lenstronomy.LensModel.Profiles.interpol import Interpol
return Interpol()
elif lens_type == 'INTERPOL_SCALED':
from lenstronomy.LensModel.Profiles.interpol import InterpolScaled
return InterpolScaled()
elif lens_type == 'SHAPELETS_POLAR':
from lenstronomy.LensModel.Profiles.shapelet_pot_polar import PolarShapelets
return PolarShapelets()
elif lens_type == 'SHAPELETS_CART':
from lenstronomy.LensModel.Profiles.shapelet_pot_cartesian import CartShapelets
return CartShapelets()
elif lens_type == 'DIPOLE':
from lenstronomy.LensModel.Profiles.dipole import Dipole
return Dipole()
elif lens_type == 'CURVED_ARC':
from lenstronomy.LensModel.Profiles.curved_arc import CurvedArc
return CurvedArc()
elif lens_type == 'coreBURKERT':
from lenstronomy.LensModel.Profiles.coreBurkert import CoreBurkert
return CoreBurkert()
elif lens_type == 'NumericalAlpha':
from lenstronomy.LensModel.Profiles.numerical_deflections import NumericalAlpha
return NumericalAlpha(custom_class)
else:
raise ValueError('%s is not a valid lens model' % lens_type)
def _bool_list(self, k=None):
"""
returns a bool list of the length of the lens models
if k = None: returns bool list with True's
if k is int, returns bool list with False's but k'th is True
:param k: None, int, or list of ints
:return: bool list
"""
n = len(self.func_list)
if k is None:
bool_list = [True] * n
elif isinstance(k, (int, np.integer)):
bool_list = [False] * n
bool_list[k] = True
else:
bool_list = [False] * n
for i, k_i in enumerate(k):
if k_i is not False:
if k_i is True:
bool_list[i] = True
elif k_i < n:
bool_list[k_i] = True
else:
raise ValueError("k as set by %s is not convertable in a bool string!" % k)
return bool_list
def set_static(self, kwargs_list):
"""
:param kwargs_list: list of keyword arguments for each profile
:return: kwargs_list
"""
for i, func in enumerate(self.func_list):
func.set_static(**kwargs_list[i])
return kwargs_list
def set_dynamic(self):
"""
:return: None
"""
for i, func in enumerate(self.func_list):
func.set_dynamic()
| 46.469636 | 125 | 0.634692 | 1,223 | 11,478 | 5.735078 | 0.148814 | 0.066153 | 0.164243 | 0.218991 | 0.314656 | 0.225121 | 0.126319 | 0.08982 | 0.068149 | 0.045338 | 0 | 0 | 0.297526 | 11,478 | 246 | 126 | 46.658537 | 0.8699 | 0.08329 | 0 | 0.045 | 0 | 0 | 0.073045 | 0.016124 | 0 | 0 | 0 | 0 | 0 | 1 | 0.03 | false | 0 | 0.28 | 0 | 0.57 | 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 |
e0225cc7ae574faae313b96ffc7ec237e3fa82bb | 1,412 | py | Python | rqalpha/mod/rqalpha_mod_sys_accounts/testing.py | HaidongHe/rqalpha | bb824178425909e051c456f6062a6c5bdc816421 | [
"Apache-2.0"
] | 1 | 2020-11-10T05:44:39.000Z | 2020-11-10T05:44:39.000Z | rqalpha/mod/rqalpha_mod_sys_accounts/testing.py | HaidongHe/rqalpha | bb824178425909e051c456f6062a6c5bdc816421 | [
"Apache-2.0"
] | null | null | null | rqalpha/mod/rqalpha_mod_sys_accounts/testing.py | HaidongHe/rqalpha | bb824178425909e051c456f6062a6c5bdc816421 | [
"Apache-2.0"
] | 1 | 2020-03-05T05:06:45.000Z | 2020-03-05T05:06:45.000Z | # -*- coding: utf-8 -*-
# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)
#
# 除非遵守当前许可,否则不得使用本软件。
#
# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。
# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。
#
# * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件):
# 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。
# 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。
# 详细的授权流程,请联系 public@ricequant.com 获取。
from rqalpha.utils.testing import EnvironmentFixture
class BenchmarkAccountFixture(EnvironmentFixture):
def __init__(self, *args, **kwargs):
super(BenchmarkAccountFixture, self).__init__(*args, **kwargs)
self.benchmark_account_total_cash = 4000
self.benchmark_account = None
def init_fixture(self):
from rqalpha.model.positions import Positions
from rqalpha.mod.rqalpha_mod_sys_accounts.position_model.stock_position import StockPosition
from rqalpha.mod.rqalpha_mod_sys_accounts.account_model import BenchmarkAccount
super(BenchmarkAccountFixture, self).init_fixture()
self.benchmark_account = BenchmarkAccount(self.benchmark_account_total_cash, Positions(StockPosition))
| 42.787879 | 144 | 0.752125 | 154 | 1,412 | 6.720779 | 0.558442 | 0.011594 | 0.030918 | 0.019324 | 0.123672 | 0.067633 | 0.067633 | 0 | 0 | 0 | 0 | 0.0175 | 0.150142 | 1,412 | 32 | 145 | 44.125 | 0.845 | 0.447592 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0 | 0.583333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
e0258af44d55807f60df8224c29a281eeca5b21b | 41,056 | py | Python | tests/test_framework_enrichment.py | varunvarma/panoptes | 733e1b17e01d47fe0a399e2fe635f614cc5a0b88 | [
"Apache-2.0"
] | null | null | null | tests/test_framework_enrichment.py | varunvarma/panoptes | 733e1b17e01d47fe0a399e2fe635f614cc5a0b88 | [
"Apache-2.0"
] | null | null | null | tests/test_framework_enrichment.py | varunvarma/panoptes | 733e1b17e01d47fe0a399e2fe635f614cc5a0b88 | [
"Apache-2.0"
] | null | null | null | """
Copyright 2018, Oath Inc.
Licensed under the terms of the Apache 2.0 license. See LICENSE file in project root for terms.
"""
import time
import unittest
import json
import os
from mock import *
from yahoo_panoptes.framework.enrichment import PanoptesEnrichmentSet, PanoptesEnrichmentGroup, \
PanoptesEnrichmentGroupSet, PanoptesEnrichmentSchemaValidator, PanoptesEnrichmentEncoder, \
PanoptesEnrichmentMultiGroupSet
from yahoo_panoptes.framework.resources import PanoptesResource, PanoptesResourcesKeyValueStore
from yahoo_panoptes.enrichment.enrichment_plugin_agent import _store_enrichment_data, \
PanoptesEnrichmentCacheKeyValueStore, enrichment_plugin_task, PanoptesEnrichmentTaskContext
from tests.test_framework import PanoptesMockRedis
from yahoo_panoptes.framework.context import PanoptesContext
mock_time = Mock()
mock_time.return_value = 1512629517.03121
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
def _get_test_conf_file():
my_dir = os.path.dirname(os.path.realpath(__file__))
panoptes_test_conf_file = os.path.join(my_dir, 'config_files/test_panoptes_config.ini')
return my_dir, panoptes_test_conf_file
class PanoptesEnrichmentInterfaceSchemaValidator(PanoptesEnrichmentSchemaValidator):
schema = {
'enrichment_label': {
'type': 'dict',
'schema': {
'speed': {'type': 'integer'},
'index': {'type': 'integer'},
'status': {'type': 'string'}
}
}
}
def __init__(self):
super(PanoptesEnrichmentInterfaceSchemaValidator, self).__init__()
class PanoptesEnrichmentNeighborSchemaValidator(PanoptesEnrichmentSchemaValidator):
schema = {
'enrichment_label': {
'type': 'dict',
'schema': {
'vlan_id': {'type': 'integer', 'required': True},
'property': {'type': 'string', 'required': True},
'mac': {'type': 'string'}
}
}
}
def __init__(self):
super(PanoptesEnrichmentNeighborSchemaValidator, self).__init__()
class TestEnrichmentFramework(unittest.TestCase):
@patch('yahoo_panoptes.framework.resources.time', mock_time)
def setUp(self):
self.__panoptes_resource = PanoptesResource(resource_site='test', resource_class='test',
resource_subclass='test',
resource_type='test', resource_id='test', resource_endpoint='test',
resource_plugin='test')
self.__panoptes_resource.add_metadata('test', 'test')
def test_enrichment_set(self):
enrichment_set = PanoptesEnrichmentSet('int_001')
enrichment_set.add('speed', 1000)
enrichment_set.add('index', 001)
enrichment_set.add('status', 'up')
self.assertEquals(enrichment_set.key, 'int_001')
self.assertDictEqual(enrichment_set.value, {'status': 'up', 'index': 1, 'speed': 1000})
self.assertEquals(len(enrichment_set), 3)
enrichment_set1 = PanoptesEnrichmentSet('int_002', {'status': 'down', 'index': 2, 'speed': 1000})
self.assertEquals(enrichment_set1.key, 'int_002')
self.assertDictEqual(enrichment_set1.value, {'status': 'down', 'index': 2, 'speed': 1000})
with self.assertRaises(AssertionError):
PanoptesEnrichmentSet('int_001', 'string')
with self.assertRaises(AssertionError):
PanoptesEnrichmentSet('int_001', 100)
def test_enrichment_schema_validator(self):
validator = PanoptesEnrichmentInterfaceSchemaValidator()
enrichment_set = PanoptesEnrichmentSet('int_001')
enrichment_set.add('speed', 1000)
enrichment_set.add('index', 001)
enrichment_set.add('status', 'up')
self.assertTrue(validator.validate(enrichment_set))
enrichment_set.add('status', 01)
self.assertFalse(validator.validate(enrichment_set))
@patch('time.time', mock_time)
def test_enrichment_group(self):
interface_validation_object = PanoptesEnrichmentInterfaceSchemaValidator()
neighbor_validation_object = PanoptesEnrichmentNeighborSchemaValidator()
interface_data = \
'''{"data": [
{"int_001": {"index": 1, "speed": 1000, "status": "up"}},
{"int_002": {"index": 2, "speed": 1000, "status": "down"}}],
"metadata": {"_enrichment_group_creation_timestamp": %f, "_enrichment_ttl": 300, "_execute_frequency": 60},
"namespace": "interface"}''' % mock_time.return_value
neighbor_data = \
'''{"data": [{"host_name": {"mac": "aa:bb:cc:dd:ee:ff", "property": "Test Property", "vlan_id": 501}}],
"metadata": {"_enrichment_group_creation_timestamp": %f, "_enrichment_ttl": 600, "_execute_frequency": 120},
"namespace": "neighbor"}''' % mock_time.return_value
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup(1, interface_validation_object, 300, 60)
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup('interface', 'non_validation_object', 300, 60)
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup('interface', interface_validation_object, '300', 60)
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup('interface', interface_validation_object, 300, '60')
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup('interface', interface_validation_object, 0, 60)
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 0)
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60).\
add_enrichment_set('not_PanoptesEnrichmentSet_obj')
enrichment_set1 = PanoptesEnrichmentSet('int_001')
enrichment_set1.add('speed', 1000)
enrichment_set1.add('index', 001)
enrichment_set1.add('status', 'up')
enrichment_set2 = PanoptesEnrichmentSet('int_002')
enrichment_set2.add('speed', 1000)
enrichment_set2.add('index', 002)
enrichment_set2.add('status', 'down')
enrichment_group1 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
enrichment_group1.add_enrichment_set(enrichment_set1)
enrichment_group1.add_enrichment_set(enrichment_set2)
self.assertEqual(enrichment_group1.namespace, 'interface')
self.assertEqual(enrichment_group1.enrichment_ttl, 300)
self.assertEqual(enrichment_group1.execute_frequency, 60)
self.assertEqual(enrichment_group1.enrichment_group_creation_timestamp, mock_time.return_value)
self.assertEqual(ordered(json.loads(json.dumps(enrichment_group1.data, cls=PanoptesEnrichmentEncoder))),
ordered(json.loads(interface_data)['data']))
self.assertEqual(ordered(json.loads(enrichment_group1.json())), ordered(json.loads(interface_data)))
self.assertEquals(len(enrichment_group1), 2)
enrichment_set3 = PanoptesEnrichmentSet('int_002')
enrichment_set3.add('speed', 1000)
enrichment_set3.add('index', 002)
enrichment_set3.add('status', 'down')
self.assertEqual(ordered(json.loads(enrichment_group1.json())), ordered(json.loads(interface_data)))
self.assertEqual(ordered(enrichment_group1.metadata), ordered(json.loads(interface_data)['metadata']))
self.assertEquals(len(enrichment_group1), 2)
test_metadata = json.loads(interface_data)['metadata']
test_metadata['metadata_key'] = 'metadata_value'
enrichment_group1.upsert_metadata('metadata_key', 'metadata_value')
self.assertEqual(ordered(enrichment_group1.metadata), ordered(test_metadata))
enrichment_group1.upsert_metadata('ttl', 300)
with self.assertRaises(ValueError):
enrichment_group1.upsert_metadata('_enrichment_ttl', 300)
with self.assertRaises(AssertionError):
enrichment_group1.upsert_metadata('metadata', {})
with self.assertRaises(AssertionError):
enrichment_group1.upsert_metadata('metadata', [])
enrichment_set4 = PanoptesEnrichmentSet('host_name')
enrichment_set4.add('vlan_id', 501)
enrichment_set4.add('property', 'Test Property')
enrichment_set4.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group2 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group2.add_enrichment_set(enrichment_set4)
self.assertEqual(ordered(json.loads(enrichment_group2.json())), ordered(json.loads(neighbor_data)))
self.assertEquals(len(enrichment_group2), 1)
enrichment_set5 = PanoptesEnrichmentSet('host_name01')
enrichment_set5.add('vlan_id', 502)
enrichment_set5.add('property', 'Netops01.US')
enrichment_set6 = PanoptesEnrichmentSet('host_name02')
enrichment_set6.add('vlan_id', 503)
enrichment_set6.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group3 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group3.add_enrichment_set(enrichment_set5)
with self.assertRaises(AssertionError):
enrichment_group3.add_enrichment_set(enrichment_set6)
interface_store_data = '{"int_001": {"index": 1, "speed": 1000, "status": "up"}, ' \
'"int_002": {"index": 2, "speed": 1000, "status": "down"}}'
neighbor_store_data = '{"host_name": {"mac": "aa:bb:cc:dd:ee:ff", "property": "Test Property", "vlan_id": 501}}'
self.assertEquals(ordered(json.loads(enrichment_group1.serialize_data())),
ordered(json.loads(interface_store_data)))
self.assertEquals(ordered(json.loads(enrichment_group2.serialize_data())),
ordered(json.loads(neighbor_store_data)))
enrichment_group1.upsert_metadata('ttl', 300)
with self.assertRaises(ValueError):
enrichment_group1.upsert_metadata('_enrichment_ttl', 300)
interface_data_serialized = '''{{"data": {{"int_001": {{"index": 1, "speed": 1000, "status": "up"}},
"int_002": {{"index": 2, "speed": 1000, "status": "down"}}}}, "metadata":
{{"_enrichment_group_creation_timestamp": {:.5f}, "_enrichment_ttl": 300, "_execute_frequency": 60,
"metadata_key": "metadata_value", "ttl": 300}}}}'''.format(mock_time.return_value)
neighbor_data_serialized = '''{{"data": {{"host_name": {{"mac": "aa:bb:cc:dd:ee:ff", "property": "Test Property"
,"vlan_id": 501}}}}, "metadata": {{"_enrichment_group_creation_timestamp": {:.5f},
"_enrichment_ttl": 600, "_execute_frequency": 120}}}}'''.format(mock_time.return_value)
self.assertEquals(ordered(json.loads(enrichment_group1.serialize())),
ordered(json.loads(interface_data_serialized)))
self.assertEquals(ordered(json.loads(enrichment_group2.serialize())),
ordered(json.loads(neighbor_data_serialized)))
@patch('time.time', mock_time)
def test_enrichment_group_set(self):
interface_validation_object = PanoptesEnrichmentInterfaceSchemaValidator()
neighbor_validation_object = PanoptesEnrichmentNeighborSchemaValidator()
panoptes_resource = self.__panoptes_resource
enrichment_data = \
'''{{"enrichment": [{{"metadata": {{"_enrichment_group_creation_timestamp": {:.5f}, "_enrichment_ttl": 600,
"_execute_frequency": 120}}, "data": [{{"host_name":
{{"mac": "aa:bb:cc:dd:ee:ff", "property": "Test Property", "vlan_id": 501}}}}],
"namespace": "neighbor"}}, {{"metadata": {{"_enrichment_group_creation_timestamp": {:.5f},
"_enrichment_ttl": 300,
"_execute_frequency": 60}}, "data": [
{{"int_001": {{"index": 1, "speed": 1000, "status": "up"}}}}, {{"int_002": {{"index": 2, "speed": 1000,
"status": "down"}}}}], "namespace": "interface"}}],
"enrichment_group_set_creation_timestamp": {:.5f}, "resource": {{"resource_class": "test",
"resource_creation_timestamp": {:.5f}, "resource_endpoint": "test", "resource_id": "test",
"resource_metadata": {{"_resource_ttl": "604800", "test": "test"}}, "resource_plugin": "test",
"resource_site": "test",
"resource_subclass": "test", "resource_type": "test"}}}}'''.format(mock_time.return_value,
mock_time.return_value,
mock_time.return_value,
mock_time.return_value)
enrichment_set1 = PanoptesEnrichmentSet('int_001')
enrichment_set1.add('speed', 1000)
enrichment_set1.add('index', 001)
enrichment_set1.add('status', 'up')
enrichment_set2 = PanoptesEnrichmentSet('int_002')
enrichment_set2.add('speed', 1000)
enrichment_set2.add('index', 002)
enrichment_set2.add('status', 'down')
enrichment_group1 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
enrichment_group1.add_enrichment_set(enrichment_set1)
enrichment_group1.add_enrichment_set(enrichment_set2)
enrichment_set3 = PanoptesEnrichmentSet('host_name')
enrichment_set3.add('vlan_id', 501)
enrichment_set3.add('property', 'Test Property')
enrichment_set3.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group2 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group2.add_enrichment_set(enrichment_set3)
enrichment_group_set1 = PanoptesEnrichmentGroupSet(panoptes_resource)
enrichment_group_set1.add_enrichment_group(enrichment_group1)
enrichment_group_set1.add_enrichment_group(enrichment_group2)
self.assertEquals(len(enrichment_group_set1), 2)
group_set_repr = "PanoptesEnrichmentGroupSet[resource:" \
"plugin|test|site|test|class|test|subclass|test|type|test|id|test|endpoint|test," \
"enrichment_group_set_creation_timestamp:{},PanoptesEnrichmentGroup[namespace:" \
"interface,enrichment_ttl:300,execute_frequency:60,enrichment_group_creation_timestamp:{}," \
"PanoptesEnrichmentSet[int_001[status:up,index:1,speed:1000]],PanoptesEnrichmentSet" \
"[int_002[status:down,index:2,speed:1000]]],PanoptesEnrichmentGroup[namespace:neighbor," \
"enrichment_ttl:600,execute_frequency:120,enrichment_group_creation_timestamp:{}," \
"PanoptesEnrichmentSet[host_name[mac:aa:bb:cc:dd:ee:ff,property:" \
"Test Property,vlan_id:501]]]]".format(mock_time.return_value,
mock_time.return_value,
mock_time.return_value)
self.assertEquals(repr(enrichment_group_set1), group_set_repr)
self.assertIsInstance(enrichment_group_set1.resource, PanoptesResource)
self.assertEqual(enrichment_group_set1.enrichment_group_set_creation_timestamp, mock_time.return_value)
self.assertEqual(
ordered(json.loads(json.dumps(enrichment_group_set1.enrichment, cls=PanoptesEnrichmentEncoder))),
ordered(json.loads(enrichment_data)['enrichment']))
self.assertEqual(ordered(json.loads(enrichment_group_set1.json())['enrichment']),
ordered(json.loads(enrichment_data)['enrichment']))
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroupSet('bad_resource')
with self.assertRaises(AssertionError):
PanoptesEnrichmentGroupSet(panoptes_resource).add_enrichment_group('non_PanoptesEnrichmentGroup_obj')
enrichment_group_set2 = PanoptesEnrichmentGroupSet(panoptes_resource)
enrichment_group3 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
with self.assertRaises(AssertionError):
enrichment_group_set2.add_enrichment_group(enrichment_group3)
self.assertFalse(enrichment_group_set1 == enrichment_group1)
self.assertFalse(enrichment_group_set1 == enrichment_group_set2)
@patch('time.time', mock_time)
@patch('yahoo_panoptes.framework.resources.time', mock_time)
def test_multi_enrichment_group_set(self):
interface_validation_object = PanoptesEnrichmentInterfaceSchemaValidator()
neighbor_validation_object = PanoptesEnrichmentNeighborSchemaValidator()
panoptes_resource = self.__panoptes_resource
multi_enrichment_results_data = \
{
"group_sets": [
{
"enrichment": [
{
"data": [
{
"host_name": {
"mac": "aa:bb:cc:dd:ee:ff",
"property": "Test Property",
"vlan_id": 501
}
},
{
"host_name01": {
"mac": "aa:bb:cc:dd:ee:ff",
"property": "Test Property",
"vlan_id": 502
}
}
],
"metadata": {
"_enrichment_group_creation_timestamp": mock_time.return_value,
"_enrichment_ttl": 600,
"_execute_frequency": 120
},
"namespace": "neighbor"
},
{
"data": [
{
"int_001": {
"index": 1,
"speed": 1000,
"status": "up"
}
}
],
"metadata": {
"_enrichment_group_creation_timestamp": mock_time.return_value,
"_enrichment_ttl": 300,
"_execute_frequency": 60
},
"namespace": "interface"
}
],
"enrichment_group_set_creation_timestamp": mock_time.return_value,
"resource": {
"resource_class": "test_class",
"resource_creation_timestamp": mock_time.return_value,
"resource_endpoint": "test_endpoint01",
"resource_id": "test_resource_id01",
"resource_metadata": {
"_resource_ttl": "604800"
},
"resource_plugin": "test_plugin",
"resource_site": "test_site",
"resource_subclass": "test_subclass",
"resource_type": "test_type"
}
},
{
"enrichment": [
{
"data": [
{
"int_001": {
"index": 1,
"speed": 1000,
"status": "up"
}
}
],
"metadata": {
"_enrichment_group_creation_timestamp": mock_time.return_value,
"_enrichment_ttl": 300,
"_execute_frequency": 60
},
"namespace": "interface"
},
{
"data": [
{
"host_name": {
"mac": "aa:bb:cc:dd:ee:ff",
"property": "Test Property",
"vlan_id": 501
}
}
],
"metadata": {
"_enrichment_group_creation_timestamp": mock_time.return_value,
"_enrichment_ttl": 600,
"_execute_frequency": 120
},
"namespace": "neighbor"
}
],
"enrichment_group_set_creation_timestamp": mock_time.return_value,
"resource": {
"resource_class": "test",
"resource_creation_timestamp": mock_time.return_value,
"resource_endpoint": "test",
"resource_id": "test",
"resource_metadata": {
"_resource_ttl": "604800",
"test": "test"
},
"resource_plugin": "test",
"resource_site": "test",
"resource_subclass": "test",
"resource_type": "test"
}
}
]
}
enrichment_set1 = PanoptesEnrichmentSet('int_001')
enrichment_set1.add('speed', 1000)
enrichment_set1.add('index', 001)
enrichment_set1.add('status', 'up')
enrichment_group1 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
enrichment_group1.add_enrichment_set(enrichment_set1)
enrichment_set3 = PanoptesEnrichmentSet('host_name')
enrichment_set3.add('vlan_id', 501)
enrichment_set3.add('property', 'Test Property')
enrichment_set3.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group2 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group2.add_enrichment_set(enrichment_set3)
enrichment_group_set1 = PanoptesEnrichmentGroupSet(panoptes_resource)
enrichment_group_set1.add_enrichment_group(enrichment_group1)
enrichment_group_set1.add_enrichment_group(enrichment_group2)
panoptes_resource01 = PanoptesResource(resource_site='test_site',
resource_class='test_class',
resource_subclass='test_subclass',
resource_type='test_type',
resource_id='test_resource_id01',
resource_endpoint='test_endpoint01',
resource_plugin='test_plugin')
panoptes_resource02 = PanoptesResource(resource_site='test_site',
resource_class='test_class',
resource_subclass='test_subclass',
resource_type='test_type',
resource_id='test_resource_id02',
resource_endpoint='test_endpoint02',
resource_plugin='test_plugin')
enrichment_set4 = PanoptesEnrichmentSet('host_name01')
enrichment_set4.add('vlan_id', 502)
enrichment_set4.add('property', 'Test Property')
enrichment_set4.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group3 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group3.add_enrichment_set(enrichment_set3)
enrichment_group3.add_enrichment_set(enrichment_set4)
enrichment_group_set2 = PanoptesEnrichmentGroupSet(panoptes_resource01)
enrichment_group_set2.add_enrichment_group(enrichment_group1)
enrichment_group_set2.add_enrichment_group(enrichment_group3)
multi_enrichment_group_set = PanoptesEnrichmentMultiGroupSet()
multi_enrichment_group_set.add_enrichment_group_set(enrichment_group_set1)
multi_enrichment_group_set.add_enrichment_group_set(enrichment_group_set2)
multi_enrichment_group_set_repr = "PanoptesEnrichmentMultiGroupSet[PanoptesEnrichmentGroupSet[resource:" \
"plugin|test_plugin|site|test_site|class|test_class|subclass|test_subclass" \
"|type|test_type|id|test_resource_id01|endpoint|test_endpoint01," \
"enrichment_group_set_creation_timestamp:{}," \
"PanoptesEnrichmentGroup[namespace:interface,enrichment_ttl:300," \
"execute_frequency:60,enrichment_group_creation_timestamp:{}," \
"PanoptesEnrichmentSet[int_001[status:up,index:1,speed:1000]]]," \
"PanoptesEnrichmentGroup[namespace:neighbor,enrichment_ttl:600," \
"execute_frequency:120,enrichment_group_creation_timestamp:{}," \
"PanoptesEnrichmentSet[host_name[mac:aa:bb:cc:dd:ee:ff,property:" \
"Test Property,vlan_id:501]],PanoptesEnrichmentSet[host_name01" \
"[mac:aa:bb:cc:dd:ee:ff,property:Test Property,vlan_id:502]]]]," \
"PanoptesEnrichmentGroupSet[resource:plugin|test|site|test|class|test|" \
"subclass|test|type|test|id|test|endpoint|test," \
"enrichment_group_set_creation_timestamp:{}," \
"PanoptesEnrichmentGroup[namespace:interface,enrichment_ttl:300," \
"execute_frequency:60,enrichment_group_creation_timestamp:{}," \
"PanoptesEnrichmentSet[int_001[status:up,index:1,speed:1000]]]," \
"PanoptesEnrichmentGroup[namespace:neighbor,enrichment_ttl:600," \
"execute_frequency:120,enrichment_group_creation_timestamp:{}," \
"PanoptesEnrichmentSet[host_name[mac:aa:bb:cc:dd:ee:ff,property:" \
"Test Property,vlan_id:501]]]]]".format(mock_time.return_value,
mock_time.return_value,
mock_time.return_value,
mock_time.return_value,
mock_time.return_value,
mock_time.return_value)
self.assertEquals(repr(multi_enrichment_group_set), multi_enrichment_group_set_repr)
self.assertEquals(len(multi_enrichment_group_set.enrichment_group_sets), 2)
self.assertEquals(ordered(json.loads(multi_enrichment_group_set.json())),
ordered(multi_enrichment_results_data))
self.assertEquals(len(multi_enrichment_group_set), 2)
multi_enrichment_group_set.add_enrichment_group_set(enrichment_group_set2)
self.assertEquals(len(multi_enrichment_group_set), 2)
enrichment_group_set3 = PanoptesEnrichmentGroupSet(panoptes_resource02)
enrichment_group_set3.add_enrichment_group(enrichment_group1)
multi_enrichment_group_set.add_enrichment_group_set(enrichment_group_set3)
self.assertEquals(len(multi_enrichment_group_set), 3)
with self.assertRaises(AssertionError):
multi_enrichment_group_set.add_enrichment_group_set('non_enrichment_group')
enrichment_group_set3 = PanoptesEnrichmentGroupSet(panoptes_resource01)
with self.assertRaises(AssertionError):
multi_enrichment_group_set.add_enrichment_group_set(enrichment_group_set3)
class TestPanoptesEnrichmentCacheStore(unittest.TestCase):
@patch('redis.StrictRedis', PanoptesMockRedis)
@patch('time.time', mock_time)
def setUp(self):
self.my_dir, self.panoptes_test_conf_file = _get_test_conf_file()
self._panoptes_context = PanoptesContext(self.panoptes_test_conf_file,
key_value_store_class_list=[PanoptesEnrichmentCacheKeyValueStore,
PanoptesResourcesKeyValueStore])
self._enrichment_kv = self._panoptes_context.get_kv_store(PanoptesEnrichmentCacheKeyValueStore)
self._panoptes_resource = PanoptesResource(resource_site='test_site',
resource_class='test_class',
resource_subclass='test_subclass',
resource_type='test_type',
resource_id='test_resource_id',
resource_endpoint='test_endpoint',
resource_plugin='test_plugin')
interface_validation_object = PanoptesEnrichmentInterfaceSchemaValidator()
neighbor_validation_object = PanoptesEnrichmentNeighborSchemaValidator()
enrichment_set1 = PanoptesEnrichmentSet('int_001')
enrichment_set1.add('speed', 1000)
enrichment_set1.add('index', 001)
enrichment_set1.add('status', 'up')
enrichment_set2 = PanoptesEnrichmentSet('int_002')
enrichment_set2.add('speed', 1000)
enrichment_set2.add('index', 002)
enrichment_set2.add('status', 'down')
enrichment_group1 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
enrichment_group1.add_enrichment_set(enrichment_set1)
enrichment_group1.add_enrichment_set(enrichment_set2)
enrichment_set3 = PanoptesEnrichmentSet('host_name')
enrichment_set3.add('vlan_id', 501)
enrichment_set3.add('property', 'Test Property')
enrichment_set3.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group2 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group2.add_enrichment_set(enrichment_set3)
self.enrichment_group_set1 = PanoptesEnrichmentGroupSet(self._panoptes_resource)
self.enrichment_group_set1.add_enrichment_group(enrichment_group1)
self.enrichment_group_set1.add_enrichment_group(enrichment_group2)
self._panoptes_resource01 = PanoptesResource(resource_site='test_site',
resource_class='test_class',
resource_subclass='test_subclass',
resource_type='test_type',
resource_id='test_resource_id01',
resource_endpoint='test_endpoint01',
resource_plugin='test_plugin')
enrichment_set4 = PanoptesEnrichmentSet('host_name01')
enrichment_set4.add('vlan_id', 502)
enrichment_set4.add('property', 'Test Property')
enrichment_set4.add('mac', 'aa:bb:cc:dd:ee:ff')
enrichment_group3 = PanoptesEnrichmentGroup('neighbor', neighbor_validation_object, 600, 120)
enrichment_group3.add_enrichment_set(enrichment_set3)
enrichment_group3.add_enrichment_set(enrichment_set4)
self.enrichment_group_set2 = PanoptesEnrichmentGroupSet(self._panoptes_resource01)
self.enrichment_group_set2.add_enrichment_group(enrichment_group1)
self.enrichment_group_set2.add_enrichment_group(enrichment_group3)
self._multi_enrichment_group_set = PanoptesEnrichmentMultiGroupSet()
self._multi_enrichment_group_set.add_enrichment_group_set(self.enrichment_group_set1)
self._multi_enrichment_group_set.add_enrichment_group_set(self.enrichment_group_set2)
@patch('time.time', mock_time)
def test_panoptes_enrichment_set(self):
enrichment_set1 = PanoptesEnrichmentSet('int_001')
enrichment_set1.add('speed', 1000)
enrichment_set1.add('index', 001)
enrichment_set1.add('status', 'up')
self.assertEquals(enrichment_set1.json(),
'{"int_001": {"index": 1, "speed": 1000, "status": "up"}}')
self.assertEquals(repr(enrichment_set1),
"PanoptesEnrichmentSet[int_001[status:up,index:1,speed:1000]]")
enrichment_set2 = PanoptesEnrichmentSet('int_002')
enrichment_set2.add('speed', 1000)
enrichment_set2.add('index', 002)
enrichment_set2.add('status', 'down')
interface_validation_object = PanoptesEnrichmentInterfaceSchemaValidator()
enrichment_group1 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
self.assertFalse(enrichment_set1 == enrichment_group1)
self.assertFalse(enrichment_set1 == enrichment_set2)
@patch('time.time', mock_time)
def test_panoptes_enrichment_group(self):
interface_validation_object = PanoptesEnrichmentInterfaceSchemaValidator()
enrichment_group1 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
self.assertEquals(enrichment_group1.enrichment_schema, PanoptesEnrichmentInterfaceSchemaValidator.schema)
self.assertEquals(repr(enrichment_group1), "PanoptesEnrichmentGroup[namespace:interface,"
"enrichment_ttl:300,execute_frequency:60,"
"enrichment_group_creation_timestamp:{}]".format(
mock_time.return_value))
enrichment_set1 = PanoptesEnrichmentSet('int_001')
enrichment_set1.add('speed', 1000)
enrichment_set1.add('index', 001)
enrichment_set1.add('status', 'up')
self.assertFalse(enrichment_group1 == enrichment_set1)
enrichment_group2 = PanoptesEnrichmentGroup('interface', interface_validation_object, 300, 60)
enrichment_group3 = PanoptesEnrichmentGroup('other_namespace', interface_validation_object, 300, 60)
self.assertTrue(enrichment_group1 == enrichment_group2)
self.assertFalse(enrichment_group1 == enrichment_group3)
@patch('time.time', mock_time)
def test_store_enrichment_data_enrichment_group_set(self):
interface_result_data = \
{
"data": {
"int_001": {
"index": 1,
"speed": 1000,
"status": "up"
},
"int_002": {
"index": 2,
"speed": 1000,
"status": "down"
}
},
"metadata": {
"_enrichment_group_creation_timestamp": mock_time.return_value,
"_enrichment_ttl": 300,
"_execute_frequency": 60
}
}
neighbor_result_data = \
{
"data": {
"host_name": {
"mac": "aa:bb:cc:dd:ee:ff",
"property": "Test Property",
"vlan_id": 501
}
},
"metadata": {
"_enrichment_group_creation_timestamp": mock_time.return_value,
"_enrichment_ttl": 600,
"_execute_frequency": 120
}
}
_store_enrichment_data(self._panoptes_context, self.enrichment_group_set1, 'PanoptesPluginInfo')
self.assertNotEquals(ordered(interface_result_data),
ordered(json.loads(self._enrichment_kv.get('test_resource_id:neighbor'))))
self.assertEquals(ordered(interface_result_data),
ordered(json.loads(self._enrichment_kv.get('test_resource_id:interface'))))
self.assertEquals(ordered(neighbor_result_data),
ordered(json.loads(self._enrichment_kv.get('test_resource_id:neighbor'))))
def test_store_enrichment_data_enrichment_multi_group_set(self):
enrichment_result_keys = ['test_resource_id01:interface', 'test_resource_id01:neighbor',
'test_resource_id:interface', 'test_resource_id:neighbor']
neighbor_result_data = \
{"data": {"host_name": {"mac": "aa:bb:cc:dd:ee:ff", "property": "Test Property", "vlan_id": 501},
"host_name01": {"mac": "aa:bb:cc:dd:ee:ff", "property": "Test Property", "vlan_id": 502}},
"metadata": {"_enrichment_group_creation_timestamp": mock_time.return_value, "_enrichment_ttl": 600,
"_execute_frequency": 120}}
_store_enrichment_data(self._panoptes_context, self._multi_enrichment_group_set, 'PanoptesPluginInfo')
self.assertEquals(enrichment_result_keys, self._enrichment_kv.find_keys('*'))
self.assertEquals(ordered(neighbor_result_data),
ordered(json.loads(self._enrichment_kv.get('test_resource_id01:neighbor'))))
self.assertNotEquals(ordered(neighbor_result_data),
ordered(json.loads(self._enrichment_kv.get('test_resource_id01:interface'))))
@patch('yahoo_panoptes.enrichment.enrichment_plugin_agent.PanoptesPluginWithEnrichmentRunner', create_auto_spec=True)
@patch('yahoo_panoptes.framework.resources.PanoptesResourceStore.get_resource')
@patch('yahoo_panoptes.enrichment.enrichment_plugin_agent.PanoptesEnrichmentTaskContext')
def test_enrichment_plugin_task_is_executed(self, task_context, resource, enrichment_runner):
task_context.return_value = self._panoptes_context
resource.return_value = self._panoptes_resource
# Test Exception is Thrown on failure to create PanoptesEnrichmentTaskContext
task_context.side_effect = Exception()
with self.assertRaises(SystemExit):
enrichment_plugin_task('name', 'key')
task_context.side_effect = None
# Test Exception is Thrown on failure to create / run plugin
enrichment_runner.side_effect = Exception()
enrichment_plugin_task('name', 'key')
enrichment_runner.execute_plugin.assert_not_called()
enrichment_runner.side_effect = None
# Test Enrichment Is Executed
enrichment_plugin_task('name', 'key')
enrichment_runner.assert_called()
enrichment_runner().execute_plugin.assert_called_once()
| 52.234097 | 121 | 0.579842 | 3,507 | 41,056 | 6.432563 | 0.064728 | 0.074471 | 0.029523 | 0.026952 | 0.779201 | 0.70668 | 0.670686 | 0.630037 | 0.583049 | 0.547985 | 0 | 0.034224 | 0.322462 | 41,056 | 785 | 122 | 52.300637 | 0.776755 | 0.003946 | 0 | 0.493548 | 0 | 0.01129 | 0.183387 | 0.083348 | 0 | 0 | 0 | 0 | 0.122581 | 0 | null | null | 0 | 0.016129 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e02e4d70ac3a010882b6bdce086e8a5e5bfc1c40 | 758 | py | Python | UR Computer Vision/Multi-Label Actor-Action Classification/code/network.py | ChenweWu/Computer-Vision--UR | d0b9f65c292dd04a28c77b87f1f8bbd7005500e3 | [
"MIT"
] | 1 | 2021-02-24T02:20:25.000Z | 2021-02-24T02:20:25.000Z | UR Computer Vision/Multi-Label Actor-Action Classification/code/network.py | ChenweWu/Computer-Vision--UR | d0b9f65c292dd04a28c77b87f1f8bbd7005500e3 | [
"MIT"
] | null | null | null | UR Computer Vision/Multi-Label Actor-Action Classification/code/network.py | ChenweWu/Computer-Vision--UR | d0b9f65c292dd04a28c77b87f1f8bbd7005500e3 | [
"MIT"
] | 1 | 2021-03-02T19:50:22.000Z | 2021-03-02T19:50:22.000Z | import torch
import torch.nn as nn
import torchvision.models as models
import torch.autograd as autograd
from torch.autograd import Variable
import math
class net(nn.Module):
def __init__(self, args):
super(net, self).__init__()
self.resnet = nn.Sequential(*list(models.resnet152(pretrained=True).children())[:-1])
self.linear = nn.Linear( models.resnet152(pretrained=True).fc.in_features, 64)
self.fc1 = nn.Linear(64, args.num_cls)
self.bn = nn.BatchNorm1d(args.num_cls, momentum=0.01)
def forward(self, image):
with torch.no_grad():
img = self.resnet(image)
features = img.reshape(img.size(0), -1)
output = self.bn(self.fc1(self.linear(features)))
return output
| 34.454545 | 93 | 0.670185 | 106 | 758 | 4.679245 | 0.462264 | 0.066532 | 0.100806 | 0.116935 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031457 | 0.203166 | 758 | 21 | 94 | 36.095238 | 0.789735 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.105263 | false | 0 | 0.315789 | 0 | 0.526316 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
e0365b6e874402d5849dee01101a7b56a5ddcc53 | 743 | py | Python | example/test_model2.py | kirichoi/NSSR | d5ff39b4ca4be48f8bfe0a811c25c5e4afde135d | [
"MIT"
] | null | null | null | example/test_model2.py | kirichoi/NSSR | d5ff39b4ca4be48f8bfe0a811c25c5e4afde135d | [
"MIT"
] | null | null | null | example/test_model2.py | kirichoi/NSSR | d5ff39b4ca4be48f8bfe0a811c25c5e4afde135d | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 03:00:22 2017
@author: KIRI
"""
import tellurium as te
import roadrunner
#r1 = te.loada("""
#S1 + S2 -> S3 + S4; k1*S1*S2;
#
#S1 = 1.0; S2 = 2.0; S3 = 0.1; S4 = .5;
#k1 = 0.1
#""")
#
#rr1 = r1.simulate(0, 100, 100)
#r1.plot()
#
#r2 = te.loada("""
#S1 -> S3; k1*S1;
#S1 -> S4; k2*S1;
#S2 -> S3; k3*S2;
#S2 -> S4; k4*S2;
#
#S1 = 1.0; S2 = 2.0; S3 = 0.1; S4 = .5;
#k1 = 0.05; k2 = 0.05; k3 = 0.05; k4 = 0.05;
#""")
#
#rr2 = r2.simulate(0, 100, 100)
#r2.plot()
r3 = te.loada("""
S1 -> S2; k1*S1/(S4 + 1);
S2 -> S1; k2*S2;
S3 -> S4; k3*S2*S3;
S4 -> S3; k4*S4;
S1 = .83; S2 = 2.0; S3 = 0.1; S4 = .5
k1 = 0.05; k2 = 0.05; k3 = 0.05; k4 = 0.05;
""")
rr3 = r3.simulate(0, 100, 100)
print(rr3[-1]) | 16.511111 | 44 | 0.487214 | 155 | 743 | 2.335484 | 0.283871 | 0.066298 | 0.074586 | 0.049724 | 0.243094 | 0.243094 | 0.243094 | 0.243094 | 0.243094 | 0.243094 | 0 | 0.272569 | 0.224764 | 743 | 45 | 45 | 16.511111 | 0.355903 | 0.555855 | 0 | 0 | 0 | 0.166667 | 0.544851 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0.083333 | 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 |
e03b99a0d6ed7482bf975115157496b08652fabc | 547 | py | Python | data_preprocess/make_columns.py | DariaMishina/stock-news | 15fd3292f80656ab96b43dbb61122babde0b0c2c | [
"MIT"
] | 6 | 2021-02-03T04:25:06.000Z | 2022-01-28T15:28:45.000Z | data_preprocess/make_columns.py | DariaMishina/stock-news | 15fd3292f80656ab96b43dbb61122babde0b0c2c | [
"MIT"
] | null | null | null | data_preprocess/make_columns.py | DariaMishina/stock-news | 15fd3292f80656ab96b43dbb61122babde0b0c2c | [
"MIT"
] | 5 | 2021-02-01T08:41:30.000Z | 2021-09-30T22:10:49.000Z | import pandas as pd
def get_shift_percentage(numerator: pd.Series, denominator: pd.Series) -> pd.Series:
"""
На сколько процентов изменилась переменная numerator
относительно текущего denominator
"""
return numerator / denominator * 100
def get_shift_digit(s: pd.Series) -> pd.Series:
"""
Возвращает колонку с изменениями значений
Для вызова этой функции необходимо очистить колонки Close от NaN
"""
assert not s.isna().any(), "Необходимо очистить колонку от NaN"
return (s.shift(-1) - s).shift(1)
| 27.35 | 84 | 0.702011 | 70 | 547 | 5.428571 | 0.6 | 0.105263 | 0.057895 | 0.084211 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011468 | 0.202925 | 547 | 19 | 85 | 28.789474 | 0.860092 | 0.352834 | 0 | 0 | 0 | 0 | 0.107937 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 1 | 0.333333 | false | 0 | 0.166667 | 0 | 0.833333 | 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 |
e0470133f70ed1035f49b3237df6217abdc69e52 | 807 | py | Python | Python_libraries/const.py | dorucioclea/Elrond-NFT-Trading | 82259c367128a2a6410c5deb471ad54622b9fc89 | [
"MIT"
] | 3 | 2022-02-23T09:51:49.000Z | 2022-03-01T07:19:55.000Z | Python_libraries/const.py | dorucioclea/Elrond-NFT-Trading | 82259c367128a2a6410c5deb471ad54622b9fc89 | [
"MIT"
] | null | null | null | Python_libraries/const.py | dorucioclea/Elrond-NFT-Trading | 82259c367128a2a6410c5deb471ad54622b9fc89 | [
"MIT"
] | 1 | 2022-02-23T09:51:52.000Z | 2022-02-23T09:51:52.000Z | DECIMALS = {"GNG-8d7e05" : 1000000000000000000,
"MEX-4183e7" : 1000000000000000000,
"LKMEX-9acade" : 1000000000000000000,
"WATER-104d38" : 1000000000000000000}
TOKEN_TYPE = {"GNG-8d7e05" : "token",
"MEX-4183e7" : "token",
"WARMY-cc922b": "NFT",
"LKMEX-9acade" : "META",
"WATER-104d38" : "token",
"COLORS-14cff1" : "NFT"}
AUTHORIZED_TOKENS = ["GNG-8d7e05",
"MEX-4183e7",
"WARMY-cc922b",
"LKMEX-9acade",
"WATER-104d38",
"COLORS-14cff1"]
TOKEN_TYPE_U8 = {"Fungible" : "00",
"NonFungible" : "01",
"SemiFungible" : "02",
"Meta" : "03"}
| 33.625 | 51 | 0.443618 | 58 | 807 | 6.103448 | 0.482759 | 0.076271 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.298319 | 0.410161 | 807 | 23 | 52 | 35.086957 | 0.445378 | 0 | 0 | 0 | 0 | 0 | 0.309789 | 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 | 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 |
e04cb21549efa116cc9086cdef036c0fd6951e82 | 12,761 | py | Python | sdk/python/feast/specs/ImportSpec_pb2.py | davidheryanto/feast | 72cc8bd2cd0040f7bc44df255f95bad00cacd720 | [
"Apache-2.0"
] | null | null | null | sdk/python/feast/specs/ImportSpec_pb2.py | davidheryanto/feast | 72cc8bd2cd0040f7bc44df255f95bad00cacd720 | [
"Apache-2.0"
] | null | null | null | sdk/python/feast/specs/ImportSpec_pb2.py | davidheryanto/feast | 72cc8bd2cd0040f7bc44df255f95bad00cacd720 | [
"Apache-2.0"
] | 2 | 2020-05-20T22:07:11.000Z | 2021-07-25T17:28:24.000Z | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: feast/specs/ImportSpec.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='feast/specs/ImportSpec.proto',
package='feast.specs',
syntax='proto3',
serialized_options=_b('\n\013feast.specsB\017ImportSpecProtoZ6github.com/gojek/feast/protos/generated/go/feast/specs'),
serialized_pb=_b('\n\x1c\x66\x65\x61st/specs/ImportSpec.proto\x12\x0b\x66\x65\x61st.specs\x1a\x1fgoogle/protobuf/timestamp.proto\"\xba\x02\n\nImportSpec\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x41\n\rsourceOptions\x18\x02 \x03(\x0b\x32*.feast.specs.ImportSpec.SourceOptionsEntry\x12;\n\njobOptions\x18\x05 \x03(\x0b\x32\'.feast.specs.ImportSpec.JobOptionsEntry\x12\x10\n\x08\x65ntities\x18\x03 \x03(\t\x12#\n\x06schema\x18\x04 \x01(\x0b\x32\x13.feast.specs.Schema\x1a\x34\n\x12SourceOptionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x31\n\x0fJobOptionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xa2\x01\n\x06Schema\x12\"\n\x06\x66ields\x18\x01 \x03(\x0b\x32\x12.feast.specs.Field\x12\x19\n\x0ftimestampColumn\x18\x05 \x01(\tH\x00\x12\x34\n\x0etimestampValue\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.TimestampH\x00\x12\x16\n\x0e\x65ntityIdColumn\x18\x07 \x01(\tB\x0b\n\ttimestamp\"(\n\x05\x46ield\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tfeatureId\x18\x02 \x01(\tBV\n\x0b\x66\x65\x61st.specsB\x0fImportSpecProtoZ6github.com/gojek/feast/protos/generated/go/feast/specsb\x06proto3')
,
dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,])
_IMPORTSPEC_SOURCEOPTIONSENTRY = _descriptor.Descriptor(
name='SourceOptionsEntry',
full_name='feast.specs.ImportSpec.SourceOptionsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='feast.specs.ImportSpec.SourceOptionsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='feast.specs.ImportSpec.SourceOptionsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=290,
serialized_end=342,
)
_IMPORTSPEC_JOBOPTIONSENTRY = _descriptor.Descriptor(
name='JobOptionsEntry',
full_name='feast.specs.ImportSpec.JobOptionsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='feast.specs.ImportSpec.JobOptionsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='feast.specs.ImportSpec.JobOptionsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=344,
serialized_end=393,
)
_IMPORTSPEC = _descriptor.Descriptor(
name='ImportSpec',
full_name='feast.specs.ImportSpec',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='feast.specs.ImportSpec.type', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sourceOptions', full_name='feast.specs.ImportSpec.sourceOptions', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='jobOptions', full_name='feast.specs.ImportSpec.jobOptions', index=2,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='entities', full_name='feast.specs.ImportSpec.entities', index=3,
number=3, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='schema', full_name='feast.specs.ImportSpec.schema', index=4,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_IMPORTSPEC_SOURCEOPTIONSENTRY, _IMPORTSPEC_JOBOPTIONSENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=79,
serialized_end=393,
)
_SCHEMA = _descriptor.Descriptor(
name='Schema',
full_name='feast.specs.Schema',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='fields', full_name='feast.specs.Schema.fields', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='timestampColumn', full_name='feast.specs.Schema.timestampColumn', index=1,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='timestampValue', full_name='feast.specs.Schema.timestampValue', index=2,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='entityIdColumn', full_name='feast.specs.Schema.entityIdColumn', index=3,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='timestamp', full_name='feast.specs.Schema.timestamp',
index=0, containing_type=None, fields=[]),
],
serialized_start=396,
serialized_end=558,
)
_FIELD = _descriptor.Descriptor(
name='Field',
full_name='feast.specs.Field',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='feast.specs.Field.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='featureId', full_name='feast.specs.Field.featureId', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=560,
serialized_end=600,
)
_IMPORTSPEC_SOURCEOPTIONSENTRY.containing_type = _IMPORTSPEC
_IMPORTSPEC_JOBOPTIONSENTRY.containing_type = _IMPORTSPEC
_IMPORTSPEC.fields_by_name['sourceOptions'].message_type = _IMPORTSPEC_SOURCEOPTIONSENTRY
_IMPORTSPEC.fields_by_name['jobOptions'].message_type = _IMPORTSPEC_JOBOPTIONSENTRY
_IMPORTSPEC.fields_by_name['schema'].message_type = _SCHEMA
_SCHEMA.fields_by_name['fields'].message_type = _FIELD
_SCHEMA.fields_by_name['timestampValue'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_SCHEMA.oneofs_by_name['timestamp'].fields.append(
_SCHEMA.fields_by_name['timestampColumn'])
_SCHEMA.fields_by_name['timestampColumn'].containing_oneof = _SCHEMA.oneofs_by_name['timestamp']
_SCHEMA.oneofs_by_name['timestamp'].fields.append(
_SCHEMA.fields_by_name['timestampValue'])
_SCHEMA.fields_by_name['timestampValue'].containing_oneof = _SCHEMA.oneofs_by_name['timestamp']
DESCRIPTOR.message_types_by_name['ImportSpec'] = _IMPORTSPEC
DESCRIPTOR.message_types_by_name['Schema'] = _SCHEMA
DESCRIPTOR.message_types_by_name['Field'] = _FIELD
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ImportSpec = _reflection.GeneratedProtocolMessageType('ImportSpec', (_message.Message,), dict(
SourceOptionsEntry = _reflection.GeneratedProtocolMessageType('SourceOptionsEntry', (_message.Message,), dict(
DESCRIPTOR = _IMPORTSPEC_SOURCEOPTIONSENTRY,
__module__ = 'feast.specs.ImportSpec_pb2'
# @@protoc_insertion_point(class_scope:feast.specs.ImportSpec.SourceOptionsEntry)
))
,
JobOptionsEntry = _reflection.GeneratedProtocolMessageType('JobOptionsEntry', (_message.Message,), dict(
DESCRIPTOR = _IMPORTSPEC_JOBOPTIONSENTRY,
__module__ = 'feast.specs.ImportSpec_pb2'
# @@protoc_insertion_point(class_scope:feast.specs.ImportSpec.JobOptionsEntry)
))
,
DESCRIPTOR = _IMPORTSPEC,
__module__ = 'feast.specs.ImportSpec_pb2'
# @@protoc_insertion_point(class_scope:feast.specs.ImportSpec)
))
_sym_db.RegisterMessage(ImportSpec)
_sym_db.RegisterMessage(ImportSpec.SourceOptionsEntry)
_sym_db.RegisterMessage(ImportSpec.JobOptionsEntry)
Schema = _reflection.GeneratedProtocolMessageType('Schema', (_message.Message,), dict(
DESCRIPTOR = _SCHEMA,
__module__ = 'feast.specs.ImportSpec_pb2'
# @@protoc_insertion_point(class_scope:feast.specs.Schema)
))
_sym_db.RegisterMessage(Schema)
Field = _reflection.GeneratedProtocolMessageType('Field', (_message.Message,), dict(
DESCRIPTOR = _FIELD,
__module__ = 'feast.specs.ImportSpec_pb2'
# @@protoc_insertion_point(class_scope:feast.specs.Field)
))
_sym_db.RegisterMessage(Field)
DESCRIPTOR._options = None
_IMPORTSPEC_SOURCEOPTIONSENTRY._options = None
_IMPORTSPEC_JOBOPTIONSENTRY._options = None
# @@protoc_insertion_point(module_scope)
| 40.382911 | 1,174 | 0.749471 | 1,594 | 12,761 | 5.720828 | 0.120452 | 0.044742 | 0.052637 | 0.041452 | 0.654129 | 0.572651 | 0.538656 | 0.513543 | 0.513543 | 0.513543 | 0 | 0.036302 | 0.11927 | 12,761 | 315 | 1,175 | 40.511111 | 0.775069 | 0.040671 | 0 | 0.626335 | 1 | 0.010676 | 0.14357 | 0.097784 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.163701 | 0 | 0.163701 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e0508b48620632e8ca7a48fd7699a12b16c9dfa4 | 1,373 | py | Python | app/Model/Peaks/Peak.py | MrPSnrub/NMRVisualisation | 1831689ed0cd22be8f42d9a4d17d0b4db47241e8 | [
"MIT"
] | null | null | null | app/Model/Peaks/Peak.py | MrPSnrub/NMRVisualisation | 1831689ed0cd22be8f42d9a4d17d0b4db47241e8 | [
"MIT"
] | null | null | null | app/Model/Peaks/Peak.py | MrPSnrub/NMRVisualisation | 1831689ed0cd22be8f42d9a4d17d0b4db47241e8 | [
"MIT"
] | null | null | null | class Peak:
"""A peak found in spectra.
Attributes:
id: Rounded X-coordinate used to collate peak data
x: X-coordinates of peak along its traversal through spectra
y: Y-coordinates of peak along its traversal through spectra
z: Z-coordinates of peak along its traversal through spectra
"""
def __init__(self, peak_id, x, y, z):
self.peak_id = peak_id
self.x = x
self.y = y
self.z = z
self.length = len(x) + len(y) + len(z)
def add_coordinates(self, x, y, z):
"""Adds x, y, z co-ordinates to their respective lists."""
self.x.extend(x)
self.y.extend(y)
self.z.extend(z)
def remove_coordinates(self, amount):
"""Removes number of co-ordinates to solve missing data problem (https://en.wikipedia.org/wiki/Missing_data)
(Length of peak data will differ across all peaks, so remove redundant
data to ensure peak data matches average length of all detected peak data."""
for i in range(amount):
self.x.pop()
self.y.pop()
self.z.pop()
def peak_length(self):
self.length = len(self.z)
return self.length
def x_coordinates(self):
return self.x
def y_coordinates(self):
return self.y
def z_coordinates(self):
return self.z
| 30.511111 | 116 | 0.607429 | 200 | 1,373 | 4.1 | 0.32 | 0.030488 | 0.062195 | 0.080488 | 0.17561 | 0.17561 | 0.17561 | 0.17561 | 0 | 0 | 0 | 0 | 0.298616 | 1,373 | 44 | 117 | 31.204545 | 0.851506 | 0.431173 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.28 | false | 0 | 0 | 0.12 | 0.48 | 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 |
e06481e842e46fa5ae5ce92a1fcdb40eb1b3e92a | 326 | py | Python | aiida/orm/nodes/data/remote/stash/__init__.py | azadoks/aiida-core | b806b7fef8fc79090deccfe2019b77cb922e0581 | [
"MIT",
"BSD-3-Clause"
] | 180 | 2019-07-12T07:45:26.000Z | 2022-03-22T13:16:57.000Z | aiida/orm/nodes/data/remote/stash/__init__.py | azadoks/aiida-core | b806b7fef8fc79090deccfe2019b77cb922e0581 | [
"MIT",
"BSD-3-Clause"
] | 2,466 | 2016-12-24T01:03:52.000Z | 2019-07-04T13:41:08.000Z | aiida/orm/nodes/data/remote/stash/__init__.py | azadoks/aiida-core | b806b7fef8fc79090deccfe2019b77cb922e0581 | [
"MIT",
"BSD-3-Clause"
] | 88 | 2019-07-06T01:42:39.000Z | 2022-03-18T14:20:09.000Z | # -*- coding: utf-8 -*-
"""Module with data plugins that represent files of completed calculations jobs that have been stashed."""
# AUTO-GENERATED
# yapf: disable
# pylint: disable=wildcard-import
from .base import *
from .folder import *
__all__ = (
'RemoteStashData',
'RemoteStashFolderData',
)
# yapf: enable
| 18.111111 | 106 | 0.702454 | 37 | 326 | 6.081081 | 0.837838 | 0.088889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003731 | 0.177914 | 326 | 17 | 107 | 19.176471 | 0.835821 | 0.604294 | 0 | 0 | 1 | 0 | 0.302521 | 0.176471 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
e06d2fd158511a6c7851923a7b2f037169754fcb | 947 | py | Python | PYTFUN/170_Test_Driven_Development/bank_account.py | Pazzobg/PRG_PYTFUN | b661a3dd99279b3b7e3971ed1f1a194b26959f74 | [
"MIT"
] | null | null | null | PYTFUN/170_Test_Driven_Development/bank_account.py | Pazzobg/PRG_PYTFUN | b661a3dd99279b3b7e3971ed1f1a194b26959f74 | [
"MIT"
] | null | null | null | PYTFUN/170_Test_Driven_Development/bank_account.py | Pazzobg/PRG_PYTFUN | b661a3dd99279b3b7e3971ed1f1a194b26959f74 | [
"MIT"
] | null | null | null | from datetime import datetime as dt
class Account():
def __init__(self, account_nr, client_name, opening_date, interest_rate, opening_amount):
self.account_nr = account_nr
self.client_name = client_name
self.opening_date = dt.strptime(opening_date, "%Y-%m-%d")
self.interest_rate = interest_rate
self.balance = opening_amount
def deposit(self, amount):
if not self.check_enough_balance(amount):
raise ValueError("Wrong amount!")
pass
def withdraw(self, amount):
if not self.check_enough_balance(amount):
raise ValueError("Wrong amount!")
pass
def transfer_amount(self, amount, transfer_direction, transfer_account_nr):
if not self.check_enough_balance(amount):
raise ValueError("Wrong amount!")
pass
def check_enough_balance(self, minus_amount):
return self.balance - minus_amount >= 0
| 29.59375 | 93 | 0.668427 | 117 | 947 | 5.136752 | 0.324786 | 0.0599 | 0.1198 | 0.069884 | 0.362729 | 0.362729 | 0.362729 | 0.362729 | 0.362729 | 0.362729 | 0 | 0.001401 | 0.24604 | 947 | 31 | 94 | 30.548387 | 0.840336 | 0 | 0 | 0.409091 | 0 | 0 | 0.04963 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.227273 | false | 0.136364 | 0.045455 | 0.045455 | 0.363636 | 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 |
e06d3507b4fe8967f6e4ef688a697c57ce276b97 | 380 | py | Python | Chapter09/hikingapp/application/hiking/server.py | maggias/Python-Web-Development-with-Sanic | a0337b9324b4d898f79c5621705b7d0171eeb21d | [
"MIT"
] | 16 | 2022-01-03T22:17:20.000Z | 2022-03-26T09:41:35.000Z | Chapter09/hikingapp/application/hiking/server.py | maggias/Python-Web-Development-with-Sanic | a0337b9324b4d898f79c5621705b7d0171eeb21d | [
"MIT"
] | 3 | 2022-01-18T11:21:56.000Z | 2022-03-13T08:51:14.000Z | Chapter09/hikingapp/application/hiking/server.py | maggias/Python-Web-Development-with-Sanic | a0337b9324b4d898f79c5621705b7d0171eeb21d | [
"MIT"
] | 4 | 2022-01-11T21:16:07.000Z | 2022-03-30T06:24:30.000Z | from sanic import Sanic
from hiking.common.log import setup_logging
def create_app():
app = Sanic("HikingApp")
setup_logging(app)
from hiking.blueprints.view import bp # noqa
from hiking.middleware import request_context # noqa
from hiking.worker import postgres # noqa
from hiking.worker import redis # noqa
app.blueprint(bp)
return app
| 21.111111 | 57 | 0.718421 | 51 | 380 | 5.27451 | 0.470588 | 0.185874 | 0.156134 | 0.148699 | 0.193309 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.218421 | 380 | 17 | 58 | 22.352941 | 0.905724 | 0.05 | 0 | 0 | 0 | 0 | 0.025281 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0 | 0.545455 | 0 | 0.727273 | 0.181818 | 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 |
e071df6180dbb912b02250e2cc25fc29c18881bc | 16,659 | py | Python | packages/gsl/Vector.py | gmgunter/pyre | e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2 | [
"BSD-3-Clause"
] | 25 | 2018-04-23T01:45:39.000Z | 2021-12-10T06:01:23.000Z | packages/gsl/Vector.py | gmgunter/pyre | e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2 | [
"BSD-3-Clause"
] | 53 | 2018-05-31T04:55:00.000Z | 2021-10-07T21:41:32.000Z | packages/gsl/Vector.py | gmgunter/pyre | e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2 | [
"BSD-3-Clause"
] | 12 | 2018-04-23T22:50:40.000Z | 2022-02-20T17:27:23.000Z | # -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2021 all rights reserved
#
# externals
import numbers
from . import gsl # the extension
# the class declaration
class Vector:
"""
A wrapper over a gsl vector
"""
# types
from .Permutation import Permutation as permutation
# constants
defaultFormat = "+16.7"
# class methods
# mpi support
@classmethod
def bcast(cls, vector=None, communicator=None, source=0):
"""
Broadcast the given {vector} from {source} to all tasks in {communicator}
"""
# normalize the communicator
if communicator is None:
# get the mpi package
import mpi
# use the world by default
communicator = mpi.world
# get the vector capsule
data = None if vector is None else vector.data
# scatter the data
capsule, shape = gsl.bcastVector(communicator.capsule, source, data)
# dress up my local portion as a vector
result = cls(shape=shape, data=capsule)
# and return it
return result
@classmethod
def collect(cls, vector, communicator=None, destination=0):
"""
Gather the data in {vector} from each task in {communicator} into one big vector
available at the {destination} task
"""
# normalize the communicator
if communicator is None:
# get the mpi package
import mpi
# use the world by default
communicator = mpi.world
# gather the data
result = gsl.gatherVector(communicator.capsule, destination, vector.data)
# if i am not the destination task, nothing further to do
if communicator.rank != destination: return
# otherwise, unpack the result
data, shape = result
# dress up the result as a vector
result = cls(shape=shape, data=data)
# and return it
return result
def excerpt(self, communicator=None, source=0, vector=None):
"""
Scatter {vector} held by the task {source} among all tasks in {communicator} and fill me
with the partition values. Only {source} has to provide a {vector}; the other tasks can
use the default value.
"""
# normalize the communicator
if communicator is None:
# get the mpi package
import mpi
# use the world by default
communicator = mpi.world
# get the vector capsule
data = None if vector is None else vector.data
# scatter the data
gsl.scatterVector(communicator.capsule, source, self.data, data)
# and return me
return self
# public data
@property
def elements(self):
"""
Iterate over all my elements
"""
# i'm already accessible as an iterator
yield from self
# all done
return
# initialization
def zero(self):
"""
Set all my elements to zero
"""
# zero me out
gsl.vector_zero(self.data)
# and return
return self
def fill(self, value):
"""
Set all my elements to {value}
"""
# grab my capsule
data = self.data
# first, attempt to
try:
# convert {value} into a float
value = float(value)
# if this fails
except TypeError:
# go through the input values
for idx, elem in zip(range(self.shape), value):
# set the value
gsl.vector_set(data, idx, float(elem))
# if the conversion to float were successful
else:
# fill me with {value}
gsl.vector_fill(data, value)
# all done
return self
def basis(self, index):
"""
Initialize me as a basis vector: all elements are set to zero except {index}, which is
set to one
"""
# initialize
gsl.vector_basis(self.data, index)
# and return
return self
def random(self, pdf):
"""
Fill me with random numbers using the probability distribution {pdf}
"""
# the {pdf} knows how to do this
return pdf.vector(vector=self)
def clone(self):
"""
Allocate a new vector and initialize it using my values
"""
# build the clone
clone = type(self)(shape=self.shape)
# have the extension initialize the clone
gsl.vector_copy(clone.data, self.data)
# and return it
return clone
def copy(self, other):
"""
Fill me with values from {other}, which is assumed to be of compatible shape
"""
# fill me with values from {other}
gsl.vector_copy(self.data, other.data)
# and return me
return self
def tuple(self):
"""
Build a representation of my contents as a tuple
"""
# ask the extension to build the rep
rep = gsl.vector_tuple(self.data)
# and return it
return rep
def view(self, start, shape):
"""
Build a view of my from {start} to {start+shape}
"""
# access the view object
from .VectorView import VectorView
# build and return one
return VectorView(vector=self, start=start, shape=shape)
def load(self, filename, binary=None):
"""
Read my values from {filename}
This method attempts to distinguish between text and binary representations of the
data, based on the parameter {mode}, or the {filename} extension if {mode} is absent
"""
# if the caller asked for binary mode
if binary is True:
# pick the binary representation
return self.read(filename)
# if the caller asked for ascii mode
if binary is False:
# pick ascii
return self.scanf(filename)
# otherwise, look at the file extension
suffix = filename.suffix
# if it's {bin}
if suffix == "bin":
# go binary
return self.read(filename)
# otherwise
return self.scanf(filename)
def save(self, filename, binary=None, format=defaultFormat):
"""
Write my values to {filename}
This method attempts to distinguish between text and binary representations of the
data, based on the parameter {mode}, or the {filename} extension if {mode} is absent
"""
# if the caller asked for binary mode
if binary is True:
# pick the binary representation
return self.write(filename)
# if the caller asked for ascii mode
if binary is False:
# pick ascii
return self.printf(filename=filename, format=format)
# otherwise, look at the file extension
suffix = filename.suffix
# if it's {bin}
if suffix == ".bin":
# go binary
return self.write(filename)
# otherwise
return self.printf(filename=filename, format=format)
def read(self, filename):
"""
Read my values from {filename}
"""
# read
gsl.vector_read(self.data, filename.path)
# and return
return self
def write(self, filename):
"""
Write my values to {filename}
"""
# write
gsl.vector_write(self.data, filename.path)
# and return
return self
def scanf(self, filename):
"""
Read my values from {filename}
"""
# read
gsl.vector_scanf(self.data, filename.path)
# and return
return self
def printf(self, filename, format=defaultFormat):
"""
Write my values to {filename}
"""
# write
gsl.vector_printf(self.data, filename.path, '%'+format+'e')
# and return
return self
def print(self, format='{:+13.4e}', indent='', interactive=True):
"""
Print my values using the given {format}
"""
# build the line
line = ' '.join(
[ '{}['.format(indent) ] +
[ format.format(value) for value in self ] +
[']']
)
# if we are in interactive mode
if interactive:
# print all this our
print(line)
# all done
return line
# maxima and minima
def max(self):
"""
Compute my maximum value
"""
# easy enough
return gsl.vector_max(self.data)
def min(self):
"""
Compute my maximum value
"""
# easy enough
return gsl.vector_min(self.data)
def minmax(self):
"""
Compute my minimum and maximum values
"""
# easy enough
return gsl.vector_minmax(self.data)
# statistics
def sort(self):
"""
In-place sort of the elements of a vector
"""
# sort
gsl.vector_sort(self.data)
# and return myself
return self
def sortIndirect(self):
"""
Construct the permutation that would sort me in ascending order
"""
# get the permutation capsule
pdata = gsl.vector_sortIndex(self.data)
# build a permutation object and return it
return self.permutation(shape=self.shape, data=pdata)
def mean(self, weights=None):
"""
Compute the mean value of my elements, weighted by the optional {weights}
"""
# easy enough
return gsl.vector_mean(self.data, weights.data if weights is not None else None)
def median(self):
"""
Compute the median value of my elements; only works on previously sorted vectors
"""
# easy enough
return gsl.vector_median(self.data)
def variance(self, mean=None):
"""
Compute the variance of my elements with respect to {mean}. If {mean} is {None}, it is
computed on the fly
"""
# easy enough
return gsl.vector_variance(self.data, float(mean) if mean is not None else None)
def sdev(self, mean=None):
"""
Compute the mean value of my elements with respect to {mean}. If {mean} is {None}, it
is computed on the fly
"""
# easy enough
return gsl.vector_sdev(self.data, float(mean) if mean is not None else None)
def ndarray(self, copy=False):
"""
Return a numpy array reference (w/ shared data) if {copy} is False, or a new copy if {copy} is {True}
"""
# call c-api extension to create a numpy array reference
array = gsl.vector_ndarray(self.data)
# whether the data copy is required
if copy:
array = array.copy()
return array
# meta methods
def __init__(self, shape, data=None, **kwds):
# chain up
super().__init__(**kwds)
# adjust the shape, just in case
shape = int(shape)
# store
self.shape = shape
self.data = gsl.vector_alloc(shape) if data is None else data
# all done
return
# container support
def __len__(self):
# easy
return self.shape
def __iter__(self):
# for each valid value of the index
for index in range(self.shape):
# produce the corresponding element
yield gsl.vector_get(self.data, index)
# no more
return
def __contains__(self, value):
# faster than checking every element in python
return gsl.vector_contains(self.data, value)
def __getitem__(self, index):
# assuming {index} is convertible into an integer, attempt to
try:
# get and return the element
return gsl.vector_get(self.data, int(index))
# if this fails
except TypeError:
# check whether {index} is a slice
if type(index) is not slice:
# if not, we are out of ideas
raise TypeError(
'vector indices must be integers, not {.__name__}'.format(type(index)))
# we have a slice, so return an appropriate value generator
return self._slice(index)
def __setitem__(self, index, value):
# assuming {index} is convertible into an integer, attempt to
try:
# set the corresponding element to the provided value
return gsl.vector_set(self.data, int(index), value)
# if this fails
except TypeError:
# check whether {index} is a slice
if type(index) is not slice:
# if not, we are out of ideas
raise TypeError(
'vector indices must be integers, not {.__name__}'.format(type(index)))
# we have a slice; assume {value} is a compatible iterable
try:
# iterate over the slice and the values
for i,v in zip(range(*index.indices(self.shape)), value):
# and set the corresponding vector element
gsl.vector_set(self.data, i, v)
except TypeError:
raise TypeError('can only assign an iterable')
# all done
return
# comparisons
def __eq__(self, other):
# type check
if type(self) is not type(other): return NotImplemented
# hand the request off to the extension module
return gsl.vector_equal(self.data, other.data)
def __ne__(self, other):
return not (self == other)
# in-place arithmetic
def __iadd__(self, other):
"""
In-place addition with the elements of {other}
"""
# if other is a vector
if isinstance(other, Vector):
# do vector-vector addition
gsl.vector_add(self.data, other.data)
# and return
return self
# if other is a number
if isinstance(other, numbers.Number):
# do constant addition
gsl.vector_shift(self.data, float(other))
# and return
return self
# otherwise, let the interpreter know
raise NotImplemented
def __isub__(self, other):
"""
In-place subtraction with the elements of {other}
"""
# if other is a vector
if isinstance(other, Vector):
# do vector-vector subtraction
gsl.vector_sub(self.data, other.data)
# and return
return self
# if other is a number
if isinstance(other, numbers.Number):
# do constant subtraction
gsl.vector_shift(self.data, -float(other))
# and return
return self
# otherwise, let the interpreter know
raise NotImplemented
def __imul__(self, other):
"""
In-place multiplication with the elements of {other}
"""
# if other is a vector
if isinstance(other, Vector):
# do vector-vector multiplication
gsl.vector_mul(self.data, other.data)
# and return
return self
# if other is a number
if isinstance(other, numbers.Number):
# do scaling by constant
gsl.vector_scale(self.data, float(other))
# and return
return self
# otherwise, let the interpreter know
raise NotImplemented
def __itruediv__(self, other):
"""
In-place addition with the elements of {other}
"""
# if other is a vector
if isinstance(other, Vector):
# do vector-vector division
gsl.vector_div(self.data, other.data)
# and return
return self
# if other is a number
if isinstance(other, numbers.Number):
# do scaling by constant
gsl.vector_scale(self.data, 1/float(other))
# and return
return self
# otherwise, let the interpreter know
raise NotImplemented
# implementation details
def _slice(self, index):
"""
Build a generator that yields the values described in the {index}
"""
# iterate over the indices
for i in range(*index.indices(self.shape)):
# yield the corresponding value
yield gsl.vector_get(self.data, i)
# all done
return
# private data
data = None
# end of file
| 27.951342 | 109 | 0.563779 | 1,967 | 16,659 | 4.724453 | 0.179461 | 0.036802 | 0.022598 | 0.028624 | 0.470354 | 0.428495 | 0.399548 | 0.385451 | 0.36436 | 0.350802 | 0 | 0.001777 | 0.358305 | 16,659 | 595 | 110 | 27.998319 | 0.86754 | 0.360466 | 0 | 0.376812 | 0 | 0 | 0.015714 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.202899 | false | 0 | 0.033816 | 0.014493 | 0.512077 | 0.028986 | 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 |
e075957167bccf1ecb23bf44924b30eb7476d30f | 1,532 | py | Python | day8.py | mayitbeegh/advent-of-code-2020 | 1b35bdad595db3ce72712e5e81163ae7f48c344c | [
"MIT"
] | 3 | 2020-12-07T22:20:32.000Z | 2020-12-07T22:21:56.000Z | day8.py | mayitbeegh/advent-of-code-2020 | 1b35bdad595db3ce72712e5e81163ae7f48c344c | [
"MIT"
] | null | null | null | day8.py | mayitbeegh/advent-of-code-2020 | 1b35bdad595db3ce72712e5e81163ae7f48c344c | [
"MIT"
] | null | null | null | def part_one(inputs):
return get_acc(inputs, False)
def part_two(inputs):
for current_line in range(len(inputs)):
backup = inputs[current_line]
try:
if inputs[current_line][:3] == 'nop' and inputs[current_line][4:] != '+0':
inputs[current_line] = 'jmp' + inputs[current_line][3:]
return get_acc(inputs, True)
elif inputs[current_line][:3] == 'jmp':
inputs[current_line] = 'nop' + inputs[current_line][3:]
return get_acc(inputs, True)
except:
inputs[current_line] = backup
def get_acc(inputs, raise_on_loop):
executed_lines = set()
acc = 0
current_line = 0
while current_line not in executed_lines:
if current_line >= len(inputs):
return acc
executed_lines.add(current_line)
if inputs[current_line][:3] == 'nop':
current_line += 1
elif inputs[current_line][:3] == 'jmp':
current_line += int(inputs[current_line][4:])
elif inputs[current_line][:3] == 'acc':
acc += int(inputs[current_line][4:])
current_line += 1
if raise_on_loop:
raise
else:
return acc
test_inputs = """nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6""".split('\n')
assert part_one(test_inputs) == 5
assert part_two(test_inputs) == 8
with open('day8.input') as f:
inputs = f.read().splitlines()
print(part_one(inputs))
print(part_two(inputs))
| 27.357143 | 86 | 0.577023 | 205 | 1,532 | 4.107317 | 0.273171 | 0.287411 | 0.28266 | 0.149644 | 0.311164 | 0.209026 | 0.095012 | 0.095012 | 0.095012 | 0 | 0 | 0.025759 | 0.29047 | 1,532 | 55 | 87 | 27.854545 | 0.74885 | 0 | 0 | 0.208333 | 0 | 0 | 0.063969 | 0 | 0 | 0 | 0 | 0 | 0.041667 | 1 | 0.0625 | false | 0 | 0 | 0.020833 | 0.166667 | 0.041667 | 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 |
0eba2208744f07369091fb7690933857649738bb | 1,695 | py | Python | 25. python lists.py | JatinR05/Python-3-basics-series | e4b3d8056e2074602c9ed0cd201676484dd0d179 | [
"MIT"
] | 41 | 2015-05-12T12:49:35.000Z | 2021-07-13T11:07:09.000Z | 25. python lists.py | JatinR05/Python-3-basics-series | e4b3d8056e2074602c9ed0cd201676484dd0d179 | [
"MIT"
] | null | null | null | 25. python lists.py | JatinR05/Python-3-basics-series | e4b3d8056e2074602c9ed0cd201676484dd0d179 | [
"MIT"
] | 37 | 2016-10-13T04:02:09.000Z | 2021-12-16T18:28:27.000Z | '''
Since lists are mutable, this means that we will be using lists for
things where we might intend to manipulate the list of data, so how
can we do that? Turns out we can do all sorts of things.
We can add, remove, count, sort, search, and do quite a few other things
to python lists.
'''
# first we need an example list:
x = [1,6,3,2,6,1,2,6,7]
# lets add something.
# we can do .append, which will add something to the end of the list, like:
x.append(55)
print(x)
# what if you have an exact place that you'd like to put something in a list?
x.insert(2,33)
print(x)
# so the reason that went in the 3rd place, again, is because we start
# at the zero element, then go 1, 2.. .and so on.
# now we can remove things... .remove will remove the first instance
# of the value in the list. If it doesn't exist, there will be an error:
x.remove(6)
print(x)
#next, remember how we can reference an item by index in a list? like:
print(x[5])
# well we can also search for this index, like so:
print(x.index(1))
# now here, we can see that it actually returned a 0, meaning the
# first element was a 1... when we knew there was another with an index of 5.
# so instead we might want to know before-hand how many examples there are.
print(x.count(1))
# so we see there are actually 2 of them
# we can also sort the list:
x.sort()
print(x)
# what if these were strings? like:
y = ['Jan','Dan','Bob','Alice','Jon','Jack']
y.sort()
print(y)
# noooo problemo!
# You can also just reverse a list, but, before we go there, we should note that
# all of these manipulations are mutating the list. keep in mind that any
# changes you make will modify the existing variable.
| 21.455696 | 80 | 0.703245 | 328 | 1,695 | 3.634146 | 0.448171 | 0.033557 | 0.011745 | 0.020134 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018587 | 0.20649 | 1,695 | 78 | 81 | 21.730769 | 0.867658 | 0.821239 | 0 | 0.266667 | 0 | 0 | 0.077491 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.533333 | 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 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
0ec1392f92d3736989af6b49b2a5ac2ae00a5f3f | 401 | py | Python | test/test_decode.py | jzkj-luolinh/simonsc | a3c47d4ae6eba71e91f6110fe53bf1fc2e99736d | [
"Apache-2.0"
] | 2 | 2020-12-09T01:55:42.000Z | 2021-06-30T18:28:25.000Z | test/test_decode.py | jzkj-luolinh/simonsc | a3c47d4ae6eba71e91f6110fe53bf1fc2e99736d | [
"Apache-2.0"
] | 1 | 2020-12-31T06:09:56.000Z | 2020-12-31T06:09:56.000Z | test/test_decode.py | jzkj-luolinh/simonsc | a3c47d4ae6eba71e91f6110fe53bf1fc2e99736d | [
"Apache-2.0"
] | 10 | 2020-10-16T07:36:04.000Z | 2021-01-25T08:57:47.000Z | # #!/usr/bin/env python3
# # -*- coding: utf-8 -*-
# import pandas as pd
# import datetime
# from simonsc import auth
# from simonsc import history_bars
# auth("quantresearch","quantresearch")
# dt = datetime.datetime(2020,4,20)
# fields=["datetime","open","high","low","close"]
# data = history_bars(order_book_id="000001.XSHE", dt=dt, bar_count=20, frequency="1d", fields=fields)
# print(data)
| 23.588235 | 102 | 0.690773 | 56 | 401 | 4.857143 | 0.678571 | 0.080882 | 0.125 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.051282 | 0.124688 | 401 | 16 | 103 | 25.0625 | 0.723647 | 0.925187 | 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 |
0ec1f5b1cff3e8873b8bdbe0baa64e19fe70f666 | 2,550 | py | Python | subreddit_summarizer/auth.py | uszkaisandor/subreddit-summarizer | 6dd36836181bb3047f0ef17bf8542fd3ceab61de | [
"MIT"
] | null | null | null | subreddit_summarizer/auth.py | uszkaisandor/subreddit-summarizer | 6dd36836181bb3047f0ef17bf8542fd3ceab61de | [
"MIT"
] | null | null | null | subreddit_summarizer/auth.py | uszkaisandor/subreddit-summarizer | 6dd36836181bb3047f0ef17bf8542fd3ceab61de | [
"MIT"
] | null | null | null |
from flask import (
Blueprint, redirect, render_template,
request, session, url_for, current_app
)
import pymongo
from werkzeug.security import check_password_hash, generate_password_hash
bp = Blueprint('auth', __name__, url_prefix='/')
""" Connect to MongoDB """
conn = pymongo.MongoClient() # connect to localhost
db = conn['redditclient'] # select database
users = db['users'] # select users collection
subreddits = db['subreddits']
""" App entry """
@bp.route('/')
def index():
if 'username' in session:
user = session['username']
return redirect(url_for('reddit.get_reddit'))
return render_template('index.html')
""" Register """
@bp.route('/register', methods=['POST', 'GET'])
def register():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if not username:
error = 'Username is required.'
elif not password or len(password) < 8:
error = 'Password is required (8 characters min).'
elif db.users.find_one({'username': username}):
error = 'The username "{}" already exists!'.format(username)
if error is None:
password_hash = generate_password_hash(password)
db.users.insert_one(
{'username': username, 'password': password_hash, 'subreddits': [], 'posts': []})
return redirect(url_for('index'))
return render_template('register.html', error=error)
@bp.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = db.users.find_one({'username': request.form['username']})
if user is None:
error = 'Incorrect username.'
elif not check_password_hash(user['password'], password):
error = 'Incorrect password.'
if error is None:
session.clear()
session['username'] = user['username']
return redirect(url_for('index'))
return render_template('index.html', error=error)
@bp.route('/logout', methods=['POST'])
def logout():
if request.method == 'POST':
session.clear()
return redirect(url_for('index'))
@bp.route('/delete_user', methods=['POST'])
def delete_user():
if request.method == 'POST':
db.users.delete_one({"username" : session['username']})
session.clear()
return redirect(url_for('index'))
| 31.097561 | 97 | 0.619216 | 286 | 2,550 | 5.405594 | 0.272727 | 0.023286 | 0.054981 | 0.064683 | 0.354463 | 0.21216 | 0.21216 | 0.164295 | 0.10608 | 0.10608 | 0 | 0.001022 | 0.232549 | 2,550 | 81 | 98 | 31.481481 | 0.788963 | 0.023529 | 0 | 0.306452 | 1 | 0 | 0.185567 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.080645 | false | 0.145161 | 0.048387 | 0 | 0.258065 | 0.032258 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
0ec8d41d280ea99101dd0eda23622d3bd2ba7264 | 130 | py | Python | d-series/d579.py | TheLurkingCat/ZeroJudge | 6fc49c54a45e2b4b3a8d04b7a5a1fc81a2ff4eee | [
"MIT"
] | 1 | 2018-10-21T10:03:42.000Z | 2018-10-21T10:03:42.000Z | d-series/d579.py | TheLurkingCat/ZeroJudge | 6fc49c54a45e2b4b3a8d04b7a5a1fc81a2ff4eee | [
"MIT"
] | null | null | null | d-series/d579.py | TheLurkingCat/ZeroJudge | 6fc49c54a45e2b4b3a8d04b7a5a1fc81a2ff4eee | [
"MIT"
] | 2 | 2018-10-12T16:40:11.000Z | 2021-04-05T12:05:36.000Z | while True:
try:
a = float(input())
except EOFError:
break
print('|{:.4f}|={:.4f}'.format(a, abs(a)))
| 18.571429 | 46 | 0.476923 | 16 | 130 | 3.875 | 0.8125 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.021978 | 0.3 | 130 | 6 | 47 | 21.666667 | 0.659341 | 0 | 0 | 0 | 0 | 0 | 0.115385 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 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 |
0edb193daed3f23599e865e05db17baf8d451a4c | 423 | py | Python | tests/test_ledger.py | aslehigh/piecash | 797aca5abd08b686e5d47f077b00a095fb4804ed | [
"MIT"
] | null | null | null | tests/test_ledger.py | aslehigh/piecash | 797aca5abd08b686e5d47f077b00a095fb4804ed | [
"MIT"
] | null | null | null | tests/test_ledger.py | aslehigh/piecash | 797aca5abd08b686e5d47f077b00a095fb4804ed | [
"MIT"
] | null | null | null | # -*- coding: latin-1 -*-
import pytest
import sys
import codecs
import piecash
from test_helper import file_template_full
if sys.version_info.major == 2:
out = codecs.getwriter('UTF-8')(sys.stdout)
else:
out = sys.stdout
class TestLedger_out_write(object):
def test_out_write(self):
with piecash.open_book( file_template_full, open_if_lock=True ) as data:
out.write(piecash.ledger(data)) | 24.882353 | 80 | 0.718676 | 63 | 423 | 4.619048 | 0.619048 | 0.082474 | 0.109966 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008596 | 0.174941 | 423 | 17 | 81 | 24.882353 | 0.825215 | 0.054374 | 0 | 0 | 0 | 0 | 0.012531 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0.384615 | 0 | 0.538462 | 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 |
0ef671b4c13504159cc80475fd98eba6e1706ee2 | 5,786 | py | Python | Tools/HIL/run_tests.py | AlexanderAurora/Firmware | c307a046f9370f7a4016a6eeeaa5ef2a30549eae | [
"BSD-3-Clause"
] | null | null | null | Tools/HIL/run_tests.py | AlexanderAurora/Firmware | c307a046f9370f7a4016a6eeeaa5ef2a30549eae | [
"BSD-3-Clause"
] | null | null | null | Tools/HIL/run_tests.py | AlexanderAurora/Firmware | c307a046f9370f7a4016a6eeeaa5ef2a30549eae | [
"BSD-3-Clause"
] | null | null | null | #! /usr/bin/python
import serial, time
import subprocess
from subprocess import call, Popen
from argparse import ArgumentParser
import re
import unittest
import os
def do_test(port, baudrate, test_name):
databits = serial.EIGHTBITS
stopbits = serial.STOPBITS_ONE
parity = serial.PARITY_NONE
ser = serial.Serial(port, baudrate, databits, parity, stopbits, timeout=10)
ser.write('\n')
success = False
timeout = 10 # 10 seconds
timeout_start = time.time()
while True:
serial_line = ser.readline()
print(serial_line.replace('\n',''))
if "nsh>" in serial_line:
break
elif "NuttShell (NSH)" in serial_line:
break
if time.time() > timeout_start + timeout:
print("Error, timeout")
break
ser.write('\n')
time.sleep(0.01)
# run test cmd
cmd = 'tests ' + test_name
ser.write(cmd + '\n')
timeout = 180 # 3 minutes
timeout_start = time.time()
timeout_newline = timeout_start
while True:
serial_line = ser.readline()
print(serial_line.replace('\n',''))
if cmd in serial_line:
continue
elif test_name + " PASSED" in serial_line:
success = True
break
elif test_name + " FAILED" in serial_line:
success = False
break
if time.time() > timeout_start + timeout:
print("Error, timeout")
print(test_name + " FAILED")
success = False
break
# newline every 30 seconds if still running
if time.time() - timeout_newline > 30:
ser.write('\n')
timeout_newline = time.time()
ser.close()
return success
class TestHardwareMethods(unittest.TestCase):
TEST_DEVICE = 0
TEST_BAUDRATE = 0
def test_atomic_bitset(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "atomic_bitset"))
def test_bezier(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "bezier"))
def test_bitset(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "bitset"))
def test_bson(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "bson"))
def test_commander(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "commander"))
def test_controllib(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "controllib"))
# def test_dataman(self):
# self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "dataman"))
def floattest_float(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "float"))
def test_hrt(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "hrt"))
def test_IntrusiveQueue(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "IntrusiveQueue"))
def test_IntrusiveSortedList(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "IntrusiveSortedList"))
def test_List(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "List"))
def test_mathlib(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "mathlib"))
def test_matrix(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "matrix"))
def test_microbench_atomic(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "microbench_atomic"))
def test_microbench_hrt(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "microbench_hrt"))
def test_microbench_math(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "microbench_math"))
def test_microbench_matrix(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "microbench_matrix"))
def test_microbench_uorb(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "microbench_uorb"))
# def test_mixer(self):
# self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "mixer"))
def test_param(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "param"))
def test_parameters(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "parameters"))
def test_perf(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "perf"))
# def test_rc(self):
# self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "rc"))
def test_search_min(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "search_min"))
def test_sleep(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "sleep"))
def test_smoothz(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "smoothz"))
def test_time(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "time"))
def test_uorb(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "uorb"))
def test_versioning(self):
self.assertTrue(do_test(self.TEST_DEVICE, self.TEST_BAUDRATE, "versioning"))
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('--device', "-d", nargs='?', default = None, help='')
parser.add_argument("--baudrate", "-b", dest="baudrate", type=int, help="Mavlink port baud rate (default=57600)", default=57600)
args = parser.parse_args()
TestHardwareMethods.TEST_DEVICE = args.device
TestHardwareMethods.TEST_BAUDRATE = args.baudrate
unittest.main(__name__, argv=['main'])
if __name__ == "__main__":
main()
| 31.445652 | 132 | 0.673349 | 735 | 5,786 | 5.053061 | 0.165986 | 0.129241 | 0.145396 | 0.161551 | 0.526387 | 0.516963 | 0.516963 | 0.516963 | 0.516963 | 0.516963 | 0 | 0.006333 | 0.208607 | 5,786 | 183 | 133 | 31.617486 | 0.804761 | 0.06654 | 0 | 0.198347 | 0 | 0 | 0.076067 | 0 | 0 | 0 | 0 | 0 | 0.223141 | 1 | 0.239669 | false | 0.008264 | 0.057851 | 0 | 0.330579 | 0.041322 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
0eff23cb96a53d97373dd9fa43c22fb3599cd690 | 3,118 | py | Python | test_user.py | Marah-uwase/Password_locker | d658d72e3e3b8f3317d30e6bb8f2d1cad7fdaed0 | [
"MIT"
] | null | null | null | test_user.py | Marah-uwase/Password_locker | d658d72e3e3b8f3317d30e6bb8f2d1cad7fdaed0 | [
"MIT"
] | null | null | null | test_user.py | Marah-uwase/Password_locker | d658d72e3e3b8f3317d30e6bb8f2d1cad7fdaed0 | [
"MIT"
] | null | null | null | import unittest
from user import User
import pyperclip
class testUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(self):
"""
Method to run before each test case
"""
self.new_user = User("Maranatha", "uwase", "Marah-uwase", "marahuwase@31998") # Create user object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.first_name,"Maranatha")
self.assertEqual(self.new_user.last_name,"uwase")
self.assertEqual(self.new_user.user_name,"Marah-uwase")
self.assertEqual(self.new_user.password,"marahuwase@31998")
def test_save_user(self):
'''
test_save_user test case to test if the user object is saved into the user list
'''
self.new_user.save_user() #saving the new user
self.assertEqual(len(User.user_list),1)
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
User.user_list = []
def test_save_multiple_users(self):
'''
test_save_multiple_users to check if we can save multiple user
objects to our user_list
'''
self.new_user.save_user()
test_user = User("moza", "mwenge", "mMrah_afr", "marah@31998")
test_user.save_user()
self.assertEqual(len(User.user_list),2)
def test_delete_user(self):
'''
test_delete_user to test if we can remove a user from our user list
'''
self.new_user.save_user()
test_user = User("Lupita", "Nyongo'o", "Lupita", "blackis beautiful")
test_user.save_user()
self.new_user.delete_user() #Deleting a user object
self.assertEqual(len(User.user_list),1)
def test_find_by_username(self):
'''
test to check if we can find a user by their username and display infformation
'''
self.new_user.save_user()
test_user = User("Lupita", "Nyongo'o", "Lupita", "blackis beautifull")
test_user.save_user()
found_user = User.find_by_username("Lupita")
self.assertEqual(found_user.user_name,"Lupita")
def test_find_by_password(self):
'''
test to check if we can find a user by their password
'''
self.new_user.save_user()
test_user = User("cheki", "ninah", "Gloria", "gloire")
test_user.save_user()
found_password = User.find_by_userpassword("gloire")
self.assertEqual(found_password.password,"gloire")
def test_display_user_information(self):
'''
test to check if we can be able to display users saved in user_list
'''
self.assertEqual(User.display_userInfo(),User.user_list)
if __name__ == '__main__':
unittest.main()
| 28.09009 | 106 | 0.610969 | 398 | 3,118 | 4.577889 | 0.248744 | 0.05708 | 0.066411 | 0.041164 | 0.367179 | 0.29034 | 0.235456 | 0.187706 | 0.13337 | 0.13337 | 0 | 0.008119 | 0.288967 | 3,118 | 110 | 107 | 28.345455 | 0.813712 | 0.259461 | 0 | 0.255814 | 0 | 0 | 0.118022 | 0 | 0 | 0 | 0 | 0 | 0.232558 | 1 | 0.209302 | false | 0.093023 | 0.069767 | 0 | 0.302326 | 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 |
160180fa6ac15c2ea8ee0daf13623e94eaf6e581 | 143 | py | Python | solution-bank/pattern/solution_16.py | anishLearnsToCode/python-training-1 | ef5d6b64f888e167faecd1410563173dcc27f319 | [
"MIT"
] | 3 | 2021-01-05T18:00:14.000Z | 2021-11-28T15:43:04.000Z | solution-bank/pattern/solution_16.py | anishLearnsToCode/python-training-1 | ef5d6b64f888e167faecd1410563173dcc27f319 | [
"MIT"
] | null | null | null | solution-bank/pattern/solution_16.py | anishLearnsToCode/python-training-1 | ef5d6b64f888e167faecd1410563173dcc27f319 | [
"MIT"
] | null | null | null | rows = int(input())
number = 1
for i in range(rows):
for j in range(i + 1):
print(number, end=' ')
number += 1
print()
| 17.875 | 30 | 0.51049 | 22 | 143 | 3.318182 | 0.545455 | 0.191781 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.03125 | 0.328671 | 143 | 7 | 31 | 20.428571 | 0.729167 | 0 | 0 | 0 | 0 | 0 | 0.006993 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.285714 | 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 |
1607e7fa48537da1777d4826e25725a95fc6728a | 213 | py | Python | Pi2/GPIO sandbox.py | jakehyvonen/BTSPython | 9580a04622226a30fea4d5cbd036c7f88a9b732d | [
"MIT"
] | null | null | null | Pi2/GPIO sandbox.py | jakehyvonen/BTSPython | 9580a04622226a30fea4d5cbd036c7f88a9b732d | [
"MIT"
] | null | null | null | Pi2/GPIO sandbox.py | jakehyvonen/BTSPython | 9580a04622226a30fea4d5cbd036c7f88a9b732d | [
"MIT"
] | null | null | null | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
while True:
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
GPIO.output(18,GPIO.LOW)
time.sleep(1) | 21.3 | 29 | 0.71831 | 37 | 213 | 4.135135 | 0.513514 | 0.117647 | 0.156863 | 0.20915 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.043716 | 0.140845 | 213 | 10 | 30 | 21.3 | 0.79235 | 0 | 0 | 0.2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.2 | 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 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
160d85b3ec6a83b6bae2c34f841706d000d4e119 | 481 | py | Python | site/tests/test_list.py | JamesHutchison/brython | 3beb92bb6125a3e2e96b3e25e8fdac5f73a58871 | [
"BSD-3-Clause"
] | 2 | 2018-06-09T15:29:48.000Z | 2019-11-13T09:15:08.000Z | site/tests/test_list.py | JamesHutchison/brython | 3beb92bb6125a3e2e96b3e25e8fdac5f73a58871 | [
"BSD-3-Clause"
] | 2 | 2017-04-14T03:52:41.000Z | 2017-04-14T04:02:06.000Z | site/tests/test_list.py | JamesHutchison/brython | 3beb92bb6125a3e2e96b3e25e8fdac5f73a58871 | [
"BSD-3-Clause"
] | 2 | 2018-02-22T09:48:18.000Z | 2020-06-04T17:00:09.000Z | # list examples
z=[1,2,3]
assert z.__class__ == list
assert isinstance(z,list)
assert str(z)=="[1, 2, 3]"
a=['spam','eggs',100,1234]
print(a[:2]+['bacon',2*2])
print(3*a[:3]+['Boo!'])
print(a[:])
a[2]=a[2]+23
print(a)
a[0:2]=[1,12]
print(a)
a[0:2]=[]
print(a)
a[1:1]=['bletch','xyzzy']
print(a)
a[:0]=a
print(a)
a[:]=[]
print(a)
a.extend('ab')
print(a)
a.extend([1,2,33])
print(a)
# tuple
t = (1,8)
assert t.__class__ == tuple
assert isinstance(t,tuple)
assert str(t)=='(1, 8)'
| 14.147059 | 27 | 0.5842 | 101 | 481 | 2.70297 | 0.287129 | 0.21978 | 0.205128 | 0.087912 | 0.065934 | 0 | 0 | 0 | 0 | 0 | 0 | 0.093023 | 0.106029 | 481 | 33 | 28 | 14.575758 | 0.54186 | 0.039501 | 0 | 0.285714 | 0 | 0 | 0.098039 | 0 | 0 | 0 | 0 | 0 | 0.214286 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.392857 | 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 |
161f91d8b95c7a757527e07d67a4e5ab0740a5bd | 566 | py | Python | noticias/migrations/0003_auto_20190507_1727.py | miglesias91/dt | 6e00f883ebdb581f87750852f18cf9e3058aae2f | [
"MIT"
] | null | null | null | noticias/migrations/0003_auto_20190507_1727.py | miglesias91/dt | 6e00f883ebdb581f87750852f18cf9e3058aae2f | [
"MIT"
] | null | null | null | noticias/migrations/0003_auto_20190507_1727.py | miglesias91/dt | 6e00f883ebdb581f87750852f18cf9e3058aae2f | [
"MIT"
] | null | null | null | # Generated by Django 2.2.1 on 2019-05-07 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('noticias', '0002_remove_nota_comentario'),
]
operations = [
migrations.AddField(
model_name='nota',
name='slug',
field=models.SlugField(default='#', max_length=225),
),
migrations.AddField(
model_name='periodista',
name='slug',
field=models.SlugField(default='#', max_length=225),
),
]
| 23.583333 | 64 | 0.572438 | 57 | 566 | 5.561404 | 0.631579 | 0.113565 | 0.14511 | 0.170347 | 0.29653 | 0.29653 | 0.29653 | 0.29653 | 0.29653 | 0 | 0 | 0.063131 | 0.300353 | 566 | 23 | 65 | 24.608696 | 0.737374 | 0.079505 | 0 | 0.470588 | 1 | 0 | 0.11368 | 0.052023 | 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 |
1624dfaddc8d62bba59be7995c9ec30250e26ba8 | 268 | py | Python | users/serializers.py | radwanov/EEnergy | c3a690c23d27efbe28faba07bc43441d0c0a0903 | [
"MIT"
] | 2 | 2022-03-14T15:42:12.000Z | 2022-03-27T13:47:15.000Z | users/serializers.py | ahmedelmaghallawy/EEnergy | c3a690c23d27efbe28faba07bc43441d0c0a0903 | [
"MIT"
] | 4 | 2021-03-30T13:31:44.000Z | 2021-09-22T18:55:23.000Z | users/serializers.py | ahmedelmaghallawy/EEnergy | c3a690c23d27efbe28faba07bc43441d0c0a0903 | [
"MIT"
] | null | null | null | from rest_framework import serializers
from django.contrib.auth import get_user_model
class UserSerializer(serializers.ModelSerializer):
"""serialize user instance"""
class Meta:
model = get_user_model()
fields = ['id', 'username', 'email']
| 24.363636 | 50 | 0.712687 | 30 | 268 | 6.2 | 0.7 | 0.075269 | 0.129032 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.186567 | 268 | 10 | 51 | 26.8 | 0.853211 | 0.085821 | 0 | 0 | 0 | 0 | 0.062762 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 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 |
16359a81bfbc505f5296b8d20108473ca48808e9 | 2,042 | py | Python | src/apps/climsoft/schemas/instrument_schema.py | opencdms/opencdms-api | f1ed6e1d883025a8658746fe457e0c975718c7be | [
"MIT"
] | 3 | 2020-12-01T09:25:18.000Z | 2022-02-14T23:57:34.000Z | src/apps/climsoft/schemas/instrument_schema.py | opencdms/opencdms-api | f1ed6e1d883025a8658746fe457e0c975718c7be | [
"MIT"
] | 11 | 2021-12-05T10:09:00.000Z | 2022-02-17T08:11:22.000Z | src/apps/climsoft/schemas/instrument_schema.py | opencdms/opencdms-api | f1ed6e1d883025a8658746fe457e0c975718c7be | [
"MIT"
] | 2 | 2021-03-10T19:03:05.000Z | 2021-12-11T08:36:04.000Z | from typing import List
from pydantic import BaseModel, constr
from apps.climsoft.schemas import station_schema
from apps.climsoft.schemas import Response
field_names = {
"instrumentName": "instrument_name",
"instrumentId": "instrument_id",
"serialNumber": "serial_number",
"instrumentUncertainty": "instrument_uncertainty",
"installationDatetime": "installation_datetime",
"deinstallationDatetime": "uninstallation_datetime",
"instrumentPicture": "instrument_picture",
"installedAt": "installed_at"
}
class CreateInstrument(BaseModel):
instrumentName: constr(max_length=255)
instrumentId: constr(max_length=255)
serialNumber: constr(max_length=255)
abbreviation: constr(max_length=255)
model: constr(max_length=255)
manufacturer: constr(max_length=255)
instrumentUncertainty: float
installationDatetime: constr(max_length=50)
deinstallationDatetime: constr(max_length=50)
height: constr(max_length=255)
instrumentPicture: constr(max_length=255)
installedAt: constr(max_length=255)
class Config:
fields = field_names
class UpdateInstrument(BaseModel):
instrumentName: constr(max_length=255)
serialNumber: constr(max_length=255)
abbreviation: constr(max_length=255)
model: constr(max_length=255)
manufacturer: constr(max_length=255)
instrumentUncertainty: float
installationDatetime: constr(max_length=50)
deinstallationDatetime: constr(max_length=50)
height: constr(max_length=255)
instrumentPicture: constr(max_length=255)
installedAt: constr(max_length=255)
class Config:
fields = field_names
class Instrument(CreateInstrument):
class Config:
fields = field_names
orm_mode = True
allow_population_by_field_name = True
class InstrumentResponse(Response):
result: List[Instrument]
class InstrumentWithStation(Instrument):
station: station_schema.Station
class InstrumentWithStationResponse(Response):
result: List[InstrumentWithStation]
| 28.361111 | 56 | 0.754163 | 209 | 2,042 | 7.177033 | 0.282297 | 0.126 | 0.21 | 0.204 | 0.57 | 0.513333 | 0.470667 | 0.470667 | 0.470667 | 0.470667 | 0 | 0.034402 | 0.160137 | 2,042 | 71 | 57 | 28.760563 | 0.840233 | 0 | 0 | 0.518519 | 0 | 0 | 0.130328 | 0.053405 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.074074 | 0 | 0.722222 | 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 |
163b17e6e3928cdf7ab459de812eee18a84c688a | 526 | py | Python | ch3_Processing_Raw_Text/regexp_tokenize.py | MingjunZhou/nltk_book | 62eef0f5a1855e3d6c523a8d58e8725f459d2fbd | [
"BSD-3-Clause"
] | 1 | 2015-01-06T11:37:14.000Z | 2015-01-06T11:37:14.000Z | ch3_Processing_Raw_Text/regexp_tokenize.py | MingjunZhou/nltk_book | 62eef0f5a1855e3d6c523a8d58e8725f459d2fbd | [
"BSD-3-Clause"
] | null | null | null | ch3_Processing_Raw_Text/regexp_tokenize.py | MingjunZhou/nltk_book | 62eef0f5a1855e3d6c523a8d58e8725f459d2fbd | [
"BSD-3-Clause"
] | null | null | null | import nltk
text = 'That U.S.A. poster-print costs $12.40...'
pattern = r'''(?x) # set flag to allow verbose regexps
([A-Z]\.)+ # abbreviations, e.g. U.S.A.
| \w+(-\w+)* # words with optional internal hyphens
| \$?\d+(\.\d+)?%? # currently and percentages, e.g. $12.40, 82%
| \.\.\. # ellipsis
| [][.,;"'?():-_`] # these are separate tokens
'''
print nltk.regexp_tokenize(text, pattern)
| 40.461538 | 81 | 0.439163 | 57 | 526 | 4.017544 | 0.754386 | 0.017467 | 0.026201 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.030211 | 0.370722 | 526 | 12 | 82 | 43.833333 | 0.661631 | 0 | 0 | 0 | 0 | 0.1 | 0.840304 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.1 | null | null | 0.2 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
165aea16cee92f41a58d74bcedca5180d887ff9e | 4,660 | py | Python | tests/core/actions/test_loops.py | fintzd/rasa | 6359be5509c7d87cd29c2ab5149bc45e843fea85 | [
"Apache-2.0"
] | 9,701 | 2019-04-16T15:46:27.000Z | 2022-03-31T11:52:18.000Z | tests/core/actions/test_loops.py | fintzd/rasa | 6359be5509c7d87cd29c2ab5149bc45e843fea85 | [
"Apache-2.0"
] | 6,420 | 2019-04-16T15:58:22.000Z | 2022-03-31T17:54:35.000Z | tests/core/actions/test_loops.py | fintzd/rasa | 6359be5509c7d87cd29c2ab5149bc45e843fea85 | [
"Apache-2.0"
] | 3,063 | 2019-04-16T15:23:52.000Z | 2022-03-31T00:01:12.000Z | from typing import List, Any, Text
import pytest
from rasa.core.actions.loops import LoopAction
from rasa.core.channels import CollectingOutputChannel
from rasa.shared.core.domain import Domain
from rasa.shared.core.events import (
Event,
ActionExecutionRejected,
ActionExecuted,
ActiveLoop,
SlotSet,
)
from rasa.core.nlg import TemplatedNaturalLanguageGenerator
from rasa.shared.core.trackers import DialogueStateTracker
async def test_whole_loop():
expected_activation_events = [
ActionExecutionRejected("tada"),
ActionExecuted("test"),
]
expected_do_events = [ActionExecuted("do")]
expected_deactivation_events = [SlotSet("deactivated")]
form_name = "my form"
class MyLoop(LoopAction):
def name(self) -> Text:
return form_name
async def activate(self, *args: Any) -> List[Event]:
return expected_activation_events
async def do(self, *args: Any) -> List[Event]:
events_so_far = args[-1]
assert events_so_far == [ActiveLoop(form_name), *expected_activation_events]
return expected_do_events
async def deactivate(self, *args) -> List[Event]:
events_so_far = args[-1]
assert events_so_far == [
ActiveLoop(form_name),
*expected_activation_events,
*expected_do_events,
ActiveLoop(None),
]
return expected_deactivation_events
async def is_done(self, *args) -> bool:
events_so_far = args[-1]
return events_so_far == [
ActiveLoop(form_name),
*expected_activation_events,
*expected_do_events,
]
tracker = DialogueStateTracker.from_events("some sender", [])
domain = Domain.empty()
action = MyLoop()
actual = await action.run(
CollectingOutputChannel(),
TemplatedNaturalLanguageGenerator(domain.responses),
tracker,
domain,
)
assert actual == [
ActiveLoop(form_name),
*expected_activation_events,
*expected_do_events,
ActiveLoop(None),
*expected_deactivation_events,
]
async def test_loop_without_deactivate():
expected_activation_events = [
ActionExecutionRejected("tada"),
ActionExecuted("test"),
]
expected_do_events = [ActionExecuted("do")]
form_name = "my form"
class MyLoop(LoopAction):
def name(self) -> Text:
return form_name
async def activate(self, *args: Any) -> List[Event]:
return expected_activation_events
async def do(self, *args: Any) -> List[Event]:
return expected_do_events
async def deactivate(self, *args) -> List[Event]:
raise ValueError("this shouldn't be called")
async def is_done(self, *args) -> bool:
return False
tracker = DialogueStateTracker.from_events("some sender", [])
domain = Domain.empty()
action = MyLoop()
actual = await action.run(
CollectingOutputChannel(),
TemplatedNaturalLanguageGenerator(domain.responses),
tracker,
domain,
)
assert actual == [
ActiveLoop(form_name),
*expected_activation_events,
*expected_do_events,
]
async def test_loop_without_activate_and_without_deactivate():
expected_do_events = [ActionExecuted("do")]
form_name = "my form"
class MyLoop(LoopAction):
def name(self) -> Text:
return form_name
async def activate(self, *args: Any) -> List[Event]:
raise ValueError("this shouldn't be called")
async def do(self, *args: Any) -> List[Event]:
return expected_do_events
async def deactivate(self, *args) -> List[Event]:
return [SlotSet("deactivated")]
async def is_activated(self, *args: Any) -> bool:
return True
async def is_done(self, *args) -> bool:
return False
tracker = DialogueStateTracker.from_events("some sender", [])
domain = Domain.empty()
action = MyLoop()
actual = await action.run(
CollectingOutputChannel(),
TemplatedNaturalLanguageGenerator(domain.responses),
tracker,
domain,
)
assert actual == [*expected_do_events]
async def test_raise_not_implemented_error():
loop = LoopAction()
with pytest.raises(NotImplementedError):
await loop.do(None, None, None, None, [])
with pytest.raises(NotImplementedError):
await loop.is_done(None, None, None, None, [])
| 27.738095 | 88 | 0.627039 | 473 | 4,660 | 5.983087 | 0.173362 | 0.048057 | 0.062191 | 0.031802 | 0.780919 | 0.759011 | 0.699647 | 0.690459 | 0.690459 | 0.690459 | 0 | 0.00089 | 0.276609 | 4,660 | 167 | 89 | 27.904192 | 0.838624 | 0 | 0 | 0.685039 | 0 | 0 | 0.03133 | 0 | 0 | 0 | 0 | 0 | 0.03937 | 1 | 0.023622 | false | 0 | 0.062992 | 0.023622 | 0.220472 | 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 |
1670f0992ad528fa54171da132322e8c1a3fb07a | 2,147 | py | Python | 2018/wip/makemap.py | Deph0/adventofcode | 79433579954d177d886cfb550b3e03d2e3ca21dc | [
"MIT"
] | null | null | null | 2018/wip/makemap.py | Deph0/adventofcode | 79433579954d177d886cfb550b3e03d2e3ca21dc | [
"MIT"
] | 1 | 2021-05-26T20:36:27.000Z | 2021-05-26T21:42:06.000Z | 2018/wip/makemap.py | Deph0/adventofcode | 79433579954d177d886cfb550b3e03d2e3ca21dc | [
"MIT"
] | null | null | null | # AdventOfCode 2018 day 3 pt 1
# https://adventofcode.com/2018/day/3
#r = [1,1,4,4] # x,y,w,h
r1 = [1,3,4,4]
r2 = [3,1,4,4]
r3 = [5,5,2,2]
r = [r1,r2,r3]
size = 8
#map = [['.' for i in range(size)]]*size # copies the reference to each row
map = [x[:] for x in [['.'] * size] * size]
#map = [['.', '.', '.', '.', '.', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']]
#for x in map: print x
# this method only works if x or y is smaller than width or height
def nope_fillrect():
for i in range(len(r)):
rx,ry,rw,rh = r[i]
for y in range(ry,ry+rh+1): # x..width
for x in range(rx,rx+rw+1): # y..height
if map[y][x] != '.':
map[y][x] = '#' # colision
else:
map[y][x] = str(i+1)
#print i,'xy',x,y
#print i,rx,ry,rw,rh
show()
def fillrect():
yi = 0
for y in map:
xi = 0
for x in y:
#map[yi][xi] = ''
fillCord(xi,yi)
print x, xi, yi
xi = xi + 1
yi = yi + 1
show()
def fillCord(x,y):
if x in r
map[y][x] = str(1)
def show():
for x in map: print x
###########
## Random test
###########
#r = [1,1,4,4] # x,y,w,h
r1 = [1,3,4,4]
r2 = [3,1,4,4]
r3 = [5,5,2,2]
r = [r1,r2,r3]
size = 8
#map = [['.' for i in range(size)]]*size # copies the reference to each row
map = [x[:] for x in [['.'] * size] * size]
#map = [['.', '.', '.', '.', '.', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', 'o', 'o', 'o', 'o', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.']]
#for x in map: print x
for i in range(len(r)):
rx,ry,rw,rh = r[i]
for y in range(ry,rh+1):
for x in range(rx,rw+1):
if map[y][x] != '.':
map[y][x] = '#' # colision
else:
map[y][x] = str(i+1)
print i,'xy',x,y
#print i,rx,ry,rw,rh
for x in map: print x
| 25.258824 | 343 | 0.372613 | 346 | 2,147 | 2.309249 | 0.184971 | 0.075094 | 0.105131 | 0.130163 | 0.660826 | 0.628285 | 0.590738 | 0.590738 | 0.590738 | 0.590738 | 0 | 0.041063 | 0.228691 | 2,147 | 84 | 344 | 25.559524 | 0.441425 | 0.542152 | 0 | 0.595745 | 0 | 0 | 0.008556 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.085106 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
168607652349f1ae2e6a5dbff382bd0a9c85e8e0 | 504 | py | Python | tests/unit/test_get_lending_pool.py | ZeroEkkusu/aave_brownie_py | a237ca2534a891a0ef4934b70d94e3b62a93cadc | [
"MIT"
] | 1 | 2022-03-02T06:05:00.000Z | 2022-03-02T06:05:00.000Z | tests/unit/test_get_lending_pool.py | ZeroEkkusu/aave_brownie_py | a237ca2534a891a0ef4934b70d94e3b62a93cadc | [
"MIT"
] | 1 | 2022-01-26T10:42:32.000Z | 2022-01-26T11:04:43.000Z | tests/unit/test_get_lending_pool.py | ZeroEkkusu/aave_brownie_py | a237ca2534a891a0ef4934b70d94e3b62a93cadc | [
"MIT"
] | null | null | null | from brownie import interface, network, config
def test_get_lending_pool(test_only_locally):
# Arrange/Act
lending_pool_addresses_provider = interface.ILendingPoolAddressesProvider(
config["networks"][network.show_active()]["lending_pool_addresses_provider"])
lending_pool_address = lending_pool_addresses_provider.getLendingPool()
lending_pool = interface.ILendingPool(lending_pool_address)
# Assert
lending_pool.address == "0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9"
| 42 | 85 | 0.80754 | 51 | 504 | 7.568627 | 0.509804 | 0.227979 | 0.15544 | 0.217617 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.053933 | 0.117063 | 504 | 11 | 86 | 45.818182 | 0.813483 | 0.035714 | 0 | 0 | 0 | 0 | 0.167702 | 0.151139 | 0 | 0 | 0.086957 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.142857 | 0 | 0.285714 | 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 |
168c067e0f4da6002751ff9b182a14b19565b33f | 3,173 | py | Python | src/process/domain/integration/services/DataIntegrationConnectionQueueService.py | jedicontributors/pythondataintegrator | 3e877b367ab9b20185476128ec053db41087879f | [
"MIT"
] | null | null | null | src/process/domain/integration/services/DataIntegrationConnectionQueueService.py | jedicontributors/pythondataintegrator | 3e877b367ab9b20185476128ec053db41087879f | [
"MIT"
] | null | null | null | src/process/domain/integration/services/DataIntegrationConnectionQueueService.py | jedicontributors/pythondataintegrator | 3e877b367ab9b20185476128ec053db41087879f | [
"MIT"
] | null | null | null | from injector import inject
from infrastructor.data.DatabaseSessionManager import DatabaseSessionManager
from infrastructor.data.Repository import Repository
from infrastructor.dependency.scopes import IScoped
from models.dao.integration import DataIntegrationConnectionQueue
from models.dao.integration.DataIntegrationConnection import DataIntegrationConnection
from models.viewmodels.integration.CreateDataIntegrationConnectionQueueModel import \
CreateDataIntegrationConnectionQueueModel
class DataIntegrationConnectionQueueService(IScoped):
@inject
def __init__(self,
database_session_manager: DatabaseSessionManager,
):
self.database_session_manager = database_session_manager
self.data_integration_connection_queue_repository: Repository[DataIntegrationConnectionQueue] = \
Repository[DataIntegrationConnectionQueue](database_session_manager)
#######################################################################################
def get_by_id(self, id: int) -> DataIntegrationConnectionQueue:
entity = self.data_integration_connection_queue_repository.first(IsDeleted=0,
Id=id,
)
return entity
def get_by_data_integration_connection_id(self,
data_integration_connection_id: int) -> DataIntegrationConnectionQueue:
entity = self.data_integration_connection_queue_repository.first(IsDeleted=0,
DataIntegrationConnectionId=data_integration_connection_id,
)
return entity
def insert(self,
data_integration_connection: DataIntegrationConnection,
data: CreateDataIntegrationConnectionQueueModel) -> DataIntegrationConnectionQueue:
data_integration_connection_queue = DataIntegrationConnectionQueue(TopicName=data.TopicName,
DataIntegrationConnection=data_integration_connection)
self.data_integration_connection_queue_repository.insert(data_integration_connection_queue)
return data_integration_connection_queue
def update(self,
data_integration_connection: DataIntegrationConnection,
data: CreateDataIntegrationConnectionQueueModel) -> DataIntegrationConnectionQueue:
data_integration_connection_queue = self.get_by_data_integration_connection_id(
data_integration_connection_id=data_integration_connection.Id,
)
data_integration_connection_queue.DataIntegrationConnection = data_integration_connection
data_integration_connection_queue.TopicName = data.TopicName
return data_integration_connection_queue
def delete(self, id: int):
entity = self.get_by_id(id=id)
if entity is not None:
self.data_integration_connection_queue_repository.delete_by_id(id)
| 56.660714 | 132 | 0.669083 | 240 | 3,173 | 8.479167 | 0.191667 | 0.162162 | 0.27027 | 0.176904 | 0.42801 | 0.42801 | 0.306634 | 0.306634 | 0.306634 | 0.306634 | 0 | 0.000857 | 0.264103 | 3,173 | 55 | 133 | 57.690909 | 0.870664 | 0 | 0 | 0.212766 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.12766 | false | 0 | 0.148936 | 0 | 0.382979 | 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 |
16a4359618521739ad22a39abac86f02f7d06b82 | 346 | py | Python | streamduo/api/health.py | streamduo-inc/streamduo-python-sdk | 740e37c29656861522be718c216f99cba8cad70c | [
"MIT"
] | 1 | 2022-02-02T15:30:10.000Z | 2022-02-02T15:30:10.000Z | streamduo/api/health.py | streamduo-inc/streamduo-python-sdk | 740e37c29656861522be718c216f99cba8cad70c | [
"MIT"
] | null | null | null | streamduo/api/health.py | streamduo-inc/streamduo-python-sdk | 740e37c29656861522be718c216f99cba8cad70c | [
"MIT"
] | null | null | null | class HealthController:
"""
Manages interactions with the /health endpoints
"""
def __init__(self, client):
self.client = client
def check_health(self):
"""
GET request ot the /health endpoint
:return: Requests Response Object
"""
return self.client.call_api('GET', "/health")
| 24.714286 | 53 | 0.601156 | 36 | 346 | 5.611111 | 0.638889 | 0.148515 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.294798 | 346 | 13 | 54 | 26.615385 | 0.827869 | 0.33815 | 0 | 0 | 0 | 0 | 0.054945 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | false | 0 | 0 | 0 | 0.8 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
16bc02c67abb460c961171cc1c638c4aa3eff90b | 3,984 | py | Python | src/pwinput/__init__.py | MrDebugger/pwinput | 2ec28c5fbde9b67d255e1eaeef0a9187eb709edf | [
"MIT"
] | null | null | null | src/pwinput/__init__.py | MrDebugger/pwinput | 2ec28c5fbde9b67d255e1eaeef0a9187eb709edf | [
"MIT"
] | null | null | null | src/pwinput/__init__.py | MrDebugger/pwinput | 2ec28c5fbde9b67d255e1eaeef0a9187eb709edf | [
"MIT"
] | null | null | null | """PWInput
By Al Sweigart al@inventwithpython.com
A cross-platform Python module that displays **** for password input. Works on Windows, unlike getpass. Formerly called stdiomask."""
__version__ = '1.0.2' # type: str
import sys
"""Notes about making this code backwards-compatible with Python 2:
sys.stdout.write() can only write unicode strings, not Python 2 str strings.
I create STR_TYPE to use for isinstance() checks. Also, the u prefix for
unicode strings causes syntax errors on Python 3.1 and 3.2, so instead I
pass those strings to STR_TYPE, which is set to unicode() on Python 2,
which effectively does the same thing as the u prefix.
"""
STR_TYPE = str # type: type
RUNNING_PYTHON_2 = sys.version_info[0] == 2 # type: bool
if RUNNING_PYTHON_2:
STR_TYPE = unicode # Ignore the pyflakes warning on this line.
try:
from typing import List
except ImportError:
pass # There is no typing module on Python 2, but that's fine because we use the comment-style of type hints.
if sys.platform == 'win32':
# For some reason, mypy reports that msvcrt doesn't have getch, ignore this warning:
from msvcrt import getch # type: callable
else: # macOS and Linux
import tty, termios
def getch():
# type: () -> str
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def pwinput(prompt='Password: ', mask='*'):
# type: (str, str) -> str
if RUNNING_PYTHON_2:
# On Python 2, convert `prompt` and `mask` from str to unicode because sys.stdout.write requires unicode.
if isinstance(prompt, str):
# Mypy in Python 3 mode (the default mode) will complain about the following line:
prompt = prompt.decode('utf-8') # type: ignore
if isinstance(mask, str):
# Mypy in Python 3 mode (the default mode) will complain about the following line:
mask = mask.decode('utf-8') # type: ignore
if not isinstance(prompt, STR_TYPE):
raise TypeError('prompt argument must be a str, not %s' % (type(prompt).__name__))
if not isinstance(mask, STR_TYPE):
raise TypeError('mask argument must be a zero- or one-character str, not %s' % (type(prompt).__name__))
if len(mask) > 1:
raise ValueError('mask argument must be a zero- or one-character str')
if mask == '' or sys.stdin is not sys.__stdin__:
# Fall back on getpass if a mask is not needed.
import getpass as gp
return gp.getpass(prompt)
enteredPassword = [] # type: List[str]
sys.stdout.write(prompt)
sys.stdout.flush()
while True:
key = ord(getch())
if key == 13: # Enter key pressed.
if RUNNING_PYTHON_2:
sys.stdout.write(STR_TYPE('\n'))
else:
sys.stdout.write('\n')
return ''.join(enteredPassword)
elif key in (8, 127): # Backspace/Del key erases previous output.
if len(enteredPassword) > 0:
# Erases previous character.
if RUNNING_PYTHON_2:
sys.stdout.write(STR_TYPE('\b \b')) # \b doesn't erase the character, it just moves the cursor back.
else:
sys.stdout.write('\b \b') # \b doesn't erase the character, it just moves the cursor back.
sys.stdout.flush()
enteredPassword = enteredPassword[:-1]
elif 0 <= key <= 31:
# Do nothing for unprintable characters.
# TODO: Handle Esc, F1-F12, arrow keys, home, end, insert, del, pgup, pgdn
pass
else:
# Key is part of the password; display the mask character.
char = chr(key)
sys.stdout.write(mask)
sys.stdout.flush()
enteredPassword.append(char)
| 39.84 | 133 | 0.625 | 549 | 3,984 | 4.468124 | 0.371585 | 0.040359 | 0.045658 | 0.026091 | 0.202201 | 0.19364 | 0.175703 | 0.158174 | 0.158174 | 0.128007 | 0 | 0.014276 | 0.279116 | 3,984 | 99 | 134 | 40.242424 | 0.839833 | 0.313002 | 0 | 0.234375 | 0 | 0 | 0.083078 | 0 | 0 | 0 | 0 | 0.010101 | 0 | 1 | 0.03125 | false | 0.15625 | 0.09375 | 0 | 0.171875 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
16d2e529be1a7776f054de0133178cada0985e7b | 1,342 | py | Python | dpm/distributions/generator.py | nextBillyonair/DPM | 840ffaafe15c208b200b74094ffa8fe493b4c975 | [
"MIT"
] | 1 | 2021-07-20T14:02:55.000Z | 2021-07-20T14:02:55.000Z | dpm/distributions/generator.py | nextBillyonair/DPM | 840ffaafe15c208b200b74094ffa8fe493b4c975 | [
"MIT"
] | null | null | null | dpm/distributions/generator.py | nextBillyonair/DPM | 840ffaafe15c208b200b74094ffa8fe493b4c975 | [
"MIT"
] | null | null | null | import torch
from torch import nn
from torch import distributions as dists
from torch.nn import Module, Parameter, ModuleList
from torch.nn.functional import softplus
import numpy as np
import math
from .distribution import Distribution
from .normal import Normal
from .conditional_model import ConditionalModel
from .dirac_delta import DiracDelta
class Generator(Distribution):
def __init__(self, latent_distribution=None, input_dim=8,
hidden_sizes=[24, 24], activation="LeakyReLU",
output_dim=1):
super().__init__()
self.latent_distribution = latent_distribution
if latent_distribution is None:
self.latent_distribution = Normal(torch.zeros(input_dim), torch.eye(input_dim), learnable=False)
self.conditional_model = ConditionalModel(input_dim, hidden_sizes, activation,
[output_dim], [None], DiracDelta)
self.n_dims = output_dim
def log_prob(self, value):
raise NotImplementedError("Generator log_prob not implemented")
def sample(self, batch_size):
latent_samples = self.latent_distribution.sample(batch_size)
return self.conditional_model.sample(latent_samples)
def get_parameters(self):
return {'latent':self.latent_distribution.get_parameters()}
| 38.342857 | 108 | 0.71237 | 157 | 1,342 | 5.853503 | 0.401274 | 0.137106 | 0.119695 | 0.056583 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005687 | 0.21386 | 1,342 | 34 | 109 | 39.470588 | 0.865403 | 0 | 0 | 0 | 0 | 0 | 0.036513 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.137931 | false | 0 | 0.37931 | 0.034483 | 0.62069 | 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 |
16de93fe16916392547641a1dcaf11b095f41e1b | 775 | py | Python | steps/ShoutSteps.py | cucumber-ltd/shouty-python | cb6081ea75f1a7cb1e49c134a47136a05d55789b | [
"MIT"
] | null | null | null | steps/ShoutSteps.py | cucumber-ltd/shouty-python | cb6081ea75f1a7cb1e49c134a47136a05d55789b | [
"MIT"
] | null | null | null | steps/ShoutSteps.py | cucumber-ltd/shouty-python | cb6081ea75f1a7cb1e49c134a47136a05d55789b | [
"MIT"
] | 1 | 2021-07-15T08:27:46.000Z | 2021-07-15T08:27:46.000Z | from behave import *
from Coordinate import Coordinate
from Shouty import Shouty
# use_step_matcher("re")
SHOUTY = Shouty()
ARBITRARY_MESSAGE = "Hello, world"
@given('Lucy is at {xCoord:d}, {yCoord:d}')
def step_impl(context, xCoord, yCoord):
SHOUTY.set_location("Lucy", Coordinate(xCoord, yCoord))
@step('Sean is at {xCoord:d}, {yCoord:d}')
def step_impl(context, xCoord, yCoord):
SHOUTY.set_location("Sean", Coordinate(xCoord, yCoord))
@when('Sean shouts')
def step_impl(context):
SHOUTY.shout("Sean", ARBITRARY_MESSAGE)
@then('Lucy should hear Sean')
def step_impl(context):
assert(1 == len(SHOUTY.get_shouts_heard_by("Lucy")))
@then('Lucy should hear nothing')
def step_impl(context):
assert(0 == len(SHOUTY.get_shouts_heard_by("Lucy")))
| 22.142857 | 59 | 0.717419 | 111 | 775 | 4.855856 | 0.36036 | 0.064935 | 0.102041 | 0.166976 | 0.437848 | 0.348794 | 0.348794 | 0.241187 | 0.241187 | 0.241187 | 0 | 0.002972 | 0.131613 | 775 | 34 | 60 | 22.794118 | 0.79792 | 0.028387 | 0 | 0.25 | 0 | 0 | 0.20506 | 0 | 0 | 0 | 0 | 0 | 0.1 | 1 | 0.25 | false | 0 | 0.15 | 0 | 0.4 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
16e34ce2c90e292ff9a71ce49fe01c8a2302c7d6 | 572 | py | Python | tests/models/test_inv_resourcegroup.py | prorevizor/noc | 37e44b8afc64318b10699c06a1138eee9e7d6a4e | [
"BSD-3-Clause"
] | 84 | 2017-10-22T11:01:39.000Z | 2022-02-27T03:43:48.000Z | tests/models/test_inv_resourcegroup.py | prorevizor/noc | 37e44b8afc64318b10699c06a1138eee9e7d6a4e | [
"BSD-3-Clause"
] | 22 | 2017-12-11T07:21:56.000Z | 2021-09-23T02:53:50.000Z | tests/models/test_inv_resourcegroup.py | prorevizor/noc | 37e44b8afc64318b10699c06a1138eee9e7d6a4e | [
"BSD-3-Clause"
] | 23 | 2017-12-06T06:59:52.000Z | 2022-02-24T00:02:25.000Z | # ----------------------------------------------------------------------
# inv.ResourceGroup tests
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC modules
from noc.inv.models.resourcegroup import ResourceGroup
def test_clean_leagacy_id():
left = ResourceGroup._get_collection().find_one({"_legacy_id": {"$exists": True}})
assert left is None, "_legacy_id field has been left by migration"
| 38.133333 | 86 | 0.466783 | 50 | 572 | 5.14 | 0.78 | 0.062257 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015534 | 0.09965 | 572 | 14 | 87 | 40.857143 | 0.483495 | 0.545455 | 0 | 0 | 0 | 0 | 0.238095 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0.25 | false | 0 | 0.25 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
16eb2a1ab98fa4018a67799fd70122be35a4a06c | 19,381 | py | Python | act/thermo.py | RPGroup-PBoC/mwc_activation | 6ef3f02a53ecd80877082006ecc4b8fe4204c1d6 | [
"MIT"
] | null | null | null | act/thermo.py | RPGroup-PBoC/mwc_activation | 6ef3f02a53ecd80877082006ecc4b8fe4204c1d6 | [
"MIT"
] | null | null | null | act/thermo.py | RPGroup-PBoC/mwc_activation | 6ef3f02a53ecd80877082006ecc4b8fe4204c1d6 | [
"MIT"
] | null | null | null | """
A module for computing properties of various transcriptional
regulatory architectures.
"""
import numpy as np
import scipy.optimize
class MWC(object):
R"""
A base class for the Monod - Wyman - Changeux model for
allostery.
"""
def __init__(self, effector_conc=None, ka=None, ki=None, ep_ai=None,
n_sites=2, log_transform=False):
"""
Parameters
----------
ep_ai : int, float, or array
Difference in energy between the active and inactive allosteric
states of the repressor. This should be in units of k_BT.
ka, ki : ints, floats, or arrays
The effector dissociation constants for the acitve and inactive
state of the repressor.
log_transform: bool
If True, the provided ka and ki are the log transform and will be
exponentiated in the calculation of pact.
effector_conc: int, float, or array
Concentration of the allosteric effector molecule.
n_sites : int, float or array
Number of cooperative effector binding sites on the repressor.
Default value is 2.
"""
kwargs = dict(effector_conc=effector_conc, ka=ka, ki=ki,
ep_ai=ep_ai, n_sites=n_sites)
# Ensure values are provided.
for k in kwargs.keys():
if type(kwargs[k]) is None:
raise RuntimeError(
"{0} is NoneType and must be defined.".format(k))
# Assign the variables.
self.c = effector_conc
self.ep_ai = ep_ai
self.n = n_sites
if log_transform is True:
self.ka = np.exp(ka)
self.ki = np.exp(ki)
else:
self.ka = ka
self.ki = ki
# Ensure ka and ki are not zero.
if type(ka) is float or int:
_ka = np.array([ka])
if type(ki) is float or int:
_ki = np.array([ki])
if (_ka == 0).any() or (_ki == 0).any():
raise ValueError('ka and/or ki cannot be zero.')
# Ensure positivity of values.
positive_kwargs = dict(effector_conc=self.c,
ka=self.ka, ki=self.ki, n_sites=self.n)
for k in positive_kwargs.keys():
val = positive_kwargs[k]
if type(val) is float or int:
val = np.array([val])
if (val < 0).any():
raise RuntimeError('{0} must be positive.'.format(k))
def pact(self):
R"""
Compute the probability of the active state at each provided parameter
value
Returns
-------
p_active : float or nd-array
The probability of the active state evaluated at each value of
effector_conc, ka, ki, and n_sites
"""
c = self.c
n = self.n
ka = self.ka
ki = self.ki
numer = (1 + c / ka)**n
denom = numer + np.exp(-self.ep_ai) * (1 + c / ki)**n
return numer / denom
def saturation(self):
R"""
Computes the probability of the active state in the limit of
saturating effector concentration.
Returns
-------
saturation : float or nd-array
Saturation value at each provided value of ka, ki, ep_ai, and
n_sites.
"""
ka = self.ka
ki = self.ki
ep_ai = self.ep_ai
n = self.n
return (1 + np.exp(-ep_ai) * (ka / ki)**n)**-1
def leakiness(self):
R"""
COmputes the probability of the active state in the limit of zero effector.
"""
return (1 + np.exp(-self.ep_ai))**-1
class SimpleRepression(object):
R"""
A base class for simple repression with an allosteric
repressor.
"""
def __init__(self, R, ep_r, n_ns=4.6e6, **kwargs):
R"""
Instantiate the SimpleRepression object.
Parameters
----------
R : int, float, or array
Number of repressors in the system (per cell).
ep_r : int, float or array
Repressor-DNA binding energy in units of k_BT.
n_ns : int or float
Number of nonspecific DNA binding sites for the
repressor molecule.
Default value is the approximate length of the *E.
coli* genome, 4.6e6 bp.
**kwargs : dict or tuple
kwargs for allosteric transcription factors see `MWC`
documentation for more information.
"""
# Define the variables.
self.R = R
self.ep_r = ep_r
self.n_ns = n_ns
# Ensure values make sense.
positive_args = dict(R=R, n_ns=n_ns)
for p in positive_args.keys():
val = positive_args[p]
if type(val) is float or int:
val = np.array([val])
if (val < 0).any():
raise RuntimeError("{0} must be positive.".format(p))
# Determine if transcription factor is allosteric
if kwargs:
self.allo = True
self.mwc = MWC(**kwargs)
else:
self.allo = False
def fold_change(self, wpa=True, num_pol=None, ep_pol=None,
pact=False):
R"""
fold - change for simple repression.
Parameters
----------
wpa: bool
If True, the weak promoter approximation is made and the state of
polymerase being bound to the promoter is ignored.
num_pol: int, float, or array
Number of RNA Polymerase units per cell. This is required if
`wpa == True`.
ep_pol: int, float, or array
RNAP - DNA binding energy in units of k_BT. This required if
`wpa == True`.
pact : float or array
The probability of having an active repressor. If None is
provided, the probability will be computed given effector_conc.
Returns
-------
fold_change: float or nd - array
Fold - change in gene expression evaluated at each value of c.
"""
if self.allo == False:
pact = 1
else:
if type(pact) == bool:
pact = self.mwc.pact()
# Compute repression and return inverse.
repression = (1 + pact * (self.R / self.n_ns) * np.exp(-self.ep_r))
return repression**-1
def saturation(self, wpa=True, num_pol=None, ep_pol=0):
R"""
Computes the fold - change in gene expression under saturating
concentrations of effector. This function is only defined for
allosteric repressors.
Parameters
----------
wpa : bool
If True, the weak promoter approximation will be applied.
num_pol : int, float, or array
The number of RNA Polymerase molecules per cell. This is required
if `wpa == False`.
ep_pol : int, float, or array
The RNAP-DNA binding energy in units of k_BT. This is required if
`wpa == False`
Returns
-------
saturation: float or array
The leakiness of the simple repression architecture.
"""
if self.allo is False:
raise RuntimeError(
"""Saturation is only defined for allosteric molecules. (`allosteric = True`)""")
# Compute the pact in limit of c -> inf.
pact = self.mwc.saturation()
return self.fold_change(wpa, num_pol, ep_pol, pact)
def leakiness(self, wpa=True, num_pol=None, ep_pol=0):
R"""
Computes the fold-change in gene expression under a zero concentration
of effector.
Parameters
----------
wpa : bool
If True, the weak promoter approximation will be applied.
num_pol : int, float, or array
The number of RNA Polymerase molecules per cell. This is required
if `wpa == False`.
ep_pol : int, float, or array
The RNAP-DNA binding energy in units of k_BT. This is required if
`wpa == False`
Returns
-------
leakiness: float or array
The leakiness of the simple repression architecture.
"""
# Compute the pact in the limit of c -> 0.
if self.allo is True:
pact = self.mwc.leakiness()
else:
pact = 1
return self.fold_change(wpa, num_pol, ep_pol, pact)
def dynamic_range(self, wpa=True, num_pol=None, ep_pol=0):
R"""
The dynamic range of the fold - change in response to an effector
molecule. This property is only defined for allosteric molecules.
Parameters
----------
wpa : bool
If True, the weak promoter approximation will be applied.
num_pol : int, float, or array
The number of RNA Polymerase molecules per cell. This is required
if `wpa == False`.
ep_pol : int, float, or array
The RNAP-DNA binding energy in units of k_BT. This is required if
`wpa == False`
Returns
-------
dynamic_range: float or array
The leakiness of the simple repression architecture.
"""
# Compute the saturation and leakiness.
sat = self.saturation(wpa, num_pol, ep_pol)
leak = self.leakiness(wpa, num_pol, ep_pol)
return sat - leak
def ec50(self):
"""Computes the EC50 for allosteric architectures"""
if self.allo is False:
raise RuntimeError(
'EC50 defined only for allosteric architectures.')
# Determine the user provided inputs.
R = self.R
n_ns = self.n_ns
ep_r = self.ep_r
ep_ai = self.mwc.ep_ai
ka = self.mwc.ka
ki = self.mwc.ki
n_sites = self.mwc.n
# Break it into pieces
repression = 1 + (R / n_ns) * np.exp(-ep_r)
numer = repression + (ka/ki)**n_sites * \
(2 * np.exp(-ep_ai) + repression)
denom = 2 * repression + \
np.exp(-ep_ai) + (ka / ki)**n_sites * np.exp(-ep_ai)
# Assemble the pieces of the ec50 calculation.
ec50_numer = (ka / ki) - 1
ec50_denom = (ka / ki) - (numer / denom)**(1 / n_sites)
return ka * ((ec50_numer / ec50_denom) - 1)
def effective_hill(self):
"""Computes the effective hill coefficient of an allosteric repressor."""
if self.allo == False:
return RuntimeError("Effective hill only defined for allosteric architectures")
# Define the parameters
c = self.ec50()
ka = self.mwc.ka
ki = self.mwc.ki
ep_ai = self.mwc.ep_ai
n_sites = self.mwc.n
R = self.R
ep_r = self.ep_r
n_ns = self.n_ns
# Compute the fold-change
pact = MWC(c, ka, ki, ep_ai, n_sites).pact()
fc = (1 + pact * (R / n_ns) * np.exp(-ep_r))**-1
leakiness = self.leakiness()
expanded_ka = (1 + c / ka)
expanded_ki = (1 + c / ki)
# Break it into pieces.
prefactor = -fc**2 * (R / n_ns) * np.exp(-ep_r) * 2 * c * np.exp(-ep_ai)
numer = (1 / ka) * expanded_ka * expanded_ki**2 - (1 / ki) * expanded_ka**2 * expanded_ki
denom = (expanded_ka**2 + np.exp(-ep_ai) * expanded_ki**2)**2
return (2 / (fc - leakiness)) * prefactor * numer / denom
def compute_properties(self):
"""
Computes the leakiness, saturation, dynamic range, EC50, and effective hill
coefficient for the architecture. Properties are returned as a dictionary.
"""
if self.allo == False:
raise RuntimeError("Available for allosteric molecules only.")
# Compute the properties.
leak = self.leakiness()
sat = self.saturation()
dyn_rng = self.dynamic_range()
EC50 = self.ec50()
Hill = self.effective_hill()
return {'leakiness': leak, 'saturation': sat, 'dynamic_range':dyn_rng,
'EC50': EC50, 'effective_hill':Hill}
def bohr_parameter(self):
R"""
Computes the Bohr parameter of the form
bohr = k_BT(log(pact) + log(R / N_ns) + ep_r / k_BT)
"""
# Compute pact
if self.allo is True:
pact = self.mwc.pact()
else:
pact = 1
# Compute and return the Bohr.
bohr = self.ep_r - np.log(pact) - np.log(self.R / self.n_ns)
return bohr
class SimpleActivation(object):
"""
Base class for the equilibrium model of the simple activation motif
"""
def __init__(self, A, ep_a, ep_int, n_ns=4.6e6, **kwargs):
R"""
Instantiate the SimpleRepression object.
Parameters
----------
A : int, float, or array
Number of activators in the system (per cell).
ep_a : int, float or array
Activator-DNA binding energy in units of k_BT.
ep_int : int, float, or array
Activator-Polymerase interaction energy in units of k_BT.
n_ns : int or float
Number of nonspecific DNA binding sites for the
repressor molecule.
Default value is the approximate length of the *E.
coli* genome, 4.6e6 bp.
**kwargs : dict or tuple
kwargs for allosteric transcription factors see `MWC`
documentation for more information.
"""
# Define the variables.
self.A = A
self.ep_a = ep_a
self.ep_int = ep_int
self.n_ns = n_ns
# Ensure values make sense.
positive_args = dict(R=R, n_ns=n_ns)
for p in positive_args.keys():
val = positive_args[p]
if type(val) is float or int:
val = np.array([val])
if (val < 0).any():
raise RuntimeError("{0} must be positive.".format(p))
# Determine if transcription factor is allosteric
if kwargs:
self.allo = True
self.mwc = MWC(**kwargs)
else:
self.allo = False
def fold_change(self, pact=False):
R"""
fold - change for simple repression.
Parameters
----------
pact : float or array
The probability of having an active repressor. If None is
provided, the probability will be computed given effector_conc.
Returns
-------
fold_change: float or nd - array
Fold - change in gene expression evaluated at each value of c.
"""
if self.allo == False:
pact = 1
else:
if type(pact) == bool:
pact = self.mwc.pact()
# Compute repression and return inverse.
numerator = 1 + pact * (self.A / self.n_ns) * np.exp(-self.ep_a +\
self.ep_int)
denominator = 1 + pact * (self.A / self.n_ns) * np.exp(-self.ep_a)
return numerator / denominator
def saturation(self, wpa=True, num_pol=None, ep_pol=0):
R"""
Computes the fold - change in gene expression under saturating
concentrations of effector. This function is only defined for
allosteric repressors.
Parameters
----------
wpa : bool
If True, the weak promoter approximation will be applied.
num_pol : int, float, or array
The number of RNA Polymerase molecules per cell. This is required
if `wpa == False`.
ep_pol : int, float, or array
The RNAP-DNA binding energy in units of k_BT. This is required if
`wpa == False`
Returns
-------
saturation: float or array
The leakiness of the simple repression architecture.
"""
if self.allo is False:
raise RuntimeError(
"""Saturation is only defined for allosteric molecules. (`allosteric = True`)""")
# Compute the pact in limit of c -> inf.
pact = self.mwc.saturation()
return self.fold_change(wpa, num_pol, ep_pol, pact)
def leakiness(self, wpa=True, num_pol=None, ep_pol=0):
R"""
Computes the fold-change in gene expression under a zero concentration
of effector.
Parameters
----------
wpa : bool
If True, the weak promoter approximation will be applied.
num_pol : int, float, or array
The number of RNA Polymerase molecules per cell. This is required
if `wpa == False`.
ep_pol : int, float, or array
The RNAP-DNA binding energy in units of k_BT. This is required if
`wpa == False`
Returns
-------
leakiness: float or array
The leakiness of the simple repression architecture.
"""
# Compute the pact in the limit of c -> 0.
if self.allo is True:
pact = self.mwc.leakiness()
else:
pact = 1
return self.fold_change(wpa, num_pol, ep_pol, pact)
def dynamic_range(self, wpa=True, num_pol=None, ep_pol=0):
R"""
The dynamic range of the fold - change in response to an effector
molecule. This property is only defined for allosteric molecules.
Parameters
----------
wpa : bool
If True, the weak promoter approximation will be applied.
num_pol : int, float, or array
The number of RNA Polymerase molecules per cell. This is required
if `wpa == False`.
ep_pol : int, float, or array
The RNAP-DNA binding energy in units of k_BT. This is required if
`wpa == False`
Returns
-------
dynamic_range: float or array
The leakiness of the simple repression architecture.
"""
# Compute the saturation and leakiness.
sat = self.saturation(wpa, num_pol, ep_pol)
leak = self.leakiness(wpa, num_pol, ep_pol)
return sat - leak
def ec50(self):
"""Computes the EC50 for allosteric architectures"""
if self.allo is False:
raise RuntimeError(
'EC50 defined only for allosteric architectures.')
raise UserWarning("EC50 for simple activation not yet implemented.")
def effective_hill(self):
"""Computes the effective hill coefficient of an allosteric repressor."""
if self.allo == False:
return RuntimeError("Effective hill only defined for allosteric architectures")
raise UserWarning("Effective hill for simple activation not yet implemented")
def compute_properties(self):
"""
Computes the leakiness, saturation, dynamic range, EC50, and effective hill
coefficient for the architecture. Properties are returned as a dictionary.
"""
if self.allo == False:
raise RuntimeError("Available for allosteric molecules only.")
# Compute the properties.
leak = self.leakiness()
sat = self.saturation()
dyn_rng = self.dynamic_range()
EC50 = self.ec50()
Hill = self.effective_hill()
return {'leakiness': leak, 'saturation': sat, 'dynamic_range':dyn_rng,
'EC50': EC50, 'effective_hill':Hill}
| 35.561468 | 97 | 0.562716 | 2,464 | 19,381 | 4.336445 | 0.096591 | 0.02555 | 0.033692 | 0.030884 | 0.746748 | 0.723538 | 0.687412 | 0.670566 | 0.658306 | 0.645297 | 0 | 0.008859 | 0.34766 | 19,381 | 544 | 98 | 35.626838 | 0.836273 | 0.438574 | 0 | 0.568282 | 0 | 0 | 0.070096 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.092511 | false | 0 | 0.008811 | 0 | 0.193833 | 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 |
bc3ffd9a63aec03ae7504d78e07335c16e7a2800 | 634 | py | Python | src/pirateplayer/utils/confparse.py | TestDotCom/pirateplayer | c7c23f670d35b7c4f236d0f22a084cb6ee6ab5b9 | [
"MIT"
] | 12 | 2020-05-25T18:52:48.000Z | 2022-03-15T15:12:54.000Z | src/pirateplayer/utils/confparse.py | TestDotCom/pirateplayer | c7c23f670d35b7c4f236d0f22a084cb6ee6ab5b9 | [
"MIT"
] | 4 | 2020-09-11T13:29:52.000Z | 2021-12-17T16:55:54.000Z | src/pirateplayer/utils/confparse.py | TestDotCom/pirateplayer | c7c23f670d35b7c4f236d0f22a084cb6ee6ab5b9 | [
"MIT"
] | null | null | null | # pylint: disable=missing-module-docstring
import configparser
import logging
import os
_LOGGER = logging.getLogger(__name__)
_CONF = configparser.ConfigParser()
def init():
"""Read configuration file"""
_CONF.read(os.path.expanduser('~/.config/pirateplayer/conf.ini'))
def get_root() -> str:
"""Return user-defined music directory,
or default path (~/Music) if none specified.
"""
return os.path.expanduser(_CONF['PLAYER'].get('root', '~/Music'))
def get_pins() -> list:
"""Return user-defined buttons pin (BCM numbering)."""
return list(_CONF['BUTTON'].getint(btn) for btn in _CONF['BUTTON'])
| 25.36 | 71 | 0.690852 | 79 | 634 | 5.392405 | 0.607595 | 0.028169 | 0.075117 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.149842 | 634 | 24 | 72 | 26.416667 | 0.790353 | 0.309148 | 0 | 0 | 0 | 0 | 0.145278 | 0.075061 | 0 | 0 | 0 | 0 | 0 | 1 | 0.272727 | false | 0 | 0.272727 | 0 | 0.727273 | 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 |
bc4accac7ce0137550f2c96a5cd901c5465b8400 | 136 | py | Python | base/site-packages/authsub/urls.py | edisonlz/fastor | 342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3 | [
"Apache-2.0"
] | 285 | 2019-12-23T09:50:21.000Z | 2021-12-08T09:08:49.000Z | pinax/apps/authsub/urls.py | SMiGL/pinax | d08b2655fe661566bd13c5c170b1a4cad9e67a1d | [
"MIT"
] | null | null | null | pinax/apps/authsub/urls.py | SMiGL/pinax | d08b2655fe661566bd13c5c170b1a4cad9e67a1d | [
"MIT"
] | 9 | 2019-12-23T12:59:25.000Z | 2022-03-15T05:12:11.000Z | from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^login/$', 'authsub.views.login', name="authsub_login"),
) | 27.2 | 66 | 0.691176 | 17 | 136 | 5.470588 | 0.823529 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.110294 | 136 | 5 | 67 | 27.2 | 0.768595 | 0 | 0 | 0 | 0 | 0 | 0.291971 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bc53433b45808b824f9ef21a112a8b6ae1bcc1b8 | 4,652 | py | Python | src/about_dlg.py | Bertrand256/dash-masternode-tool | 8fd15e956fd50d4e0da49b7b47fcfdddad14f19d | [
"MIT"
] | 75 | 2017-03-20T06:33:14.000Z | 2022-02-15T16:16:45.000Z | src/about_dlg.py | Bertrand256/dash-masternode-tool | 8fd15e956fd50d4e0da49b7b47fcfdddad14f19d | [
"MIT"
] | 42 | 2017-10-25T06:34:54.000Z | 2022-02-10T20:53:46.000Z | src/about_dlg.py | Bertrand256/dash-masternode-tool | 8fd15e956fd50d4e0da49b7b47fcfdddad14f19d | [
"MIT"
] | 98 | 2017-03-20T05:27:36.000Z | 2022-03-20T05:03:08.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Bertrand256
# Created on: 2017-03
import os
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSize, pyqtSlot
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QDialog
from ui import ui_about_dlg
from wnd_utils import WndUtils, QDetectThemeChange
class AboutDlg(QDialog, QDetectThemeChange, ui_about_dlg.Ui_AboutDlg, WndUtils):
def __init__(self, parent, app_version_str):
QDialog.__init__(self, parent)
ui_about_dlg.Ui_AboutDlg.__init__(self)
WndUtils.__init__(self, parent.app_config)
self.app_version_str = app_version_str
self.setupUi(self)
def setupUi(self, dialog: QtWidgets.QDialog):
ui_about_dlg.Ui_AboutDlg.setupUi(self, self)
self.setWindowTitle("About")
img = QPixmap(os.path.join(self.app_config.app_dir, "img/dmt.png"))
img = img.scaled(QSize(64, 64))
self.lblImage.setPixmap(img)
self.lblAppName.setText('Dash Masternode Tool ' + self.app_version_str)
self.textAbout.setOpenExternalLinks(True)
self.textAbout.viewport().setAutoFillBackground(False)
if sys.platform == 'win32':
self.resize(600, 310)
self.textAbout.setHtml(self.textAbout.toHtml().replace('font-size:11pt', 'font-size:10pt'))
self.textAbout.setHtml(self.textAbout.toHtml().replace('font-size:9pt', 'font-size:8pt'))
elif sys.platform == 'darwin':
self.textAbout.setHtml(self.textAbout.toHtml().replace('font-size:11pt', 'font-size:13pt'))
elif sys.platform == 'linux':
self.resize(620, 320)
self.display_info()
@pyqtSlot(bool)
def on_btnClose_clicked(self):
self.close()
def onThemeChanged(self):
self.display_info()
def display_info(self):
html = f"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li {{ white-space: pre-wrap; }}
</style></head><body style=" font-family:'Arial'; font-size:13pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">
<span style=" ">This application is free for commercial and non-commercial use.</span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">
</p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">
<span style="font-weight:600;">Project's GitHub URL: </span><a href="https://github.com/Bertrand256/dash-masternode-tool">
<span>https://github.com/Bertrand256/dash-masternode-tool</span>
</a></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;
-qt-block-indent:0; text-indent:0px; "><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">
<span style="font-weight:600;">Special thanks to:</span></p>
<ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;">
<li style=" margin-top:4px; margin-bottom:0px; margin-left:0px; margin-right:0px;
-qt-block-indent:0; text-indent:0px;">chaeplin for <a href="https://github.com/chaeplin/dashmnb">dashmnb</a>, which inspired the creation of this program</li>
<li style=" " style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;
-qt-block-indent:0; text-indent:0px;">Andreas Antonopolous for his excellent technical book <a href="https://shop.oreilly.com/product/0636920049524.do">Mastering Bitcoin</a> (<a href="https://github.com/bitcoinbook/bitcoinbook/tree/develop">GitHub version</a>)</li>
<li style=" " style=" margin-top:0px; margin-bottom:6px; margin-left:0px; margin-right:0px;
-qt-block-indent:0; text-indent:0px;">Vitalik Buterin for <a href="https://github.com/vbuterin/pybitcointools">pybitcointools</a> library, which is used in this app</li></ul>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;
-qt-block-indent:0; text-indent:0px; font-size:8.25pt;"><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">
<span style=" font-weight:600;">Author:</span><span style=" "> Bertrand256 (<a href="mailto:blogin@protonmail.com">blogin@protonmail.com</a>)</span>
</p>
</body></html>
"""
self.textAbout.setHtml(html) | 56.048193 | 267 | 0.699699 | 687 | 4,652 | 4.673945 | 0.298399 | 0.086889 | 0.044534 | 0.065089 | 0.453753 | 0.427593 | 0.41389 | 0.41389 | 0.384615 | 0.353161 | 0 | 0.037884 | 0.126182 | 4,652 | 83 | 268 | 56.048193 | 0.75203 | 0.017842 | 0 | 0.157143 | 0 | 0.3 | 0.631187 | 0.073149 | 0 | 0 | 0 | 0 | 0 | 1 | 0.071429 | false | 0 | 0.114286 | 0 | 0.2 | 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 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bc53f5427f1766b08a1850c7f243ebf9b07df940 | 1,978 | py | Python | tests/test_pipelines.py | akamanzi/scrapy | 4d594b8c2bf32cb2e171805cdb71c68b5184cca3 | [
"BSD-3-Clause"
] | 1 | 2020-01-04T15:53:27.000Z | 2020-01-04T15:53:27.000Z | tests/test_pipelines.py | billkangbin/scrapy | ce618fb6f234a854ae3b2a14a8a4e488539999bb | [
"BSD-3-Clause"
] | null | null | null | tests/test_pipelines.py | billkangbin/scrapy | ce618fb6f234a854ae3b2a14a8a4e488539999bb | [
"BSD-3-Clause"
] | 1 | 2021-06-24T17:15:29.000Z | 2021-06-24T17:15:29.000Z | from twisted.internet import defer
from twisted.internet.defer import Deferred
from twisted.trial import unittest
from scrapy import Spider, signals, Request
from scrapy.utils.test import get_crawler
from tests.mockserver import MockServer
class SimplePipeline:
def process_item(self, item, spider):
item['pipeline_passed'] = True
return item
class DeferredPipeline:
def cb(self, item):
item['pipeline_passed'] = True
return item
def process_item(self, item, spider):
d = Deferred()
d.addCallback(self.cb)
d.callback(item)
return d
class ItemSpider(Spider):
name = 'itemspider'
def start_requests(self):
yield Request(self.mockserver.url('/status?n=200'))
def parse(self, response):
return {'field': 42}
class PipelineTestCase(unittest.TestCase):
def setUp(self):
self.mockserver = MockServer()
self.mockserver.__enter__()
def tearDown(self):
self.mockserver.__exit__(None, None, None)
def _on_item_scraped(self, item):
self.assertIsInstance(item, dict)
self.assertTrue(item.get('pipeline_passed'))
self.items.append(item)
def _create_crawler(self, pipeline_class):
settings = {
'ITEM_PIPELINES': {__name__ + '.' + pipeline_class.__name__: 1},
}
crawler = get_crawler(ItemSpider, settings)
crawler.signals.connect(self._on_item_scraped, signals.item_scraped)
self.items = []
return crawler
@defer.inlineCallbacks
def test_simple_pipeline(self):
crawler = self._create_crawler(SimplePipeline)
yield crawler.crawl(mockserver=self.mockserver)
self.assertEqual(len(self.items), 1)
@defer.inlineCallbacks
def test_deferred_pipeline(self):
crawler = self._create_crawler(DeferredPipeline)
yield crawler.crawl(mockserver=self.mockserver)
self.assertEqual(len(self.items), 1)
| 27.472222 | 76 | 0.674924 | 224 | 1,978 | 5.763393 | 0.3125 | 0.065066 | 0.055771 | 0.027885 | 0.255616 | 0.255616 | 0.106894 | 0.106894 | 0.106894 | 0.106894 | 0 | 0.005229 | 0.226491 | 1,978 | 71 | 77 | 27.859155 | 0.838562 | 0 | 0 | 0.226415 | 0 | 0 | 0.044489 | 0 | 0 | 0 | 0 | 0 | 0.075472 | 1 | 0.207547 | false | 0.056604 | 0.113208 | 0.018868 | 0.509434 | 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 |
bc6d5e8dd3f3a74c05ebab2b43fbfc0a5c262f8d | 2,626 | py | Python | molsysmt/tests/topology/get_sequence_identity/test_get_sequence_identity.py | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | molsysmt/tests/topology/get_sequence_identity/test_get_sequence_identity.py | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | molsysmt/tests/topology/get_sequence_identity/test_get_sequence_identity.py | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | """
Unit and regression test for the get_sequence_identity module of the molsysmt package on molsysmt MolSys molecular
systems.
"""
# Import package, test suite, and other packages as needed
import molsysmt as msm
import numpy as np
import math as math
# Distance between atoms in space and time
def test_get_sequence_identity_molsysmt_MolSys_1():
molsys = msm.convert(msm.demo['T4 lysozyme L99A']['181l.msmpk'], to_form='molsysmt.MolSys')
molsys_2 = msm.convert(msm.demo['T4 lysozyme L99A']['1l17.msmpk'], to_form='molsysmt.MolSys')
identity, intersection, ref_intersection = msm.topology.get_sequence_identity(molsys, selection='molecule_type=="protein"',
reference_molecular_system=molsys_2, reference_selection='molecule_type=="protein"')
intersection_true = np.array([0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161])
ref_intersection_true = np.array([0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 99, 100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159, 160, 161])
check_identity = math.isclose(97.53086419, identity)
check_intersection = np.all(intersection_true == intersection)
check_intersection_ref = np.all(ref_intersection_true == intersection_true)
assert check_identity and check_intersection and check_intersection_ref
| 70.972973 | 131 | 0.613481 | 467 | 2,626 | 3.374732 | 0.468951 | 0.050761 | 0.036168 | 0.021574 | 0.568528 | 0.536802 | 0.536802 | 0.497462 | 0.497462 | 0.497462 | 0 | 0.375492 | 0.2262 | 2,626 | 36 | 132 | 72.944444 | 0.400098 | 0.084539 | 0 | 0 | 0 | 0 | 0.054302 | 0.02005 | 0 | 0 | 0 | 0 | 0.038462 | 1 | 0.038462 | false | 0 | 0.115385 | 0 | 0.153846 | 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 |
bc87c4fd05dad0241a52bffc55c49157b5f7dc36 | 1,444 | py | Python | geneticalgorithm/selectionfunctions.py | grajekf/wae-2018 | 609423ad5a6431da3cc481aedfe23c5fdd156373 | [
"MIT"
] | null | null | null | geneticalgorithm/selectionfunctions.py | grajekf/wae-2018 | 609423ad5a6431da3cc481aedfe23c5fdd156373 | [
"MIT"
] | null | null | null | geneticalgorithm/selectionfunctions.py | grajekf/wae-2018 | 609423ad5a6431da3cc481aedfe23c5fdd156373 | [
"MIT"
] | null | null | null | import numpy as np
from geneticalgorithm.selectionfunctor import SelectionFunctor
class TournamentSelection(SelectionFunctor):
def __init__(self, torunament_size):
self.tournament_size = torunament_size
def _select(self, population, fitness):
population_with_fitness = list(zip(population, fitness))
return max([population_with_fitness[i] for i in np.random.choice(len(population_with_fitness), self.tournament_size)],
key=lambda p: p[1])[0]
def select(self, population, fitness):
return self._select(population, fitness), self._select(population, fitness)
def getparameters(self):
return {
'tournament_size': self.tournament_size
}
def setparameter(self, key, value):
changed = False
if key == "tournament_size":
self.tournament_size = value
changed = True
return changed
# def tournament_generator(tournament_size):
# def select_tournament(population, fitness):
# population_with_fitness = list(zip(population, fitness))
# return max([population_with_fitness[i] for i in np.random.choice(len(population_with_fitness), tournament_size)],
# key=lambda p: p[1])[0]
# return select_tournament
# def repeat(fun, n = 2):
# def inner(population, fitness):
# return [fun(population, fitness) for i in range(n)]
# return inner
| 33.581395 | 126 | 0.668283 | 165 | 1,444 | 5.654545 | 0.290909 | 0.163987 | 0.135048 | 0.07074 | 0.466238 | 0.351554 | 0.351554 | 0.351554 | 0.293676 | 0.293676 | 0 | 0.004533 | 0.23615 | 1,444 | 42 | 127 | 34.380952 | 0.841342 | 0.335873 | 0 | 0 | 0 | 0 | 0.031646 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.238095 | false | 0 | 0.095238 | 0.095238 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
bc96f40fb40b644c2ae4d1967127065007a23b3b | 114 | py | Python | modelsearch/src/common.py | stevencdang/AutoML-DS-Components | b0490262d3db5307c37f82c92e25cd938dd3a242 | [
"Apache-2.0"
] | null | null | null | modelsearch/src/common.py | stevencdang/AutoML-DS-Components | b0490262d3db5307c37f82c92e25cd938dd3a242 | [
"Apache-2.0"
] | 8 | 2020-09-04T17:39:26.000Z | 2022-03-02T03:28:38.000Z | modelsearch/src/common.py | stevencdang/AutoML-DS-Components | b0490262d3db5307c37f82c92e25cd938dd3a242 | [
"Apache-2.0"
] | null | null | null | import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
__version__ = '0.1'
| 16.285714 | 39 | 0.789474 | 14 | 114 | 5.857143 | 0.785714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.019417 | 0.096491 | 114 | 6 | 40 | 19 | 0.776699 | 0 | 0 | 0 | 0 | 0 | 0.026316 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bc999a8cba585f6ba3d8b7997aad9afe89cf1510 | 317 | py | Python | src/django_dynamicfields/table_storage/admin.py | saxix/django-dynamicfields | 4c200a3de1b2082f18d89f6b2484103888524f93 | [
"BSD-3-Clause"
] | 1 | 2021-07-14T02:48:25.000Z | 2021-07-14T02:48:25.000Z | src/django_dynamicfields/table_storage/admin.py | saxix/django-dynamicfields | 4c200a3de1b2082f18d89f6b2484103888524f93 | [
"BSD-3-Clause"
] | null | null | null | src/django_dynamicfields/table_storage/admin.py | saxix/django-dynamicfields | 4c200a3de1b2082f18d89f6b2484103888524f93 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from .models import TableStorage
@admin.register(TableStorage)
class ICustomFieldHolder(ModelAdmin):
list_display = ('field', 'value')
| 24.384615 | 72 | 0.785489 | 37 | 317 | 6.513514 | 0.648649 | 0.082988 | 0.141079 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003584 | 0.119874 | 317 | 12 | 73 | 26.416667 | 0.860215 | 0.066246 | 0 | 0 | 0 | 0 | 0.034014 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.571429 | 0 | 0.857143 | 0.142857 | 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 |
bca044293a22ab251d85ea4c7ebcefa165d6b650 | 79 | py | Python | test.py | php568/FlapPyBird-master | 0afcfc8c96762cd2f1931c668681b89bd2f0de44 | [
"MIT"
] | null | null | null | test.py | php568/FlapPyBird-master | 0afcfc8c96762cd2f1931c668681b89bd2f0de44 | [
"MIT"
] | null | null | null | test.py | php568/FlapPyBird-master | 0afcfc8c96762cd2f1931c668681b89bd2f0de44 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
a = ['doge1','doge2','doge3','doge4']
print(a)
| 6.583333 | 37 | 0.468354 | 10 | 79 | 3.7 | 0.9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.080645 | 0.21519 | 79 | 11 | 38 | 7.181818 | 0.516129 | 0.265823 | 0 | 0 | 0 | 0 | 0.416667 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
bca64fd690ec5ac86896993d46e62da31694a534 | 322 | py | Python | apps/organization/migrations/0017_merge.py | SVArago/alexia | 96ae6dfabb893388bd4610ea971574a993b8029d | [
"BSD-3-Clause"
] | 3 | 2015-12-22T00:50:43.000Z | 2017-01-07T18:09:36.000Z | apps/organization/migrations/0017_merge.py | SVArago/alexia | 96ae6dfabb893388bd4610ea971574a993b8029d | [
"BSD-3-Clause"
] | 24 | 2015-11-02T15:38:40.000Z | 2017-01-07T21:18:42.000Z | apps/organization/migrations/0017_merge.py | SVArago/alexia | 96ae6dfabb893388bd4610ea971574a993b8029d | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-11 19:00
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('organization', '0011_merge'),
('organization', '0016_merge'),
]
operations = [
]
| 18.941176 | 48 | 0.645963 | 37 | 322 | 5.432432 | 0.783784 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 0.223602 | 322 | 16 | 49 | 20.125 | 0.704 | 0.21118 | 0 | 0 | 1 | 0 | 0.175299 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.222222 | 0 | 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 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
bcb135fd17acb275088df3eac095e655af0416c1 | 3,283 | py | Python | romcomma/mogpflow/mean_functions.py | C-O-M-M-A/rom-comma | 2e4c5e200b3a3cc9a5c578c803575cf76445f2cf | [
"BSD-3-Clause"
] | 1 | 2021-06-08T16:01:09.000Z | 2021-06-08T16:01:09.000Z | romcomma/mogpflow/mean_functions.py | C-O-M-M-A/rom-comma | 2e4c5e200b3a3cc9a5c578c803575cf76445f2cf | [
"BSD-3-Clause"
] | null | null | null | romcomma/mogpflow/mean_functions.py | C-O-M-M-A/rom-comma | 2e4c5e200b3a3cc9a5c578c803575cf76445f2cf | [
"BSD-3-Clause"
] | 2 | 2021-07-05T11:58:05.000Z | 2021-11-06T17:35:11.000Z | # BSD 3-Clause License.
#
# Copyright (c) 2019-2021 Robert A. Milton. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Mean functions for mogpflow - i.e. Gaussian prior predictions."""
from __future__ import annotations
from typing import Sequence, Optional, Union
from gpflow.config import default_float
from gpflow.mean_functions import MeanFunction, Zero
import tensorflow as tf
class MOMeanFunction(MeanFunction):
""" Mean functions for MOGPR. Basically a wrapper for a Sequence of gpflow.mean_functions.MeanFunctions, one for each output_dim.
These functions constitute the prior mean predictions f(x) in the absence of any training data.
"""
@property
def output_dim(self):
""" Also known as L."""
return len(self._functions)
@property
def L(self):
return self.output_dim
@property
def functions(self):
""" The sequence of functions defining this MOMeanFunction."""
return self._functions
def __call__(self, X):
""" Given N datapoints in X, returns an output_dim * N vector of flatten(functions(X))."""
return tf.reshape(tf.concat([f(X) for f in self._functions], axis=0), [-1])
def __init__(self, output_dim: int, mean_functions: Union[MOMeanFunction, MeanFunction, Sequence[MeanFunction]] = Zero()):
"""
Args:
output_dim: The number of mean_functions required, also known as L.
mean_functions: Is broadcast to an L-Sequence of functions, giving the prior mean f(x) for each output_dim in turn.
"""
if isinstance(mean_functions, MOMeanFunction):
mean_functions = mean_functions.functions
elif isinstance(mean_functions, MeanFunction):
mean_functions = (mean_functions,) * output_dim
self._functions = mean_functions
| 49.742424 | 148 | 0.736521 | 449 | 3,283 | 5.302895 | 0.443207 | 0.076438 | 0.027719 | 0.01932 | 0.077278 | 0.057119 | 0.057119 | 0.057119 | 0.057119 | 0.057119 | 0 | 0.005323 | 0.198903 | 3,283 | 65 | 149 | 50.507692 | 0.9 | 0.660676 | 0 | 0.130435 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.217391 | false | 0 | 0.217391 | 0.043478 | 0.652174 | 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 |
bcb43e9b5d3b68b89e53bad3933456c3adcdc7da | 33,529 | py | Python | pysnmp/DAVID-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/DAVID-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/DAVID-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 DAVID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DAVID-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:21: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)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
DisplayString, = mibBuilder.importSymbols("RFC1155-SMI", "DisplayString")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, IpAddress, Integer32, iso, ModuleIdentity, Gauge32, Counter32, Bits, ObjectIdentity, MibIdentifier, TimeTicks, Counter64, Unsigned32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "IpAddress", "Integer32", "iso", "ModuleIdentity", "Gauge32", "Counter32", "Bits", "ObjectIdentity", "MibIdentifier", "TimeTicks", "Counter64", "Unsigned32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
david = MibIdentifier((1, 3, 6, 1, 4, 1, 66))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1))
davidExpressNet = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3))
exNetChassis = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 1))
exNetEthernet = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2))
exNetConcentrator = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1))
exNetModule = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2))
exNetPort = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3))
exNetMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4))
exNetChassisType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("other", 1), ("m6102", 2), ("m6103", 3), ("m6310tel", 4), ("m6310rj", 5), ("m6318st", 6), ("m6318sma", 7), ("reserved", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisType.setStatus('mandatory')
exNetChassisBkplType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("expressNet", 2), ("reserved", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisBkplType.setStatus('mandatory')
exNetChassisBkplRev = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisBkplRev.setStatus('mandatory')
exNetChassisPsType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("standardXfmr", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisPsType.setStatus('mandatory')
exNetChassisPsStatus = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("failed", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisPsStatus.setStatus('mandatory')
exNetSlotConfigTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7), )
if mibBuilder.loadTexts: exNetSlotConfigTable.setStatus('mandatory')
exNetSlotConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1), ).setIndexNames((0, "DAVID-MIB", "exNetSlotIndex"))
if mibBuilder.loadTexts: exNetSlotConfigEntry.setStatus('mandatory')
exNetSlotIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetSlotIndex.setStatus('mandatory')
exNetBoardId = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardId.setStatus('mandatory')
exNetBoardType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("empty", 1), ("other", 2), ("m6203", 3), ("m6201", 4), ("m6311", 5), ("m6312", 6), ("m6313st", 7), ("m6313sma", 8), ("m6006", 9), ("reserved", 10)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardType.setStatus('mandatory')
exNetBoardDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardDescr.setStatus('mandatory')
exNetBoardNumOfPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 40), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardNumOfPorts.setStatus('mandatory')
exNetChassisCapacity = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisCapacity.setStatus('mandatory')
exNetConcRetimingStatus = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcRetimingStatus.setStatus('mandatory')
exNetConcFrmsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFrmsRxOk.setStatus('mandatory')
exNetConcOctetsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcOctetsRxOk.setStatus('mandatory')
exNetConcMcastFrmsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcMcastFrmsRxOk.setStatus('mandatory')
exNetConcBcastFrmsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcBcastFrmsRxOk.setStatus('mandatory')
exNetConcColls = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcColls.setStatus('mandatory')
exNetConcTooLongErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcTooLongErrors.setStatus('mandatory')
exNetConcRuntErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcRuntErrors.setStatus('mandatory')
exNetConcFragErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFragErrors.setStatus('mandatory')
exNetConcAlignErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcAlignErrors.setStatus('mandatory')
exNetConcFcsErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFcsErrors.setStatus('mandatory')
exNetConcLateCollErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcLateCollErrors.setStatus('mandatory')
exNetConcName = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 40), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetConcName.setStatus('mandatory')
exNetConcJabbers = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcJabbers.setStatus('mandatory')
exNetConcSfdErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcSfdErrors.setStatus('mandatory')
exNetConcAutoPartitions = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcAutoPartitions.setStatus('mandatory')
exNetConcOosBitRate = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcOosBitRate.setStatus('mandatory')
exNetConcLinkErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcLinkErrors.setStatus('mandatory')
exNetConcFrameErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFrameErrors.setStatus('mandatory')
exNetConcNetUtilization = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 47), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 10))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcNetUtilization.setStatus('mandatory')
exNetConcResetTimeStamp = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 48), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcResetTimeStamp.setStatus('mandatory')
exNetConcReset = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noReset", 1), ("reset", 2), ("resetToDefault", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetConcReset.setStatus('mandatory')
exNetModuleTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1), )
if mibBuilder.loadTexts: exNetModuleTable.setStatus('mandatory')
exNetModuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1), ).setIndexNames((0, "DAVID-MIB", "exNetModuleIndex"))
if mibBuilder.loadTexts: exNetModuleEntry.setStatus('mandatory')
exNetModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleIndex.setStatus('mandatory')
exNetModuleType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("empty", 1), ("other", 2), ("m6203", 3), ("m6201", 4), ("m6311", 5), ("m6312", 6), ("m6313st", 7), ("m6313sma", 8), ("m6006", 9), ("reserved", 10)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleType.setStatus('mandatory')
exNetModuleHwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleHwVer.setStatus('mandatory')
exNetModuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("ok", 1), ("noComms", 2), ("selfTestFail", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleStatus.setStatus('mandatory')
exNetModuleReset = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noReset", 1), ("reset", 2), ("resetToDefault", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModuleReset.setStatus('mandatory')
exNetModulePartStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("partition", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModulePartStatus.setStatus('mandatory')
exNetModuleNmCntlStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notNmControl", 1), ("nmControl", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleNmCntlStatus.setStatus('mandatory')
exNetModulePsStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("fail", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModulePsStatus.setStatus('mandatory')
exNetModuleFrmsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFrmsRxOk.setStatus('mandatory')
exNetModuleOctetsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleOctetsRxOk.setStatus('mandatory')
exNetModuleColls = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleColls.setStatus('mandatory')
exNetModuleTooLongErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleTooLongErrors.setStatus('mandatory')
exNetModuleRuntErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleRuntErrors.setStatus('mandatory')
exNetModuleAlignErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleAlignErrors.setStatus('mandatory')
exNetModuleFcsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFcsErrors.setStatus('mandatory')
exNetModuleLateCollErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleLateCollErrors.setStatus('mandatory')
exNetModuleName = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 40), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModuleName.setStatus('mandatory')
exNetModuleJabbers = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleJabbers.setStatus('mandatory')
exNetModuleSfdErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleSfdErrors.setStatus('mandatory')
exNetModuleAutoPartitions = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleAutoPartitions.setStatus('mandatory')
exNetModuleOosBitRate = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleOosBitRate.setStatus('mandatory')
exNetModuleLinkErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleLinkErrors.setStatus('mandatory')
exNetModuleFrameErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFrameErrors.setStatus('mandatory')
exNetModuleFragErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 47), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFragErrors.setStatus('mandatory')
exNetModulePortConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 48), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModulePortConfig.setStatus('mandatory')
exNetModuleLinkStatConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 49), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModuleLinkStatConfig.setStatus('mandatory')
exNetModuleResetTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 50), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleResetTimeStamp.setStatus('mandatory')
exNetModuleLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 51), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleLinkStatus.setStatus('mandatory')
exNetModuleFwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 52), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFwVer.setStatus('mandatory')
exNetModuleFwFeaturePkg = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 53), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFwFeaturePkg.setStatus('mandatory')
exNetModuleSelfTestResult = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 54), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleSelfTestResult.setStatus('mandatory')
exNetPortTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1), )
if mibBuilder.loadTexts: exNetPortTable.setStatus('mandatory')
exNetPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1), ).setIndexNames((0, "DAVID-MIB", "exNetPortModuleIndex"), (0, "DAVID-MIB", "exNetPortIndex"))
if mibBuilder.loadTexts: exNetPortEntry.setStatus('mandatory')
exNetPortModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortModuleIndex.setStatus('mandatory')
exNetPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortIndex.setStatus('mandatory')
exNetPortLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("off", 1), ("on", 2), ("other", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortLinkStatus.setStatus('mandatory')
exNetPortPartStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("enabled", 1), ("partition", 2), ("autoPartition", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortPartStatus.setStatus('mandatory')
exNetPortJabberStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("jabbering", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortJabberStatus.setStatus('mandatory')
exNetPortFrmsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFrmsRxOk.setStatus('mandatory')
exNetPortOctetsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortOctetsRxOk.setStatus('mandatory')
exNetPortColls = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortColls.setStatus('mandatory')
exNetPortTooLongErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortTooLongErrors.setStatus('mandatory')
exNetPortRuntErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortRuntErrors.setStatus('mandatory')
exNetPortAlignErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortAlignErrors.setStatus('mandatory')
exNetPortFcsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFcsErrors.setStatus('mandatory')
exNetPortLateCollErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortLateCollErrors.setStatus('mandatory')
exNetPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 40), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortName.setStatus('mandatory')
exNetPortJabbers = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortJabbers.setStatus('mandatory')
exNetPortSfdErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortSfdErrors.setStatus('mandatory')
exNetPortAutoPartitions = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortAutoPartitions.setStatus('mandatory')
exNetPortOosBitRate = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortOosBitRate.setStatus('mandatory')
exNetPortLinkErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortLinkErrors.setStatus('mandatory')
exNetPortFrameErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFrameErrors.setStatus('mandatory')
exNetPortFragErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 47), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFragErrors.setStatus('mandatory')
exNetPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 48), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("repeater", 2), ("tenBasefAsync", 3), ("tenBasefSync", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortType.setStatus('mandatory')
exNetPortMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("other", 1), ("tenBase5", 2), ("tenBaseT", 3), ("fOIRL", 4), ("tenBase2", 5), ("tenBaseFA", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortMauType.setStatus('mandatory')
exNetPortConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("enabled", 2), ("disabled", 3), ("txDisabled", 4), ("rxDisabled", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortConfig.setStatus('mandatory')
exNetPortLinkStatConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 51), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("enabled", 2), ("disabled", 3), ("txDisabled", 4), ("rxDisabled", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortLinkStatConfig.setStatus('mandatory')
exNetPortPolarity = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 52), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("positive", 2), ("negative", 3), ("txNegative", 4), ("rxNegative", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortPolarity.setStatus('mandatory')
exNetPortTransmitTest = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 53), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortTransmitTest.setStatus('mandatory')
exNetMgmtType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("tbd", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtType.setStatus('mandatory')
exNetMgmtHwVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtHwVer.setStatus('mandatory')
exNetMgmtFwVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtFwVer.setStatus('mandatory')
exNetMgmtSwMajorVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtSwMajorVer.setStatus('mandatory')
exNetMgmtSwMinorVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtSwMinorVer.setStatus('mandatory')
exNetMgmtStatus = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtStatus.setStatus('mandatory')
exNetMgmtMode = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtMode.setStatus('mandatory')
exNetMgmtReset = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notReset", 1), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtReset.setStatus('mandatory')
exNetMgmtRestart = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notRestart", 1), ("restart", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtRestart.setStatus('mandatory')
exNetMgmtIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 10), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtIpAddr.setStatus('mandatory')
exNetMgmtNetMask = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 11), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtNetMask.setStatus('mandatory')
exNetMgmtDefaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 12), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtDefaultGateway.setStatus('mandatory')
exNetMgmtBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 17), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtBaudRate.setStatus('mandatory')
exNetMgmtLocation = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 19), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtLocation.setStatus('mandatory')
exNetMgmtTrapReceiverTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20), )
if mibBuilder.loadTexts: exNetMgmtTrapReceiverTable.setStatus('mandatory')
exNetMgmtTrapReceiverEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1), ).setIndexNames((0, "DAVID-MIB", "exNetMgmtTrapReceiverAddr"))
if mibBuilder.loadTexts: exNetMgmtTrapReceiverEntry.setStatus('mandatory')
exNetMgmtTrapType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2))).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtTrapType.setStatus('mandatory')
exNetMgmtTrapReceiverAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtTrapReceiverAddr.setStatus('mandatory')
exNetMgmtTrapReceiverComm = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(20, 20)).setFixedLength(20)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtTrapReceiverComm.setStatus('mandatory')
exNetMgmtAuthTrap = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtAuthTrap.setStatus('mandatory')
mibBuilder.exportSymbols("DAVID-MIB", exNetPortIndex=exNetPortIndex, exNetMgmtAuthTrap=exNetMgmtAuthTrap, exNetModuleOctetsRxOk=exNetModuleOctetsRxOk, exNetPortPartStatus=exNetPortPartStatus, exNetPortSfdErrors=exNetPortSfdErrors, exNetConcAlignErrors=exNetConcAlignErrors, exNetPortLinkErrors=exNetPortLinkErrors, exNetChassisCapacity=exNetChassisCapacity, exNetMgmtHwVer=exNetMgmtHwVer, exNetConcAutoPartitions=exNetConcAutoPartitions, exNetMgmtDefaultGateway=exNetMgmtDefaultGateway, exNetChassisBkplType=exNetChassisBkplType, exNetMgmt=exNetMgmt, exNetModuleRuntErrors=exNetModuleRuntErrors, exNetMgmtTrapReceiverTable=exNetMgmtTrapReceiverTable, exNetConcentrator=exNetConcentrator, exNetConcLinkErrors=exNetConcLinkErrors, exNetModuleSfdErrors=exNetModuleSfdErrors, exNetModuleFwVer=exNetModuleFwVer, exNetModulePortConfig=exNetModulePortConfig, exNetChassisPsStatus=exNetChassisPsStatus, exNetModuleEntry=exNetModuleEntry, exNetPortLateCollErrors=exNetPortLateCollErrors, exNetModuleNmCntlStatus=exNetModuleNmCntlStatus, exNetMgmtFwVer=exNetMgmtFwVer, exNetConcResetTimeStamp=exNetConcResetTimeStamp, exNetModuleSelfTestResult=exNetModuleSelfTestResult, exNetModule=exNetModule, exNetMgmtLocation=exNetMgmtLocation, exNetSlotIndex=exNetSlotIndex, exNetModuleAutoPartitions=exNetModuleAutoPartitions, exNetSlotConfigTable=exNetSlotConfigTable, exNetPortPolarity=exNetPortPolarity, exNetPortJabberStatus=exNetPortJabberStatus, exNetConcJabbers=exNetConcJabbers, exNetPortTable=exNetPortTable, exNetMgmtMode=exNetMgmtMode, exNetMgmtTrapReceiverComm=exNetMgmtTrapReceiverComm, exNetMgmtSwMajorVer=exNetMgmtSwMajorVer, exNetBoardId=exNetBoardId, exNetConcOctetsRxOk=exNetConcOctetsRxOk, exNetModuleStatus=exNetModuleStatus, exNetMgmtStatus=exNetMgmtStatus, exNetMgmtReset=exNetMgmtReset, exNetModuleHwVer=exNetModuleHwVer, exNetModuleIndex=exNetModuleIndex, davidExpressNet=davidExpressNet, exNetConcBcastFrmsRxOk=exNetConcBcastFrmsRxOk, exNetPortLinkStatus=exNetPortLinkStatus, exNetConcMcastFrmsRxOk=exNetConcMcastFrmsRxOk, exNetModuleType=exNetModuleType, exNetConcLateCollErrors=exNetConcLateCollErrors, exNetMgmtSwMinorVer=exNetMgmtSwMinorVer, exNetPortFrmsRxOk=exNetPortFrmsRxOk, exNetModuleFrmsRxOk=exNetModuleFrmsRxOk, exNetPortColls=exNetPortColls, exNetModuleName=exNetModuleName, exNetModuleLinkStatConfig=exNetModuleLinkStatConfig, exNetConcRetimingStatus=exNetConcRetimingStatus, exNetModuleColls=exNetModuleColls, exNetPortTooLongErrors=exNetPortTooLongErrors, exNetConcOosBitRate=exNetConcOosBitRate, exNetMgmtBaudRate=exNetMgmtBaudRate, exNetPortModuleIndex=exNetPortModuleIndex, exNetBoardNumOfPorts=exNetBoardNumOfPorts, exNetPortFrameErrors=exNetPortFrameErrors, exNetConcSfdErrors=exNetConcSfdErrors, exNetMgmtTrapReceiverAddr=exNetMgmtTrapReceiverAddr, exNetModuleFragErrors=exNetModuleFragErrors, exNetChassisPsType=exNetChassisPsType, exNetBoardDescr=exNetBoardDescr, exNetPortEntry=exNetPortEntry, exNetModuleLateCollErrors=exNetModuleLateCollErrors, exNetPortMauType=exNetPortMauType, exNetConcReset=exNetConcReset, exNetModuleTable=exNetModuleTable, david=david, exNetModuleTooLongErrors=exNetModuleTooLongErrors, exNetSlotConfigEntry=exNetSlotConfigEntry, exNetModulePsStatus=exNetModulePsStatus, exNetModuleFwFeaturePkg=exNetModuleFwFeaturePkg, exNetConcFrameErrors=exNetConcFrameErrors, exNetPortOosBitRate=exNetPortOosBitRate, exNetConcFragErrors=exNetConcFragErrors, exNetConcTooLongErrors=exNetConcTooLongErrors, exNetModuleLinkStatus=exNetModuleLinkStatus, exNetChassisType=exNetChassisType, exNetModuleResetTimeStamp=exNetModuleResetTimeStamp, exNetPortAlignErrors=exNetPortAlignErrors, exNetPortFcsErrors=exNetPortFcsErrors, exNetBoardType=exNetBoardType, exNetEthernet=exNetEthernet, exNetPortType=exNetPortType, exNetConcRuntErrors=exNetConcRuntErrors, exNetConcColls=exNetConcColls, exNetConcFrmsRxOk=exNetConcFrmsRxOk, exNetModulePartStatus=exNetModulePartStatus, exNetPortName=exNetPortName, exNetPortTransmitTest=exNetPortTransmitTest, exNetPortJabbers=exNetPortJabbers, exNetMgmtIpAddr=exNetMgmtIpAddr, exNetPortConfig=exNetPortConfig, exNetModuleJabbers=exNetModuleJabbers, exNetPortLinkStatConfig=exNetPortLinkStatConfig, exNetMgmtNetMask=exNetMgmtNetMask, exNetPortOctetsRxOk=exNetPortOctetsRxOk, exNetModuleOosBitRate=exNetModuleOosBitRate, exNetModuleReset=exNetModuleReset, exNetModuleFrameErrors=exNetModuleFrameErrors, exNetPortAutoPartitions=exNetPortAutoPartitions, exNetModuleFcsErrors=exNetModuleFcsErrors, exNetMgmtTrapType=exNetMgmtTrapType, exNetChassis=exNetChassis, exNetConcName=exNetConcName, products=products, exNetModuleLinkErrors=exNetModuleLinkErrors, exNetModuleAlignErrors=exNetModuleAlignErrors, exNetMgmtType=exNetMgmtType, exNetConcFcsErrors=exNetConcFcsErrors, exNetMgmtTrapReceiverEntry=exNetMgmtTrapReceiverEntry, exNetPortFragErrors=exNetPortFragErrors, exNetPort=exNetPort, exNetMgmtRestart=exNetMgmtRestart, exNetConcNetUtilization=exNetConcNetUtilization, exNetChassisBkplRev=exNetChassisBkplRev, exNetPortRuntErrors=exNetPortRuntErrors)
| 129.455598 | 5,017 | 0.752185 | 3,873 | 33,529 | 6.511748 | 0.081332 | 0.020301 | 0.014988 | 0.019984 | 0.492308 | 0.466812 | 0.380174 | 0.374148 | 0.32839 | 0.275337 | 0 | 0.078064 | 0.084971 | 33,529 | 258 | 5,018 | 129.957364 | 0.74397 | 0.009305 | 0 | 0 | 0 | 0 | 0.09844 | 0.002078 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.027888 | 0 | 0.027888 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bcc2aade9ea83649520c64810e09e87b3fbcfdfb | 273 | py | Python | documents/error_calculate/error_calculate.py | fe1t/wifi_positioning | a4059704ed66404b9c2f143b07b5c02fdb69c8a7 | [
"MIT"
] | 2 | 2017-12-20T14:01:01.000Z | 2021-12-29T08:31:44.000Z | documents/error_calculate/error_calculate.py | fe1t/wifi_positioning | a4059704ed66404b9c2f143b07b5c02fdb69c8a7 | [
"MIT"
] | null | null | null | documents/error_calculate/error_calculate.py | fe1t/wifi_positioning | a4059704ed66404b9c2f143b07b5c02fdb69c8a7 | [
"MIT"
] | null | null | null |
import math
with open("error_collection") as f:
data = eval(f.read())
def find_erdst(x1, y1, x2, y2):
return math.sqrt( (x1-x2)**2 + (y1 - y2) ** 2)
error_distance = 0
for i in data:
error_distance += find_erdst(*i)
print float(error_distance) / len(data)
| 18.2 | 50 | 0.644689 | 46 | 273 | 3.695652 | 0.630435 | 0.229412 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.050228 | 0.197802 | 273 | 14 | 51 | 19.5 | 0.726027 | 0 | 0 | 0 | 0 | 0 | 0.058824 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.111111 | null | null | 0.111111 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bcc36e7cdd3a9e6085424429b5fb4d4950ab10ef | 1,414 | py | Python | cooking_dl.py | ilvar/coursera_cooking_dl | 31ab3ed551d087ad0b03df52d4949f09587dee15 | [
"MIT"
] | null | null | null | cooking_dl.py | ilvar/coursera_cooking_dl | 31ab3ed551d087ad0b03df52d4949f09587dee15 | [
"MIT"
] | null | null | null | cooking_dl.py | ilvar/coursera_cooking_dl | 31ab3ed551d087ad0b03df52d4949f09587dee15 | [
"MIT"
] | null | null | null | import netrc
import os
import selenium.webdriver
import wget
rc = netrc.netrc()
user, host, password = rc.hosts['coursera-dl']
try:
os.makedirs(os.path.join('.', 'videos'))
except OSError:
pass
browser = selenium.webdriver.Firefox()
browser.implicitly_wait(10)
try:
browser.get('https://www.coursera.org/learn/childnutrition/outline')
browser.find_element_by_link_text('Log In').click()
browser.find_element_by_css_selector('div[data-state="login"] #user-modal-email').send_keys(user)
browser.find_element_by_css_selector('div[data-state="login"] #user-modal-password').send_keys(password)
browser.find_element_by_css_selector('div[data-state="login"] button[data-js="submit"]').click()
browser.find_element_by_id('coursera-header-account-popup')
links = browser.find_elements_by_css_selector('a[href*="learn/childnutrition/lecture"]')
links = [a.get_attribute('href') for a in links]
for i, l in enumerate(links):
print 'Processing', l
browser.get(l)
video = browser.find_element_by_tag_name('video')
video_url = video.get_attribute('src')
fname = '%05d_%s.mp4' % (i + 1, os.path.basename(l))
fpath = os.path.join('.', 'videos', fname)
if not os.path.exists(fpath):
print 'Saving to %s' % fname
wget.download(video_url, out=fpath)
print ''
finally:
browser.quit()
| 32.136364 | 108 | 0.681047 | 196 | 1,414 | 4.734694 | 0.464286 | 0.082974 | 0.116379 | 0.12931 | 0.206897 | 0.174569 | 0.174569 | 0.174569 | 0.174569 | 0.174569 | 0 | 0.005106 | 0.169024 | 1,414 | 43 | 109 | 32.883721 | 0.784681 | 0 | 0 | 0.058824 | 0 | 0 | 0.23338 | 0.113861 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.088235 | 0.117647 | null | null | 0.088235 | 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 |
bcc91f3666662e9b6a5c9d87f7ed3c4635394635 | 7,142 | py | Python | securetea/args/arguments.py | jay13patel/SecureTea-Project | 73686512bd3633809bb3e83948d3d4ea45cc0218 | [
"MIT"
] | 1 | 2019-03-26T11:01:03.000Z | 2019-03-26T11:01:03.000Z | securetea/args/arguments.py | jay13patel/SecureTea-Project | 73686512bd3633809bb3e83948d3d4ea45cc0218 | [
"MIT"
] | null | null | null | securetea/args/arguments.py | jay13patel/SecureTea-Project | 73686512bd3633809bb3e83948d3d4ea45cc0218 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
u"""Arguments module for SecureTea.
Project:
╔═╗┌─┐┌─┐┬ ┬┬─┐┌─┐╔╦╗┌─┐┌─┐
╚═╗├┤ │ │ │├┬┘├┤ ║ ├┤ ├─┤
╚═╝└─┘└─┘└─┘┴└─└─┘ ╩ └─┘┴ ┴
Author: Rejah Rehim <rejah@appfabs.com> , Aug 31 2018
Version: 1.1
Module: SecureTea
"""
import argparse
def get_args():
"""Docstring.
Returns:
Args: total arguments
"""
parser = argparse.ArgumentParser(description='Arguments of SecureTea')
parser.add_argument(
'--conf',
type=str,
required=False,
help='Path of config file. default:- "~/.securetea/securetea.conf" '
)
parser.add_argument(
'--debug',
default=False,
action="store_true",
help='Degug true or false'
)
parser.add_argument(
'--twitter',
required=False,
action='store_true',
help='Setup twitter credentials'
)
parser.add_argument(
'--twilio_sms',
required=False,
action='store_true',
help='Setup twilio SMS credentials'
)
parser.add_argument(
'--telegram',
required=False,
action='store_true',
help='Setup telegram SMS credentials'
)
parser.add_argument(
'--slack',
required=False,
action='store_true',
help='Setup Slack credentials'
)
parser.add_argument(
'--aws_ses',
required=False,
action='store_true',
help='Setup AWS SES credentials'
)
parser.add_argument(
'--twitter_api_key',
'-tak',
type=str,
required=False,
help='Twitter api key'
)
parser.add_argument(
'--twitter_api_secret_key',
'-tas',
type=str,
required=False,
help='Twitter api secret'
)
parser.add_argument(
'--twitter_access_token',
'-tat',
type=str,
required=False,
help='Twitter access token'
)
parser.add_argument(
'--twitter_access_token_secret',
'-tats',
type=str,
required=False,
help='Twitter access token secret'
)
parser.add_argument(
'--telegram_bot_token',
'-tbt',
type=str,
required=False,
help='Telegram Bot Token'
)
parser.add_argument(
'--telegram_user_id',
'-tui',
type=str,
required=False,
help='Telegram user id'
)
parser.add_argument(
'--twilio_sid',
'-tws',
type=str,
required=False,
help='Twilio SID'
)
parser.add_argument(
'--twilio_token',
'-twt',
type=str,
required=False,
help='Twilio authorization token'
)
parser.add_argument(
'--twilio_from',
'-twf',
type=str,
required=False,
help='Twilio (From) phone number'
)
parser.add_argument(
'--twilio_to',
'-twto',
type=str,
required=False,
help='Twilio (To) phone number'
)
parser.add_argument(
'--slack_token',
'-st',
type=str,
required=False,
help='Slack token'
)
parser.add_argument(
'--slack_user_id',
'-suid',
type=str,
required=False,
help='Slack user id'
)
parser.add_argument(
'--aws_email',
'-awse',
type=str,
required=False,
help='AWS email id'
)
parser.add_argument(
'--aws_secret_key',
'-awss',
type=str,
required=False,
help='AWS secret key'
)
parser.add_argument(
'--aws_access_key',
'-awsa',
type=str,
required=False,
help='AWS access key'
)
parser.add_argument(
'--firewall',
'-f',
required=False,
action='store_true',
help='Start firewall'
)
parser.add_argument(
'--interface',
required=False,
help='Name of the interface'
)
parser.add_argument(
'--inbound_IP_action',
type=str,
required=False,
help='Inbound IP rule action'
)
parser.add_argument(
'--inbound_IP_list',
type=str,
required=False,
help='List of inbound IPs to look for'
)
parser.add_argument(
'--outbound_IP_action',
type=str,
required=False,
help='Outbound IP rule action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--outbound_IP_list',
type=str,
required=False,
help='List of outbound IPs to look for'
)
parser.add_argument(
'--protocol_action',
type=str,
required=False,
help='Protocol action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--protocol_list',
type=str,
required=False,
help='List of protocols to look for'
)
parser.add_argument(
'--scan_action',
type=str,
required=False,
help='Scan load action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--scan_list',
type=str,
required=False,
help='List of extensions to scan for'
)
parser.add_argument(
'--dest_port_action',
type=str,
required=False,
help='Destination port action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--dest_port_list',
type=str,
required=False,
help='List of destination ports to look for'
)
parser.add_argument(
'--source_port_action',
type=str,
required=False,
help='Source port action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--source_port_list',
type=str,
required=False,
help='List of source ports to look for'
)
parser.add_argument(
'--HTTP_request_action',
type=str,
required=False,
help='HTTP request action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--HTTP_response_action',
type=str,
required=False,
help='HTTP response action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--dns_action',
type=str,
required=False,
help='DNS action (0: BLOCK, 1: ALLOW)'
)
parser.add_argument(
'--dns_list',
type=str,
required=False,
help='List of DNS to look for'
)
parser.add_argument(
'--time_lb',
type=str,
required=False,
help='Time lower bound'
)
parser.add_argument(
'--time_ub',
type=str,
required=False,
help='Time upper bound'
)
parser.add_argument(
'--insecure_headers',
'-ih',
action="store_true",
required=False,
help="Test URL for insecure headers"
)
parser.add_argument(
'--url',
'-u',
type=str,
required=False,
help="URL on which operations are to be performed"
)
args = parser.parse_args()
return args
| 20.347578 | 76 | 0.521143 | 742 | 7,142 | 4.959569 | 0.200809 | 0.107609 | 0.203261 | 0.190217 | 0.608696 | 0.495652 | 0.326359 | 0.170652 | 0.082065 | 0 | 0 | 0.005388 | 0.350322 | 7,142 | 350 | 77 | 20.405714 | 0.772845 | 0.042705 | 0 | 0.452962 | 0 | 0 | 0.290119 | 0.021583 | 0 | 0 | 0 | 0 | 0 | 1 | 0.003484 | false | 0 | 0.003484 | 0 | 0.010453 | 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 |
bccfcffbb39fca37f60ccc443b121849785ebf24 | 88 | py | Python | chapter10/examples/file_examples/with_file.py | YordanIH/Intro_to_CS_w_Python | eebbb8efd7ef0d07be9bc45b6b1e8f20737ce01a | [
"MIT"
] | null | null | null | chapter10/examples/file_examples/with_file.py | YordanIH/Intro_to_CS_w_Python | eebbb8efd7ef0d07be9bc45b6b1e8f20737ce01a | [
"MIT"
] | null | null | null | chapter10/examples/file_examples/with_file.py | YordanIH/Intro_to_CS_w_Python | eebbb8efd7ef0d07be9bc45b6b1e8f20737ce01a | [
"MIT"
] | null | null | null | with open('file_example.txt', 'r') as file:
contents = file.read()
print(contents)
| 17.6 | 43 | 0.670455 | 13 | 88 | 4.461538 | 0.769231 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.159091 | 88 | 4 | 44 | 22 | 0.783784 | 0 | 0 | 0 | 0 | 0 | 0.193182 | 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 |
bce9d13708c55bad3aa02aa3011288d4cd4b2fed | 3,906 | py | Python | tests/test_app.py | eliksir/Flask-RQ2 | e90a624d5429539e2c91243d2d1d11b435b375ad | [
"MIT"
] | 160 | 2018-02-06T15:18:20.000Z | 2022-03-31T09:39:31.000Z | tests/test_app.py | eliksir/Flask-RQ2 | e90a624d5429539e2c91243d2d1d11b435b375ad | [
"MIT"
] | 62 | 2018-02-05T11:23:13.000Z | 2022-02-19T16:34:58.000Z | tests/test_app.py | eliksir/Flask-RQ2 | e90a624d5429539e2c91243d2d1d11b435b375ad | [
"MIT"
] | 33 | 2018-03-02T01:26:18.000Z | 2022-02-05T09:07:58.000Z | # -*- coding: utf-8 -*-
from redis import StrictRedis
from rq.queue import Queue
from rq.utils import import_attribute
from rq.worker import Worker
from rq_scheduler import Scheduler
import pytest
from flask_rq2 import RQ
def exception_handler(*args, **kwargs):
pass
def test_init_app(app, config):
rq = RQ()
assert 'rq2' not in getattr(app, 'extensions', {})
assert getattr(rq, 'module', None) is None
rq.init_app(app)
assert rq.redis_url == config.RQ_REDIS_URL
assert isinstance(rq.connection, StrictRedis)
assert 'rq2' in getattr(app, 'extensions', {})
def test_rq_outside_flask():
rq = RQ()
assert pytest.raises(RuntimeError, lambda: rq.connection)
def test_config_redis(config, rq):
assert rq.redis_url == config.RQ_REDIS_URL
assert isinstance(rq.connection, StrictRedis)
def test_config_queues(config, rq):
assert rq.queues == config.RQ_QUEUES
def test_config_async(app, config, rq):
assert rq._is_async == config.RQ_ASYNC
def test_config_async_override(app, config, rq):
rq2 = RQ(app, is_async=not config.RQ_ASYNC)
assert rq2._is_async != config.RQ_ASYNC
def test_config_default_timeout(app, config):
rq3 = RQ(app, default_timeout=911)
assert rq3.default_timeout != Queue.DEFAULT_TIMEOUT
assert rq3.default_timeout == 911
def test_config_scheduler_interval(config, rq):
rq.scheduler_interval == config.RQ_SCHEDULER_INTERVAL
def test_config_scheduler_queue(config, rq):
rq.scheduler_queue = config.RQ_SCHEDULER_QUEUE
def test_exception_handler(rq):
rq.exception_handler(exception_handler)
assert 'test_app.exception_handler' in rq._exception_handlers
def test_get_worker(rq):
worker = rq.get_worker()
assert isinstance(worker, Worker)
assert [queue.name for queue in worker.queues] == rq.queues
def test_get_worker_with_queues(rq):
worker = rq.get_worker('some-queue')
assert isinstance(worker, Worker)
queue_names = [queue.name for queue in worker.queues]
assert queue_names != rq.queues
assert 'some-queue' in queue_names
def test_get_worker_with_exception_handlers(rq):
rq.exception_handler(exception_handler)
worker = rq.get_worker()
assert exception_handler in worker._exc_handlers
def test_get_queue(rq):
assert rq._queue_instances == {}
queue = rq.get_queue()
assert rq._queue_instances != {}
assert queue in rq._queue_instances.values()
assert isinstance(queue, Queue)
assert isinstance(queue, import_attribute(rq.queue_class))
assert queue.name == rq.default_queue
assert queue._default_timeout == rq.default_timeout
assert queue._is_async == rq._is_async
assert queue.connection == rq.connection
def test_get_queue_with_name(rq):
queue = rq.get_queue('some-queue')
assert queue.name == 'some-queue'
assert queue.name in rq._queue_instances
name2 = 'some-other-queue'
assert name2 not in rq._queue_instances
queue2 = rq.get_queue(name2)
assert queue2.name == name2
assert name2 in rq._queue_instances
def test_get_scheduler(rq):
scheduler = rq.get_scheduler()
assert isinstance(scheduler, Scheduler)
assert isinstance(scheduler, import_attribute(rq.scheduler_class))
assert scheduler.queue_name == rq.scheduler_queue
assert scheduler._interval == rq.scheduler_interval
assert scheduler.connection == rq.connection
def test_get_scheduler_interval(rq):
scheduler = rq.get_scheduler(interval=23)
assert scheduler._interval != rq.scheduler_interval
assert scheduler._interval == 23
def test_get_scheduler_queue(rq):
scheduler = rq.get_scheduler(queue='other')
assert scheduler.queue_name == 'other'
def test_get_scheduler_importerror(rq):
# in case scheduler can't be imported
rq.scheduler_class = 'non.existing.Scheduler'
with pytest.raises(ImportError):
rq.get_scheduler()
| 27.125 | 70 | 0.740143 | 541 | 3,906 | 5.085028 | 0.133087 | 0.048346 | 0.032715 | 0.026172 | 0.272628 | 0.189022 | 0.139586 | 0.117048 | 0.051618 | 0.051618 | 0 | 0.007983 | 0.166155 | 3,906 | 143 | 71 | 27.314685 | 0.83666 | 0.014593 | 0 | 0.129032 | 0 | 0 | 0.037962 | 0.012481 | 0 | 0 | 0 | 0 | 0.451613 | 1 | 0.215054 | false | 0.010753 | 0.11828 | 0 | 0.333333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bcedf0f2d815f1f2aee3c13ec37a18efe1beeae6 | 258 | py | Python | winregistry/__init__.py | michael-rolfe/winregistry | f3f2cfcb794a0482283ce7c96d03b13f665c3695 | [
"MIT"
] | 18 | 2017-04-04T04:19:13.000Z | 2022-01-11T09:16:52.000Z | winregistry/__init__.py | michael-rolfe/winregistry | f3f2cfcb794a0482283ce7c96d03b13f665c3695 | [
"MIT"
] | 6 | 2017-09-21T21:14:05.000Z | 2022-03-30T11:35:24.000Z | winregistry/__init__.py | michael-rolfe/winregistry | f3f2cfcb794a0482283ce7c96d03b13f665c3695 | [
"MIT"
] | 4 | 2019-03-21T08:24:09.000Z | 2021-10-13T10:49:22.000Z | from winregistry.consts import ShortRootAlias, WinregType
from winregistry.models import RegEntry, RegKey
from winregistry.winregistry import WinRegistry
__all__ = (
"WinRegistry",
"RegEntry",
"RegKey",
"WinregType",
"ShortRootAlias",
)
| 21.5 | 57 | 0.74031 | 23 | 258 | 8.130435 | 0.434783 | 0.240642 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.170543 | 258 | 11 | 58 | 23.454545 | 0.873832 | 0 | 0 | 0 | 0 | 0 | 0.189922 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.3 | 0 | 0.3 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
bcfab6b007439fd9ae2c247f08fd70da16c4508b | 1,613 | py | Python | lambda/custom/core/interceptors/logger_interceptors.py | Antoninj/stib-alexa-skill | bb6335fe9ac37f7fd0630d51a514071143467ecb | [
"Apache-2.0"
] | 1 | 2020-05-15T19:42:52.000Z | 2020-05-15T19:42:52.000Z | lambda/custom/core/interceptors/logger_interceptors.py | Antoninj/stib-alexa-skill | bb6335fe9ac37f7fd0630d51a514071143467ecb | [
"Apache-2.0"
] | 127 | 2020-05-18T05:48:27.000Z | 2022-03-01T04:12:44.000Z | lambda/custom/core/interceptors/logger_interceptors.py | Antoninj/stib-alexa-skill | bb6335fe9ac37f7fd0630d51a514071143467ecb | [
"Apache-2.0"
] | 1 | 2020-08-27T10:17:41.000Z | 2020-08-27T10:17:41.000Z | # Copyright 2020 Antonin Jousson
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file 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 ask_sdk_core.dispatch_components import (AbstractRequestInterceptor,
AbstractResponseInterceptor)
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
from aws_lambda_powertools.logging import Logger
from aws_lambda_powertools.tracing import Tracer
# Logging/tracing configuration
logger = Logger(service="Logger interceptor")
tracer = Tracer(service="Logger interceptor")
class RequestLoggerInterceptor(AbstractRequestInterceptor):
"""Request Interceptor for logging purposes."""
def process(self, handler_input):
"""Log the request envelope."""
# type: (HandlerInput) -> None
logger.debug({"Request Envelope": handler_input.request_envelope})
class ResponseLoggerInterceptor(AbstractResponseInterceptor):
"""Response Interceptor for logging purposes."""
def process(self, handler_input, response):
"""Log the response envelope."""
# type: (HandlerInput, Response) -> None
logger.debug({"Response": response})
| 35.844444 | 74 | 0.733416 | 188 | 1,613 | 6.207447 | 0.489362 | 0.051414 | 0.025707 | 0.023993 | 0.094259 | 0.094259 | 0.094259 | 0.094259 | 0.094259 | 0 | 0 | 0.006079 | 0.184129 | 1,613 | 44 | 75 | 36.659091 | 0.880699 | 0.466832 | 0 | 0 | 0 | 0 | 0.072816 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.357143 | 0 | 0.642857 | 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 |
bcfea4dd69268c2de2af8fbd371a1fc8ba6ee819 | 1,506 | py | Python | rankings/migrations/0033_auto_20190505_1042.py | rubenvanerk/lifesavingrankings | 7d3ed8d5011d9de16e4dd8bffe89faa506041350 | [
"MIT"
] | 5 | 2018-06-04T05:12:18.000Z | 2021-01-24T13:37:41.000Z | rankings/migrations/0033_auto_20190505_1042.py | rubenvanerk/lifesavingrankings | 7d3ed8d5011d9de16e4dd8bffe89faa506041350 | [
"MIT"
] | 39 | 2019-12-07T16:07:05.000Z | 2021-05-09T10:57:48.000Z | rankings/migrations/0033_auto_20190505_1042.py | rubenvanerk/lifesavingrankings | 7d3ed8d5011d9de16e4dd8bffe89faa506041350 | [
"MIT"
] | null | null | null | # Generated by Django 2.1.5 on 2019-05-05 08:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rankings', '0032_individualresult_round'),
]
operations = [
migrations.AlterModelOptions(
name='individualresult',
options={'ordering': ['time']},
),
migrations.AlterField(
model_name='athlete',
name='first_name',
field=models.CharField(blank=True, default=None, max_length=20, null=True),
),
migrations.AlterField(
model_name='athlete',
name='last_name',
field=models.CharField(blank=True, default=None, max_length=30, null=True),
),
migrations.AlterField(
model_name='athlete',
name='nationalities',
field=models.ManyToManyField(blank=True, default=None, related_name='nationalities', to='rankings.Nationality'),
),
migrations.AlterField(
model_name='athlete',
name='year_of_birth',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='individualresult',
name='extra_analysis_time_by',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| 33.466667 | 147 | 0.61421 | 152 | 1,506 | 5.953947 | 0.421053 | 0.110497 | 0.138122 | 0.160221 | 0.352486 | 0.352486 | 0.223204 | 0.223204 | 0.117127 | 0.117127 | 0 | 0.020871 | 0.26826 | 1,506 | 44 | 148 | 34.227273 | 0.800363 | 0.02988 | 0 | 0.394737 | 1 | 0 | 0.141878 | 0.033585 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.078947 | 0 | 0.157895 | 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 |
4c14e411a1e09ca88b97eac85b5439f49ef56afb | 368 | py | Python | src/bci4als/__init__.py | Chgabri2/bci4als | cfa8bfb6190389e473100cc37281c304b6a3bc4a | [
"MIT"
] | 3 | 2021-12-15T09:57:51.000Z | 2022-01-26T09:52:39.000Z | src/bci4als/__init__.py | Chgabri2/bci4als | cfa8bfb6190389e473100cc37281c304b6a3bc4a | [
"MIT"
] | 3 | 2020-12-25T14:50:44.000Z | 2021-03-16T14:08:34.000Z | src/bci4als/__init__.py | Chgabri2/bci4als | cfa8bfb6190389e473100cc37281c304b6a3bc4a | [
"MIT"
] | 6 | 2021-11-10T19:43:26.000Z | 2021-12-23T18:02:57.000Z | """Top-level package for BCI-4-ALS."""
import importlib_metadata
__author__ = """Evyatar Luvaton, Noam Siegel"""
__email__ = 'noamsi@post.bgu.ac.il'
__version__ = importlib_metadata.version('bci4als')
from bci4als.experiments.offline import OfflineExperiment
from bci4als.experiments.online import OnlineExperiment
from .eeg import EEG
from .ml_model import MLModel
| 30.666667 | 57 | 0.80163 | 47 | 368 | 5.957447 | 0.702128 | 0.121429 | 0.157143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012048 | 0.097826 | 368 | 11 | 58 | 33.454545 | 0.831325 | 0.086957 | 0 | 0 | 0 | 0 | 0.169697 | 0.063636 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.75 | 0 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
4c3616d754ebfd2e7013ed646a2882a86d60cdfb | 3,154 | py | Python | ooobuild/lo/sheet/x_sheet_auditing.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/lo/sheet/x_sheet_auditing.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/lo/sheet/x_sheet_auditing.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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.
#
# Interface Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.sheet
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from ..table.cell_address import CellAddress as CellAddress_ae5f0b56
class XSheetAuditing(XInterface_8f010a43):
"""
provides methods to access auditing (detective) features in a spreadsheet.
See Also:
`API XSheetAuditing <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1sheet_1_1XSheetAuditing.html>`_
"""
__ooo_ns__: str = 'com.sun.star.sheet'
__ooo_full_ns__: str = 'com.sun.star.sheet.XSheetAuditing'
__ooo_type_name__: str = 'interface'
__pyunointerface__: str = 'com.sun.star.sheet.XSheetAuditing'
@abstractmethod
def clearArrows(self) -> None:
"""
removes all auditing arrows from the spreadsheet.
"""
@abstractmethod
def hideDependents(self, aPosition: 'CellAddress_ae5f0b56') -> bool:
"""
removes arrows for one level of dependents of a formula cell.
If the method is executed again for the same cell, the previous level of dependent cells is removed.
"""
@abstractmethod
def hidePrecedents(self, aPosition: 'CellAddress_ae5f0b56') -> bool:
"""
removes arrows for one level of precedents of a formula cell.
If the method is executed again for the same cell, the previous level of dependent cells is removed.
"""
@abstractmethod
def showDependents(self, aPosition: 'CellAddress_ae5f0b56') -> bool:
"""
draws arrows between a formula cell and its dependents.
If the method is executed again for the same cell, the next level of dependent cells is marked.
"""
@abstractmethod
def showErrors(self, aPosition: 'CellAddress_ae5f0b56') -> bool:
"""
draws arrows between a formula cell containing an error and the cells causing the error.
"""
@abstractmethod
def showInvalid(self) -> bool:
"""
marks all cells containing invalid values.
"""
@abstractmethod
def showPrecedents(self, aPosition: 'CellAddress_ae5f0b56') -> bool:
"""
draws arrows between a formula cell and its precedents.
If the method is executed again for the same cell, the next level of dependent cells is marked.
"""
__all__ = ['XSheetAuditing']
| 37.105882 | 132 | 0.693722 | 399 | 3,154 | 5.370927 | 0.41604 | 0.05553 | 0.055996 | 0.074662 | 0.371442 | 0.371442 | 0.331311 | 0.331311 | 0.331311 | 0.331311 | 0 | 0.022643 | 0.229867 | 3,154 | 84 | 133 | 37.547619 | 0.859613 | 0.548827 | 0 | 0.28 | 0 | 0 | 0.179376 | 0.057192 | 0 | 0 | 0 | 0 | 0 | 1 | 0.28 | false | 0 | 0.16 | 0 | 0.64 | 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 |
4c548f08a22c9f738e8832ce62e66653a4a2e6e6 | 12,736 | py | Python | tests/plugins/test_excel.py | hbruch/frictionless-py | 0f97d33c8fea7ef60cf8458b72eb0f54f4649798 | [
"MIT"
] | null | null | null | tests/plugins/test_excel.py | hbruch/frictionless-py | 0f97d33c8fea7ef60cf8458b72eb0f54f4649798 | [
"MIT"
] | null | null | null | tests/plugins/test_excel.py | hbruch/frictionless-py | 0f97d33c8fea7ef60cf8458b72eb0f54f4649798 | [
"MIT"
] | null | null | null | import io
import pytest
from decimal import Decimal
from datetime import datetime
from frictionless import Resource, Layout, FrictionlessException, helpers
from frictionless.plugins.excel import ExcelDialect
BASE_URL = "https://raw.githubusercontent.com/frictionlessdata/tabulator-py/master/%s"
# Read
def test_xlsx_parser_table():
source = io.open("data/table.xlsx", mode="rb")
with Resource(source, format="xlsx") as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1.0, "name": "english"},
{"id": 2.0, "name": "中国人"},
]
@pytest.mark.vcr
def test_xlsx_parser_remote():
source = BASE_URL % "data/table.xlsx"
with Resource(source) as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1.0, "name": "english"},
{"id": 2.0, "name": "中国人"},
]
def test_xlsx_parser_sheet_by_index():
source = "data/sheet2.xlsx"
dialect = ExcelDialect(sheet=2)
with Resource(source, dialect=dialect) as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1.0, "name": "english"},
{"id": 2.0, "name": "中国人"},
]
@pytest.mark.skip
def test_xlsx_parser_format_error_sheet_by_index_not_existent():
source = "data/sheet2.xlsx"
dialect = ExcelDialect(sheet=3)
resource = Resource(source, dialect=dialect)
with pytest.raises(FrictionlessException) as excinfo:
resource.open()
error = excinfo.value.error
assert error.code == "format-error"
assert error.note == 'Excel document "data/sheet2.xlsx" does not have a sheet "3"'
def test_xlsx_parser_sheet_by_name():
source = "data/sheet2.xlsx"
dialect = ExcelDialect(sheet="Sheet2")
with Resource(source, dialect=dialect) as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1.0, "name": "english"},
{"id": 2.0, "name": "中国人"},
]
@pytest.mark.skip
def test_xlsx_parser_format_errors_sheet_by_name_not_existent():
source = "data/sheet2.xlsx"
dialect = ExcelDialect(sheet="bad")
resource = Resource(source, dialect=dialect)
with pytest.raises(FrictionlessException) as excinfo:
resource.open()
error = excinfo.value.error
assert error.code == "format-error"
assert error.note == 'Excel document "data/sheet2.xlsx" does not have a sheet "bad"'
def test_xlsx_parser_merged_cells():
source = "data/merged-cells.xlsx"
layout = Layout(header=False)
with Resource(source, layout=layout) as resource:
assert resource.read_rows() == [
{"field1": "data", "field2": None},
]
def test_xlsx_parser_merged_cells_fill():
source = "data/merged-cells.xlsx"
dialect = ExcelDialect(fill_merged_cells=True)
layout = Layout(header=False)
with Resource(source, dialect=dialect, layout=layout) as resource:
assert resource.read_rows() == [
{"field1": "data", "field2": "data"},
{"field1": "data", "field2": "data"},
{"field1": "data", "field2": "data"},
]
def test_xlsx_parser_adjust_floating_point_error():
source = "data/adjust-floating-point-error.xlsx"
dialect = ExcelDialect(
fill_merged_cells=False,
preserve_formatting=True,
adjust_floating_point_error=True,
)
layout = Layout(skip_fields=["<blank>"])
with pytest.warns(UserWarning):
with Resource(source, dialect=dialect, layout=layout) as resource:
assert resource.read_rows()[1].cells[2] == 274.66
def test_xlsx_parser_adjust_floating_point_error_default():
source = "data/adjust-floating-point-error.xlsx"
dialect = ExcelDialect(preserve_formatting=True)
layout = Layout(skip_fields=["<blank>"])
with pytest.warns(UserWarning):
with Resource(source, dialect=dialect, layout=layout) as resource:
assert resource.read_rows()[1].cells[2] == 274.65999999999997
@pytest.mark.skipif(helpers.is_platform("windows"), reason="It doesn't work for Windows")
def test_xlsx_parser_preserve_formatting():
source = "data/preserve-formatting.xlsx"
dialect = ExcelDialect(preserve_formatting=True)
layout = Layout(header_rows=[1])
with Resource(source, dialect=dialect, layout=layout, infer_type="any") as resource:
assert resource.read_rows() == [
{
# general
"empty": None,
# numeric
"0": "1001",
"0.00": "1000.56",
"0.0000": "1000.5577",
"0.00000": "1000.55770",
"0.0000#": "1000.5577",
# temporal
"m/d/yy": "5/20/40",
"d-mmm": "20-May",
"mm/dd/yy": "05/20/40",
"mmddyy": "052040",
"mmddyyam/pmdd": "052040AM20",
}
]
def test_xlsx_parser_preserve_formatting_percentage():
source = "data/preserve-formatting-percentage.xlsx"
dialect = ExcelDialect(preserve_formatting=True)
with Resource(source, dialect=dialect) as resource:
assert resource.read_rows() == [
{"col1": 123, "col2": "52.00%"},
{"col1": 456, "col2": "30.00%"},
{"col1": 789, "col2": "6.00%"},
]
def test_xlsx_parser_preserve_formatting_number_multicode():
source = "data/number-format-multicode.xlsx"
dialect = ExcelDialect(preserve_formatting=True)
layout = Layout(skip_fields=["<blank>"])
with Resource(source, dialect=dialect, layout=layout) as resource:
assert resource.read_rows() == [
{"col1": Decimal("4.5")},
{"col1": Decimal("-9.032")},
{"col1": Decimal("15.8")},
]
@pytest.mark.vcr
def test_xlsx_parser_workbook_cache():
source = BASE_URL % "data/special/sheets.xlsx"
for sheet in ["Sheet1", "Sheet2", "Sheet3"]:
dialect = ExcelDialect(sheet=sheet, workbook_cache={})
with Resource(source, dialect=dialect) as resource:
assert len(dialect.workbook_cache) == 1
assert resource.read_rows()
def test_xls_parser():
with Resource("data/table.xls") as table:
assert table.header == ["id", "name"]
assert table.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
@pytest.mark.vcr
def test_xls_parser_remote():
with Resource(BASE_URL % "data/table.xls") as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
def test_xls_parser_sheet_by_index():
source = "data/sheet2.xls"
dialect = ExcelDialect(sheet=2)
with Resource(source, dialect=dialect) as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
@pytest.mark.skip
def test_xls_parser_sheet_by_index_not_existent():
source = "data/sheet2.xls"
dialect = ExcelDialect(sheet=3)
with pytest.raises(FrictionlessException) as excinfo:
Resource(source, dialect=dialect).open()
assert 'sheet "3"' in str(excinfo.value)
def test_xls_parser_sheet_by_name():
source = "data/sheet2.xls"
dialect = ExcelDialect(sheet="Sheet2")
with Resource(source, dialect=dialect) as resource:
assert resource.header == ["id", "name"]
assert resource.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
@pytest.mark.skip
def test_xls_parser_sheet_by_name_not_existent():
source = "data/sheet2.xls"
dialect = ExcelDialect(sheet="bad")
with pytest.raises(FrictionlessException) as excinfo:
Resource(source, dialect=dialect).open()
assert 'sheet "bad"' in str(excinfo.value)
def test_xls_parser_merged_cells():
source = "data/merged-cells.xls"
layout = Layout(header=False)
with Resource(source, layout=layout) as resource:
assert resource.read_rows() == [
{"field1": "data", "field2": None},
{"field1": None, "field2": None},
{"field1": None, "field2": None},
]
def test_xls_parser_merged_cells_fill():
source = "data/merged-cells.xls"
dialect = ExcelDialect(fill_merged_cells=True)
layout = Layout(header=False)
with Resource(source, dialect=dialect, layout=layout) as resource:
assert resource.read_rows() == [
{"field1": "data", "field2": "data"},
{"field1": "data", "field2": "data"},
{"field1": "data", "field2": "data"},
]
def test_xls_parser_with_boolean():
with Resource("data/table-with-booleans.xls") as resource:
assert resource.header == ["id", "boolean"]
assert resource.read_rows() == [
{"id": 1, "boolean": True},
{"id": 2, "boolean": False},
]
def test_xlsx_parser_merged_cells_boolean():
source = "data/merged-cells-boolean.xls"
layout = Layout(header=False)
with Resource(source, layout=layout) as resource:
assert resource.read_rows() == [
{"field1": True, "field2": None},
{"field1": None, "field2": None},
{"field1": None, "field2": None},
]
def test_xlsx_parser_merged_cells_fill_boolean():
source = "data/merged-cells-boolean.xls"
dialect = ExcelDialect(fill_merged_cells=True)
layout = Layout(header=False)
with Resource(source, dialect=dialect, layout=layout) as resource:
assert resource.read_rows() == [
{"field1": True, "field2": True},
{"field1": True, "field2": True},
{"field1": True, "field2": True},
]
def test_xls_parser_with_ints_floats_dates():
source = "data/table-with-ints-floats-dates.xls"
with Resource(source) as resource:
assert resource.header == ["Int", "Float", "Date"]
assert resource.read_rows() == [
{"Int": 2013, "Float": Decimal("3.3"), "Date": datetime(2009, 8, 16)},
{"Int": 1997, "Float": Decimal("5.6"), "Date": datetime(2009, 9, 20)},
{"Int": 1969, "Float": Decimal("11.7"), "Date": datetime(2012, 8, 23)},
]
@pytest.mark.vcr
def test_xlsx_parser_fix_for_2007_xls():
source = "https://ams3.digitaloceanspaces.com/budgetkey-files/spending-reports/2018-3-משרד התרבות והספורט-לשכת הפרסום הממשלתית-2018-10-22-c457.xls"
with Resource(source, format="xlsx") as resource:
assert len(resource.read_rows()) > 10
# Write
@pytest.mark.skipif(helpers.is_platform("windows"), reason="It doesn't work for Windows")
def test_xlsx_parser_write(tmpdir):
source = Resource("data/table.csv")
target = Resource(str(tmpdir.join("table.xlsx")), trusted=True)
source.write(target)
with target:
assert target.header == ["id", "name"]
assert target.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
@pytest.mark.skipif(helpers.is_platform("windows"), reason="It doesn't work for Windows")
def test_xlsx_parser_write_sheet_name(tmpdir):
dialect = ExcelDialect(sheet="sheet")
source = Resource("data/table.csv")
target = Resource(str(tmpdir.join("table.xlsx")), dialect=dialect, trusted=True)
source.write(target)
with target:
assert target.header == ["id", "name"]
assert target.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
@pytest.mark.skipif(helpers.is_platform("windows"), reason="It doesn't work for Windows")
def test_xls_parser_write(tmpdir):
source = Resource("data/table.csv")
target = Resource(str(tmpdir.join("table.xls")), trusted=True)
source.write(target)
with target:
assert target.header == ["id", "name"]
assert target.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
@pytest.mark.skipif(helpers.is_platform("windows"), reason="It doesn't work for Windows")
def test_xls_parser_write_sheet_name(tmpdir):
dialect = ExcelDialect(sheet="sheet")
source = Resource("data/table.csv")
target = Resource(str(tmpdir.join("table.xls")), dialect=dialect, trusted=True)
source.write(target)
with target:
assert target.header == ["id", "name"]
assert target.read_rows() == [
{"id": 1, "name": "english"},
{"id": 2, "name": "中国人"},
]
| 34.421622 | 151 | 0.611338 | 1,499 | 12,736 | 5.0507 | 0.134757 | 0.028662 | 0.046493 | 0.061022 | 0.799498 | 0.791969 | 0.755911 | 0.692511 | 0.623432 | 0.567693 | 0 | 0.03052 | 0.233354 | 12,736 | 369 | 152 | 34.514905 | 0.744879 | 0.002748 | 0 | 0.585859 | 0 | 0.003367 | 0.172273 | 0.034423 | 0 | 0 | 0 | 0 | 0.161616 | 1 | 0.104377 | false | 0 | 0.020202 | 0 | 0.124579 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4c5dbd664b24a1dde1d54b1ffce013942ad4d73c | 1,251 | py | Python | tests/pybaseball/test_plotting.py | akern40/pybaseball | 55a3e35b2dd2d4fc5c59f8d3f17bfee1364a86f3 | [
"MIT"
] | 650 | 2017-06-29T20:05:19.000Z | 2022-03-31T03:27:25.000Z | tests/pybaseball/test_plotting.py | akern40/pybaseball | 55a3e35b2dd2d4fc5c59f8d3f17bfee1364a86f3 | [
"MIT"
] | 216 | 2017-10-21T05:05:08.000Z | 2022-03-31T04:04:53.000Z | tests/pybaseball/test_plotting.py | akern40/pybaseball | 55a3e35b2dd2d4fc5c59f8d3f17bfee1364a86f3 | [
"MIT"
] | 214 | 2017-07-18T21:40:01.000Z | 2022-03-29T03:19:55.000Z | import pytest
import pandas as pd
from pandas.testing import assert_frame_equal, assert_series_equal
from pybaseball.plotting import transform_coordinates
@pytest.fixture
def coords():
return pd.DataFrame({"x": [1.0, 2.0, -1.0], "y": [1.0, 0.0, 10.0]})
def test_transform_coordinates_identity_scale(coords):
transformed_coords = transform_coordinates(coords, scale=1)
assert_series_equal(coords.x, transformed_coords.x)
assert_series_equal(-coords.y, transformed_coords.y)
def test_transform_coordinates(coords):
transformed_coords = transform_coordinates(coords, scale=2, x_center=0, y_center=0)
assert_series_equal(2 * coords.x, transformed_coords.x)
assert_series_equal(-2 * coords.y, transformed_coords.y)
transformed_coords = transform_coordinates(coords, scale=2, x_center=1, y_center=1)
expected = pd.DataFrame({"x": [1.0, 3.0, -3.0], "y": [-1.0, 1.0, -19.0]})
assert_frame_equal(expected, transformed_coords)
xc = 123.4
yc = 432.1
transformed_coords = transform_coordinates(coords, scale=0, x_center=xc, y_center=yc)
assert_series_equal(pd.Series(name="x", data=3 * [xc]), transformed_coords.x)
assert_series_equal(pd.Series(name="y", data=3 * [yc]), -transformed_coords.y)
| 37.909091 | 89 | 0.738609 | 190 | 1,251 | 4.621053 | 0.215789 | 0.212984 | 0.135535 | 0.168565 | 0.54328 | 0.432802 | 0.291572 | 0.223235 | 0.127563 | 0 | 0 | 0.042241 | 0.129496 | 1,251 | 32 | 90 | 39.09375 | 0.764004 | 0 | 0 | 0 | 0 | 0 | 0.004796 | 0 | 0 | 0 | 0 | 0 | 0.347826 | 1 | 0.130435 | false | 0 | 0.173913 | 0.043478 | 0.347826 | 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 |
4c63aabbb2299991a78620198288a1c46c57e023 | 8,240 | py | Python | src/kbpo/sampling.py | arunchaganty/kbp-online | 9f8763d8f4bfb1fb8a01f1f4f506f56625dd38d8 | [
"MIT"
] | 4 | 2017-08-09T14:05:48.000Z | 2018-12-25T01:34:23.000Z | src/kbpo/sampling.py | arunchaganty/kbp-online | 9f8763d8f4bfb1fb8a01f1f4f506f56625dd38d8 | [
"MIT"
] | 12 | 2017-01-19T23:18:18.000Z | 2018-12-23T18:57:54.000Z | src/kbpo/sampling.py | arunchaganty/kbp-online | 9f8763d8f4bfb1fb8a01f1f4f506f56625dd38d8 | [
"MIT"
] | 2 | 2017-08-08T09:48:20.000Z | 2018-07-09T09:12:43.000Z | """
Generate samples for a corpus tag and for a submission.
"""
import json
import logging
import numpy as np
from . import db
from . import distribution
from .sample_util import sample_without_replacement
from .counter_utils import normalize
logger = logging.getLogger(__name__)
def sample_document_uniform(corpus_tag, n_samples):
# Get distribution
P = distribution.document_uniform(corpus_tag)
# Get samples
doc_ids = sample_without_replacement(P, n_samples)
with db.CONN:
with db.CONN.cursor() as cur:
cur.execute("""
INSERT INTO sample_batch(distribution_type, corpus_tag, params) VALUES %s RETURNING id
""", [('uniform', corpus_tag, json.dumps({'type':'uniform', 'with_replacement': False}),)])
batch_id, = next(cur)
db.execute_values(cur, """
INSERT INTO document_sample(batch_id, doc_id) VALUES %s
""", [(batch_id, doc_id) for doc_id in doc_ids])
def test_sample_document_uniform():
np.random.seed(42)
tag = 'kbp2016'
db.execute("""TRUNCATE sample_batch CASCADE;
ALTER SEQUENCE sample_batch_id_seq RESTART;
""")
sample_document_uniform(tag, 20)
batches = db.select("""SELECT id, submission_id, distribution_type, corpus_tag, params FROM sample_batch""")
assert len(batches) == 1
batch = batches[0]
assert batch.id == 1
assert batch.submission_id is None
assert batch.distribution_type == "uniform"
assert batch.corpus_tag == "kbp2016"
assert batch.params == {"type":"uniform", "with_replacement": False}
docs = db.select("""SELECT doc_id FROM document_sample WHERE batch_id=%(batch_id)s""", batch_id=batch.id)
assert len(docs) == 20
def sample_document_entity(corpus_tag, n_samples, mention_table='evaluation_mention'):
# Get documents
seed_documents = [(row.doc_id,) for row in db.select("""
SELECT s.doc_id
FROM document_sample s,
document_tag d
WHERE s.doc_id = d.doc_id AND d.tag = %(corpus_tag)s
""", corpus_tag=corpus_tag)]
# Get distribution
P = distribution.document_entity(corpus_tag, seed_documents, mention_table=mention_table)
# Remove seed documents.
for doc_id in seed_documents:
P[doc_id] = 0.
P = normalize(P)
# Get samples
doc_ids = sample_without_replacement(P, n_samples)
with db.CONN:
with db.CONN.cursor() as cur:
cur.execute("""
INSERT INTO sample_batch(distribution_type, corpus_tag, params) VALUES %s RETURNING id
""", [('entity', corpus_tag, json.dumps({'type':'entity', 'with_replacement': False}),)])
batch_id, = next(cur)
db.execute_values(cur, """
INSERT INTO document_sample(batch_id, doc_id) VALUES %s
""", [(batch_id, doc_id) for doc_id in doc_ids])
def test_sample_document_entity():
tag = 'kbp2016'
db.execute("""TRUNCATE sample_batch CASCADE;
ALTER SEQUENCE sample_batch_id_seq RESTART;
""")
sample_document_uniform(tag, 20)
sample_document_entity(tag, 20, mention_table="suggested_mention")
batches = db.select("""SELECT id, submission_id, distribution_type, corpus_tag, params FROM sample_batch""")
assert len(batches) == 2
batch = batches[1]
assert batch.id == 2
assert batch.submission_id is None
assert batch.distribution_type == "entity"
assert batch.corpus_tag == "kbp2016"
assert batch.params == {"type":"entity", "with_replacement": False}
docs = db.select("""SELECT doc_id FROM document_sample WHERE batch_id=%(batch_id)s""", batch_id=batch.id)
assert len(docs) == 20
# TODO: compute sample size
def sample_submission(corpus_tag, submission_id, type_, n_samples):
# Get distribution
logger.info("Computing distributions")
if type_ == "instance":
P = distribution.submission_instance(corpus_tag, submission_id)
elif type_ == "relation":
P = distribution.submission_relation(corpus_tag, submission_id)
elif type_ == "entity":
P = distribution.submission_entity(corpus_tag, submission_id)
elif type_ == "entity_relation":
P = distribution.submission_entity_relation(corpus_tag, submission_id)
else:
raise ValueError("Invalid submission sampling distribution type: {}".format(type_))
# Get samples
logger.info("Drawing samples")
relation_mentions = sample_without_replacement(P[submission_id], n_samples)
logger.info("Loading samples into batch")
with db.CONN:
with db.CONN.cursor() as cur:
cur.execute("""
INSERT INTO sample_batch(submission_id, distribution_type, corpus_tag, params) VALUES %s RETURNING id
""", [(submission_id, type_, corpus_tag, json.dumps({'submission_id':submission_id, 'type':type_, 'with_replacement': False}),)])
batch_id, = next(cur)
db.execute_values(cur, """
INSERT INTO submission_sample(batch_id, submission_id, doc_id, subject, object) VALUES %s
""", [(batch_id, submission_id, doc_id, db.Int4NumericRange(*subject), db.Int4NumericRange(*object_)) for doc_id, subject, object_ in relation_mentions])
return batch_id
def test_sample_submission_instance():
tag = 'kbp2016'
submission_id = 1 # patterns
db.execute("""TRUNCATE sample_batch CASCADE;
ALTER SEQUENCE sample_batch_id_seq RESTART;
""")
sample_submission(tag, submission_id, 'instance', 20)
batches = db.select("""SELECT id, submission_id, distribution_type, corpus_tag, params FROM sample_batch""")
assert len(batches) == 1
batch = batches[0]
assert batch.id == 1
assert batch.submission_id == submission_id
assert batch.distribution_type == "instance"
assert batch.corpus_tag == "kbp2016"
assert batch.params == {"submission_id": submission_id, "type":"instance", "with_replacement": False}
relation_mentions = db.select("""SELECT doc_id, subject, object FROM submission_sample WHERE batch_id=%(batch_id)s AND submission_id=%(submission_id)s""", batch_id=batch.id, submission_id=submission_id)
assert len(relation_mentions) == 20
def test_sample_submission_relation():
tag = 'kbp2016'
submission_id = 1 # patterns
db.execute("""TRUNCATE sample_batch CASCADE;
ALTER SEQUENCE sample_batch_id_seq RESTART;
""")
sample_submission(tag, submission_id, 'relation', 20)
batches = db.select("""SELECT id, submission_id, distribution_type, corpus_tag, params FROM sample_batch""")
assert len(batches) == 1
batch = batches[0]
assert batch.id == 1
assert batch.submission_id == submission_id
assert batch.distribution_type == "relation"
assert batch.corpus_tag == "kbp2016"
assert batch.params == {"submission_id": submission_id, "type":"relation", "with_replacement": False}
relation_mentions = db.select("""SELECT doc_id, subject, object FROM submission_sample WHERE batch_id=%(batch_id)s AND submission_id=%(submission_id)s""", batch_id=batch.id, submission_id=submission_id)
assert len(relation_mentions) == 20
def test_sample_submission_entity():
tag = 'kbp2016'
submission_id = 1 # patterns
db.execute("""TRUNCATE sample_batch CASCADE;
ALTER SEQUENCE sample_batch_id_seq RESTART;
""")
sample_submission(tag, submission_id, 'entity', 20)
batches = db.select("""SELECT id, submission_id, distribution_type, corpus_tag, params FROM sample_batch""")
assert len(batches) == 1
batch = batches[0]
assert batch.id == 1
assert batch.submission_id == submission_id
assert batch.distribution_type == "entity"
assert batch.corpus_tag == "kbp2016"
assert batch.params == {"submission_id": submission_id, "type":"entity", "with_replacement": False}
relation_mentions = db.select("""SELECT doc_id, subject, object FROM submission_sample WHERE batch_id=%(batch_id)s AND submission_id=%(submission_id)s""", batch_id=batch.id, submission_id=submission_id)
assert len(relation_mentions) == 20
| 41.827411 | 206 | 0.678883 | 1,042 | 8,240 | 5.107486 | 0.104607 | 0.110485 | 0.063134 | 0.058625 | 0.729613 | 0.685269 | 0.6708 | 0.655393 | 0.655393 | 0.636415 | 0 | 0.013055 | 0.20983 | 8,240 | 196 | 207 | 42.040816 | 0.804331 | 0.028277 | 0 | 0.576159 | 1 | 0 | 0.358037 | 0.045568 | 0 | 0 | 0 | 0.005102 | 0.231788 | 1 | 0.05298 | false | 0 | 0.046358 | 0 | 0.10596 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4c65364049fc0c809f78550c6a6143be6864d0e0 | 704 | py | Python | terrascript/heroku/r.py | vfoucault/python-terrascript | fe82b3d7e79ffa72b7871538f999828be0a115d0 | [
"BSD-2-Clause"
] | null | null | null | terrascript/heroku/r.py | vfoucault/python-terrascript | fe82b3d7e79ffa72b7871538f999828be0a115d0 | [
"BSD-2-Clause"
] | null | null | null | terrascript/heroku/r.py | vfoucault/python-terrascript | fe82b3d7e79ffa72b7871538f999828be0a115d0 | [
"BSD-2-Clause"
] | null | null | null | from terrascript import _resource
class heroku_addon(_resource): pass
addon = heroku_addon
class heroku_addon_attachment(_resource): pass
addon_attachment = heroku_addon_attachment
class heroku_app(_resource): pass
app = heroku_app
class heroku_app_feature(_resource): pass
app_feature = heroku_app_feature
class heroku_cert(_resource): pass
cert = heroku_cert
class heroku_domain(_resource): pass
domain = heroku_domain
class heroku_drain(_resource): pass
drain = heroku_drain
class heroku_pipeline(_resource): pass
pipeline = heroku_pipeline
class heroku_pipeline_coupling(_resource): pass
pipeline_coupling = heroku_pipeline_coupling
class heroku_space(_resource): pass
space = heroku_space
| 22 | 47 | 0.838068 | 93 | 704 | 5.913978 | 0.182796 | 0.2 | 0.058182 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.105114 | 704 | 31 | 48 | 22.709677 | 0.873016 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.47619 | 0.047619 | 0 | 0.52381 | 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 |
d5c46687c0b6853b7ffcf1ac3a09bb36dad4dd21 | 889 | py | Python | batman/symlinks.py | RealGeeks/batman | ac61d193cbc6cc736f61ae8cf5e933a576b50698 | [
"MIT"
] | 1 | 2018-01-09T20:50:49.000Z | 2018-01-09T20:50:49.000Z | batman/symlinks.py | RealGeeks/batman | ac61d193cbc6cc736f61ae8cf5e933a576b50698 | [
"MIT"
] | 1 | 2021-03-25T21:27:26.000Z | 2021-03-25T21:27:26.000Z | batman/symlinks.py | RealGeeks/batman | ac61d193cbc6cc736f61ae8cf5e933a576b50698 | [
"MIT"
] | 1 | 2019-12-26T12:25:23.000Z | 2019-12-26T12:25:23.000Z | import os
from path_utils import normalize_path
def ensure(links, basedir):
for target, link_name in links.iteritems():
target, link_name = \
normalize_path(target, basedir), \
normalize_path(link_name, basedir)
if os.path.exists(link_name) and not os.path.islink(link_name):
# Non-link file exists. Delete but warn
print "WARNING: Deleting non-link file {0}".format(link_name)
os.remove(link_name)
if os.path.islink(link_name) and os.readlink(link_name) != target:
# Link exists but points to the wrong place
os.unlink(link_name)
if not os.path.islink(link_name):
print "creating link at {link_name} pointing to {target}".format(
link_name=link_name,
target=target
)
os.symlink(target, link_name)
| 38.652174 | 77 | 0.613048 | 117 | 889 | 4.495727 | 0.367521 | 0.228137 | 0.079848 | 0.091255 | 0.125475 | 0.087452 | 0 | 0 | 0 | 0 | 0 | 0.001603 | 0.298088 | 889 | 22 | 78 | 40.409091 | 0.841346 | 0.089989 | 0 | 0 | 0 | 0 | 0.104218 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.111111 | null | null | 0.111111 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.