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
308e63c76843dc2c83c6e852f8d1de8f5c88dc24
236
py
Python
thirdweb/modules/__init__.py
princetonwong/python-sdk
f35181d97620e29d055498fca75f3702f3bb2449
[ "Apache-2.0" ]
1
2022-02-18T16:59:12.000Z
2022-02-18T16:59:12.000Z
thirdweb/modules/__init__.py
princetonwong/python-sdk
f35181d97620e29d055498fca75f3702f3bb2449
[ "Apache-2.0" ]
null
null
null
thirdweb/modules/__init__.py
princetonwong/python-sdk
f35181d97620e29d055498fca75f3702f3bb2449
[ "Apache-2.0" ]
null
null
null
"""All Modules""" from .nft import NftModule as NftModuleV2 from .nft_v1 import * from .nft_types import * from .currency import * from .market import * from .pack import * from .collection import CollectionModule from .bundle import *
23.6
41
0.762712
32
236
5.5625
0.5
0.280899
0
0
0
0
0
0
0
0
0
0.01
0.152542
236
9
42
26.222222
0.88
0.04661
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
30901a41bb25b4bd3ce2983a3e73c05998cafcb0
1,394
py
Python
tests/test_gln.py
jodal/biip
ea56a53a8999f3ded04be881c3348b1b9a373d22
[ "Apache-2.0" ]
17
2020-06-30T08:07:31.000Z
2022-03-26T08:14:24.000Z
tests/test_gln.py
jodal/biip
ea56a53a8999f3ded04be881c3348b1b9a373d22
[ "Apache-2.0" ]
117
2020-08-12T14:32:11.000Z
2022-03-28T04:07:48.000Z
tests/test_gln.py
jodal/biip
ea56a53a8999f3ded04be881c3348b1b9a373d22
[ "Apache-2.0" ]
1
2020-11-23T23:15:58.000Z
2020-11-23T23:15:58.000Z
"""Tests of parsing GLNs.""" import pytest from biip import ParseError from biip.gln import Gln from biip.gs1 import GS1Prefix def test_parse() -> None: gln = Gln.parse("1234567890128") assert gln == Gln( value="1234567890128", prefix=GS1Prefix(value="123", usage="GS1 US"), payload="123456789012", check_digit=8, ) def test_parse_strips_surrounding_whitespace() -> None: gln = Gln.parse(" \t 1234567890128 \n ") assert gln.value == "1234567890128" def test_parse_value_with_invalid_length() -> None: with pytest.raises(ParseError) as exc_info: Gln.parse("123") assert ( str(exc_info.value) == "Failed to parse '123' as GLN: Expected 13 digits, got 3." ) def test_parse_nonnumeric_value() -> None: with pytest.raises(ParseError) as exc_info: Gln.parse("123456789o128") assert ( str(exc_info.value) == "Failed to parse '123456789o128' as GLN: Expected a numerical value." ) def test_parse_with_invalid_check_digit() -> None: with pytest.raises(ParseError) as exc_info: Gln.parse("1234567890127") assert ( str(exc_info.value) == "Invalid GLN check digit for '1234567890127': Expected 8, got 7." ) def test_as_gln() -> None: gln = Gln.parse(" \t 1234567890128 \n ") assert gln.as_gln() == "1234567890128"
22.852459
80
0.643472
176
1,394
4.9375
0.3125
0.048331
0.069045
0.051784
0.35443
0.330265
0.330265
0.330265
0.252014
0.162255
0
0.149577
0.237446
1,394
60
81
23.233333
0.667921
0.015782
0
0.282051
0
0
0.24451
0
0
0
0
0
0.153846
1
0.153846
false
0
0.102564
0
0.25641
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30909c4ad0b0995022dfe80c45b1417b387a7f7d
3,523
py
Python
web/views.py
Chaixi/My-Django-Demo
43cea290f4a4a1c1a3b981eae3be11cc1188b103
[ "MIT" ]
null
null
null
web/views.py
Chaixi/My-Django-Demo
43cea290f4a4a1c1a3b981eae3be11cc1188b103
[ "MIT" ]
null
null
null
web/views.py
Chaixi/My-Django-Demo
43cea290f4a4a1c1a3b981eae3be11cc1188b103
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.views.decorators.csrf import csrf_exempt import json from django.core import serializers # Create your views here. from django.http import HttpResponse from django.http.response import JsonResponse from web import models def hello(request): # return HttpResponse("hello world!") context = {} # 数据绑定 context['hello'] = 'Hello world!' # 将绑定的数据传入前台 return render(request, 'hello.html', context) @csrf_exempt def index(request): if request.method == 'POST': pass else: xmu_news_list = models.News.objects.order_by('-release_time').all() jwc_news_list = models.jwc_News.objects.order_by('-release_time').all() xsc_news_list = models.xsc_News.objects.order_by('-release_time').all() xmu_news_paginator = Paginator(xmu_news_list, 10) #show 20 news per page jwc_news_paginator = Paginator(jwc_news_list, 10) xsc_news_paginator = Paginator(xsc_news_list, 10) # print("p.count:"+str(paginator.count)) # print("p.num_pages:"+str(paginator.num_pages)) # print("p.page_range:"+str(paginator.page_range)) source = request.GET.get("source") page = request.GET.get('page') xmu_news = xmu_news_paginator.get_page(1) jwc_news = jwc_news_paginator.get_page(1) xsc_news = xsc_news_paginator.get_page(1) if(source == 'xmu'): xmu_news = xmu_news_paginator.get_page(page) elif(source == 'jwc'): jwc_news = jwc_news_paginator.get_page(page) elif (source == 'xsc'): xsc_news = xsc_news_paginator.get_page(page) # print("p.number:"+str(news.number)) return render(request, 'index.html', {'li':xmu_news, 'jwc_li':jwc_news, 'xsc_li': xsc_news}) @csrf_exempt def get_page(request): if request.method == 'GET': source = request.GET.get('source') num_page = request.GET.get('page') all_news_list = models.News.objects.order_by('-release_time').all() paginator = Paginator(all_news_list, 20) # show 20 news per page # print("p.count:"+str(paginator.count)) # print("p.num_pages:"+str(paginator.num_pages)) # print("p.page_range:"+str(paginator.page_range)) # page = request.GET.get('page') news = paginator.get_page(num_page) return HttpResponse() @csrf_exempt def get_detail(request): if request.method == 'POST': id = request.POST.get("id") source = request.POST.get("source") print("source: {0}, news_id: {1}".format(source, str(id))) # 此处用get会报错,用filter比较方便 if (source == 'xmu'): item = models.News.objects.filter(id=id) models.News.objects.filter(id=id).update(read_status=2) elif (source == 'jwc'): item = models.jwc_News.objects.filter(id=id) models.jwc_News.objects.filter(id=id).update(read_status=2) elif (source == 'xsc'): item = models.xsc_News.objects.filter(id=id) models.xsc_News.objects.filter(id=id).update(read_status=2) item = item # print(item) # print(item[0]) # json_item = serializers.serialize("json", item) # print(json_item) # json_item = json.loads(json_item) print("Data from get_detail(). 数据从get_detail()获取") return JsonResponse(json_item[0]['fields'], safe=False)
35.94898
100
0.640931
465
3,523
4.655914
0.189247
0.035566
0.051732
0.064665
0.466975
0.371824
0.356582
0.194919
0.194919
0.177367
0
0.008056
0.224808
3,523
97
101
36.319588
0.784694
0.147885
0
0.171875
0
0
0.079168
0
0
0
0
0
0
1
0.0625
false
0.015625
0.125
0
0.25
0.03125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
3090c8adc1b353688b3835d02eb3cdfdcb57bf29
362
py
Python
pcam/datasets/pcam_dataset.py
valeoai/PCAM
ea810250324f74e5c5769dc747ed08ffc97d6f0e
[ "Apache-2.0" ]
19
2021-10-04T10:44:47.000Z
2022-03-01T06:32:05.000Z
pcam/datasets/pcam_dataset.py
valeoai/PCAM
ea810250324f74e5c5769dc747ed08ffc97d6f0e
[ "Apache-2.0" ]
null
null
null
pcam/datasets/pcam_dataset.py
valeoai/PCAM
ea810250324f74e5c5769dc747ed08ffc97d6f0e
[ "Apache-2.0" ]
3
2021-10-04T10:11:18.000Z
2021-12-06T00:22:23.000Z
import torch from torch.utils.data import Dataset class PCAMDataset(Dataset): def __init__(self, root, phase, voxel_size, num_points): super(PCAMDataset, self).__init__() self.root = root self.phase = phase self.voxel_size = voxel_size self.num_points = num_points def __len__(self): return len(self.files)
24.133333
60
0.671271
47
362
4.787234
0.446809
0.12
0.106667
0
0
0
0
0
0
0
0
0
0.240331
362
14
61
25.857143
0.818182
0
0
0
0
0
0
0
0
0
0
0
0
1
0.181818
false
0
0.181818
0.090909
0.545455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
309223f2f8156cc62e0138df83ac0f0153900966
62
py
Python
duckgo.py
yashaka/webdriver-demo
bf1c7d29f54af5e3c77ab2d85bc4bed054a609e1
[ "MIT" ]
null
null
null
duckgo.py
yashaka/webdriver-demo
bf1c7d29f54af5e3c77ab2d85bc4bed054a609e1
[ "MIT" ]
null
null
null
duckgo.py
yashaka/webdriver-demo
bf1c7d29f54af5e3c77ab2d85bc4bed054a609e1
[ "MIT" ]
null
null
null
from selenipupser import element query = element('[name=q]')
15.5
32
0.741935
8
62
5.75
0.875
0
0
0
0
0
0
0
0
0
0
0
0.129032
62
3
33
20.666667
0.851852
0
0
0
0
0
0.129032
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
309278752cdbc75820f2505608011313cc6f1b0b
2,017
py
Python
pyclustering/nnet/tests/integration/__init__.py
JosephChataignon/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
1,013
2015-01-26T19:50:14.000Z
2022-03-31T07:38:48.000Z
pyclustering/nnet/tests/integration/__init__.py
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
542
2015-01-20T16:44:32.000Z
2022-01-29T14:57:20.000Z
pyclustering/nnet/tests/integration/__init__.py
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
262
2015-03-19T07:28:12.000Z
2022-03-30T07:28:24.000Z
"""! @brief Integration-test runner for tests of oscillatory and neural networks. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest from pyclustering.tests.suite_holder import suite_holder # Generate images without having a window appear. import matplotlib matplotlib.use('Agg') from pyclustering.nnet.tests.integration import it_hhn as nnet_hhn_integration_tests from pyclustering.nnet.tests.integration import it_legion as nnet_legion_integration_tests from pyclustering.nnet.tests.integration import it_pcnn as nnet_pcnn_integration_tests from pyclustering.nnet.tests.integration import it_som as nnet_som_integration_tests from pyclustering.nnet.tests.integration import it_sync as nnet_sync_integration_tests from pyclustering.nnet.tests.integration import it_syncpr as nnet_syncpr_integration_tests from pyclustering.nnet.tests.integration import it_syncsegm as nnet_syncsegm_integration_tests class nnet_integration_tests(suite_holder): def __init__(self): super().__init__() nnet_integration_tests.fill_suite(self.get_suite()) @staticmethod def fill_suite(integration_nnet_suite): integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_hhn_integration_tests)) integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_legion_integration_tests)) integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_pcnn_integration_tests)) integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_som_integration_tests)) integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_sync_integration_tests)) integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_syncpr_integration_tests)) integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_syncsegm_integration_tests))
48.02381
116
0.819534
240
2,017
6.541667
0.25
0.163057
0.101911
0.111465
0.626115
0.626115
0.626115
0.598089
0.55414
0.324841
0
0.005036
0.114031
2,017
41
117
49.195122
0.873531
0.108081
0
0
0
0
0.001714
0
0
0
0
0
0
1
0.083333
false
0
0.416667
0
0.541667
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
3094ceba4f2b42b31ff34703aec38ad0bb23b36e
658
py
Python
tests/unit/utils/test_beta.py
cwegrzyn/records-mover
e3b71d6c09d99d0bcd6a956b9d09d20f8abe98d2
[ "Apache-2.0" ]
36
2020-03-17T11:56:51.000Z
2022-01-19T16:03:32.000Z
tests/unit/utils/test_beta.py
cwegrzyn/records-mover
e3b71d6c09d99d0bcd6a956b9d09d20f8abe98d2
[ "Apache-2.0" ]
60
2020-03-02T23:13:29.000Z
2021-05-19T15:05:42.000Z
tests/unit/utils/test_beta.py
cwegrzyn/records-mover
e3b71d6c09d99d0bcd6a956b9d09d20f8abe98d2
[ "Apache-2.0" ]
4
2020-08-11T13:17:37.000Z
2021-11-05T21:11:52.000Z
from records_mover.utils import beta, BetaWarning import unittest from unittest.mock import patch @patch('records_mover.utils.warnings') class TestBeta(unittest.TestCase): def test_beta(self, mock_warnings): @beta def my_crazy_function(): return 123 out = my_crazy_function() self.assertEqual(out, 123) mock_warnings.warn.assert_called_with('Call to beta function my_crazy_function - ' 'interface may change in the future!', category=BetaWarning, stacklevel=2)
34.631579
90
0.571429
67
658
5.41791
0.58209
0.057851
0.123967
0
0
0
0
0
0
0
0
0.016706
0.363222
658
18
91
36.555556
0.849642
0
0
0
0
0
0.159574
0.042553
0
0
0
0
0.133333
1
0.133333
false
0
0.2
0.066667
0.466667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
309593a460380fa8b25ca8344484335fa4f31aad
8,444
py
Python
creator/organizations/mutations.py
kids-first/kf-api-study-creator
93a79b108b6474f9b4135ace06c89ddcf63dd257
[ "Apache-2.0" ]
3
2019-05-04T02:07:28.000Z
2020-10-16T17:47:44.000Z
creator/organizations/mutations.py
kids-first/kf-api-study-creator
93a79b108b6474f9b4135ace06c89ddcf63dd257
[ "Apache-2.0" ]
604
2019-02-21T18:14:51.000Z
2022-02-10T08:13:54.000Z
creator/organizations/mutations.py
kids-first/kf-api-study-creator
93a79b108b6474f9b4135ace06c89ddcf63dd257
[ "Apache-2.0" ]
null
null
null
import graphene from graphql import GraphQLError from graphql_relay import from_global_id from django.contrib.auth import get_user_model from creator.organizations.models import Organization from creator.organizations.queries import OrganizationNode from creator.events.models import Event User = get_user_model() class CreateOrganizationInput(graphene.InputObjectType): """ Schema for creating a new study """ name = graphene.String( required=True, description="The name of the organization" ) description = graphene.String( required=False, description="The description of the organization" ) website = graphene.String( required=False, description="The url of the organization's website" ) email = graphene.String( required=False, description="The email address of the organization" ) image = graphene.String( required=False, description="The url of the display image for the organization", ) class CreateOrganizationMutation(graphene.Mutation): """ Mutation to create a new organization """ class Arguments: """ Arguments for creating a new organization """ input = CreateOrganizationInput( required=True, description="Attributes for the new organization" ) organization = graphene.Field(OrganizationNode) def mutate(self, info, input): """ Create a new organization and add the requesting user to it. """ user = info.context.user if not user.has_perm("organizations.add_organization"): raise GraphQLError("Not allowed") organization = Organization(**input) organization.clean_fields() organization.save() organization.members.add(user) return CreateOrganizationMutation(organization=organization) class UpdateOrganizationInput(graphene.InputObjectType): """ Schema for updating an organization """ name = graphene.String( required=True, description="The name of the organization" ) description = graphene.String( required=False, description="The description of the organization" ) website = graphene.String( required=False, description="The url of the organization's website" ) email = graphene.String( required=False, description="The email of the organization" ) image = graphene.String( required=False, description="A display image for the organization" ) class UpdateOrganizationMutation(graphene.Mutation): """ Mutation to update an organization """ class Arguments: """ Arguments for creating a new organization """ id = graphene.ID( required=True, description="The ID of the organization to update" ) input = UpdateOrganizationInput( required=True, description="Attributes for the new organization" ) organization = graphene.Field(OrganizationNode) def mutate(self, info, id, input): """ Update an organization. """ user = info.context.user if not user.has_perm("organizations.change_organization"): raise GraphQLError("Not allowed") _, organization_id = from_global_id(id) try: organization = Organization.objects.get(pk=organization_id) except Organization.DoesNotExist: raise GraphQLError( f"Organization {organization_id} does not exist" ) for attr, value in input.items(): setattr(organization, attr, value) organization.clean_fields() organization.save() return UpdateOrganizationMutation(organization=organization) class AddMemberMutation(graphene.Mutation): """ Mutation to add a member to an organization """ class Arguments: """ Arguments to add a member to an organization """ organization = graphene.ID( required=True, description="The ID of the organization to update" ) user = graphene.ID( required=True, description="The ID of the user to add the to the organization", ) organization = graphene.Field(OrganizationNode) def mutate(self, info, organization, user): """ Add a member to an organization """ user_id = user user = info.context.user if not user.has_perm("organizations.change_organization"): raise GraphQLError("Not allowed") try: _, organization_id = from_global_id(organization) organization = Organization.objects.get(pk=organization_id) except Organization.DoesNotExist: raise GraphQLError( f"Organization {organization_id} does not exist" ) try: _, user_id = from_global_id(user_id) member = User.objects.get(id=int(user_id)) except (User.DoesNotExist, TypeError): raise GraphQLError(f"User {user_id} does not exist.") if not member.organizations.filter(pk=organization_id).exists(): organization.members.add(member) message = ( f"{user.display_name} added {member.display_name} " f"to organization {organization.name}" ) event = Event( organization=organization, description=message, event_type="MB_ADD", ) else: raise GraphQLError( f"User {member.display_name} is already a member of " f"organization {organization.name}." ) organization.save() if not user._state.adding: event.user = user event.save() return AddMemberMutation(organization=organization) class RemoveMemberMutation(graphene.Mutation): """ Mutation to remove a member from an organization """ class Arguments: """ Arguments to remove a member from an organization """ organization = graphene.ID( required=True, description="The ID of the organization to update" ) user = graphene.ID( required=True, description="The ID of the user to remove the to the organization", ) organization = graphene.Field(OrganizationNode) def mutate(self, info, organization, user): """ Remove a member from an organization """ user_id = user user = info.context.user if not user.has_perm("organizations.change_organization"): raise GraphQLError("Not allowed") try: _, organization_id = from_global_id(organization) organization = Organization.objects.get(pk=organization_id) except Organization.DoesNotExist: raise GraphQLError( f"Organization {organization_id} does not exist" ) try: _, user_id = from_global_id(user_id) member = User.objects.get(id=int(user_id)) except (User.DoesNotExist, TypeError): raise GraphQLError(f"User {user_id} does not exist.") if member.organizations.filter(pk=organization_id).exists(): organization.members.remove(member) message = ( f"{user.display_name} removed {member.display_name} " f"from organization {organization.name}" ) event = Event( organization=organization, description=message, event_type="MB_REM", ) else: raise GraphQLError( f"User {member.display_name} is not a member of " f"organization {organization.name}." ) organization.save() if not user._state.adding: event.user = user event.save() return RemoveMemberMutation(organization=organization) class Mutation: create_organization = CreateOrganizationMutation.Field( description="Create a new organization" ) update_organization = UpdateOrganizationMutation.Field( description="Update an organization" ) add_member = AddMemberMutation.Field( description="Add a member to an organization" ) remove_member = RemoveMemberMutation.Field( description="Remove a member from an organization" )
31.984848
79
0.629678
840
8,444
6.247619
0.133333
0.114329
0.035633
0.041159
0.724848
0.706936
0.645389
0.627477
0.627477
0.536585
0
0
0.289081
8,444
263
80
32.106464
0.87423
0.068214
0
0.542105
0
0
0.188723
0.027609
0
0
0
0
0
1
0.021053
false
0
0.036842
0
0.231579
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
0
0
0
0
0
0
0
0
0
1
30959754a6e2c8e563632f08b50d266c0db6795c
4,835
py
Python
msqure.py
Levi-Huynh/JS-INTERVIEW
768e5577fd8f3f26c244154be9d9fd5a348f6171
[ "MIT" ]
null
null
null
msqure.py
Levi-Huynh/JS-INTERVIEW
768e5577fd8f3f26c244154be9d9fd5a348f6171
[ "MIT" ]
null
null
null
msqure.py
Levi-Huynh/JS-INTERVIEW
768e5577fd8f3f26c244154be9d9fd5a348f6171
[ "MIT" ]
null
null
null
""" Mag Square #always do Detective work nm what UNDERSTAND -nxn matrix of distinctive pos INT from 1 to n^2 -Sum of any row, column, or diagonal of length n is always equal to the same number: "Mag" constant -Given: 3x3 matrix s of integers in the inclusive range [1,9] we can convert any digit a to any other digit b in the range [1,9] at cost of |a-b| -Given s, convert it into a magic square at minimal cost. Print this cost to a new line -constraints: resulting magic square must contain distinct integers on inclusive range [1,9] input= array (3x3 matrix) of s intes, in range[1,9] (convert any digit a to any digit b in range [1,9] at cost |a-b| abs value a-b) output= minimal cost |a-b|, 1 integer input: 5* 3 4 1 5 8* 6 4* 2 OUTPUT: 8* 3 4 1 5 9* 6 7* 2 input [[5,3,4],[1,5,8],[6,4,2]] 12 14 12 output [[8,3,4],[1,5,9],[6,7,2]] 15 15 15 if [i][i] + [i+1][i] + [i+2][i] //C [i][i] + [i][i+1] + [i][i+2] && //R [i][i] + [i+1][i+2] + [i+2][i+2] //D oputput took 3 replacements at cost of |5-8| + |8-9| + |4-7| = 7 3 1 3 row, column, diagonal row1 = s[0][0] [0][1] [0][2] 2 = s[1][0], [1][1], [2][2] 3 [2][0] [2][1] [2][2] #i do it the way you want it done, when you want it done lord #when i say i dont have money for something you ask me for, lack of faith # do you help me to your own hurt? put me first #my strength is in you your laws ty, consistently give all the time input: 4 8* 2 |9-8| 1 // 14R, 15D, 14C 4* 5 7 |3-4| 1 // 16RM, 14MC 6* 1 6 |8-6| 2 // 13R, 13D, 15C input [[4,8,2],[4,5,7],[6,1,6]] 14 16 13 output [[4,9,2],[3,5,7],[8,1,6]] 15 15 15 totla min =4 PLAN EXECUTE REFLECT */ /* input: 5* 3 4 1 5 8* 6 4* 2 OUTPUT: 8* 3 4 1 5 9* 6 7* 2 input [[5,3,4],[1,5,8],[6,4,2]] 12 14 12 output [[8,3,4],[1,5,9],[6,7,2]] 15 15 15 if [i][i] + [i+1][i] + [i+2][i] //C [i][i] + [i][i+1] + [i][i+2] && //R [i][i] + [i+1][i+2] + [i+2][i+2] //D */ function Sq(arr) { let i = 0; let col1 = arr[i][i] + arr[i+1][i] + arr[i+2][i] let col2 = arr[i][i+1] + arr[i+1][i+1] + arr[i+2][i+1] let col3 = arr[i][i+2] + arr[i+1][i+2] + arr[i+2][i+2] let row1 = arr[i][i] + arr[i][i+1] + arr[i][i+2] let row2 = arr[i+1][i] + arr[i+1][i+1]+ arr[i+1][i+2] let row3=arr[i+2][i] + arr[i+2][i+1]+ arr[i+2][i+2] let dia = arr[i][i] + arr[i+1][i+1] + arr[i+2][i+2] let dia2 = arr[i][i+2] + arr[i+1][i+1] + arr[i+2][i] //console.log("col1:", col1, "col2:", col2, "col3:", col3+ "\n" + "row1:", row1, "row2:", row2, "row3:", row3 + "\n" + "diag:", dia, "diag2:", dia2) console.log(col1 - col3) } Sq([[5,3,4],[1,5,8],[6,4,2]]) // //1=? what makes the col/row/diag thats not the primary sums, equal to primary sum //2== how to find the col/row/diag thats diff than main prim sum // store all sums of each col/rows/diags in list // find most freq sum // if col/row/diag != mostfreqsum, then store in tracker array diffSum=[] //diffSum 14, 14 // mostfreqsum - each tracker:colX/rowX/diagX // store ^ all difference in track variable col1: 12 col2: 12 col3: 14 row1: 12 row2: 14 row3: 12 diag: 12 diag2: 15 """ import statistics def Sq(arr): i=0 store=[] dict1 = {} keys = ["col1", "col2", "col3", "row1", "row2", "row3", "diag", "diag2"] col1 = arr[i][i] + arr[i+1][i] + arr[i+2][i] col2 = arr[i][i+1] + arr[i+1][i+1] + arr[i+2][i+1] col3 = arr[i][i+2] + arr[i+1][i+2] + arr[i+2][i+2] row1 = arr[i][i] + arr[i][i+1] + arr[i][i+2] row2 = arr[i+1][i] + arr[i+1][i+1]+ arr[i+1][i+2] row3=arr[i+2][i] + arr[i+2][i+1]+ arr[i+2][i+2] dia = arr[i][i] + arr[i+1][i+1] + arr[i+2][i+2] dia2 = arr[i][i+2] + arr[i+1][i+1] + arr[i+2][i] print("col1:", col1, "col2:", col2, "col3:", col3, "\n" + "row1:", row1, "row2:", row2, "row3:", row3, "\n" + "diag:", dia, "diag2:", dia2) store.append([col1, col2, col3, row1,row2, row3, dia, dia2]) for i in keys: for x in store[0]: dict1[i] = x t= dict1["col1"] #print("dict", t) counter =0 num = store[0][0] track={} for key,value in dict1.items(): if value not in track: track[value]=0 else: track[value]+=1 mostfreq= max(dict1, key=lambda k:dict1[k]) maxtra= max(track, key=track.get) print("h",mostfreq,maxtra) # if store.count(num) < 3, get average from list # FIND mean of store """ mything= sorted(store[0]) print(mything) mymean= statistics.median(mything) rmean= round(mymean) print(mymean, rmean) myl= [rmean-x for x in store[0] if x != rmean] mysum= abs(sum(myl)) print(myl, mysum) """ #return mysum Sq([[4,9,2],[3,5,7],[8,1,5]]) #1
24.668367
150
0.535677
976
4,835
2.653689
0.217213
0.075676
0.025483
0.037066
0.351351
0.318147
0.282239
0.282239
0.273745
0.27027
0
0.114207
0.250259
4,835
196
151
24.668367
0.600276
0.705895
0
0
0
0
0.071001
0
0
0
0
0
0
1
0.03125
false
0
0.03125
0
0.0625
0.0625
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
3095b3e9337fe55ac442949b05abdd6196442a62
1,371
py
Python
scripts/common/rename.py
andrewsanchez/GenBankQC-Workflow
8e630ca89c3f1a3cd9d6b2c4987100e3552d831e
[ "MIT" ]
1
2020-03-19T13:00:30.000Z
2020-03-19T13:00:30.000Z
scripts/common/rename.py
andrewsanchez/GenBankQC-Workflow
8e630ca89c3f1a3cd9d6b2c4987100e3552d831e
[ "MIT" ]
null
null
null
scripts/common/rename.py
andrewsanchez/GenBankQC-Workflow
8e630ca89c3f1a3cd9d6b2c4987100e3552d831e
[ "MIT" ]
null
null
null
import re def parse_genome_id(genome): genome_id = re.search("GCA_[0-9]*.[0-9]", genome).group() return genome_id def rm_duplicates(seq): """Remove duplicate strings during renaming """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def clean_up_name(name): rm_words = re.compile(r"((?<=_)(sp|sub|substr|subsp|str|strain)(?=_))") name = re.sub(" +", "_", name) name = rm_words.sub("_", name) name = re.sub("_+", "_", name) name = re.sub("[\W]+", "_", name) name = rm_duplicates(filter(None, name.split("_"))) name = "_".join(name) return name def rename_genome(genome, assembly_summary): """Rename FASTAs based on info in the assembly summary """ genome_id = parse_genome_id(genome) infraspecific_name = assembly_summary.at[genome_id, "infraspecific_name"] organism_name = assembly_summary.at[genome_id, "organism_name"] if type(infraspecific_name) == float: infraspecific_name = "" isolate = assembly_summary.at[genome_id, "isolate"] if type(isolate) == float: isolate = "" assembly_level = assembly_summary.at[genome_id, "assembly_level"] name = "_".join( [genome_id, organism_name, infraspecific_name, isolate, assembly_level] ) name = clean_up_name(name) + ".fna.gz" return name
30.466667
79
0.648432
184
1,371
4.559783
0.342391
0.095352
0.081049
0.109654
0.183552
0.06913
0
0
0
0
0
0.003656
0.202042
1,371
44
80
31.159091
0.763254
0.070751
0
0.0625
0
0
0.108108
0.035771
0
0
0
0
0
1
0.125
false
0
0.03125
0
0.28125
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30963bad8971717768000852380d252200fb7adb
1,598
py
Python
example/fetch.py
bh2smith/duneapi
835d69fc0b62876b1ac313ac5c21faedd80a8350
[ "Apache-2.0" ]
1
2022-03-15T18:58:33.000Z
2022-03-15T18:58:33.000Z
example/fetch.py
bh2smith/duneapi
835d69fc0b62876b1ac313ac5c21faedd80a8350
[ "Apache-2.0" ]
6
2022-03-25T08:18:52.000Z
2022-03-28T13:52:28.000Z
example/fetch.py
bh2smith/duneapi
835d69fc0b62876b1ac313ac5c21faedd80a8350
[ "Apache-2.0" ]
null
null
null
"""Sample Fetch script from DuneAnalytics""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime from src.duneapi.api import DuneAPI from src.duneapi.types import Network, QueryParameter, DuneQuery from src.duneapi.util import open_query @dataclass class Record: """Arbitrary record with a few different data types""" string: str integer: int decimal: float time: datetime @classmethod def from_dict(cls, obj: dict[str, str]) -> Record: """Constructs Record from Dune Data as string dict""" return cls( string=obj["block_hash"], integer=int(obj["number"]), decimal=float(obj["tx_fees"]), # Dune timestamps are UTC! time=datetime.strptime(obj["time"], "%Y-%m-%dT%H:%M:%S+00:00"), ) def fetch_records(dune: DuneAPI) -> list[Record]: """Initiates and executes Dune query, returning results as Python Objects""" sample_query = DuneQuery.from_environment( raw_sql=open_query("./example/query.sql"), name="Sample Query", network=Network.MAINNET, parameters=[ QueryParameter.number_type("IntParam", 10), QueryParameter.date_type("DateParam", datetime(2022, 3, 10, 12, 30, 30)), QueryParameter.text_type("TextParam", "aba"), ], ) results = dune.fetch(sample_query) return [Record.from_dict(row) for row in results] if __name__ == "__main__": records = fetch_records(DuneAPI.new_from_environment()) print("First result:", records[0])
30.730769
85
0.655194
193
1,598
5.274611
0.507772
0.020629
0.041257
0
0
0
0
0
0
0
0
0.016155
0.225282
1,598
51
86
31.333333
0.806139
0.145181
0
0
0
0
0.097398
0.0171
0
0
0
0
0
1
0.055556
false
0
0.166667
0
0.416667
0.027778
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
3096ae721713437784a75b40a0cbba1472f8290d
696
py
Python
arnold/api.py
hacklabza/arnold
d51f6b751ce6530650555cd33bf707f00b60af59
[ "BSD-3-Clause" ]
2
2021-08-20T05:19:37.000Z
2022-01-11T09:39:39.000Z
arnold/api.py
hacklabza/arnold
d51f6b751ce6530650555cd33bf707f00b60af59
[ "BSD-3-Clause" ]
null
null
null
arnold/api.py
hacklabza/arnold
d51f6b751ce6530650555cd33bf707f00b60af59
[ "BSD-3-Clause" ]
null
null
null
from typing import Optional from bottle import request, route, run import uvicorn from arnold import config from arnold.output.speaker import Speaker API_CONFIG = config.API # Module class instances, rather than init everytime speaker = Speaker() # TODO (qoda): Make this super generic @route('/health') def health(): return {'success': True} @route('/output/speaker', method='POST') def speak(): phrase = request.json.get('phrase', 'No input') speaker.say(phrase) return {'success': True} def runserver(host: Optional[str] = None, port: Optional[int] = None): host = host or API_CONFIG['host'] port = port or API_CONFIG['port'] run(host=host, port=port)
19.885714
70
0.698276
95
696
5.084211
0.505263
0.055901
0.070393
0
0
0
0
0
0
0
0
0
0.175287
696
34
71
20.470588
0.841463
0.125
0
0.105263
0
0
0.10231
0
0
0
0
0.029412
0
1
0.157895
false
0
0.263158
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
1
0
0
0
0
0
0
0
0
0
0
1
30989459794313f3040cb1606c1e87631a244492
27,430
py
Python
app/tests/manual/sample_tweet_stream.py
MichaelCurrin/twitterverse
9629f848377e4346be833db70f11c593cc0d7b6c
[ "MIT" ]
10
2019-03-22T07:07:41.000Z
2022-01-26T00:57:45.000Z
app/tests/manual/sample_tweet_stream.py
MichaelCurrin/twitterverse
9629f848377e4346be833db70f11c593cc0d7b6c
[ "MIT" ]
70
2017-07-12T19:49:38.000Z
2020-09-02T10:03:28.000Z
app/tests/manual/sample_tweet_stream.py
MichaelCurrin/twitterverse
9629f848377e4346be833db70f11c593cc0d7b6c
[ "MIT" ]
2
2017-06-30T07:13:39.000Z
2020-12-04T00:39:12.000Z
#!/usr/bin/env python """ Process a sample tweet fetched using streaming API. Usage: $ ipython -i FILENAME >>> data = main() >>> data.keys() # Then explore the `data` object in ipython. ['contributors', 'truncated', 'text', 'is_quote_status', 'in_reply_to_status_id', 'id', 'favorite_count', 'source', 'retweeted', 'coordinates', 'timestamp_ms', 'entities', 'in_reply_to_screen_name', 'id_str', 'retweet_count', 'in_reply_to_user_id', 'favorited', 'retweeted_status', 'user', 'geo', 'in_reply_to_user_id_str', 'lang', 'created_at', 'filter_level', 'in_reply_to_status_id_str', 'place'] >>> data['text'] 'RT @twice_ph: [TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4\u2026 ' >>> print(data['text']) RT @twice_ph: [TWICETAGRAM] 170701 오랜만에 #두부한모 저희는 잘 있어요 우리 #ONCE 는? #ONCE 가 보고싶다 뒤엔 상큼주의 쯔위가 찍어준 사진ㅋㅋㅋ #TWICE #트와이스… If copying from the command line into Python, characters need to be escaped or the prefix `r` must be applied to the string. Alternatives which I couldn't get to work fully: https://stackoverflow.com/questions/22394235/invalid-control-character-with-python-json-loads https://stackoverflow.com/questions/7262828/python-how-to-convert-string-literal-to-raw-string-literal """ import json def main(): # No line breaks, straight from API x = r'{"created_at":"Sat Jul 01 08:43:29 +0000 2017","id":881070742980313088,"id_str":"881070742980313088","text":"RT @twice_ph: [TWICETAGRAM] 170701\n\\uc624\\ub79c\\ub9cc\\uc5d0 #\\ub450\\ubd80\\ud55c\\ubaa8 \n\\uc800\\ud76c\\ub294 \\uc798 \\uc788\\uc5b4\\uc694 \\uc6b0\\ub9ac #ONCE \\ub294?\n#ONCE \\uac00 \\ubcf4\\uace0\\uc2f6\\ub2e4\n\n\\ub4a4\\uc5d4 \\uc0c1\\ud07c\\uc8fc\\uc758 \\ucbd4\\uc704\\uac00 \\ucc0d\\uc5b4\\uc900 \\uc0ac\\uc9c4\\u314b\\u314b\\u314b \n#TWICE #\\ud2b8\\uc640\\uc774\\uc2a4\\u2026 ","source":"\\u003ca href="http:\\/\\/twitter.com\\/download\\/android" rel="nofollow"\\u003eTwitter for Android\\u003c\\/a\\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":3722867834,"id_str":"3722867834","name":"Amazing Twice","screen_name":"metdew1","location":"\\ub300\\ud55c\\ubbfc\\uad6d \\uc11c\\uc6b8","url":null,"description":"I\'m a korean. My age too old. \nBut really really like TWICE. World ONCE\nfamily i alway thanks your support to\nTWICE. Wish good luck alway with U.","protected":false,"verified":false,"followers_count":977,"friends_count":1204,"listed_count":59,"favourites_count":114142,"statuses_count":100351,"created_at":"Tue Sep 29 06:19:21 +0000 2015","utc_offset":-25200,"time_zone":"Pacific Time (US & Canada)","geo_enabled":false,"lang":"ko","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http:\\/\\/abs.twimg.com\\/images\\/themes\\/theme1\\/bg.png","profile_background_image_url_https":"https:\\/\\/abs.twimg.com\\/images\\/themes\\/theme1\\/bg.png","profile_background_tile":false,"profile_link_color":"9266CC","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http:\\/\\/pbs.twimg.com\\/profile_images\\/858888732539207681\\/89mbzS98_normal.jpg","profile_image_url_https":"https:\\/\\/pbs.twimg.com\\/profile_images\\/858888732539207681\\/89mbzS98_normal.jpg","profile_banner_url":"https:\\/\\/pbs.twimg.com\\/profile_banners\\/3722867834\\/1494858108","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Sat Jul 01 06:10:54 +0000 2017","id":881032343829463040,"id_str":"881032343829463040","text":"[TWICETAGRAM] 170701\n\\uc624\\ub79c\\ub9cc\\uc5d0 #\\ub450\\ubd80\\ud55c\\ubaa8 \n\\uc800\\ud76c\\ub294 \\uc798 \\uc788\\uc5b4\\uc694 \\uc6b0\\ub9ac #ONCE \\ub294?\n#ONCE \\uac00 \\ubcf4\\uace0\\uc2f6\\ub2e4\n\n\\ub4a4\\uc5d4 \\uc0c1\\ud07c\\uc8fc\\uc758 \\ucbd4\\uc704\\uac00 \\ucc0d\\uc5b4\\uc900 \\uc0ac\\uc9c4\\u314b\\u314b\\u314b \n#TWICE #\\ud2b8\\uc640\\uc774\\uc2a4\\u2026 https:\\/\\/t.co\\/9CPNYQiwcq","display_text_range":[0,140],"source":"\\u003ca href="http:\\/\\/twitter.com\\/download\\/android" rel="nofollow"\\u003eTwitter for Android\\u003c\\/a\\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":3779372892,"id_str":"3779372892","name":"TWICE PHILIPPINES \\u2728","screen_name":"twice_ph","location":"Philippines \\ud544\\ub9ac\\ud540","url":null,"description":"Philippine-based support group for TWICE. Officially affiliated with JYPNPH and PKCI http:\\/\\/facebook.com\\/groups\\/TWICEPH\\u2026 ... http:\\/\\/facebook.com\\/TWICEPH\\/","protected":false,"verified":false,"followers_count":7071,"friends_count":224,"listed_count":72,"favourites_count":523,"statuses_count":12448,"created_at":"Sun Oct 04 09:05:12 +0000 2015","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"FFFFFF","profile_background_image_url":"http:\\/\\/pbs.twimg.com\\/profile_background_images\\/722977345053712385\\/naASDMjX.jpg","profile_background_image_url_https":"https:\\/\\/pbs.twimg.com\\/profile_background_images\\/722977345053712385\\/naASDMjX.jpg","profile_background_tile":true,"profile_link_color":"FF3485","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":true,"profile_image_url":"http:\\/\\/pbs.twimg.com\\/profile_images\\/863338740629905408\\/tO_19lHj_normal.jpg","profile_image_url_https":"https:\\/\\/pbs.twimg.com\\/profile_images\\/863338740629905408\\/tO_19lHj_normal.jpg","profile_banner_url":"https:\\/\\/pbs.twimg.com\\/profile_banners\\/3779372892\\/1494670969","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"[TWICETAGRAM] 170701\n\\uc624\\ub79c\\ub9cc\\uc5d0 #\\ub450\\ubd80\\ud55c\\ubaa8 \n\\uc800\\ud76c\\ub294 \\uc798 \\uc788\\uc5b4\\uc694 \\uc6b0\\ub9ac #ONCE \\ub294?\n#ONCE \\uac00 \\ubcf4\\uace0\\uc2f6\\ub2e4\n\n\\ub4a4\\uc5d4 \\uc0c1\\ud07c\\uc8fc\\uc758 \\ucbd4\\uc704\\uac00 \\ucc0d\\uc5b4\\uc900 \\uc0ac\\uc9c4\\u314b\\u314b\\u314b \n#TWICE #\\ud2b8\\uc640\\uc774\\uc2a4 \nhttps:\\/\\/t.co\\/NHPtfkruR4 https:\\/\\/t.co\\/WRv9qP8Mk2","display_text_range":[0,129],"entities":{"hashtags":[{"text":"\\ub450\\ubd80\\ud55c\\ubaa8","indices":[26,31]},{"text":"ONCE","indices":[46,51]},{"text":"ONCE","indices":[55,60]},{"text":"TWICE","indices":[92,98]},{"text":"\\ud2b8\\uc640\\uc774\\uc2a4","indices":[99,104]}],"urls":[{"url":"https:\\/\\/t.co\\/NHPtfkruR4","expanded_url":"https:\\/\\/www.instagram.com\\/p\\/BV_i2J_gx1w\\/","display_url":"instagram.com\\/p\\/BV_i2J_gx1w\\/","indices":[106,129]}],"user_mentions":[],"symbols":[],"media":[{"id":881032307179573248,"id_str":"881032307179573248","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":680,"h":680,"resize":"fit"},"medium":{"w":960,"h":960,"resize":"fit"},"large":{"w":960,"h":960,"resize":"fit"}}},{"id":881032328272683008,"id_str":"881032328272683008","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"large":{"w":734,"h":734,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":734,"h":734,"resize":"fit"},"small":{"w":680,"h":680,"resize":"fit"}}}]},"extended_entities":{"media":[{"id":881032307179573248,"id_str":"881032307179573248","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":680,"h":680,"resize":"fit"},"medium":{"w":960,"h":960,"resize":"fit"},"large":{"w":960,"h":960,"resize":"fit"}}},{"id":881032328272683008,"id_str":"881032328272683008","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"large":{"w":734,"h":734,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":734,"h":734,"resize":"fit"},"small":{"w":680,"h":680,"resize":"fit"}}}]}},"retweet_count":1,"favorite_count":40,"entities":{"hashtags":[{"text":"\\ub450\\ubd80\\ud55c\\ubaa8","indices":[26,31]},{"text":"ONCE","indices":[46,51]},{"text":"ONCE","indices":[55,60]},{"text":"TWICE","indices":[92,98]},{"text":"\\ud2b8\\uc640\\uc774\\uc2a4","indices":[99,104]}],"urls":[{"url":"https:\\/\\/t.co\\/9CPNYQiwcq","expanded_url":"https:\\/\\/twitter.com\\/i\\/web\\/status\\/881032343829463040","display_url":"twitter.com\\/i\\/web\\/status\\/8\\u2026","indices":[106,129]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"ko"},"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"\\ub450\\ubd80\\ud55c\\ubaa8","indices":[40,45]},{"text":"ONCE","indices":[60,65]},{"text":"ONCE","indices":[69,74]},{"text":"TWICE","indices":[106,112]},{"text":"\\ud2b8\\uc640\\uc774\\uc2a4","indices":[113,118]}],"urls":[{"url":"","expanded_url":null,"indices":[120,120]}],"user_mentions":[{"screen_name":"twice_ph","name":"TWICE PHILIPPINES \\u2728","id":3779372892,"id_str":"3779372892","indices":[3,12]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"ko","timestamp_ms":"1498898609286"}' # With link breaks from formatting - see http://jsonviewer.stack.hu/ y = r"""{ "id": 881070742980313088, "created_at": "Sat Jul 01 08:43:29 +0000 2017", "id_str": "881070742980313088", "text": "RT @twice_ph: [TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4\u2026 ", "source": "\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e", "truncated": false, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 3722867834, "id_str": "3722867834", "name": "Amazing Twice", "screen_name": "metdew1", "location": "\ub300\ud55c\ubbfc\uad6d \uc11c\uc6b8", "url": null, "description": "I'm a korean. My age too old. \nBut really really like TWICE. World ONCE\nfamily i alway thanks your support to\nTWICE. Wish good luck alway with U.", "protected": false, "verified": false, "followers_count": 977, "friends_count": 1204, "listed_count": 59, "favourites_count": 114142, "statuses_count": 100351, "created_at": "Tue Sep 29 06:19:21 +0000 2015", "utc_offset": -25200, "time_zone": "Pacific Time (US & Canada)", "geo_enabled": false, "lang": "ko", "contributors_enabled": false, "is_translator": false, "profile_background_color": "000000", "profile_background_image_url": "http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png", "profile_background_image_url_https": "https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png", "profile_background_tile": false, "profile_link_color": "9266CC", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": false, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/858888732539207681\/89mbzS98_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/858888732539207681\/89mbzS98_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/3722867834\/1494858108", "default_profile": false, "default_profile_image": false, "following": null, "follow_request_sent": null, "notifications": null }, "geo": null, "coordinates": null, "place": null, "contributors": null, "retweeted_status": { "created_at": "Sat Jul 01 06:10:54 +0000 2017", "id": 881032343829463040, "id_str": "881032343829463040", "text": "[TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4\u2026 https:\/\/t.co\/9CPNYQiwcq", "display_text_range": [ 0, 140 ], "source": "\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e", "truncated": true, "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 3779372892, "id_str": "3779372892", "name": "TWICE PHILIPPINES \u2728", "screen_name": "twice_ph", "location": "Philippines \ud544\ub9ac\ud540", "url": null, "description": "Philippine-based support group for TWICE. Officially affiliated with JYPNPH and PKCI http:\/\/facebook.com\/groups\/TWICEPH\u2026 ... http:\/\/facebook.com\/TWICEPH\/", "protected": false, "verified": false, "followers_count": 7071, "friends_count": 224, "listed_count": 72, "favourites_count": 523, "statuses_count": 12448, "created_at": "Sun Oct 04 09:05:12 +0000 2015", "utc_offset": null, "time_zone": null, "geo_enabled": false, "lang": "en", "contributors_enabled": false, "is_translator": false, "profile_background_color": "FFFFFF", "profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/722977345053712385\/naASDMjX.jpg", "profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/722977345053712385\/naASDMjX.jpg", "profile_background_tile": true, "profile_link_color": "FF3485", "profile_sidebar_border_color": "000000", "profile_sidebar_fill_color": "000000", "profile_text_color": "000000", "profile_use_background_image": true, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/863338740629905408\/tO_19lHj_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/863338740629905408\/tO_19lHj_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/3779372892\/1494670969", "default_profile": false, "default_profile_image": false, "following": null, "follow_request_sent": null, "notifications": null }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "extended_tweet": { "full_text": "[TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4 \nhttps:\/\/t.co\/NHPtfkruR4 https:\/\/t.co\/WRv9qP8Mk2", "display_text_range": [ 0, 129 ], "entities": { "hashtags": [ { "text": "\ub450\ubd80\ud55c\ubaa8", "indices": [ 26, 31 ] }, { "text": "ONCE", "indices": [ 46, 51 ] }, { "text": "ONCE", "indices": [ 55, 60 ] }, { "text": "TWICE", "indices": [ 92, 98 ] }, { "text": "\ud2b8\uc640\uc774\uc2a4", "indices": [ 99, 104 ] } ], "urls": [ { "url": "https:\/\/t.co\/NHPtfkruR4", "expanded_url": "https:\/\/www.instagram.com\/p\/BV_i2J_gx1w\/", "display_url": "instagram.com\/p\/BV_i2J_gx1w\/", "indices": [ 106, 129 ] } ], "user_mentions": [ ], "symbols": [ ], "media": [ { "id": 881032307179573248, "id_str": "881032307179573248", "indices": [ 130, 153 ], "media_url": "http:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg", "media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg", "url": "https:\/\/t.co\/WRv9qP8Mk2", "display_url": "pic.twitter.com\/WRv9qP8Mk2", "expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1", "type": "photo", "sizes": { "thumb": { "w": 150, "h": 150, "resize": "crop" }, "small": { "w": 680, "h": 680, "resize": "fit" }, "medium": { "w": 960, "h": 960, "resize": "fit" }, "large": { "w": 960, "h": 960, "resize": "fit" } } }, { "id": 881032328272683008, "id_str": "881032328272683008", "indices": [ 130, 153 ], "media_url": "http:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg", "media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg", "url": "https:\/\/t.co\/WRv9qP8Mk2", "display_url": "pic.twitter.com\/WRv9qP8Mk2", "expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1", "type": "photo", "sizes": { "large": { "w": 734, "h": 734, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 734, "h": 734, "resize": "fit" }, "small": { "w": 680, "h": 680, "resize": "fit" } } } ] }, "extended_entities": { "media": [ { "id": 881032307179573248, "id_str": "881032307179573248", "indices": [ 130, 153 ], "media_url": "http:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg", "media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg", "url": "https:\/\/t.co\/WRv9qP8Mk2", "display_url": "pic.twitter.com\/WRv9qP8Mk2", "expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1", "type": "photo", "sizes": { "thumb": { "w": 150, "h": 150, "resize": "crop" }, "small": { "w": 680, "h": 680, "resize": "fit" }, "medium": { "w": 960, "h": 960, "resize": "fit" }, "large": { "w": 960, "h": 960, "resize": "fit" } } }, { "id": 881032328272683008, "id_str": "881032328272683008", "indices": [ 130, 153 ], "media_url": "http:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg", "media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg", "url": "https:\/\/t.co\/WRv9qP8Mk2", "display_url": "pic.twitter.com\/WRv9qP8Mk2", "expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1", "type": "photo", "sizes": { "large": { "w": 734, "h": 734, "resize": "fit" }, "thumb": { "w": 150, "h": 150, "resize": "crop" }, "medium": { "w": 734, "h": 734, "resize": "fit" }, "small": { "w": 680, "h": 680, "resize": "fit" } } } ] } }, "retweet_count": 1, "favorite_count": 40, "entities": { "hashtags": [ { "text": "\ub450\ubd80\ud55c\ubaa8", "indices": [ 26, 31 ] }, { "text": "ONCE", "indices": [ 46, 51 ] }, { "text": "ONCE", "indices": [ 55, 60 ] }, { "text": "TWICE", "indices": [ 92, 98 ] }, { "text": "\ud2b8\uc640\uc774\uc2a4", "indices": [ 99, 104 ] } ], "urls": [ { "url": "https:\/\/t.co\/9CPNYQiwcq", "expanded_url": "https:\/\/twitter.com\/i\/web\/status\/881032343829463040", "display_url": "twitter.com\/i\/web\/status\/8\u2026", "indices": [ 106, 129 ] } ], "user_mentions": [ ], "symbols": [ ] }, "favorited": false, "retweeted": false, "possibly_sensitive": false, "filter_level": "low", "lang": "ko" }, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "entities": { "hashtags": [ { "text": "\ub450\ubd80\ud55c\ubaa8", "indices": [ 40, 45 ] }, { "text": "ONCE", "indices": [ 60, 65 ] }, { "text": "ONCE", "indices": [ 69, 74 ] }, { "text": "TWICE", "indices": [ 106, 112 ] }, { "text": "\ud2b8\uc640\uc774\uc2a4", "indices": [ 113, 118 ] } ], "urls": [ { "url": "", "expanded_url": null, "indices": [ 120, 120 ] } ], "user_mentions": [ { "screen_name": "twice_ph", "name": "TWICE PHILIPPINES \u2728", "id": 3779372892, "id_str": "3779372892", "indices": [ 3, 12 ] } ], "symbols": [ ] }, "favorited": false, "retweeted": false, "filter_level": "low", "lang": "ko", "timestamp_ms": "1498898609286" } """ # Works on y, but not x data = json.loads(y) print((json.dumps(data, indent=4))) return data if __name__ == "__main__": main()
52.347328
9,560
0.537149
2,909
27,430
4.895841
0.140254
0.024716
0.024716
0.020222
0.937719
0.934138
0.93147
0.928802
0.928802
0.928802
0
0.145265
0.268939
27,430
523
9,561
52.447419
0.564803
0.052862
0
0.58811
0
0.012739
0.713109
0.19714
0
0
0
0
0
1
0.002123
false
0
0.002123
0
0.006369
0.002123
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
1
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
8
3098faf17a69f75a1483cd08aad053831460cf55
144
py
Python
Prazen Euler.py
Babnik21/Euler
e73f27ca477c58940a8212b17cd86fce9684e15b
[ "MIT" ]
null
null
null
Prazen Euler.py
Babnik21/Euler
e73f27ca477c58940a8212b17cd86fce9684e15b
[ "MIT" ]
null
null
null
Prazen Euler.py
Babnik21/Euler
e73f27ca477c58940a8212b17cd86fce9684e15b
[ "MIT" ]
null
null
null
i = 0 vsota = 0 while i < 1000: if i % 3 == 0: vsota += i elif i % 5 == 0: vsota += i i += 1 print(vsota)
7.2
20
0.375
23
144
2.347826
0.478261
0.333333
0.259259
0
0
0
0
0
0
0
0
0.148649
0.486111
144
19
21
7.578947
0.581081
0
0
0.222222
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.111111
1
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
309bdc9a6d187eaaf1d1bd279e7967ac39ed0b19
1,886
py
Python
koabot/patterns.py
luni3359/koa-bot
3faf4af89f2a414313e651088f6fd16d12e298ec
[ "MIT" ]
2
2020-05-05T03:02:39.000Z
2021-07-05T13:38:21.000Z
koabot/patterns.py
luni3359/koa-bot
3faf4af89f2a414313e651088f6fd16d12e298ec
[ "MIT" ]
65
2019-01-05T05:51:47.000Z
2022-03-26T17:39:20.000Z
koabot/patterns.py
luni3359/koa-bot
3faf4af89f2a414313e651088f6fd16d12e298ec
[ "MIT" ]
1
2021-01-06T03:39:00.000Z
2021-01-06T03:39:00.000Z
"""Regex pattern constants""" import re URL_PATTERN = re.compile(r'(http[s]?://(?:[a-zA-Z]|[0-9]|[$-;?-_=@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)') NUMBER_PATTERN = re.compile(r'(\.\d+|\d[,\d]*(?:\.\d+)?)') UNIT_PATTERN_TUPLE = [ # [length] ('inch', re.compile(r' *("|inch|inches|ins?)(?!\w)')), ('foot', re.compile(r' *(\'|foot|feet|ft)(?!\w)')), ('mile', re.compile(r' *(miles?|mi)(?!\w)')), ('yard', re.compile(r' *(yards?|yr?d)(?!\w)')), ('centimeter', re.compile(r' *(centimeters?|centimetres?|cms?)(?!\w)')), ('meter', re.compile(r' *(meters?|metres?|mt?r?s?)(?!\w)')), ('kilometer', re.compile(r' *(kilometers?|kilometres?|kms?)(?!\w)')), # [length ** 3] ('gallon', re.compile(r' *(gallons?|gal)(?!\w)')), ('liter', re.compile(r' *(liters?|litres?|lt?r?s?)(?!\w)')), # [mass] ('ounce', re.compile(r' *(ounces?|oz)(?!\w)')), ('pound', re.compile(r' *(pounds?|lbs?)(?!\w)')), ('gram', re.compile(r' *(grams?|gr?m?s?)(?!\w)')), ('kilogram', re.compile(r' *(kilograms?|kgs?)(?!\w)')), # [temperature] ('celsius', re.compile(r' *(°|degrees?|degs?)? *([Cc]|[CcSs]el[sc]ius)(?!\w)')), ('fahrenheit', re.compile(r' *(°|degrees?|degs?)? *([Ff]|[Ff]h?ah?rh?enheit)(?!\w)')), ('kelvin', re.compile(r' *(°|degrees?|degs?)? *([Kk]|[Kk]el[vb]in)(?!\w)')), ('rankine', re.compile(r' *(°|degrees?|degs?)? *([Rr]|[Rr]ankine?)(?!\w)')), ] SPECIAL_UNIT_PATTERN_TUPLE = ('footinches', re.compile(r'(\.\d+|\d[,\d]*(?:\.\d+)?)\'(\.\d+|\d[,\d]*(?:\.\d+)?)"?')) DICE_PATTERN = re.compile(r'(?:([+-])\ ?)?(?:(\d*)?d(\d+)(?:\ ?(k[hl]\d+))?|(\d+))') CHANNEL_URL_PATTERN = re.compile(r'https:\/\/(?:ptb\.)?discord(?:app)?\.com\/channels(?:\/\d{18}){3}') DISCORD_EMOJI_PATTERN = re.compile(r'(<:[\w_]{1,32}:\d{18}>)') HTML_TAG_OR_ENTITY_PATTERN = re.compile(r'<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
46
116
0.494168
272
1,886
3.375
0.426471
0.235294
0.261438
0.111111
0.203704
0.160131
0.06427
0
0
0
0
0.014741
0.100742
1,886
40
117
47.15
0.524175
0.036055
0
0
0
0.074074
0.535102
0.365948
0
0
0
0
0
1
0
false
0
0.037037
0
0.037037
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
309c11fc57b0f92270c9e810c9427e1dc68d5961
38
py
Python
apis/resources/__init__.py
Fusemachines/fuse-python-training
939bf935646a60817b1da329791e376c7e59464b
[ "FSFAP" ]
null
null
null
apis/resources/__init__.py
Fusemachines/fuse-python-training
939bf935646a60817b1da329791e376c7e59464b
[ "FSFAP" ]
null
null
null
apis/resources/__init__.py
Fusemachines/fuse-python-training
939bf935646a60817b1da329791e376c7e59464b
[ "FSFAP" ]
null
null
null
from apis.resources.users import user
19
37
0.842105
6
38
5.333333
1
0
0
0
0
0
0
0
0
0
0
0
0.105263
38
1
38
38
0.941176
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
5
309cb4e46480df6e33282f805360a5aeb8f64ac4
11,873
py
Python
pi_spark/backup_old_spark.py
cybertraining-dsc/sp20-516-246
73e1e9d8ed421d821848cb895368fd0e1c56f343
[ "Apache-2.0" ]
null
null
null
pi_spark/backup_old_spark.py
cybertraining-dsc/sp20-516-246
73e1e9d8ed421d821848cb895368fd0e1c56f343
[ "Apache-2.0" ]
null
null
null
pi_spark/backup_old_spark.py
cybertraining-dsc/sp20-516-246
73e1e9d8ed421d821848cb895368fd0e1c56f343
[ "Apache-2.0" ]
null
null
null
import os import textwrap from pprint import pprint #import cloudmesh.pi.cluster from cloudmesh.pi.cluster.Installer import Installer from cloudmesh.pi.cluster.Installer import Script from cloudmesh.common.Host import Host from cloudmesh.common.Printer import Printer from cloudmesh.common.console import Console from cloudmesh.common.parameter import Parameter from cloudmesh.common.util import banner # see also: https://github.com/cloudmesh/cloudmesh-pi-cluster/tree/master/cloudmesh/cluster/spark class Spark(Installer): def __init__(self, master=None, workers=None): """ :param master: :param workers: """ self.master = master self.workers = workers self.java_version = "11" self.version = "2.4.5" self.user = "pi" self.script = Script() self.service = "spark" #self.port = 6443 self.hostname = os.uname()[1] self.scripts() def scripts(self): self.script["spark.check"] = """ hostname uname -a """ self.script["spark.test"] = """ sh $SPARK_HOME/sbin/start-all.sh $SPARK_HOME/bin/run-example SparkPi 4 10 sh $SPARK_HOME/sbin/stop-all.sh """ self.script["spark.setup.master"] = """ sudo apt-get update sudo apt-get install default-jdk sudo apt-get install scala cd ~ sudo wget http://mirror.metrocast.net/apache/spark/spark-{version}/spark-{version}-bin-hadoop2.7.tgz -O sparkout.tgz sudo tar -xzf sparkout.tgz sudo cp ~/.bashrc ~/.bashrc-backup sudo chmod 777 ~/spark-{version}-bin-hadoop2.7/conf sudo cp /home/pi/spark-{version}-bin-hadoop2.7/conf/slaves.template /home/pi/spark-{version}-bin-hadoop2.7/conf/slaves """ self.script["spark.setup.worker"] = """ sudo apt-get update sudo apt-get install default-jdk sudo apt-get install scala cd ~ sudo tar -xzf sparkout.tgz sudo cp ~/.bashrc ~/.bashrc-backup """ self.script["copy.spark.to.worker"] = """ scp /bin/spark-setup-worker.sh {user}@self.workers: scp ~/sparkout.tgz {user}@{worker}: ssh {user}@{worker} sh ~/spark-setup-worker.sh """ self.script["spark.uninstall2.4.5"] = """ sudo apt-get remove openjdk-11-jre sudo apt-get remove scala cd ~ sudo rm -rf spark-2.4.5-bin-hadoop2.7 sudo rm -f sparkout.tgz sudo cp ~/.bashrc-backup ~/.bashrc """ self.script["update.bashrc"] = """ # ################################################ # SPARK BEGIN # #JAVA_HOME export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-armhf/ #SCALA_HOME export SCALA_HOME=/usr/share/scala export PATH=$PATH:$SCALA_HOME/bin #SPARK_HOME export SPARK_HOME=~/spark-2.4.5-bin-hadoop2.7 export PATH=$PATH:$SPARK_HOME/bin # # SPARK END # ################################################ """ script["spark.setup.worker.sh"] = """ #!/usr/bin/env bash sudo apt-get update sudo apt-get install default-jdk sudo apt-get install scala cd ~ sudo tar -xzf sparkout.tgz cat ~/.bashrc ~/spark-bashrc.txt > ~/temp-bashrc sudo cp ~/.bashrc ~/.bashrc-backup sudo cp ~/temp-bashrc ~/.bashrc sudo rm ~/temp-bashrc sudo chmod 777 ~/spark-{version}-bin-hadoop2.7/ """ return self.script def execute(self, arguments): """ pi spark setup --master=MASTER --workers=WORKER pi spark start --master=MASTER --workers=WORKER pi spark stop --master=MASTER --workers=WORKER pi spark test --master=MASTER --workers=WORKER pi spark check --master=MASTER --worker=WORKER :param arguments: :return: """ self.dryrun = arguments["--dryrun"] master = Parameter.expand(arguments.master) workers = Parameter.expand(arguments.workers) if len(master) > 1: Console.error("You can have only one master") master = master[0] # find master and worker from arguments if arguments.master: hosts.append(arguments.master) if arguments.workers: hosts = Parameter.expand(arguments.workers) if workers is not None and master is None: Console.error("You need to specify at least one master or worker") return "" # do the action on master amd workers found if arguments.setup: self.setup(master, workers) elif arguments.start: self.start(master, workers) elif arguments.stop: self.stop(master, workers) elif arguments.test: self.test(master, workers) elif arguments.check: self.check(master, workers) def run(self, script=None, hosts=None, username=None, processors=4, verbose=False): results = [] if type(hosts) != list: hosts = Parameter.expand(hosts) for command in script.splitlines(): if hosts == None: hosts = "" if command.startswith("#") or command.strip() == "": print(command) elif len(hosts) == 1 and hosts[0] == self.hostname: command = command.format(user=self.user, version=self.version, host=host, hostname=hostname) print(hosts, "->", command) if self.dryrun: Console.info(f"Executiong command >{command}<") else: os.system(command) elif len(hosts) == 1 and hosts[0] != self.hostname: host = hosts[0] command = command.format(user=self.user, version=self.version, host=host, hostname=hostname) print(hosts, "->", command, hosts) if self.dryrun: Console.info(f"Executiong command >{command}<") else: os.system(f"ssh {host} {command}") else: #@staticmethod #def run(hosts=None, # command=None, # execute=None, # processors=3, # shell=False, # **kwargs): if self.dryrun: executor = print else: executor = os.system result = Host.ssh(hosts=hosts, command=command, username=username, key="~/.ssh/id_rsa.pub", processors=processors, executor=executor, version=self.version, # this was your bug, you did not pass this along user=self.user # this was your bug, you did not pass this along ) results.append(result) if verbose: pprint(results) for result in results: print(Printer.write(result, order=['host', 'stdout'])) return results def run_script(self, name=None, hosts=None): banner(name) print("self.script = ") pprint(self.script) results = self.run(script=self.script[name], hosts=hosts, verbose=True) def setup(self, master= None, workers=None): # # SETUP THE MASTER # banner(f"Setup Master: {master}") self.run_script(name="sparksetup", hosts=self.master) #os.system("sudo apt-get update") if "SPARK_HOME" not in os.environ: Console.error("$SPARK_HOME is not set") return "" spark_home = os.environ("SPARK_HOME") filename = "{spark_home}/conf/slaves" banner(f"Updating file: {filename}") filename = if not self.dryrun: Installer.add_script(fileanme, "{user}@{worker}") banner(f"Setup bashrc: {master}") print(Spark.update_bashrc()) # # SETUP THE WORKER. STEP 1: GET THE FILES FROM MASTER # banner(f"Get files from {master}") print(self.create_spark_setup_worker()) self.run_script(name="copy.spark.to.worker", hosts=self.workers) # # SETUP THE WORKER. SETUP BASHRC ON WORKERS # print(self.create_spark_bashrc_txt()) print(self.update_slaves()) # Print created cluster #self.view() # raise NotImplementedError def start(self, master=None, hosts=None): # Setup Spark on the master if master is not None: if type(master) != list: master = Parameter.expand(master) banner(f"Start Master: {master[0]}") os.system("sh $SPARK_HOME/sbin/start-all.sh") # command = Installer.oneline(f""" # sh $SPARK_HOME/sbin/start-all.sh - # """) # raise NotImplementedError def test(self, master=None, hosts=None): banner(f"Listing $SPARK_HOME from {master[0]}") os.system("ls $SPARK_HOME") os.system("$SPARK_HOME/bin/run-example SparkPi 4 10") def stop(self, master=None, hosts=None): # Stop Spark on master and all workers if master is not None: if type(master) != list: master = Parameter.expand(master) # # TODO - bug I should be able to run this even if I am not on master # banner(f"Start Master: {master[0]}") os.system("sh $SPARK_HOME/sbin/stop-all.sh") #command = Installer.oneline(f""" # sh $SPARK_HOME/sbin/stop-all.sh - # """) # raise NotImplementedError def update_bashrc(self): """ Add the following lines to the bottom of the ~/.bashrc file :return: """ banner("Updating ~/.bashrc file") script = textwrap.dedent(self.script["update.bashrc"]) Installer.add_script("~/.bashrc", script) def create_spark_setup_worker(self): """ This file is created on master and copied to worker, then executed on worker from master :return: """ banner("Creating the spark.setup.worker.sh file") script = self.script["spark.setup.worker.sh"] if self.dryrun: print (script) else: f = open("/home/pi/spark-setup-worker.sh", "w+") #f.write("test") f.close() Installer.add_script("~/spark-setup-worker.sh", script) def create_spark_bashrc_txt(self): """ Test to add at bottome of ~/.bashrc. File is created on master and copied to worker :return: """ script = self.script["update.bashrc"] if self.dryrun: print (script) else: f = open("/home/pi/spark-bashrc.txt", "w+") #f.write("test") f.close() Installer.add_script("~/spark-bashrc.txt", script)
33.44507
133
0.516971
1,283
11,873
4.744349
0.177709
0.026614
0.019714
0.0207
0.37999
0.309676
0.271234
0.252341
0.230327
0.205027
0
0.008238
0.366125
11,873
354
134
33.539548
0.800558
0.087931
0
0.255507
0
0.008811
0.362431
0.083906
0
0
0
0.002825
0
0
null
null
0
0.044053
null
null
0.066079
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
309e29bd5c11a93e22fbf0abbb2d7d78bdce1323
1,321
py
Python
constants.py
tabilab-dip/sentiment-embeddings
8859a19d19cb96ee0b0da5053396a1c54bab5da6
[ "MIT" ]
7
2020-11-18T10:02:22.000Z
2022-01-06T03:24:37.000Z
constants.py
tabilab-dip/sentiment-embeddings
8859a19d19cb96ee0b0da5053396a1c54bab5da6
[ "MIT" ]
1
2020-10-26T18:56:23.000Z
2020-10-26T18:56:23.000Z
constants.py
tabilab-dip/sentiment-embeddings
8859a19d19cb96ee0b0da5053396a1c54bab5da6
[ "MIT" ]
1
2020-12-04T13:51:46.000Z
2020-12-04T13:51:46.000Z
#!/usr/bin/py # -*- coding: utf-8 -*- """ @author: Cem Rıfkı Aydın Constant parameters to be leveraged across the program. """ import os COMMAND = "cross_validate" # Dimension size of embeddings EMBEDDING_SIZE = 100 #Language can be either "turkish" or "english" LANG = "turkish" DATASET_PATH = os.path.join("input", "Sentiment_dataset_turk.csv") # Sentiment_dataset_tr.csv; test_tr.csv CONTEXT_WINDOW_SIZE = 5 """ Word embedding type can be one of the following: corpus_svd: SVD - U vector lexical_svd: Dictionary, SVD - U vector supervised: Four context delta idf score vector ensemble: Combination of the above three embeddings clustering: Clustering vector word2vec: word2vec """ EMBEDDING_TYPE = "ensemble" # Number of cross-validation CV_NUMBER = 10 # Concatenation of the maximum, average, and minimum delta-idf polarity scores with the average document vector. USE_3_REV_POL_SCORES = True # The below variables are used only if the command "train_and_test_separately" is chosen. TRAINING_FILE_PATH = os.path.join("input", "Turkish_twitter_train.csv") TEST_FILE_PATH = os.path.join("input", "Turkish_twitter_test.csv") # The below file name for the model trained could also be used given that # model parameters (e.g. embedding size and type) are the same. MODEL_FILE_NAME = 'finalized_model.sav'
26.42
112
0.7676
199
1,321
4.934673
0.567839
0.01833
0.03055
0.04277
0.094705
0.075356
0.075356
0.075356
0
0
0
0.008842
0.14383
1,321
49
113
26.959184
0.859416
0.445117
0
0
0
0
0.312925
0.170068
0
0
0
0
0
1
0
false
0
0.083333
0
0.083333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30a148fcef8cc908dd17aa013d41bed192bfd5de
122
py
Python
libraries/website/docs/snippets/cas/overview/evaluate_expression.py
justindujardin/mathy
776ac528d4586d6ea558a7212adb3559ea487a3c
[ "MIT" ]
95
2020-01-02T23:02:34.000Z
2022-03-08T18:57:24.000Z
libraries/website/docs/snippets/cas/overview/evaluate_expression.py
justindujardin/mathy
776ac528d4586d6ea558a7212adb3559ea487a3c
[ "MIT" ]
44
2020-01-05T03:07:45.000Z
2021-08-11T20:45:53.000Z
libraries/website/docs/snippets/cas/overview/evaluate_expression.py
justindujardin/mathy
776ac528d4586d6ea558a7212adb3559ea487a3c
[ "MIT" ]
5
2020-04-04T16:46:36.000Z
2022-03-30T08:10:02.000Z
from mathy_core import ExpressionParser expression = ExpressionParser().parse("4 + 2") assert expression.evaluate() == 6
24.4
46
0.770492
14
122
6.642857
0.857143
0
0
0
0
0
0
0
0
0
0
0.027778
0.114754
122
4
47
30.5
0.833333
0
0
0
0
0
0.040984
0
0
0
0
0
0.333333
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
30a1b3867be211ebdc0dea68618ce31d72b2a875
352
py
Python
quarkc/test/ffi/expected/py/overlapping_namespaces/setup.py
datawire/quark
df0058a148b077c0aff535eb6ee382605c556273
[ "Apache-2.0" ]
112
2015-10-02T19:51:51.000Z
2022-03-07T06:29:44.000Z
quarkc/test/ffi/expected/py/overlapping_namespaces/setup.py
datawire/quark
df0058a148b077c0aff535eb6ee382605c556273
[ "Apache-2.0" ]
181
2015-10-01T20:23:38.000Z
2016-12-07T17:21:26.000Z
quarkc/test/ffi/expected/py/overlapping_namespaces/setup.py
datawire/quark
df0058a148b077c0aff535eb6ee382605c556273
[ "Apache-2.0" ]
31
2015-10-13T22:10:00.000Z
2020-08-03T02:50:12.000Z
# Setup file for package overlapping_namespace from setuptools import setup setup(name="overlapping_namespace", version="0.1.0", install_requires=["wheel", "quark==0.0.1", "org_example_foo==0.1.0"], setup_requires=["wheel"], py_modules=[], packages=['org', 'org.example', 'org.example.bar', 'overlapping_namespace_md'])
32
85
0.678977
46
352
5
0.543478
0.26087
0.026087
0
0
0
0
0
0
0
0
0.0301
0.150568
352
10
86
35.2
0.73913
0.125
0
0
0
0
0.401961
0.218954
0
0
0
0
0
1
0
true
0
0.142857
0
0.142857
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
30a37bf131fb4b3429d304093f34cb95cda25236
9,285
py
Python
torpido/io.py
AP-Atul/Torpido
a646b4d6de7f2e2c96de4c64ce3113f53e3931c2
[ "Unlicense" ]
21
2020-12-23T07:13:10.000Z
2022-01-12T10:32:22.000Z
torpido/io.py
AP-Atul/Torpido
a646b4d6de7f2e2c96de4c64ce3113f53e3931c2
[ "Unlicense" ]
2
2020-12-30T10:45:42.000Z
2021-09-25T09:52:00.000Z
torpido/io.py
AP-Atul/Torpido
a646b4d6de7f2e2c96de4c64ce3113f53e3931c2
[ "Unlicense" ]
1
2021-02-06T21:39:41.000Z
2021-02-06T21:39:41.000Z
""" This file contains function to separate out video and audio using ffmpeg. It consists of two functions to split and merge video and audio using ffmpeg. """ import os from torpido.config.constants import (CACHE_DIR, CACHE_NAME, IN_AUDIO_FILE, OUT_AUDIO_FILE, OUT_VIDEO_FILE, THUMBNAIL_FILE) from torpido.exceptions import AudioStreamMissingException, FFmpegProcessException from torpido.ffpbar import Progress from torpido.tools.ffmpeg import split, merge, thumbnail from torpido.tools.logger import Log class FFMPEG: """ FFMPEG helper function to make use of the subprocess module to run command to trim and split video files. The std out logs are parsed to generate a progress bar to show the progress of the command that is being executed. Attributes ---------- __input_file_name : str input video file name __input_file_path : str input video file name __output_video_file_name : str output video file name __input_audio_file_name : str original splatted audio file name __output_audio_file_name : str de-noised audio file name __output_file_path : str same as the input file path __intro : str name of the intro video file __outro : str name of the outro video file __extension : str name of the extension of the input file __progress_bar : tqdm object of tqdm to display a progress bar """ def __init__(self): self.__input_file_name = self.__input_file_path = self.__output_video_file_name = self.__input_audio_file_name = None self.__output_audio_file_name = self.__output_file_path = self.__thumbnail_file = self.__intro = None self.__outro = self.__extension = self.__progress_bar = None def set_intro_video(self, intro): """ Sets the intro video file """ self.__intro = intro def set_outro_video(self, outro): """ Sets the outro video file """ self.__outro = outro def get_input_file_name_path(self): """ Returns file name that was used for processing """ if self.__input_file_name is not None: return os.path.join(self.__input_file_path, self.__input_file_name) def get_output_file_name_path(self): """ Returns output file name generated from input file name """ if self.__output_video_file_name is not None: return os.path.join(self.__output_file_path, self.__output_video_file_name) def get_input_audio_file_name_path(self): """ Returns name and path of the input audio file that is split from the input video file """ if self.__input_audio_file_name is not None: return os.path.join(self.__output_file_path, self.__input_audio_file_name) def get_output_audio_file_name_path(self): """ Returns the output audio file name and path that is de-noised """ if self.__output_audio_file_name is not None: return os.path.join(self.__output_file_path, self.__output_audio_file_name) def split_video_audio(self, input_file): """ Function to split the input video file into audio file using FFmpeg. Progress bar is updated as the command is run Note : No new video file is created, only audio file is created Parameters ---------- input_file : str input video file Returns ------- bool returns True if success else Error """ if os.path.isfile(input_file) is False: Log.e("File does not exists") return False # storing all the references self.__input_file_path = os.path.dirname(input_file) self.__output_file_path = self.__input_file_path self.__input_file_name = os.path.basename(input_file) # get the base name without the extension base_name, self.__extension = os.path.splitext(self.__input_file_name) self.__output_video_file_name = "".join([base_name, OUT_VIDEO_FILE, self.__extension]) self.__input_audio_file_name = base_name + IN_AUDIO_FILE self.__output_audio_file_name = base_name + OUT_AUDIO_FILE self.__thumbnail_file = base_name + THUMBNAIL_FILE # call ffmpeg tool to do the splitting try: Log.i("Splitting the video file.") self.__progress_bar = Progress() for log in split(input_file, os.path.join(self.__output_file_path, self.__input_audio_file_name)): self.__progress_bar.display(log) if not os.path.isfile(os.path.join(self.__output_file_path, self.__input_audio_file_name)): raise AudioStreamMissingException self.__progress_bar.complete() print("----------------------------------------------------------") return True # no audio in the video except AudioStreamMissingException: Log.e(AudioStreamMissingException.cause) self.__progress_bar.clear() return False def merge_video_audio(self, timestamps): """ Function to merge the processed files using FFmpeg. The timestamps are used the trim the original video file and the audio stream is replaced with the de-noised audio file created by `Auditory` Parameters ---------- timestamps : list list of start and end timestamps Returns ------- bool True id success else error is raised """ if self.__input_file_name is None or self.__output_audio_file_name is None: Log.e("Files not found for merging") return False # call ffmpeg tool to merge the files try: self.__progress_bar = Progress() Log.i("Writing the output video file.") for log in merge(os.path.join(self.__output_file_path, self.__input_file_name), os.path.join(self.__output_file_path, self.__output_audio_file_name), os.path.join(self.__output_file_path, self.__output_video_file_name), timestamps, intro=self.__intro, outro=self.__outro): self.__progress_bar.display(log) if not os.path.isfile(os.path.join(self.__output_file_path, self.__output_video_file_name)): raise FFmpegProcessException self.__progress_bar.complete() print("----------------------------------------------------------") return True except FFmpegProcessException: Log.e(FFmpegProcessException.cause) self.__progress_bar.clear() return False def gen_thumbnail(self, time): """ Generates the thumbnail from the timestamps. Since, the timestamps contains the best of all the video, so picking a random int (sec) from a video and saving the frame as the thumbnail, Later some kind of peak rank from the input data can be picked. Notes ----- To pick the max rank we can use the sum rank and easily get the max value and use it to generate the thumbnail for the video. """ # call ffmpeg tool to merge the files try: self.__progress_bar = Progress() Log.i("Writing the output video file.") for log in thumbnail(os.path.join(self.__output_file_path, self.__input_file_name), os.path.join(self.__output_file_path, self.__thumbnail_file), time): self.__progress_bar.display(log) if not os.path.isfile(os.path.join(self.__output_file_path, self.__thumbnail_file)): raise FFmpegProcessException self.__progress_bar.complete() print("----------------------------------------------------------") return True except FFmpegProcessException: Log.e(FFmpegProcessException.cause) self.__progress_bar.clear() return False def clean_up(self): """ Deletes extra files created while processing, deletes the ranking files cache, etc. """ # processing is not yet started for something went wrong if self.__input_file_name is not None: # original audio split from the video file if os.path.isfile(os.path.join(self.__output_file_path, self.__input_audio_file_name)): os.unlink(os.path.join(self.__output_file_path, self.__input_audio_file_name)) # de-noised audio file output of Auditory if os.path.isfile(os.path.join(self.__output_file_path, self.__output_audio_file_name)): os.unlink(os.path.join(self.__output_file_path, self.__output_audio_file_name)) # cache storage file if os.path.isfile(os.path.join(CACHE_DIR, CACHE_NAME)): os.unlink(os.path.join(CACHE_DIR, CACHE_NAME)) del self.__progress_bar Log.d("Clean up completed.")
39.510638
125
0.627464
1,179
9,285
4.597964
0.164546
0.070836
0.055156
0.059768
0.4418
0.37613
0.353994
0.323372
0.290168
0.290168
0
0
0.287561
9,285
234
126
39.679487
0.819501
0.294561
0
0.339623
0
0
0.053498
0.028642
0
0
0
0
0
1
0.103774
false
0
0.056604
0
0.283019
0.028302
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30a405d600ad2e3396405bee7abf07a60fc56839
2,108
py
Python
plugins/callback/human.py
Benoth/projects-installer
0c657fd05c8fa4c38cee35fe3f6a98684a7eddc8
[ "MIT" ]
1
2018-01-04T06:54:32.000Z
2018-01-04T06:54:32.000Z
plugins/callback/human.py
Benoth/projects-installer
0c657fd05c8fa4c38cee35fe3f6a98684a7eddc8
[ "MIT" ]
null
null
null
plugins/callback/human.py
Benoth/projects-installer
0c657fd05c8fa4c38cee35fe3f6a98684a7eddc8
[ "MIT" ]
null
null
null
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.callback import CallbackBase from ansible.utils.color import stringc class CallbackModule(CallbackBase): CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'stdout' CALLBACK_NAME = 'human' def __init__(self): super(CallbackModule, self).__init__() self.line = "" def v2_runner_on_failed(self, result, ignore_errors=False): if 'exception' in result._result: if self._display.verbosity < 3: # extract just the actual error message from the exception text error = result._result['exception'].strip().split('\n')[-1] msg = "An exception occurred during task execution. To see the full traceback, use -vvv. The error was: %s" % error else: msg = "An exception occurred during task execution. The full traceback is:\n" + result._result['exception'] self._display.display("> " + msg, color='red') # finally, remove the exception from the result so it's not shown every time del result._result['exception'] self._display.display(" > %s" % (self._dump_results(result._result)), color='red') def v2_runner_on_ok(self, result): if result._result.get('changed', True): self._display.display(self.line, color='green') self._handle_warnings(result._result) self.line = "" def v2_runner_on_skipped(self, result): self.line = "" def v2_runner_on_unreachable(self, result): self._display.display(self.line + "> UNREACHABLE!", color='yellow') def v2_playbook_on_play_start(self, play): self._display.display(self.line + " RUNNING PLAYBOOK...", color='yellow') def v2_playbook_on_task_start(self, task, is_conditional): self.line = " " + task.get_name().strip() def v2_on_file_diff(self, result): if 'diff' in result._result: self._display.display(" " + self._get_diff(result._result['diff']))
38.327273
131
0.652277
262
2,108
4.984733
0.396947
0.082695
0.082695
0.039816
0.305513
0.219755
0.104135
0
0
0
0
0.007417
0.232448
2,108
54
132
39.037037
0.799753
0.078273
0
0.081081
0
0.027027
0.155235
0
0
0
0
0
0
1
0.216216
false
0
0.081081
0
0.405405
0.027027
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
0
0
0
1
30a54810ed9eb56db883cc95109f0ab931d09a5e
605
py
Python
COS120/testPlanet.py
thejayhaykid/Python
641c33b94762f0cace203dcf4cc121571625ab02
[ "MIT" ]
null
null
null
COS120/testPlanet.py
thejayhaykid/Python
641c33b94762f0cace203dcf4cc121571625ab02
[ "MIT" ]
null
null
null
COS120/testPlanet.py
thejayhaykid/Python
641c33b94762f0cace203dcf4cc121571625ab02
[ "MIT" ]
null
null
null
import planetClass def createSomePlanets(): aPlanet=planetClass.Planet("Zorks",2000,30000,100000,5) bPlanet=planetClass.Planet("Zapps",1000,20000,200000,17) print(aPlanet.getName() + " has a radius of " + str(aPlanet.getRadius())) planetList=[aPlanet,bPlanet] for planet in planetList: print(planet.getName() + " has a mass of " + str(planet.getMass())) for planet in planetList: print(planet.getName() + " has " + str(planet.getMoons()) + " moons.") print(bPlanet.getName() + " has a circumference of " + str(bPlanet.getCircumference())) createSomePlanets()
40.333333
91
0.680992
70
605
5.885714
0.485714
0.097087
0.080097
0.101942
0.203884
0.203884
0.203884
0.203884
0
0
0
0.065606
0.168595
605
14
92
43.214286
0.753479
0
0
0.166667
0
0
0.128926
0
0
0
0
0
0
1
0.083333
false
0
0.083333
0
0.166667
0.333333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30a588158c50b26b948593296dc5a892bedb5ede
101
py
Python
scripts/fastapi/escuelas.py
HighDeFing/thesis_v4
2dc9288af75a8b51fe54ed66f520e8aa8a0ab3c7
[ "Apache-2.0" ]
null
null
null
scripts/fastapi/escuelas.py
HighDeFing/thesis_v4
2dc9288af75a8b51fe54ed66f520e8aa8a0ab3c7
[ "Apache-2.0" ]
null
null
null
scripts/fastapi/escuelas.py
HighDeFing/thesis_v4
2dc9288af75a8b51fe54ed66f520e8aa8a0ab3c7
[ "Apache-2.0" ]
null
null
null
import json f = open('Thesis_v3/scripts/fastapi/web/static/data/escuelas.json') data = json.load(f)
20.2
67
0.752475
17
101
4.411765
0.764706
0
0
0
0
0
0
0
0
0
0
0.01087
0.089109
101
4
68
25.25
0.804348
0
0
0
0
0
0.544554
0.544554
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
1
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
30a7222ecfe5a24f86695b0a4cf26331038a5731
1,410
py
Python
Source/mincost.py
aarsheem/696-ds
2d74b1e3f430e369202982d7ad8c56f362b00f76
[ "MIT" ]
2
2020-02-12T22:56:40.000Z
2020-02-17T16:59:05.000Z
Source/mincost.py
aarsheem/696-ds
2d74b1e3f430e369202982d7ad8c56f362b00f76
[ "MIT" ]
null
null
null
Source/mincost.py
aarsheem/696-ds
2d74b1e3f430e369202982d7ad8c56f362b00f76
[ "MIT" ]
2
2020-02-12T17:25:33.000Z
2021-02-01T20:29:17.000Z
import numpy as np from systemrl.agents.q_learning import QLearning import matplotlib.pyplot as plt from helper import decaying_epsilon, evaluate_interventions from tqdm import tqdm #This is not converging def mincost(env, human_policy, min_performance, agent, num_episodes=1000, max_steps=1000): print("mincost") episode_returns_ = [] for episodes in tqdm(range(num_episodes)): env.reset() state = env.state is_end = False returns = 0 returns_ = 0 count = 0 epsilon = decaying_epsilon(episodes, num_episodes) while not is_end and count < max_steps: count += 1 if np.random.random() < epsilon: action = np.random.randint(agent.num_actions) else: action = agent.get_action(state) next_state, reward, is_end = env.step(action) returns += reward if is_end == True or count >= max_steps: if returns < min_performance: reward_ = -100 elif action == human_policy[state]: reward_ = 0 else: reward_ = -1 agent.train(state, action, reward_, next_state) state = next_state returns_ += reward_ episode_returns_.append(returns_) return evaluate_interventions(env, human_policy, agent)
32.790698
90
0.595745
161
1,410
4.987578
0.42236
0.024907
0.034869
0
0
0
0
0
0
0
0
0.018028
0.331206
1,410
42
91
33.571429
0.83351
0.015603
0
0.055556
0
0
0.005047
0
0
0
0
0
0
1
0.027778
false
0
0.138889
0
0.194444
0.027778
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30a791a26136890491f10b4931b42e8e670355a5
2,076
py
Python
server/algorithms.py
sebastianfrey/geoio-server
2f127244adda96d54e7a082f8514f9bdc9c8db97
[ "MIT" ]
null
null
null
server/algorithms.py
sebastianfrey/geoio-server
2f127244adda96d54e7a082f8514f9bdc9c8db97
[ "MIT" ]
null
null
null
server/algorithms.py
sebastianfrey/geoio-server
2f127244adda96d54e7a082f8514f9bdc9c8db97
[ "MIT" ]
null
null
null
"""All algorithms used by geoio-server""" import math import functools import geojson def angle(point_1, point_2): """calculates the angle between two points in radians""" return math.atan2(point_2[1] - point_1[1], point_2[0] - point_1[0]) def convex_hull(collection): """Calculates the convex hull of an geojson feature collection.""" features_or_geometries = [] if collection["type"] == "GeometryCollection": features_or_geometries = collection["geometries"] elif collection["type"] == "FeatureCollection": features_or_geometries = collection["features"] if features_or_geometries is None or len(features_or_geometries) == 0: raise Exception("No features or geometries where found") features_or_geometries_mapper = lambda feature_or_geometry: list(geojson.utils.coords(feature_or_geometry)) coordinates_reducer = lambda a, b: a + b coordinates_list = list(map(features_or_geometries_mapper, features_or_geometries)) points = list(functools.reduce(coordinates_reducer, coordinates_list)) if len(points) < 3: raise Exception("Can not calculate convex hull of less then 3 input points.") points = list(set(points)) points = sorted(points, key=lambda point: (point[1], point[0])) point0 = points.pop(0) points = list(map(lambda point: (point[0], point[1], angle(point0, point)), points)) points = list(sorted(points, key=lambda point: point[2])) points.insert(0, point0) hull = [points[0], (points[1][0], points[1][1])] i = 2 points_count = len(points) while i < points_count: stack_length = len(hull) point_1 = hull[stack_length-1] point_2 = hull[stack_length-2] point_i = points[i] discrimnante = (point_2[0] - point_1[0]) * (point_i[1] - point_1[1]) - (point_i[0] - point_1[0]) * (point_2[1] - point_1[1]) if discrimnante < 0 or stack_length == 2: hull.append((point_i[0], point_i[1])) i = i+1 else: hull.pop() return geojson.Polygon(hull)
32.952381
132
0.66474
286
2,076
4.643357
0.283217
0.045181
0.135542
0.018072
0.108434
0.088855
0
0
0
0
0
0.032297
0.209538
2,076
62
133
33.483871
0.776965
0.070809
0
0
0
0
0.081547
0
0
0
0
0
0
1
0.05
false
0
0.075
0
0.175
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30a8e19c8a3340ed914debb399aef2df50e28dac
2,495
py
Python
First Project/Exercise2/modified_bisection.py
TasosOperatingInBinary/Numerical-Analysis-Projects
61a8014f2b853a646145cea5a4d3655e100be854
[ "MIT" ]
null
null
null
First Project/Exercise2/modified_bisection.py
TasosOperatingInBinary/Numerical-Analysis-Projects
61a8014f2b853a646145cea5a4d3655e100be854
[ "MIT" ]
null
null
null
First Project/Exercise2/modified_bisection.py
TasosOperatingInBinary/Numerical-Analysis-Projects
61a8014f2b853a646145cea5a4d3655e100be854
[ "MIT" ]
null
null
null
import numpy as np def modified_bisection(f, a, b, eps=5e-6): """ Function that finds a root using modified Bisection method for a given function f(x). On each iteration instead of the middle of the interval, a random number is chosen as the next guess for the root. The function finds the root of f(x) with a predefined absolute accuracy epsilon. The function excepts an interval [a,b] in which is known that the function f has a root. If the function f has multiple roots in this interval then Bisection method converges randomly to one of them. If in the interval [a,b] f(x) doesn't change sign (Bolzano theorem can not be applied) the function returns nan as root and -1 as the number of iterations.Also the function checks if either a or b is a root of f(x), if both are then the function returns the value of a. Parameters ---------- f : callable The function to find a root of. a : float The start of the initial interval in which the function will find the root of f(x). b : float The end of the initial interval in which the function will find the root of f(x). eps : float The target accuracy. The iteration stops when the length of the current interval divided by 2 to the power of n+1 is below eps. Default value is 5e-6. Returns ------- root : float The estimated value for the root. iterations_num : int The number of iterations. """ # check if Bolzano theorem can not be applied or a is larger than b if f(a) * f(b) > 0 or a > b: return np.nan, -1 elif f(a) == 0: # check if a is root of f return a, 0 elif f(b) == 0: # or b is root of f return b, 0 # Modified Bisection algorithm iterations_num = 0 while abs(b - a) >= eps: current_root = np.random.uniform(a, b) # each iteration root approximation is a random number from a uniform # distribution if f(a) * f(current_root) < 0: # find out where Bolzano theorem still can be applied and update the interval # [a,b] b = current_root else: a = current_root iterations_num += 1 current_root = np.random.uniform(a, b) return current_root, iterations_num
42.288136
119
0.600401
382
2,495
3.89267
0.314136
0.073974
0.028245
0.02152
0.180901
0.153329
0.114324
0.076664
0.076664
0.076664
0
0.009744
0.341884
2,495
58
120
43.017241
0.895859
0.676553
0
0.111111
0
0
0
0
0
0
0
0
0
1
0.055556
false
0
0.055556
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
0
0
0
0
0
0
0
0
0
1
0
30a910ea0718b3060e358f1839e61f48a5b25649
8,454
py
Python
dynamic_forms/models.py
juandisay/django-dynamic-forms
761bfea5332fbd4d247a0fa55a19cfc0dd36e3c8
[ "BSD-3-Clause" ]
135
2015-01-16T08:14:23.000Z
2021-12-22T07:21:37.000Z
dynamic_forms/models.py
ayoub-root/django-dynamic-forms
614b9a06f6edfeb3349b7e64cc8820e56535ad59
[ "BSD-3-Clause" ]
33
2015-01-18T13:24:00.000Z
2019-05-03T12:26:17.000Z
dynamic_forms/models.py
ayoub-root/django-dynamic-forms
614b9a06f6edfeb3349b7e64cc8820e56535ad59
[ "BSD-3-Clause" ]
48
2015-01-20T20:04:20.000Z
2022-01-06T10:02:57.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from collections import OrderedDict from django.core.urlresolvers import reverse from django.db import models from django.db.transaction import atomic from django.template.defaultfilters import slugify from django.utils.crypto import get_random_string from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.html import format_html, format_html_join from django.utils.translation import ugettext_lazy as _ from dynamic_forms.actions import action_registry from dynamic_forms.conf import settings from dynamic_forms.fields import TextMultiSelectField from dynamic_forms.formfields import formfield_registry @python_2_unicode_compatible class FormModel(models.Model): name = models.CharField(_('Name'), max_length=50, unique=True) submit_url = models.CharField(_('Submit URL'), max_length=100, unique=True, help_text=_('The full URL path to the form. It should start ' 'and end with a forward slash (<code>/</code>).')) success_url = models.CharField(_('Success URL'), max_length=100, help_text=_('The full URL path where the user will be ' 'redirected after successfully sending the form. It should start ' 'and end with a forward slash (<code>/</code>). If empty, the ' 'success URL is generated by appending <code>done/</code> to the ' '“Submit URL”.'), blank=True, default='') actions = TextMultiSelectField(_('Actions'), default='', choices=action_registry.get_as_choices()) form_template = models.CharField(_('Form template path'), max_length=100, default='dynamic_forms/form.html', choices=settings.DYNAMIC_FORMS_FORM_TEMPLATES) success_template = models.CharField(_('Success template path'), max_length=100, default='dynamic_forms/form_success.html', choices=settings.DYNAMIC_FORMS_SUCCESS_TEMPLATES) allow_display = models.BooleanField(_('Allow display'), default=False, help_text=_('Allow a user to view the input at a later time. This ' 'requires the “Store in database” action to be active. The sender ' 'will be given a unique URL to recall the data.')) recipient_email = models.EmailField(_('Recipient email'), blank=True, null=True, help_text=_('Email address to send form data.')) class Meta: ordering = ['name'] verbose_name = _('Dynamic form') verbose_name_plural = _('Dynamic forms') def __str__(self): return self.name def get_fields_as_dict(self): """ Returns an ``OrderedDict`` (``SortedDict`` when ``OrderedDict is not available) with all fields associated with this form where their name is the key and their label is the value. """ return OrderedDict(self.fields.values_list('name', 'label').all()) def save(self, *args, **kwargs): """ Makes sure that the ``submit_url`` and -- if defined the ``success_url`` -- end with a forward slash (``'/'``). """ if not self.submit_url.endswith('/'): self.submit_url = self.submit_url + '/' if self.success_url: if not self.success_url.endswith('/'): self.success_url = self.success_url + '/' else: self.success_url = self.submit_url + 'done/' super(FormModel, self).save(*args, **kwargs) @python_2_unicode_compatible class FormFieldModel(models.Model): parent_form = models.ForeignKey(FormModel, on_delete=models.CASCADE, related_name='fields') field_type = models.CharField(_('Type'), max_length=255, choices=formfield_registry.get_as_choices()) label = models.CharField(_('Label'), max_length=255) name = models.SlugField(_('Name'), max_length=50, blank=True) _options = models.TextField(_('Options'), blank=True, null=True) position = models.SmallIntegerField(_('Position'), blank=True, default=0) class Meta: ordering = ['parent_form', 'position'] unique_together = ("parent_form", "name",) verbose_name = _('Form field') verbose_name_plural = _('Form fields') def __str__(self): return _('Field “%(field_name)s” in form “%(form_name)s”') % { 'field_name': self.label, 'form_name': self.parent_form.name, } def generate_form_field(self, form): field_type_cls = formfield_registry.get(self.field_type) field = field_type_cls(**self.get_form_field_kwargs()) field.contribute_to_form(form) return field def get_form_field_kwargs(self): kwargs = self.options kwargs.update({ 'name': self.name, 'label': self.label, }) return kwargs @property def options(self): """Options passed to the form field during construction.""" if not hasattr(self, '_options_cached'): self._options_cached = {} if self._options: try: self._options_cached = json.loads(self._options) except ValueError: pass return self._options_cached @options.setter def options(self, opts): if hasattr(self, '_options_cached'): del self._options_cached self._options = json.dumps(opts) def save(self, *args, **kwargs): if not self.name: self.name = slugify(self.label) given_options = self.options field_type_cls = formfield_registry.get(self.field_type) invalid = set(self.options.keys()) - set(field_type_cls._meta.keys()) if invalid: for key in invalid: del given_options[key] self.options = given_options super(FormFieldModel, self).save(*args, **kwargs) @python_2_unicode_compatible class FormModelData(models.Model): form = models.ForeignKey(FormModel, on_delete=models.SET_NULL, related_name='data', null=True) value = models.TextField(_('Form data'), blank=True, default='') submitted = models.DateTimeField(_('Submitted on'), auto_now_add=True) display_key = models.CharField(_('Display key'), max_length=24, null=True, blank=True, db_index=True, default=None, unique=True, help_text=_('A unique identifier that is used to allow users to view ' 'their sent data. Unique over all stored data sets.')) class Meta: verbose_name = _('Form data') verbose_name_plural = _('Form data') def __str__(self): return _('Form: “%(form)s” on %(date)s') % { 'form': self.form, 'date': self.submitted, } def save(self, *args, **kwargs): with atomic(): if self.form.allow_display and not self.display_key: dk = get_random_string(24) while FormModelData.objects.filter(display_key=dk).exists(): dk = get_random_string(24) self.display_key = dk super(FormModelData, self).save(*args, **kwargs) @property def json_value(self): return OrderedDict(sorted(json.loads(self.value).items())) def pretty_value(self): try: value = format_html_join('', '<dt>{0}</dt><dd>{1}</dd>', ( (force_text(k), force_text(v)) for k, v in self.json_value.items() ) ) return format_html('<dl>{0}</dl>', value) except ValueError: return self.value pretty_value.allow_tags = True @property def show_url(self): """ If the form this data set belongs to has :attr:`~FormModel.allow_display` ``== True``, return the permanent URL. If displaying is not allowed, return an empty string. """ if self.form.allow_display: return reverse('dynamic_forms:data-set-detail', kwargs={'display_key': self.display_key}) return '' @property def show_url_link(self): """ Similar to :attr:`show_url` but wraps the display key in an `<a>`-tag linking to the permanent URL. """ if self.form.allow_display: return format_html('<a href="{0}">{1}</a>', self.show_url, self.display_key) return ''
38.427273
88
0.62917
1,028
8,454
4.957198
0.2393
0.03022
0.020016
0.018838
0.167975
0.111068
0.091444
0.074568
0.074568
0.020016
0
0.006209
0.257038
8,454
219
89
38.60274
0.805127
0.075112
0
0.16568
0
0
0.158738
0.013945
0
0
0
0
0
1
0.088757
false
0.005917
0.088757
0.023669
0.402367
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30a9ab75ade2dbd70c38b6cd9c991c10b08234de
1,215
py
Python
banshee/tests/pta-bt-test.py
CARV-ICS-FORTH/scoop
9fbd86629a7e1951a392959149bb553fb5611a5f
[ "Apache-2.0" ]
2
2017-02-15T23:36:49.000Z
2018-09-11T09:34:14.000Z
banshee/tests/pta-bt-test.py
CARV-ICS-FORTH/scoop
9fbd86629a7e1951a392959149bb553fb5611a5f
[ "Apache-2.0" ]
null
null
null
banshee/tests/pta-bt-test.py
CARV-ICS-FORTH/scoop
9fbd86629a7e1951a392959149bb553fb5611a5f
[ "Apache-2.0" ]
2
2015-10-15T07:41:09.000Z
2019-10-08T12:55:13.000Z
#!/usr/bin/python import sys import os import string #print sys.argv frontend = "../cparser/parser.exe" flags = "-fprint-results" pta_cmd = "%s %s" % (frontend, flags) prefix = "" prefix_size = int(sys.argv[1]) for x in sys.argv[2:(2+prefix_size)]: prefix = " %s %s" % (prefix, x) filelist = "" for x in sys.argv[2:]: filelist = "%s %s" % (filelist, x) # this computes the points to set size for the prefix list output = os.popen(pta_cmd + prefix + " 2> /dev/null | grep \"Number of things pointed to:\" ") try: total = int(string.split((output.readlines()[0]))[5]) except: sys.stderr.write("Warning: failed to analyze some files\n") exit output = os.popen(pta_cmd + filelist + (" -fbt%d" %prefix_size) + " 2> /dev/null | grep \"Number of things pointed to:\" ") try: total2 = int(string.split((output.readlines()[0]))[5]) except: sys.stderr.write("Warning: failed to analyze some files\n") exit print "Total number of things pointed to (%d files): %d" % (prefix_size,total) print "Total number of things pointed to (%d files): with backtracking: %d" % (prefix_size,total2) if (total != total2): print "A backtracking test failed" sys.exit(1) else: sys.exit(0)
27
123
0.652675
188
1,215
4.175532
0.367021
0.063694
0.071338
0.107006
0.501911
0.453503
0.417834
0.417834
0.417834
0.318471
0
0.015075
0.18107
1,215
44
124
27.613636
0.773869
0.071605
0
0.25
0
0
0.288
0.018667
0
0
0
0
0
0
null
null
0
0.09375
null
null
0.125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
30abf6ce8fba41eb376313eba17a397685a314e9
29,178
py
Python
src/pumpwood_djangoviews/views.py
Murabei-OpenSource-Codes/pumpwood-djangoviews
792fb825a5e924d1b7307c0bc3b40d798b68946d
[ "BSD-3-Clause" ]
null
null
null
src/pumpwood_djangoviews/views.py
Murabei-OpenSource-Codes/pumpwood-djangoviews
792fb825a5e924d1b7307c0bc3b40d798b68946d
[ "BSD-3-Clause" ]
null
null
null
src/pumpwood_djangoviews/views.py
Murabei-OpenSource-Codes/pumpwood-djangoviews
792fb825a5e924d1b7307c0bc3b40d798b68946d
[ "BSD-3-Clause" ]
null
null
null
"""Create views using Pumpwood pattern.""" import os import pandas as pd import simplejson as json from io import BytesIO from django.conf import settings from django.http import HttpResponse from rest_framework.parsers import JSONParser from rest_framework import viewsets, status from rest_framework.response import Response from werkzeug.utils import secure_filename from pumpwood_communication import exceptions from pumpwood_communication.serializers import PumpWoodJSONEncoder from django.db.models.fields import NOT_PROVIDED from pumpwood_djangoviews.renderer import PumpwoodJSONRenderer from pumpwood_djangoviews.query import filter_by_dict from pumpwood_djangoviews.action import load_action_parameters from pumpwood_djangoviews.aux.map_django_types import django_map from django.db.models.fields.files import FieldFile def save_serializer_instance(serializer_instance): is_valid = serializer_instance.is_valid() if is_valid: return serializer_instance.save() else: raise exceptions.PumpWoodException(serializer_instance.errors) class PumpWoodRestService(viewsets.ViewSet): """Basic View-Set for pumpwood rest end-points.""" _view_type = "simple" renderer_classes = [PumpwoodJSONRenderer] ##################### # Route information # endpoint_description = None dimentions = {} icon = None ##################### service_model = None storage_object = None microservice = None trigger = False # List fields serializer = None list_fields = None foreign_keys = {} file_fields = {} # Front-end uses 50 as limit to check if all data have been fetched, # if change this parameter, be sure to update front-end list component. list_paginate_limit = 50 @staticmethod def _allowed_extension(filename, allowed_extensions): extension = 'none' if '.' in filename: extension = filename.rsplit('.', 1)[1].lower() if "*" not in allowed_extensions: if extension not in allowed_extensions: return [( "File {filename} with extension {extension} not " + "allowed.\n Allowed extensions: {allowed_extensions}" ).format(filename=filename, extension=extension, allowed_extensions=str(allowed_extensions))] return [] def list(self, request): """ View function to list objects with pagination. Number of objects are limited by settings.REST_FRAMEWORK['PAGINATE_BY']. To get next page, use exclude_dict['pk__in': [list of the received pks]] to get more objects. Use to limit the query .query.filter_by_dict function. :param request.data['filter_dict']: Dictionary passed as objects.filter(**filter_dict) :type request.data['filter_dict']: dict :param request.data['exclude_dict']: Dictionary passed as objects.exclude(**exclude_dict) :type request.data['exclude_dict']: dict :param request.data['order_by']: List passed as objects.order_by(*order_by) :type request.data['order_by']: list :return: A list of objects using list_serializer """ try: request_data = request.data limit = request_data.pop("limit", None) list_paginate_limit = limit or self.list_paginate_limit fields = request_data.pop("fields", None) list_fields = fields or self.list_fields arg_dict = {'query_set': self.service_model.objects.all()} arg_dict.update(request_data) query_set = filter_by_dict(**arg_dict)[:list_paginate_limit] return Response(self.serializer( query_set, many=True, fields=list_fields).data) except TypeError as e: raise exceptions.PumpWoodQueryException(message=str(e)) def list_without_pag(self, request): """List data without pagination. View function to list objects. Basicaley the same of list, but without limitation by settings.REST_FRAMEWORK['PAGINATE_BY']. :param request.data['filter_dict']: Dictionary passed as objects.filter(**filter_dict) :type request.data['filter_dict']: dict :param request.data['exclude_dict']: Dictionary passed as objects.exclude(**exclude_dict) :type request.data['exclude_dict']: dict :param request.data['order_by']: List passed as objects.order_by(*order_by) :type request.data['order_by']: list :return: A list of objects using list_serializer .. note:: Be careful with the number of the objects that will be retrieved """ try: request_data = request.data fields = request_data.pop("fields", None) list_fields = fields or self.list_fields arg_dict = {'query_set': self.service_model.objects.all()} arg_dict.update(request_data) query_set = filter_by_dict(**arg_dict) return Response(self.serializer( query_set, many=True, fields=list_fields).data) except TypeError as e: raise exceptions.PumpWoodQueryException( message=str(e)) def retrieve(self, request, pk=None): """ Retrieve view, uses the retrive_serializer to return object with pk. :param int pk: Object pk to be retrieve :return: The representation of the object passed by self.retrive_serializer :rtype: dict """ obj = self.service_model.objects.get(pk=pk) return Response(self.serializer(obj, many=False).data) def retrieve_file(self, request, pk: int): """ Read file without stream. Args: pk (int): Pk of the object to save file field. file_field(str): File field to receive stream file. Returns: A stream of bytes with da file. """ if self.storage_object is None: raise exceptions.PumpWoodForbidden( "storage_object not set") file_field = request.query_params.get('file-field', None) if file_field not in self.file_fields.keys(): msg = ( "'{file_field}' must be set on file_fields " "dictionary.").format(file_field=file_field) raise exceptions.PumpWoodForbidden(msg) obj = self.service_model.objects.get(id=pk) file_path = getattr(obj, file_field) if isinstance(file_path, FieldFile): file_path = file_path.name if file_path is None: raise exceptions.PumpWoodObjectDoesNotExist( "field [{}] not found at object".format(file_field)) file_data = self.storage_object.read_file(file_path) file_name = os.path.basename(file_path) response = HttpResponse(content=BytesIO(file_data["data"])) response['Content-Type'] = file_data["content_type"] response['Content-Disposition'] = \ 'attachment; filename=%s' % file_name return response def delete(self, request, pk=None): """ Delete view. :param int pk: Object pk to be retrieve """ obj = self.service_model.objects.get(pk=pk) return_data = self.serializer(obj, many=False).data obj.delete() return Response(return_data, status=200) def delete_many(self, request): """ Delete many data using filter. :param request.data['filter_dict']: Dictionary passed as objects.filter(**filter_dict) :type request.data['filter_dict']: dict :param request.data['exclude_dict']: Dictionary passed as objects.exclude(**exclude_dict) :type request.data['exclude_dict']: dict :return: True if delete is ok """ try: arg_dict = {'query_set': self.service_model.objects.all()} arg_dict.update(request.data) query_set = filter_by_dict(**arg_dict) query_set.delete() return Response(True, status=200) except TypeError as e: raise exceptions.PumpWoodQueryException( message=str(e)) def remove_file_field(self, request, pk: int) -> bool: """ Remove file field. Args: pk (int): pk of the object. Kwargs: No kwargs for this function. Raises: PumpWoodForbidden: If file_file is not in file_fields keys of the view. PumpWoodException: Propagates exceptions from storage_objects. """ file_field = request.query_params.get('file_field', None) if file_field not in self.file_fields.keys(): raise exceptions.PumpWoodForbidden( "file_field must be set on self.file_fields dictionary.") obj = self.service_model.objects.get(id=pk) file = getattr(obj, file_field) if file is None: raise exceptions.PumpWoodObjectDoesNotExist( "field [{}] not found at object".format(file_field)) else: file_path = file.name setattr(obj, file_field, None) obj.save() try: self.storage_object.delete_file(file_path) return Response(True) except Exception as e: raise exceptions.PumpWoodException(str(e)) def save(self, request): """ Save and update object acording to request.data. Object will be updated if request.data['pk'] is not None. :param dict request.data: Object representation as self.retrive_serializer :raise PumpWoodException: 'Object model class diferent from {service_model} : {service_model}' request.data['service_model'] not the same as self.service_model.__name__ """ request_data: dict = None if "application/json" in request.content_type.lower(): request_data = request.data else: request_data = request.data.dict() for k in request_data.keys(): if k not in self.file_fields.keys(): request_data[k] = json.loads(request_data[k]) data_pk = request_data.get('pk') saved_obj = None for field in self.file_fields.keys(): request_data.pop(field, None) # update if data_pk: data_to_update = self.service_model.objects.get(pk=data_pk) serializer = self.serializer( data_to_update, data=request_data, context={'request': request}) saved_obj = save_serializer_instance(serializer) response_status = status.HTTP_200_OK # save else: serializer = self.serializer( data=request_data, context={'request': request}) saved_obj = save_serializer_instance(serializer) response_status = status.HTTP_201_CREATED # Uploading files object_errors = {} for field in self.file_fields.keys(): field_errors = [] if field in request.FILES: file = request.FILES[field] file_name = secure_filename(file.name) field_errors.extend(self._allowed_extension( filename=file_name, allowed_extensions=self.file_fields[field])) filename = "{}___{}".format(saved_obj.id, file_name) if len(field_errors) != 0: object_errors[field] = field_errors else: model_class = self.service_model.__name__.lower() file_path = '{model_class}__{field}/'.format( model_class=model_class, field=field) storage_filepath = self.storage_object.write_file( file_path=file_path, file_name=filename, data=file.read(), content_type=file.content_type, if_exists='overide') setattr(saved_obj, field, storage_filepath) if object_errors != {}: message = "error when saving object: " \ if data_pk is None else "error when updating object: " payload = object_errors message_to_append = [] for key, value in object_errors.items(): message_to_append.append(key + ", " + str(value)) message = message + "; ".join(message_to_append) raise exceptions.PumpWoodObjectSavingException( message=message, payload=payload) saved_obj.save() if self.microservice is not None and self.trigger: # Process ETLTrigger for the model class self.microservice.login() if data_pk is None: self.microservice.execute_action( "ETLTrigger", action="process_triggers", parameters={ "model_class": self.service_model.__name__.lower(), "type": "create", "pk": None, "action_name": None}) else: self.microservice.execute_action( "ETLTrigger", action="process_triggers", parameters={ "model_class": self.service_model.__name__.lower(), "type": "update", "pk": saved_obj.pk, "action_name": None}) # Overhead, serializando e deserializando o objecto return Response( self.serializer(saved_obj).data, status=response_status) def get_actions(self): """Get all actions with action decorator.""" # this import works here only import inspect function_dict = dict(inspect.getmembers( self.service_model, predicate=inspect.isfunction)) method_dict = dict(inspect.getmembers( self.service_model, predicate=inspect.ismethod)) method_dict.update(function_dict) actions = { name: func for name, func in method_dict.items() if getattr(func, 'is_action', False)} return actions def list_actions(self, request): """List model exposed actions.""" actions = self.get_actions() action_descriptions = [ action.action_object.to_dict() for name, action in actions.items()] return Response(action_descriptions) def list_actions_with_objects(self, request): """List model exposed actions acording to selected objects.""" actions = self.get_actions() action_descriptions = [ action.action_object.description for name, action in actions.items()] return Response(action_descriptions) def execute_action(self, request, action_name, pk=None): """Execute action over object or class using parameters.""" parameters = request.data actions = self.get_actions() rest_action_names = list(actions.keys()) if action_name not in rest_action_names: message = ( "There is no method {action} in rest actions " "for {class_name}").format( action=action_name, class_name=self.service_model.__name__) raise exceptions.PumpWoodForbidden( message=message, payload={"action_name": action_name}) action = getattr(self.service_model, action_name) if pk is None and not action.action_object.is_static_function: msg_template = ( "Action [{action}] at model [{class_name}] is not " "a classmethod and not pk provided.") message = msg_template.format( action=action_name, class_name=self.service_model.__name__) raise exceptions.PumpWoodActionArgsException( message=message, payload={"action_name": action_name}) if pk is not None and action.action_object.is_static_function: msg_template = ( "Action [{action}] at model [{class_name}] is a" "classmethod and pk provided.") message = msg_template.format( action=action_name, class_name=self.service_model.__name__) raise exceptions.PumpWoodActionArgsException( message=message, payload={"action_name": action_name}) object_dict = None action = None if pk is not None: model_object = self.service_model.objects.filter(pk=pk).first() if model_object is None: message_template = ( "Requested object {service_model}[{pk}] not found.") temp_service_model = \ self.service_model.__name__ message = message_template.format( service_model=temp_service_model, pk=pk) raise exceptions.PumpWoodObjectDoesNotExist( message=message, payload={ "service_model": temp_service_model, "pk": pk}) action = getattr(model_object, action_name) object_dict = self.serializer( model_object, many=False, fields=self.list_fields).data else: action = getattr(self.service_model, action_name) loaded_parameters = load_action_parameters(action, parameters, request) result = action(**loaded_parameters) if self.microservice is not None and self.trigger: self.microservice.login() self.microservice.execute_action( "ETLTrigger", action="process_triggers", parameters={ "model_class": self.service_model.__name__.lower(), "type": "action", "pk": pk, "action_name": action_name}) return Response({ 'result': result, 'action': action_name, 'parameters': parameters, 'object': object_dict}) @classmethod def cls_search_options(cls): fields = cls.service_model._meta.get_fields() all_info = {} # f = fields[10] for f in fields: column_info = {} ################################################################ # Do not create relations between models in search description # is_relation = getattr(f, "is_relation", False) if is_relation: continue ################################################################ # Getting correspondent simple type column_type = f.get_internal_type() python_type = django_map.get(column_type) if python_type is None: msg = ( "Type [{column_type}] not implemented in map dictionary " "django type -> python type") raise NotImplementedError( msg.format(column_type=column_type)) # Getting default value default = None f_default = getattr(f, 'default', None) if f_default != NOT_PROVIDED and f_default is not None: if callable(f_default): default = f_default() else: default = f_default primary_key = getattr(f, "primary_key", False) help_text = str(getattr(f, "help_text", "")) db_index = getattr(f, "db_index", False) unique = getattr(f, "unique", False) column = None if primary_key: column = "pk" else: column = f.column column_info = { 'primary_key': primary_key, "column": column, "doc_string": help_text, "type": python_type, "nullable": f.null, "default": default, "indexed": db_index or primary_key, "unique": unique} # Get choice options if avaiable choices = getattr(f, "choices", None) if choices is not None: column_info["type"] = "options" column_info["in"] = [ {"value": choice[0], "description": choice[1]} for choice in choices] # Set autoincrement for primary keys if primary_key: column_info["column"] = "pk" column_info["default"] = "#autoincrement#" column_info["doc_string"] = "object primary key" # Ajust type if file file_field = cls.file_fields.get(column) if file_field is not None: column_info["type"] = "file" column_info["permited_file_types"] = file_field all_info[column] = column_info # Adding description for foreign keys for key, item in cls.foreign_keys.items(): column = getattr(cls.service_model, key, None) if column is None: msg = ( "Foreign Key incorrectly configured at Pumpwood View. " "[{key}] not found on [{model}]").format( key=key, model=str(cls.service_model)) raise Exception(msg) primary_key = getattr(column.field, "primary_key", False) help_text = str(getattr(column.field, "help_text", "")) db_index = getattr(column.field, "db_index", False) unique = getattr(column.field, "unique", False) null = getattr(column.field, "null", False) # Getting default value default = None f_default = getattr(f, 'default', None) if f_default != NOT_PROVIDED and f_default is not None: if callable(f_default): default = f_default() else: default = f_default column_info = { 'primary_key': primary_key, "column": key, "doc_string": help_text, "type": "foreign_key", "nullable": null, "default": default, "indexed": db_index or primary_key, "unique": unique} if isinstance(item, dict): column_info["model_class"] = item["model_class"] column_info["many"] = item["many"] elif isinstance(item, str): column_info["model_class"] = item column_info["many"] = False else: msg = ( "foreign_key not correctly defined, check column" "[{key}] from model [{model}]").format( key=key, model=str(cls.service_model)) raise Exception(msg) all_info[key] = column_info return all_info def search_options(self, request): """ Return options to be used in list funciton. :return: Dictionary with options for list parameters :rtype: dict .. note:: Must be implemented """ return Response(self.cls_search_options()) def fill_options(self, request): """ Return options for object update acording its partial data. :param dict request.data: Partial object data. :return: A dictionary with options for diferent objects values :rtype: dict .. note:: Must be implemented """ return Response(self.cls_search_options()) class PumpWoodDataBaseRestService(PumpWoodRestService): """This view extends PumpWoodRestService, including pivot function.""" _view_type = "data" model_variables = [] """Specify which model variables will be returned in pivot. Line index are the model_variables - columns (function pivot parameter) itens.""" expected_cols_bulk_save = [] """Set the collumns needed at bulk_save.""" def pivot(self, request): """ Pivot QuerySet data acording to columns selected, and filters passed. :param request.data['filter_dict']: Dictionary passed as objects.filter(**filter_dict) :type request.data['filter_dict']: dict :param request.data['exclude_dict']: Dictionary passed as objects.exclude(**exclude_dict) :type request.data['exclude_dict']: dict :param request.data['order_by']: List passed as objects.order_by(*order_by) :type request.data['order_by']: list :param request.data['columns']: Variables to be used as pivot collumns :type request.data['columns']: list :param request.data['format']: Format used in pandas.DataFrame().to_dict() :type request.data['columns']: str :return: Return database data pivoted acording to columns parameter :rtyoe: panas.Dataframe converted to disctionary """ columns = request.data.get('columns', []) format = request.data.get('format', 'list') model_variables = request.data.get('variables') show_deleted = request.data.get('show_deleted', False) model_variables = model_variables or self.model_variables if type(columns) != list: raise exceptions.PumpWoodException( 'Columns must be a list of elements.') if len(set(columns) - set(model_variables)) != 0: raise exceptions.PumpWoodException( 'Column chosen as pivot is not at model variables') index = list(set(model_variables) - set(columns)) filter_dict = request.data.get('filter_dict', {}) exclude_dict = request.data.get('exclude_dict', {}) order_by = request.data.get('order_by', {}) if hasattr(self.service_model, 'deleted'): if not show_deleted: filter_dict["deleted"] = False arg_dict = {'query_set': self.service_model.objects.all(), 'filter_dict': filter_dict, 'exclude_dict': exclude_dict, 'order_by': order_by} query_set = filter_by_dict(**arg_dict) try: filtered_objects_as_list = list( query_set.values_list(*(model_variables))) except TypeError as e: raise exceptions.PumpWoodQueryException(message=str(e)) melted_data = pd.DataFrame( filtered_objects_as_list, columns=model_variables) if len(columns) == 0: return Response(melted_data.to_dict(format)) if melted_data.shape[0] == 0: return Response({}) else: if "value" not in melted_data.columns: raise exceptions.PumpWoodException( "'value' column not at melted data, it is not possible" " to pivot dataframe.") pivoted_table = pd.pivot_table( melted_data, values='value', index=index, columns=columns, aggfunc=lambda x: tuple(x)[0]) return Response( pivoted_table.reset_index().to_dict(format)) def bulk_save(self, request): """ Bulk save data. Args: data_to_save(list): List of dictionaries which must have self.expected_cols_bulk_save. Return: dict: ['saved_count']: total of saved objects. """ data_to_save = request.data if data_to_save is None: raise exceptions.PumpWoodException( 'Post payload must have data_to_save key.') if len(self.expected_cols_bulk_save) == 0: raise exceptions.PumpWoodException('Bulk save not avaiable.') pd_data_to_save = pd.DataFrame(data_to_save) pd_data_cols = set(list(pd_data_to_save.columns)) if len(set(self.expected_cols_bulk_save) - pd_data_cols) == 0: objects_to_load = [] for d in data_to_save: new_obj = self.service_model(**d) objects_to_load.append(new_obj) self.service_model.objects.bulk_create(objects_to_load) return Response({'saved_count': len(objects_to_load)}) else: template = 'Expected columns and data columns do not match:' + \ '\nExpected columns:{expected}' + \ '\nData columns:{data_cols}' raise exceptions.PumpWoodException(template.format( expected=set(self.expected_cols_bulk_save), data_cols=pd_data_cols,))
38.955941
79
0.579512
3,136
29,178
5.185906
0.122449
0.041936
0.02558
0.015557
0.376437
0.339851
0.317408
0.285126
0.281436
0.250507
0
0.001527
0.326479
29,178
748
80
39.008021
0.826023
0.180753
0
0.314465
0
0
0.097511
0.001956
0
0
0
0
0
1
0.039832
false
0
0.039832
0
0.165618
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30ac17625116d9c557fcb9f766bc9c4e0e187256
273
py
Python
scripts/scenes/combat/elements/unit_behaviours/heavy.py
novialriptide/nqp2
db2c8a2ce298638eb06f84d283ed3f6807c2e131
[ "MIT" ]
12
2022-01-02T11:21:46.000Z
2022-03-12T20:53:40.000Z
scripts/scenes/combat/elements/unit_behaviours/heavy.py
novialriptide/nqp2
db2c8a2ce298638eb06f84d283ed3f6807c2e131
[ "MIT" ]
142
2021-07-25T14:05:11.000Z
2022-03-26T21:12:53.000Z
scripts/scenes/combat/elements/unit_behaviours/heavy.py
novialriptide/nqp2
db2c8a2ce298638eb06f84d283ed3f6807c2e131
[ "MIT" ]
9
2021-08-25T00:25:24.000Z
2022-03-12T20:53:41.000Z
from .base import Base class Heavy(Base): def complete_init(self): super().complete_init() self.force_regroup = True if self.unit.use_ammo: self.smart_range_retarget = True def process(self, dt): super().process(dt)
18.2
44
0.611722
35
273
4.6
0.628571
0.149068
0.198758
0
0
0
0
0
0
0
0
0
0.285714
273
14
45
19.5
0.825641
0
0
0
0
0
0
0
0
0
0
0
0
1
0.222222
false
0
0.111111
0
0.444444
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
30b094be213a7211a4cc02bd180d2df939d842b1
899
py
Python
tests/test_import_conceptnet.py
vishalbelsare/kgtk
7dbcc901a5d52cc9d1af97715e12697e5b460dc7
[ "MIT" ]
222
2020-03-31T17:45:04.000Z
2022-03-30T22:48:08.000Z
tests/test_import_conceptnet.py
vishalbelsare/kgtk
7dbcc901a5d52cc9d1af97715e12697e5b460dc7
[ "MIT" ]
510
2020-04-02T00:32:44.000Z
2022-03-29T01:20:22.000Z
tests/test_import_conceptnet.py
vishalbelsare/kgtk
7dbcc901a5d52cc9d1af97715e12697e5b460dc7
[ "MIT" ]
41
2020-03-31T17:45:07.000Z
2022-03-22T02:49:44.000Z
import shutil import unittest import tempfile import pandas as pd from kgtk.cli_entry import cli_entry from kgtk.exceptions import KGTKException class TestKGTKImportConceptNet(unittest.TestCase): def setUp(self) -> None: self.temp_dir=tempfile.mkdtemp() def tearDown(self) -> None: shutil.rmtree(self.temp_dir) def test_kgtk_import_conceptnet(self): cli_entry("kgtk", "import-conceptnet", "--english_only", "-i", "data/conceptnet.csv", "-o", f'{self.temp_dir}/conceptnet.tsv') df = pd.read_csv(f'{self.temp_dir}/conceptnet.tsv', sep='\t') self.assertEqual(len(df), 77) # Make sure that there are 77 rows with English nodes out of the total 100 self.assertEqual(df['node2'][0], '/c/en/1') # Make sure that the first node2 is the expected one self.assertEqual(len(df.columns), 9) relations = df['relation'].unique()
32.107143
134
0.688543
128
899
4.742188
0.539063
0.052718
0.072488
0.039539
0.082372
0.082372
0
0
0
0
0
0.016327
0.182425
899
27
135
33.296296
0.809524
0.136819
0
0
0
0
0.181347
0.07772
0
0
0
0
0.166667
1
0.166667
false
0
0.5
0
0.722222
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
30b203119c6c5793b1d0fe751409e9c5ee26bbf6
53
py
Python
lib/__init__.py
jesseokeya/linkedin-scraper
6b9d5af5167c8c936db63a855a9885728efbfeb5
[ "MIT" ]
null
null
null
lib/__init__.py
jesseokeya/linkedin-scraper
6b9d5af5167c8c936db63a855a9885728efbfeb5
[ "MIT" ]
1
2020-01-04T19:33:58.000Z
2021-09-07T15:03:03.000Z
lib/__init__.py
jesseokeya/linkedin-scraper
6b9d5af5167c8c936db63a855a9885728efbfeb5
[ "MIT" ]
1
2021-12-02T06:51:46.000Z
2021-12-02T06:51:46.000Z
from .scrape import Scrape from .helper import Helper
26.5
26
0.830189
8
53
5.5
0.5
0
0
0
0
0
0
0
0
0
0
0
0.132075
53
2
27
26.5
0.956522
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
5
30b35825288ae55d3b4e9f3fda30cd87266a239e
4,030
py
Python
test_contest/solutions/ladders.py
tbuzzelli/Veris
b2e9bd5f944a60365de8c18f17e041fa65f9e74a
[ "Apache-2.0" ]
7
2018-09-26T17:17:01.000Z
2020-12-20T17:23:33.000Z
test_contest/solutions/ladders.py
tbuzzelli/Veris
b2e9bd5f944a60365de8c18f17e041fa65f9e74a
[ "Apache-2.0" ]
4
2018-09-26T17:49:24.000Z
2020-12-20T17:15:37.000Z
test_contest/solutions/ladders.py
tbuzzelli/Veris
b2e9bd5f944a60365de8c18f17e041fa65f9e74a
[ "Apache-2.0" ]
1
2021-12-03T17:49:50.000Z
2021-12-03T17:49:50.000Z
# Written by Will Cromar # Python 3.6 from collections import deque # DX/DY array. In order of precedence, we'll move # left, right, up, and down DX = [-1, 1, 0, 0] DY = [0, 0, -1, 1] # Constants for types of spaces EMPTY = '.' LADDER = '#' CHUTE = '*' START = 'S' EXIT = 'E' # Primary business functions. Includes several helpers def solve(grid, l, w, h): # Generator that gives all adjacent spots to the given one def adjacent(x, y, z): # print("call to adj w/", (x, y, z)) for dx, dy in zip(DX, DY): # print(x + dx, y + dy, z) yield x + dx, y + dy, z # True if the result is in bounds, false otherwise def inBounds(x, y, z): return x >= 0 and y >= 0 and z >= 0 and x < w and y < l and z < h # Gives all adjacent nodes that are in bounds def moves(x, y, z): # Get all adjacent nodes and then filter them return filter(lambda triplet: inBounds(*triplet), adjacent(x, y, z)) # Follow a chute to the bottom def chuteBottom(x, y, z): # While the spot below us is still a chute, keep moving down levels while z > 0 and grid[z - 1][y][x] == CHUTE: z -= 1 return x, y, z # Gives vertically adjacent spots that have ladders def ladderSpots(x, y, z): # If there's a ladder above us, yield it if z < h - 1 and grid[z + 1][y][x] == LADDER: yield x, y, z + 1 # Likewise, yield ladders below us if z > 0 and grid[z - 1][y][x] == LADDER: yield x, y, z - 1 # Searches for the start symbol and returns an ordered triplet # or None def findStart(): for z, level in enumerate(grid): for y, row in enumerate(level): if START in row: return row.find(START), y, z # Finally, we can move on to our breadth-first search # This will store which spots we've seen before seen = set() # Will store an ordered triplet and a number of steps q = deque() # Find the starting position and add it to the queue w/ 0 steps start = findStart() seen.add(start) q.append(start) # Run BFS until the queue empties while len(q) > 0: # Unpack the data from the queue triplet = q.popleft() x, y, z = triplet # If we've found the exit, we're done! if grid[z][y][x] == EXIT: return True # If we stepped on a chute, fall if grid[z][y][x] == CHUTE: next = chuteBottom(x, y, z) if next not in seen: seen.add(next) q.appendleft(next) # If we're not at the bottom of the chute, then we # can't move anywhere else if next != triplet: continue # If we stepped on a ladder, see where we can go if grid[z][y][x] == LADDER: for next in ladderSpots(x, y, z): if next not in seen: seen.add(next) q.append(next) # Otherwise, explore our "slice" of the map for next in moves(x, y, z): if next not in seen: seen.add(next) q.append(next) return False # Number of test cases n = int(input()) # Process each test case for case in range(n): # Get the dimensions of the grid l, w, h = map(int, input().strip().split()) # Read it in grid = [] for _ in range(h): slice = [] for _ in range(l): slice.append(input().strip()) grid.append(slice) # I reverse the list to make z = 0 correspond to the lowest # slice on the map grid.reverse() # Determine if there is a path from start to end ans = solve(grid, l, w, h) # If there is, print "Yes", otherwise, "No" print("Map #%d: %s" % (case + 1, "Yes" if ans else "No"))
29.416058
77
0.525806
606
4,030
3.493399
0.320132
0.014171
0.019839
0.009447
0.140293
0.083609
0.083609
0.083609
0.076523
0.076523
0
0.010285
0.372705
4,030
136
78
29.632353
0.827136
0.368983
0
0.115942
0
0
0.008872
0
0
0
0
0
0
1
0.101449
false
0
0.014493
0.028986
0.202899
0.014493
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30b3709aef46a9041782b934920c7987f957d49e
1,789
py
Python
fits2fshr.py
rainwoodman/fsfits
e052c159915e7a67f10972c7851d2924afeaa302
[ "MIT" ]
null
null
null
fits2fshr.py
rainwoodman/fsfits
e052c159915e7a67f10972c7851d2924afeaa302
[ "MIT" ]
null
null
null
fits2fshr.py
rainwoodman/fsfits
e052c159915e7a67f10972c7851d2924afeaa302
[ "MIT" ]
null
null
null
import fitsio import fsfits from argparse import ArgumentParser import json import numpy ap = ArgumentParser() ap.add_argument('--check', action='store_true', default=False, help="Test if output contains identical information to input") ap.add_argument('input') ap.add_argument('output') ns = ap.parse_args() def main(): fin = fitsio.FITS(ns.input) if ns.check: fout = fsfits.FSHR.open(ns.output) else: fout = fsfits.FSHR.create(ns.output) with fout: for hdui, hdu in enumerate(fin): header = hdu.read_header() header = dict(header) type = hdu.get_exttype() if hdu.has_data(): if type in ( 'BINARY_TBL', 'ASCII_TBL'): data = hdu[:] elif type in ('IMAGE_HDU'): data = hdu[:, :] else: data = None if ns.check: block = fout["HDU-%04d" % hdui] with block: for key in header: assert header[key] == block.metadata[key] if data is not None: assert (block[...] == data).all() else: assert block[...] is None else: if data is not None: block = fout.create_block("HDU-%04d" % hdui, data.shape, data.dtype) else: block = fout.create_block("HDU-%04d" % hdui, (0,), None) with block: block.metadata.update(header) if data is not None: block[...] = data main()
28.854839
70
0.455562
184
1,789
4.358696
0.380435
0.018703
0.048628
0.041147
0.137157
0.118454
0.074813
0
0
0
0
0.007007
0.441587
1,789
61
71
29.327869
0.795796
0
0
0.269231
0
0
0.074902
0
0
0
0
0
0.057692
1
0.019231
false
0
0.096154
0
0.115385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30b43d3abb832538af7887238ea688d9f984e472
4,086
py
Python
window_switcher/window.py
include4eto/linux-appfinder
23b00d7e18760409e53aad7deb0544d7a4850bc3
[ "MIT" ]
2
2018-04-24T22:05:08.000Z
2018-04-25T09:50:37.000Z
window_switcher/window.py
include4eto/linux-appfinder
23b00d7e18760409e53aad7deb0544d7a4850bc3
[ "MIT" ]
1
2018-04-25T09:26:59.000Z
2018-04-25T09:36:43.000Z
window_switcher/window.py
include4eto/window-switcher
23b00d7e18760409e53aad7deb0544d7a4850bc3
[ "MIT" ]
2
2019-11-07T03:43:53.000Z
2021-03-25T12:14:01.000Z
from tkinter import Entry, Listbox, StringVar import sys, tkinter, subprocess from window_switcher.aux import get_windows class Window: FONT = ('Monospace', 11) ITEM_HEIGHT = 22 MAX_FOUND = 10 BG_COLOR = '#202b3a' FG_COLOR = '#ced0db' def resize(self, items): if self.resized: return self.root.geometry('{0}x{1}'.format(self.width, self.height + items * Window.ITEM_HEIGHT)) self.resized = True def __init__(self, root, width, height): self.root = root self.width = width self.height = height self.all_windows = [] self.resized = False # master.geometry(500) root.title("window switcher") root.resizable(width=False, height=False) root.configure(background=Window.BG_COLOR) # ugly tkinter code below sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.on_entry(sv)) self.main_entry = Entry( root, font=Window.FONT, width=1000, textvariable=sv, bg=Window.BG_COLOR, fg=Window.FG_COLOR, insertbackground=Window.FG_COLOR, bd=0 ) self.main_entry.grid(row=0, column=0, padx=10) self.main_entry.focus_set() self.listbox = Listbox( root, height=Window.ITEM_HEIGHT, font=Window.FONT, highlightthickness=0, borderwidth=0, bg=Window.BG_COLOR, fg=Window.FG_COLOR, selectbackground='#2c3c51', selectforeground='#cedaed' ) self.listbox.grid(row=1, column=0, sticky='we', padx=10, pady=10) # key bindings self.main_entry.bind('<Control-a>', self.select_all) self.main_entry.bind('<Up>', self.select_prev) self.main_entry.bind('<Down>', self.select_next) self.main_entry.bind('<Return>', self.select_window) self.root.bind('<Escape>', lambda e: sys.exit()) # self.resize(Window.MAX_FOUND) self.initial_get(None) def initial_get(self, event): self.all_windows = get_windows() self.find_windows('') def select_all(self, event): # select text self.main_entry.select_clear() self.main_entry.select_range(0, 'end') # move cursor to the end self.main_entry.icursor('end') return 'break' def find_windows(self, text): text = text.lower() found = [window for window in self.all_windows if window['name'].find(text) != -1] # print(found) self.found = found self.listbox.delete(0, 'end') for i, item in enumerate(found): if i >= Window.MAX_FOUND: break self.listbox.insert('end', item['name']) self.resize(min(len(found), Window.MAX_FOUND)) # select first element self.listbox.selection_set(0) def select_next(self, event): if len(self.found) == 0: return idx = self.listbox.curselection()[0] max = self.listbox.size() idx += 1 if idx >= max: idx = 0 self.listbox.selection_clear(0, 'end') self.listbox.selection_set(idx) def select_prev(self, event): if len(self.found) == 0: return idx = self.listbox.curselection()[0] max = self.listbox.size() idx -= 1 if idx < 0: idx = max - 1 self.listbox.selection_clear(0, 'end') self.listbox.selection_set(idx) def select_window(self, event): idx = self.listbox.curselection()[0] id = self.found[idx]['id'] # switch to window and exit # wmctrl -ia <id`> subprocess.call(['wmctrl', '-ia', id]) # print(subprocess.check_output(['wmctrl', '-ia', id]).decode('utf-8')) sys.exit(0) def on_entry(self, newtext): search_test = newtext.get() self.find_windows(search_test) return True
27.986301
98
0.564366
496
4,086
4.52621
0.282258
0.068597
0.057906
0.03029
0.170601
0.158575
0.158575
0.158575
0.131849
0.131849
0
0.01958
0.312531
4,086
145
99
28.17931
0.779637
0.065835
0
0.213592
0
0
0.037057
0
0
0
0
0
0
1
0.087379
false
0
0.029126
0
0.223301
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30b47ce03ab25050c96be917e8653691dbb6ff93
5,292
py
Python
app/udp_comm/proto-py/imu_samples_pb2.py
ewfuentes/esp32_stuff
5bf87555e91ffef48316f85f81d3765a6ef4a2c6
[ "Apache-2.0" ]
null
null
null
app/udp_comm/proto-py/imu_samples_pb2.py
ewfuentes/esp32_stuff
5bf87555e91ffef48316f85f81d3765a6ef4a2c6
[ "Apache-2.0" ]
null
null
null
app/udp_comm/proto-py/imu_samples_pb2.py
ewfuentes/esp32_stuff
5bf87555e91ffef48316f85f81d3765a6ef4a2c6
[ "Apache-2.0" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: imu_samples.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() DESCRIPTOR = _descriptor.FileDescriptor( name='imu_samples.proto', package='app.udp_comm', syntax='proto3', serialized_options=None, serialized_pb=_b('\n\x11imu_samples.proto\x12\x0c\x61pp.udp_comm\"\xce\x01\n\nImuSamples\x12\x1b\n\x13time_of_validity_us\x18\x01 \x01(\x12\x12\x12\n\ntimestamps\x18\x02 \x03(\x12\x12\x14\n\x0c\x61\x63\x63\x65l_x_mpss\x18\x03 \x03(\x02\x12\x14\n\x0c\x61\x63\x63\x65l_y_mpss\x18\x04 \x03(\x02\x12\x14\n\x0c\x61\x63\x63\x65l_z_mpss\x18\x05 \x03(\x02\x12\x12\n\ngyro_x_dps\x18\x06 \x03(\x02\x12\x12\n\ngyro_y_dps\x18\x07 \x03(\x02\x12\x12\n\ngyro_z_dps\x18\x08 \x03(\x02\x12\x11\n\ttemp_degc\x18\t \x03(\x02\x62\x06proto3') ) _IMUSAMPLES = _descriptor.Descriptor( name='ImuSamples', full_name='app.udp_comm.ImuSamples', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='time_of_validity_us', full_name='app.udp_comm.ImuSamples.time_of_validity_us', index=0, number=1, type=18, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='timestamps', full_name='app.udp_comm.ImuSamples.timestamps', index=1, number=2, type=18, cpp_type=2, 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='accel_x_mpss', full_name='app.udp_comm.ImuSamples.accel_x_mpss', index=2, number=3, type=2, cpp_type=6, 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='accel_y_mpss', full_name='app.udp_comm.ImuSamples.accel_y_mpss', index=3, number=4, type=2, cpp_type=6, 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='accel_z_mpss', full_name='app.udp_comm.ImuSamples.accel_z_mpss', index=4, number=5, type=2, cpp_type=6, 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='gyro_x_dps', full_name='app.udp_comm.ImuSamples.gyro_x_dps', index=5, number=6, type=2, cpp_type=6, 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='gyro_y_dps', full_name='app.udp_comm.ImuSamples.gyro_y_dps', index=6, number=7, type=2, cpp_type=6, 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='gyro_z_dps', full_name='app.udp_comm.ImuSamples.gyro_z_dps', index=7, number=8, type=2, cpp_type=6, 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='temp_degc', full_name='app.udp_comm.ImuSamples.temp_degc', index=8, number=9, type=2, cpp_type=6, 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), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=36, serialized_end=242, ) DESCRIPTOR.message_types_by_name['ImuSamples'] = _IMUSAMPLES _sym_db.RegisterFileDescriptor(DESCRIPTOR) ImuSamples = _reflection.GeneratedProtocolMessageType('ImuSamples', (_message.Message,), dict( DESCRIPTOR = _IMUSAMPLES, __module__ = 'imu_samples_pb2' # @@protoc_insertion_point(class_scope:app.udp_comm.ImuSamples) )) _sym_db.RegisterMessage(ImuSamples) # @@protoc_insertion_point(module_scope)
42
522
0.74263
752
5,292
4.928191
0.1875
0.060443
0.03238
0.059363
0.595791
0.595791
0.533459
0.533459
0.468969
0.468969
0
0.045078
0.132275
5,292
125
523
42.336
0.761977
0.041005
0
0.490566
1
0.009434
0.204971
0.164529
0
0
0
0
0
1
0
false
0
0.04717
0
0.04717
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
0
0
0
1
30b4986ed423fc0d856c04b8b25dc611fff18369
3,394
py
Python
imcsdk/mometa/bios/BiosVfSgxLePubKeyHash.py
ecoen66/imcsdk
b10eaa926a5ee57cea7182ae0adc8dd1c818b0ab
[ "Apache-2.0" ]
31
2016-06-14T07:23:59.000Z
2021-09-12T17:17:26.000Z
imcsdk/mometa/bios/BiosVfSgxLePubKeyHash.py
sthagen/imcsdk
1831eaecb5960ca03a8624b1579521749762b932
[ "Apache-2.0" ]
109
2016-05-25T03:56:56.000Z
2021-10-18T02:58:12.000Z
imcsdk/mometa/bios/BiosVfSgxLePubKeyHash.py
sthagen/imcsdk
1831eaecb5960ca03a8624b1579521749762b932
[ "Apache-2.0" ]
67
2016-05-17T05:53:56.000Z
2022-03-24T15:52:53.000Z
"""This module contains the general information for BiosVfSgxLePubKeyHash ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfSgxLePubKeyHashConsts: VP_SGX_LE_PUB_KEY_HASH0_PLATFORM_DEFAULT = "platform-default" VP_SGX_LE_PUB_KEY_HASH1_PLATFORM_DEFAULT = "platform-default" VP_SGX_LE_PUB_KEY_HASH2_PLATFORM_DEFAULT = "platform-default" VP_SGX_LE_PUB_KEY_HASH3_PLATFORM_DEFAULT = "platform-default" class BiosVfSgxLePubKeyHash(ManagedObject): """This is BiosVfSgxLePubKeyHash class.""" consts = BiosVfSgxLePubKeyHashConsts() naming_props = set([]) mo_meta = { "classic": MoMeta("BiosVfSgxLePubKeyHash", "biosVfSgxLePubKeyHash", "Sgx-Le-PubKeyHash", VersionMeta.Version421a, "InputOutput", 0xff, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]), } prop_meta = { "classic": { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version421a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), "vp_sgx_le_pub_key_hash0": MoPropertyMeta("vp_sgx_le_pub_key_hash0", "vpSgxLePubKeyHash0", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []), "vp_sgx_le_pub_key_hash1": MoPropertyMeta("vp_sgx_le_pub_key_hash1", "vpSgxLePubKeyHash1", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []), "vp_sgx_le_pub_key_hash2": MoPropertyMeta("vp_sgx_le_pub_key_hash2", "vpSgxLePubKeyHash2", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []), "vp_sgx_le_pub_key_hash3": MoPropertyMeta("vp_sgx_le_pub_key_hash3", "vpSgxLePubKeyHash3", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x80, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []), }, } prop_map = { "classic": { "childAction": "child_action", "dn": "dn", "rn": "rn", "status": "status", "vpSgxLePubKeyHash0": "vp_sgx_le_pub_key_hash0", "vpSgxLePubKeyHash1": "vp_sgx_le_pub_key_hash1", "vpSgxLePubKeyHash2": "vp_sgx_le_pub_key_hash2", "vpSgxLePubKeyHash3": "vp_sgx_le_pub_key_hash3", }, } def __init__(self, parent_mo_or_dn, **kwargs): self._dirty_mask = 0 self.child_action = None self.status = None self.vp_sgx_le_pub_key_hash0 = None self.vp_sgx_le_pub_key_hash1 = None self.vp_sgx_le_pub_key_hash2 = None self.vp_sgx_le_pub_key_hash3 = None ManagedObject.__init__(self, "BiosVfSgxLePubKeyHash", parent_mo_or_dn, **kwargs)
50.656716
235
0.675015
385
3,394
5.58961
0.231169
0.048792
0.065056
0.092937
0.493959
0.47723
0.192379
0.153346
0.139405
0.079461
0
0.036878
0.177077
3,394
66
236
51.424242
0.73362
0.035946
0
0.042553
0
0
0.291411
0.103988
0
0
0.008896
0
0
1
0.021277
false
0
0.06383
0
0.319149
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30b5e4e7800e589009301f09b9320ccd7cff9745
256
py
Python
services/helpers.py
jonti09/postgresql-manager
b41dab209b3b655c71c5e0f36699e63ddba1ad06
[ "MIT" ]
null
null
null
services/helpers.py
jonti09/postgresql-manager
b41dab209b3b655c71c5e0f36699e63ddba1ad06
[ "MIT" ]
null
null
null
services/helpers.py
jonti09/postgresql-manager
b41dab209b3b655c71c5e0f36699e63ddba1ad06
[ "MIT" ]
null
null
null
from configparser import ConfigParser import boto3 class S3Client: @staticmethod def get_client(config: ConfigParser): return boto3.Session( profile_name=config.get('S3', 'profile', fallback='default') ).client('s3')
21.333333
72
0.671875
27
256
6.296296
0.666667
0.211765
0
0
0
0
0
0
0
0
0
0.025126
0.222656
256
11
73
23.272727
0.829146
0
0
0
0
0
0.070313
0
0
0
0
0
0
1
0.125
false
0
0.25
0.125
0.625
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
1
1
0
0
4
30babde668ddbdfd3b25264b810e1027b167156a
1,791
py
Python
setup.py
naritotakizawa/getsize
25989cdb07e343c6684586768e60363f366f8c71
[ "MIT" ]
1
2017-08-07T18:15:37.000Z
2017-08-07T18:15:37.000Z
setup.py
naritotakizawa/getsize
25989cdb07e343c6684586768e60363f366f8c71
[ "MIT" ]
null
null
null
setup.py
naritotakizawa/getsize
25989cdb07e343c6684586768e60363f366f8c71
[ "MIT" ]
null
null
null
import os import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) with open(os.path.join(os.path.dirname(__file__), 'README.rst'), 'rb') as readme: README = readme.read() setup( name='getsize', version='0.1', packages=find_packages(exclude=('tests',)), include_package_data=True, license='MIT License', description='Command Line Tools For Get File and Directory Size', long_description=README.decode('utf-8'), url='https://github.com/naritotakizawa/getsize', author='Narito Takizawa', author_email='toritoritorina@gmail.com', classifiers=[ "Environment :: Console", 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', "Programming Language :: Python :: 3", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', "Topic :: Software Development :: Libraries :: Python Modules", ], tests_require = ['pytest', 'pytest-cov'], cmdclass = {'test': PyTest}, entry_points={'console_scripts': [ 'pysize = getsize.main:main', ]}, )
32.563636
82
0.624232
199
1,791
5.502513
0.547739
0.086758
0.114155
0.094977
0
0
0
0
0
0
0
0.007407
0.246231
1,791
55
83
32.563636
0.803704
0.027359
0
0
0
0
0.33827
0.014218
0
0
0
0
0
1
0.065217
false
0.021739
0.108696
0
0.217391
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30bb85a4d211b4c8e0c05cca0ae92e39839b9906
1,194
py
Python
dockwidgetpluginbase.py
sandroklippel/qgis-dockable-plugin
9410d20646155d1fe90ec44caa7d15a607d1e72d
[ "MIT" ]
null
null
null
dockwidgetpluginbase.py
sandroklippel/qgis-dockable-plugin
9410d20646155d1fe90ec44caa7d15a607d1e72d
[ "MIT" ]
null
null
null
dockwidgetpluginbase.py
sandroklippel/qgis-dockable-plugin
9410d20646155d1fe90ec44caa7d15a607d1e72d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets class Ui_DockWidgetPluginBase(object): def setupUi(self, DockWidgetPluginBase): DockWidgetPluginBase.setObjectName("DockWidgetPluginBase") DockWidgetPluginBase.resize(232, 141) self.dockWidgetContents = QtWidgets.QWidget() self.dockWidgetContents.setObjectName("dockWidgetContents") self.gridLayout = QtWidgets.QGridLayout(self.dockWidgetContents) self.gridLayout.setObjectName("gridLayout") self.label = QtWidgets.QLabel(self.dockWidgetContents) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) # DockWidgetPluginBase.setWidget(self.dockWidgetContents) self.retranslateUi(DockWidgetPluginBase) QtCore.QMetaObject.connectSlotsByName(DockWidgetPluginBase) def retranslateUi(self, DockWidgetPluginBase): _translate = QtCore.QCoreApplication.translate DockWidgetPluginBase.setWindowTitle(_translate("DockWidgetPluginBase", "Test DockWidget")) self.label.setText(_translate("DockWidgetPluginBase", "Replace this QLabel\n" "with the desired\n" "plugin content."))
42.642857
98
0.741206
101
1,194
8.722772
0.465347
0.124858
0.088536
0
0
0
0
0
0
0
0
0.011964
0.159967
1,194
27
99
44.222222
0.866401
0.064489
0
0
0
0
0.145553
0
0
0
0
0
0
1
0.1
false
0
0.05
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
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30bc0d5caa2ba95a5a11a4f13508d048a4057cd0
684
py
Python
setup.py
KirstensGitHub/attention-memory-task
c3d4b13e43134d4cc25c277e5f49220ac48ab931
[ "MIT" ]
4
2017-10-30T20:46:25.000Z
2020-10-16T16:28:29.000Z
setup.py
KirstensGitHub/attention-memory-task
c3d4b13e43134d4cc25c277e5f49220ac48ab931
[ "MIT" ]
26
2017-10-30T20:44:07.000Z
2019-10-11T20:07:33.000Z
setup.py
KirstensGitHub/attention-memory-task
c3d4b13e43134d4cc25c277e5f49220ac48ab931
[ "MIT" ]
7
2019-08-21T13:20:41.000Z
2022-03-01T03:25:26.000Z
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='attention-memory-task', version='0.1.0', description='Attention and Memory Experiment', long_description='This repository contains the Psychopy code for a psychology experiment exploring the relationship between covert attention and recognition memory.', author='Contextual Dynamics Laboratory', author_email='contextualdynamics@gmail.com', url='https://github.com/ContextLab/attention-memory-task', license=license, packages=find_packages(exclude=('tests')) )
29.73913
170
0.72076
85
684
5.752941
0.658824
0.04908
0.07771
0
0
0
0
0
0
0
0
0.006932
0.156433
684
22
171
31.090909
0.840555
0.030702
0
0
0
0
0.504545
0.074242
0
0
0
0
0
1
0
false
0
0.0625
0
0.0625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30bc925cd0ed0b7b60bfef9a34e4c38e0b3fa974
3,659
py
Python
blue_print/testLogReg.py
yimingq/COMP90051-SML
3e1d93d9b1a8cd23f4c05eeb18d615e87d4d6369
[ "Apache-2.0" ]
1
2020-09-16T04:58:49.000Z
2020-09-16T04:58:49.000Z
blue_print/testLogReg.py
yimingq/COMP90051-SML
3e1d93d9b1a8cd23f4c05eeb18d615e87d4d6369
[ "Apache-2.0" ]
null
null
null
blue_print/testLogReg.py
yimingq/COMP90051-SML
3e1d93d9b1a8cd23f4c05eeb18d615e87d4d6369
[ "Apache-2.0" ]
2
2020-03-31T08:55:45.000Z
2020-09-05T14:02:16.000Z
from numpy import * import matplotlib.pyplot as plt import time from LogReg import trainLogRegres, showLogRegres, predicTestData # from sklearn.datasets import make_circles # from sklearn.model_selection import train_test_split # from sklearn.metrics import accuracy_score import csv def loadTrainData(): train_x = [] train_y = [] # fileIn = open('/Users/martinzhang/Desktop/testSet.txt') # for line in fileIn.readlines(): # lineArr = line.strip().split() # train_x.append([1, float(lineArr[0]), float(lineArr[1])]) # train_y.append(float(lineArr[2])) # # return mat(train_x), mat(train_y).transpose() # for userA, relation in range(relation_dic): # for userB in range(userlist): # if user not in relation: # label = 0 # else: # label = 1 # train_x.append([1, float(lineArr[0]), float(lineArr[1])]) # train_y.append(label) # return mat(train_x), mat(train_y).transpose() with load('/Users/martinzhang/Desktop/compressed_test_7features.npz') as fd: temp_matrix = fd["temptest"] # d = [0, 1, 2, 3, 4, 5, 6] length =10336114 a = ones(length) temp_matrix_x = temp_matrix[0:length, 0:7] result = insert(temp_matrix_x, 0, values=a, axis=1) temp_matrix_y = temp_matrix[0:length, 7] return mat(result), mat(temp_matrix_y).transpose() def loadTestData(): # test_list = [] # test_id = [] test_x = [] # test_y = [] # file_path = open('/Users/martinzhang/Desktop/ml_data/test-public.txt') index = -1 for line in file_path.readlines(): index += 1 if index == 0: pass else: line_content = line.strip().split() data_id = line_content[0] data_source = line_content[1] data_sink = line_content[2] # test_list.append([data_id, data_source, data_sink]) # test_id.append(data_id) test_x.append([data_id, data_source, data_sink]) # test_x if index == 100: return mat(test_x) # # ## step 1: load data print("step 1: load data...") train_x, train_y = loadTrainData() # for item in train_x: # print item # test_list = loadTestData() # for test_data in test_list: # test_x = train_x # test_y = train_y # test_x = loadTestData() ## step 2: training... print("step 2: training...") opts = {'alpha': 0.01, 'maxIter': 1, 'optimizeType': 'gradDescent'} optimalWeights = trainLogRegres(train_x, train_y, opts) # print(optimalWeights.transpose().tolist()[0]) # for line in optimalWeights: # print(line[0]) print(optimalWeights.transpose().tolist()[0][1]) print(shape(optimalWeights)) ## step 3: predicting # print("step 3: predicting...") # accuracy = predicTestData(optimalWeights, test_x, test_y) # ## step 4: show the result # print("step 4: show the result...") # print('The classify accuracy is: %.3f%%' % (accuracy * 100)) # showLogRegres(optimalWeights, train_x, train_y) # test = loadTestData() # for item in test: # print(item) # def testCSV(): # test_y = [] # # csvfile = open('/Users/martinzhang/Desktop/ml_data/result.csv', 'wb') # with open('/Users/martinzhang/Desktop/ml_data/result.csv', 'w') as csvfile: # writer = csv.writer(csvfile) # for i in range(0, 100): # # predict = float(sigmoid(test_x[i, 1:] * weights)[0, 0]) # wwwww='ggg' # # bytes(wwwww, encoding="utf8") # writer.writerow((i, wwwww)) # csvfile.close() # print('finishing!') # # testCSV()
28.364341
81
0.608363
471
3,659
4.564756
0.284501
0.027907
0.053488
0.022326
0.21814
0.185581
0.148837
0.148837
0.047442
0.047442
0
0.0251
0.248702
3,659
128
82
28.585938
0.757003
0.558896
0
0
0
0
0.089669
0.036387
0
0
0
0
0
1
0.052632
false
0.026316
0.131579
0
0.236842
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30bcbf7ce957c6c88d400b8fdc56ff1017f41f6b
1,303
py
Python
Pyautogui_tutorial/mousecontrolscipt.py
xfzlun/WinUIAutomation
0f94388671cf0aacbc8499293b7dd31ddfa205fa
[ "MIT" ]
null
null
null
Pyautogui_tutorial/mousecontrolscipt.py
xfzlun/WinUIAutomation
0f94388671cf0aacbc8499293b7dd31ddfa205fa
[ "MIT" ]
null
null
null
Pyautogui_tutorial/mousecontrolscipt.py
xfzlun/WinUIAutomation
0f94388671cf0aacbc8499293b7dd31ddfa205fa
[ "MIT" ]
null
null
null
import pyautogui as pg # 间隔2秒钟将鼠标移动到坐标为100,100的位置 pg.FAILSAFE = False #关掉保护措施,不设置会报下面附录的错误 pg.moveTo(x=100, y=100, duration=2) pg.click() #鼠标左键点击一次, 这个函数有很多参数,参见以下,可以玩看看 #pg.click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=pg.linear) ''' 第一次执行的时候报了这个错误,搜了一下貌似要关掉 Exception has occurred: FailSafeException PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED. File "F:\codehub\WInAutomation\Pyautogui_tutorial\mousecontrolscipt.py", line 4, in <module> pg.moveTo(x=100, y=100, duration=2) ''' # 鼠标移动到相对位置 # 用2秒钟的时间,将鼠标移动到现在鼠标所在位置的相对移动,向右移动10,向下移动10 pg.move.Rel(xOffset=10, yOffset=10, duration = 2) #一般不用pyautogui.click()这个函数,因为记不住参数,使用下面封装好的参数比较快 #双击 pg.doubleClick() #triple click pg.tripleClick() #右击 pg.rightClick() #中击 pg.middleClick() # 鼠标当前位置滚轮滚动 pg.scroll() # 鼠标拖拽 pg.dragTo(x=427, y=535, duration=3, button='left') # 鼠标相对拖拽 pg.dragRel(xOffset=100, yOffset=100, duration=3, button='left', mouseDownUp=False) #鼠标移到x=1796, y=778位置按下 pg.mouseDown(x=1796, y=778, button='left') #鼠标移到x=2745, y=778位置松开(与mouseDown组合使用选中) pg.mouseUp(x=2745, y=778, button='left', duration=5)
25.54902
175
0.720645
185
1,303
5.07027
0.583784
0.053305
0.01919
0.025586
0.053305
0.053305
0.053305
0.053305
0
0
0
0.071556
0.14198
1,303
50
176
26.06
0.767442
0.281658
0
0
0
0
0.033058
0
0
0
0
0
0
1
0
true
0
0.071429
0
0.071429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
1
30bdbe577a5d9d1dbc9a092c3e7fa1f6b9c7256d
9,683
py
Python
Backup/moduleA.py
ejekt/rigging-system
dedf09cc832f56b310587b818deadfd4f8ca7b3b
[ "MIT" ]
3
2019-12-12T03:46:41.000Z
2021-01-16T06:29:45.000Z
Backup/moduleA.py
ejekt/rigging-system
dedf09cc832f56b310587b818deadfd4f8ca7b3b
[ "MIT" ]
null
null
null
Backup/moduleA.py
ejekt/rigging-system
dedf09cc832f56b310587b818deadfd4f8ca7b3b
[ "MIT" ]
null
null
null
import os import naming as n reload(n) import maya.cmds as mc import System.utils as utils reload(utils) CLASS_NAME = 'ModuleA' TITLE = 'Module A' DESCRIPTION = 'Test desc for module A' ICON = os.environ['RIGGING_TOOL_ROOT'] + '/Icons/_hand.xpm' #cNamer = n.Name(type='blueprint', mod=CLASS_NAME) class ModuleA: def __init__(self, sName): # module namespace name initialized self.moduleName = CLASS_NAME self.userSpecifiedName = sName self.moduleNamespace = self.moduleName + '__' + self.userSpecifiedName self.containerName = self.moduleNamespace + ":module_container" self.jointInfo = [['root_joint', [0.0,0.0,0.0]], ['end_joint',[4.0,0.0,0.0]]] print 'init module namespace: ', self.moduleNamespace def install(self): print '\n== MODULE install class {} using namespace {}'.format(CLASS_NAME, self.moduleNamespace) # check if one already exists and increment the index if it does mc.namespace(setNamespace=':') mc.namespace(add=self.moduleNamespace) self.jointsGrp = mc.group(em=True, n=self.moduleNamespace+':joints_grp') self.hierarchyRepGrp = mc.group(em=True, n=self.moduleNamespace+':hierarchyRep_grp') self.orientationControlGrp = mc.group(em=True, n=self.moduleNamespace+':orientationControls_grp') self.moduleGrp = mc.group([self.jointsGrp, self.hierarchyRepGrp], n=self.moduleNamespace+':module_grp') mc.container(n=self.containerName, addNode=[self.moduleGrp], includeHierarchyBelow=True) mc.select(cl=True) # create the joints in self.jointInfo index = 0 joints = [] for joint in self.jointInfo: jointName = joint[0] jointPos = joint[1] parentJoint = '' if index > 0: # in case this is not the root joint, select the parent joint name parentJoint = self.moduleNamespace+':'+self.jointInfo[index-1][0] mc.select(parentJoint, r=True) # create the joint and add it to the container jointName_full = mc.joint(n=self.moduleNamespace+':'+jointName, p=jointPos) joints.append(jointName_full) mc.setAttr(jointName_full+'.v', 0) utils.addNodeToContainer(self.containerName, jointName_full, ihb=True) mc.container(self.containerName, edit=True, publishAndBind=[jointName_full+'.rotate', jointName+'_R']) mc.container(self.containerName, edit=True, publishAndBind=[jointName_full+'.rotateOrder', jointName+'_RO']) # orient the parent joint to the newly created joint if index > 0: mc.joint(parentJoint, edit=True, orientJoint='xyz', sao='yup') index += 1 mc.parent(joints[0], self.jointsGrp, absolute=True) # prepare the parent translation control group self.initializeModuleTransforn(self.jointInfo[0][1]) # create translation controls for the joints translationControls = [] for joint in joints: translationControls.append(self.createTranslationControlAtJoint(joint)) rootJoint_pCon = mc.pointConstraint(translationControls[0], joints[0], mo=False, n=joints[0]+'_pCon') utils.addNodeToContainer(self.containerName, rootJoint_pCon) # setup stretchy joint segement for index in range(len(joints) - 1): self.setupStretchyJointSegment(joints[index], joints[index+1]) # NON DEFAULT FUNCTIONALITY self.createOrientationControl(joints[0], joints[1]) utils.forceSceneUpdate() # lock the container mc.lockNode(self.containerName, lock=True, lockUnpublished=True) def createTranslationControlAtJoint(self, joint): # import the control sphere posControlFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/translation_control.ma' mc.file(posControlFile, i=True) # go through and rename all the nodes based on the joint container = mc.rename('translation_control_container', joint+'_translation_control_container') utils.addNodeToContainer(self.containerName, container) # add it all to this instance's container for node in mc.container(container, q=True, nodeList=True): mc.rename(node, joint+'_'+node, ignoreShape=True) # position the control control = joint+'_translation_control' # parent it to the initialized transform control group mc.parent(control, self.moduleTransform, absolute=True) # match the control to the joint poision jointPos = mc.xform(joint, q=True, ws=True, t=True) mc.xform(control, ws=True, absolute=True, t=jointPos) # publish attributes niceName = utils.stripLeadingNamespace(joint)[1] attrName = niceName + '_T' mc.container(container, edit=True, publishAndBind=[control+'.t', attrName]) mc.container(self.containerName, edit=True, publishAndBind=[container+'.'+attrName, attrName]) return control def getTranslationControl(self, jointName): return jointName + '_translation_control' def setupStretchyJointSegment(self, parentJoint, childJoint): # setup 2 joints to have an IK and stretchy joint in the segment parentTranslationControl = self.getTranslationControl(parentJoint) childTranslationControl = self.getTranslationControl(childJoint) pvLoc = mc.spaceLocator(n=parentTranslationControl+'pvLoc')[0] pvLocGrp = mc.group(pvLoc, n=pvLoc+'_pConGrp') mc.parent(pvLocGrp, self.moduleGrp, absolute=True) parentConst = mc.parentConstraint(parentTranslationControl, pvLocGrp, mo=False)[0] mc.setAttr(pvLoc+'.v', 0) mc.setAttr(pvLoc+'.ty', -0.5) dIkNodes = utils.basicStretchyIK(parentJoint, childJoint, sContainer=self.containerName, bMinLengthLock=False, poleVectorObj=pvLoc, sScaleCorrectionAttr=None) ikHandle = dIkNodes['ikHandle'] rootLoc = dIkNodes['rootLoc'] endLoc = dIkNodes['endLoc'] child_pCon = mc.pointConstraint(childTranslationControl, endLoc, mo=False, n=endLoc+'_pCon')[0] utils.addNodeToContainer(self.containerName, [pvLocGrp,child_pCon], ihb=True) for node in [ikHandle, rootLoc, endLoc]: mc.parent(node, self.jointsGrp) mc.setAttr(node+'.v', 0) self.createHierarchyRepresentation(parentJoint, childJoint) def createHierarchyRepresentation(self, parentJoint, childJoint): # run the createStretchyObject and parent to grp nodes = self.createStretchyObject('/ControlObjects/Blueprint/hierarchy_representation.ma', 'hierarchy_representation_container', 'hierarchy_representation', parentJoint, childJoint) constrainedGrp = nodes[2] mc.parent(constrainedGrp, self.hierarchyRepGrp, r=True) def createStretchyObject(self, objectRelativeFilePath, objectContainerName, objectName, parentJoint, childJoint): # import the prepared hierarchy representation geo, connect their scale and constrain to the joints objFile = os.environ['RIGGING_TOOL_ROOT'] + objectRelativeFilePath mc.file(objFile, i=True) objContainer = mc.rename(objectContainerName, parentJoint+'_'+objectContainerName) for node in mc.container(objContainer, q=True, nodeList=True): mc.rename(node, parentJoint+'_'+node, ignoreShape=True) obj = parentJoint+'_'+objectName constrainedGrp = mc.group(em=True, n=obj+'_parentConstraint_grp') mc.parent(obj, constrainedGrp, absolute=True) pCon = mc.parentConstraint(parentJoint, constrainedGrp, mo=False)[0] mc.connectAttr(childJoint+'.tx', constrainedGrp+'.sx') sCon = mc.scaleConstraint(self.moduleTransform, constrainedGrp, skip=['x'], mo=False)[0] utils.addNodeToContainer(objContainer, [constrainedGrp, pCon, sCon], ihb=True) utils.addNodeToContainer(self.containerName, objContainer) return(objContainer, obj, constrainedGrp) def initializeModuleTransforn(self, rootPos): controlGrpFile = os.environ['RIGGING_TOOL_ROOT']+'/ControlObjects/Blueprint/controlGroup_control.ma' mc.file(controlGrpFile, i=True) self.moduleTransform = mc.rename('controlGroup_control', self.moduleNamespace+':module_transform') mc.xform(self.moduleTransform, ws=True, absolute=True, t=rootPos) utils.addNodeToContainer(self.containerName, self.moduleTransform, ihb=True) # setup global scaling mc.connectAttr(self.moduleTransform+'.sy', self.moduleTransform+'.sx') mc.connectAttr(self.moduleTransform+'.sy', self.moduleTransform+'.sz') mc.aliasAttr('globalScale', self.moduleTransform+'.sy') mc.container(self.containerName, e=True, publishAndBind=[self.moduleTransform+'.translate', 'module_transform_T']) mc.container(self.containerName, e=True, publishAndBind=[self.moduleTransform+'.rotate', 'module_transform_R']) mc.container(self.containerName, e=True, publishAndBind=[self.moduleTransform+'.globalScale', 'module_transform_globalScale']) def deleteHierarchyRepresentation(self, parentJoint): hierarchyContainer = parentJoint + '_hierarchy_representation_container' mc.delete(hierarchyContainer) def createOrientationControl(self, parentJoint, childJoint): self.deleteHierarchyRepresentation(parentJoint) nodes = self.createStretchyObject('/ControlObjects/Blueprint/orientation_control.ma', 'orientation_control_container', 'orientation_control', parentJoint, childJoint) orientationContainer = nodes[0] orientationControl = nodes[1] constrainedGrp = nodes[2] mc.parent(constrainedGrp, self.orientationControlGrp, relative=True) parentJoint_noNs = utils.stripAllNamespaces(parentJoint)[1] attrName = parentJoint_noNs + '_orientation' #childJoint_noNs= utils.stripAllNamespaces(child)[1] mc.container(orientationContainer, e=True, publishAndBind=[orientationControl+'.rx', attrName]) mc.container(self.containerName, e=True, publishAndBind=[orientationContainer+'.'+attrName, attrName]) return orientationControl
41.380342
129
0.741402
1,073
9,683
6.614166
0.230196
0.040721
0.002959
0.027617
0.172608
0.122587
0.122587
0.045653
0.045653
0
0
0.005797
0.144893
9,683
234
130
41.380342
0.851329
0.107405
0
0.051948
0
0
0.122213
0.053893
0
0
0
0
0
0
null
null
0
0.025974
null
null
0.038961
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
30bf63f85cca01c1bcc1223cd6e0ff4f4c12199f
7,652
py
Python
tests/exporter/test_metadata.py
HumanCellAtlas/ingest-common
6a230f9606f64cd787b67c143854db36e012a2b7
[ "Apache-2.0" ]
null
null
null
tests/exporter/test_metadata.py
HumanCellAtlas/ingest-common
6a230f9606f64cd787b67c143854db36e012a2b7
[ "Apache-2.0" ]
null
null
null
tests/exporter/test_metadata.py
HumanCellAtlas/ingest-common
6a230f9606f64cd787b67c143854db36e012a2b7
[ "Apache-2.0" ]
null
null
null
from unittest import TestCase from mock import Mock from ingest.exporter.metadata import MetadataResource, MetadataService, MetadataParseException, MetadataProvenance class MetadataResourceTest(TestCase): def test_provenance_from_dict(self): # given: uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d' data = { 'uuid': {'uuid': uuid_value}, 'submissionDate': 'a submission date', 'updateDate': 'an update date', 'dcpVersion': '2019-12-02T13:40:50.520Z', 'content': { 'describedBy': 'https://some-schema/1.2.3' } } # when: metadata_provenance = MetadataResource.provenance_from_dict(data) # then: self.assertIsNotNone(metadata_provenance) self.assertEqual(uuid_value, metadata_provenance.document_id) self.assertEqual('a submission date', metadata_provenance.submission_date) self.assertEqual('2019-12-02T13:40:50.520Z', metadata_provenance.update_date) def test_provenance_from_dict_fail_fast(self): # given: uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d' data = {'uuid': uuid_value, # unexpected structure structure 'submissionDate': 'a submission date', 'updateDate': 'an update date'} # then: with self.assertRaises(MetadataParseException): # when MetadataResource.provenance_from_dict(data) def test_from_dict(self): # given: uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d' data = self._create_test_data(uuid_value) # when: metadata = MetadataResource.from_dict(data) # then: self.assertIsNotNone(metadata) self.assertEqual('biomaterial', metadata.metadata_type) self.assertEqual(data['content'], metadata.metadata_json) self.assertEqual(data['dcpVersion'], metadata.dcp_version) # and: self.assertEqual(uuid_value, metadata.uuid) def test_from_dict_provenance_optional(self): # given: uuid = '566be204-a684-4896-bda7-8dbb3e4fc65c' data_no_provenance = self._create_test_data(uuid) del data_no_provenance['submissionDate'] # and: data = self._create_test_data(uuid) # when: metadata_no_provenance = MetadataResource.from_dict(data_no_provenance, require_provenance=False) metadata = MetadataResource.from_dict(data, require_provenance=False) # then: self.assertIsNotNone(metadata_no_provenance) self.assertEqual(uuid, metadata_no_provenance.uuid) self.assertIsNone(metadata_no_provenance.provenance) # and: self.assertIsNotNone(metadata.provenance) def test_from_dict_fail_fast_with_missing_info(self): # given: data = {} # then: with self.assertRaises(MetadataParseException): # when MetadataResource.from_dict(data) def test_to_bundle_metadata(self): # given: uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d' data = self._create_test_data(uuid_value) metadata = MetadataResource.from_dict(data) # and: data_no_provenance = self._create_test_data(uuid_value) del data_no_provenance['submissionDate'] metadata_no_provenance = MetadataResource.from_dict(data_no_provenance, require_provenance=False) self.assertIsNone(metadata_no_provenance.provenance) # when bundle_metadata = metadata.to_bundle_metadata() bundle_metadata_no_provenance = metadata_no_provenance.to_bundle_metadata() # then: self.assertTrue('provenance' in bundle_metadata) self.assertTrue(bundle_metadata['provenance'] == metadata.provenance.to_dict()) self.assertTrue(set(data['content'].keys()) <= set( bundle_metadata.keys())) # <= operator checks if a dict is subset of another dict # and: self.assertIsNotNone(bundle_metadata_no_provenance) self.assertEqual(metadata_no_provenance.metadata_json['describedBy'], bundle_metadata_no_provenance['describedBy']) @staticmethod def _create_test_data(uuid_value): return {'type': 'Biomaterial', 'uuid': {'uuid': uuid_value}, 'content': {'describedBy': "http://some-schema/1.2.3", 'some': {'content': ['we', 'are', 'agnostic', 'of']}}, 'dcpVersion': '6.9.1', 'submissionDate': 'a date', 'updateDate': 'another date'} def test_get_staging_file_name(self): # given: metadata_resource_1 = MetadataResource(metadata_type='specimen', uuid='9b159cae-a1fe-4cce-94bc-146e4aa20553', metadata_json={'description': 'test'}, dcp_version='5.1.0', provenance=MetadataProvenance('9b159cae-a1fe-4cce-94bc-146e4aa20553', 'some date', 'some other date', 1, 1)) metadata_resource_2 = MetadataResource(metadata_type='donor_organism', uuid='38e0ee7c-90dc-438a-a0ed-071f9231f590', metadata_json={'text': 'sample'}, dcp_version='1.0.7', provenance=MetadataProvenance('38e0ee7c-90dc-438a-a0ed-071f9231f590', 'some date', 'some other date', '2', '2')) # expect: self.assertEqual('specimen_9b159cae-a1fe-4cce-94bc-146e4aa20553.json', metadata_resource_1.get_staging_file_name()) self.assertEqual('donor_organism_38e0ee7c-90dc-438a-a0ed-071f9231f590.json', metadata_resource_2.get_staging_file_name()) class MetadataServiceTest(TestCase): def test_fetch_resource(self): # given: ingest_client = Mock(name='ingest_client') uuid = '301636f7-f97b-4379-bf77-c5dcd9f17bcb' raw_metadata = {'type': 'Biomaterial', 'uuid': {'uuid': uuid}, 'content': {'describedBy': "http://some-schema/1.2.3", 'some': {'content': ['we', 'are', 'agnostic', 'of']}}, 'dcpVersion': '2019-12-02T13:40:50.520Z', 'submissionDate': 'a submission date', 'updateDate': 'an update date' } ingest_client.get_entity_by_callback_link = Mock(return_value=raw_metadata) # and: metadata_service = MetadataService(ingest_client) # when: metadata_resource = metadata_service.fetch_resource( 'hca.domain.com/api/cellsuspensions/301636f7-f97b-4379-bf77-c5dcd9f17bcb') # then: self.assertEqual('biomaterial', metadata_resource.metadata_type) self.assertEqual(uuid, metadata_resource.uuid) self.assertEqual(raw_metadata['content'], metadata_resource.metadata_json) self.assertEqual(raw_metadata['dcpVersion'], metadata_resource.dcp_version) self.assertEqual(raw_metadata['submissionDate'], metadata_resource.provenance.submission_date) self.assertEqual(raw_metadata['dcpVersion'], metadata_resource.provenance.update_date)
42.748603
119
0.604809
733
7,652
6.060027
0.20191
0.057407
0.049527
0.024313
0.507879
0.303692
0.271724
0.188429
0.136875
0.136875
0
0.060018
0.292342
7,652
178
120
42.988764
0.760295
0.033978
0
0.232759
0
0
0.187772
0.082745
0
0
0
0
0.25
1
0.077586
false
0
0.025862
0.008621
0.12931
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30bfa3735b16a51315054b5acedc817b34e86510
919
py
Python
models.py
tensorway/Neural-cellular-automata-and-Bitcoin
79d19dc036217f93d6845be9ea96c6cc25b23b92
[ "MIT" ]
null
null
null
models.py
tensorway/Neural-cellular-automata-and-Bitcoin
79d19dc036217f93d6845be9ea96c6cc25b23b92
[ "MIT" ]
null
null
null
models.py
tensorway/Neural-cellular-automata-and-Bitcoin
79d19dc036217f93d6845be9ea96c6cc25b23b92
[ "MIT" ]
null
null
null
import torch as th import torch.nn as nn import torch.nn.functional as F import torchvision as tv import matplotlib.pyplot as plt import cv2 from torch.utils.tensorboard import SummaryWriter import time from collections import deque import random import copy from utils import xsobel, ysobel class Cell(nn.Module): def __init__(self, net_arch, last_activation = lambda x: x): super().__init__() self.layers = nn.ModuleList([nn.Linear(a, b) for a, b in zip(net_arch[:-1], net_arch[1:])]) self.last_activation = last_activation def forward(self, x, stochastic=True, p_dropout=0.5): h = th.cat((x, xsobel(x), ysobel(x)), dim=1) h = h.transpose(1, -1) for lay in self.layers[:-1]: h = F.relu(lay(h)) h = self.layers[-1](h) h = h.transpose(1, -1) h = th.nn.functional.dropout2d(h, p=p_dropout, training=stochastic) return h
34.037037
99
0.660501
146
919
4.047945
0.424658
0.013536
0.043993
0.040609
0.043993
0
0
0
0
0
0
0.018106
0.218716
919
27
100
34.037037
0.805014
0
0
0.076923
0
0
0
0
0
0
0
0
0
1
0.076923
false
0
0.461538
0
0.615385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
30c056f49843fec67503aa5c21f43521e60897d9
5,708
py
Python
src/delivery/delivery.py
ska-telescope/sdp-workflows-procfunc
ef6e7be9584a006e936139ae653902a41af4d906
[ "BSD-3-Clause" ]
null
null
null
src/delivery/delivery.py
ska-telescope/sdp-workflows-procfunc
ef6e7be9584a006e936139ae653902a41af4d906
[ "BSD-3-Clause" ]
null
null
null
src/delivery/delivery.py
ska-telescope/sdp-workflows-procfunc
ef6e7be9584a006e936139ae653902a41af4d906
[ "BSD-3-Clause" ]
null
null
null
""" Prototype Delivery Workflow. """ import os import sys import glob import logging import ska_sdp_config import dask import distributed from google.oauth2 import service_account from google.cloud import storage # Initialise logging logging.basicConfig() LOG = logging.getLogger("delivery") LOG.setLevel(logging.INFO) def ee_dask_deploy(config, pb_id, image, n_workers=1, buffers=[], secrets=[]): """Deploy Dask execution engine. :param config: configuration DB handle :param pb_id: processing block ID :param image: Docker image to deploy :param n_workers: number of Dask workers :param buffers: list of buffers to mount on Dask workers :param secrets: list of secrets to mount on Dask workers :return: deployment ID and Dask client handle """ # Make deployment deploy_id = "proc-{}-dask".format(pb_id) values = {"image": image, "worker.replicas": n_workers} for i, b in enumerate(buffers): values["buffers[{}]".format(i)] = b for i, s in enumerate(secrets): values["secrets[{}]".format(i)] = s deploy = ska_sdp_config.Deployment( deploy_id, "helm", {"chart": "dask", "values": values} ) for txn in config.txn(): txn.create_deployment(deploy) # Wait for scheduler to become available scheduler = deploy_id + "-scheduler." + os.environ["SDP_HELM_NAMESPACE"] + ":8786" client = None while client is None: try: client = distributed.Client(scheduler, timeout=1) except: pass return deploy_id, client def ee_dask_remove(config, deploy_id): """Remove Dask EE deployment. :param config: configuration DB handle :param deploy_id: deployment ID """ for txn in config.txn(): deploy = txn.get_deployment(deploy_id) txn.delete_deployment(deploy) def upload_directory_to_gcp(sa_file, bucket_name, src_dir, dst_dir): """Recursively upload contents of directory to Google Cloud Platform :param sa_file: service account JSON file :param bucket_name: name of the bucket on GCP :param src_dir: local source directory :param dst_dir: destination directory in GCP bucket """ # Recursively list everything in directory src_list = sorted(glob.glob(src_dir + "/**", recursive=True)) # Get connection to GCP bucket credentials = service_account.Credentials.from_service_account_file(sa_file) client = storage.Client(credentials=credentials, project=credentials.project_id) bucket = client.bucket(bucket_name) # Upload files (ignoring directories) for src_name in src_list: if not os.path.isdir(src_name): dst_name = dst_dir + "/" + src_name[len(src_dir) + 1 :] blob = bucket.blob(dst_name) blob.upload_from_filename(src_name) def deliver(client, parameters): """Delivery function :param client: Dask distributed client :param parameters: parameters """ sa = parameters.get("service_account") bucket = parameters.get("bucket") buffers = parameters.get("buffers", []) if sa is None or bucket is None: return sa_file = "/secret/{}/{}".format(sa.get("secret"), sa.get("file")) tasks = [] for b in buffers: src_dir = "/buffer/" + b.get("name") dst_dir = b.get("destination") tasks.append( dask.delayed(upload_directory_to_gcp)(sa_file, bucket, src_dir, dst_dir) ) client.compute(tasks, sync=True) def main(argv): """Workflow main function.""" pb_id = argv[0] config = ska_sdp_config.Config() for txn in config.txn(): txn.take_processing_block(pb_id, config.client_lease) pb = txn.get_processing_block(pb_id) LOG.info("Claimed processing block %s", pb_id) # Parse parameters n_workers = pb.parameters.get("n_workers", 1) buffers = [b.get("name") for b in pb.parameters.get("buffers", [])] secrets = [pb.parameters.get("service_account", {}).get("secret")] # Set state to indicate workflow is waiting for resources LOG.info("Setting status to WAITING") for txn in config.txn(): state = txn.get_processing_block_state(pb_id) state["status"] = "WAITING" txn.update_processing_block_state(pb_id, state) # Wait for resources_available to be true LOG.info("Waiting for resources to be available") for txn in config.txn(): state = txn.get_processing_block_state(pb_id) ra = state.get("resources_available") if ra is not None and ra: LOG.info("Resources are available") break txn.loop(wait=True) # Set state to indicate workflow is running for txn in config.txn(): state = txn.get_processing_block_state(pb_id) state["status"] = "RUNNING" txn.update_processing_block_state(pb_id, state) # Deploy Dask EE LOG.info("Deploying Dask EE") image = "artefact.skao.int/ska-sdp-wflow-delivery:{}".format( pb.workflow.get("version") ) deploy_id, client = ee_dask_deploy( config, pb.id, image, n_workers=n_workers, buffers=buffers, secrets=secrets ) # Run delivery function LOG.info("Starting delivery") deliver(client, pb.parameters) LOG.info("Finished delivery") # Remove Dask EE deployment LOG.info("Removing Dask EE deployment") ee_dask_remove(config, deploy_id) # Set state to indicate processing is finished for txn in config.txn(): state = txn.get_processing_block_state(pb_id) state["status"] = "FINISHED" txn.update_processing_block_state(pb_id, state) config.close() if __name__ == "__main__": main(sys.argv[1:])
30.201058
86
0.666608
758
5,708
4.850923
0.220317
0.016318
0.01523
0.026652
0.208866
0.193364
0.132989
0.115583
0.08458
0.065543
0
0.002484
0.224071
5,708
188
87
30.361702
0.827726
0.22267
0
0.130841
0
0
0.125522
0.009977
0
0
0
0
0
1
0.046729
false
0.009346
0.084112
0
0.149533
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30c1376c3fde4348e43ee2ba12a8534b910f98c1
1,527
py
Python
dragon/usystem.py
NicEastvillage/RLBot-DropShot-Dragon-Python
b0d94fd054ab410ad02880a3d56e72b5eddd7ba6
[ "MIT" ]
1
2019-08-07T21:38:59.000Z
2019-08-07T21:38:59.000Z
dragon/usystem.py
NicEastvillage/RLBot-DropShot-Dragon-Python
b0d94fd054ab410ad02880a3d56e72b5eddd7ba6
[ "MIT" ]
null
null
null
dragon/usystem.py
NicEastvillage/RLBot-DropShot-Dragon-Python
b0d94fd054ab410ad02880a3d56e72b5eddd7ba6
[ "MIT" ]
null
null
null
from RLUtilities.LinearAlgebra import vec3 from RLUtilities.Maneuvers import Drive class UtilitySystem: def __init__(self, choices, prev_bias=0.15): self.choices = choices self.current_best_index = -1 self.prev_bias = prev_bias def evaluate(self, bot): best_index = -1 best_score = 0 for i, ch in enumerate(self.choices): score = ch.utility(bot) if i == self.current_best_index: score += self.prev_bias # was previous best choice bias if score > best_score: best_score = score best_index = i if best_index != self.current_best_index: self.reset_current() # New choice self.current_best_index = best_index return self.choices[self.current_best_index], best_score def reset_current(self): if self.current_best_index != -1: reset_method = getattr(self.choices[self.current_best_index], "reset", None) if callable(reset_method): reset_method() def reset(self): self.reset_current() self.current_best_index = -1 class Atba: def __init__(self, bot): pass def utility(self, bot): return 0.5 def execute(self, bot): bot.renderer.draw_string_3d(bot.info.my_car.pos, 1, 1, "Atba", bot.renderer.white()) drive = Drive(bot.info.my_car, bot.info.ball.pos, 1500) drive.step(0.01666) bot.controls = drive.controls
29.365385
92
0.611002
197
1,527
4.502538
0.299492
0.121759
0.135287
0.180383
0.180383
0.069899
0
0
0
0
0
0.022346
0.29666
1,527
51
93
29.941176
0.803538
0.026195
0
0.102564
0
0
0.006065
0
0
0
0
0
0
1
0.179487
false
0.025641
0.051282
0.025641
0.333333
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
0
0
0
1
30c246c819da13e7b7505537f7f56ed38dc95334
7,516
py
Python
ands/ds/BinaryHeap.py
bssrdf/ands
504d91abfe12d316119424ddcb0ad3df3207ee73
[ "MIT" ]
50
2016-12-14T15:10:39.000Z
2022-03-05T23:32:19.000Z
ands/ds/BinaryHeap.py
bssrdf/ands
504d91abfe12d316119424ddcb0ad3df3207ee73
[ "MIT" ]
58
2016-11-17T23:27:52.000Z
2020-12-30T13:55:46.000Z
ands/ds/BinaryHeap.py
bssrdf/ands
504d91abfe12d316119424ddcb0ad3df3207ee73
[ "MIT" ]
15
2016-12-11T12:43:18.000Z
2020-12-17T12:44:42.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 01/07/2015 Updated: 06/04/2018 # Description Contains the abstract class BinaryHeap. # References - Slides by prof. A. Carzaniga - Chapter 13 of Introduction to Algorithms (3rd ed.) - http://www.math.clemson.edu/~warner/M865/HeapDelete.html - https://docs.python.org/3/library/exceptions.html#NotImplementedError - http://effbot.org/pyfaq/how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it.htm - https://en.wikipedia.org/wiki/Heap_(data_structure) - https://arxiv.org/pdf/1012.0956.pdf - http://pymotw.com/2/heapq/ - http://stackoverflow.com/a/29197855/3924118 """ import io import math from abc import ABC, abstractmethod __all__ = ["BinaryHeap", "build_pretty_binary_heap"] class BinaryHeap(ABC): """Abstract class to represent binary heaps. This binary heap allows duplicates. It's the responsibility of the client to ensure that inserted elements are comparable among them. Their order also defines their priority. Public interface: - size - is_empty - clear - add - contains - delete - merge MinHeap, MaxHeap and MinMaxHeap all derive from this class.""" def __init__(self, ls=None): self.heap = [] if not isinstance(ls, list) else ls self._build_heap() @property def size(self) -> int: """Returns the number of elements in this heap. Time complexity: O(1).""" return len(self.heap) def is_empty(self) -> bool: """Returns true if this heap is empty, false otherwise. Time complexity: O(1).""" return self.size == 0 def clear(self) -> None: """Removes all elements from this heap. Time complexity: O(1).""" self.heap.clear() def add(self, x: object) -> None: """Adds object x to this heap. This algorithm proceeds by placing x at an available leaf of this heap, then bubbles up from there, in order to maintain the heap property. Time complexity: O(log n).""" if x is None: raise ValueError("x cannot be None") self.heap.append(x) if self.size > 1: self._push_up(self.size - 1) def contains(self, x: object) -> bool: """Returns true if x is in this heap, false otherwise. Time complexity: O(n).""" if x is None: raise ValueError("x cannot be None") return self._index(x) != -1 def delete(self, x: object) -> None: """Removes the first found x from this heap. If x is not in this heap, LookupError is raised. Time complexity: O(n).""" if x is None: raise ValueError("x cannot be None") i = self._index(x) if i == -1: raise LookupError("x not found") # self has at least one element. if i == self.size - 1: self.heap.pop() else: self._swap(i, self.size - 1) self.heap.pop() self._push_down(i) self._push_up(i) def merge(self, o: "Heap") -> None: """Merges this heap with the o heap. Time complexity: O(n + m).""" self.heap += o.heap self._build_heap() @abstractmethod def _push_down(self, i: int) -> None: """Classical "heapify" operation for heaps.""" pass @abstractmethod def _push_up(self, i: int) -> None: """Classical reverse-heapify operation for heaps.""" pass def _build_heap(self) -> list: """Builds the heap data structure using Robert Floyd's heap construction algorithm. Floyd's algorithm is optimal as long as complexity is expressed in terms of sets of functions described via the asymptotic symbols O, Θ and Ω. Indeed, its linear complexity Θ(n), both in the worst and best case, cannot be improved as each object must be examined at least once. Floyd's algorithm was invented in 1964 as an improvement of the construction phase of the classical heap-sort algorithm introduced earlier that year by Williams J.W.J. Time complexity: Θ(n).""" if self.heap: for index in range(len(self.heap) // 2, -1, -1): self._push_down(index) def _index(self, x: object) -> int: """Returns the index of x in this heap if x is in this heap, otherwise it returns -1. Time complexity: O(n).""" for i, node in enumerate(self.heap): if node == x: return i return -1 def _swap(self, i: int, j: int) -> None: """Swaps elements at indexes i and j. Time complexity: O(1).""" assert self._is_good_index(i) and self._is_good_index(j) self.heap[i], self.heap[j] = self.heap[j], self.heap[i] def _left_index(self, i: int) -> int: """Returns the left child's index of the node at index i, if it exists, otherwise this function returns -1. Time complexity: O(1).""" assert self._is_good_index(i) left = i * 2 + 1 return left if self._is_good_index(left) else -1 def _right_index(self, i: int) -> int: """Returns the right child's index of the node at index i, if it exists, otherwise this function returns -1. Time complexity: O(1).""" assert self._is_good_index(i) right = i * 2 + 2 return right if self._is_good_index(right) else -1 def _parent_index(self, i: int) -> int: """Returns the parent's index of the node at index i. If i = 0, then -1 is returned, because the root has no parent. Time complexity: O(1).""" assert self._is_good_index(i) return -1 if i == 0 else (i - 1) // 2 def _is_good_index(self, i: int) -> bool: """Returns true if i is in the bounds of elf.heap, false otherwise. Time complexity: O(1).""" return False if (i < 0 or i >= self.size) else True def __str__(self): return str(self.heap) def __repr__(self): return build_pretty_binary_heap(self.heap) def build_pretty_binary_heap(heap: list, total_width=36, fill=" ") -> str: """Returns a string (which can be printed) representing heap as a tree. To increase/decrease the horizontal space between nodes, just increase/decrease the float number h_space. To increase/decrease the vertical space between nodes, just increase/decrease the integer number v_space. Note: v_space must be an integer. To change the length of the line under the heap, you can simply change the line_length variable.""" if not isinstance(heap, list): raise TypeError("heap must be an list object") if len(heap) == 0: return "Nothing to print: heap is empty." output = io.StringIO() last_row = -1 h_space = 3.0 v_space = 2 for i, heap_node in enumerate(heap): if i != 0: row = int(math.floor(math.log(i + 1, 2))) else: row = 0 if row != last_row: output.write("\n" * v_space) columns = 2 ** row column_width = int(math.floor((total_width * h_space) / columns)) output.write(str(heap_node).center(column_width, fill)) last_row = row s = output.getvalue() + "\n" line_length = total_width + 15 s += ('-' * line_length + "\n") return s
29.245136
112
0.608302
1,090
7,516
4.100917
0.282569
0.028635
0.043624
0.028635
0.230649
0.184116
0.16264
0.10179
0.10179
0.096197
0
0.018934
0.283262
7,516
256
113
29.359375
0.810841
0.458622
0
0.19
0
0
0.044846
0.006563
0
0
0
0
0.04
1
0.2
false
0.02
0.03
0.02
0.37
0.01
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30c249456403ba1e6baa94afda95313e18e736de
106
py
Python
textProcessing/urls.py
nvakhilnair/Text-Pre-processing-for-Sentiment-Analysis
646b79258af745ea0cdb623b9763de714717259d
[ "MIT" ]
null
null
null
textProcessing/urls.py
nvakhilnair/Text-Pre-processing-for-Sentiment-Analysis
646b79258af745ea0cdb623b9763de714717259d
[ "MIT" ]
null
null
null
textProcessing/urls.py
nvakhilnair/Text-Pre-processing-for-Sentiment-Analysis
646b79258af745ea0cdb623b9763de714717259d
[ "MIT" ]
null
null
null
from .views import API from django.urls import path urlpatterns = [ path('', API.as_view()), ]
11.777778
28
0.632075
14
106
4.714286
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.235849
106
8
29
13.25
0.814815
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
30c2fc61b7992bd51c445c7ef21cc3452bd93e85
2,190
py
Python
product.py
trytonus/trytond-customs-value
ce2097fefab714131fae77ec1f49322141051110
[ "BSD-3-Clause" ]
null
null
null
product.py
trytonus/trytond-customs-value
ce2097fefab714131fae77ec1f49322141051110
[ "BSD-3-Clause" ]
1
2016-04-12T18:10:19.000Z
2016-04-12T18:10:19.000Z
product.py
fulfilio/trytond-customs-value
ce2097fefab714131fae77ec1f49322141051110
[ "BSD-3-Clause" ]
6
2015-08-24T12:44:43.000Z
2016-04-12T10:04:08.000Z
# -*- coding: utf-8 -*- from trytond.pool import PoolMeta from trytond.model import fields from trytond.pyson import Eval, Bool, Not __all__ = ['Product'] __metaclass__ = PoolMeta class Product: "Product" __name__ = 'product.product' country_of_origin = fields.Many2One( 'country.country', 'Country of Origin', ) customs_value = fields.Numeric( "Customs Value", states={ 'invisible': Bool(Eval('use_list_price_as_customs_value')), 'required': Not(Bool(Eval('use_list_price_as_customs_value'))) }, depends=['use_list_price_as_customs_value'], ) use_list_price_as_customs_value = fields.Boolean( "Use List Price As Customs Value ?" ) customs_value_used = fields.Function( fields.Numeric("Customs Value Used"), 'get_customs_value_used' ) customs_description = fields.Text( "Customs Description", states={ 'invisible': Bool(Eval("use_name_as_customs_description")), 'required': Not(Bool(Eval("use_name_as_customs_description"))) }, depends=["use_name_as_customs_description"] ) use_name_as_customs_description = fields.Boolean( "Use Name as Customs Description ?" ) customs_description_used = fields.Function( fields.Text("Customs Description Used"), "get_customs_description_used" ) @classmethod def get_customs_description_used(cls, products, name): return { product.id: ( product.name if product.use_name_as_customs_description else product.customs_description ) for product in products } @staticmethod def default_use_name_as_customs_description(): return True @staticmethod def default_use_list_price_as_customs_value(): return True @classmethod def get_customs_value_used(cls, products, name): return { product.id: ( product.list_price if product.use_list_price_as_customs_value else product.customs_value ) for product in products }
27.375
77
0.636986
238
2,190
5.478992
0.222689
0.128834
0.064417
0.075153
0.41181
0.268405
0.168712
0.115031
0
0
0
0.001263
0.276712
2,190
79
78
27.721519
0.82197
0.013699
0
0.21875
0
0
0.217351
0.108906
0
0
0
0
0
1
0.0625
false
0
0.046875
0.0625
0.3125
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30c67023520b45683449e683c5e3f1a8e0df06b5
523
py
Python
samples/indicator/rsi_test.py
gsamarakoon/ParadoxTrading
2c4024e60b14bf630fd141ccd4c77f197b7c901a
[ "MIT" ]
95
2018-01-14T14:35:35.000Z
2021-03-17T02:10:24.000Z
samples/indicator/rsi_test.py
yutiansut/ParadoxTrading
b915d1491663443bedbb048017abeed3f7dcd4e2
[ "MIT" ]
2
2018-01-14T14:35:51.000Z
2018-07-06T02:57:49.000Z
samples/indicator/rsi_test.py
yutiansut/ParadoxTrading
b915d1491663443bedbb048017abeed3f7dcd4e2
[ "MIT" ]
25
2018-01-14T14:38:08.000Z
2020-07-15T16:03:04.000Z
from ParadoxTrading.Chart import Wizard from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex from ParadoxTrading.Indicator import RSI fetcher = FetchDominantIndex() market = fetcher.fetchDayData('20100701', '20170101', 'rb') rsi = RSI(14).addMany(market).getAllData() wizard = Wizard() price_view = wizard.addView('price', _view_stretch=3) price_view.addLine('market', market.index(), market['closeprice']) sub_view = wizard.addView('sub') sub_view.addLine('rsi', rsi.index(), rsi['rsi']) wizard.show()
27.526316
66
0.76673
63
523
6.269841
0.460317
0.136709
0.086076
0
0
0
0
0
0
0
0
0.039832
0.087954
523
18
67
29.055556
0.78826
0
0
0
0
0
0.091778
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30c7a9362a7e00f4dea1c4a3028e5f5f01134985
406
py
Python
Multipliers/mult.py
ThoAppelsin/pure-music
ab1a8604cc24b1dbf329a556154d5f0cc7f2236b
[ "MIT" ]
null
null
null
Multipliers/mult.py
ThoAppelsin/pure-music
ab1a8604cc24b1dbf329a556154d5f0cc7f2236b
[ "MIT" ]
null
null
null
Multipliers/mult.py
ThoAppelsin/pure-music
ab1a8604cc24b1dbf329a556154d5f0cc7f2236b
[ "MIT" ]
null
null
null
import fractions from pprint import pprint lcm_limit = 32 octave_limit = 4 candidates = [(x, y) for x in range(1, lcm_limit + 1) for y in range(1, lcm_limit + 1)] candidates = [c for c in candidates if fractions.gcd(c[0], c[1]) == 1 and c[0] * c[1] <= lcm_limit and 1 / octave_limit <= c[0] / c[1] <= octave_limit] candidates.sort(key=lambda c: c[0] / c[1]) pprint(candidates) print(len(candidates))
25.375
87
0.672414
76
406
3.5
0.342105
0.120301
0.045113
0.06015
0.12782
0.12782
0
0
0
0
0
0.050746
0.174877
406
16
88
25.375
0.743284
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.166667
0
0.166667
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
0
0
0
1
0
30c828d9ab280febb16bf5ef11feff5b3f99b8e8
573
py
Python
Python3/24.swap-nodes-in-pairs.py
canhetingsky/LeetCode
67f4eaeb5746d361056d08df828c653f89dd9fdd
[ "MIT" ]
1
2019-09-23T13:25:21.000Z
2019-09-23T13:25:21.000Z
Python3/24.swap-nodes-in-pairs.py
canhetingsky/LeetCode
67f4eaeb5746d361056d08df828c653f89dd9fdd
[ "MIT" ]
6
2019-10-25T10:17:50.000Z
2019-11-17T05:07:19.000Z
Python3/24.swap-nodes-in-pairs.py
canhetingsky/LeetCode
67f4eaeb5746d361056d08df828c653f89dd9fdd
[ "MIT" ]
null
null
null
# # @lc app=leetcode id=24 lang=python3 # # [24] Swap Nodes in Pairs # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: curr = dummyHead = ListNode(0) curr.next = head while curr.next and curr.next.next: l = curr.next r = l.next curr.next, r.next, l.next = r, l, r.next curr = l return dummyHead.next # @lc code=end
19.758621
52
0.556719
78
573
4.038462
0.5
0.126984
0.057143
0
0
0
0
0
0
0
0
0.015584
0.328098
573
28
53
20.464286
0.802597
0.369983
0
0
0
0
0
0
0
0
0
0
0
1
0.1
false
0
0
0
0.3
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30cae5fcba520d2336e9de37bde53bf9f641c26d
1,593
py
Python
src/Controllers/CEOControl.py
shulip/ShoppingMallSystem
01e5a04a8353ca319ed2dc002fc358f6e44c33dd
[ "MIT" ]
null
null
null
src/Controllers/CEOControl.py
shulip/ShoppingMallSystem
01e5a04a8353ca319ed2dc002fc358f6e44c33dd
[ "MIT" ]
null
null
null
src/Controllers/CEOControl.py
shulip/ShoppingMallSystem
01e5a04a8353ca319ed2dc002fc358f6e44c33dd
[ "MIT" ]
1
2021-04-22T15:14:21.000Z
2021-04-22T15:14:21.000Z
####################################################### # # CEOControl.py # Python implementation of the Class CEOControl # Generated by Enterprise Architect # Created on: 16-5��-2019 12:06:10 # Original author: ���� # ####################################################### from Models.Statement import Statement from Models.Contract import Contract from Controllers.User import User from Controllers.Login import Login class CEOControl(User): def __init__(self,ID): super().__init__() self.__identity = 'ceo' self.__ID = ID self.m_Statement = Statement() self.__contractCon = Contract() def set_contract_ceoaffirm_by_id(self,user_id, ceoaffirm): self.__contractCon.set_contract_ceoaffirm_by_id(user_id, ceoaffirm) def set_contract_ceosign_by_id(self,user_id, ceosign): self.__contractCon.set_contract_ceosign_by_id(user_id, ceosign) def check_all_information(self): pass def get_all_contracts(self): return self.m_Statement.contracts def get_all_receipts(self): return self.m_Statement.receipts def get_all_receivable(self): return self.m_Statement.receivable def confirm_contract(self): pass def login(self,name,password,identity): super().login(name,password,identity) def registration(self): pass def remind_arrearage(self): pass def remind_expiration_con(self): pass def sign_contract(self): pass if __name__ == '__main__': ceo = CEOControl() ceo.login('as',12,'ceo')
24.890625
75
0.640301
188
1,593
5.12234
0.340426
0.049844
0.057113
0.046729
0.19107
0
0
0
0
0
0.003766
0.011876
0.207156
1,593
64
76
24.890625
0.745843
0.096045
0
0.157895
1
0
0.012112
0
0
0
0
0
0
1
0.342105
false
0.210526
0.105263
0.078947
0.552632
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
4
30cb99ee5910824c55927f1d17d6bec03ac81d17
2,104
py
Python
apps/plugins/plugin.py
rmdes/tanzawa
d53baa10bd6c217cd18628437a88a43e3bd02b70
[ "Apache-2.0" ]
25
2021-06-13T03:38:44.000Z
2022-03-15T15:53:31.000Z
apps/plugins/plugin.py
rmdes/tanzawa
d53baa10bd6c217cd18628437a88a43e3bd02b70
[ "Apache-2.0" ]
59
2021-06-12T23:35:06.000Z
2022-03-24T21:40:24.000Z
apps/plugins/plugin.py
rmdes/tanzawa
d53baa10bd6c217cd18628437a88a43e3bd02b70
[ "Apache-2.0" ]
null
null
null
import abc import pathlib from importlib import util as importlib_util from typing import Optional, Protocol from plugins.models import MPlugin class TopNavProtocol(Protocol): @property def public_has_top_nav(self) -> bool: """Does this plugin have public facing top nav?""" return False class Plugin(abc.ABC, TopNavProtocol): name: str description: str # A unique namespaced identifier for the plugin identifier: str def is_enabled(self) -> bool: return MPlugin.objects.filter(identifier=self.identifier).values_list("enabled", flat=True).first() or False @property def plugin_module(self) -> str: """Return the python module path to the plugin's module""" return ".".join(self.__module__.split(".")[:-1]) @property def settings_url(self) -> str: """The main URL for configuring the plugin. Plugins that do not provide any configuration via the admin should return a blank string. """ return "" def render_navigation( self, *, context, render_location: str, ) -> str: """Render the public facing navigation menu item.""" return "" @property def urls(self) -> Optional[str]: """Return the path to the _public_ url configuration for a plugin""" # TODO: Make this check for a urls.py and return None if not exists return f"{self.plugin_module}.urls" @property def admin_urls(self) -> Optional[str]: """Return the path to the _admin_ url configuration for a plugin""" return f"{self.plugin_module}.admin_urls" @property def has_migrations(self) -> bool: """Check if a plugin has migration directory. Uses pathlib instead of importlib to avoid importing modules. """ module_spec = importlib_util.find_spec(self.__module__) if not module_spec or not module_spec.origin: return False migration_module = pathlib.Path(module_spec.origin).parent / "migrations" return migration_module.is_dir()
30.057143
116
0.654943
265
2,104
5.064151
0.384906
0.04918
0.026826
0.028316
0.128167
0.055142
0.055142
0.055142
0.055142
0
0
0.000638
0.254753
2,104
69
117
30.492754
0.85523
0.294677
0
0.243902
0
0
0.053079
0.039632
0
0
0
0.014493
0
1
0.195122
false
0
0.146341
0.02439
0.682927
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
1
0
0
2
30cc83890770a4003caacdcf071dce2fdf40b1e0
1,102
py
Python
lesson_01/005.py
amindmobile/geekbrains-python-002
4bc2f7af755d00e73ddc48f1138830cb78e87034
[ "MIT" ]
null
null
null
lesson_01/005.py
amindmobile/geekbrains-python-002
4bc2f7af755d00e73ddc48f1138830cb78e87034
[ "MIT" ]
null
null
null
lesson_01/005.py
amindmobile/geekbrains-python-002
4bc2f7af755d00e73ddc48f1138830cb78e87034
[ "MIT" ]
null
null
null
# Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма # (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если # фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите # численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника. earnings = float(input("Укажите сумму выручки: ")) expenses = float(input("Укажите сумму расходов: ")) if earnings > expenses: # если прибыль больше расходов employee = int(input("Сколько служащих в вашей организации: ")) global_Profit = earnings - expenses # выручка employee_Profit = global_Profit / employee # сколько денег зарабатывает один сотрудник print(f"Фирма в прибыли {global_Profit:.2f}¥, с рентабельностью {earnings / expenses:.2f}%") print(f"Примерно {employee_Profit:.2f}¥ зарабатывает для вас каждый служащий.") elif earnings == expenses: print("У вас бестолковая организация, она работает 'в ноль'.") else: print("У вас убытки.")
55.1
119
0.777677
140
1,102
6.114286
0.564286
0.074766
0.03972
0.051402
0
0
0
0
0
0
0
0.003155
0.137024
1,102
19
120
58
0.892744
0.46461
0
0
0
0
0.519793
0.07401
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30ccc835225f0f39d9631aa44f69223b6d2b4527
5,825
py
Python
ratschlab_common/io/dataframe_formats.py
ratschlab/ratschlab-common
e7d71c3220c8b991d9d1c2f2de5cf393fce8357c
[ "MIT" ]
1
2021-02-01T22:45:24.000Z
2021-02-01T22:45:24.000Z
ratschlab_common/io/dataframe_formats.py
ratschlab/ratschlab-common
e7d71c3220c8b991d9d1c2f2de5cf393fce8357c
[ "MIT" ]
2
2019-11-25T09:10:26.000Z
2020-02-14T13:08:28.000Z
ratschlab_common/io/dataframe_formats.py
ratschlab/ratschlab-common
e7d71c3220c8b991d9d1c2f2de5cf393fce8357c
[ "MIT" ]
1
2018-09-20T01:38:01.000Z
2018-09-20T01:38:01.000Z
import os from abc import ABCMeta, abstractmethod from types import MappingProxyType import dask.dataframe import pandas as pd class AbstractDataFrameFormat: """ Provides helper functions to serialize and deserialize pandas and dask dataframes. Instances of such classes can define their own default options via the constructor. If none are specified, the library default are taken as default options. Default options can be overwritten in the calling functions. """ __metaclass__ = ABCMeta def __init__(self, default_reading_options=None, default_writing_options=None): self.default_reading_options = default_reading_options self.default_writing_options = default_writing_options @abstractmethod def read_df(self, file_path, options=None): raise NotImplementedError @abstractmethod def write_df(self, df, file_path, options=None): raise NotImplementedError @abstractmethod def read_dask_df(self, directory, options=None): raise NotImplementedError @abstractmethod def write_dask_df(self, ddf, directory, options=None, compute=False): raise NotImplementedError @abstractmethod def format_extension(self): raise NotImplementedError @abstractmethod def _library_default_reading_options(self): raise NotImplementedError @abstractmethod def _library_default_writing_options(self): raise NotImplementedError def get_default_reading_options(self): """ Default options used, if no options are passed in the read functions :return: dictionary with options """ if self.default_reading_options: return self.default_reading_options return self._library_default_reading_options() def get_default_writing_options(self): """ Default options used, if no options are passed in the write functions :return: dictionary with options """ if self.default_writing_options: return self.default_writing_options return self._library_default_writing_options() @staticmethod def _get_effective_options(params, defaults): if not params: effective_params = defaults else: effective_params = dict(defaults, **params) return effective_params class ParquetDataFrameFormat(AbstractDataFrameFormat): DEFAULT_ENGINE = 'pyarrow' def read_df(self, file_path, options=None): e = ParquetDataFrameFormat._get_effective_options(options, self.get_default_reading_options()) return pd.read_parquet(file_path, **e) def write_df(self, df, file_path, options=None): e = self._get_effective_options(options, self.get_default_writing_options()) df.to_parquet(file_path, **e) def read_dask_df(self, directory, options=None): in_pattern = os.path.join(directory, '*.{}'.format(self.format_extension())) e = ParquetDataFrameFormat._get_effective_options(options, self.get_default_reading_options()) return dask.dataframe.read_parquet(str(in_pattern), **e) def write_dask_df(self, ddf, directory, options=None, compute=False): e = ParquetDataFrameFormat._get_effective_options(options, self.get_default_writing_options()) return ddf.to_parquet(str(directory), compute=compute, **e) def format_extension(self): return "parquet" def _library_default_reading_options(self): return MappingProxyType({'engine': self.DEFAULT_ENGINE}) def _library_default_writing_options(self): return MappingProxyType({'engine': self.DEFAULT_ENGINE, 'compression': 'snappy'}) class HdfDataFrameFormat(AbstractDataFrameFormat): DEFAULT_KEY = 'data' def read_df(self, file_path, options=None): eff = HdfDataFrameFormat._get_effective_options(options, self.get_default_reading_options()) return pd.read_hdf(file_path, **eff) def write_df(self, df, file_path, options=None): eff = HdfDataFrameFormat._get_effective_options(options, self.get_default_writing_options()) df.to_hdf(file_path, **eff) def read_dask_df(self, directory, options=None): in_pattern = os.path.join(directory, '*.{}'.format(self.format_extension())) e = HdfDataFrameFormat._get_effective_options(options, self.get_default_reading_options()) return dask.dataframe.read_hdf(str(in_pattern), **e) def write_dask_df(self, ddf, directory, options=None, compute=False): e = HdfDataFrameFormat._get_effective_options(options, self.get_default_writing_options()) out_pattern = os.path.join(directory, 'part-*.{}'.format(self.format_extension())) return ddf.to_hdf(out_pattern, compute=compute, **e) def format_extension(self): return 'h5' def _library_default_reading_options(self): return MappingProxyType({'mode': 'r', 'key': self.DEFAULT_KEY}) def _library_default_writing_options(self): return MappingProxyType({'key': self.DEFAULT_KEY, 'format': 'table', 'complib': 'blosc:lz4', 'complevel': 5})
36.63522
93
0.633305
599
5,825
5.868114
0.175292
0.053201
0.083642
0.059175
0.672262
0.626458
0.58606
0.541679
0.357326
0.311238
0
0.000725
0.289442
5,825
158
94
36.867089
0.848514
0.08721
0
0.537736
0
0
0.021652
0
0
0
0
0
0
1
0.235849
false
0
0.04717
0.056604
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
30cd6249b329b46a03cfecc7898ea184033964d2
378
py
Python
HannaL Programming 12 Portfolio/Hanna L Chapter 1 Lab/AreaOfTrapezoidCalculator.py
HannaLuu/Programming12_Portfolio
b6b480b557ab88e428580c40fda2bb8f10ac115a
[ "MIT" ]
null
null
null
HannaL Programming 12 Portfolio/Hanna L Chapter 1 Lab/AreaOfTrapezoidCalculator.py
HannaLuu/Programming12_Portfolio
b6b480b557ab88e428580c40fda2bb8f10ac115a
[ "MIT" ]
null
null
null
HannaL Programming 12 Portfolio/Hanna L Chapter 1 Lab/AreaOfTrapezoidCalculator.py
HannaLuu/Programming12_Portfolio
b6b480b557ab88e428580c40fda2bb8f10ac115a
[ "MIT" ]
null
null
null
print("This program calculates the area of a trapezoid.") height = float(input("Enter height of trapezoid:")) top_base_length = float(input("Enter top length of trapezoid:")) bottom_base_length = float(input("Enter bottom length of trapezoid:")) area_of_trapezoid = .5 * (top_base_length + bottom_base_length) * height print ("The area of the trapezoid is," , area_of_trapezoid)
63
72
0.769841
57
378
4.894737
0.333333
0.197133
0.16129
0.143369
0.179211
0
0
0
0
0
0
0.003003
0.119048
378
6
73
63
0.834835
0
0
0
0
0
0.437995
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
30d0d4d6a16170d4deabeabcc9a6af64c6ea52e2
5,498
py
Python
src/pumpwood_djangoviews/action.py
Murabei-OpenSource-Codes/pumpwood-djangoviews
792fb825a5e924d1b7307c0bc3b40d798b68946d
[ "BSD-3-Clause" ]
null
null
null
src/pumpwood_djangoviews/action.py
Murabei-OpenSource-Codes/pumpwood-djangoviews
792fb825a5e924d1b7307c0bc3b40d798b68946d
[ "BSD-3-Clause" ]
null
null
null
src/pumpwood_djangoviews/action.py
Murabei-OpenSource-Codes/pumpwood-djangoviews
792fb825a5e924d1b7307c0bc3b40d798b68946d
[ "BSD-3-Clause" ]
null
null
null
"""Define actions decorator.""" import inspect import pandas as pd from typing import cast from datetime import date, datetime from typing import Callable from pumpwood_communication.exceptions import PumpWoodActionArgsException class Action: """Define a Action class to be used in decorator action.""" def __init__(self, func: Callable, info: str, auth_header: str = None): """.""" signature = inspect.signature(func) function_parameters = signature.parameters parameters = {} is_static_function = True for key in function_parameters.keys(): if key in ['self', 'cls', auth_header]: if key == "self": is_static_function = False continue param = function_parameters[key] if param.annotation == inspect.Parameter.empty: if inspect.Parameter.empty: param_type = "Any" else: param_type = type(param.default).__name__ else: param_type = param.annotation \ if type(param.annotation) == str \ else param.annotation.__name__ parameters[key] = { "required": param.default is inspect.Parameter.empty, "type": param_type } if param.default is not inspect.Parameter.empty: parameters[key]['default_value'] = param.default self.action_name = func.__name__ self.is_static_function = is_static_function self.parameters = parameters self.info = info self.auth_header = auth_header def to_dict(self): """Return dict representation of the action.""" return { "action_name": self.action_name, "is_static_function": self.is_static_function, "info": self.info, "parameters": self.parameters} def action(info: str = "", auth_header: str = None): """ Define decorator that will convert the function into a rest action. Args: info: Just an information about the decorated function that will be returned in GET /rest/<model_class>/actions/. Kwargs: request_user (str): Variable that will receive logged user. Returns: func: Action decorator. """ def action_decorator(func): func.is_action = True func.action_object = Action( func=func, info=info, auth_header=auth_header) return func return action_decorator def load_action_parameters(func: Callable, parameters: dict, request): """Cast arguments to its original types.""" signature = inspect.signature(func) function_parameters = signature.parameters # Loaded parameters for action run return_parameters = {} # Errors found when processing the parameters errors = {} # Unused parameters, passed but not in function unused_params = set(parameters.keys()) - set(function_parameters.keys()) # The request user parameter, set the logged user auth_header = func.action_object.auth_header if len(unused_params) != 0: errors["unused args"] = { "type": "unused args", "message": list(unused_params)} for key in function_parameters.keys(): # pass if arguments are self and cls for classmethods if key in ['self', 'cls']: continue # If arguent is the request user one, set with the logged user if key == auth_header: token = request.headers.get('Authorization') return_parameters[key] = {'Authorization': token} continue param_type = function_parameters[key] par_value = parameters.get(key) if par_value is not None: try: if param_type.annotation == date: return_parameters[key] = pd.to_datetime(par_value).date() elif param_type.annotation == datetime: return_parameters[key] = \ pd.to_datetime(par_value).to_pydatetime() else: return_parameters[key] = param_type.annotation(par_value) # If any error ocorrur then still try to cast data from python # typing except Exception: try: return_parameters[key] = return_parameters[key] = cast( param_type.annotation, par_value) except Exception as e: errors[key] = { "type": "unserialize", "message": str(e)} # If parameter is not passed and required return error elif param_type.default is inspect.Parameter.empty: errors[key] = { "type": "nodefault", "message": "not set and no default"} # Raise if there is any error in serilization if len(errors.keys()) != 0: template = "[{key}]: {message}" error_msg = "error when unserializing function arguments:\n" error_list = [] for key in errors.keys(): error_list.append(template.format( key=key, message=errors[key]["message"])) error_msg = error_msg + "\n".join(error_list) raise PumpWoodActionArgsException( status_code=400, message=error_msg, payload={ "arg_errors": errors}) return return_parameters
35.934641
77
0.591124
595
5,498
5.295798
0.247059
0.031736
0.030467
0.019042
0.160584
0.10092
0.066646
0.066646
0
0
0
0.001342
0.322117
5,498
152
78
36.171053
0.844111
0.166788
0
0.153846
0
0
0.065526
0
0
0
0
0
0
1
0.048077
false
0
0.057692
0
0.153846
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30d36f714ffcf578c5b755784494e079e2271651
5,426
py
Python
logistic-regression/mnist_binary_classifier.py
eliben/deep-learning-samples
d5ca86c5db664fabfb302cbbc231c50ec3d6a103
[ "Unlicense" ]
183
2015-12-29T07:21:24.000Z
2022-01-18T01:19:23.000Z
logistic-regression/mnist_binary_classifier.py
eliben/deep-learning-samples
d5ca86c5db664fabfb302cbbc231c50ec3d6a103
[ "Unlicense" ]
null
null
null
logistic-regression/mnist_binary_classifier.py
eliben/deep-learning-samples
d5ca86c5db664fabfb302cbbc231c50ec3d6a103
[ "Unlicense" ]
68
2016-06-02T15:31:51.000Z
2021-09-08T19:58:10.000Z
# A binary linear classifier for MNIST digits. # # Poses a binary classification problem - is this image showing digit D (for # some D, for example "4"); trains a linear classifier to solve the problem. # # Eli Bendersky (http://eli.thegreenplace.net) # This code is in the public domain from __future__ import print_function import argparse import numpy as np import sys from mnist_dataset import * from regression_lib import * if __name__ == '__main__': argparser = argparse.ArgumentParser() argparser.add_argument('--type', choices=['binary', 'logistic'], default='logistic', help='Type of classification: binary (yes/no result)' 'or logistic (probability of "yes" result).') argparser.add_argument('--set-seed', default=-1, type=int, help='Set random seed to this number (if > 0).') argparser.add_argument('--nsteps', default=150, type=int, help='Number of steps for gradient descent.') argparser.add_argument('--recognize-digit', default=4, type=int, help='Digit to recognize in training.') argparser.add_argument('--display-test', default=-1, type=int, help='Display this image from the test data ' 'set and exit.') argparser.add_argument('--normalize', action='store_true', default=False, help='Normalize data: (x-mu)/sigma.') argparser.add_argument('--report-mistakes', action='store_true', default=False, help='Report all mistakes made in classification.') args = argparser.parse_args() if args.set_seed > 0: np.random.seed(args.set_seed) # Load MNIST data into memory; this may download the MNIST dataset from # the web if not already on disk. (X_train, y_train), (X_valid, y_valid), (X_test, y_test) = get_mnist_data() if args.display_test > -1: display_mnist_image(X_test[args.display_test], y_test[args.display_test]) sys.exit(1) if args.normalize: print('Normalizing data...') X_train_normalized, mu, sigma = feature_normalize(X_train) X_train_augmented = augment_1s_column(X_train_normalized) X_valid_augmented = augment_1s_column((X_valid - mu) / sigma) X_test_augmented = augment_1s_column((X_test - mu) / sigma) else: X_train_augmented = augment_1s_column(X_train) X_valid_augmented = augment_1s_column(X_valid) X_test_augmented = augment_1s_column(X_test) # Convert y_train to binary "is this a the digit D", with +1 for D, -1 # otherwise. Also reshape it into a column vector as regression_lib expects. D = args.recognize_digit print('Training for digit', D) y_train_binary = convert_y_to_binary(y_train, D) y_valid_binary = convert_y_to_binary(y_valid, D) y_test_binary = convert_y_to_binary(y_test, D) # Hyperparameters. LEARNING_RATE = 0.08 REG_BETA=0.03 if args.type == 'binary': print('Training binary classifier with hinge loss...') lossfunc = lambda X, y, theta: hinge_loss(X, y, theta, reg_beta=REG_BETA) else: print('Training logistic classifier with cross-entropy loss...') lossfunc = lambda X, y, theta: cross_entropy_loss_binary( X, y, theta, reg_beta=REG_BETA) n = X_train_augmented.shape[1] gi = gradient_descent(X_train_augmented, y_train_binary, init_theta=np.random.randn(n, 1), lossfunc=lossfunc, batch_size=256, nsteps=args.nsteps, learning_rate=LEARNING_RATE) for i, (theta, loss) in enumerate(gi): if i % 50 == 0 and i > 0: print(i, loss) # We use predict_binary for both binary and logistic classification. # See comment on predict_binary to understand why it works for # logistic as well. yhat = predict_binary(X_train_augmented, theta) yhat_valid = predict_binary(X_valid_augmented, theta) print('train accuracy =', np.mean(yhat == y_train_binary)) print('valid accuracy =', np.mean(yhat_valid == y_valid_binary)) print('After {0} training steps...'.format(args.nsteps)) print('loss =', loss) yhat_valid = predict_binary(X_valid_augmented, theta) yhat_test = predict_binary(X_test_augmented, theta) print('valid accuracy =', np.mean(yhat_valid == y_valid_binary)) print('test accuracy =', np.mean(yhat_test == y_test_binary)) # For logistic, get predicted probabilities as well. if args.type == 'logistic': yhat_test_prob = predict_logistic_probability(X_test_augmented, theta) if args.report_mistakes: for i in range(yhat_test.size): if yhat_test[i][0] != y_test_binary[i][0]: print('@ {0}: predict {1}, actual {2}'.format( i, yhat_test[i][0], y_test_binary[i][0]), end='') if args.type == 'logistic': print('; prob={0}'.format(yhat_test_prob[i][0])) else: print('')
44.113821
80
0.605418
691
5,426
4.51809
0.250362
0.019218
0.044843
0.046124
0.225176
0.213004
0.155029
0.141576
0.046765
0.032031
0
0.011449
0.291743
5,426
122
81
44.47541
0.800937
0.13509
0
0.097826
0
0
0.159752
0
0
0
0
0
0
1
0
false
0
0.065217
0
0.065217
0.163043
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30d54fa27b6407cf613e47ef65f685b9f45ab6fc
37
py
Python
src/RGT/userProfile/__init__.py
danrg/RGT-tool
115ba9a93686595699b3e182958921b3d60382b3
[ "MIT" ]
7
2015-02-09T12:12:04.000Z
2019-03-31T08:23:36.000Z
src/RGT/userProfile/__init__.py
danrg/RGT-tool
115ba9a93686595699b3e182958921b3d60382b3
[ "MIT" ]
3
2015-07-05T20:49:14.000Z
2017-07-03T19:45:18.000Z
src/RGT/userProfile/__init__.py
danrg/RGT-tool
115ba9a93686595699b3e182958921b3d60382b3
[ "MIT" ]
1
2021-03-23T14:01:22.000Z
2021-03-23T14:01:22.000Z
from views import displayUserProfile
18.5
36
0.891892
4
37
8.25
1
0
0
0
0
0
0
0
0
0
0
0
0.108108
37
1
37
37
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
6
30d65ba961b4012c418911d00c91a40240451543
5,409
py
Python
IEEE-ASHRAE_kernel/01_data_minify.py
Daniel1586/Initiative_Kaggle
945e0a2ebe94aa7ee3ed59dd0de53d9a1b82aa05
[ "MIT" ]
1
2019-08-12T14:28:22.000Z
2019-08-12T14:28:22.000Z
IEEE-ASHRAE_kernel/01_data_minify.py
Daniel1586/Initiative_Kaggle
945e0a2ebe94aa7ee3ed59dd0de53d9a1b82aa05
[ "MIT" ]
null
null
null
IEEE-ASHRAE_kernel/01_data_minify.py
Daniel1586/Initiative_Kaggle
945e0a2ebe94aa7ee3ed59dd0de53d9a1b82aa05
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ (https://www.kaggle.com/c/ashrae-energy-prediction). Train shape:(590540,394),identity(144233,41)--isFraud 3.5% Test shape:(506691,393),identity(141907,41) ############### TF Version: 1.13.1/Python Version: 3.7 ############### """ import os import math import random import warnings import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder warnings.filterwarnings('ignore') # make all processes deterministic/固定随机数生成器的种子 # environ是一个字符串所对应环境的映像对象,PYTHONHASHSEED为其中的环境变量 # Python会用一个随机的种子来生成str/bytes/datetime对象的hash值; # 如果该环境变量被设定为一个数字,它就被当作一个固定的种子来生成str/bytes/datetime对象的hash值 def set_seed(seed=0): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) # reduce memory for dataframe/优化dataframe数据格式,减少内存占用 def reduce_mem_usage(df, verbose=True): numerics = ["int16", "int32", "int64", "float16", "float32", "float64"] start_mem = df.memory_usage().sum() / 1024**2 for col in df.columns: col_type = df[col].dtypes if col_type in numerics: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == "int": if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) end_mem = df.memory_usage().sum() / 1024**2 reduction = 100*(start_mem-end_mem)/start_mem if verbose: print("Default Mem. {:.2f} Mb, Optimized Mem. {:.2f} Mb, Reduction {:.1f}%". format(start_mem, end_mem, reduction)) return df if __name__ == "__main__": print("========== 1.Set random seed ...") SEED = 42 set_seed(SEED) LOCAL_TEST = False print("========== 2.Load csv data ...") dir_data_csv = os.getcwd() + "\\great-energy-predictor\\" train_df = pd.read_csv(dir_data_csv + "\\train.csv") infer_df = pd.read_csv(dir_data_csv + "\\test.csv") build_df = pd.read_csv(dir_data_csv + "\\building_metadata.csv") train_weat_df = pd.read_csv(dir_data_csv + "\\weather_train.csv") infer_weat_df = pd.read_csv(dir_data_csv + "\\weather_test.csv") print('#' * 30) print('Main data:', list(train_df), train_df.info()) print('#' * 30) print('Buildings data:', list(build_df), build_df.info()) print('#' * 30) print('Weather data:', list(train_weat_df), train_weat_df.info()) print('#' * 30) for df in [train_df, infer_df, train_weat_df, infer_weat_df]: df["timestamp"] = pd.to_datetime(df["timestamp"]) for df in [train_df, infer_df]: df["DT_M"] = df["timestamp"].dt.month.astype(np.int8) df["DT_W"] = df["timestamp"].dt.weekofyear.astype(np.int8) df["DT_D"] = df["timestamp"].dt.dayofyear.astype(np.int16) df["DT_hour"] = df["timestamp"].dt.hour.astype(np.int8) df["DT_day_week"] = df["timestamp"].dt.dayofweek.astype(np.int8) df["DT_day_month"] = df["timestamp"].dt.day.astype(np.int8) df["DT_week_month"] = df["timestamp"].dt.day / 7 df["DT_week_month"] = df["DT_week_month"].apply(lambda x: math.ceil(x)).astype(np.int8) print("========== 3.ETL tran categorical feature [String] ...") build_df['primary_use'] = build_df['primary_use'].astype('category') build_df['floor_count'] = build_df['floor_count'].fillna(0).astype(np.int8) build_df['year_built'] = build_df['year_built'].fillna(-999).astype(np.int16) le = LabelEncoder() build_df['primary_use'] = build_df['primary_use'].astype(str) build_df['primary_use'] = le.fit_transform(build_df['primary_use']).astype(np.int8) do_not_convert = ['category', 'datetime64[ns]', 'object'] for df in [train_df, infer_df, build_df, train_weat_df, infer_weat_df]: original = df.copy() df = reduce_mem_usage(df) for col in list(df): if df[col].dtype.name not in do_not_convert: if (df[col] - original[col]).sum() != 0: df[col] = original[col] print('Bad transformation', col) print('#' * 30) print('Main data:', list(train_df), train_df.info()) print('#' * 30) print('Buildings data:', list(build_df), build_df.info()) print('#' * 30) print('Weather data:', list(train_weat_df), train_weat_df.info()) print('#' * 30) print("========== 4.Save pkl ...") train_df.to_pickle("train.pkl") infer_df.to_pickle("infer.pkl") build_df.to_pickle("build.pkl") train_weat_df.to_pickle("weather_train.pkl") infer_weat_df.to_pickle("weather_infer.pkl")
41.290076
95
0.612683
778
5,409
4.062982
0.244216
0.031636
0.034166
0.022145
0.388168
0.319203
0.285353
0.139829
0.139829
0.094274
0
0.035145
0.210945
5,409
130
96
41.607692
0.705483
0.094842
0
0.158416
0
0
0.174314
0.010037
0
0
0
0
0
1
0.019802
false
0
0.069307
0
0.09901
0.19802
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30d759a40bbb943fa4065bfc1dc4dff7a8c4a0fa
8,774
py
Python
src/optim/DeepSAD_trainer.py
wych1005/Deep-SAD-PyTorch
af93186a38ed30985dc155d1b00b90aa181cfe0b
[ "MIT" ]
null
null
null
src/optim/DeepSAD_trainer.py
wych1005/Deep-SAD-PyTorch
af93186a38ed30985dc155d1b00b90aa181cfe0b
[ "MIT" ]
null
null
null
src/optim/DeepSAD_trainer.py
wych1005/Deep-SAD-PyTorch
af93186a38ed30985dc155d1b00b90aa181cfe0b
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt from base.base_trainer import BaseTrainer from base.base_dataset import BaseADDataset from base.base_net import BaseNet import seaborn as sns from torch.utils.data.dataloader import DataLoader from sklearn.metrics import roc_auc_score, confusion_matrix, average_precision_score, roc_curve, precision_recall_curve import logging import time import torch import torch.optim as optim import numpy as np class DeepSADTrainer(BaseTrainer): def __init__(self, c, eta: float, optimizer_name: str = 'adam', lr: float = 0.001, n_epochs: int = 150, lr_milestones: tuple = (), batch_size: int = 128, weight_decay: float = 1e-6, device: str = 'cuda', n_jobs_dataloader: int = 0): super().__init__(optimizer_name, lr, n_epochs, lr_milestones, batch_size, weight_decay, device, n_jobs_dataloader) # Deep SAD parameters self.c = torch.tensor(c, device=self.device) if c is not None else None self.eta = eta # Optimization parameters self.eps = 1e-6 # Results self.train_time = None self.test_auc = None self.test_auprc = None self.test_confusion_matrix = None self.test_time = None self.test_scores = None self.roc_x = None self.roc_y = None self.prec = None self.rec = None def train(self, dataset: BaseADDataset, net: BaseNet): logger = logging.getLogger() # Get train data loader train_loader, _ = dataset.loaders(batch_size=self.batch_size, num_workers=self.n_jobs_dataloader) # Set device for network net = net.to(self.device) # Set optimizer (Adam optimizer for now) optimizer = optim.Adam(net.parameters(), lr=self.lr, weight_decay=self.weight_decay) # Set learning rate scheduler scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=self.lr_milestones, gamma=0.1) # Initialize hypersphere center c (if c not loaded) if self.c is None: logger.info('Initializing center c...') self.c = self.init_center_c(train_loader, net) logger.info('Center c initialized.') # Training logger.info('Starting training...') start_time = time.time() net.train() for epoch in range(self.n_epochs): scheduler.step() if epoch in self.lr_milestones: logger.info(' LR scheduler: new learning rate is %g' % float(scheduler.get_lr()[0])) epoch_loss = 0.0 n_batches = 0 epoch_start_time = time.time() for data in train_loader: inputs, _, semi_targets, _ = data inputs, semi_targets = inputs.to(self.device), semi_targets.to(self.device) # Zero the network parameter gradients optimizer.zero_grad() # Update network parameters via backpropagation: forward + backward + optimize outputs = net(inputs) dist = torch.sum((outputs - self.c) ** 2, dim=1) losses = torch.where(semi_targets == 0, dist, self.eta * ((dist + self.eps) ** semi_targets.float())) loss = torch.mean(losses) loss.backward() optimizer.step() epoch_loss += loss.item() n_batches += 1 # log epoch statistics epoch_train_time = time.time() - epoch_start_time logger.info(f'| Epoch: {epoch + 1:03}/{self.n_epochs:03} | Train Time: {epoch_train_time:.3f}s ' f'| Train Loss: {epoch_loss / n_batches:.6f} |') self.train_time = time.time() - start_time logger.info('Training Time: {:.3f}s'.format(self.train_time)) logger.info('Finished training.') return net def test(self, dataset: BaseADDataset, net: BaseNet): logger = logging.getLogger() # Get test data loader _, test_loader = dataset.loaders(batch_size=self.batch_size, num_workers=self.n_jobs_dataloader) # Set device for network net = net.to(self.device) # Testing logger.info('Starting testing...') epoch_loss = 0.0 n_batches = 0 start_time = time.time() idx_label_score = [] net.eval() with torch.no_grad(): for data in test_loader: inputs, labels, semi_targets, idx = data inputs = inputs.to(self.device) labels = labels.to(self.device) semi_targets = semi_targets.to(self.device) idx = idx.to(self.device) outputs = net(inputs) dist = torch.sum((outputs - self.c) ** 2, dim=1) losses = torch.where(semi_targets == 0, dist, self.eta * ((dist + self.eps) ** semi_targets.float())) loss = torch.mean(losses) scores = dist # Save triples of (idx, label, score) in a list idx_label_score += list(zip(idx.cpu().data.numpy().tolist(), labels.cpu().data.numpy().tolist(), scores.cpu().data.numpy().tolist())) epoch_loss += loss.item() n_batches += 1 self.test_time = time.time() - start_time self.test_scores = idx_label_score score_array = np.array(self.test_scores, dtype=np.int32) # Get predictions prediction_array = np.array([int(abs(p - 1) < abs(p)) for p in list(score_array[:, 2])], dtype=np.int32) gt_array = score_array[:, 1] # Compute AUC _, labels, scores = zip(*idx_label_score) labels = np.array(labels) scores = np.array(scores) self.test_auc = roc_auc_score(labels, scores) self.test_auprc = average_precision_score(labels, scores) self.roc_x, self.roc_y, _ = roc_curve(labels, scores) self.prec, self.rec, _ = precision_recall_curve(labels, scores) self.test_confusion_matrix = confusion_matrix(gt_array, prediction_array) sns.heatmap(self.test_confusion_matrix, annot=True, fmt='.2%') plt.savefig("cm_deepsad.png") plt.close() # Log results logger.info('Test Loss: {:.6f}'.format(epoch_loss / n_batches)) logger.info('Test AUROC: {:.2f}%'.format(100. * self.test_auc)) logger.info('Test AUPRC: {:.2f}%'.format(100. * self.test_auprc)) logger.info('Test Time: {:.3f}s'.format(self.test_time)) logger.info('Finished testing.') ####### ROC and AUC ############ lw = 2 plt.figure() ####### ROC ############ plt.plot(self.roc_x, self.roc_y, color='darkorange', lw=lw, label='ROC curve (AUC = %0.2f)' % self.test_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--', label="No-skill classifier") plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate ') plt.ylabel('True Positive Rate ') plt.title('ROC (Receiver Operating Characteristic curve)') plt.legend(loc="lower right") plt.show() plt.savefig('roc_auc.png') plt.close() ####### PR ############ plt.figure() plt.plot(self.prec, self.rec, color='darkorange', lw=lw, label='PR curve (AUC = %0.2f)' % self.test_auprc) plt.plot([0, 1], [0.0526, 0.0526], color='navy', lw=lw, linestyle='--', label="No-skill classifier") plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('Recall ') plt.ylabel('Precision ') plt.title('PRC (Precision-Recall curve)') plt.legend(loc="lower right") plt.show() plt.savefig('pr_auc.png') plt.close() def init_center_c(self, train_loader: DataLoader, net: BaseNet, eps=0.1): """Initialize hypersphere center c as the mean from an initial forward pass on the data.""" n_samples = 0 c = torch.zeros(net.rep_dim, device=self.device) net.eval() with torch.no_grad(): for data in train_loader: # get the inputs of the batch inputs, _, _, _ = data inputs = inputs.to(self.device) outputs = net(inputs) n_samples += outputs.shape[0] c += torch.sum(outputs, dim=0) c /= n_samples # If c_i is too close to 0, set to +-eps. Reason: a zero unit can be trivially matched with zero weights. c[(abs(c) < eps) & (c < 0)] = -eps c[(abs(c) < eps) & (c > 0)] = eps return c
39.345291
119
0.574652
1,110
8,774
4.39009
0.214414
0.027909
0.022163
0.01416
0.312333
0.252001
0.208085
0.18387
0.18387
0.146932
0
0.01714
0.301801
8,774
222
120
39.522523
0.778322
0.083884
0
0.275
0
0.00625
0.086738
0.005908
0
0
0
0
0
1
0.025
false
0
0.075
0
0.11875
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30d9462a88c0ebc7b1a28e773898227835681362
1,430
py
Python
covidxpert/utils/__init__.py
LucaCappelletti94/covidxpert
8adda25f3d6fb648607c0f8af7d3ff54b42c59fb
[ "MIT" ]
2
2020-05-22T12:50:11.000Z
2021-03-12T01:00:17.000Z
covidxpert/utils/__init__.py
LucaCappelletti94/covidxpert
8adda25f3d6fb648607c0f8af7d3ff54b42c59fb
[ "MIT" ]
6
2020-05-27T19:03:15.000Z
2021-03-02T11:12:06.000Z
covidxpert/utils/__init__.py
LucaCappelletti94/covidxpert
8adda25f3d6fb648607c0f8af7d3ff54b42c59fb
[ "MIT" ]
1
2020-05-27T07:21:02.000Z
2020-05-27T07:21:02.000Z
from .load_image import load_image from .normalize_image import normalize_image from .remove_artefacts import remove_artefacts, fill_small_white_blobs, fill_small_black_blobs from .padding import trim_padding, add_padding from .inpaint import inpaint from .darken import darken from .difference_of_gaussians_pyramid import difference_of_gaussians_pyramid from .compute_linear_coefficients import compute_linear_coefficients from .get_projected_points import get_projected_points from .polar2cartesian import polar2cartesian from .simmetry import trim_flip, simmetry_loss, get_simmetry_axis from .fill_lower_max import fill_lower_max from .median_mask import median_mask from .rotate_image import rotate_image from .thumbnail import get_thumbnail from .peaks_and_valleys import valleys_cut from .retinex import automated_msrcr from .demosaicking import demosaicking __all__ = [ "load_image", "normalize_image", "remove_artefacts", "trim_padding", "add_padding", "inpaint", "darken", "difference_of_gaussians_pyramid", "compute_linear_coefficients", "get_projected_points", "polar2cartesian", "fill_small_white_blobs", "fill_small_black_blobs", "get_simmetry_axis", "trim_flip", "fill_lower_max", "median_mask", "simmetry_loss", "rotate_image", "get_thumbnail", "valleys_cut", "get_simmetry_axis", "automated_msrcr", "demosaicking", ]
31.086957
94
0.79021
178
1,430
5.898876
0.264045
0.034286
0.06
0.08
0.072381
0.072381
0.072381
0.072381
0
0
0
0.002443
0.141259
1,430
45
95
31.777778
0.852606
0
0
0.045455
0
0
0.25035
0.071329
0
0
0
0
0
1
0
false
0
0.409091
0
0.409091
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
0
0
0
1
30d9946316ecfd307f0f761701c4aed9a868f4ca
625
py
Python
proxy/python/proxy_client.py
koonchen/awesome-design-patterns
53891e5331b211bce7c2b3f8ea6fdd1a9f4086d1
[ "MIT" ]
5
2018-10-19T15:30:00.000Z
2018-11-30T06:02:12.000Z
proxy/python/proxy_client.py
koonchen/awesome-design-patterns
53891e5331b211bce7c2b3f8ea6fdd1a9f4086d1
[ "MIT" ]
null
null
null
proxy/python/proxy_client.py
koonchen/awesome-design-patterns
53891e5331b211bce7c2b3f8ea6fdd1a9f4086d1
[ "MIT" ]
2
2018-10-19T15:30:08.000Z
2019-02-20T15:28:38.000Z
#!/usr/bin/env python # coding:utf8 # @Date : 2018/8/27 # @Author : Koon # @Link : chenzeping.com # When I wrote this, only God and I understood what I was doing. Now, God only knows. class Subject(object): def request(self): print("Subject instance has been created") class RealSubject(Subject): def request(self): print("RealSubject instance has been created") class Proxy(Subject): def __init__(self, subject): self._subject = subject def request(self): self._subject.request() if __name__ == "__main__": proxy = Proxy(RealSubject()) proxy.request()
20.833333
85
0.6544
80
625
4.9375
0.5625
0.075949
0.106329
0.096203
0.136709
0
0
0
0
0
0
0.016598
0.2288
625
29
86
21.551724
0.802905
0.2864
0
0.214286
0
0
0.177273
0
0
0
0
0
0
1
0.285714
false
0
0
0
0.5
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
1
0
0
0
0
0
0
0
1
30dd9689a3bf67ed453ecd720684aa2b2390bfa6
4,680
py
Python
authors/apps/articles/tests/test_like_comments.py
andela/ah-codeofduty
ab749037dbb08712a2e47848e31a1ccb14de1165
[ "BSD-3-Clause" ]
null
null
null
authors/apps/articles/tests/test_like_comments.py
andela/ah-codeofduty
ab749037dbb08712a2e47848e31a1ccb14de1165
[ "BSD-3-Clause" ]
41
2018-10-23T08:45:43.000Z
2022-03-11T23:34:18.000Z
authors/apps/articles/tests/test_like_comments.py
andela/ah-codeofduty
ab749037dbb08712a2e47848e31a1ccb14de1165
[ "BSD-3-Clause" ]
3
2020-05-01T16:21:13.000Z
2021-05-11T08:25:11.000Z
from .base import BaseTest from authors.apps.articles.models import Article from rest_framework.views import status import json class CommentsLikeDislikeTestCase(BaseTest): """test class for liking and disliking comments """ def create_article(self, token, article): """ Method to create an article""" return self.client.post(self.ARTICLES, self.test_article_data, HTTP_AUTHORIZATION=self.token, format='json') def create_comment(self, token, slug, test_comment_data): """ Method to create an article then comment""" self.client.post(self.ARTICLES, self.test_article_data, HTTP_AUTHORIZATION=self.token, format='json') return self.client.post('/api/articles/test-title12/comment/', self.test_comment_data, HTTP_AUTHORIZATION=self.token, format='json') def test_like_comment(self): """Test test the liking of a comment""" # article created response = self.create_article(self.token, self.test_article_data) self.assertEquals(status.HTTP_201_CREATED, response.status_code) # creating a comment slug = response.data['slug'] response = self.create_comment(self.token, slug, self.test_comment_data) comment_id = response.data["id"] self.assertEquals(status.HTTP_201_CREATED, response.status_code) # like a comment response = self.client.put('/api/articles/test-title12/comment/' + str(comment_id) + '/like/', HTTP_AUTHORIZATION=self.token, format='json') self.assertEquals(status.HTTP_200_OK, response.status_code) def test_unlike_comment(self): """Test test the liking of a comment""" response = self.create_article(self.token, self.test_article_data) self.assertEquals(status.HTTP_201_CREATED, response.status_code) slug = response.data['slug'] response = self.create_comment(self.token, slug, self.test_comment_data) comment_id = response.data["id"] self.assertEquals(status.HTTP_201_CREATED, response.status_code) response = self.client.put('/api/articles/test-title12/comment/' + str(comment_id) + '/like/', HTTP_AUTHORIZATION=self.token, format='json') self.assertEquals(status.HTTP_200_OK, response.status_code) def test_like_missing_article(self): """Test test the liking of a comment""" response = self.create_article(self.token, self.test_article_data) self.assertEquals(status.HTTP_201_CREATED, response.status_code) slug = response.data['slug'] response = self.create_comment(self.token, slug, self.test_comment_data) comment_id = response.data["id"] self.assertEquals(status.HTTP_201_CREATED, response.status_code) response = self.client.put('/api/articles/me/comment/' + str(comment_id) + '/dislike/', HTTP_AUTHORIZATION=self.token, format='json' ) self.assertEquals(status.HTTP_404_NOT_FOUND, response.status_code) def test_like_missing_comment(self): """Test test the liking of a comment""" response = self.create_article(self.token, self.test_article_data) self.assertEquals(status.HTTP_201_CREATED, response.status_code) slug = response.data['slug'] response = self.create_comment(self.token, slug, self.test_comment_data) self.assertEquals(status.HTTP_201_CREATED, response.status_code) response = self.client.put('/api/articles/test-title12/comment/99/dislike/', HTTP_AUTHORIZATION=self.token, format='json' ) self.assertEquals(status.HTTP_404_NOT_FOUND, response.status_code) def test_like_comment_if_article_does_not_exist(self): """Test test the liking of a comment in an article that does not exist""" slug = 'test-title12' response = self.create_comment(self.token, slug, self.test_comment_data) comment_id = response.data["id"] self.assertEquals(status.HTTP_201_CREATED, response.status_code) # like a comment response = self.client.put('/api/articles/test-title123/comment/' + str(comment_id) + '/like/', HTTP_AUTHORIZATION=self.token, format='json' ) self.assertEquals(response.data['Error'], 'The article does not exist')
47.272727
103
0.640385
546
4,680
5.283883
0.130037
0.059272
0.099133
0.117158
0.835009
0.8
0.8
0.793761
0.767071
0.753899
0
0.015544
0.257692
4,680
98
104
47.755102
0.814911
0.082051
0
0.651515
0
0
0.079529
0.049882
0
0
0
0
0.212121
1
0.106061
false
0
0.060606
0
0.212121
0
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
6
30de8aa4ae6150e3acdc0398071ec1e1b7a6910b
1,577
py
Python
server.py
rikuru-to865/Voyeur-with-python
104d61e189912134f38463842a0ee0834dd31129
[ "MIT" ]
null
null
null
server.py
rikuru-to865/Voyeur-with-python
104d61e189912134f38463842a0ee0834dd31129
[ "MIT" ]
null
null
null
server.py
rikuru-to865/Voyeur-with-python
104d61e189912134f38463842a0ee0834dd31129
[ "MIT" ]
null
null
null
import socket import numpy import cv2 import threading import os BUFFER_SIZE = 4096*10 currentPort = 50001 buf = b'' class capture(): def __init__(self,port): self.port = port def recive(self): global buf with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: while True: s.bind(("0.0.0.0", self.port)) try: data,address = s.recvfrom(BUFFER_SIZE) if not data: break buf = buf + data finally: s.close() narray=numpy.frombuffer(buf,dtype='uint8') buf = b"" return cv2.imdecode(narray,1) def show(self): while True: img = self.recive() cv2.imshow('Capture',img) if cv2.waitKey(100) & 0xFF == ord('q'): break img = '' with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as portInfo: portInfo.bind(("0.0.0.0",50000)) portInfo.listen() print("aitayo") while True: (connection, client) = portInfo.accept() print("kita!") try: data = connection.recv(800) if data == b"OpenPortRequest": print('recive') connection.send(currentPort.to_bytes(2,"big")) cap = capture(currentPort) th = threading.Thread(target=cap.show) th.daemon = True th.start() finally: connection.close()
26.728814
67
0.496512
169
1,577
4.568047
0.47929
0.015544
0.015544
0.056995
0.119171
0.098446
0.098446
0.098446
0
0
0
0.039749
0.393786
1,577
59
68
26.728814
0.767782
0
0
0.176471
0
0
0.03929
0
0
0
0.002535
0
0
1
0.058824
false
0
0.098039
0
0.196078
0.058824
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30deb57c91134b9206c1ecfd63be99c7504cefa8
565
py
Python
machina/apps/forum/receivers.py
BrendaH/django-machina
c75b6f39f61ca92745aebb0bb6ab3c707d88063d
[ "BSD-3-Clause" ]
572
2015-04-10T06:15:43.000Z
2022-03-30T06:40:25.000Z
machina/apps/forum/receivers.py
BrendaH/django-machina
c75b6f39f61ca92745aebb0bb6ab3c707d88063d
[ "BSD-3-Clause" ]
241
2015-10-26T22:23:59.000Z
2022-03-25T12:30:56.000Z
machina/apps/forum/receivers.py
BrendaH/django-machina
c75b6f39f61ca92745aebb0bb6ab3c707d88063d
[ "BSD-3-Clause" ]
156
2015-10-02T19:32:08.000Z
2022-03-30T06:40:11.000Z
""" Forum signal receivers ====================== This module defines signal receivers. """ from django.db.models import F from django.dispatch import receiver from machina.apps.forum.signals import forum_viewed @receiver(forum_viewed) def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs): """ Handles the update of the link redirects counter associated with link forums. """ if forum.is_link and forum.link_redirects: forum.link_redirects_count = F('link_redirects_count') + 1 forum.save()
26.904762
89
0.707965
72
565
5.402778
0.555556
0.133676
0.092545
0
0
0
0
0
0
0
0
0.002137
0.171681
565
20
90
28.25
0.82906
0.288496
0
0
0
0
0.053333
0
0
0
0
0
0
1
0.125
false
0
0.375
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
30df28d88d0e3028115d06d1db6c4ac57bd2c0df
185
py
Python
Google Kickstart/2019/Round C/circuit_board.py
mishrakeshav/Competitive-Programming
b25dcfeec0fb9a9c71bf3a05644b619f4ca83dd2
[ "MIT" ]
2
2020-06-25T21:10:32.000Z
2020-12-10T06:53:45.000Z
Google Kickstart/2019/Round C/circuit_board.py
mishrakeshav/Competitive-Programming
b25dcfeec0fb9a9c71bf3a05644b619f4ca83dd2
[ "MIT" ]
null
null
null
Google Kickstart/2019/Round C/circuit_board.py
mishrakeshav/Competitive-Programming
b25dcfeec0fb9a9c71bf3a05644b619f4ca83dd2
[ "MIT" ]
3
2020-05-15T14:17:09.000Z
2021-07-25T13:18:20.000Z
for t in range(int(input())): r,c,k = map(int , input().split()) circuit_board = [] for i in range(r): circuit_board.append(list(map(int,input().split())))
26.428571
60
0.551351
28
185
3.571429
0.571429
0.24
0.22
0.32
0
0
0
0
0
0
0
0
0.248649
185
7
61
26.428571
0.719424
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
5
30e0d9aba329cb35b870099915a7b244906f7302
1,978
py
Python
lcm/lcm/nf/serializers/lccn_filter_data.py
onap/vfc-gvnfm-vnflcm
e3127fee0fdb5bf193fddc74a69312363a6d20eb
[ "Apache-2.0" ]
1
2019-04-02T03:15:20.000Z
2019-04-02T03:15:20.000Z
lcm/lcm/nf/serializers/lccn_filter_data.py
onap/vfc-gvnfm-vnflcm
e3127fee0fdb5bf193fddc74a69312363a6d20eb
[ "Apache-2.0" ]
null
null
null
lcm/lcm/nf/serializers/lccn_filter_data.py
onap/vfc-gvnfm-vnflcm
e3127fee0fdb5bf193fddc74a69312363a6d20eb
[ "Apache-2.0" ]
1
2021-10-15T15:26:47.000Z
2021-10-15T15:26:47.000Z
# Copyright (C) 2018 Verizon. 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. from rest_framework import serializers from .vnf_instance_subscription_filter import VnfInstanceSubscriptionFilter from lcm.nf.const import NOTIFICATION_TYPES, LCM_OPERATION_TYPES, LCM_OPERATION_STATE_TYPES class LifeCycleChangeNotificationsFilter(serializers.Serializer): notificationTypes = serializers.ListField( child=serializers.ChoiceField(required=True, choices=NOTIFICATION_TYPES), help_text="Match particular notification types", allow_null=False, required=False) operationTypes = serializers.ListField( child=serializers.ChoiceField(required=True, choices=LCM_OPERATION_TYPES), help_text="Match particular VNF lifecycle operation types for the " + "notification of type VnfLcmOperationOccurrenceNotification.", allow_null=False, required=False) operationStates = serializers.ListField( child=serializers.ChoiceField(required=True, choices=LCM_OPERATION_STATE_TYPES), help_text="Match particular LCM operation state values as reported " + "in notifications of type VnfLcmOperationOccurrenceNotification.", allow_null=False, required=False) vnfInstanceSubscriptionFilter = VnfInstanceSubscriptionFilter( help_text="Filter criteria to select VNF instances about which to notify.", required=False, allow_null=False)
46
91
0.761375
228
1,978
6.5
0.495614
0.040486
0.037787
0.072874
0.319163
0.244265
0.244265
0.244265
0.105263
0.105263
0
0.004905
0.17543
1,978
42
92
47.095238
0.90374
0.289687
0
0.24
0
0
0.237239
0.054637
0
0
0
0
0
1
0
false
0
0.12
0
0.32
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30e38abbdfe5ba2eb3dbe185a3fb1b8a9ce8a9b5
2,213
py
Python
treeNodeTravelThrewTreeNodes.py
GehartM/german-text-watermarking
f9765702225e0cfdce868eec816ed6e6fd4ffc63
[ "MIT" ]
1
2021-04-08T11:23:46.000Z
2021-04-08T11:23:46.000Z
treeNodeTravelThrewTreeNodes.py
GehartM/german-text-watermarking
f9765702225e0cfdce868eec816ed6e6fd4ffc63
[ "MIT" ]
null
null
null
treeNodeTravelThrewTreeNodes.py
GehartM/german-text-watermarking
f9765702225e0cfdce868eec816ed6e6fd4ffc63
[ "MIT" ]
null
null
null
def TravelThrewTreeNodes(currentTreeNode, leftDirections, encodedSign): # Überprüfung, ob die letzte Stelle erreicht wurde. Sollte dies nicht der Fall sein so wird weiter durch den # Baum navigiert if not len(leftDirections) == 1: # Speicherung der nächsten Richtung nextDirection = leftDirections[0] # Löschen der aktuellen Richtung von den übrigen Richtungen leftDirections = leftDirections[1:] # Überprüfung, ob vom aktuellen TreeNode in Richtung 0 navigiert werden soll if nextDirection == '0': if not CheckIfChildrenTreeNodeAlreadyExists(currentTreeNode.zero): # Die gewünschte Richtung existiert noch nicht, daher wird ein neuer TreeNode für diese # Richtung erstellt currentTreeNode.AddTreeNode(True) TravelThrewTreeNodes(currentTreeNode.zero, leftDirections, encodedSign) elif nextDirection == '1': if not CheckIfChildrenTreeNodeAlreadyExists(currentTreeNode.one): # Die gewünschte Richtung existiert noch nicht, daher wird ein neuer TreeNode für diese Richtung # erstellt currentTreeNode.AddTreeNode(False) TravelThrewTreeNodes(currentTreeNode.one, leftDirections, encodedSign) else: # Es wurde die letzte Stelle erreicht. Damit kann das kodierte Zeichen an seine vorgesehene Stelle gespeichert # werden # Überprüfung, ob vom aktuellen TreeNode in Richtung 0 navigiert werden soll if leftDirections == '0': # Erstelle einen neuen TreeNode für diese Richtung und speichere als Wert das kodierte Zeichen currentTreeNode.AddTreeNode(True, encodedSign) elif leftDirections == '1': # Erstelle einen neuen TreeNode für diese Richtung und speichere als Wert das kodierte Zeichen currentTreeNode.AddTreeNode(False, encodedSign) def CheckIfChildrenTreeNodeAlreadyExists(childrenTreeNode): # Existiert das abzufragende Kind-Objekt bereits, so wird True zurückgegeben if childrenTreeNode is not None: return True else: return False
49.177778
119
0.685043
215
2,213
7.051163
0.404651
0.029024
0.042216
0.063325
0.37467
0.37467
0.37467
0.37467
0.37467
0.37467
0
0.005573
0.270221
2,213
44
120
50.295455
0.933127
0.428378
0
0.090909
0
0
0.00332
0
0
0
0
0
0
1
0.090909
false
0
0
0
0.181818
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30e55d7e04ab513adf991395e8e91f97eaca5c02
5,633
py
Python
jarvis/resume/skillset.py
Anubhav722/blahblah
160698e06a02e671ac40de3113cd37d642e72e96
[ "MIT" ]
1
2019-01-03T06:10:04.000Z
2019-01-03T06:10:04.000Z
jarvis/resume/skillset.py
Anubhav722/blahblah
160698e06a02e671ac40de3113cd37d642e72e96
[ "MIT" ]
1
2021-03-31T19:11:52.000Z
2021-03-31T19:11:52.000Z
jarvis/resume/skillset.py
Anubhav722/blahblah
160698e06a02e671ac40de3113cd37d642e72e96
[ "MIT" ]
null
null
null
skills_list = [ "actionscript", "ado.net", "ajax", "akka", "algorithm", "amazon-ec2", "amazon-s3", "amazon-web-services", "android", "angular", "angularjs", "ansible", "ant", "apache", "apache-camel", "apache-kafka", "apache-poi", "apache-spark", "apache-spark-sql", "apache2", "applet", "arduino", "asp.net", "asp.net-core", "asp.net-core-mvc", "asp.net-mvc", "assembly", "asynchronous", "automation", "awk", "azure", "backbone.js", "beautifulsoup", "bigdata", "bootstrap", "c#", "c++", "cakephp", "cassandra", "chef", "ckeditor", "clang", "clojure", "cocoa", "coffeescript", "coldfusion", "concurrency", "content-management-system", "continuous-integration", "cordova", "cryptography", "css", "cucumber", "cuda", "cursor", "cygwin", "cypher", "d3.js", "dart", "data-binding", "data-structures", "database", "database-design", "datatables", "deep-learning", "delphi", "dependency-injection", "deployment", "design", "design-patterns", "django", "dns", "docker", "dplyr", "drupal", "ejb", "elasticsearch", "eloquent", "emacs", "ember.js", "entity-framework", "erlang", "event-handling", "excel", "excel-vba", "express", "express.js", "expressjs", "extjs", "f#", "facebook-graph-api", "firebase", "flask", "flex", "flexbox", "fortran", "frameworks", "functional-programming", "git", "glassfish", "go", "golang", "google-analytics", "google-api", "google-app-engine", "google-apps-script", "google-bigquery", "google-chrome", "google-chrome-extension", "google-cloud-datastore", "google-cloud-messaging", "google-cloud-platform", "google-drive-sdk", "google-maps", "gps", "gradle", "grails", "groovy", "gruntjs", "gson", "gtk", "gulp", "gwt", "hadoop", "handlebars.js", "haskell", "hbase", "hdfs", "heroku", "hibernate", "highcharts", "hive", "html", "html5", "hyperlink", "ibm-mobilefirst", "iis", "image-processing", "imagemagick", "ionic-framework", "ionic2", "itext", "jackson", "jasmine", "java", "java-8", "java-ee", "java-me", "javafx", "javascript", "jax-rs", "jaxb", "jboss", "jdbc", "jenkins", "jersey", "jetty", "jframe", "jmeter", "jms", "jni", "join", "joomla", "jpa", "jpanel", "jqgrid", "jquery", "jsf", "jsf-2", "json", "json.net", "jsoup", "jsp", "jtable", "junit", "jupyter-notebook", "jvm", "kendo-grid", "kendo-ui", "keras", "knockout.js", "kotlin", "kubernetes", "laravel", "linq", "log4j", "lua", "lucene", "machine-learning", "macros", "magento", "mapreduce", "matlab", "matplotlib", "matrix", "maven", "memory-management", "mercurial", "meteor", "mockito", "model-view-controller", "mongodb", "mongoose", "multiprocessing", "multithreading", "mysql", "neo4j", "network-programming", "networking", "neural-network", "nginx", "nhibernate", "nlp", "node.js", "nosql", "numpy", "oauth", "object", "objective-c", "odbc", "odoo", "oop", "opencv", "openssl", "oracle", "pandas", "perl", "phantomjs", "php", "playframework", "plsql", "postgresql", "powershell", "prolog", "pthreads", "pyqt", "pyspark", "python", "qml", "qt", "rabbitmq", "raspberry-pi", "razor", "react-native", "react-redux", "react-router", "reactjs", "realm", "recursion", "redirect", "redis", "redux", "refactoring", "reference", "reflection", "regex", "registry", "requirejs", "responsive-design", "rest", "rss", "ruby", "ruby-on-rails", "rust", "rxjs", "sails.js", "salesforce", "sas", "sass", "scala", "scikit-learn", "scipy", "scrapy", "scripting", "security", "selenium", "selenium-webdriver", "seo", "servlets", "sharepoint", "shell", "silverlight", "smtp", "soap", "socket.io", "sockets", "solr", "sonarqube", "speech-recognition", "spring", "sql", "sql-server", "sqlalchemy", "sqlite", "sqlite3", "svn", "swift", "swing", "swt", "symfony", "synchronization", "telerik", "tensorflow", "three.js", "titanium", "tkinter", "tomcat", "twitter-bootstrap", "typescript", "vagrant", "vb.net", "vb6", "vba", "vbscript", "version-control", "vim", "visual-c++", "vue.js", "vuejs2", "wamp", "wcf", "web", "web-applications", "web-crawler", "web-scraping", "web-services", "webdriver", "websocket", "websphere", "woocommerce", "wordpress", "wpf", "wsdl", "wso2", "wxpython", "x86", "xamarin", "xaml", "xampp", "xcode", "xml", "xml-parsing", "xmlhttprequest", "xmpp", "xna", "xsd", "xslt", "yii", "yii2", "zend-framework", ] skillset = set(skills_list)
15.867606
32
0.480916
460
5,633
5.884783
0.817391
0.008866
0.007388
0
0
0
0
0
0
0
0
0.004387
0.312089
5,633
354
33
15.912429
0.694194
0
0
0
0
0
0.494585
0.0316
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30e8e22ed734b9dbbb1ecdf7de1dcc755608c15e
40
py
Python
5.3_HANDLER/handler_module.py
pedroMoya/alaska_2_share
a5f958da45b97e8c8cdc0b868e4447dbc500c6f9
[ "MIT" ]
2
2020-06-02T18:39:45.000Z
2021-01-01T19:17:15.000Z
5.3_HANDLER/handler_module.py
pedroMoya/alaska_2_share
a5f958da45b97e8c8cdc0b868e4447dbc500c6f9
[ "MIT" ]
1
2021-01-01T19:17:08.000Z
2021-03-19T00:10:52.000Z
5.3_HANDLER/handler_module.py
pedroMoya/alaska_2_share
a5f958da45b97e8c8cdc0b868e4447dbc500c6f9
[ "MIT" ]
1
2021-01-01T19:17:17.000Z
2021-01-01T19:17:17.000Z
# handler module centralize the control
20
39
0.825
5
40
6.6
1
0
0
0
0
0
0
0
0
0
0
0
0.15
40
1
40
40
0.970588
0.925
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
5
30ea17aa8e12d9e828b613b0ece0e52f6bb41391
313
py
Python
external/lfp_tools.py
dmartin35/pronosfoot
861ae091fbb65684d00ae8c5ff3726eeaa306ed7
[ "MIT" ]
4
2017-07-09T21:18:18.000Z
2022-02-16T13:05:10.000Z
external/lfp_tools.py
dmartin35/pronosfoot
861ae091fbb65684d00ae8c5ff3726eeaa306ed7
[ "MIT" ]
2
2020-01-16T14:21:42.000Z
2021-03-02T18:34:15.000Z
external/lfp_tools.py
dmartin35/pronosfoot
861ae091fbb65684d00ae8c5ff3726eeaa306ed7
[ "MIT" ]
null
null
null
def escape_team_names(mystr): """ temporary fix for solving ? characters in bad team names encoding from LFP's ICS calendar """ mystr = mystr.replace('N?MES','NÎMES') mystr = mystr.replace('SAINT-?TIENNE','SAINT-ÉTIENNE') mystr = mystr.replace('H?RAULT', 'HÉRAULT') return mystr
26.083333
69
0.654952
41
313
4.95122
0.707317
0.147783
0.251232
0
0
0
0
0
0
0
0
0
0.207668
313
12
70
26.083333
0.818548
0.284345
0
0
0
0
0.245098
0
0
0
0
0
0
1
0.2
false
0
0
0
0.4
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
30eaa9dd3051eaa994ef4cd89b26f3deca2ee553
6,054
py
Python
startup/users/30-user-chen_xpcs.py
NSLS-II-SMI/profile_collection
c1e2236a7520f605ac85e7591f05682add06357c
[ "BSD-3-Clause" ]
null
null
null
startup/users/30-user-chen_xpcs.py
NSLS-II-SMI/profile_collection
c1e2236a7520f605ac85e7591f05682add06357c
[ "BSD-3-Clause" ]
13
2018-09-25T19:35:08.000Z
2021-01-15T20:42:26.000Z
startup/users/30-user-chen_xpcs.py
NSLS-II-SMI/profile_collection
c1e2236a7520f605ac85e7591f05682add06357c
[ "BSD-3-Clause" ]
3
2019-09-06T01:40:59.000Z
2020-07-01T20:27:39.000Z
def grid_scan_xpcs(): folder = "301000_Chen34" xs = np.linspace(-9350, -9150, 2) ys = np.linspace(1220, 1420, 2) names=['PSBMA5_200um_grid'] energies = [2450, 2472, 2476, 2490] x_off = [0, 60, 0, 60] y_off = [0, 0, 60, 60] xxs, yys = np.meshgrid(xs, ys) dets = [pil1M] for name in names: for ener, xof, yof in zip(energies, x_off, y_off): yield from bps.mv(energy, ener) yield from bps.sleep(10) for i, (x, y) in enumerate(zip(xxs.ravel(), yys.ravel())): pil1M.cam.file_path.put(f"/ramdisk/images/users/2019_3/%s/1M/%s_pos%s"%(folder, name, i)) yield from bps.mv(piezo.x, x+xof) yield from bps.mv(piezo.y, y+yof) name_fmt = '{sample}_{energy}eV_pos{pos}' sample_name = name_fmt.format(sample=name, energy=ener, pos = '%2.2d'%i) sample_id(user_name='Chen', sample_name=sample_name) yield from bps.sleep(5) det_exposure_time(0.03, 30) print(f'\n\t=== Sample: {sample_name} ===\n') pil1M.cam.acquire.put(1) yield from bps.sleep(5) pv = EpicsSignal('XF:12IDC-ES:2{Det:1M}cam1:Acquire', name="pv") while pv.get() == 1: yield from bps.sleep(5) yield from bps.mv(energy, 2475) yield from bps.mv(energy, 2450) def NEXAFS_SAXS_S_edge(t=1): dets = [pil300KW] name = 'sample_thick_waxs' energies = [2450, 2480, 2483, 2484, 2485, 2486, 2500] det_exposure_time(t,t) name_fmt = '{sample}_{energy}eV_wa{wa}' waxs_an = np.linspace(0, 26, 5) yss = np.linspace(1075, 1575, 5) for wax in waxs_an: yield from bps.mv(waxs, wax) for e, ys in zip(energies, yss): yield from bps.mv(energy, e) yield from bps.mv(piezo.y, ys) sample_name = name_fmt.format(sample=name, energy=e, wa = '%3.1f'%wax) sample_id(user_name='Chen', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.count(dets, num=1) yield from bps.mv(energy, 2475) yield from bps.mv(energy, 2450) def grid_scan_static(): names=['PSBMA30_10um_static'] x_off = -36860+np.asarray([-200, 200]) y_off = 1220+np.asarray([-100, 0, 100]) energies = np.linspace(2500, 2450, 51) xxs, yys = np.meshgrid(x_off, y_off) dets = [pil300KW, pil1M] for name in names: for i, (x, y) in enumerate(zip(xxs.ravel(), yys.ravel())): yield from bps.mv(piezo.x, x) yield from bps.mv(piezo.y, y) energies = energies[::-1] yield from bps.sleep(2) for ener in energies: yield from bps.mv(energy, ener) yield from bps.sleep(0.1) name_fmt = '{sample}_{energy}eV_pos{pos}_xbpm{xbpm}' sample_name = name_fmt.format(sample=name, energy=ener, pos = '%2.2d'%i, xbpm='%3.1f'%xbpm3.sumY.value) sample_id(user_name='Chen', sample_name=sample_name) det_exposure_time(0.1, 0.1) yield from bp.count(dets, num=1) def nexafs_S_edge_chen(t=1): dets = [pil300KW] det_exposure_time(t,t) waxs_arc = [45.0] name_fmt = 'nexafs_sampletest1_4_{energy}eV_wa{wax}_bpm{xbpm}' for wa in waxs_arc: for e in energies: yield from bps.mv(energy, e) yield from bps.sleep(1) bpm = xbpm2.sumX.value sample_name = name_fmt.format(energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm) sample_id(user_name='WC', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.count(dets, num=1) yield from bps.mv(energy, 2490) yield from bps.mv(energy, 2470) yield from bps.mv(energy, 2450) def waxs_S_edge_chen_2020_3(t=1): dets = [pil300KW, pil1M] names = ['sampleA1', 'sampleB1', 'sampleB2', 'sampleB3', 'sampleC4', 'sampleC5', 'sampleE8', 'sampleD1', 'sampleD2', 'sampleD3', 'sampleD4', 'sampleD5', 'sampleC8', 'sampleF1', 'sampleF2', 'sampleE1', 'sampleE3', 'sampleE4', 'sampleE5', 'sampleD8', 'sampleF8'] x = [43800, 28250, 20750, 13350, 5150, -5660, -10900, -18400, -26600, -34800, -42800, 42300, 34400, 26700, 18800, 11200, 2900, -5000, -12000, -20300, -27800, ] y = [-4900, -5440, -5960, -5660, -5660, -5660, -5880, -4750, -5450, -5000, -4450, 6950, 6950, 6950, 7450, 7200, 7400, 8250, 8250, 8250, 7750] energies = [2450.0, 2474.0, 2475.0, 2476.0, 2477.0, 2478.0, 2479.0, 2482.0, 2483.0, 2484.0, 2485.0, 2486.0, 2487.0, 2490.0, 2500.0] waxs_arc = np.linspace(0, 13, 3) for name, xs, ys in zip(names, x, y): yield from bps.mv(piezo.x, xs) yield from bps.mv(piezo.y, ys+30) for wa in waxs_arc: yield from bps.mv(waxs, wa) det_exposure_time(t,t) name_fmt = '{sample}_rev_{energy}eV_wa{wax}_bpm{xbpm}' for e in energies[::-1]: yield from bps.mv(energy, e) yield from bps.sleep(1) bpm = xbpm2.sumX.value sample_name = name_fmt.format(sample=name, energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm) sample_id(user_name='GF', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.count(dets, num=1) yield from bps.mv(energy, 2480) yield from bps.mv(energy, 2460)
33.633333
146
0.521143
830
6,054
3.675904
0.249398
0.103245
0.121927
0.105539
0.549
0.490659
0.457883
0.363815
0.319895
0.276303
0
0.136216
0.339115
6,054
180
147
33.633333
0.626343
0
0
0.356522
0
0
0.114121
0.042775
0
0
0
0
0
1
0.043478
false
0
0
0
0.043478
0.034783
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30efd3e520d72e743da6e55444a12e5dda1b5179
199
py
Python
sdipylib/plot.py
sdrdl/sdipylib
197a6c434d2b34a52e6544973407e92f3561727a
[ "BSD-2-Clause" ]
null
null
null
sdipylib/plot.py
sdrdl/sdipylib
197a6c434d2b34a52e6544973407e92f3561727a
[ "BSD-2-Clause" ]
null
null
null
sdipylib/plot.py
sdrdl/sdipylib
197a6c434d2b34a52e6544973407e92f3561727a
[ "BSD-2-Clause" ]
null
null
null
"""Plotting support""" def source_attribution(ax, text ): ax.text(0, -.05, text, fontsize=14, horizontalalignment='left', verticalalignment='top', transform=ax.transAxes)
33.166667
64
0.643216
21
199
6.047619
0.809524
0.094488
0
0
0
0
0
0
0
0
0
0.031646
0.20603
199
6
65
33.166667
0.772152
0.080402
0
0
0
0
0.039326
0
0
0
0
0
0
1
0.25
false
0
0
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
1
0
0
0
0
0
0
0
3
30f29e0855bb09fb75ab5994617d326c1d54e876
9,298
py
Python
hl7tools.py
cdgramos/Sublime-Text-3---HL7-Plug-In
b4b821f272460fa970c019c261ded552c724fee7
[ "MIT" ]
8
2018-03-01T14:38:01.000Z
2020-02-28T22:41:34.000Z
hl7tools.py
cdgramos/Sublime-Text-3---HL7-Plug-In
b4b821f272460fa970c019c261ded552c724fee7
[ "MIT" ]
19
2018-04-13T21:13:08.000Z
2021-09-02T22:48:53.000Z
hl7tools.py
cdgramos/Sublime-Text-3---HL7-Plug-In
b4b821f272460fa970c019c261ded552c724fee7
[ "MIT" ]
1
2020-05-18T21:43:46.000Z
2020-05-18T21:43:46.000Z
import sublime import sublime_plugin import re import webbrowser from .lib.hl7Event import * from .lib.hl7Segment import * from .lib.hl7TextUtils import * hl7EventList = hl7Event("","") hl7EventList = hl7EventList.loadEventList() hl7SegmentList = hl7Segment("","") hl7SegmentList = hl7SegmentList.loadSegmentList() STATUS_BAR_HL7 = 'StatusBarHL7' # On selection modified it will update the status bar class selectionModifiedListener(sublime_plugin.EventListener): def on_selection_modified(self, view): line = getLineTextBeforeCursorPosition(self, view, sublime) fullLine = getLineAtCursorPosition(self, view) # Get the first 3 letters of the line segment = fullLine[:3] if hl7Segment.getSegmentByCode(self, segment, hl7SegmentList) != None: statusBarText = '[ ' + segment + ' ' fieldList = re.split(r'(?<!\\)(?:\\\\)*\|', line) fieldCounter = len(fieldList) if segment != 'MSH': statusBarText += str(fieldCounter-1) else: statusBarText += str(fieldCounter) isComponentRequired = False isSubComponentRequired = False fullField = getFieldAtCursorPosition(self, view, sublime) # Level of detail required if fieldHasComponents(self, fullField) == True: isComponentRequired = True if fieldHasSubComponents(self, fullField) == True: isComponentRequired = True isSubComponentRequired = True if isComponentRequired == True: field = fieldList[-1] componentList = re.split(r'(?<!\\)(?:\\\\)*\^', field) componentCounter = len(componentList) statusBarText += '.' + str(componentCounter) if isSubComponentRequired == True: subComponent = componentList[-1] subComponentList = re.split(r'(?<!\\)(?:\\\\)*\&', subComponent) subComponentCounter = len(subComponentList) statusBarText += '.' + str(subComponentCounter) statusBarText += ' ]' #sublime.status_message('\t' + statusBarText + ' '*20) view.set_status(STATUS_BAR_HL7, statusBarText) else: #sublime.status_message('') view.erase_status(STATUS_BAR_HL7) # Double click on keywords (segments / events) class doubleClickKeywordListener(sublime_plugin.EventListener): def on_text_command(self, view, cmd, args): if cmd == 'drag_select' and 'event' in args: event = args['event'] isEvent = True pt = view.window_to_text((event['x'], event['y'])) text = [] if view.sel(): for region in view.sel(): print(view.substr(view.word(region))) if region.empty(): text.append(view.substr(view.word(region))) def asyncMessagePopup(): desc = "" for eventItem in hl7EventList: regex = "(\^)" filler = "_" codeWithoutCircunflex = re.sub(regex, filler, text[0]) if (eventItem.code == codeWithoutCircunflex): desc = eventItem.description for segmentItem in hl7SegmentList: regex = "(\^)" filler = "_" codeWithoutCircunflex = re.sub(regex, filler, text[0]) if (segmentItem.code == codeWithoutCircunflex): desc = segmentItem.description if (len(desc) > 0): if(getComponentAtCursorPosition(self, view, sublime) == text[0]): view.show_popup('<b style="color:#33ccff;">' + desc + '</b>', location=pt) sublime.set_timeout_async(asyncMessagePopup) else: text.append(view.substr(region)) # Searchs an event or segment on caristix web-site class hl7searchCommand(sublime_plugin.WindowCommand): def run(self): window = self.window view = window.active_view() sel = view.sel() region1 = sel[0] selectionText = view.substr(region1) isValid = 0 URL = "http://hl7-definition.caristix.com:9010/HL7%20v2.5.1/Default.aspx?version=HL7 v2.5.1&" for eventItem in hl7EventList: regex = "(\^)" filler = "_" codeWithoutCircunflex = re.sub(regex, filler, selectionText) if (eventItem.code == codeWithoutCircunflex): URL = URL + "triggerEvent=" + eventItem.code isValid = 1 for segmentItem in hl7SegmentList: if (segmentItem.code == selectionText): URL = URL + "segment=" + segmentItem.code isValid = 1 if (isValid == 1): webbrowser.open_new(URL) # Inspects an entire line class hl7inspectorCommand(sublime_plugin.TextCommand): def run(self, edit): #Popup layout header = "" body = "" segmentCode = "" #Segment selectedSegment = self.view.substr(self.view.line(self.view.sel()[0])) fields = selectedSegment.split('|') fields = re.split(r'(?<!\\)(?:\\\\)*\|', selectedSegment) fieldId = 0 componentId = 1 subComponentId = 1 for segmentItem in hl7SegmentList: if (segmentItem.code == fields[0]): header = segmentItem.code + " - " + segmentItem.description segmentCode = segmentItem.code header = '<b style="color:#33ccff;">' + header + '</b>' for field in fields: if (field != ""): if(field != "^~\&"): components = re.compile(r'(?<!\\)(?:\\\\)*\^').split(field) totalCircunflex = field.count("^") for component in components: if(component != ""): subComponents = re.compile(r'(?<!\\)(?:\\\\)*&').split(component) if(len(subComponents) > 1): for subComponent in subComponents: if(subComponent != ""): regex = "(<)" filler = "&lt;" subComponent = re.sub(regex, filler, subComponent) regex = "(>)" filler = "&gt;" subComponent = re.sub(regex, filler, subComponent) body = body + '<br>' + str(fieldId) + "." + str(componentId) + "."+ str(subComponentId) + " - " + subComponent subComponentId = subComponentId + 1 subComponentId = 1 else: regex = "(<)" filler = "&lt;" component = re.sub(regex, filler, component) regex = "(>)" filler = "&gt;" component = re.sub(regex, filler, component) till = re.compile(r'(?<!\\)(?:\\\\)*~').split(component) if segmentCode == 'MSH' and fieldId > 1: fieldCounter = fieldId + 1 else: fieldCounter = fieldId if(totalCircunflex > 0): for tillItem in till: body = body + '<br>' + str(fieldCounter) + "." + str(componentId) + " - " + tillItem else: for tillItem in till: body = body + '<br>' + str(fieldCounter) + " - " + tillItem componentId = componentId + 1 componentId = 1 else: if len(selectedSegment) > 3: if selectedSegment[3] == '|': body = body + '<br>' + str(1) + " - " + selectedSegment[3] + "\n" if len(fields) > 0: body = body + '<br>' + str(2) + " - " + fields[1] + "\n" fieldId = fieldId + 1 message = header + body message = message.replace("\&", "\&amp;") self.view.show_popup(message, on_navigate=print) # Cleans an HL7 message from reduntant information and idents it class hl7cleanerCommand(sublime_plugin.TextCommand): def run(self, edit): content = self.view.substr(sublime.Region(0, self.view.size())) for segmentItem in hl7SegmentList: regex = "(\^M)" + segmentItem.code filler = "\n" + segmentItem.code content = re.sub(regex, filler, content) for segmentItem in hl7SegmentList: regex = "(\^K)" + segmentItem.code filler = "\n" + segmentItem.code content = re.sub(regex, filler, content) #remove any empty space before each segment for segmentItem in hl7SegmentList: regex = "\ {1,}" + segmentItem.code filler = "" + segmentItem.code content = re.sub(regex, filler, content) #when there is no space before for segmentItem in hl7SegmentList: regex = "(\|){1,}(?<=[a-zA-Z0-9|])" + segmentItem.code + "(\|){1,}" filler = "|\n" + segmentItem.code + "|" content = re.sub(regex, filler, content) #last two ^M at the end of content followed by new line content = re.sub("(\^M\^\\\\\^M)\n", "\n", content) #last two ^M at the end of content followed by end of content content = re.sub("(\^M\^\\\\\^M)$", "\n", content) #last ^M with new line regex = "(\^M)\n" filler = "\n" content = re.sub(regex, filler, content) #last ^M with end of content regex = "(\^M)$" filler = "\n" content = re.sub(regex, filler, content) #last two ^M at the end of content followed by new line with empty space before content = re.sub("(\^M\^\\\\\^M)\ {1,}\n", "\n", content) #last two ^M at the end of content followed by end of content with empty space before content = re.sub("(\^M\^\\\\\^M)\ {1,}$", "\n", content) #last ^M with new line with empty space before regex = "(\^M)\ {1,}\n" filler = "\n" content = re.sub(regex, filler, content) #last ^M with end of content with empty space before regex = "(\^M)\ {1,}$" filler = "\n" content = re.sub(regex, filler, content) #extra circumflex ^ content = re.sub("(\^{1,})[|]", "|", content) #extra pipes | followed by new lines content = re.sub("\|{2,}\n", "|\n", content) #extra pipes | followed by end of content content = re.sub("\|{2,}$", "|\n", content) #empty lines at the beginning of the text content = re.sub("^(\n){1,}", "", content) #blank spaces at the beginning of the text content = re.sub("^ {1,}", "", content) self.view.insert(edit, 0, content + "\n\n\n")
26.490028
120
0.61766
1,036
9,298
5.511583
0.212355
0.021016
0.035727
0.042032
0.355867
0.290893
0.240455
0.209457
0.170228
0.142032
0
0.014436
0.22521
9,298
350
121
26.565714
0.778179
0.11368
0
0.307692
0
0.004808
0.082907
0.008644
0
0
0
0
0
1
0.028846
false
0
0.033654
0
0.086538
0.009615
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30f2d2c111d6644e79246c0c70b3eff7c89f77de
218
py
Python
leetcode/hard/1203.py
phantomnat/python-learning
addc7ba5fc4fb8920cdd2891d4b2e79efd1a524a
[ "MIT" ]
null
null
null
leetcode/hard/1203.py
phantomnat/python-learning
addc7ba5fc4fb8920cdd2891d4b2e79efd1a524a
[ "MIT" ]
null
null
null
leetcode/hard/1203.py
phantomnat/python-learning
addc7ba5fc4fb8920cdd2891d4b2e79efd1a524a
[ "MIT" ]
null
null
null
# https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/ # graph, dfs class Solution: def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
36.333333
101
0.683486
30
218
4.966667
0.766667
0.14094
0
0
0
0
0
0
0
0
0
0
0.146789
218
6
102
36.333333
0.801075
0.394495
0
0
0
0
0
0
0
0
0
0
0
0
null
null
0
0
null
null
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
1
0
0
0
0
0
0
0
0
2
30f2e9dc143ed93952cacd555538c812b12a36a2
8,220
py
Python
gen_data/yolo_label.py
KevinLADLee/CARLA_INVS
b23249500ffbafdb312a71d17b0dfef4191672f0
[ "MIT" ]
null
null
null
gen_data/yolo_label.py
KevinLADLee/CARLA_INVS
b23249500ffbafdb312a71d17b0dfef4191672f0
[ "MIT" ]
null
null
null
gen_data/yolo_label.py
KevinLADLee/CARLA_INVS
b23249500ffbafdb312a71d17b0dfef4191672f0
[ "MIT" ]
null
null
null
#!/usr/bin/python3 import argparse import time import cv2 import glob import sys from pathlib import Path import numpy as np import pandas as pd import yaml from multiprocessing.dummy import Pool as ThreadPool sys.path.append(Path(__file__).resolve().parent.parent.as_posix()) # repo path sys.path.append(Path(__file__).resolve().parent.as_posix()) # file path from params import * LABEL_DATAFRAME = pd.DataFrame(columns=['raw_value', 'color', 'coco_names_index'], data=[ # [ 4, (220, 20, 60), 0], [18, (250, 170, 30), 9], [12, (220, 220, 0), 80]]) LABEL_COLORS = np.array([ # (220, 20, 60), # Pedestrian # (0, 0, 142), # Vehicle (220, 220, 0), # TrafficSign -> COCO INDEX (250, 170, 30), # TrafficLight ]) COCO_NAMES = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'traffic sign'] class YoloLabel: def __init__(self, data_path, debug=False): self.data_path = data_path self.data_output_path = Path(data_path) / "../yolo_dataset" self.data_output_path = Path(os.path.abspath(self.data_output_path.as_posix())) print(self.data_output_path) self.image_out_path = self.data_output_path / "images" / "train" self.label_out_path = self.data_output_path / "labels" / "train" self.image_rgb = None self.image_seg = None self.preview_img = None self.rec_pixels_min = 150 self.debug = debug self.thread_pool = ThreadPool() def process(self): img_path_list = sorted(glob.glob(self.data_path + '/*.png')) img_seg_path_list = sorted(glob.glob(self.data_path + '/seg' + '/*.png')) start = time.time() self.thread_pool.starmap(self.label_img, zip(img_path_list, img_seg_path_list)) # for rgb_img, seg_img in zip(img_path_list, img_seg_path_list): # self.label_img(rgb_img, seg_img) self.thread_pool.close() self.thread_pool.join() print("cost: {}s".format(time.time()-start)) def label_img(self, rgb_img_path, seg_img_path): success = self.check_id(rgb_img_path, seg_img_path) if not success: return image_rgb = None image_seg = None image_rgb = cv2.imread(rgb_img_path, cv2.IMREAD_COLOR) image_seg = cv2.imread(seg_img_path, cv2.IMREAD_UNCHANGED) if image_rgb is None or image_seg is None: return image_rgb = cv2.cvtColor(image_rgb, cv2.COLOR_RGBA2RGB) image_seg = cv2.cvtColor(image_seg, cv2.COLOR_BGRA2RGB) img_name = os.path.basename(rgb_img_path) height, width, _ = image_rgb.shape labels_all = [] for index, label_info in LABEL_DATAFRAME.iterrows(): seg_color = label_info['color'] coco_id = label_info['coco_names_index'] mask = (image_seg == seg_color) tmp_mask = (mask.sum(axis=2, dtype=np.uint8) == 3) mono_img = np.array(tmp_mask * 255, dtype=np.uint8) preview_img = image_rgb # self.preview_img = self.image_seg # cv2.imshow("seg", self.preview_img) # cv2.imshow("mono", mono_img) # cv2.waitKey() contours, _ = cv2.findContours(mono_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) labels = [] for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) if w * h < self.rec_pixels_min: continue # cv2.rectangle(self.preview_img, (x, y), (x + w, y + h), (0, 255, 0), 1) # cv2.imshow("rect", self.preview_img) # cv2.waitKey() max_y, max_x, _ = image_rgb.shape if y + h >= max_y or x + w >= max_x: continue # Draw label info to image cv2.putText(preview_img, COCO_NAMES[coco_id], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36, 255, 12), 1) cv2.rectangle(image_rgb, (x, y), (x + w, y + h), (0, 255, 0), 1) label_info = "{} {} {} {} {}".format(coco_id, float(x + (w / 2.0)) / width, float(y + (h / 2.0)) / height, float(w) / width, float(h) / height) labels.append(label_info) # cv2.imshow("result", self.preview_img) # cv2.imshow("test", self.preview_img[y:y+h, x:x+w, :]) # cv2.waitKey() if len(labels) > 0: labels_all += labels if len(labels_all) > 0: os.makedirs(self.label_out_path, exist_ok=True) os.makedirs(self.image_out_path, exist_ok=True) # print("image\t\t\twidth\theight\n{}\t{}\t{}".format(img_name, width, height)) # print("Got {} labels".format(len(labels_all))) cv2.imwrite(self.image_out_path.as_posix() + '/' + os.path.splitext(img_name)[0] + '.jpg', image_rgb) # print(self.image_rgb.shape) with open(self.label_out_path.as_posix() + '/' + os.path.splitext(img_name)[0] + '.txt', "w") as f: for label in labels_all: f.write(label) f.write('\n') # print("Label output path: {}".format(self.label_out_path)) self.dump_yaml(self.data_output_path.as_posix()) # print("******") return def check_id(self, rgb_img_path, seg_img_path): img_name = os.path.splitext(os.path.basename(rgb_img_path))[0] seg_name = os.path.splitext(os.path.basename(seg_img_path))[0] if img_name != seg_name: print("Img name error: {} {}".format(img_name, seg_name)) return False else: return True def dump_yaml(self, dataset_path): dict_file = { 'path': dataset_path, 'train': 'images/train', 'val': 'images/train', 'test': '', 'nc': len(COCO_NAMES), 'names': COCO_NAMES } with open(dataset_path + '/../yolo_coco_carla.yaml', 'w') as file: yaml.dump(dict_file, file) def main(): argparser = argparse.ArgumentParser(description=__doc__) argparser.add_argument( '--record_id', default='record2021_1106_0049', help='record_id of raw data') argparser.add_argument( '--debug', default=False ) args = argparser.parse_args() debug = args.debug data_path = RAW_DATA_PATH / Path(args.record_id) print(data_path) vehicle_data_list = glob.glob(data_path.as_posix() + '/vehicle*' + '/vehicle*') for vehicle_data_path in vehicle_data_list: yolo_label_manager = YoloLabel(vehicle_data_path, debug) yolo_label_manager.process() return if __name__ == '__main__': try: main() except KeyboardInterrupt: print('\nCancelled by user. Bye!') except RuntimeError as e: print(e)
40.895522
123
0.550243
1,008
8,220
4.246032
0.301587
0.022897
0.022897
0.029439
0.168925
0.131776
0.107477
0.051402
0.02243
0.02243
0
0.025234
0.310584
8,220
200
124
41.1
0.730016
0.103528
0
0.052632
0
0
0.122054
0.003269
0
0
0
0
0
1
0.039474
false
0
0.072368
0
0.157895
0.039474
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30f35ff68fe1eac3b585ba8e3b6bf7e40042a3c9
3,004
py
Python
tr/acs_config_test.py
DentonGentry/gfiber-catawampus
b01e4444f3c7f12b1af7837203b37060fd443bb7
[ "Apache-2.0" ]
2
2017-10-03T16:06:29.000Z
2020-09-08T13:03:13.000Z
tr/acs_config_test.py
DentonGentry/gfiber-catawampus
b01e4444f3c7f12b1af7837203b37060fd443bb7
[ "Apache-2.0" ]
null
null
null
tr/acs_config_test.py
DentonGentry/gfiber-catawampus
b01e4444f3c7f12b1af7837203b37060fd443bb7
[ "Apache-2.0" ]
1
2017-05-07T17:39:02.000Z
2017-05-07T17:39:02.000Z
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. # unittest requires method names starting in 'test' # pylint:disable=invalid-name # # Refactored, originally from: platform/gfmedia/device_test.py """Unit tests for device.py.""" __author__ = 'jnewlin@google.com (John Newlin)' import os import shutil import tempfile import google3 import tornado.testing import acs_config from wvtest import unittest class AcsConfigTest(tornado.testing.AsyncTestCase, unittest.TestCase): """Tests for acs_config.py.""" def setUp(self): super(AcsConfigTest, self).setUp() self.old_ACSCONTACT = acs_config.ACSCONTACT self.old_ACSCONNECTED = acs_config.ACSCONNECTED self.old_SET_ACS = acs_config.SET_ACS acs_config.SET_ACS = 'testdata/acs_config/set-acs' self.scriptout = tempfile.NamedTemporaryFile() os.environ['TESTOUTPUT'] = self.scriptout.name def tearDown(self): super(AcsConfigTest, self).tearDown() acs_config.ACSCONTACT = self.old_ACSCONTACT acs_config.ACSCONNECTED = self.old_ACSCONNECTED acs_config.SET_ACS = self.old_SET_ACS self.scriptout = None # File will delete itself def testSetAcs(self): ac = acs_config.AcsConfig() self.assertEqual(ac.GetAcsUrl(), 'bar') ac.SetAcsUrl('foo') self.assertEqual(self.scriptout.read().strip(), 'cwmp foo') def testClearAcs(self): ac = acs_config.AcsConfig() ac.SetAcsUrl('') self.assertEqual(self.scriptout.read().strip(), 'cwmp clear') def testAcsAccess(self): tmpdir = tempfile.mkdtemp() acscontact = os.path.join(tmpdir, 'acscontact') self.assertRaises(OSError, os.stat, acscontact) # File does not exist yet acs_config.ACSCONTACT = acscontact acsconnected = os.path.join(tmpdir, 'acsconnected') self.assertRaises(OSError, os.stat, acsconnected) acs_config.ACSCONNECTED = acsconnected ac = acs_config.AcsConfig() acsurl = 'this is the acs url' # Simulate ACS connection attempt ac.AcsAccessAttempt(acsurl) self.assertTrue(os.stat(acscontact)) self.assertEqual(open(acscontact, 'r').read(), acsurl) self.assertRaises(OSError, os.stat, acsconnected) # Simulate ACS connection success ac.AcsAccessSuccess(acsurl) self.assertTrue(os.stat(acscontact)) self.assertTrue(os.stat(acsconnected)) self.assertEqual(open(acsconnected, 'r').read(), acsurl) # cleanup shutil.rmtree(tmpdir) if __name__ == '__main__': unittest.main()
31.957447
78
0.734687
387
3,004
5.602067
0.423773
0.062269
0.02214
0.027675
0.255535
0.129151
0.074723
0
0
0
0
0.003559
0.158123
3,004
93
79
32.301075
0.853697
0.296937
0
0.132075
0
0
0.069264
0.012987
0
0
0
0
0.207547
1
0.09434
false
0
0.132075
0
0.245283
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30f370fe717239a2c55137458132ce5868ea35e1
337
py
Python
enema/crypto.py
kjczarne/enema
6ac59cb13663f924574846d2558f27e0bb41a92d
[ "MIT" ]
null
null
null
enema/crypto.py
kjczarne/enema
6ac59cb13663f924574846d2558f27e0bb41a92d
[ "MIT" ]
null
null
null
enema/crypto.py
kjczarne/enema
6ac59cb13663f924574846d2558f27e0bb41a92d
[ "MIT" ]
null
null
null
import os from cryptography.fernet import Fernet def encrypt_password(password: str, key): f = Fernet(key) return str(f.encrypt(bytes(password, 'utf-8')), 'utf-8') def decrypt_password(password: str, key): f = Fernet(key) return str(f.decrypt(bytes(password, 'utf-8')), 'utf-8') KEY = os.environ.get("DASH_APP_KEY")
22.466667
60
0.68546
52
337
4.365385
0.384615
0.070485
0.167401
0.193833
0.555066
0.555066
0.370044
0.370044
0.370044
0.370044
0
0.014035
0.154303
337
15
61
22.466667
0.782456
0
0
0.222222
0
0
0.094675
0
0
0
0
0
0
1
0.222222
false
0.444444
0.222222
0
0.666667
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
1
0
0
0
0
0
3
30f3cfcf7af0bb5923bab6a38ac6e979bd553f2b
275
py
Python
sphinxcontrib/__init__.py
nikicc/anaconda-recipes
9c611a5854bf41bbc5e7ed9853dc71c0851a62ef
[ "BSD-3-Clause" ]
130
2015-07-28T03:41:21.000Z
2022-03-16T03:07:41.000Z
sphinxcontrib/__init__.py
nikicc/anaconda-recipes
9c611a5854bf41bbc5e7ed9853dc71c0851a62ef
[ "BSD-3-Clause" ]
147
2017-08-13T04:31:27.000Z
2022-03-07T11:22:23.000Z
sphinxcontrib/__init__.py
nikicc/anaconda-recipes
9c611a5854bf41bbc5e7ed9853dc71c0851a62ef
[ "BSD-3-Clause" ]
72
2015-07-29T02:35:56.000Z
2022-02-26T14:31:15.000Z
# This empty file makes the sphinxcontrib namespace package work. # It is the only file included in the 'sphinxcontrib' conda package. # Conda packages which use the sphinxcontrib namespace do not include # this file, but depend on the 'sphinxcontrib' conda package instead.
55
69
0.796364
40
275
5.475
0.625
0.292237
0.228311
0.255708
0
0
0
0
0
0
0
0
0.16
275
4
70
68.75
0.948052
0.967273
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
6
30f3fff33de30496fe028fef08f8b083e40facf8
2,941
py
Python
src/tests/integration/api_test_client.py
doitintl/elastic-event-store
ad00f1fbecf430432c306d5917984d9f9ff522f4
[ "MIT" ]
22
2021-02-02T17:11:55.000Z
2021-12-19T15:00:26.000Z
src/tests/integration/api_test_client.py
vladikk/elastic-event-store
ad00f1fbecf430432c306d5917984d9f9ff522f4
[ "MIT" ]
8
2021-02-04T19:21:25.000Z
2021-02-08T07:48:06.000Z
src/tests/integration/api_test_client.py
vladikk/elastic-event-store
ad00f1fbecf430432c306d5917984d9f9ff522f4
[ "MIT" ]
4
2021-02-02T16:58:26.000Z
2021-07-17T04:17:43.000Z
import boto3 import os import requests class ApiTestClient(): api_endpoint: str some_metadata = { 'timestamp': '123123', 'command_id': '456346234', 'issued_by': 'test@test.com' } some_events = [ { "type": "init", "foo": "bar" }, { "type": "update", "foo": "baz" }, ] def __init__(self, sam_stack_name=None): if not sam_stack_name: sam_stack_name = os.environ.get("AWS_SAM_STACK_NAME") if not sam_stack_name: raise Exception( "Cannot find env var AWS_SAM_STACK_NAME. \n" "Please setup this environment variable with the stack name where we are running integration tests." ) client = boto3.client("cloudformation") try: response = client.describe_stacks(StackName=sam_stack_name) except Exception as e: raise Exception( f"Cannot find stack {sam_stack_name}. \n" f'Please make sure stack with the name "{sam_stack_name}" exists.' ) from e stacks = response["Stacks"] stack_outputs = stacks[0]["Outputs"] api_outputs = [output for output in stack_outputs if output["OutputKey"] == "ApiEndpoint"] if not api_outputs: raise Exception(f"Cannot find output ApiEndpoint in stack {sam_stack_name}") self.api_endpoint = api_outputs[0]["OutputValue"] + '/' def commit(self, stream_id, events=None, metadata=None, last_changeset_id=None, last_event_id=None): expected_last_changeset = "" expected_last_event = "" if last_changeset_id is not None: try: expected_last_changeset = int(last_changeset_id) except ValueError: expected_last_changeset = last_changeset_id if last_event_id is not None: try: expected_last_event = int(last_event_id) except ValueError: expected_last_event = last_event_id url = self.api_endpoint + f'streams/{stream_id}?expected_last_changeset={expected_last_changeset}&expected_last_event={expected_last_event}' payload = { } if events: payload["events"] = events if metadata: payload["metadata"] = metadata return requests.post(url, json=payload) def query_changesets(self, stream_id, from_changeset=None, to_changeset=None): url = self.api_endpoint + f'streams/{stream_id}/changesets?&from={from_changeset or ""}&to={to_changeset or ""}' return requests.get(url) def query_events(self, stream_id, from_event=None, to_event=None): url = self.api_endpoint + f'streams/{stream_id}/events?&from={from_event or ""}&to={to_event or ""}' return requests.get(url) def version(self): return requests.get(self.api_endpoint + "version")
35.865854
148
0.615097
352
2,941
4.872159
0.286932
0.057726
0.069971
0.050729
0.26414
0.16793
0.094461
0.06414
0.044315
0
0
0.009035
0.284937
2,941
82
149
35.865854
0.806467
0
0
0.174603
0
0
0.253569
0.07036
0
0
0
0
0
1
0.079365
false
0
0.047619
0.015873
0.253968
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30f4b65b22ebdf31ffa7df998fa1124ad1b7b169
4,076
py
Python
openstack_dashboard/dashboards/project/connections/reachability_tests/bcf_testpath_api.py
xinwu/horizon
0e984a2c75d253dd35ab92e7926021b82d730b26
[ "Apache-2.0" ]
null
null
null
openstack_dashboard/dashboards/project/connections/reachability_tests/bcf_testpath_api.py
xinwu/horizon
0e984a2c75d253dd35ab92e7926021b82d730b26
[ "Apache-2.0" ]
null
null
null
openstack_dashboard/dashboards/project/connections/reachability_tests/bcf_testpath_api.py
xinwu/horizon
0e984a2c75d253dd35ab92e7926021b82d730b26
[ "Apache-2.0" ]
null
null
null
import eventlet import json import rest_lib import urllib import logging as log from openstack_dashboard.dashboards.project.connections import bsn_api eventlet.monkey_patch() URL_TEST_PATH = ('applications/bcf/test/path/controller-view' '[src-tenant=\"%(src-tenant)s\"]' '[src-segment=\"%(src-segment)s\"]' '[src-ip=\"%(src-ip)s\"]' '[dst-ip=\"%(dst-ip)s\"]') class ControllerCluster(object): """ Controller interfaces for a big switch controller cluster """ def __init__(self, controllers=bsn_api.controllers, port=bsn_api.port): self.controllers = tuple(controllers) self.port = port self.cookie = None self.origin = 'neutron' @property def active_controller(self): pool = eventlet.greenpool.GreenPool() coroutines = {} active = None standby_offline = [] for controller in self.controllers: coroutines[controller] = pool.spawn(self.auth, controller) while coroutines: completed = None for controller in coroutines.keys(): if coroutines[controller].dead: completed = controller break eventlet.sleep(0.1) if completed: coro = coroutines.pop(completed) try: cookie = coro.wait() url = 'core/controller/role' res = rest_lib.get(cookie, url, controller, self.port)[2] if 'active' in res: active = controller self.cookie = cookie else: standby_offline.append((cookie, controller)) self.logout(cookie, controller) except: standby_offline.append(('', controller)) if active: pool.spawn(self.cleanup_remaining, standby_offline, coroutines) return active # none responded in time, return first in list return self.controllers[0] def cleanup_remaining(self, finished, waiting): for cookie, controller in finished: if not cookie: continue self.logout(cookie, controller) for controller in waiting.keys(): try: cookie = waiting[controller].wait() self.logout(cookie, controller) except: pass def auth(self, server, username=bsn_api.username, password=bsn_api.password): login = {"user": username, "password": password} host = "%s:%d" % (server, self.port) log.info("PRE AUTH: Host: %s\t user: %s password: %s" % (server, username, password)) ret = rest_lib.request("/api/v1/auth/login", prefix='', method='POST', data=json.dumps(login), host=host) session = json.loads(ret[2]) if ret[0] != 200: raise Exception(session["error_message"]) if ("session_cookie" not in session): raise Exception("Failed to authenticate: session cookie not set") return session["session_cookie"] def logout(self, cookie, controller): url = "core/aaa/session[auth-token=\"%s\"]" % cookie ret = rest_lib.delete(cookie, url, controller, self.port) log.info("LOGOUT Session: cookie: %s" % cookie) return ret def getTestPath(self, src, dst): url = (URL_TEST_PATH % {'src-tenant': src['tenant'], 'src-segment': src['segment'], 'src-ip': src['ip'], 'dst-ip': dst['ip']}) controller = self.active_controller ret = rest_lib.get(self.cookie, url, controller, self.port) data = list() if ret[0] in range(200, 300): data = json.loads(ret[2]) return data
36.720721
79
0.531894
415
4,076
5.149398
0.313253
0.045859
0.016846
0.032288
0.067852
0
0
0
0
0
0
0.006881
0.358194
4,076
110
80
37.054545
0.810015
0.02527
0
0.072917
0
0
0.115997
0.045742
0
0
0
0
0
1
0.0625
false
0.052083
0.0625
0
0.1875
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
0
0
0
1
30f4e2ae84a31284f08d9dd4f970283a7dda20d5
40,407
py
Python
pysnmp_mibs/ROHC-MIB.py
jackjack821/pysnmp-mibs
9835ea0bb2420715caf4ee9aaa07d59bb263acd6
[ "BSD-2-Clause" ]
6
2017-04-21T13:48:08.000Z
2022-01-06T19:42:52.000Z
pysnmp_mibs/ROHC-MIB.py
jackjack821/pysnmp-mibs
9835ea0bb2420715caf4ee9aaa07d59bb263acd6
[ "BSD-2-Clause" ]
1
2020-05-05T16:42:25.000Z
2020-05-05T16:42:25.000Z
pysnmp_mibs/ROHC-MIB.py
jackjack821/pysnmp-mibs
9835ea0bb2420715caf4ee9aaa07d59bb263acd6
[ "BSD-2-Clause" ]
6
2020-02-08T20:28:49.000Z
2021-09-14T13:36:46.000Z
# # PySNMP MIB module ROHC-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/ROHC-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:27:00 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( Integer, OctetString, ObjectIdentifier, ) = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint") ( ifIndex, ) = mibBuilder.importSymbols("IF-MIB", "ifIndex") ( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ( ModuleCompliance, ObjectGroup, NotificationGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") ( ObjectIdentity, iso, Unsigned32, Gauge32, mib_2, MibIdentifier, Integer32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter64, Counter32, NotificationType, ModuleIdentity, IpAddress, ) = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "iso", "Unsigned32", "Gauge32", "mib-2", "MibIdentifier", "Integer32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter64", "Counter32", "NotificationType", "ModuleIdentity", "IpAddress") ( TimeInterval, DisplayString, TruthValue, TextualConvention, DateAndTime, ) = mibBuilder.importSymbols("SNMPv2-TC", "TimeInterval", "DisplayString", "TruthValue", "TextualConvention", "DateAndTime") rohcMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 112)).setRevisions(("2004-06-03 00:00",)) if mibBuilder.loadTexts: rohcMIB.setLastUpdated('200406030000Z') if mibBuilder.loadTexts: rohcMIB.setOrganization('IETF Robust Header Compression Working Group') if mibBuilder.loadTexts: rohcMIB.setContactInfo('WG charter:\n http://www.ietf.org/html.charters/rohc-charter.html\n\n Mailing Lists:\n General Discussion: rohc@ietf.org\n To Subscribe: rohc-request@ietf.org\n In Body: subscribe your_email_address\n\n Editor:\n Juergen Quittek\n NEC Europe Ltd.\n Network Laboratories\n Kurfuersten-Anlage 36\n\n\n\n 69221 Heidelberg\n Germany\n Tel: +49 6221 90511-15\n EMail: quittek@netlab.nec.de') if mibBuilder.loadTexts: rohcMIB.setDescription('This MIB module defines a set of basic objects for\n monitoring and configuring robust header compression.\n The module covers information about running instances\n of ROHC (compressors or decompressors) at IP interfaces.\n\n Information about compressor contexts and decompressor\n contexts has different structure for different profiles.\n Therefore it is not provided by this MIB module, but by\n individual modules for different profiles.\n\n Copyright (C) The Internet Society (2004). The\n initial version of this MIB module was published\n in RFC 3816. For full legal notices see the RFC\n itself or see:\n http://www.ietf.org/copyrights/ianamib.html') class RohcChannelIdentifier(Unsigned32, TextualConvention): displayHint = 'd' subtypeSpec = Unsigned32.subtypeSpec+ValueRangeConstraint(1,4294967295) class RohcChannelIdentifierOrZero(Unsigned32, TextualConvention): displayHint = 'd' subtypeSpec = Unsigned32.subtypeSpec+ValueRangeConstraint(0,4294967295) class RohcCompressionRatio(Unsigned32, TextualConvention): displayHint = 'd' rohcObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 1)) rohcConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 2)) rohcInstanceObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 1, 1)) rohcChannelTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 1, 1), ) if mibBuilder.loadTexts: rohcChannelTable.setDescription('This table lists and describes all ROHC channels\n per interface.') rohcChannelEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ROHC-MIB", "rohcChannelID")) if mibBuilder.loadTexts: rohcChannelEntry.setDescription('An entry describing a particular script. Every script that\n is stored in non-volatile memory is required to appear in\n\n\n\n this script table.\n\n Note, that the rohcChannelID identifies the channel\n uniquely. The ifIndex is part of the index of this table\n just in order to allow addressing channels per interface.') rohcChannelID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 2), RohcChannelIdentifier()) if mibBuilder.loadTexts: rohcChannelID.setDescription("The locally arbitrary, but unique identifier associated\n with this channel. The value is REQUIRED to be unique\n per ROHC MIB implementation independent of the associated\n interface.\n\n The value is REQUIRED to remain constant at least from one\n re-initialization of the entity's network management system\n to the next re-initialization. It is RECOMMENDED that the\n value persist across such re-initializations.") rohcChannelType = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("notInUse", 1), ("rohc", 2), ("dedicatedFeedback", 3),))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcChannelType.setDescription('Type of usage of the channel. A channel might be currently\n not in use for ROHC or feedback, it might be in use as\n a ROHC channel carrying packets and optional piggy-backed\n feedback, or it might be used as a dedicated feedback\n channel exclusively carrying feedback.') rohcChannelFeedbackFor = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 4), RohcChannelIdentifierOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcChannelFeedbackFor.setDescription('The index of another channel of this interface for which\n the channel serves as feedback channel.\n\n If no feedback information is transferred on this channel,\n then the value of this ID is 0. If the channel type is set\n to notInUse(1), then the value of this object must be 0.\n If the channel type is rohc(2) and the value of this object\n is a valid channel ID, then feedback information is\n piggy-backed on the ROHC channel. If the channel type is\n dedicatedFeedback(3), then feedback is transferred on this\n channel and the value of this object MUST be different from\n 0 and MUST identify an existing ROHC channel.') rohcChannelDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 5), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcChannelDescr.setDescription('A textual description of the channel.') rohcChannelStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2),))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcChannelStatus.setDescription('Status of the channel.') rohcInstanceTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 1, 2), ) if mibBuilder.loadTexts: rohcInstanceTable.setDescription('This table lists properties of running instances\n of robust header compressors and decompressors\n at IP interfaces. It is indexed by interface number,\n the type of instance (compressor or decompressor),\n and the ID of the channel used by the instance as\n ROHC channel.\n\n Note that the rohcChannelID uniquely identifies an\n instance. The ifIndex and rohcInstanceType are part\n of the index, because it simplifies accessing instances\n per interface and for addressing either compressors or\n decompressors only.') rohcInstanceEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ROHC-MIB", "rohcInstanceType"), (0, "ROHC-MIB", "rohcChannelID")) if mibBuilder.loadTexts: rohcInstanceEntry.setDescription('An entry describing a particular instance\n of a robust header compressor or decompressor.') rohcInstanceType = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("compressor", 1), ("decompressor", 2),))) if mibBuilder.loadTexts: rohcInstanceType.setDescription('Type of the instance of ROHC. It is either a\n compressor instance or a decompressor instance.') rohcInstanceFBChannelID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 4), RohcChannelIdentifierOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceFBChannelID.setDescription('Identifier of the channel used for feedback.\n If no feedback channel is used, the value of\n this object is 0 .') rohcInstanceVendor = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 5), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceVendor.setDescription('An object identifier that identifies the vendor who\n provides the implementation of robust header description.\n This object identifier SHALL point to the object identifier\n directly below the enterprise object identifier\n {1 3 6 1 4 1} allocated for the vendor. The value must be\n the object identifier {0 0} if the vendor is not known.') rohcInstanceVersion = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0,32))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceVersion.setDescription('The version number of the implementation of robust header\n compression. The zero-length string shall be used if the\n implementation does not have a version number.\n\n\n\n\n It is suggested that the version number consist of one or\n more decimal numbers separated by dots, where the first\n number is called the major version number.') rohcInstanceDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 7), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceDescr.setDescription('A textual description of the implementation.') rohcInstanceClockRes = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 8), Unsigned32()).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceClockRes.setDescription('This object indicates the system clock resolution in\n units of milliseconds. A zero (0) value means that there\n is no clock available.') rohcInstanceMaxCID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 9), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1,16383))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceMaxCID.setDescription('The highest context ID number to be used by the\n compressor. Note that this parameter is not coupled to,\n but in effect further constrained by,\n rohcChannelLargeCIDs.') rohcInstanceLargeCIDs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 10), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceLargeCIDs.setDescription('When retrieved, this boolean object returns false if\n the short CID representation (0 bytes or 1 prefix byte,\n covering CID 0 to 15) is used; it returns true, if the\n embedded CID representation (1 or 2 embedded CID bytes\n covering CID 0 to 16383) is used.') rohcInstanceMRRU = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceMRRU.setDescription('Maximum reconstructed reception unit. This is the\n size of the largest reconstructed unit in octets that\n the decompressor is expected to reassemble from\n segments (see RFC 3095, Section 5.2.5). Note that this\n size includes the CRC. If MRRU is negotiated to be 0,\n no segment headers are allowed on the channel.') rohcInstanceContextStorageTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 12), TimeInterval().clone(360000)).setUnits('centi-seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: rohcInstanceContextStorageTime.setDescription('This object indicates the default maximum amount of time\n information on a context belonging to this instance is kept\n as entry in the rohcContextTable after the context is\n expired or terminated. The value of this object is used\n to initialize rohcContexStorageTime object when a new\n context is created.\n Changing the value of an rohcInstanceContextStorageTime\n instance does not affect any entry of the rohcContextTable\n created previously.\n ROHC-MIB implementations SHOULD store the set value of this\n object persistently.') rohcInstanceStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2),))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceStatus.setDescription('Status of the instance of ROHC.') rohcInstanceContextsTotal = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceContextsTotal.setDescription('Counter of all contexts created by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.') rohcInstanceContextsCurrent = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 15), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceContextsCurrent.setDescription('Number of currently active contexts created by this\n instance.') rohcInstancePackets = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstancePackets.setDescription('Counter of all packets passing this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.') rohcInstanceIRs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceIRs.setDescription('The number of all IR packets that are either sent\n or received by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n\n\n\n value of ifCounterDiscontinuityTime.') rohcInstanceIRDYNs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceIRDYNs.setDescription('The number of all IR-DYN packets that are either sent\n or received by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.') rohcInstanceFeedbacks = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceFeedbacks.setDescription('The number of all feedbacks that are either sent\n or received by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.') rohcInstanceCompressionRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 20), RohcCompressionRatio()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcInstanceCompressionRatio.setDescription('This object indicates the compression ratio so far over all\n packets on the channel served by this instance. The\n compression is computed over all bytes of the IP packets\n including the IP header but excluding all lower layer\n headers.') rohcProfileTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 1, 3), ) if mibBuilder.loadTexts: rohcProfileTable.setDescription('This table lists a set of profiles supported by the\n instance.') rohcProfileEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1), ).setIndexNames((0, "ROHC-MIB", "rohcChannelID"), (0, "ROHC-MIB", "rohcProfile")) if mibBuilder.loadTexts: rohcProfileEntry.setDescription('An entry describing a particular profile supported by\n the instance. It is indexed by the rohcChannelID\n identifying the instance and by the rohcProfile.') rohcProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))) if mibBuilder.loadTexts: rohcProfile.setDescription("Identifier of a profile supported. For a listing of\n possible profile values, see the IANA registry for\n 'RObust Header Compression (ROHC) Profile Identifiers'\n at http://www.iana.org/assignments/rohc-pro-ids") rohcProfileVendor = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcProfileVendor.setDescription('An object identifier that identifies the vendor who\n provides the implementation of robust header description.\n This object identifier SHALL point to the object identifier\n directly below the enterprise object identifier\n {1 3 6 1 4 1} allocated for the vendor. The value must be\n the object identifier {0 0} if the vendor is not known.') rohcProfileVersion = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 4), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0,32))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcProfileVersion.setDescription('The version number of the implementation of robust header\n compression. The zero-length string shall be used if the\n implementation does not have a version number.\n\n It is suggested that the version number consist of one or\n more decimal numbers separated by dots, where the first\n number is called the major version number.') rohcProfileDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 5), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcProfileDescr.setDescription('A textual description of the implementation.') rohcProfileNegotiated = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 6), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcProfileNegotiated.setDescription('When retrieved, this boolean object returns true\n if the profile has been negotiated to be used at\n the instance, i.e., is supported also be the\n corresponding compressor/decompressor.') rohcContextTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 2), ) if mibBuilder.loadTexts: rohcContextTable.setDescription('This table lists and describes all compressor contexts\n per instance.') rohcContextEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 2, 1), ).setIndexNames((0, "ROHC-MIB", "rohcChannelID"), (0, "ROHC-MIB", "rohcContextCID")) if mibBuilder.loadTexts: rohcContextEntry.setDescription('An entry describing a particular compressor context.') rohcContextCID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,16383))) if mibBuilder.loadTexts: rohcContextCID.setDescription('The context identifier (CID) of this context.') rohcContextCIDState = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("unused", 1), ("active", 2), ("expired", 3), ("terminated", 4),))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextCIDState.setDescription("State of the CID. When a CID is assigned to a context,\n its state changes from `unused' to `active'. The active\n context may stop operation due to some explicit\n signalling or after observing no packet for some specified\n time. In the first case then the CID state changes to\n `terminated', in the latter case it changes to `expired'.\n If the CID is re-used again for another context, the\n state changes back to `active'.") rohcContextProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextProfile.setDescription('Identifier of the profile for this context.\n The profile is identified by its index in the\n rohcProfileTable for this instance. There MUST exist a\n corresponding entry in the rohcProfileTable using the\n value of rohcContextProfile as second part of the index\n (and using the same rohcChannelID as first part of the\n index).') rohcContextDecompressorDepth = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextDecompressorDepth.setDescription('This object indicates whether reverse decompression, for\n example as described in RFC 3095, Section 6.1, is used\n on this channel or not, and if used, to what extent.\n\n\n\n\n Its value is only valid for decompressor contexts, i.e.,\n if rohcInstanceType has the value decompressor(2). For\n compressor contexts where rohcInstanceType has the value\n compressor(1), the value of this object is irrelevant\n and MUST be set to zero (0).\n\n The value of the reverse decompression depth indicates\n the maximum number of packets that are buffered, and thus\n possibly be reverse decompressed by the decompressor.\n A zero (0) value means that reverse decompression is not\n used.') rohcContextStorageTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 6), TimeInterval()).setUnits('centi-seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: rohcContextStorageTime.setDescription('The value of this object specifies how long this row\n can exist in the rohcContextTable after the\n rohcContextCIDState switched to expired(3) or\n terminated(4). This object returns the remaining time\n that the row may exist before it is aged out. The object\n is initialized with the value of the associated\n rohcContextStorageTime object. After expiration or\n termination of the context, the value of this object ticks\n backwards. The entry in the rohcContextTable is destroyed\n when the value reaches 0.\n\n The value of this object may be set in order to increase or\n reduce the remaining time that the row may exist. Setting\n the value to 0 will destroy this entry as soon as the\n rochContextCIDState has the value expired(3) or\n terminated(4).\n\n Note that there is no guarantee that the row is stored as\n long as this object indicates. In case of limited CID\n space, the instance may re-use a CID before the storage\n time of the corresponding row in rohcContextTable reaches\n the value of 0. In this case the information stored in this\n row is not anymore available.') rohcContextActivationTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 7), DateAndTime().clone(hexValue="0000000000000000")).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextActivationTime.setDescription("The date and time when the context started to be able to\n compress packets or decompress packets, respectively.\n The value '0000000000000000'H is returned if the context\n has not been activated yet.") rohcContextDeactivationTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 8), DateAndTime().clone(hexValue="0000000000000000")).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextDeactivationTime.setDescription("The date and time when the context stopped being able to\n compress packets or decompress packets, respectively,\n because it expired or was terminated for other reasons.\n The value '0000000000000000'H is returned if the context\n has not been deactivated yet.") rohcContextPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextPackets.setDescription('The number of all packets passing this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.') rohcContextIRs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextIRs.setDescription('The number of all IR packets sent or received,\n respectively, by this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n\n\n\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.') rohcContextIRDYNs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextIRDYNs.setDescription('The number of all IR-DYN packets sent or received,\n respectively, by this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.') rohcContextFeedbacks = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextFeedbacks.setDescription('The number of all feedbacks sent or received,\n respectively, by this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.') rohcContextDecompressorFailures = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextDecompressorFailures.setDescription('The number of all decompressor failures so far in this\n context. The number is only valid for decompressor\n contexts, i.e., if rohcInstanceType has the value\n decompressor(2).\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.') rohcContextDecompressorRepairs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextDecompressorRepairs.setDescription('The number of all context repairs so far in this\n context. The number is only valid for decompressor\n contexts, i.e., if rohcInstanceType has the value\n decompressor(2).\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.') rohcContextAllPacketsRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 15), RohcCompressionRatio()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextAllPacketsRatio.setDescription('This object indicates the compression ratio so far over all\n packets passing this context. The compression is computed\n over all bytes of the IP packets including the IP header\n but excluding all lower layer headers.') rohcContextAllHeadersRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 16), RohcCompressionRatio()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextAllHeadersRatio.setDescription('This object indicates the compression ratio so far over all\n packet headers passing this context. The compression is\n computed over all bytes of all headers that are subject to\n compression for the used profile.') rohcContextAllPacketsMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 17), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextAllPacketsMeanSize.setDescription('This object indicates the mean compressed packet size\n of all packets passing this context. The packet size\n includes the IP header and payload but excludes all lower\n layer headers. The mean value is given in byte rounded\n to the next integer value.') rohcContextAllHeadersMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 18), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextAllHeadersMeanSize.setDescription('This object indicates the mean compressed packet header size\n of all packets passing this context. The packet header size\n is the sum of the size of all headers of a packet that are\n subject to compression for the used profile. The mean value\n is given in byte rounded to the next integer value.') rohcContextLastPacketsRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 19), RohcCompressionRatio()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextLastPacketsRatio.setDescription('This object indicates the compression ratio\n concerning the last 16 packets passing this context\n or concerning all packets passing this context\n if they are less than 16, so far. The compression is\n computed over all bytes of the IP packets including the IP\n header but excluding all lower layer headers.') rohcContextLastHeadersRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 20), RohcCompressionRatio()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextLastHeadersRatio.setDescription('This object indicates the compression ratio concerning the\n headers of the last 16 packets passing this context or\n concerning the headers of all packets passing this context\n if they are less than 16, so far. The compression is\n computed over all bytes of all headers that are subject to\n compression for the used profile.') rohcContextLastPacketsMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 21), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextLastPacketsMeanSize.setDescription('This object indicates the mean compressed packet size\n concerning the last 16 packets passing this context or\n concerning all packets passing this context if they are\n less than 16, so far. The packet size includes the IP\n header and payload but excludes all lower layer headers.\n The mean value is given in byte rounded to the next\n integer value.') rohcContextLastHeadersMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 22), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rohcContextLastHeadersMeanSize.setDescription('This object indicates the mean compressed packet header size\n concerning the last 16 packets passing this context or\n concerning all packets passing this context if they are\n less than 16, so far. The packet header size is the sum of\n the size of all headers of a packet that are subject to\n compression for the used profile. The mean value is given\n in byte rounded to the next integer value.') rohcCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 2, 1)) rohcGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 2, 2)) rohcCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 112, 2, 1, 1)).setObjects(*(("ROHC-MIB", "rohcInstanceGroup"), ("ROHC-MIB", "rohcContextGroup"), ("ROHC-MIB", "rohcStatisticsGroup"), ("ROHC-MIB", "rohcTimerGroup"), ("ROHC-MIB", "rohcContextStatisticsGroup"),)) if mibBuilder.loadTexts: rohcCompliance.setDescription('The compliance statement for SNMP entities that implement\n the ROHC-MIB.\n\n Note that compliance with this compliance\n statement requires compliance with the\n ifCompliance3 MODULE-COMPLIANCE statement of the\n IF-MIB (RFC2863).') rohcInstanceGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 2)).setObjects(*(("ROHC-MIB", "rohcChannelType"), ("ROHC-MIB", "rohcChannelFeedbackFor"), ("ROHC-MIB", "rohcChannelDescr"), ("ROHC-MIB", "rohcChannelStatus"), ("ROHC-MIB", "rohcInstanceFBChannelID"), ("ROHC-MIB", "rohcInstanceVendor"), ("ROHC-MIB", "rohcInstanceVersion"), ("ROHC-MIB", "rohcInstanceDescr"), ("ROHC-MIB", "rohcInstanceClockRes"), ("ROHC-MIB", "rohcInstanceMaxCID"), ("ROHC-MIB", "rohcInstanceLargeCIDs"), ("ROHC-MIB", "rohcInstanceMRRU"), ("ROHC-MIB", "rohcInstanceStatus"), ("ROHC-MIB", "rohcProfileVendor"), ("ROHC-MIB", "rohcProfileVersion"), ("ROHC-MIB", "rohcProfileDescr"), ("ROHC-MIB", "rohcProfileNegotiated"),)) if mibBuilder.loadTexts: rohcInstanceGroup.setDescription('A collection of objects providing information about\n ROHC instances, used channels and available profiles.') rohcStatisticsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 4)).setObjects(*(("ROHC-MIB", "rohcInstanceContextsTotal"), ("ROHC-MIB", "rohcInstanceContextsCurrent"), ("ROHC-MIB", "rohcInstancePackets"), ("ROHC-MIB", "rohcInstanceIRs"), ("ROHC-MIB", "rohcInstanceIRDYNs"), ("ROHC-MIB", "rohcInstanceFeedbacks"), ("ROHC-MIB", "rohcInstanceCompressionRatio"),)) if mibBuilder.loadTexts: rohcStatisticsGroup.setDescription('A collection of objects providing ROHC statistics.') rohcContextGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 5)).setObjects(*(("ROHC-MIB", "rohcContextCIDState"), ("ROHC-MIB", "rohcContextProfile"), ("ROHC-MIB", "rohcContextDecompressorDepth"),)) if mibBuilder.loadTexts: rohcContextGroup.setDescription('A collection of objects providing information about\n ROHC compressor contexts and decompressor contexts.') rohcTimerGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 6)).setObjects(*(("ROHC-MIB", "rohcInstanceContextStorageTime"), ("ROHC-MIB", "rohcContextStorageTime"), ("ROHC-MIB", "rohcContextActivationTime"), ("ROHC-MIB", "rohcContextDeactivationTime"),)) if mibBuilder.loadTexts: rohcTimerGroup.setDescription('A collection of objects providing statistical information\n about ROHC compressor contexts and decompressor contexts.') rohcContextStatisticsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 7)).setObjects(*(("ROHC-MIB", "rohcContextPackets"), ("ROHC-MIB", "rohcContextIRs"), ("ROHC-MIB", "rohcContextIRDYNs"), ("ROHC-MIB", "rohcContextFeedbacks"), ("ROHC-MIB", "rohcContextDecompressorFailures"), ("ROHC-MIB", "rohcContextDecompressorRepairs"), ("ROHC-MIB", "rohcContextAllPacketsRatio"), ("ROHC-MIB", "rohcContextAllHeadersRatio"), ("ROHC-MIB", "rohcContextAllPacketsMeanSize"), ("ROHC-MIB", "rohcContextAllHeadersMeanSize"), ("ROHC-MIB", "rohcContextLastPacketsRatio"), ("ROHC-MIB", "rohcContextLastHeadersRatio"), ("ROHC-MIB", "rohcContextLastPacketsMeanSize"), ("ROHC-MIB", "rohcContextLastHeadersMeanSize"),)) if mibBuilder.loadTexts: rohcContextStatisticsGroup.setDescription('A collection of objects providing statistical information\n about ROHC compressor contexts and decompressor contexts.') mibBuilder.exportSymbols("ROHC-MIB", rohcProfileVendor=rohcProfileVendor, rohcInstanceEntry=rohcInstanceEntry, rohcContextDecompressorDepth=rohcContextDecompressorDepth, rohcInstanceIRs=rohcInstanceIRs, rohcChannelID=rohcChannelID, rohcContextTable=rohcContextTable, rohcContextDeactivationTime=rohcContextDeactivationTime, rohcInstanceContextsCurrent=rohcInstanceContextsCurrent, rohcInstanceTable=rohcInstanceTable, rohcInstanceMaxCID=rohcInstanceMaxCID, rohcInstanceFBChannelID=rohcInstanceFBChannelID, RohcChannelIdentifierOrZero=RohcChannelIdentifierOrZero, rohcContextFeedbacks=rohcContextFeedbacks, rohcMIB=rohcMIB, rohcTimerGroup=rohcTimerGroup, rohcContextDecompressorRepairs=rohcContextDecompressorRepairs, rohcInstanceContextStorageTime=rohcInstanceContextStorageTime, rohcInstanceGroup=rohcInstanceGroup, RohcCompressionRatio=RohcCompressionRatio, rohcContextPackets=rohcContextPackets, rohcInstanceLargeCIDs=rohcInstanceLargeCIDs, rohcStatisticsGroup=rohcStatisticsGroup, rohcProfileVersion=rohcProfileVersion, rohcContextLastPacketsMeanSize=rohcContextLastPacketsMeanSize, rohcChannelDescr=rohcChannelDescr, rohcObjects=rohcObjects, rohcContextIRs=rohcContextIRs, rohcContextAllHeadersMeanSize=rohcContextAllHeadersMeanSize, rohcInstancePackets=rohcInstancePackets, rohcContextDecompressorFailures=rohcContextDecompressorFailures, rohcCompliances=rohcCompliances, rohcInstanceStatus=rohcInstanceStatus, rohcContextLastPacketsRatio=rohcContextLastPacketsRatio, rohcInstanceVendor=rohcInstanceVendor, rohcContextLastHeadersMeanSize=rohcContextLastHeadersMeanSize, rohcContextProfile=rohcContextProfile, rohcChannelEntry=rohcChannelEntry, rohcInstanceVersion=rohcInstanceVersion, rohcInstanceFeedbacks=rohcInstanceFeedbacks, rohcContextStorageTime=rohcContextStorageTime, rohcContextAllPacketsMeanSize=rohcContextAllPacketsMeanSize, rohcChannelTable=rohcChannelTable, rohcContextActivationTime=rohcContextActivationTime, rohcContextIRDYNs=rohcContextIRDYNs, rohcContextCID=rohcContextCID, rohcInstanceClockRes=rohcInstanceClockRes, rohcContextCIDState=rohcContextCIDState, rohcProfile=rohcProfile, rohcContextLastHeadersRatio=rohcContextLastHeadersRatio, rohcInstanceCompressionRatio=rohcInstanceCompressionRatio, rohcProfileDescr=rohcProfileDescr, rohcGroups=rohcGroups, rohcChannelStatus=rohcChannelStatus, rohcCompliance=rohcCompliance, rohcProfileNegotiated=rohcProfileNegotiated, PYSNMP_MODULE_ID=rohcMIB, RohcChannelIdentifier=RohcChannelIdentifier, rohcProfileEntry=rohcProfileEntry, rohcChannelType=rohcChannelType, rohcContextGroup=rohcContextGroup, rohcInstanceMRRU=rohcInstanceMRRU, rohcInstanceIRDYNs=rohcInstanceIRDYNs, rohcContextEntry=rohcContextEntry, rohcChannelFeedbackFor=rohcChannelFeedbackFor, rohcContextStatisticsGroup=rohcContextStatisticsGroup, rohcContextAllHeadersRatio=rohcContextAllHeadersRatio, rohcProfileTable=rohcProfileTable, rohcConformance=rohcConformance, rohcInstanceType=rohcInstanceType, rohcInstanceContextsTotal=rohcInstanceContextsTotal, rohcInstanceDescr=rohcInstanceDescr, rohcInstanceObjects=rohcInstanceObjects, rohcContextAllPacketsRatio=rohcContextAllPacketsRatio)
246.384146
3,124
0.740144
5,111
40,407
5.850323
0.128351
0.008093
0.011036
0.009498
0.480151
0.43945
0.369887
0.343667
0.312163
0.29484
0
0.040076
0.163239
40,407
163
3,125
247.895706
0.844281
0.007226
0
0.019608
0
0.30719
0.568543
0.033436
0
0
0
0
0
1
0
false
0.065359
0.052288
0
0.104575
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
1
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
4
30f632315bf80a25755270e8635ee48d72de5b33
3,085
py
Python
features/tests/features/generators/test_datetime.py
daobook/autogluon
7309118f2ab1c9519f25acf61a283a95af95842b
[ "Apache-2.0" ]
1
2022-02-19T13:22:26.000Z
2022-02-19T13:22:26.000Z
features/tests/features/generators/test_datetime.py
daobook/autogluon
7309118f2ab1c9519f25acf61a283a95af95842b
[ "Apache-2.0" ]
3
2021-12-30T20:28:01.000Z
2022-02-09T20:19:21.000Z
features/tests/features/generators/test_datetime.py
daobook/autogluon
7309118f2ab1c9519f25acf61a283a95af95842b
[ "Apache-2.0" ]
null
null
null
from autogluon.features.generators import DatetimeFeatureGenerator def test_datetime_feature_generator(generator_helper, data_helper): # Given input_data = data_helper.generate_multi_feature_full() generator_1 = DatetimeFeatureGenerator() generator_2 = DatetimeFeatureGenerator(features = ['hour']) expected_feature_metadata_in_full = { ('datetime', ()): ['datetime'], ('object', ('datetime_as_object',)): ['datetime_as_object'], } expected_feature_metadata_full_1 = {('int', ('datetime_as_int',)): [ 'datetime', 'datetime.year', 'datetime.month', 'datetime.day', 'datetime.dayofweek', 'datetime_as_object', 'datetime_as_object.year', 'datetime_as_object.month', 'datetime_as_object.day', 'datetime_as_object.dayofweek' ]} expected_feature_metadata_full_2 = {('int', ('datetime_as_int',)): [ 'datetime', 'datetime.hour', 'datetime_as_object', 'datetime_as_object.hour', ]} expected_output_data_feat_datetime = [ 1533140820000000000, 1301322000000000000, 1301322000000000000, 1524238620000000000, 1524238620000000000, -5364662400000000000, 7289654340000000000, 1301322000000000000, 1301322000000000000 ] expected_output_data_feat_datetime_year = [ 2018, 2011, # blank and nan values are set to the mean of good values = 2011 2011, 2018, 2018, 1800, 2200, 2011, # 2700 and 1000 are out of range for a pandas datetime so they are set to the mean 2011 # see limits at https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.max.html ] expected_output_data_feat_datetime_hour = [ 16, 14, 14, 15, 15, 0, 23, 14, 14 ] # When output_data_1 = generator_helper.fit_transform_assert( input_data=input_data, generator=generator_1, expected_feature_metadata_in_full=expected_feature_metadata_in_full, expected_feature_metadata_full=expected_feature_metadata_full_1, ) assert list(output_data_1['datetime'].values) == list(output_data_1['datetime_as_object'].values) assert expected_output_data_feat_datetime == list(output_data_1['datetime'].values) assert expected_output_data_feat_datetime_year == list(output_data_1['datetime.year'].values) output_data_2 = generator_helper.fit_transform_assert( input_data=input_data, generator=generator_2, expected_feature_metadata_in_full=expected_feature_metadata_in_full, expected_feature_metadata_full=expected_feature_metadata_full_2, ) assert list(output_data_2['datetime'].values) == list(output_data_2['datetime_as_object'].values) assert expected_output_data_feat_datetime == list(output_data_2['datetime'].values) assert expected_output_data_feat_datetime_hour == list(output_data_2['datetime.hour'].values)
32.135417
101
0.67812
342
3,085
5.695906
0.245614
0.087269
0.129877
0.079055
0.577515
0.463039
0.311088
0.311088
0.259754
0.259754
0
0.106992
0.23047
3,085
95
102
32.473684
0.713564
0.077472
0
0.333333
1
0
0.152925
0.042283
0
0
0
0
0.102564
1
0.012821
false
0
0.012821
0
0.025641
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
30f6d4afaaa493162b41239409c7176bc51a45d0
2,785
py
Python
validation/synthetic_promoters.py
umarov90/DeepREFind
c3b24b760f3829ea8ed6ba6ed7db76cf90c45a9e
[ "Apache-2.0" ]
1
2022-03-16T07:39:10.000Z
2022-03-16T07:39:10.000Z
validation/synthetic_promoters.py
umarov90/DeepREFind
c3b24b760f3829ea8ed6ba6ed7db76cf90c45a9e
[ "Apache-2.0" ]
2
2021-11-04T14:58:52.000Z
2022-02-11T04:28:32.000Z
validation/synthetic_promoters.py
umarov90/ReFeaFi
c3b24b760f3829ea8ed6ba6ed7db76cf90c45a9e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" import common as cm import tensorflow as tf import numpy as np import math from scipy import stats from Bio.Seq import Seq half_size = 500 batch_size = 128 scan_step = 1 seq_len = 1001 out = [] os.chdir(open("../data_dir").read().strip()) fasta = cm.parse_genome("data/genomes/hg19.fa") # fasta = pickle.load(open("fasta.p", "rb")) background = {} background["RPLP0_CE_bg"] = ["chr12", "-", 120638861 - 1, 120639013 - 1] background["ACTB_CE_bg"] = ["chr7", "-", 5570183 - 1, 5570335 - 1] background["C14orf166_CE_bg"] = ["chr14", "+", 52456090 - 1, 52456242 - 1] our_scores = [] real_scores = [] new_graph = tf.Graph() with tf.Session(graph=new_graph) as sess: tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], "models/model_predict") saver = tf.train.Saver() saver.restore(sess, "models/model_predict/variables/variables") input_x = tf.get_default_graph().get_tensor_by_name("input_prom:0") y = tf.get_default_graph().get_tensor_by_name("output_prom:0") kr = tf.get_default_graph().get_tensor_by_name("kr:0") in_training_mode = tf.get_default_graph().get_tensor_by_name("in_training_mode:0") with open('data/Supplemental_Table_S7.tsv') as file: next(file) for line in file: vals = line.split("\t") fa = vals[25].strip() if(vals[3] in background.keys()): bg = background[vals[3]] strand = bg[1] real_score = float(vals[23]) if math.isnan(real_score): continue real_scores.append(real_score) if (strand == "+"): fa_bg = fasta[bg[0]][bg[2] - (half_size - 114): bg[2] - (half_size - 114) + seq_len] faf = fa_bg[:half_size - 49] + fa + fa_bg[half_size + 115:] else: fa_bg = fasta[bg[0]][bg[2] - (half_size - 49): bg[2] - (half_size - 49) + seq_len] fa_bg = str(Seq(fa_bg).reverse_complement()) faf = fa_bg[:half_size - 114] + fa + fa_bg[half_size + 50:] predict = sess.run(y, feed_dict={input_x: [cm.encode_seq(faf)], kr: 1.0, in_training_mode: False}) score = predict[0][0] - predict[0][1] score = math.log(1 + score / (1.0001 - score)) our_scores.append(score) out.append(str(real_score) + "," + str(score)) real_scores = np.asarray(real_scores) corr = stats.pearsonr(np.asarray(our_scores), np.asarray(real_scores))[0] print(corr) with open("figures_data/synth.csv", 'w+') as f: f.write('\n'.join(out))
39.785714
111
0.596409
400
2,785
3.925
0.39
0.04586
0.030573
0.043312
0.2
0.110828
0.110828
0.110828
0.029299
0
0
0.062171
0.249192
2,785
70
112
39.785714
0.688666
0.022621
0
0
0
0
0.109886
0.033811
0
0
0
0
0
1
0
false
0
0.114754
0
0.114754
0.016393
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30f7b5fce84c80a74ad5a056cdaf77b75b688b7c
740
py
Python
tests/test_index.py
cxan96/strong-but-simple-passwords
c7242f870a2968bd40eceb97b163b4ae307cb84c
[ "MIT" ]
2
2021-04-04T03:44:16.000Z
2021-06-04T13:50:29.000Z
tests/test_index.py
cxan96/strong-but-simple-passwords
c7242f870a2968bd40eceb97b163b4ae307cb84c
[ "MIT" ]
null
null
null
tests/test_index.py
cxan96/strong-but-simple-passwords
c7242f870a2968bd40eceb97b163b4ae307cb84c
[ "MIT" ]
1
2021-08-28T03:35:36.000Z
2021-08-28T03:35:36.000Z
from strong_but_simple_passwords import views def test_index_http_ok(client): response = client.get("/") assert response.status_code == 200 def test_empty_post(monkeypatch, client): a_random_sentence = "A random sentence." monkeypatch.setattr(views, "get_random_sentence", lambda: a_random_sentence) response = client.post("/") assert response.status_code == 200 assert a_random_sentence in str(response.data) def test_strong_password(client): payload = {"input_sentence": "A very long input sentence for a strong password"} response = client.post("/", data=payload) assert response.status_code == 200 assert b"Congratulations!" in response.data assert b"centuries" in response.data
28.461538
84
0.736486
98
740
5.336735
0.397959
0.133843
0.114723
0.137667
0.17782
0.126195
0
0
0
0
0
0.014587
0.166216
740
25
85
29.6
0.833063
0
0
0.1875
0
0
0.171622
0
0
0
0
0
0.375
1
0.1875
false
0.1875
0.0625
0
0.25
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
0
0
0
1
30f85e513a4285e63e608e0444128184121a5ac0
865
py
Python
dojos/lendico/sinais.py
ramalho/tdd-com-pytest
edae805ddf2267d8e08eea6ab344242217f52043
[ "BSD-3-Clause" ]
15
2018-05-25T16:17:08.000Z
2020-04-02T21:39:41.000Z
dojos/lendico/sinais.py
ramalho/tdd-com-pytest
edae805ddf2267d8e08eea6ab344242217f52043
[ "BSD-3-Clause" ]
null
null
null
dojos/lendico/sinais.py
ramalho/tdd-com-pytest
edae805ddf2267d8e08eea6ab344242217f52043
[ "BSD-3-Clause" ]
1
2021-04-19T21:27:17.000Z
2021-04-19T21:27:17.000Z
#!/usr/bin/env python3 import sys def search(query, data): query = query.replace('-',' ') words = set(query.upper().split()) for code, char, name in data: name = name.replace('-',' ') if words <= set(name.split()): yield f'{code}\t{char}\t{name}' def reader(): with open('UnicodeData.txt') as _file: for line in _file: code, name = line.split(';')[:2] char = chr(int(code, 16)) yield f'U+{code}', char, name def main(*words): if len(words) < 1: print("Please provide one word or more", file=sys.stderr) return query = ' '.join(words) index = -1 for index, line in enumerate(search(query, reader())): print(line) if index == -1: print("No results", file=sys.stderr) if __name__ == "__main__": main(*sys.argv[1:])
23.378378
65
0.543353
116
865
3.965517
0.474138
0.047826
0.052174
0
0
0
0
0
0
0
0
0.012903
0.283237
865
36
66
24.027778
0.729032
0.024277
0
0
0
0
0.118624
0.026097
0
0
0
0
0
1
0.115385
false
0
0.038462
0
0.192308
0.115385
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30f86263cd9609adb5d7644c7670d39fe1c0be15
6,154
py
Python
bms_2/app01/views.py
luyl1017713252/python
3b30cffa85b625e512415fa882b4bc7708a5e0b8
[ "MulanPSL-1.0" ]
null
null
null
bms_2/app01/views.py
luyl1017713252/python
3b30cffa85b625e512415fa882b4bc7708a5e0b8
[ "MulanPSL-1.0" ]
null
null
null
bms_2/app01/views.py
luyl1017713252/python
3b30cffa85b625e512415fa882b4bc7708a5e0b8
[ "MulanPSL-1.0" ]
null
null
null
import json from django.shortcuts import render, redirect, HttpResponse # Create your views here. from django.urls import reverse from app01 import models from app01.models import Book, Publish, Author, AuthorDetail def books(request): book_list = Book.objects.all() publish_list = Publish.objects.all() author_list = Author.objects.all() return render(request, 'books.html', {'book_list': book_list, 'publish_list': publish_list, 'author_list': author_list}) def add_book(request): if request.method == 'GET': publish_list = Publish.objects.all() author_list = Author.objects.all() return render(request, 'book_add.html', {'publish_list': publish_list, 'author_list': author_list}) else: title = request.POST.get('title') price = request.POST.get('price') pub_date = request.POST.get('pub_date') publish = request.POST.get('publish') authors = request.POST.getlist('authors') book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish) book.authors.add(*authors) return redirect('/books/') def del_book(request): book_id = request.POST.get('id_book') print(book_id) ret = Book.objects.filter(id=book_id).delete() if ret: return HttpResponse('True') else: return HttpResponse('False') def up_book(request, book_id): if request.method == 'GET': book_up_list = Book.objects.filter(id=book_id) publish_list = Publish.objects.all() author_list = Author.objects.all() book = Book.objects.filter(id=book_id).values('publish')[0] author = Book.objects.filter(id=book_id).values('authors')[0] publish_name = Publish.objects.filter(id=book['publish']).first() author_name = Author.objects.filter(id=author['authors']).first() return render(request, 'up_book.html', {'book_up_list': book_up_list, 'publish_list': publish_list, 'author_list': author_list, 'publish_name': publish_name, 'author_name': author_name}) else: title = request.POST.get('title') price = request.POST.get('price') pub_date = request.POST.get('pub_date') publish = request.POST.get('publish') authors = request.POST.getlist('authors') # a_list = {'author_id': authors} print(authors) date_list = {'title': title, 'price': price, 'pub_date': pub_date, 'publish_id': publish} Book.objects.filter(id=book_id).update(**date_list) book = Book.objects.filter(id=book_id).first() book.authors.set(authors) return redirect(reverse('books')) def publishs(request): publish_list = Publish.objects.all() return render(request, 'publishs.html', {'publish_list': publish_list}) def add_publish(request): if request.method == 'GET': return render(request, 'publish_add.html') else: name = request.POST.get('name') email = request.POST.get('email') Publish.objects.create(name=name, email=email) return redirect('/publishs/') def del_publish(request, publish_id): Publish.objects.filter(id=publish_id).delete() return redirect('/publishs/') def up_publish(request, publish_id): if request.method == 'GET': publish = Publish.objects.filter(id=publish_id) return render(request, 'up_publish.html', {'publish': publish}) else: publish = request.POST.dict() del publish['csrfmiddlewaretoken'] Publish.objects.filter(id=publish_id).update(**publish) return redirect('/publishs/') def authors(request): author_list = Author.objects.all() return render(request, 'authors.html', {'author_list': author_list}) def add_author(request): if request.method == 'GET': return render(request, 'author_add.html') else: name = request.POST.get('name') age = request.POST.get('age') email = request.POST.get('email') tel = request.POST.get('tel') tels = AuthorDetail.objects.create(tel=tel) author = Author.objects.create(name=name, age=age, email=email, ad=tels) return redirect('/authors/') def del_author(request, author_id): author = Author.objects.filter(id=author_id) ad_id = author.values('ad_id')[0]['ad_id'] author.delete() AuthorDetail.objects.filter(id=ad_id).delete() return redirect('/authors/') def up_author(request, author_id): if request.method == 'GET': author = Author.objects.filter(id=author_id) return render(request, 'up_author.html', {'author': author}) else: name = request.POST.get('name') age = request.POST.get('age') email = request.POST.get('email') tel = request.POST.get('tel') author = Author.objects.filter(id=author_id) author.update(name=name, age=age, email=email) AuthorDetail.objects.filter(id=author.values('ad_id')[0]['ad_id']).update(tel=tel) return redirect('/authors/') def ajax_add_book(request): authors_list = [] title = request.POST.get('title') price = str(format(int(request.POST.get('price')), '.2f')) pub_date = request.POST.get('pub_date') publish = request.POST.get('publish') authors = request.POST.getlist('authors') book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish) print(price) book.authors.add(*authors) count_book = Book.objects.all().count() publish_name = Publish.objects.filter(id=publish).first() authors_name = Author.objects.filter(id__in=authors) for i in authors_name: authors_list.append(i.name) data_dict = { 'pd': 'true', 'book_id': book.id, 'count_book': count_book, 'title': title, 'price': price, 'pub_date': pub_date, 'publish_name': publish_name.name, 'authors': authors_list } # print(authors, publish) if book: data_dict['pd'] = 'true' else: data_dict['pd'] = 'false' return HttpResponse(json.dumps(data_dict))
35.165714
124
0.647221
782
6,154
4.938619
0.098465
0.076903
0.083376
0.034438
0.564215
0.487053
0.399275
0.347488
0.279907
0.245469
0
0.001847
0.207995
6,154
175
125
35.165714
0.790521
0.012837
0
0.415493
0
0
0.11166
0
0
0
0
0
0
1
0.091549
false
0
0.035211
0
0.267606
0.021127
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30fcb43dd0f69d332ab19924f865fff8aca3d2e2
3,642
py
Python
chatbot/scripts/interactive_slack.py
check-spelling/learning
a3b031cf8fe766ad97e023ec1f3177389778853b
[ "Apache-2.0" ]
2
2021-08-24T05:20:48.000Z
2021-09-30T18:03:46.000Z
chatbot/scripts/interactive_slack.py
check-spelling/learning
a3b031cf8fe766ad97e023ec1f3177389778853b
[ "Apache-2.0" ]
null
null
null
chatbot/scripts/interactive_slack.py
check-spelling/learning
a3b031cf8fe766ad97e023ec1f3177389778853b
[ "Apache-2.0" ]
3
2021-07-24T23:19:45.000Z
2021-12-27T04:20:45.000Z
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Talk with a model using a Slack channel. # Examples ```shell parlai interactive_slack --token xoxb-... --task blended_skill_talk:all -mf zoo:blenderbot2/blenderbot2_400M/model --search-server http://localhost:5000``` """ from os import getenv from pprint import pformat from parlai.scripts.interactive import setup_args from parlai.core.agents import create_agent from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging from parlai.agents.local_human.local_human import LocalHumanAgent try: from slack import RTMClient except ImportError: raise ImportError('The slackclient package must be installed to run this script') SHARED = {} SLACK_BOT_TOKEN = getenv('SLACK_BOT_TOKEN') def setup_slack_args(shared): """ Build and parse CLI opts. """ parser = setup_args() parser.description = 'Interactive chat with a model in a Slack channel' parser.add_argument( '--token', default=SLACK_BOT_TOKEN, metavar='SLACK_BOT_TOKEN', help='A legacy Slack bot token to use for RTM messaging', ) return parser @RTMClient.run_on(event='message') async def rtm_handler(rtm_client, web_client, data, **kwargs): """ Handles new chat messages from Slack. Does the following to let the user know immediately that the agent is working since it takes a while Adds the :eyes: reaction to let the user Sets the status of the bot to typing Runs the agent on the given text Returns the model_response text to the channel where the message came from. Removes the :eyes: reaction Only works on user messages, not messages from other bots """ global SHARED if 'bot_profile' in data: # Dont respond to bot messages (eg the one this app generates) return logging.info(f'Got new message {pformat(data)}') channel = data['channel'] web_client.reactions_add(channel=channel, name='eyes', timestamp=data['ts']) reply = {'episode_done': False, 'text': data['text']} SHARED['agent'].observe(reply) logging.info('Agent observed') await rtm_client.typing(channel=channel) model_response = SHARED['agent'].act() logging.info('Agent acted') web_client.chat_postMessage(channel=channel, text=model_response['text']) logging.info(f'Sent response: {model_response["text"]}') web_client.reactions_remove(channel=channel, name='eyes', timestamp=data['ts']) def interactive_slack(opt): global SHARED if not opt.get('token'): raise RuntimeError( 'A Slack bot token must be specified. Must be a legacy bot app token for RTM messaging' ) human_agent = LocalHumanAgent(opt) agent = create_agent(opt, requireModelExists=True) agent.opt.log() agent.opt['verbose'] = True SHARED['opt'] = agent.opt SHARED['agent'] = agent SHARED['world'] = create_task(SHARED.get('opt'), [human_agent, SHARED['agent']]) SHARED['client'] = client = RTMClient(token=opt['token']) logging.info('Slack client is starting') client.start() @register_script('interactive_slack', aliases=['slack'], hidden=True) class InteractiveSlack(ParlaiScript): @classmethod def setup_args(cls): return setup_slack_args(SHARED) def run(self): return interactive_slack(self.opt) if __name__ == '__main__': InteractiveSlack.main()
33.412844
155
0.7095
496
3,642
5.092742
0.40121
0.019002
0.030879
0.015835
0.029295
0.029295
0.029295
0
0
0
0
0.003383
0.188358
3,642
108
156
33.722222
0.85115
0.136189
0
0.030303
0
0
0.204443
0.009036
0
0
0
0
0
1
0.060606
false
0
0.166667
0.030303
0.30303
0.015152
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30fd7f4d4cd4681834c31425f77246c6aabccc27
2,542
py
Python
plywood/plugins/include.py
colinta/plywood
49cf98f198da302ec66e11338320c6b72b642ffa
[ "BSD-2-Clause-FreeBSD" ]
1
2015-06-11T06:17:42.000Z
2015-06-11T06:17:42.000Z
plywood/plugins/include.py
colinta/plywood
49cf98f198da302ec66e11338320c6b72b642ffa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
plywood/plugins/include.py
colinta/plywood
49cf98f198da302ec66e11338320c6b72b642ffa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
''' Includes content from another template. If you assign any keyword arguments, those will be available in the scope of that template. ''' import os from plywood import Plywood from plywood.values import PlywoodValue from plywood.exceptions import InvalidArguments from plywood.env import PlywoodEnv @PlywoodEnv.register_runtime() def include(states, scope, arguments, block): if len(arguments.args) != 1: raise InvalidArguments('`include` only accepts one argument') if len(block.lines): raise InvalidArguments('`include` does not accept a block') restore_scope = {} delete_scope = [] if isinstance(scope['self'], PlywoodValue): context = scope['self'].python_value(scope) else: context = scope['self'] if len(arguments.kwargs): kwargs = dict( (item.key.get_name(), item.value) for item in arguments.kwargs ) for key, value in kwargs.items(): if key in context: restore_scope[key] = context[key] else: delete_scope.append(key) context[key] = value if '__env' in scope: env = scope['__env'] else: env = PlywoodEnv({'separator': ' '}) template_name = arguments.args[0].python_value(scope) plywood = None for path in scope['__paths']: template_path = os.path.join(path, template_name) + '.ply' if template_path in env.includes: plywood = env.includes[template_path] elif os.path.exists(template_path): retval = '' with open(template_path) as f: input = f.read() plywood = Plywood(input) env.includes[template_path] = plywood # scope is not pushed/popped - `include` adds its variables to the local scope. if plywood: break if not plywood: raise Exception('Could not find template: {0!r}'.format(template_name)) retval = plywood.run(context, env) if len(arguments.kwargs): for key, value in restore_scope.items(): context[key] = value for key in delete_scope: del context[key] return states, retval @PlywoodEnv.register_startup() def startup(plywood, scope): if plywood.options.get('paths'): scope['__paths'] = plywood.options.get('paths') elif plywood.options.get('path'): scope['__paths'] = [plywood.options.get('path')] else: scope['__paths'] = [os.getcwd()]
31
95
0.611723
298
2,542
5.110738
0.338926
0.047275
0.044649
0.026264
0.072226
0.03677
0
0
0
0
0
0.001641
0.280881
2,542
81
96
31.382716
0.83151
0.083006
0
0.126984
0
0
0.077486
0
0
0
0
0
0
1
0.031746
false
0
0.079365
0
0.126984
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
30fe3ede542736245b717c523c0b5b49831e3733
1,178
py
Python
m3uragen/m3u.py
TiBeN/m3uragen
45f6f7c76c7a345d01f43a152f1f815a9891441f
[ "Apache-2.0" ]
1
2020-12-19T09:18:13.000Z
2020-12-19T09:18:13.000Z
m3uragen/m3u.py
TiBeN/m3uragen
45f6f7c76c7a345d01f43a152f1f815a9891441f
[ "Apache-2.0" ]
1
2021-10-22T00:38:17.000Z
2021-12-15T13:48:18.000Z
m3uragen/m3u.py
TiBeN/m3uragen
45f6f7c76c7a345d01f43a152f1f815a9891441f
[ "Apache-2.0" ]
null
null
null
"""Handle M3U files generation""" import os import logging def generate(software, out_dir, suffix, dry_run): """Generate M3U file for the given software into out_dir""" m3u_filename = software.name + (suffix if suffix else '') + '.m3u' if not dry_run: m3u_fd = open(os.path.join(out_dir, m3u_filename), 'w') for i in software.images(): image_rel_path = os.path.relpath(i.path, out_dir) if not dry_run: m3u_fd.write((image_rel_path + '\n')) if not dry_run: m3u_fd.close() logging.info('Created M3U file for %s (%i image files)', software.name, len(software.images())) def generate_all(softwares, out_dir, suffix, dry_run): """Generate M3U file for the list of softwares into out_dir""" if not dry_run: if not out_dir.exists(): out_dir.mkdir(parents=True) multi_images_softwares = (x for x in softwares if x.nb_images() > 1) for i in multi_images_softwares: try: generate(i, out_dir, suffix, dry_run) except UnicodeEncodeError: logging.warning("Unicode error while processing %s", ascii(i.name))
31
79
0.633277
171
1,178
4.181287
0.374269
0.075524
0.044755
0.061538
0.233566
0.208392
0.109091
0.109091
0.109091
0.109091
0
0.012571
0.257216
1,178
37
80
31.837838
0.804571
0.117148
0
0.166667
1
0
0.078125
0
0
0
0
0
0
1
0.083333
false
0
0.083333
0
0.166667
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
0
0
0
1
a5001932f04ab10d0bb10446b772ad4ac5a29053
860
py
Python
Dataset/Leetcode/train/46/7.py
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/46/7.py
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/46/7.py
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution(object): def XXXUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [] nums.sort() n = len(nums) visited = [0] * n res = [] def helper1(temp_list, length): # if length == n and temp_list not in res: # res.append(temp_list) if length == n: res.append(temp_list) for i in range(n): if visited[i] or (i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]): continue visited[i] = 1 helper1(temp_list + [nums[i]], length + 1) visited[i] = 0 def helper2(nums, temp_list, length): if length == n and temp_list not in res: res.append(temp_list) for i in range(len(nums)): helper2(nums[:i] + nums[i + 1:], temp_list + [nums[i]], length + 1) helper1([],0) # helper2(nums, [], 0) return res
23.888889
79
0.561628
133
860
3.56391
0.24812
0.151899
0.056962
0.107595
0.462025
0.415612
0.331224
0.331224
0.248945
0.248945
0
0.027419
0.27907
860
35
80
24.571429
0.737097
0
0
0.083333
0
0
0
0
0
0
0
0
0
0
null
null
0
0
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
a500ed1e01eb7264848c0ee426a0677826902113
7,635
py
Python
tests/test_uvscli.py
kouritron/uvs
42a4241445360fd64fc09f39fb9a4b5e596d622c
[ "BSD-3-Clause" ]
null
null
null
tests/test_uvscli.py
kouritron/uvs
42a4241445360fd64fc09f39fb9a4b5e596d622c
[ "BSD-3-Clause" ]
null
null
null
tests/test_uvscli.py
kouritron/uvs
42a4241445360fd64fc09f39fb9a4b5e596d622c
[ "BSD-3-Clause" ]
null
null
null
import os import sys import shutil import io # if you got module not found errors, uncomment these. PyCharm IDE does not need it. # get the abs version of . and .. and append them to this process's path. sys.path.append(os.path.abspath('..')) sys.path.append(os.path.abspath('.')) #print sys.path import unittest import subprocess import testutils as tu import libuvs.systemdefaults as sdef from libuvs import uvsmanager class TestUVSCli(unittest.TestCase): repo_root_path = None repo_root_cksums_file = None # This will run once for all tests in this class, @classmethod def setUpClass(cls): super(TestUVSCli, cls).setUpClass() cwd = os.getcwd() print "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> setUpClass() called from cwd: " + str(cwd) tests_folder_abs_path = os.path.dirname(tu.find_file_within_this_project('test_uvscli.py')) print "Found tests directory path to be: " + str(tests_folder_abs_path) cls.repo_root_path = os.path.join(tests_folder_abs_path, 'ignoreme') cls.repo_root_cksums_file = os.path.join(tests_folder_abs_path, "ignoreme_md5sums") print "repo root path: " + cls.repo_root_path print "repo root cksums file: " + cls.repo_root_cksums_file @classmethod def tearDownClass(cls): super(TestUVSCli, cls).tearDownClass() print "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> tearDownClass() called" #cls.remove_test_repo() @classmethod def remove_test_repo(cls): """ Delete all files set up for test repo. """ print "remove_test_repo() called, deleting everything that was set up for test repo" try: shutil.rmtree(cls.repo_root_path) except: print "could not delete repo root path, skipping." try: os.remove(cls.repo_root_cksums_file) except: print "could not delete repo root cksum file, skipping." @classmethod def empty_test_repo(cls): """ Clear the test repo, that is delete the checked out copy, but not delete the uvs internal files. """ print "empty_test_repo() called, emptying the checked out files at test repo, but not uvs internals." # delete everything at repo_root_path except uvs internal files. repo_root_members = os.listdir(cls.repo_root_path) paths_to_remove = [] dont_remove = set() dont_remove.add(sdef.TEMP_DIR_NAME) dont_remove.add(sdef.SHADOW_FOLDER_NAME) dont_remove.add(sdef.SHADOW_DB_FILE_NAME) for repo_root_member in repo_root_members: if repo_root_member not in dont_remove: paths_to_remove.append(os.path.join(cls.repo_root_path, repo_root_member)) for path in paths_to_remove: if os.path.isdir(path): shutil.rmtree(path) elif os.path.isfile(path): os.remove(path) # setUp will run once before every test case def setUp(self): pass # tearDown will run once after every test case def tearDown(self): pass def test_cli_init_twice_wont_overwrite(self): # delete previous test repo if it existed. self.remove_test_repo() if not os.path.exists(self.repo_root_path): os.makedirs(self.repo_root_path) test_pass = '123' init_cmd = ['uvs', 'init'] p = subprocess.Popen(init_cmd, stdin=subprocess.PIPE, cwd=self.repo_root_path) p.stdin.write(test_pass) p.stdin.close() # wait for process to terminate, note that wait is not safe to call # if we had set stdout or stderr to PIPE as well as stdin. exit_code = p.wait() print "$ " + str(init_cmd[0]) + " " + str(init_cmd[1]) + "\nexit code: " + str(exit_code) self.assertEquals(exit_code, 0) # -------------------------------------------------------------------------- init again check exit code. p = subprocess.Popen(init_cmd, stdin=subprocess.PIPE, cwd=self.repo_root_path) p.stdin.write(test_pass) p.stdin.close() # wait for process to terminate, note that wait is not safe to call # if we had set stdout or stderr to PIPE as well as stdin. exit_code = p.wait() result = "# doing it 2nd time. it should not be allowed. expect non-zero exit code.\n$ " + str(init_cmd[0]) result += " " + str(init_cmd[1]) + "\nexit code: " + str(exit_code) print result self.assertNotEquals(exit_code, 0) def test_cli_init_then_make_one_commit_then_recover(self): # delete previous test repo if it existed. self.remove_test_repo() # this should a folder called ignoreme resident on the same location where this file (test_uvscli.py) resides print "creating test uvs repo at: " + self.repo_root_path if not os.path.exists(self.repo_root_path): os.makedirs(self.repo_root_path) # make and populate the repo root ith some random dirs and files to # be treated as a test uvs repository. tu.populate_directory_with_random_files_and_subdirs(dirpath=self.repo_root_path) # now save md5 of what we created. cmd = "find " + self.repo_root_path cmd += " -type f -print0 | xargs -0 md5sum > " + self.repo_root_cksums_file subprocess.call(cmd, shell=True) # ---------------------------------------------------------------------------- Repo ready to go test_pass = '123' init_cmd = ['uvs', 'init'] # p = subprocess.Popen('cat', stdin=subprocess.PIPE, stdout=subprocess.PIPE) #p = subprocess.Popen(['uvs', 'init'], stdin=subprocess.PIPE, shell=True) p = subprocess.Popen(init_cmd, stdin=subprocess.PIPE, cwd=self.repo_root_path) p.stdin.write(test_pass) p.stdin.close() # wait for process to terminate, note that wait is not safe to call if we had set stdout or stderr to PIPE # as well as stdin. exit_code = p.wait() print "$ " + str(init_cmd[0]) + " " + str(init_cmd[1]) + "\nexit code: " + str(exit_code) self.assertEquals(exit_code, 0) # TODO delete the files and check them back out again then verify using md5 def _disabled_test_init_then_make_one_commit_then_recover(self): test_pass = "123" # ---------------- init uvs repo on self.repo_root_path uvsmanager.init_new_uvs_repo_overwrite(repo_pass=test_pass, repo_root_path=self.repo_root_path) # ---------------- make a commit uvsmgr = uvsmanager.UVSManager(repo_pass=test_pass, repo_root_path=self.repo_root_path) snapid = uvsmgr.take_snapshot(snapshot_msg='test commit', author_name="n/a", author_email="n/a") # ---------------- delete the checked out copy. self.empty_test_repo() # ---------------- now checkout last commit uvsmgr.checkout_reference_at_repo_root(snapshot_ref=snapid, clear_dest=True) # ---------------- now check to see if we recovered correctly. check_cmd = "md5sum -c " + self.repo_root_cksums_file # if exit code is non-zero (md5 failed) check output should raise error. # subprocess.check_output(check_cmd, shell=True) # call will return the exit code. blackhole = open(os.devnull, 'wb') check_cmd_exit_code = subprocess.call(check_cmd, stdout=blackhole, stderr=blackhole, shell=True) self.assertEquals(check_cmd_exit_code, 0) if __name__ == '__main__': unittest.main()
31.549587
117
0.62816
1,043
7,635
4.392138
0.237776
0.068107
0.062868
0.045405
0.370443
0.320017
0.296878
0.282471
0.25191
0.245143
0
0.004855
0.244663
7,635
242
118
31.549587
0.789492
0.247544
0
0.324324
0
0.009009
0.138694
0.01655
0
0
0
0.004132
0.036036
0
null
null
0.09009
0.081081
null
null
0.126126
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
a5011c8dc68549aa930d5e1f66b7f91d841322f1
388
py
Python
segundos.py
rafabentoss/courses
ced3f5447dea38220b904678c601ed2bf7f2b0f1
[ "CC0-1.0" ]
null
null
null
segundos.py
rafabentoss/courses
ced3f5447dea38220b904678c601ed2bf7f2b0f1
[ "CC0-1.0" ]
null
null
null
segundos.py
rafabentoss/courses
ced3f5447dea38220b904678c601ed2bf7f2b0f1
[ "CC0-1.0" ]
null
null
null
segundos_str = int(input("Por favor, entre com o número de segundos que deseja converter:")) dias=segundos_str//86400 segs_restantes1=segundos_str%86400 horas=segs_restantes1//3600 segs_restantes2=segs_restantes1%3600 minutos=segs_restantes2//60 segs_restantes_final=segs_restantes2%60 print(dias,"dias,",horas, "horas,",minutos, "minutos e", segs_restantes_final, "segundos.")
38.8
93
0.796392
55
388
5.381818
0.490909
0.111486
0.108108
0
0
0
0
0
0
0
0
0.07932
0.090206
388
10
94
38.8
0.759207
0
0
0
0
0
0.242105
0
0
0
0
0
0
1
0
false
0
0
0
0
0.125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
a50155ac15b87a1b73c7f2ca4058bdf66488534d
1,323
py
Python
examples/cheb/example_dft.py
Hadrien-Montanelli/chebpy
c22f1f13b42b3c80f2e34be6e7136ef2d0277971
[ "MIT" ]
1
2020-12-02T10:17:26.000Z
2020-12-02T10:17:26.000Z
examples/cheb/example_dft.py
Hadrien-Montanelli/chebpy
c22f1f13b42b3c80f2e34be6e7136ef2d0277971
[ "MIT" ]
null
null
null
examples/cheb/example_dft.py
Hadrien-Montanelli/chebpy
c22f1f13b42b3c80f2e34be6e7136ef2d0277971
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 15:37:10 2020 Copyright 2020 by Hadrien Montanelli. """ # %% Imports. # Standard library imports: import numpy as np # Chebpy imports: from chebpy.cheb import chebpts, coeffs2vals, vals2coeffs # %% Transforms (1D) on [-1,1]. f = lambda x: np.exp(-10*x**2) n = 100 x = chebpts(n) error = coeffs2vals(vals2coeffs(f(x))) - f(x) print(f'Error (1D): {np.max(np.abs(error)):.2e}') # %% Transforms (1D) on [0,2]. f = lambda x: np.exp(-10*x**2) n = 100 x = chebpts(n, [0, 2]) error = coeffs2vals(vals2coeffs(f(x))) - f(x) print(f'Error (1D): {np.max(np.abs(error)):.2e}') # %% Transforms (2D) on [-1,1]x[-1,1]. f = lambda x, y: np.exp(-10*(x**2 + y**2)) n = 100 x = chebpts(n) y = chebpts(n) X, Y = np.meshgrid(x, y) values = f(X, Y) coeffs = vals2coeffs(vals2coeffs(values).T).T values2 = coeffs2vals(coeffs2vals(coeffs).T).T error = values2 - values print(f'Error (2D): {np.max(np.abs(error)):.2e}') # %% Transforms (2D) on [0,2]x[-1,0]. f = lambda x, y: np.exp(-10*(x**2 + y**2)) n = 100 x = chebpts(n, [0, 2]) y = chebpts(n, [-1, 0]) X, Y = np.meshgrid(x, y) values = f(X, Y) coeffs = vals2coeffs(vals2coeffs(values).T).T values2 = coeffs2vals(coeffs2vals(coeffs).T).T error = values2 - values print(f'Error (2D): {np.max(np.abs(error)):.2e}')
23.625
57
0.619803
238
1,323
3.445378
0.231092
0.019512
0.039024
0.039024
0.709756
0.704878
0.704878
0.704878
0.7
0.678049
0
0.081033
0.151172
1,323
56
58
23.625
0.649154
0.229781
0
0.875
0
0
0.155378
0.10757
0
0
0
0
0
1
0
false
0
0.0625
0
0.0625
0.125
0
0
0
null
0
0
0
0
1
1
1
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
5
a501d89e850c922d43a99061a0daa6321c93954a
870
py
Python
src/balloons.py
cloudzfy/pychallenge
1af98a632021532e136721d282b0e7c2cbc519a3
[ "MIT" ]
3
2016-07-23T03:31:46.000Z
2019-08-22T01:23:07.000Z
src/balloons.py
cloudzfy/pychallenge
1af98a632021532e136721d282b0e7c2cbc519a3
[ "MIT" ]
null
null
null
src/balloons.py
cloudzfy/pychallenge
1af98a632021532e136721d282b0e7c2cbc519a3
[ "MIT" ]
3
2017-05-22T09:41:20.000Z
2018-09-06T02:05:19.000Z
import urllib import StringIO import gzip from difflib import Differ from binascii import unhexlify import Image src = urllib.urlopen('http://huge:file@www.pythonchallenge.com/pc/return/deltas.gz').read() file = gzip.GzipFile(fileobj=StringIO.StringIO(src)) left = [] right = [] for line in file.readlines(): left.append(line[0:53]) right.append(line[56:109]) file.close() d = Differ() result = list(d.compare(left, right)) pic1 = '' pic2 = '' pic3 = '' for line in result: if line[0] == ' ': pic1 += line[1:].replace(' ', '').replace('\n', '') elif line[0] == '+': pic2 += line[1:].replace(' ', '').replace('\n', '') elif line[0] == '-': pic3 += line[1:].replace(' ', '').replace('\n', '') Image.open(StringIO.StringIO(unhexlify(pic1))).show() Image.open(StringIO.StringIO(unhexlify(pic2))).show() Image.open(StringIO.StringIO(unhexlify(pic3))).show()
24.166667
91
0.654023
119
870
4.781513
0.428571
0.112478
0.063269
0.100176
0.330404
0.235501
0.101933
0.101933
0
0
0
0.030105
0.121839
870
35
92
24.857143
0.71466
0
0
0
0
0
0.082759
0
0
0
0
0
0
1
0
false
0
0.206897
0
0.206897
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0