hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
39bfed4c3b2ea966740de31f26fe83daafbdbab5
171
py
Python
setup.py
andribas404/splay_benchmark
1ba2fe4d715b25db806c0b241c6adadd8d442a77
[ "MIT" ]
null
null
null
setup.py
andribas404/splay_benchmark
1ba2fe4d715b25db806c0b241c6adadd8d442a77
[ "MIT" ]
null
null
null
setup.py
andribas404/splay_benchmark
1ba2fe4d715b25db806c0b241c6adadd8d442a77
[ "MIT" ]
null
null
null
""" Setup. python setup.py build_ext --inplace """ from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize('splay_tree.pyx'))
13.153846
46
0.760234
39c13236092aa20981aa814b36bf7e898a69daef
343
py
Python
app.py
victorathanasio/KPI-test
cbc24ebc9b6e9304c7ff0428458c827d09bd99aa
[ "MIT" ]
null
null
null
app.py
victorathanasio/KPI-test
cbc24ebc9b6e9304c7ff0428458c827d09bd99aa
[ "MIT" ]
null
null
null
app.py
victorathanasio/KPI-test
cbc24ebc9b6e9304c7ff0428458c827d09bd99aa
[ "MIT" ]
null
null
null
from WebApp.mainapp import app import dash_html_components as html import flask from REST_API.rest_api import API from WebApp.Layout import Layout app.layout = Layout() app.server.register_blueprint(API) server = app.server if __name__ == '__main__': # app.run_server(debug=False, host='0.0.0.0', port=90) app.run_server(debug=True)
24.5
58
0.766764
39c16bfed4316959a8bb44396e89b0248bfc5ee5
719
py
Python
URI/multiplicador.py
LuccasTraumer/pythonRepositorio
52d4455cea0615c8eba7ab4c6224ce3350bbcf47
[ "MIT" ]
null
null
null
URI/multiplicador.py
LuccasTraumer/pythonRepositorio
52d4455cea0615c8eba7ab4c6224ce3350bbcf47
[ "MIT" ]
null
null
null
URI/multiplicador.py
LuccasTraumer/pythonRepositorio
52d4455cea0615c8eba7ab4c6224ce3350bbcf47
[ "MIT" ]
null
null
null
''' Leia 2 valores inteiros (A e B). Aps, o programa deve mostrar uma mensagem "Sao Multiplos" ou "Nao sao Multiplos", indicando se os valores lidos so mltiplos entre si. ''' data = str(input()) values = data.split(' ') first_value = int(values[0]) second_value = int(values[1]) if(second_value > first_value): resul = second_value / first_value if(first_value * resul == second_value and second_value % first_value == 0): print('Sao Multiplos') else: print('Nao sao Multiplos') else: result = first_value / second_value if(second_value * result == first_value and first_value % second_value == 0): print('Sao Multiplos') else: print('Nao sao Multiplos')
27.653846
94
0.673157
39c247e8b1fdf8e3efae1a8994e7cba05bbc1477
2,767
py
Python
app/listeners.py
seratch/slack_learning_app_ja
9552489b1d5d3adc61a7c73645a1ae09abc9d933
[ "MIT" ]
11
2020-10-28T08:04:16.000Z
2022-03-18T09:12:29.000Z
app/listeners.py
seratch/slack_learning_app_ja
9552489b1d5d3adc61a7c73645a1ae09abc9d933
[ "MIT" ]
1
2020-10-29T23:10:52.000Z
2020-10-29T23:37:00.000Z
app/listeners.py
seratch/slack_learning_app_ja
9552489b1d5d3adc61a7c73645a1ae09abc9d933
[ "MIT" ]
null
null
null
import re from slack_bolt import App from app.onboarding import ( message_multi_users_select, message_multi_users_select_lazy, ) from app.tutorials import ( tutorial_page_transition, tutorial_page_transition_lazy, app_home_opened, app_home_opened_lazy, page1_home_tab_button_click, page1_home_tab_button_click_lazy, page1_home_tab_users_select_lazy, page1_home_tab_users_select, page2_modal, page2_modal_lazy, page2_modal_submission, page4_create_channel, page4_create_channel_lazy, page4_create_channel_submission, page4_create_channel_submission_lazy, page4_create_channel_setup, page4_create_channel_setup_lazy, global_shortcut_handler, global_shortcut_view_submission, global_shortcut_view_submission_lazy, message_shortcut_handler, message_shortcut_handler_lazy, external_data_source_handler, )
30.744444
88
0.734731
39c310b2a22377850644e8e3e7bb4274bb90e2dd
1,213
py
Python
project2/redactor.py
m-harikiran/cs5293sp21-project2
48547543001813aee17731399f617f82043e4a8f
[ "MIT" ]
null
null
null
project2/redactor.py
m-harikiran/cs5293sp21-project2
48547543001813aee17731399f617f82043e4a8f
[ "MIT" ]
null
null
null
project2/redactor.py
m-harikiran/cs5293sp21-project2
48547543001813aee17731399f617f82043e4a8f
[ "MIT" ]
null
null
null
import nltk import re from nltk.corpus import wordnet # This method reads the file and redacts names in it and writes redacted data to file with extension python3.redacted
32.783784
117
0.660346
39c3360de5ed5436c13f0b5c11ff3ff8f4c1e5e8
935
py
Python
python3/max_area_of_island.py
joshiaj7/CodingChallenges
f95dd79132f07c296e074d675819031912f6a943
[ "MIT" ]
1
2020-10-08T09:17:40.000Z
2020-10-08T09:17:40.000Z
python3/max_area_of_island.py
joshiaj7/CodingChallenges
f95dd79132f07c296e074d675819031912f6a943
[ "MIT" ]
null
null
null
python3/max_area_of_island.py
joshiaj7/CodingChallenges
f95dd79132f07c296e074d675819031912f6a943
[ "MIT" ]
null
null
null
# Space : O(n) # Time : O(m*n)
25.972222
61
0.37754
39c42e302788d37384d6aba69dfd98df2d11d258
1,000
py
Python
datasets/linear/parking/lr.py
diego1q2w/lregret
823c7f609559d1012ed52f619b1aa1297d5f2517
[ "Apache-2.0" ]
null
null
null
datasets/linear/parking/lr.py
diego1q2w/lregret
823c7f609559d1012ed52f619b1aa1297d5f2517
[ "Apache-2.0" ]
null
null
null
datasets/linear/parking/lr.py
diego1q2w/lregret
823c7f609559d1012ed52f619b1aa1297d5f2517
[ "Apache-2.0" ]
null
null
null
import os from datetime import datetime import time import pandas as pd from datasets.linear import LinearProblem from regresion.linear.feature import PolFeatures from regresion.linear.linear import LinearRegression # lr = LinearRegression() # p = ParkingProblem(lr) # p.fit_solving()
29.411765
100
0.678
39c714143377ff9b1982f6d7182df1f2ee8d4c39
244
py
Python
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_max_length_1_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_max_length_1_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/name/schema_instance/nistschema_sv_iv_atomic_name_max_length_1_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.atomic.name.schema_instance.nistschema_sv_iv_atomic_name_max_length_1_xsd.nistschema_sv_iv_atomic_name_max_length_1 import NistschemaSvIvAtomicNameMaxLength1 __all__ = [ "NistschemaSvIvAtomicNameMaxLength1", ]
40.666667
186
0.889344
39c80db6883ae8bab680917b15a4a104eed100d2
4,888
py
Python
vl/h5/mg_genome/norm_h5.py
hurwitzlab/viral-learning
8d7aebc0d58fa32a429f4a47593452ee2722ba82
[ "MIT" ]
1
2018-02-23T16:49:30.000Z
2018-02-23T16:49:30.000Z
vl/h5/mg_genome/norm_h5.py
hurwitzlab/viral-learning
8d7aebc0d58fa32a429f4a47593452ee2722ba82
[ "MIT" ]
null
null
null
vl/h5/mg_genome/norm_h5.py
hurwitzlab/viral-learning
8d7aebc0d58fa32a429f4a47593452ee2722ba82
[ "MIT" ]
null
null
null
""" 1. Normalizing the entire dataset with mean and variance, shuffle, compression=9 runs for more than 8 hours on ocelote and results in a file of more than 150GB. 2. Try normalizing with only variance and without shuffle. """ import os.path import sys import time import h5py import numpy as np def calculate_mean_variance(dsets): """ Given a list of datasets calculate the mean and variance for all rows in all datasets. Arguments: dsets: sequence of datasets with matching column counts Returns: (mean, variance): tuple of mean vector and variance vector """ print('calculating mean and variance for "{}"'.format([dset.name for dset in dsets])) t0 = time.time() mean = np.zeros((1, dsets[0].shape[1])) M2 = np.zeros((1, dsets[0].shape[1])) count = 0 for dset in dsets: # find the right subset size to load without running out of memory # if dset has more than 10,000 rows use 10,000 # if dset has fewer than 10,000 rows load the whole dset dsubset = np.zeros((min(10000, dset.shape[0]), dset.shape[1])) print(' working on "{}"'.format(dset.name)) for n in range(0, dset.shape[0], dsubset.shape[0]): m = min(n + dsubset.shape[0], dset.shape[0]) dset.read_direct(dsubset, source_sel=np.s_[n:m, :]) t00 = time.time() for i in range(0, dsubset.shape[0]): count = count + 1 delta = dsubset[i, :] - mean mean += delta / count delta2 = dsubset[i, :] - mean M2 += delta * delta2 print(' processed slice [{}:{}] {:5.2f}s'.format(n, m, time.time()-t00)) print(' finished mean and variance in {:5.2f}s'.format(time.time()-t0)) # return mean, variance return (mean, M2/(count - 1)) if __name__ == '__main__': main()
35.678832
110
0.557897
39c9516fadde5be713c7c8c8f3a12e5d1178fce7
780
py
Python
app/controller/api/fields/comment.py
Arianxx/LoniceraBlog
1f13d336f42c7041b16293dc8f1af62cc98ce2f4
[ "MIT" ]
8
2018-09-08T04:41:01.000Z
2018-09-08T13:15:59.000Z
app/controller/api/fields/comment.py
Arianxx/LoniceraBlog
1f13d336f42c7041b16293dc8f1af62cc98ce2f4
[ "MIT" ]
null
null
null
app/controller/api/fields/comment.py
Arianxx/LoniceraBlog
1f13d336f42c7041b16293dc8f1af62cc98ce2f4
[ "MIT" ]
6
2018-09-08T08:51:50.000Z
2018-09-11T00:29:20.000Z
from flask_restful import fields from .custom import Num, EdgeUrl, PaginateUrl getCommentField = { "id": fields.Integer, "time": fields.DateTime(attribute="timestamp"), "author_name": fields.String(attribute="username"), "article_id": fields.Integer(attribute="postid"), "body": fields.String, "urls": { "arthor": fields.Url("api.user", absolute=True), "post": fields.Url("api.post", absolute=True), }, } getPostCommentsField = { "prev": EdgeUrl("api.post_comments", 0), "next": EdgeUrl("api.post_comments", 1), "all_comments": fields.Integer(attribute="total"), "all_pages": fields.Integer(attribute="pages"), "urls": fields.List( PaginateUrl("api.comment", "commentid", "id"), attribute="items" ), }
31.2
72
0.65
39cc957ec5fbf6dc9322a11520c340004afd7af2
1,132
py
Python
faq/templatetags/faq_tags.py
HerbyDE/jagdreisencheck-webapp
9af5deda2423b787da88a0c893f3c474d8e4f73f
[ "BSD-3-Clause" ]
null
null
null
faq/templatetags/faq_tags.py
HerbyDE/jagdreisencheck-webapp
9af5deda2423b787da88a0c893f3c474d8e4f73f
[ "BSD-3-Clause" ]
null
null
null
faq/templatetags/faq_tags.py
HerbyDE/jagdreisencheck-webapp
9af5deda2423b787da88a0c893f3c474d8e4f73f
[ "BSD-3-Clause" ]
null
null
null
from django import template from faq.forms import FaqInstanceForm, FaqAnswerForm from faq.models import FaqInstance, FaqAnswer register = template.Library()
28.3
104
0.754417
39cd092c9896194e7d5884416a86b0b247f8dee4
486
py
Python
markflow/detectors/__init__.py
jmholla/markflow
1accc4a23f9c06d9ab77d6c180c586da3d9ec69b
[ "Apache-2.0" ]
14
2020-08-14T03:09:53.000Z
2022-03-22T22:46:50.000Z
markflow/detectors/__init__.py
jmholla/markflow
1accc4a23f9c06d9ab77d6c180c586da3d9ec69b
[ "Apache-2.0" ]
6
2020-08-19T18:13:24.000Z
2021-02-11T03:56:34.000Z
markflow/detectors/__init__.py
jmholla/markflow
1accc4a23f9c06d9ab77d6c180c586da3d9ec69b
[ "Apache-2.0" ]
3
2020-08-13T16:40:13.000Z
2022-01-18T12:31:37.000Z
# flake8: noqa """ MarkFlow MarkDown Section Detection Library This library provide this functions MarkFlow uses to split a document into it's individual text types. """ from .atx_heading import * from .blank_line import * from .block_quote import * from .fenced_code_block import * from .indented_code_block import * from .link_reference_definition import * from .list import * from .paragraph import * from .setext_heading import * from .table import * from .thematic_break import *
25.578947
79
0.788066
39cd57d3e96930bf2512f61084f0ec5dbd909936
2,129
py
Python
django_project/apps/qfauth/forms.py
gaohj/nzflask_bbs
36a94c380b78241ed5d1e07edab9618c3e8d477b
[ "Apache-2.0" ]
null
null
null
django_project/apps/qfauth/forms.py
gaohj/nzflask_bbs
36a94c380b78241ed5d1e07edab9618c3e8d477b
[ "Apache-2.0" ]
27
2020-02-12T07:55:58.000Z
2022-03-12T00:19:09.000Z
django_project/apps/qfauth/forms.py
gaohj/nzflask_bbs
36a94c380b78241ed5d1e07edab9618c3e8d477b
[ "Apache-2.0" ]
2
2020-02-18T01:54:55.000Z
2020-02-21T11:36:28.000Z
from django import forms from apps.forms import FormMixin from django.core import validators from .models import User from django.core.cache import cache
43.44898
136
0.716768
39cf488b67a5b1e7312e55ca067c9bf0bfbe9c6e
156
py
Python
receives/pytest.py
felixsch/receives
0d149e3a24c0377ac60d502736299c9f4348244a
[ "MIT" ]
null
null
null
receives/pytest.py
felixsch/receives
0d149e3a24c0377ac60d502736299c9f4348244a
[ "MIT" ]
null
null
null
receives/pytest.py
felixsch/receives
0d149e3a24c0377ac60d502736299c9f4348244a
[ "MIT" ]
null
null
null
import pytest from receives.receiver import Receiver
14.181818
38
0.730769
39cfddaaca78d75a0a19c8026c9b58cbdca9cec8
18,099
py
Python
contracts/crawler.py
waldyrious/public-contracts
3107ddc007f3574ce19aaa2223399484bc6b1382
[ "BSD-3-Clause" ]
25
2015-03-05T00:15:11.000Z
2021-04-04T18:50:43.000Z
contracts/crawler.py
waldyrious/public-contracts
3107ddc007f3574ce19aaa2223399484bc6b1382
[ "BSD-3-Clause" ]
36
2015-03-21T17:04:54.000Z
2017-07-06T10:35:51.000Z
contracts/crawler.py
waldyrious/public-contracts
3107ddc007f3574ce19aaa2223399484bc6b1382
[ "BSD-3-Clause" ]
7
2015-03-24T16:18:02.000Z
2019-05-29T11:51:01.000Z
import json import logging from django.core.exceptions import ValidationError from django.db import transaction from django.forms import DateField, CharField import requests import requests.exceptions from . import models from contracts.crawler_forms import EntityForm, ContractForm, \ TenderForm, clean_place, PriceField logger = logging.getLogger(__name__)
35.627953
82
0.560749
39d2a63c210e03ad35c58e5b3b5e1afaa5b2db56
36,251
py
Python
com/precisely/apis/model/validate_mailing_address_uscanapi_options.py
PreciselyData/PreciselyAPIsSDK-Python
28ffff0c96d81d3a53a5599c987d54d7b632b508
[ "Apache-2.0" ]
null
null
null
com/precisely/apis/model/validate_mailing_address_uscanapi_options.py
PreciselyData/PreciselyAPIsSDK-Python
28ffff0c96d81d3a53a5599c987d54d7b632b508
[ "Apache-2.0" ]
null
null
null
com/precisely/apis/model/validate_mailing_address_uscanapi_options.py
PreciselyData/PreciselyAPIsSDK-Python
28ffff0c96d81d3a53a5599c987d54d7b632b508
[ "Apache-2.0" ]
null
null
null
""" Precisely APIs Enhance & enrich your data, applications, business processes, and workflows with rich location, information, and identify APIs. # noqa: E501 The version of the OpenAPI document: 11.9.3 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from com.precisely.apis.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from com.precisely.apis.exceptions import ApiAttributeError
83.914352
290
0.670354
39d42321cd5a87223e9348e07673ab77d3799ca1
105
py
Python
serverless/aws/features/__init__.py
captain-fox/serverless-builder
d79d120578d692dd34dd2f0a3bb75cc8ec719c81
[ "MIT" ]
3
2022-03-16T14:25:03.000Z
2022-03-24T15:04:55.000Z
serverless/aws/features/__init__.py
captain-fox/serverless-builder
d79d120578d692dd34dd2f0a3bb75cc8ec719c81
[ "MIT" ]
3
2022-01-24T20:11:15.000Z
2022-01-26T19:33:20.000Z
serverless/aws/features/__init__.py
epsyhealth/serverless-builder
6a1f943b5cabc4c4748234b1623a9ced6464043a
[ "MIT" ]
1
2022-02-15T13:54:29.000Z
2022-02-15T13:54:29.000Z
from .api_handler import DefaultFourHundredResponse from .api_keys import ApiKeys from .xray import XRay
26.25
51
0.857143
39d50b087b533ec75540f6aeefa21a97dbda7cfa
7,392
py
Python
tests/unit/test_resources.py
butla/PyDAS
39df5abbe9563b58da7caaa191b89852fb122ab7
[ "MIT" ]
13
2016-06-29T13:35:05.000Z
2021-05-25T09:47:31.000Z
tests/unit/test_resources.py
butla/PyDAS
39df5abbe9563b58da7caaa191b89852fb122ab7
[ "MIT" ]
1
2016-07-11T23:11:33.000Z
2016-07-11T23:11:33.000Z
tests/unit/test_resources.py
butla/PyDAS
39df5abbe9563b58da7caaa191b89852fb122ab7
[ "MIT" ]
3
2017-10-17T15:54:25.000Z
2022-03-24T01:11:37.000Z
import copy import json import os from unittest.mock import MagicMock, call from bravado.client import SwaggerClient import bravado.exception from bravado_falcon import FalconHttpClient import falcon import pytest import pytest_falcon.plugin import responses import yaml from data_acquisition.acquisition_request import AcquisitionRequest, RequestNotFoundError from data_acquisition.consts import (ACQUISITION_PATH, DOWNLOAD_CALLBACK_PATH, METADATA_PARSER_CALLBACK_PATH, GET_REQUEST_PATH) from data_acquisition.resources import (get_download_callback_url, get_metadata_callback_url, AcquisitionResource) import tests from tests.consts import (TEST_DOWNLOAD_REQUEST, TEST_DOWNLOAD_CALLBACK, TEST_ACQUISITION_REQ, TEST_ACQUISITION_REQ_JSON) FAKE_TIME = 234.25 FAKE_TIMESTAMP = 234 def test_get_download_callback_url(): callback_url = get_download_callback_url('https://some-test-das-url', 'some-test-id') assert callback_url == 'https://some-test-das-url/v1/das/callback/downloader/some-test-id' def test_get_metadata_callback_url(): callback_url = get_metadata_callback_url('https://some-test-das-url', 'some-test-id') assert callback_url == 'https://some-test-das-url/v1/das/callback/metadata/some-test-id'
38.103093
97
0.759199
39d5975250cb33441f80fb188d15a624f07f6415
4,216
py
Python
GraphOfDocs.py
NC0DER/GraphOfDocs
16603de9d8695ae8205117aa7123707d1dcbe0e0
[ "Apache-2.0" ]
12
2020-01-27T20:26:08.000Z
2022-03-10T14:45:09.000Z
GraphOfDocs.py
NC0DER/GraphOfDocs
16603de9d8695ae8205117aa7123707d1dcbe0e0
[ "Apache-2.0" ]
1
2021-11-17T11:45:55.000Z
2021-11-17T11:45:55.000Z
GraphOfDocs.py
NC0DER/GraphOfDocs
16603de9d8695ae8205117aa7123707d1dcbe0e0
[ "Apache-2.0" ]
2
2020-01-27T13:17:11.000Z
2020-01-29T09:35:22.000Z
import sys import platform from neo4j import ServiceUnavailable from GraphOfDocs.neo4j_wrapper import Neo4jDatabase from GraphOfDocs.utils import generate_words, read_dataset, clear_screen from GraphOfDocs.parse_args import parser from GraphOfDocs.create import * if __name__ == '__main__': # If only one argument is specified, # Then it's the script name. # Print help for using the script and exit. if len(sys.argv) == 1: parser.print_help() parser.exit() # Parse all arguments from terminal. args = parser.parse_args() # If create flag is set but no dirpath is specified, print error. if args.create and args.dirpath is None: parser.error('Please set the dirpath flag and specify a valid filepath!') # Else if create flag is specified along with a valid dirpath. elif args.create: print(args) # Run the graphofdocs function with create and initialize set to True. # The first argument (0th index) after the dirpath flag is the actual directory path. graphofdocs(True, True, args.dirpath[0], args.window_size[0], args.extend_window, args.insert_stopwords, args.lemmatize, args.stem) # Else if reinitialize flag is specified, unset the create flag. elif args.reinitialize: print(args) # Run the graphofdocs function with create set to False and initialize set to True. # We also set the directory path to None, since its not needed. graphofdocs(False, True, None, args.window_size[0], args.extend_window, args.insert_stopwords, args.lemmatize, args.stem)
43.916667
95
0.64777
39d61db6e252ece16991b4c554bc384accb4d908
27,144
py
Python
line/f_MessageService.py
winbotscript/LineService
4c79029648e858e567378485e75276f865c1f73f
[ "Apache-2.0" ]
1
2020-08-20T08:00:23.000Z
2020-08-20T08:00:23.000Z
line/f_MessageService.py
winbotscript/LineService
4c79029648e858e567378485e75276f865c1f73f
[ "Apache-2.0" ]
null
null
null
line/f_MessageService.py
winbotscript/LineService
4c79029648e858e567378485e75276f865c1f73f
[ "Apache-2.0" ]
null
null
null
# # Autogenerated by Frugal Compiler (3.4.3) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # from threading import Lock from frugal.middleware import Method from frugal.exceptions import TApplicationExceptionType from frugal.exceptions import TTransportExceptionType from frugal.processor import FBaseProcessor from frugal.processor import FProcessorFunction from frugal.util.deprecate import deprecated from frugal.util import make_hashable from thrift.Thrift import TApplicationException from thrift.Thrift import TMessageType from thrift.transport.TTransport import TTransportException from .ttypes import * def _write_application_exception(ctx, oprot, method, ex_code=None, message=None, exception=None): if exception is not None: x = exception else: x = TApplicationException(type=ex_code, message=message) oprot.write_response_headers(ctx) oprot.writeMessageBegin(method, TMessageType.EXCEPTION, 0) x.write(oprot) oprot.writeMessageEnd() oprot.get_transport().flush() return x
35.57536
171
0.597222
39d6297dad17364278641be6d1ed6ea276348300
886
py
Python
Medium/279. Perfect Squares/solution (2).py
czs108/LeetCode-Solutions
889f5b6a573769ad077a6283c058ed925d52c9ec
[ "MIT" ]
3
2020-05-09T12:55:09.000Z
2022-03-11T18:56:05.000Z
Medium/279. Perfect Squares/solution (2).py
czs108/LeetCode-Solutions
889f5b6a573769ad077a6283c058ed925d52c9ec
[ "MIT" ]
null
null
null
Medium/279. Perfect Squares/solution (2).py
czs108/LeetCode-Solutions
889f5b6a573769ad077a6283c058ed925d52c9ec
[ "MIT" ]
1
2022-03-11T18:56:16.000Z
2022-03-11T18:56:16.000Z
# 279. Perfect Squares # Runtime: 60 ms, faster than 96.81% of Python3 online submissions for Perfect Squares. # Memory Usage: 14.7 MB, less than 42.95% of Python3 online submissions for Perfect Squares.
30.551724
97
0.555305
39d67d232e49de41fe6fece39a3376037a1fe5cc
1,650
py
Python
simulator/card_defs.py
NewLordVile/alphasheep
2a86cf0009b686edafee8c80aa961d7075a5bd46
[ "MIT" ]
8
2019-11-25T22:05:58.000Z
2022-01-19T23:48:39.000Z
simulator/card_defs.py
NewLordVile/alphasheep
2a86cf0009b686edafee8c80aa961d7075a5bd46
[ "MIT" ]
5
2019-12-23T12:43:40.000Z
2020-03-19T19:16:46.000Z
simulator/card_defs.py
NewLordVile/alphasheep
2a86cf0009b686edafee8c80aa961d7075a5bd46
[ "MIT" ]
4
2020-03-14T21:25:29.000Z
2022-01-27T22:59:31.000Z
""" Definitions for Card, Suit, Pip, etc. WARN: DO NOT CHANGE THE ENUMS IN THIS FILE! Changing the values might affect the ordering of the state/action space of agents, and will break compatibility with previously saved model checkpoints. """ from enum import IntEnum pip_scores = { Pip.sieben: 0, Pip.acht: 0, Pip.neun: 0, Pip.unter: 2, Pip.ober: 3, Pip.koenig: 4, Pip.zehn: 10, Pip.sau: 11} def new_deck(): """ Returns an ordered deck. """ return [Card(suit, pip) for suit in Suit for pip in Pip]
23.571429
129
0.633333
39d6fc42a60ee57ea74155e98d6216d785fa855c
2,720
py
Python
server/perform_action/common.py
darrenfoong/battleships
2866207b3a55d24fc085beedbd735d489990e487
[ "MIT" ]
11
2020-01-15T14:25:48.000Z
2021-11-25T04:21:18.000Z
server/perform_action/common.py
darrenfoong/battleships
2866207b3a55d24fc085beedbd735d489990e487
[ "MIT" ]
8
2021-02-04T16:41:57.000Z
2022-03-29T21:57:15.000Z
esp8266/common.py
pythings/PythingsOS
276b41a32af7fa0d5395b2bb308e611f784f9711
[ "Apache-2.0" ]
null
null
null
MAX_COPIES = 2 RECV_SIZE = 1024 SEND_SIZE = 1024 SERVER_IP = "172.24.1.107" SERVER_PORT = 10000 # Error Codes CODE_SUCCESS = 300 CODE_FAILURE = 400
28.93617
190
0.683824
39da37adde81c90589b9c7e68358e7bc3b53628e
1,361
py
Python
repeat_samples.py
xiz675/OpenNMT-py
eaee466437d6a2f7c06a2401f9a8ef6c7757cabd
[ "MIT" ]
null
null
null
repeat_samples.py
xiz675/OpenNMT-py
eaee466437d6a2f7c06a2401f9a8ef6c7757cabd
[ "MIT" ]
null
null
null
repeat_samples.py
xiz675/OpenNMT-py
eaee466437d6a2f7c06a2401f9a8ef6c7757cabd
[ "MIT" ]
null
null
null
if __name__ == '__main__': key = "train" base_path = "./data/Twitter/" src_path = base_path + key + "_post.txt" conv_path = base_path + key + "_conv.txt" tag_path = base_path + key + "_tag.txt" srcs = read_file(src_path) convs = read_file(conv_path) tags = read_file(tag_path) new_data = repeat(srcs, convs, tags) write_to_file(base_path + key + "new_post.txt", new_data[0]) write_to_file(base_path + key + "new_conv.txt", new_data[1]) write_to_file(base_path + key + "new_tag.txt", new_data[2])
28.957447
64
0.603968
39daa2204b3c5436de83103da0b269b9aadad179
1,540
py
Python
tests/test_movies.py
dipakgupta12/taste_dive
37df3f67e6efdf961cca230a4b2c8cfe23a38984
[ "MIT" ]
null
null
null
tests/test_movies.py
dipakgupta12/taste_dive
37df3f67e6efdf961cca230a4b2c8cfe23a38984
[ "MIT" ]
null
null
null
tests/test_movies.py
dipakgupta12/taste_dive
37df3f67e6efdf961cca230a4b2c8cfe23a38984
[ "MIT" ]
null
null
null
import mock
42.777778
114
0.701948
39dce94f390b2bc845f4a4548517b2bf61e50466
5,711
py
Python
CiscoWebAuthManager.py
darizotas/ciscowebauth
aaac65b5e78fe3246f0d4dedaf44eea4d8d293cb
[ "BSD-3-Clause" ]
1
2018-01-22T04:43:39.000Z
2018-01-22T04:43:39.000Z
CiscoWebAuthManager.py
darizotas/ciscowebauth
aaac65b5e78fe3246f0d4dedaf44eea4d8d293cb
[ "BSD-3-Clause" ]
null
null
null
CiscoWebAuthManager.py
darizotas/ciscowebauth
aaac65b5e78fe3246f0d4dedaf44eea4d8d293cb
[ "BSD-3-Clause" ]
null
null
null
"""Script that establishes a session in a wireless network managed by Cisco Web Authentication. This script requests for re-establishing a session in a wireless network managed by Cisco Web Authentication. Copyright 2013 Dario B. darizotas at gmail dot com This software is licensed under a new BSD License. Unported License. http://opensource.org/licenses/BSD-3-Clause """ from wlanapi.wlanapiwrapper import * from wlanapi.wlanconninfo import * from webauth.CiscoWebAuth import * import sys import argparse import ssl # Main def login(args): """Wrapper function to use through argparse to login to the wireless network""" manager = CiscoWebAuthManager() if manager.isConnected(args.ssid): if not manager.login(args.host, args.user, args.pwd): sys.exit(1) else: print "Not associated to %s. There is nothing to do." % args.ssid def logout(args): """Wrapper function to use through argparse to logout to the wireless network""" manager = CiscoWebAuthManager() if manager.isConnected(args.ssid): if not manager.logout(args.host): sys.exit(1) else: print "Not associated to %s. There is nothing to do." % args.ssid # Top-level argument parser parser = argparse.ArgumentParser(description='Establishes a session in a wireless network managed ' \ 'by Cisco Web Authentication.') # SSID wireless network param parser.add_argument('ssid', help='SSID name of the wireless network') parser.add_argument('host', help='Cisco Web Authentication hostname or IP') subparser = parser.add_subparsers(title='sub-commands', help='Available sub-commands') # Login sub-command parserCmdLogin = subparser.add_parser('login', help='Login request') parserCmdLogin.add_argument('-u', '--user', required=True, help='User name') parserCmdLogin.add_argument('-p', '--pwd', required=True, help='Password') parserCmdLogin.set_defaults(func=login) # Logout sub-command parserCmdLogout = subparser.add_parser('logout', help='Logout request') parserCmdLogout.set_defaults(func=logout) args = parser.parse_args() args.func(args) sys.exit(0)
34.823171
102
0.615654
39dee2f2383aa49564e67055109a18b1b7a24546
192
py
Python
qr_code/urls.py
mapreri/django-qr-code
4792dcc19f04b0915dc715ba83ae22372aa78ce9
[ "BSD-3-Clause" ]
null
null
null
qr_code/urls.py
mapreri/django-qr-code
4792dcc19f04b0915dc715ba83ae22372aa78ce9
[ "BSD-3-Clause" ]
null
null
null
qr_code/urls.py
mapreri/django-qr-code
4792dcc19f04b0915dc715ba83ae22372aa78ce9
[ "BSD-3-Clause" ]
null
null
null
from django.urls import path from qr_code import views app_name = 'qr_code' urlpatterns = [ path('images/serve-qr-code-image/', views.serve_qr_code_image, name='serve_qr_code_image') ]
19.2
94
0.755208
39df74f7e7ea40de0f014c2a1bd6b468baf99ae0
974
py
Python
matching.py
siweiwang24/marriage
d0f041ef380562885177418944791491949d024e
[ "MIT" ]
null
null
null
matching.py
siweiwang24/marriage
d0f041ef380562885177418944791491949d024e
[ "MIT" ]
null
null
null
matching.py
siweiwang24/marriage
d0f041ef380562885177418944791491949d024e
[ "MIT" ]
null
null
null
""" Stable Marriage Problem solution using Gale-Shapley. Copyright 2020. Siwei Wang. """ # pylint: disable=no-value-for-parameter from typing import Optional from click import command, option, Path from read_validate import get_smp from marriage import compute_smp from write import print_results if __name__ == '__main__': main()
32.466667
69
0.724846
39e0cfb770931442146ef89aab0fb46b52dd6602
7,908
py
Python
chimeric_blacklist.py
regnveig/juicer1.6_compact
21cd24f4c711640584965704f4fa72e5a25b76e3
[ "MIT" ]
null
null
null
chimeric_blacklist.py
regnveig/juicer1.6_compact
21cd24f4c711640584965704f4fa72e5a25b76e3
[ "MIT" ]
null
null
null
chimeric_blacklist.py
regnveig/juicer1.6_compact
21cd24f4c711640584965704f4fa72e5a25b76e3
[ "MIT" ]
null
null
null
import pysam import json import bisect import subprocess Main(InputFileSAM = "/Data/NGS_Data/20211228_NGS_MinjaF_Pool/Results/Human_HiC/K1/splits/8_S73_L003.fastq.gz.filtered.sam", OutputFileTXT = "test_mergednodups.txt.gz", InterPairsTXT = "test_interpairs.txt.gz", MappingQualityFailedSAM = "/dev/null", ChimericAmbiguousFileSAM = "/dev/null", UnmappedSAM = "/dev/null", StatsTXT = "test.stats.txt", RestrictionSiteFile = None, MinMAPQ = 30)
55.300699
386
0.661861
39e1251d560049f22f859dac5fed8e5ec4b4ca80
95
py
Python
solutions/carrots.py
dx-dt/Kattis
62856999ae2ac43dab81f87beeac5bf8979528f5
[ "Unlicense" ]
null
null
null
solutions/carrots.py
dx-dt/Kattis
62856999ae2ac43dab81f87beeac5bf8979528f5
[ "Unlicense" ]
null
null
null
solutions/carrots.py
dx-dt/Kattis
62856999ae2ac43dab81f87beeac5bf8979528f5
[ "Unlicense" ]
null
null
null
# https://open.kattis.com/problems/carrots import sys print sys.stdin.read().split()[1]
15.833333
43
0.684211
39e14dad20bbe0a515df5d2bbdc11d428ec81e56
1,799
py
Python
yacht/data/transforms.py
IusztinPaul/yacht
c68ab7c66bde860bb91534c29e97772ba328adb5
[ "Apache-2.0" ]
5
2021-09-03T10:16:50.000Z
2022-02-28T07:32:43.000Z
yacht/data/transforms.py
IusztinPaul/yacht
c68ab7c66bde860bb91534c29e97772ba328adb5
[ "Apache-2.0" ]
null
null
null
yacht/data/transforms.py
IusztinPaul/yacht
c68ab7c66bde860bb91534c29e97772ba328adb5
[ "Apache-2.0" ]
1
2022-03-05T16:06:46.000Z
2022-03-05T16:06:46.000Z
from abc import ABC, abstractmethod from typing import Any, List, Optional import pandas as pd from yacht.config import Config ####################################################################################################################### transforms_registry = { 'RelativeClosePriceScaling': RelativeClosePriceScaling, 'AverageValueDiff': AverageValueDiff }
27.676923
119
0.625347
39e198255bc72ec3d147506eb38e23671a7f0cb4
4,088
py
Python
bot.py
gilgamezh/registration_desk
98303a6f96be78e0c1898a523db761f6d19866fc
[ "MIT" ]
null
null
null
bot.py
gilgamezh/registration_desk
98303a6f96be78e0c1898a523db761f6d19866fc
[ "MIT" ]
null
null
null
bot.py
gilgamezh/registration_desk
98303a6f96be78e0c1898a523db761f6d19866fc
[ "MIT" ]
null
null
null
import csv import logging import os import discord from discord.ext import commands, tasks from discord.utils import get # logging config logging.basicConfig( filename=".log/reg.log", format="%(asctime)s - %(message)s", level=logging.INFO, datefmt="%d-%b-%y %H:%M:%S", ) # set up channel ids and enviroment variables reg_channel_id = int(os.environ["REG_CHANNEL_ID"]) try: log_channel_id = int(os.environ["LOG_CHANNEL_ID"]) except: log_channel_id = None try: only_respond_reg = int(os.environ["ONLY_RESPOND_REG"]) except: only_respond_reg = False # TODO: seperate customization in conf file event_name = "EuroPython" instruction = f"Welcome to {event_name}! Please use `!register <Full Name>, <Ticket Number>` to register.\nE.g. `!register James Brown, 99999`\nNOTE: please ONLY register for YOURSELF." bot = commands.Bot( command_prefix="!", description=f"Registration Desk for {event_name}", help_command=None, ) bot.run(os.environ["REG_BOT_SECRET"])
34.066667
315
0.613748
39e1a049e695d46df354014950cf2221cf9cdc1c
1,551
py
Python
src/gameServer.py
LesGameDevToolsMagique/GameEditor
06bed29845ded5cca35e57a3dd457dc72c2a2e8e
[ "MIT" ]
null
null
null
src/gameServer.py
LesGameDevToolsMagique/GameEditor
06bed29845ded5cca35e57a3dd457dc72c2a2e8e
[ "MIT" ]
null
null
null
src/gameServer.py
LesGameDevToolsMagique/GameEditor
06bed29845ded5cca35e57a3dd457dc72c2a2e8e
[ "MIT" ]
null
null
null
#!/usr/bin/env python # skeleton from http://kmkeen.com/socketserver/2009-04-03-13-45-57-003.html import socketserver, subprocess, sys from threading import Thread from pprint import pprint import json my_unix_command = ['bc'] HOST = 'localhost' PORT = 12321 with open('storage.json') as data_file: JSONdata = json.load(data_file)['commands'] def __init__(self, server_address, RequestHandlerClass): socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) if __name__ == "__main__": server = SimpleServer((HOST, PORT), SingleTCPHandler) try: server.serve_forever() except KeyboardInterrupt: sys.exit(0)
31.02
78
0.648614
39e3fc7a595793dc10754a5adbe8f528668e75d2
360
py
Python
src/keycloakclient/aio/openid_connect.py
phoebebright/python-keycloak-client
8590fbcdbda8edbe993a01bbff06d9d9be679c5e
[ "MIT" ]
null
null
null
src/keycloakclient/aio/openid_connect.py
phoebebright/python-keycloak-client
8590fbcdbda8edbe993a01bbff06d9d9be679c5e
[ "MIT" ]
null
null
null
src/keycloakclient/aio/openid_connect.py
phoebebright/python-keycloak-client
8590fbcdbda8edbe993a01bbff06d9d9be679c5e
[ "MIT" ]
null
null
null
from keycloakclient.aio.mixins import WellKnownMixin from keycloakclient.openid_connect import ( KeycloakOpenidConnect as SyncKeycloakOpenidConnect, PATH_WELL_KNOWN, ) __all__ = ( 'KeycloakOpenidConnect', )
24
71
0.8
39e4afc96a10bdb1d7dfe165b5b83d57bfbc7c47
9,987
py
Python
multi_script_editor/jedi/evaluate/precedence.py
paulwinex/pw_multiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
[ "MIT" ]
142
2015-03-21T12:56:21.000Z
2022-02-08T04:42:46.000Z
jedi/evaluate/precedence.py
blueyed/jedi
a01e4c6b375795bb8c8ee0d4e86d4c535456f5b4
[ "MIT" ]
18
2015-05-06T21:14:14.000Z
2015-08-29T18:24:43.000Z
jedi/evaluate/precedence.py
blueyed/jedi
a01e4c6b375795bb8c8ee0d4e86d4c535456f5b4
[ "MIT" ]
51
2016-05-07T14:27:42.000Z
2022-02-10T05:55:11.000Z
""" Handles operator precedence. """ from jedi._compatibility import unicode from jedi.parser import representation as pr from jedi import debug from jedi.common import PushBackIterator from jedi.evaluate.compiled import CompiledObject, create, builtin from jedi.evaluate import analysis def create_precedence(expression_list): iterator = PushBackIterator(iter(expression_list)) return _check_operator(iterator) def _syntax_error(element, msg='SyntaxError in precedence'): debug.warning('%s: %s, %s' % (msg, element, element.start_pos)) def _get_number(iterator, priority=PythonGrammar.LOWEST_PRIORITY): el = next(iterator) if isinstance(el, pr.Operator): if el in PythonGrammar.FACTOR: right = _get_number(iterator, PythonGrammar.FACTOR_PRIORITY) elif el in PythonGrammar.NOT_TEST \ and priority >= PythonGrammar.NOT_TEST_PRIORITY: right = _get_number(iterator, PythonGrammar.NOT_TEST_PRIORITY) elif el in PythonGrammar.SLICE \ and priority >= PythonGrammar.SLICE_PRIORITY: iterator.push_back(el) return None else: _syntax_error(el) return _get_number(iterator, priority) return Precedence(None, el, right) elif isinstance(el, pr.tokenize.Token): return _get_number(iterator, priority) else: return el
33.513423
88
0.601382
39e817d468144ef60c9cbbd969d60eec454c7689
1,967
py
Python
search.py
manimaul/mxmcc
923458b759c8daa74dd969e968bc72b17fdffe02
[ "BSD-2-Clause", "BSD-3-Clause" ]
1
2016-08-24T21:30:45.000Z
2016-08-24T21:30:45.000Z
search.py
manimaul/mxmcc
923458b759c8daa74dd969e968bc72b17fdffe02
[ "BSD-2-Clause", "BSD-3-Clause" ]
5
2021-03-18T23:25:15.000Z
2022-03-11T23:44:20.000Z
search.py
manimaul/mxmcc
923458b759c8daa74dd969e968bc72b17fdffe02
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python __author__ = 'Will Kamp' __copyright__ = 'Copyright 2013, Matrix Mariner Inc.' __license__ = 'BSD' __email__ = 'will@mxmariner.com' __status__ = 'Development' # 'Prototype', 'Development', or 'Production' import os # def __walker(self, args, p_dir, p_file): # map_extensions, include_only = args # if include_only is not None: # include_only = set(include_only) # for f in p_file: # if f.upper().endswith(map_extensions) and (include_only is None or f in include_only) and not f.startswith( # "."): # self.file_paths.append(os.path.join(p_dir, f)) if __name__ == '__main__': print("foo")
34.508772
120
0.56482
39ebe1a3f9b6deca1adc431db80e1a994f12644b
5,041
py
Python
fsh_validator/cli.py
glichtner/fsh-validator
c3b16546221c8d43c24bcee426ec7882938305bd
[ "BSD-3-Clause" ]
null
null
null
fsh_validator/cli.py
glichtner/fsh-validator
c3b16546221c8d43c24bcee426ec7882938305bd
[ "BSD-3-Clause" ]
1
2022-03-01T16:06:09.000Z
2022-03-01T16:06:09.000Z
fsh_validator/cli.py
glichtner/fsh-validator
c3b16546221c8d43c24bcee426ec7882938305bd
[ "BSD-3-Clause" ]
null
null
null
"""Command line interface for fsh-validator.""" import os import sys import argparse from pathlib import Path import yaml from .fsh_validator import ( print_box, run_sushi, validate_all_fsh, validate_fsh, download_validator, bcolors, VALIDATOR_BASENAME, store_log, assert_sushi_installed, get_fsh_base_path, get_fhir_version_from_sushi_config, ) from .fshpath import FshPath def get_config(base_path: Path): """ Get the config file from the base path. :param base_path: The base path to the .fsh-validator.yml File. :return: Configuration """ config_file = base_path / ".fsh-validator.yml" if not config_file.exists(): return dict() return yaml.safe_load(open(config_file)) def main(): """ fsh-validator command line interface main. :return: None """ parser = argparse.ArgumentParser( description="Validate a fsh file", formatter_class=argparse.RawTextHelpFormatter, ) arg_fname = parser.add_argument( "filename", help="fsh file names (basename only - no path)", nargs="*" ) parser.add_argument( "--all", dest="all", action="store_true", help="if set, all detected profiles will be validated", required=False, default=False, ) parser.add_argument( "--subdir", dest="subdir", type=str, help="Specifies the subdirectory (relative to input/fsh/) in which to search for profiles if --all is set", required=False, default="", ) parser.add_argument( "--validator-path", dest="path_validator", type=str, help="path to validator", required=False, default=None, ) parser.add_argument( "--verbose", dest="verbose", action="store_true", help="Be verbose", required=False, default=False, ) parser.add_argument( "--no-sushi", dest="no_sushi", action="store_true", help="Do not run sushi before validating", required=False, default=False, ) parser.add_argument( "--log-path", dest="log_path", type=str, help="log file path - if supplied, log files will be written", required=False, default=None, ) args = parser.parse_args() if not args.all and len(args.filename) == 0: raise argparse.ArgumentError( arg_fname, "filename must be set if --all is not specified" ) elif args.all and len(args.filename) == 0: # Use current working dir as input path filenames = [FshPath(os.getcwd())] else: filenames = [FshPath(filename) for filename in args.filename] base_paths = set(filename.fsh_base_path() for filename in filenames) if len(base_paths) > 1: raise ValueError( "Found multiple base paths for fsh project, expecting exactly one" ) base_path = base_paths.pop() validator_path = ( args.path_validator if args.path_validator is not None else base_path ) fname_validator = Path(validator_path) / VALIDATOR_BASENAME if not fname_validator.exists(): print_box("Downloading java validator") download_validator(fname_validator.resolve()) if not args.no_sushi: print_box("Running SUSHI") run_sushi(base_path) fhir_version = get_fhir_version_from_sushi_config(base_path) config = get_config(base_path) if "exclude_code_systems" in config: exclude_code_systems = set(config["exclude_code_systems"]) else: exclude_code_systems = set() if "exclude_resource_type" in config: exclude_resource_types = set(config["exclude_resource_type"]) else: exclude_resource_types = set() if args.all: print_box("Validating all FSH files") results = validate_all_fsh( base_path, args.subdir, str(fname_validator), exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, fhir_version=fhir_version, verbose=args.verbose, ) else: print_box("Validating FSH files") results = validate_fsh( filenames, str(fname_validator), fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=args.verbose, ) if args.log_path is not None: log_path = Path(args.log_path) if not log_path.exists(): log_path.mkdir() store_log(results, log_path) if any([r.failed() for r in results]): print_box("Errors during profile validation", col=bcolors.FAIL) sys.exit(1) else: print_box("All profiles successfully validated", col=bcolors.OKGREEN) sys.exit(0) if __name__ == "__main__": main()
26.671958
115
0.623686
39ec9a70f64ddc65a70eb731b8421b2083d1e79f
410
py
Python
src/aerocloud/packages.py
Aerometrex/aerocloud-python-client
0bd15432bb0f81fc5e9ca03c48b9b15c8e8ed438
[ "MIT" ]
null
null
null
src/aerocloud/packages.py
Aerometrex/aerocloud-python-client
0bd15432bb0f81fc5e9ca03c48b9b15c8e8ed438
[ "MIT" ]
null
null
null
src/aerocloud/packages.py
Aerometrex/aerocloud-python-client
0bd15432bb0f81fc5e9ca03c48b9b15c8e8ed438
[ "MIT" ]
null
null
null
import os from enum import Enum def getPackageDirectory(package: AppPackage, version: str = None): "Gets the directory where the specified package is installed." varName = f'AZ_BATCH_APP_PACKAGE_{package.value}' if version != None: varName = f'{varName}#{version}' return os.environ[varName]
21.578947
66
0.702439
39ef2ca7f17378b96bb6865f18c59fdf8633759c
680
py
Python
src/nodeforge/StartEngine.py
nsk89/nodeforge
51e798092cfaf52112cfdc96af359633741da799
[ "BSD-3-Clause" ]
null
null
null
src/nodeforge/StartEngine.py
nsk89/nodeforge
51e798092cfaf52112cfdc96af359633741da799
[ "BSD-3-Clause" ]
1
2018-10-21T05:30:32.000Z
2018-10-31T05:53:18.000Z
src/nodeforge/StartEngine.py
nsk89/nodeforge
51e798092cfaf52112cfdc96af359633741da799
[ "BSD-3-Clause" ]
2
2018-10-31T05:56:34.000Z
2018-10-31T05:57:36.000Z
""" This file should be imported at the bottom of configure.py TODO: All of this may be moved into a single function in the future so people can choose a reactor in configure.py """ from twisted.internet import reactor from twisted.internet.task import LoopingCall from threading import currentThread, Thread # Check to see if main thread is alive mainthread = currentThread() # Every second, make sure that the interface thread is alive. LoopingCall(checkExit).start(1) # start the network loop in a new thread Thread(target=lambda : reactor.run(installSignalHandlers=0)).start()
29.565217
68
0.744118
39ef5804d073f8e1a8698f5b8f98bbb0a09926ef
7,170
py
Python
src/asit.py
6H057WH1P3/Asit
4dce80e3c4c05c4f56563110c59bae55e61aeaae
[ "MIT" ]
null
null
null
src/asit.py
6H057WH1P3/Asit
4dce80e3c4c05c4f56563110c59bae55e61aeaae
[ "MIT" ]
3
2015-09-16T17:54:13.000Z
2015-09-18T06:54:33.000Z
src/asit.py
6H057WH1P3/Asit
4dce80e3c4c05c4f56563110c59bae55e61aeaae
[ "MIT" ]
null
null
null
import random import time import requests
39.61326
155
0.565969
39f17c6cf9e734ea907636289c61a9999dc0de12
251
py
Python
src/core/views.py
Ao99/django-boilerplate
7fa8078b67655698a4070ce58c10d2226fe1d59b
[ "MIT" ]
null
null
null
src/core/views.py
Ao99/django-boilerplate
7fa8078b67655698a4070ce58c10d2226fe1d59b
[ "MIT" ]
null
null
null
src/core/views.py
Ao99/django-boilerplate
7fa8078b67655698a4070ce58c10d2226fe1d59b
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.views import View # Create your views here.
31.375
54
0.717131
39f26329f53e08a2340c221abdf702988c619417
12,075
py
Python
hashvis.py
boredzo/hashvis
74a017c7fa9b6d48e43172ffd15fc19ccfb060e1
[ "BSD-3-Clause" ]
15
2015-12-02T14:26:52.000Z
2018-01-21T15:18:59.000Z
hashvis.py
boredzo/hashvis
74a017c7fa9b6d48e43172ffd15fc19ccfb060e1
[ "BSD-3-Clause" ]
10
2015-12-04T06:00:42.000Z
2016-07-09T21:40:53.000Z
hashvis.py
boredzo/hashvis
74a017c7fa9b6d48e43172ffd15fc19ccfb060e1
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """hashvis by Peter Hosey Reads from standard input or files, and prints what it reads, along with colorized versions of any hashes or signatures found in each line. The goal here is visual comparability. You should be able to tell whether two hashes are the same at a glance, rather than having to closely compare digits (or, more probably, not bother and just assume the hashes match!). The more obvious of the two methods used is shaping the output: Each hash will be represented as a rectangle of an aspect ratio determined by the hash. You may thus end up with one that's tall and one that's wide, or one that's square (if the hash length is a square number) and one that isn't. If two hashes are the same shape (or if you passed --oneline), another difference is that each byte is represented by a different pair of foreground and background colors. You should thus be able to compare the color-patterns rather than having to look at individual digits. """ # #mark - Imports and utilities import sys import os import re import base64 import binascii import cmath as math range = xrange # #mark - Parsing MD5_exp = re.compile(r'^MD5 \(.*\) = ([0-9a-fA-F]+)') fingerprint_exp = re.compile(r'^(?:R|ECD)SA key fingerprint is (?:(?:MD5:)?(?P<hex>[:0-9a-fA-F]+)|SHA256:(?P<base64>[+/0-9a-zA-Z]+))\.') commit_exp = re.compile(r'^commit ([0-9a-fA-F]+)') more_base64_padding_than_anybody_should_ever_need = '=' * 64 def extract_hash_from_line(input_line): "Returns a tuple of the extracted hash as hex, and whether it was originally hex (vs, say, base64). The hash may be None if none was found in the input." if input_line[:1] == 'M': match = MD5_exp.match(input_line) if match: return match.group(1), True else: return '', False elif input_line[:1] in 'RE': match = fingerprint_exp.match(input_line) if match: hex = match.group('hex') if hex: return hex, True b64str = match.group('base64') if b64str: # Pacify the base64 module, which wants *some* padding (at least sometimes) but doesn't care how much. b64str += more_base64_padding_than_anybody_should_ever_need # Re-encode to hex for processing downstream. Arguably a refactoring opportunity return binascii.b2a_hex(base64.b64decode(b64str)), False return '', False elif input_line[:7] == 'commit ': match = commit_exp.match(input_line) if match: return match.group(1), True if input_line: try: hash, not_the_hash = input_line.split(None, 1) except ValueError: # Insufficient fields. This line doesn't contain any whitespace. Use the entire line. hash = input_line hash = hash.strip().replace('-', '') try: int(hash, 16) except ValueError: # Not a hex number. return None, False else: return hash, True # #mark - Representation def fgcolor(idx, deep_color=False): if deep_color: return '\x1b[38;5;{0}m'.format(idx) idx = ((idx >> 4) & 0xf) # 90 is bright foreground; 30 is dull foreground. if idx < 0x8: base = 30 else: base = 90 idx = idx - 0x8 return '\x1b[{0}m'.format(base + idx) def bgcolor(idx, deep_color=False): if deep_color: idx = ((idx & 0xf) << 4) | ((idx & 0xf0) >> 4) # This add 128 and mod 256 is important, because it ensures double-digits such as 00 remain different colors. return '\x1b[48;5;{0}m'.format((idx + 128) % 256) else: idx = (idx & 0xf) # 100 is bright background; 40 is dull background. if idx < 0x8: base = 40 else: base = 100 idx = idx - 0x8 return '\x1b[{0}m'.format(base + idx) BOLD = '\x1b[1m' RESET = '\x1b[0m' if __name__ == '__main__': # #mark - Self-tests run_tests = False if run_tests: # A square number. Should contain a diagonal pair (in this case, (16,16)). factors_of_256 = set(factors(256)) assert factors_of_256 == set([(256, 1), (16, 16), (8, 32), (2, 128), (64, 4), (1, 256), (32, 8), (128, 2), (4, 64)]) # A rectangular number: not square, but still composite. No diagonal pair here. factors_of_12 = set(factors(12)) assert factors_of_12 == set([(2, 6), (12, 1), (1, 12), (6, 2), (4, 3), (3, 4)]) assert (1, 256) in factors_of_256 assert (256, 1) in factors_of_256 assert (1, 256) not in except_one(factors_of_256) assert (256, 1) not in except_one(factors_of_256) # A prime number. Should have exactly one pair of factors. factors_of_5 = set(factors(5)) assert factors_of_5 == set([(1, 5), (5, 1)]) assert list(parse_hex('ab15e')) == [0xab, 0x15, 0x0e] assert list(parse_hex(':::ab:15:e')) == [0xab, 0x15, 0x0e] assert extract_hash_from_line('RSA key fingerprint is b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38.\n') == ('b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38', True) assert extract_hash_from_line('RSA key fingerprint is b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38.') == ('b8:79:03:7d:00:44:98:6e:67:a0:59:1a:01:21:36:38', True) #Alternate output example from https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Authentication_Keys : assert extract_hash_from_line('RSA key fingerprint is MD5:10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16.') == ('10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16', True) # Also from https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Authentication_Keys : assert extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') == ('2cf162318aeb098415b1550fce3387bfe663cb10879556093015457ab5423fb9', False), extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') assert extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.') == ('2cf162318aeb098415b1550fce3387bfe663cb10879556093015457ab5423fb9', False), extract_hash_from_line('ECDSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.') # Mix and match RSA and ECDSA with MD5 and SHA256: assert extract_hash_from_line('ECDSA key fingerprint is MD5:10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16.') == ('10:4a:ec:d2:f1:38:f7:ea:0a:a0:0f:17:57:ea:a6:16', True) assert extract_hash_from_line('RSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') == ('2cf162318aeb098415b1550fce3387bfe663cb10879556093015457ab5423fb9', False), extract_hash_from_line('RSA key fingerprint is SHA256:LPFiMYrrCYQVsVUPzjOHv+ZjyxCHlVYJMBVFerVCP7k.\n') #UUID assert extract_hash_from_line('E6CD379E-12CD-4E00-A83A-B06E74CF03B8') == ('E6CD379E12CD4E00A83AB06E74CF03B8', True), extract_hash_from_line('E6CD379E-12CD-4E00-A83A-B06E74CF03B8') assert extract_hash_from_line('e6cd379e-12cd-4e00-a83a-b06e74cf03b8') == ('e6cd379e12cd4e00a83ab06e74cf03b8', True), extract_hash_from_line('e6cd379e-12cd-4e00-a83a-b06e74cf03b8') assert extract_hash_from_line('MD5 (hashvis.py) = e21c7b846f76826d52a0ade79ef9cb49\n') == ('e21c7b846f76826d52a0ade79ef9cb49', True) assert extract_hash_from_line('MD5 (hashvis.py) = e21c7b846f76826d52a0ade79ef9cb49') == ('e21c7b846f76826d52a0ade79ef9cb49', True) assert extract_hash_from_line('8b948e9c85fdf68f872017d7064e839c hashvis.py\n') == ('8b948e9c85fdf68f872017d7064e839c', True) assert extract_hash_from_line('8b948e9c85fdf68f872017d7064e839c hashvis.py') == ('8b948e9c85fdf68f872017d7064e839c', True) assert extract_hash_from_line('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924 hashvis.py\n') == ('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924', True) assert extract_hash_from_line('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924 hashvis.py') == ('2c9997ce32cb35823b2772912e221b350717fcb2d782c667b8f808be44ae77ba1a7b94b4111e386c64a2e87d15c64a2fc2177cd826b9a0fba6b348b4352ed924', True) assert extract_hash_from_line('#!/usr/bin/python\n')[0] is None # Protip: Use vis -co to generate these. (line,) = hash_to_pic('78', represent_as_hex=True, deep_color=False) assert line == '\033[1m\033[37m\033[100m78\033[0m', repr(line) (line,) = hash_to_pic('7f', represent_as_hex=True, deep_color=False) assert line == '\033[1m\033[37m\033[107m7f\033[0m', repr(line) assert list(hash_to_pic('aebece', deep_color=False)) != list(hash_to_pic('deeefe', deep_color=False)), (list(hash_to_pic('aebece', deep_color=False)), list(hash_to_pic('deeefe', deep_color=False))) assert list(hash_to_pic('eaebec', deep_color=False)) != list(hash_to_pic('edeeef', deep_color=False)), (list(hash_to_pic('eaebec', deep_color=False)), list(hash_to_pic('edeeef', deep_color=False))) sys.exit(0) # #mark - Main use_256color = os.getenv('TERM') == 'xterm-256color' import argparse parser = argparse.ArgumentParser(description="Visualize hexadecimal input (hashes, UUIDs, etc.) as an arrangement of color blocks.") parser.add_argument('--one-line', '--oneline', action='store_true', help="Unconditionally produce a rectangle 1 character tall. The default is to choose a pair of width and height based upon one of the bytes of the input.") parser.add_argument('--color-test', '--colortest', action='store_true', help="Print the 16-color, 256-color foreground, and 256-color background color palettes, then exit.") options, args = parser.parse_known_args() if options.color_test: for x in range(16): print fgcolor(x, deep_color=False), print bgcolor(x, deep_color=False), else: print for x in range(256): sys.stdout.write(fgcolor(x, deep_color=True) + bgcolor(x, deep_color=True) + '%02x' % (x,)) else: print RESET import sys sys.exit(0) import fileinput for input_line in fileinput.input(args): print input_line.rstrip('\n') hash, is_hex = extract_hash_from_line(input_line) if hash: for output_line in hash_to_pic(hash, only_ever_one_line=options.one_line, represent_as_hex=is_hex, deep_color=use_256color): print output_line
46.087786
319
0.729441
39f2718894e3565b21d9ad13de2638c2e9273b26
270
py
Python
euler_7_nth_prime.py
igorakkerman/euler-challenge
1fdedce439520fc31a2e5fb66abe23b6f99f04db
[ "MIT" ]
null
null
null
euler_7_nth_prime.py
igorakkerman/euler-challenge
1fdedce439520fc31a2e5fb66abe23b6f99f04db
[ "MIT" ]
null
null
null
euler_7_nth_prime.py
igorakkerman/euler-challenge
1fdedce439520fc31a2e5fb66abe23b6f99f04db
[ "MIT" ]
null
null
null
# https://projecteuler.net/problem=7 import math print(sum(sieve(2000000)))
20.769231
57
0.533333
39f3a173967eb82662e3417309654bea4d1eda7a
3,066
py
Python
docker/ubuntu/16-04/ub_limonero/migrations/versions/32053847c4db_add_new_types.py
eubr-atmosphere/jenkins
a9065584d810238c6fa101d92d12c131d1d317cb
[ "Apache-2.0" ]
null
null
null
docker/ubuntu/16-04/ub_limonero/migrations/versions/32053847c4db_add_new_types.py
eubr-atmosphere/jenkins
a9065584d810238c6fa101d92d12c131d1d317cb
[ "Apache-2.0" ]
null
null
null
docker/ubuntu/16-04/ub_limonero/migrations/versions/32053847c4db_add_new_types.py
eubr-atmosphere/jenkins
a9065584d810238c6fa101d92d12c131d1d317cb
[ "Apache-2.0" ]
null
null
null
"""Add new types Revision ID: 32053847c4db Revises: 05a62958a9cc Create Date: 2019-06-11 10:36:14.456629 """ from alembic import context from sqlalchemy.orm import sessionmaker # revision identifiers, used by Alembic. revision = '32053847c4db' down_revision = '05a62958a9cc' branch_labels = None depends_on = None all_commands = [ (""" ALTER TABLE data_source CHANGE `format` `format` ENUM( 'CSV','CUSTOM','GEO_JSON','HAR_IMAGE_FOLDER','HDF5','DATA_FOLDER', 'IMAGE_FOLDER', 'JDBC','JSON','NETCDF4','PARQUET','PICKLE','SHAPEFILE', 'TAR_IMAGE_FOLDER','TEXT', 'VIDEO_FOLDER', 'UNKNOWN','XML_FILE') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""", """ ALTER TABLE data_source CHANGE `format` `format` ENUM( 'CSV','CUSTOM','GEO_JSON','HDF5','JDBC','JSON', 'NETCDF4','PARQUET','PICKLE','SHAPEFILE','TEXT', 'UNKNOWN','XML_FILE') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""" ), (""" ALTER TABLE `storage` CHANGE `type` `type` ENUM( 'HDFS','OPHIDIA','ELASTIC_SEARCH','MONGODB','POSTGIS','HBASE', 'CASSANDRA','JDBC','LOCAL') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""", """ ALTER TABLE `storage` CHANGE `type` `type` ENUM( 'HDFS','OPHIDIA','ELASTIC_SEARCH','MONGODB','POSTGIS','HBASE', 'CASSANDRA','JDBC') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL;""", ), ( """ALTER TABLE `model` CHANGE `type` `type` ENUM( 'KERAS','SPARK_ML_REGRESSION','SPARK_MLLIB_CLASSIFICATION', 'SPARK_ML_CLASSIFICATION','UNSPECIFIED') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL; """, """ALTER TABLE `model` CHANGE `type` `type` ENUM( 'KERAS','SPARK_ML_REGRESSION','SPARK_MLLIB_CLASSIFICATION', 'SPARK_ML_CLASSIFICATION','UNSPECIFIED') CHARSET utf8 COLLATE utf8_unicode_ci NOT NULL; """ ) ]
32.967742
80
0.599152
39f4f90e9b80ade83346acbec06fcedbaeda8cb3
88
py
Python
advanced_tools/__init__.py
kvdogan/advanced_tools
7e93232374980d83fda8051496a190188c11fe0d
[ "MIT" ]
null
null
null
advanced_tools/__init__.py
kvdogan/advanced_tools
7e93232374980d83fda8051496a190188c11fe0d
[ "MIT" ]
null
null
null
advanced_tools/__init__.py
kvdogan/advanced_tools
7e93232374980d83fda8051496a190188c11fe0d
[ "MIT" ]
null
null
null
from advanced_tools.IO_path_utils import * from advanced_tools.algorithm_utils import *
29.333333
44
0.863636
39f5a45cf3414a12f90b8d040d893593304736d0
2,836
py
Python
sets-master/sets-master/sets/utility.py
FedericoMolinaChavez/tesis-research
d77cc621d452c9ecf48d9ac80349b41aeb842412
[ "MIT" ]
null
null
null
sets-master/sets-master/sets/utility.py
FedericoMolinaChavez/tesis-research
d77cc621d452c9ecf48d9ac80349b41aeb842412
[ "MIT" ]
4
2021-03-09T20:33:57.000Z
2022-02-18T12:56:32.000Z
sets-master/sets-master/sets/utility.py
FedericoMolinaChavez/tesis-research
d77cc621d452c9ecf48d9ac80349b41aeb842412
[ "MIT" ]
null
null
null
import os import pickle import functools import errno import shutil from urllib.request import urlopen #import definitions def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'. """ directory = os.path.expanduser(directory) ensure_directory(directory) return wrapper def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = os.path.split(url) directory = os.path.expanduser(directory) ensure_directory(directory) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): return filepath print('Download', filepath) with urlopen(url) as response, open(filepath, 'wb') as file_: shutil.copyfileobj(response, file_) return filepath def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise e
35.012346
80
0.619182
f2cdba45917fad7ff9ab33f608fa9dbb603aec4b
1,984
py
Python
src/test_fps.py
pjenpoomjai/tfpose-herokuNEW
7d1085a3fcb02c0f6d16ed7f2cf1ad8daff103ea
[ "Apache-2.0" ]
null
null
null
src/test_fps.py
pjenpoomjai/tfpose-herokuNEW
7d1085a3fcb02c0f6d16ed7f2cf1ad8daff103ea
[ "Apache-2.0" ]
null
null
null
src/test_fps.py
pjenpoomjai/tfpose-herokuNEW
7d1085a3fcb02c0f6d16ed7f2cf1ad8daff103ea
[ "Apache-2.0" ]
null
null
null
import cv2 import time import numpy as np import imutils camera= 0 cam = cv2.VideoCapture(camera) fgbg = cv2.createBackgroundSubtractorMOG2(history=1000,varThreshold=0,detectShadows=False) width=600 height=480 fps_time = 0 while True: ret_val,image = cam.read() image = cv2.resize(image,(width,height)) image = cv2.GaussianBlur(image, (5, 5), 0) fgmask = fgbg.apply(image) # image = fgbg.apply(image,learningRate=0.001) # image = imutils.resize(image, width=500) # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cnts = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] # loop over the contours x_left = -1 y_left = -1 x_right = -1 y_right = -1 for c in cnts: # if the contour is too small, ignore it # if cv2.contourArea(c) > 500: # continue # compute the bounding box for the contour, draw it on the frame, # and update the text (x, y, w, h) = cv2.boundingRect(c) if x_left ==-1 : x_left = x y_left = y if x < x_left: x_left = x if y < y_left: y_left = y if x+w > x_right: x_right = x+w if y+h > y_right: y_right = y+h # cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2) if (x_left==0 and y_left==0 and x_right==width and y_right==height)==False: cv2.rectangle(image, (x_left, y_left), (x_right, y_right), (0, 255, 0), 2) # cv2.putText(image, # "FPS: %f [press 'q'to quit]" % (1.0 / (time.time() - fps_time)), # (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, # (0, 255, 0), 2) cv2.imshow('tf-pose-estimation result',fgmask) cv2.imshow('tf-pose-estimation result2',image) fps_time = time.time() if cv2.waitKey(1)==ord('q'): cam.release() cv2.destroyAllWindows() break
28.342857
90
0.579133
f2ce254695f631034aa335be9147cb99e06d1cfc
999
py
Python
Python/367.ValidPerfectSquare.py
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
263
2020-10-05T18:47:29.000Z
2022-03-31T19:44:46.000Z
Python/367.ValidPerfectSquare.py
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
1,264
2020-10-05T18:13:05.000Z
2022-03-31T23:16:35.000Z
Python/367.ValidPerfectSquare.py
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
760
2020-10-05T18:22:51.000Z
2022-03-29T06:06:20.000Z
#Given a positive integer num, write a function which returns True if num is a perfect square else False.
47.571429
140
0.617618
f2d302744caca38acace037f6391b1ffee2c8630
1,432
py
Python
src/minescrubber/controller.py
alok1974/minescrubber
0c18d960b385a4a59ac0cf38bc69271a23c667e7
[ "MIT" ]
1
2020-08-11T23:08:34.000Z
2020-08-11T23:08:34.000Z
src/minescrubber/controller.py
alok1974/minescrubber
0c18d960b385a4a59ac0cf38bc69271a23c667e7
[ "MIT" ]
null
null
null
src/minescrubber/controller.py
alok1974/minescrubber
0c18d960b385a4a59ac0cf38bc69271a23c667e7
[ "MIT" ]
null
null
null
from minescrubber_core import abstract from . import mainwindow def run(): controller = Controller() controller.run(ui_class=UI)
22.730159
68
0.670391
f2d339d173f754cc9a0dd3025640fbb292c58b5b
36
py
Python
CADRE/power_dymos/__init__.py
johnjasa/CADRE
a4ffd61582b8474953fc309aa540838a14f29dcf
[ "Apache-2.0" ]
null
null
null
CADRE/power_dymos/__init__.py
johnjasa/CADRE
a4ffd61582b8474953fc309aa540838a14f29dcf
[ "Apache-2.0" ]
null
null
null
CADRE/power_dymos/__init__.py
johnjasa/CADRE
a4ffd61582b8474953fc309aa540838a14f29dcf
[ "Apache-2.0" ]
null
null
null
from .power_group import PowerGroup
18
35
0.861111
f2d47c8b76e7230c4405127adcd43ba0cfb587fd
2,386
py
Python
client/elementtype.py
Schille/weimar-graphstore
76b47f98fba419ec6290628b56a202c60d8f2d46
[ "MIT" ]
2
2016-08-27T04:51:01.000Z
2020-09-05T01:34:41.000Z
client/elementtype.py
Schille/weimar-graphstore
76b47f98fba419ec6290628b56a202c60d8f2d46
[ "MIT" ]
null
null
null
client/elementtype.py
Schille/weimar-graphstore
76b47f98fba419ec6290628b56a202c60d8f2d46
[ "MIT" ]
null
null
null
""" .. module:: elementtype.py :platform: Linux .. moduleauthor:: Michael Schilonka <michael@schilonka.de> """ import logging
24.854167
82
0.60855
f2d4d9817772d3d480a3be486cdd4fa4ac3b04f2
672
py
Python
src/OTLMOW/OTLModel/Classes/Infiltratievoorziening.py
davidvlaminck/OTLClassPython
71330afeb37c3ea6d9981f521ff8f4a3f8b946fc
[ "MIT" ]
2
2022-02-01T08:58:11.000Z
2022-02-08T13:35:17.000Z
src/OTLMOW/OTLModel/Classes/Infiltratievoorziening.py
davidvlaminck/OTLMOW
71330afeb37c3ea6d9981f521ff8f4a3f8b946fc
[ "MIT" ]
null
null
null
src/OTLMOW/OTLModel/Classes/Infiltratievoorziening.py
davidvlaminck/OTLMOW
71330afeb37c3ea6d9981f521ff8f4a3f8b946fc
[ "MIT" ]
null
null
null
# coding=utf-8 from OTLMOW.OTLModel.Classes.Put import Put from OTLMOW.OTLModel.Classes.PutRelatie import PutRelatie from OTLMOW.GeometrieArtefact.VlakGeometrie import VlakGeometrie # Generated with OTLClassCreator. To modify: extend, do not edit
37.333333
93
0.763393
f2d563db44644c1403a6f057432f77eaa66bdff6
1,517
py
Python
Chapter04/chapter4.py
Kushalshingote/Hands-On-Generative-Adversarial-Networks-with-Keras
fccada4810ba1fe8b79c5a74420a590c95623b52
[ "MIT" ]
76
2019-05-27T23:38:53.000Z
2021-12-19T00:31:13.000Z
Chapter04/chapter4.py
Kushalshingote/Hands-On-Generative-Adversarial-Networks-with-Keras
fccada4810ba1fe8b79c5a74420a590c95623b52
[ "MIT" ]
9
2019-05-29T21:01:32.000Z
2020-07-30T12:00:02.000Z
Chapter04/chapter4.py
Kushalshingote/Hands-On-Generative-Adversarial-Networks-with-Keras
fccada4810ba1fe8b79c5a74420a590c95623b52
[ "MIT" ]
35
2019-05-12T04:20:54.000Z
2022-03-03T19:46:06.000Z
# get the training data D, sample the Generator with random z to produce r N = X_train z = np.random.uniform(-1, 1, (1, z_dim)) r = G.predict_on_batch(z) # define our distance measure S to be L1 S = lambda n, r: np.sum(np.abs(n - r)) # compute the distances between the reference and the samples in N using the measure D distances = [D(n, r) for n in N] # find the indices of the most similar samples and select them from N nearest_neighbors_index = np.argpartition(distances, k) nearest_neighbors_images = N[nearest_neighbors_index] # generate fake images from the discriminator n_fake_images = 5000 z = np.random.uniform(-1, 1, (n_fake_images, z_dim)) x = G.predict_on_batch(z) # marginal probability of y q_y = np.mean(p_y_given_x, axis=0) inception_scores = p_y_given_x * (np.log(p_y_given_x) - np.log(q_y) inception_score = np.exp(np.mean(inception_scores)) return inception_score def get_mean_and_covariance(data): mean = np.mean(data, axis=0) covariance = np.cov(data, rowvar=False) # rowvar? return mean, covariance def compute_frechet_inception_distance(mean_r, mean_f, cov_r, cov_f): l2_mean = np.sum((mean_r - mean_f)**2) cov_mean, _ = np.trace(scipy.linalg.sqrtm(np.dot(cov_r, cov_f))) return l2_mu + np.trace(cov_r) + np.trace(cov_f) - 2 * np.trace(cov_mean)
35.27907
87
0.712591
f2d5d419d88204df9613b1050b9f75f4f36ef80c
20,923
py
Python
naspi/naspi.py
fgiroult321/simple-nas-pi
6d1a13523f1f20ebe26f780c758a3ff15be899ff
[ "MIT" ]
null
null
null
naspi/naspi.py
fgiroult321/simple-nas-pi
6d1a13523f1f20ebe26f780c758a3ff15be899ff
[ "MIT" ]
null
null
null
naspi/naspi.py
fgiroult321/simple-nas-pi
6d1a13523f1f20ebe26f780c758a3ff15be899ff
[ "MIT" ]
null
null
null
import os import boto3 # import subprocess from subprocess import Popen, PIPE from time import sleep import json import ast from datetime import datetime, time, timedelta, date import logging import logging.handlers import sys, getopt import glob import shutil logger = logging.getLogger() logger.setLevel(logging.INFO) #### #### function defs #### if __name__=='__main__': main() # main(sys.argv[1:])
38.461397
164
0.633322
f2d7e6c6a86e1314f1b2716ac6227b1dc354be91
14,328
py
Python
fawkes/differentiator_lowkey.py
biergaiqiao/Oriole-Thwarting-Privacy-against-Trustworthy-Deep-Learning-Models
ffadb82b666e8c1561a036a10d9922db8a3266cc
[ "MIT" ]
1
2021-05-18T01:14:44.000Z
2021-05-18T01:14:44.000Z
fawkes/differentiator_lowkey.py
biergaiqiao/Oriole-Thwarting-Privacy-against-Trustworthy-Deep-Learning-Models
ffadb82b666e8c1561a036a10d9922db8a3266cc
[ "MIT" ]
null
null
null
fawkes/differentiator_lowkey.py
biergaiqiao/Oriole-Thwarting-Privacy-against-Trustworthy-Deep-Learning-Models
ffadb82b666e8c1561a036a10d9922db8a3266cc
[ "MIT" ]
1
2021-05-18T01:14:47.000Z
2021-05-18T01:14:47.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-10-21 # @Author : Emily Wenger (ewenger@uchicago.edu) import time import numpy as np import tensorflow as tf import tensorflow_addons as tfa from keras.utils import Progbar
44.775
135
0.620254
f2d93f0a50f1963382d3895bbaf47dcf3e2de6e0
1,124
py
Python
routes/class_incoming.py
fingerecho/proms-4.0
6c3a1fd62c9394761664e100fc1dde50fd79dc11
[ "CC-BY-4.0" ]
2
2019-11-23T03:56:28.000Z
2019-12-03T15:48:34.000Z
routes/class_incoming.py
fingerecho/proms-4.0
6c3a1fd62c9394761664e100fc1dde50fd79dc11
[ "CC-BY-4.0" ]
null
null
null
routes/class_incoming.py
fingerecho/proms-4.0
6c3a1fd62c9394761664e100fc1dde50fd79dc11
[ "CC-BY-4.0" ]
3
2019-04-12T18:09:35.000Z
2020-03-14T14:38:45.000Z
from abc import ABCMeta, abstractmethod import database from . import w_l
29.578947
120
0.615658
f2da20f8cd9ede45ff2e1e9791b316945d38036c
418
py
Python
openwater/utils/decorator.py
jeradM/openwater
740b7e76622a1ee909b970d9e5c612a840466cec
[ "MIT" ]
null
null
null
openwater/utils/decorator.py
jeradM/openwater
740b7e76622a1ee909b970d9e5c612a840466cec
[ "MIT" ]
null
null
null
openwater/utils/decorator.py
jeradM/openwater
740b7e76622a1ee909b970d9e5c612a840466cec
[ "MIT" ]
null
null
null
from typing import Callable
20.9
58
0.717703
f2db2b20dcde6fe54280e2d0105ffc23c0015da0
404
py
Python
setup.py
TDGerve/ramCOH
328f27891906e7207344fb3c5a685648a0924dd2
[ "MIT" ]
2
2022-03-08T12:30:55.000Z
2022-03-29T19:46:59.000Z
setup.py
TDGerve/ramCOH
328f27891906e7207344fb3c5a685648a0924dd2
[ "MIT" ]
null
null
null
setup.py
TDGerve/ramCOH
328f27891906e7207344fb3c5a685648a0924dd2
[ "MIT" ]
null
null
null
import setuptools setuptools.setup( name= 'ramCOH', version= '0.1', description= '...', author= 'Thomas van Gerve', packages= setuptools.find_packages( exclude= ['examples'] ), # package_dir= {'' : 'petroPy'}, package_data= {'ramCOH': ['static/*']}, install_requires= [ 'pandas', 'matplotlib', 'numpy', 'scipy', 'csaps' ] )
17.565217
44
0.534653
f2dd43c40f9fe338eecf074d6dac1c0de992c516
798
py
Python
chess.py
jrj92280/python-eve-backend
c0566cdef5e5c75e2b75e59bde804e0d4ce407e3
[ "MIT" ]
null
null
null
chess.py
jrj92280/python-eve-backend
c0566cdef5e5c75e2b75e59bde804e0d4ce407e3
[ "MIT" ]
null
null
null
chess.py
jrj92280/python-eve-backend
c0566cdef5e5c75e2b75e59bde804e0d4ce407e3
[ "MIT" ]
null
null
null
from chess_game._board import make_board from chess_game.chess_game import ChessGame from chess_game.play_game import get_user_input, game_event_loop if __name__ == "__main__": game_board = make_board() # pawn = Pawn('x', 'y', None, None, None) # pawn.move() print('Chess') print(' : Rules') print(' : input - piece''s position x,y, second x,y = destination') print(" : x = row number 1 though 8") print(" : y = column number 1 though 8") player1_name = get_user_input(' : Enter player one name', is_move=False) player2_name = get_user_input(' : Enter player two name', is_move=False) print('------------------------------------------------') chess_game = ChessGame(game_board, player1_name, player2_name) game_event_loop(chess_game)
33.25
76
0.639098
f2dda34548b86bf17367a72a0ef32f5325649770
576
py
Python
python/binary_tree/104.maximum-depth-of-binary-tree.py
Nobodylesszb/LeetCode
0e902f6bff4834a93ce64cf9c57fd64297e63523
[ "MIT" ]
null
null
null
python/binary_tree/104.maximum-depth-of-binary-tree.py
Nobodylesszb/LeetCode
0e902f6bff4834a93ce64cf9c57fd64297e63523
[ "MIT" ]
null
null
null
python/binary_tree/104.maximum-depth-of-binary-tree.py
Nobodylesszb/LeetCode
0e902f6bff4834a93ce64cf9c57fd64297e63523
[ "MIT" ]
null
null
null
""" Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. """ import Math
20.571429
114
0.625
f2de6356f341ba86e79ed1873bc9d766068dfedf
1,589
py
Python
strstr/3-2.py
stonemary/lintcode_solutions
f41fd0e56fb88ab54d0ab624977bff1623a6d33a
[ "Apache-2.0" ]
null
null
null
strstr/3-2.py
stonemary/lintcode_solutions
f41fd0e56fb88ab54d0ab624977bff1623a6d33a
[ "Apache-2.0" ]
null
null
null
strstr/3-2.py
stonemary/lintcode_solutions
f41fd0e56fb88ab54d0ab624977bff1623a6d33a
[ "Apache-2.0" ]
null
null
null
# time 15 mins # used time 15 mins # time 15 mins # used time 15 mins # this is actually a correct solution # the code i submitted a day ago, which passed lintcode, is actually wrong after i looked KMP up # the previous version does not take care of the situations where the target contains repeatitive elements
34.543478
118
0.570799
f2e1fc7cc5cf4031b844d0facd03421c1cb64cd2
15,633
py
Python
ProyectoFinal.py
T0N1R/Recommendation-System-python-neo4J
09dd1bbefa7e436a1aeedf9ccc9160719ec3a353
[ "MIT" ]
null
null
null
ProyectoFinal.py
T0N1R/Recommendation-System-python-neo4J
09dd1bbefa7e436a1aeedf9ccc9160719ec3a353
[ "MIT" ]
null
null
null
ProyectoFinal.py
T0N1R/Recommendation-System-python-neo4J
09dd1bbefa7e436a1aeedf9ccc9160719ec3a353
[ "MIT" ]
null
null
null
# -*- coding: cp1252 -*- # -*- coding: utf-8 -*- """ Algoritmos y Estructuras de Datos Proyecto Final Antonio Reyes #17273 Esteban Cabrera #17781 Miguel #17102 """ import random import xlrd file_location = "C:/Users/Antonio/Desktop/Recommendation-System-python-neo4J-master/Database.xlsx" workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) from neo4jrestclient.client import GraphDatabase db = GraphDatabase("http://localhost:7474",username="neo4j", password="1111") dataB = db.labels.create("Database") gen = db.labels.create("Genero") #se crea un diccionario (como vimos en hashmaps) database = {} #donde se guardan los generos de las series que ya se vieron historial = [] #en el for se puede poner sheet.nrows para imprimir todo #se utiliza el cdigo mostrado en este link para mostrar los generos que se repiten ms veces #https://stackoverflow.com/questions/3594514/how-to-find-most-common-elements-of-a-list #mtodo para mostrar todas las series y peliculas de un genero #****************************************************************************************************** #******************************************************************************************************* menu() opcion = input("Option: ") print ("**********************************") print ("**********************************") while(opcion != 9): if(opcion == 0): add_Excel() print ("**********************************") print ("**********************************") print ("Values added to Database") menu() opcion = input("Option: ") elif(opcion == 1): add_database() print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") elif(opcion == 2): watch() print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") elif(opcion == 3): show_genre() print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") else: print("This option is not valid") print ("**********************************") print ("**********************************") menu() opcion = input("Option: ") print ("Thanks for using the program")
30.414397
147
0.515832
f2e37e6fb52ee6d2e740ecb159b5517384b2a2c4
324
py
Python
www/async_flask/__init__.py
StarAhri/flask
facd476065c945f3467d4bfd7bc4ca910cc27d74
[ "BSD-3-Clause" ]
null
null
null
www/async_flask/__init__.py
StarAhri/flask
facd476065c945f3467d4bfd7bc4ca910cc27d74
[ "BSD-3-Clause" ]
null
null
null
www/async_flask/__init__.py
StarAhri/flask
facd476065c945f3467d4bfd7bc4ca910cc27d74
[ "BSD-3-Clause" ]
null
null
null
from flask import Flask import time from _thread import get_ident app=Flask(__name__) if __name__=="__main__": app.run(port=6003)
17.052632
42
0.675926
f2e440f4b6da4c3dc8c1545aee15d9066fc4d3f5
724
py
Python
codility-python/util/test_strings.py
mforoni/codility
be5005e96612dd7bb33b88bb76a590d28084b032
[ "MIT" ]
null
null
null
codility-python/util/test_strings.py
mforoni/codility
be5005e96612dd7bb33b88bb76a590d28084b032
[ "MIT" ]
null
null
null
codility-python/util/test_strings.py
mforoni/codility
be5005e96612dd7bb33b88bb76a590d28084b032
[ "MIT" ]
null
null
null
import unittest import util.strings as strings if __name__ == '__main__': unittest.main()
31.478261
97
0.686464
f2e49a7f41a62f84a3de746b66ce03eb20e0b955
1,395
py
Python
ipython/data/parseSource/input.py
cainja/RMG-Py
f9ad0f4244e476a28768c8a4a37410ad55bcd556
[ "MIT" ]
1
2020-01-14T09:12:22.000Z
2020-01-14T09:12:22.000Z
ipython/data/parseSource/input.py
speth/RMG-Py
1d2c2b684580396e984459d9347628a5ceb80e2e
[ "MIT" ]
72
2016-06-06T18:18:49.000Z
2019-11-17T03:21:10.000Z
ipython/data/parseSource/input.py
speth/RMG-Py
1d2c2b684580396e984459d9347628a5ceb80e2e
[ "MIT" ]
3
2017-09-22T15:47:37.000Z
2021-12-30T23:51:47.000Z
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [('C3', False)], seedMechanisms = ['GRI-Mech3.0'], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # List of species species( label='ethane', reactive=True, structure=SMILES("CC"), ) species( label='N2', reactive=False, structure=adjacencyList(""" 1 N u0 p1 c0 {2,T} 2 N u0 p1 c0 {1,T} """), ) # Reaction systems simpleReactor( temperature=(1350,'K'), pressure=(1.0,'bar'), initialMoleFractions={ "ethane": 0.1, "N2": 0.9 }, terminationConversion={ 'ethane': 0.9, }, terminationTime=(1e6,'s'), ) simulator( atol=1e-16, rtol=1e-8, ) model( toleranceKeepInEdge=0.0, toleranceMoveToCore=0.1, toleranceInterruptSimulation=0.1, maximumEdgeSpecies=100000, ) options( units='si', saveRestartPeriod=None, generateOutputHTML=True, generatePlots=False, saveEdgeSpecies=True, saveSimulationProfiles=True, verboseComments=True, ) pressureDependence( method='modified strong collision', maximumGrainSize=(0.5,'kcal/mol'), minimumNumberOfGrains=250, temperatures=(300,2200,'K',2), pressures=(0.01,100,'bar',3), interpolation=('Chebyshev', 6, 4), maximumAtoms=15, )
19.375
47
0.632258
f2e593a65e27e8bb4c6dbcd20c5d00538ad0aa1c
438
py
Python
simbench/__init__.py
BaraaUniKassel/simbench
eca679bbef2b7c61d4a42dd9d9716ad969ff6f77
[ "BSD-3-Clause" ]
null
null
null
simbench/__init__.py
BaraaUniKassel/simbench
eca679bbef2b7c61d4a42dd9d9716ad969ff6f77
[ "BSD-3-Clause" ]
null
null
null
simbench/__init__.py
BaraaUniKassel/simbench
eca679bbef2b7c61d4a42dd9d9716ad969ff6f77
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2019-2021 by University of Kassel, Tu Dortmund, RWTH Aachen University and Fraunhofer # Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual # contributors (see AUTHORS file for details). All rights reserved. __version__ = "1.3.0" __author__ = "smeinecke" import os sb_dir = os.path.dirname(os.path.realpath(__file__)) from simbench.converter import * from simbench.networks import *
33.692308
101
0.783105
f2e72fd64f8c76f1c9fc74fe2d074f594b42d146
215
py
Python
src/output_module.py
abhishekpandeyIT/Virtual_Intelligent_Personal_Agent
786261fbcf1468bcbaee9f6d17aea3f3cc06f81e
[ "Apache-2.0" ]
null
null
null
src/output_module.py
abhishekpandeyIT/Virtual_Intelligent_Personal_Agent
786261fbcf1468bcbaee9f6d17aea3f3cc06f81e
[ "Apache-2.0" ]
null
null
null
src/output_module.py
abhishekpandeyIT/Virtual_Intelligent_Personal_Agent
786261fbcf1468bcbaee9f6d17aea3f3cc06f81e
[ "Apache-2.0" ]
null
null
null
import assistantResume from speak_module import speak from database import speak_is_on
23.888889
44
0.702326
f2ed016efef1c89871a2e33d8718c95390697abc
3,545
py
Python
vk_bot/needrework/relation.py
triangle1984/vk-bot
39dea7bf8043e791ef079ea1ac6616f95d5b5312
[ "BSD-3-Clause" ]
3
2019-11-05T12:32:04.000Z
2019-11-15T14:29:46.000Z
vk_bot/needrework/relation.py
anar66/vk-bot
39dea7bf8043e791ef079ea1ac6616f95d5b5312
[ "BSD-3-Clause" ]
1
2019-12-11T20:26:31.000Z
2019-12-11T20:26:31.000Z
vk_bot/needrework/relation.py
triangle1984/vk-bot
39dea7bf8043e791ef079ea1ac6616f95d5b5312
[ "BSD-3-Clause" ]
5
2019-11-20T14:20:30.000Z
2022-02-05T10:37:01.000Z
import vk_api from vk_api.utils import get_random_id from vk_bot.core.sql.vksql import *
48.561644
172
0.598025
f2ed7a6bb514c982bc41d3c33e724e9e6365650e
1,746
py
Python
wallpaperdownloader/main.py
k-vinogradov/wallpaper-downloader
568c6a1e3a2307f710bf6fe313b39da2d620213a
[ "MIT" ]
null
null
null
wallpaperdownloader/main.py
k-vinogradov/wallpaper-downloader
568c6a1e3a2307f710bf6fe313b39da2d620213a
[ "MIT" ]
null
null
null
wallpaperdownloader/main.py
k-vinogradov/wallpaper-downloader
568c6a1e3a2307f710bf6fe313b39da2d620213a
[ "MIT" ]
null
null
null
"""Wallpaper Downloader Main Module.""" import argparse import asyncio import logging import sys from datetime import datetime from wallpaperdownloader.downloader import download, LOGGER_NAME def abort(*args): """Print message to the stderr and exit the program.""" print(*args, file=sys.stderr) sys.exit(1) def check_args(args): """Check if arguments are valid.""" month, year = (args.month, args.year) if month < 1 or month > 12: abort("Invalid month number %d", month) date_string = f"{year:04}{month:02}" if date_string < "201205": abort("There are no wallpapers older than May 2012") if date_string > datetime.now().strftime("%Y%M"): abort("Too early... come a bit later") def configure_logger(level): """Configure console log output.""" logger = logging.getLogger(LOGGER_NAME) handler = logging.StreamHandler() logger.setLevel(level) handler.setLevel(level) logger.addHandler(handler) def main(): """Run WD main routine.""" parser = argparse.ArgumentParser( description="Download wallpapers from www.smashingmagazine.com" ) parser.add_argument("month", type=int, help="Month number") parser.add_argument("year", type=int, help="Year") parser.add_argument("resolution", type=str, help="Image resolution") parser.add_argument( "-v", "--verbose", action="store_true", help="Enable verbose output" ) args = parser.parse_args() check_args(args) configure_logger(logging.DEBUG if args.verbose else logging.INFO) year, month, res = (args.year, args.month, args.resolution) asyncio.get_event_loop().run_until_complete(download(year, month, res)) if __name__ == "__main__": main()
29.59322
76
0.683849
f2ee02add396584dc919e32b6bdd9a63f34df039
4,512
py
Python
Lib/site-packages/hackedit/app/common.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
null
null
null
Lib/site-packages/hackedit/app/common.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
20
2021-05-03T18:02:23.000Z
2022-03-12T12:01:04.000Z
Lib/site-packages/hackedit/app/common.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
null
null
null
""" Functions shared across the main window, the welcome window and the system tray. """ import os import qcrash.api as qcrash from PyQt5 import QtWidgets from hackedit.app import templates, settings from hackedit.app.dialogs.dlg_about import DlgAbout from hackedit.app.dialogs.dlg_template_answers import DlgTemplateVars from hackedit.app.dialogs.preferences import DlgPreferences from hackedit.app.wizards.new import WizardNew def show_about(window): """ Shows the about dialog on the parent window :param window: parent window. """ DlgAbout.show_about(window) def check_for_update(*args, **kwargs): """ Checks for update. :param window: parent window :param show_up_to_date_msg: True to show a message box when the app is up to date. """ # todo: improve this: make an update wizard that update both hackedit # and its packages (to ensure compatiblity) # if pip_tools.check_for_update('hackedit', __version__): # answer = QtWidgets.QMessageBox.question( # window, 'Check for update', # 'A new version of HackEdit is available...\n' # 'Would you like to install it now?') # if answer == QtWidgets.QMessageBox.Yes: # try: # status = pip_tools.graphical_install_package( # 'hackedit', autoclose_dlg=True) # except RuntimeError as e: # QtWidgets.qApp.processEvents() # QtWidgets.QMessageBox.warning( # window, 'Update failed', # 'Failed to update hackedit: %r' % e) # else: # QtWidgets.qApp.processEvents() # if status: # QtWidgets.QMessageBox.information( # window, 'Check for update', # 'Update completed with sucess, the application ' # 'will now restart...') # window.app.restart() # else: # QtWidgets.QMessageBox.warning( # window, 'Update failed', # 'Failed to update hackedit') # else: # _logger().debug('HackEdit up to date') # if show_up_to_date_msg: # QtWidgets.QMessageBox.information( # window, 'Check for update', 'HackEdit is up to date.') pass
32
77
0.623005
f2ee858e562eab312d062843fa52105cd18f06ef
4,778
py
Python
pygame_menu/locals.py
apuly/pygame-menu
77bf8f2c8913de5a24674ee0d0d2c7c9b816a58b
[ "MIT" ]
419
2017-05-01T20:00:08.000Z
2022-03-29T13:49:16.000Z
pygame_menu/locals.py
apuly/pygame-menu
77bf8f2c8913de5a24674ee0d0d2c7c9b816a58b
[ "MIT" ]
363
2017-11-05T17:42:48.000Z
2022-03-27T21:13:33.000Z
pygame_menu/locals.py
apuly/pygame-menu
77bf8f2c8913de5a24674ee0d0d2c7c9b816a58b
[ "MIT" ]
167
2017-05-02T20:42:24.000Z
2022-03-24T16:17:38.000Z
""" pygame-menu https://github.com/ppizarror/pygame-menu LOCALS Local constants. License: ------------------------------------------------------------------------------- The MIT License (MIT) Copyright 2017-2021 Pablo Pizarro R. @ppizarror Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- """ __all__ = [ # Alignment 'ALIGN_CENTER', 'ALIGN_LEFT', 'ALIGN_RIGHT', # Data types 'INPUT_FLOAT', 'INPUT_INT', 'INPUT_TEXT', # Positioning 'POSITION_CENTER', 'POSITION_EAST', 'POSITION_NORTH', 'POSITION_NORTHEAST', 'POSITION_SOUTHWEST', 'POSITION_SOUTH', 'POSITION_SOUTHEAST', 'POSITION_NORTHWEST', 'POSITION_WEST', # Orientation 'ORIENTATION_HORIZONTAL', 'ORIENTATION_VERTICAL', # Scrollarea 'SCROLLAREA_POSITION_BOTH_HORIZONTAL', 'SCROLLAREA_POSITION_BOTH_VERTICAL', 'SCROLLAREA_POSITION_FULL', # Cursors 'CURSOR_ARROW', 'CURSOR_CROSSHAIR', 'CURSOR_HAND', 'CURSOR_IBEAM', 'CURSOR_NO', 'CURSOR_SIZEALL', 'CURSOR_SIZENESW', 'CURSOR_SIZENS', 'CURSOR_SIZENWSE', 'CURSOR_SIZEWE', 'CURSOR_WAIT', 'CURSOR_WAITARROW', # Event compatibility 'FINGERDOWN', 'FINGERMOTION', 'FINGERUP' ] import pygame as __pygame # Alignment ALIGN_CENTER = 'align-center' ALIGN_LEFT = 'align-left' ALIGN_RIGHT = 'align-right' # Input data type INPUT_FLOAT = 'input-float' INPUT_INT = 'input-int' INPUT_TEXT = 'input-text' # Position POSITION_CENTER = 'position-center' POSITION_EAST = 'position-east' POSITION_NORTH = 'position-north' POSITION_NORTHEAST = 'position-northeast' POSITION_NORTHWEST = 'position-northwest' POSITION_SOUTH = 'position-south' POSITION_SOUTHEAST = 'position-southeast' POSITION_SOUTHWEST = 'position-southwest' POSITION_WEST = 'position-west' # Menu ScrollArea position SCROLLAREA_POSITION_BOTH_HORIZONTAL = 'scrollarea-position-both-horizontal' SCROLLAREA_POSITION_BOTH_VERTICAL = 'scrollarea_position-both-vertical' SCROLLAREA_POSITION_FULL = 'scrollarea-position-full' # Orientation ORIENTATION_HORIZONTAL = 'orientation-horizontal' ORIENTATION_VERTICAL = 'orientation-vertical' # Cursors CURSOR_ARROW = None if not hasattr(__pygame, 'SYSTEM_CURSOR_ARROW') else __pygame.SYSTEM_CURSOR_ARROW CURSOR_CROSSHAIR = None if not hasattr(__pygame, 'SYSTEM_CURSOR_CROSSHAIR') else __pygame.SYSTEM_CURSOR_CROSSHAIR CURSOR_HAND = None if not hasattr(__pygame, 'SYSTEM_CURSOR_HAND') else __pygame.SYSTEM_CURSOR_HAND CURSOR_IBEAM = None if not hasattr(__pygame, 'SYSTEM_CURSOR_IBEAM') else __pygame.SYSTEM_CURSOR_IBEAM CURSOR_NO = None if not hasattr(__pygame, 'SYSTEM_CURSOR_NO') else __pygame.SYSTEM_CURSOR_NO CURSOR_SIZEALL = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZEALL') else __pygame.SYSTEM_CURSOR_SIZEALL CURSOR_SIZENESW = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZENESW') else __pygame.SYSTEM_CURSOR_SIZENESW CURSOR_SIZENS = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZENS') else __pygame.SYSTEM_CURSOR_SIZENS CURSOR_SIZENWSE = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZENWSE') else __pygame.SYSTEM_CURSOR_SIZENWSE CURSOR_SIZEWE = None if not hasattr(__pygame, 'SYSTEM_CURSOR_SIZEWE') else __pygame.SYSTEM_CURSOR_SIZEWE CURSOR_WAIT = None if not hasattr(__pygame, 'SYSTEM_CURSOR_WAIT') else __pygame.SYSTEM_CURSOR_WAIT CURSOR_WAITARROW = None if not hasattr(__pygame, 'SYSTEM_CURSOR_WAITARROW') else __pygame.SYSTEM_CURSOR_WAITARROW # Events compatibility with lower pygame versions FINGERDOWN = -1 if not hasattr(__pygame, 'FINGERDOWN') else __pygame.FINGERDOWN FINGERMOTION = -1 if not hasattr(__pygame, 'FINGERMOTION') else __pygame.FINGERMOTION FINGERUP = -1 if not hasattr(__pygame, 'FINGERUP') else __pygame.FINGERUP
35.392593
113
0.75429
f2efb530b1ef641d5c0b78f798aa8a3ec91dbadc
3,184
py
Python
functions/constants.py
Katolus/functions
c4aff37231432ce6ef4ed6b37c8b5baaede5975a
[ "MIT" ]
4
2022-03-08T08:46:44.000Z
2022-03-19T07:52:11.000Z
functions/constants.py
Katolus/functions
c4aff37231432ce6ef4ed6b37c8b5baaede5975a
[ "MIT" ]
114
2021-10-30T05:48:54.000Z
2022-03-06T10:57:00.000Z
functions/constants.py
Katolus/functions
c4aff37231432ce6ef4ed6b37c8b5baaede5975a
[ "MIT" ]
null
null
null
import os import sys from enum import Enum from enum import unique from typing import List # Set system constants based on the current platform if sys.platform.startswith("win32"): DEFAULT_SYSTEM_CONFIG_PATH = os.path.join(os.environ["APPDATA"], "config") elif sys.platform.startswith("linux"): DEFAULT_SYSTEM_CONFIG_PATH = os.path.join(os.environ["HOME"], ".config") elif sys.platform.startswith("darwin"): DEFAULT_SYSTEM_CONFIG_PATH = os.path.join( os.environ["HOME"], "Library", "Application Support" ) else: DEFAULT_SYSTEM_CONFIG_PATH = os.path.join(os.environ["HOME"], "config") # System configuration PACKAGE_BASE_CONFIG_FOLDER = "ventress-functions" PACKAGE_CONFIG_DIR_PATH = os.path.join( DEFAULT_SYSTEM_CONFIG_PATH, PACKAGE_BASE_CONFIG_FOLDER ) DEFAULT_LOG_FILENAME = "functions.log" DEFAULT_LOG_FILEPATH = os.path.join(PACKAGE_CONFIG_DIR_PATH, DEFAULT_LOG_FILENAME) # Project constants PROJECT_VENDOR = "ventress" PROJECT_MARK = "ventress-functions"
25.269841
83
0.666143
f2f174769c76e5752b21c530463b089bffb53275
1,076
py
Python
mkmk/extend.py
tundra/mkmk
4ca7a3e337dcc3345fb01ea205ae05c397f396b0
[ "Apache-2.0" ]
null
null
null
mkmk/extend.py
tundra/mkmk
4ca7a3e337dcc3345fb01ea205ae05c397f396b0
[ "Apache-2.0" ]
null
null
null
mkmk/extend.py
tundra/mkmk
4ca7a3e337dcc3345fb01ea205ae05c397f396b0
[ "Apache-2.0" ]
null
null
null
#- Copyright 2014 GOTO 10. #- Licensed under the Apache License, Version 2.0 (see LICENSE). ## Utilities used for creating build extensions. from abc import ABCMeta, abstractmethod # Abstract superclass of the tool sets loaded implicitly into each context. # There can be many of these, one for each context. # Controller for this kind of extension. There is only one of these for each # kind of extension.
25.619048
76
0.737918
f2f29f0872d8843eb8b228cb03ec5eb0946af9b8
32,864
py
Python
tracklib/model/model.py
xueyuelei/tracklib
d33912baf1bebd1605d5e9c8dfc31484c96628cc
[ "MIT" ]
5
2020-03-04T11:36:19.000Z
2020-06-21T16:49:45.000Z
tracklib/model/model.py
xueyuelei/tracklib
d33912baf1bebd1605d5e9c8dfc31484c96628cc
[ "MIT" ]
null
null
null
tracklib/model/model.py
xueyuelei/tracklib
d33912baf1bebd1605d5e9c8dfc31484c96628cc
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ''' REFERENCES: [1] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, "Estimation with Applications to Tracking and Navigation," New York: John Wiley and Sons, Inc, 2001. [2] R. A. Singer, "Estimating Optimal Tracking Filter Performance for Manned Maneuvering Targets," in IEEE Transactions on Aerospace and Electronic Systems, vol. AES-6, no. 4, pp. 473-483, July 1970. [3] X. Rong Li and V. P. Jilkov, "Survey of maneuvering target tracking. Part I. Dynamic models," in IEEE Transactions on Aerospace and Electronic Systems, vol. 39, no. 4, pp. 1333-1364, Oct. 2003. [4] W. Koch, "Tracking and Sensor Data Fusion: Methodological Framework and Selected Applications," Heidelberg, Germany: Springer, 2014. [5] Mo Longbin, Song Xiaoquan, Zhou Yiyu, Sun Zhong Kang and Y. Bar-Shalom, "Unbiased converted measurements for tracking," in IEEE Transactions on Aerospace and Electronic Systems, vol. 34, no. 3, pp. 1023-1027, July 1998 ''' from __future__ import division, absolute_import, print_function __all__ = [ 'F_poly', 'F_singer', 'F_van_keuk', 'Q_poly_dc', 'Q_poly_dd', 'Q_singer', 'Q_van_keuk', 'H_pos_only', 'R_pos_only', 'F_cv', 'f_cv', 'f_cv_jac', 'Q_cv_dc', 'Q_cv_dd', 'H_cv', 'h_cv', 'h_cv_jac', 'R_cv', 'F_ca', 'f_ca', 'f_ca_jac', 'Q_ca_dc', 'Q_ca_dd', 'H_ca', 'h_ca', 'h_ca_jac', 'R_ca', 'F_ct', 'f_ct', 'f_ct_jac', 'Q_ct', 'h_ct', 'h_ct_jac', 'R_ct', 'convert_meas', 'model_switch', 'trajectory_cv', 'trajectory_ca', 'trajectory_ct', 'trajectory_generator', 'trajectory_with_pd', 'trajectory_to_meas' ] import numbers import numpy as np import scipy.linalg as lg import scipy.stats as st import scipy.special as sl from tracklib.utils import sph2cart, pol2cart def F_poly(order, axis, T): ''' This polynomial transition matrix is used with discretized continuous-time models as well as direct discrete-time models. see section 6.2 and 6.3 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. Returns ------- F : ndarray The state transition matrix under a linear dynamic model of the given order and axis. ''' assert (order >= 1) assert (axis >= 1) F_base = np.zeros((order, order)) tmp = np.arange(order) F_base[0, :] = T**tmp / sl.factorial(tmp) for row in range(1, order): F_base[row, row:] = F_base[0, :order - row] F = np.kron(np.eye(axis), F_base) return F def F_singer(axis, T, tau=20): ''' Get the singer model transition matrix, see section 8.2 in [1]. Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used.The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- F : ndarray The state transition matrix under a Gauss-Markov dynamic model of the given axis. ''' assert (axis >= 1) alpha = 1 / tau F_base = np.zeros((3, 3)) aT = alpha * T eaT = np.exp(-aT) F_base[0, 0] = 1 F_base[0, 1] = T F_base[0, 2] = (aT - 1 + eaT) * tau**2 F_base[1, 1] = 1 F_base[1, 2] = (1 - eaT) * tau F_base[2, 2] = eaT F = np.kron(np.eye(axis), F_base) return F def F_van_keuk(axis, T, tau=20): ''' Get the state transition matrix for the van Keuk dynamic model. This is a direct discrete-time model such that the acceleration advances in each dimension over time as a[k+1]=exp(-T/tau)a[k]+std*sqrt(1-exp(-2*T/tau))*v[k], see section 2.2.1 in [4] Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used.The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- F : ndarray The state transition matrix under a Gauss-Markov dynamic model of the given axis. ''' assert (axis >= 1) F_base = F_poly(3, 1, T) F_base[-1, -1] = np.exp(-T / tau) F = np.kron(np.eye(axis), F_base) return F def Q_poly_dc(order, axis, T, std): ''' Process noise covariance matrix used with discretized continuous-time models. see section 6.2 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list The standard deviation (square root of intensity) of continuous-time porcess noise Returns ------- Q : ndarray Process noise convariance ''' assert (order >= 1) assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis sel = np.arange(order - 1, -1, -1) col, row = np.meshgrid(sel, sel) Q_base = T**(col + row + 1) / (sl.factorial(col) * sl.factorial(row) * (col + row + 1)) Q = np.kron(np.diag(std)**2, Q_base) return Q def Q_poly_dd(order, axis, T, std, ht=0): ''' Process noise covariance matrix used with direct discrete-time models. see section 6.3 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list The standard deviation of discrete-time porcess noise ht : int ht means that the order of the noise is `ht` greater than the highest order of the state, e.g., if the highest order of state is acceleration, then ht=0 means that the noise is of the same order as the highest order of state, that is, the noise is acceleration and the model is DWPA, see section 6.3.3 in [1]. If the highest order is velocity, the ht=1 means the noise is acceleration and the model is DWNA, see section 6.3.2 in [1]. Returns ------- Q : ndarray Process noise convariance Notes ----- For the model to which the alpha filter applies, we have order=0, ht=2. Likewise, for the alpha-beta filter, order=1, ht=1 and for the alpha- beta-gamma filter, order=2, ht=0 ''' assert (order >= 1) assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis sel = np.arange(ht + order - 1, ht - 1, -1) L = T**sel / sl.factorial(sel) Q_base = np.outer(L, L) Q = np.kron(np.diag(std)**2, Q_base) return Q def Q_singer(axis, T, std, tau=20): ''' Process noise covariance matrix used with Singer models. see section 8.2 in [1] Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list std is the instantaneous standard deviation of the acceleration knowm as Ornstein-Uhlenbeck process, which can be obtained by assuming it to be 1. Equal to a maxmum acceleration a_M with probability p_M and -a_M with the same probability 2. Equal to zero with probability p_0 3. Uniformly distributed in [-a_M, a_M] with the remaining probability mass All parameters mentioned above are chosen by the designer. So the expected std^2 is (a_M^2 / 3)*(1 + 4*p_M - p_0) tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used.The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- Q : ndarray Process noise convariance ''' assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis alpha = 1 / tau aT = alpha * T eaT = np.exp(-aT) e2aT = np.exp(-2 * aT) q11 = tau**4 * (1 - e2aT + 2 * aT + 2 * aT**3 / 3 - 2 * aT**2 - 4 * aT * eaT) q12 = tau**3 * (e2aT + 1 - 2 * eaT + 2 * aT * eaT - 2 * aT + aT**2) q13 = tau**2 * (1 - e2aT - 2 * aT * eaT) q22 = tau**2 * (4 * eaT - 3 - e2aT + 2 * aT) q23 = tau * (e2aT + 1 - 2 * eaT) q33 = 1 - e2aT Q_base = np.array([[q11, q12, q13], [q12, q22, q23], [q13, q23, q33]], dtype=float) Q = np.kron(np.diag(std)**2, Q_base) return Q def Q_van_keuk(axis, T, std, tau=20): ''' Process noise covariance matrix for a Van Keuk dynamic model, see section 2.2.1 in [4] Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. T : float The time-duration of the propagation interval. std : number, list std is the instantaneous standard deviation of the acceleration knowm as Ornstein-Uhlenbeck process, which can be obtained by assuming it to be 1. Equal to a maxmum acceleration a_M with probability p_M and -a_M with the same probability 2. Equal to zero with probability p_0 3. Uniformly distributed in [-a_M, a_M] with the remaining probability mass All parameters mentioned above are chosen by the designer. So the expected std^2 is (a_M^2 / 3)*(1 + 4*p_M - p_0) tau : float The time constant of the target acceleration autocorrelation, that is, the decorrelation time is approximately 2*tau. A reasonable range of tau for Singer's model is between 5 and 20 seconds. Typical values of tau for aircraft are 20s for slow turn and 5s for an evasive maneuver. If this parameter is omitted, the default value of 20 is used. The time constant is assumed the same for all dimensions of motion, so this parameter is scalar. Returns ------- Q : ndarray Process noise convariance ''' assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis Q_base = np.diag([0., 0., 1.]) Q_base = (1 - np.exp(-2 * T / tau)) * Q_base Q = np.kron(np.diag(std)**2, Q_base) return Q def H_pos_only(order, axis): ''' Position-only measurement matrix is used with discretized continuous-time models as well as direct discrete-time models. see section 6.5 in [1]. Parameters ---------- order : int The order of the filter. If order=2, then it is constant velocity, 3 means constant acceleration, 4 means constant jerk, etc. axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. Returns ------- H : ndarray the measurement or obervation matrix ''' assert (order >= 1) assert (axis >= 1) H = np.eye(order * axis) H = H[::order] return H def R_pos_only(axis, std): ''' Position-only measurement noise covariance matrix and the noise of each axis is assumed to be uncorrelated. Parameters ---------- axis : int Motion directions in Cartesian coordinate. If axis=1, it means x-axis, 2 means x-axis and y-axis, etc. Returns ------- R : ndarray the measurement noise covariance matrix ''' assert (axis >= 1) if isinstance(std, numbers.Number): std = [std] * axis R = np.diag(std)**2 return R def trajectory_generator(record): ''' record = { 'interval': [1, 1], 'start': [ [0, 0, 0], [0, 5, 0] ], 'pattern': [ [ {'model': 'cv', 'length': 100, 'velocity': [250, 250, 0]}, {'model': 'ct', 'length': 25, 'turnrate': 30} ], [ {'model': 'cv', 'length': 100, 'velocity': [250, 250, 0]}, {'model': 'ct', 'length': 30, 'turnrate': 30, 'velocity': 30} ] ], 'noise': [ 10 * np.eye(3), 10 * np.eye(3) ], 'pd': [ 0.9, 0.9 ], 'entries': 2 } ''' dim, order, axis = 9, 3, 3 ca_sel = range(dim) acc_sel = range(2, dim, order) cv_sel = np.setdiff1d(ca_sel, acc_sel) ct_sel = np.setdiff1d(ca_sel, acc_sel) insert_sel = [2, 4, 6] interval = record['interval'] start = record['start'] pattern = record['pattern'] noise = record['noise'] entries = record['entries'] trajs_state = [] for i in range(entries): head = np.kron(start[i], [1., 0., 0.]) state = np.kron(start[i], [1., 0., 0.]).reshape(1, -1) for pat in pattern[i]: if pat['model'] == 'cv': ret, head_cv = trajectory_cv(head[cv_sel], interval[i], pat['length'], pat['velocity']) ret = np.insert(ret, insert_sel, 0, axis=1) head = ret[-1, ca_sel] state[-1, acc_sel] = 0 # set the acceleration of previous state to zero state[-1, cv_sel] = head_cv # change the velocity of previous state state = np.vstack((state, ret)) elif pat['model'] == 'ca': ret, head_ca = trajectory_ca(head, interval[i], pat['length'], pat['acceleration']) head = ret[-1, ca_sel] state[-1, ca_sel] = head_ca # change the acceleartion of previous state state = np.vstack((state, ret)) elif pat['model'] == 'ct': if 'velocity' in pat: ret, head_ct = trajectory_ct(head[ct_sel], interval[i], pat['length'], pat['turnrate'], pat['velocity']) else: ret, head_ct = trajectory_ct(head[ct_sel], interval[i], pat['length'], pat['turnrate']) ret = np.insert(ret, insert_sel, 0, axis=1) head = ret[-1, ca_sel] state[-1, acc_sel] = 0 state[-1, ct_sel] = head_ct state = np.vstack((state, ret)) else: raise ValueError('invalid model') trajs_state.append(state) # add noise trajs_meas = [] for i in range(entries): H = H_ca(axis) traj_len = trajs_state[i].shape[0] noi = st.multivariate_normal.rvs(cov=noise[i], size=traj_len) trajs_meas.append(np.dot(trajs_state[i], H.T) + noi) return trajs_state, trajs_meas
32.538614
222
0.549781
f2f2ed4004131258cff5093c7d766ecf35ed6781
848
py
Python
orders/migrations/0005_auto_20210619_0848.py
garrett-rh/Slice-of-a-Pizza
0e30e3a27b0e65e77cd52db1ef7db0470dea7a3f
[ "MIT" ]
2
2020-05-15T10:20:13.000Z
2021-04-03T12:38:37.000Z
orders/migrations/0005_auto_20210619_0848.py
garrett-rh/Slice-of-a-Pizza
0e30e3a27b0e65e77cd52db1ef7db0470dea7a3f
[ "MIT" ]
2
2020-05-15T10:39:42.000Z
2021-11-26T03:01:19.000Z
orders/migrations/0005_auto_20210619_0848.py
garrett-rh/Slice-of-a-Pizza
0e30e3a27b0e65e77cd52db1ef7db0470dea7a3f
[ "MIT" ]
1
2021-11-12T12:10:57.000Z
2021-11-12T12:10:57.000Z
# Generated by Django 3.2.4 on 2021-06-19 08:48 from django.db import migrations, models
29.241379
99
0.604953
f2f3e2812670f2833f39a5b2980f1ac2b7819f19
1,229
py
Python
benchbuild/engine.py
sturmianseq/benchbuild
e3cc1a24e877261e90baf781aa67a9d6f6528dac
[ "MIT" ]
11
2017-10-05T08:59:35.000Z
2021-05-29T01:43:07.000Z
benchbuild/engine.py
sturmianseq/benchbuild
e3cc1a24e877261e90baf781aa67a9d6f6528dac
[ "MIT" ]
326
2016-07-12T08:11:43.000Z
2022-03-28T07:10:11.000Z
benchbuild/engine.py
sturmianseq/benchbuild
e3cc1a24e877261e90baf781aa67a9d6f6528dac
[ "MIT" ]
13
2016-06-17T12:13:35.000Z
2022-01-04T16:09:12.000Z
""" Orchestrate experiment execution. """ import typing as tp import attr from benchbuild.experiment import Experiment from benchbuild.project import Project from benchbuild.utils import actions, tasks ExperimentCls = tp.Type[Experiment] Experiments = tp.List[ExperimentCls] ProjectCls = tp.Type[Project] Projects = tp.List[ProjectCls] ExperimentProject = tp.Tuple[ExperimentCls, ProjectCls] Actions = tp.Sequence[actions.Step] StepResults = tp.List[actions.StepResult]
25.604167
77
0.68511
f2f4e04a8614d8edbaff0777a5f1c47f01d09f5f
6,751
py
Python
misc_code/fcn_loss_layer.py
kbardool/mrcnn3
f4cbb1e34de97ab08558b56fb7362647436edbd7
[ "MIT" ]
7
2018-08-07T13:56:32.000Z
2021-04-06T11:07:20.000Z
misc_code/fcn_loss_layer.py
kbardool/Contextual-Inference-V2
f4cbb1e34de97ab08558b56fb7362647436edbd7
[ "MIT" ]
null
null
null
misc_code/fcn_loss_layer.py
kbardool/Contextual-Inference-V2
f4cbb1e34de97ab08558b56fb7362647436edbd7
[ "MIT" ]
1
2019-02-01T06:52:18.000Z
2019-02-01T06:52:18.000Z
""" Mask R-CNN Dataset functions and classes. Copyright (c) 2017 Matterport, Inc. Licensed under the MIT License (see LICENSE for details) Written by Waleed Abdulla """ import numpy as np import tensorflow as tf import keras.backend as KB import keras.layers as KL import keras.initializers as KI import keras.engine as KE import mrcnn.utils as utils from mrcnn.loss import smooth_l1_loss import pprint pp = pprint.PrettyPrinter(indent=2, width=100) ##----------------------------------------------------------------------- ## FCN loss ##----------------------------------------------------------------------- def fcn_loss_graph(target_masks, pred_masks): # def fcn_loss_graph(input): # target_masks, pred_masks = input """Mask binary cross-entropy loss for the masks head. target_masks: [batch, height, width, num_classes]. pred_masks: [batch, height, width, num_classes] float32 tensor """ # Reshape for simplicity. Merge first two dimensions into one. print('\n fcn_loss_graph ' ) print(' target_masks shape :', target_masks.get_shape()) print(' pred_masks shape :', pred_masks.get_shape()) mask_shape = tf.shape(target_masks) print(' mask_shape shape :', mask_shape.shape) target_masks = KB.reshape(target_masks, (-1, mask_shape[1], mask_shape[2])) print(' target_masks shape :', target_masks.shape) pred_shape = tf.shape(pred_masks) print(' pred_shape shape :', pred_shape.shape) pred_masks = KB.reshape(pred_masks, (-1, pred_shape[1], pred_shape[2])) print(' pred_masks shape :', pred_masks.get_shape()) # Compute binary cross entropy. If no positive ROIs, then return 0. # shape: [batch, roi, num_classes] # Smooth-L1 Loss loss = KB.switch(tf.size(target_masks) > 0, smooth_l1_loss(y_true=target_masks, y_pred=pred_masks), tf.constant(0.0)) loss = KB.mean(loss) loss = KB.reshape(loss, [1, 1]) print(' loss type is :', type(loss)) return loss ##----------------------------------------------------------------------- ## FCN loss for L2 Normalized graph ##----------------------------------------------------------------------- def fcn_norm_loss_graph(target_masks, pred_masks): ''' Mask binary cross-entropy loss for the masks head. target_masks: [batch, height, width, num_classes]. pred_masks: [batch, height, width, num_classes] float32 tensor ''' print(type(target_masks)) pp.pprint(dir(target_masks)) # Reshape for simplicity. Merge first two dimensions into one. print('\n fcn_norm_loss_graph ' ) print(' target_masks shape :', target_masks.shape) print(' pred_masks shape :', pred_masks.shape) print('\n L2 normalization ------------------------------------------------------') output_shape=KB.int_shape(pred_masks) print(' output shape is :' , output_shape, ' ', pred_masks.get_shape(), pred_masks.shape, tf.shape(pred_masks)) output_flatten = KB.reshape(pred_masks, (pred_masks.shape[0], -1, pred_masks.shape[-1]) ) output_norm1 = KB.l2_normalize(output_flatten, axis = 1) output_norm = KB.reshape(output_norm1, KB.shape(pred_masks) ) print(' output_flatten : ', KB.int_shape(output_flatten) , ' Keras tensor ', KB.is_keras_tensor(output_flatten) ) print(' output_norm1 : ', KB.int_shape(output_norm1) , ' Keras tensor ', KB.is_keras_tensor(output_norm1) ) print(' output_norm final : ', KB.int_shape(output_norm) , ' Keras tensor ', KB.is_keras_tensor(output_norm) ) pred_masks1 = output_norm print('\n L2 normalization ------------------------------------------------------') gauss_flatten = KB.reshape(target_masks, (target_masks.shape[0], -1, target_masks.shape[-1]) ) gauss_norm1 = KB.l2_normalize(gauss_flatten, axis = 1) gauss_norm = KB.reshape(gauss_norm1, KB.shape(target_masks)) print(' guass_flatten : ', KB.int_shape(gauss_flatten), 'Keras tensor ', KB.is_keras_tensor(gauss_flatten) ) print(' gauss_norm shape : ', KB.int_shape(gauss_norm1) , 'Keras tensor ', KB.is_keras_tensor(gauss_norm1) ) print(' gauss_norm final shape: ', KB.int_shape(gauss_norm) , 'Keras tensor ', KB.is_keras_tensor(gauss_norm) ) print(' complete') target_masks1 = gauss_norm mask_shape = tf.shape(target_masks1) print(' mask_shape shape :', mask_shape.shape) target_masks1 = KB.reshape(target_masks1, (-1, mask_shape[1], mask_shape[2])) print(' target_masks shape :', target_masks1.shape) pred_shape = tf.shape(pred_masks1) print(' pred_shape shape :', pred_shape.shape) pred_masks1 = KB.reshape(pred_masks1, (-1, pred_shape[1], pred_shape[2])) print(' pred_masks shape :', pred_masks1.get_shape()) # Compute binary cross entropy. If no positive ROIs, then return 0. # shape: [batch, roi, num_classes] # Smooth-L1 Loss loss = KB.switch(tf.size(target_masks1) > 0, smooth_l1_loss(y_true=target_masks1, y_pred=pred_masks1), tf.constant(0.0)) loss = KB.mean(loss) loss = KB.reshape(loss, [1, 1]) print(' loss type is :', type(loss)) return loss
40.915152
123
0.578877
f2f6b4c27e7561e29dbb147f768e0c58a7d09bb7
2,150
py
Python
mysticbit/plots.py
Connossor/mystic-bit
f57f471d3d154560d23bc9eff17fd5b8f284684c
[ "MIT" ]
6
2018-11-23T20:13:53.000Z
2019-02-25T15:54:55.000Z
mysticbit/plots.py
Connossor/mystic-bit
f57f471d3d154560d23bc9eff17fd5b8f284684c
[ "MIT" ]
null
null
null
mysticbit/plots.py
Connossor/mystic-bit
f57f471d3d154560d23bc9eff17fd5b8f284684c
[ "MIT" ]
11
2018-11-23T20:55:44.000Z
2021-12-20T17:25:24.000Z
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def plot_well_map(df_logs, fig_size=(10, 10)): """ Simple map of locations of nearby wells """ f, ax = plt.subplots(figsize=fig_size) df = df_logs.drop_duplicates(subset=['HACKANAME', 'X', 'Y']) plt.scatter(df['X'], df['Y']) plt.axis('scaled') for label, x, y in zip(df['HACKANAME'], df['X'], df['Y']): plt.annotate(label, xy=(x, y), xytext=(-10, 10), textcoords='offset points') return f, ax def make_log_plot(df_logs, well_name, cols=['GR', 'DT', 'CALI'], ztop=None, zbot=None, fig_size=(8, 12)): """ Single well log plot, both GR and Resistivity """ logs = df_logs[df_logs['HACKANAME'] == well_name] logs = logs.sort_values(by='TVDSS') if not ztop: ztop = logs.TVDSS.min() if not zbot: zbot = logs.TVDSS.max() f, ax = plt.subplots(nrows=1, ncols=len(cols), figsize=fig_size) for i in range(len(ax)): log_name = cols[i] ax[i].scatter(logs[log_name], logs['TVDSS'], marker='+') ax[i].set_xlabel(log_name) ax[i].set_ylim(ztop, zbot) ax[i].invert_yaxis() ax[i].grid() ax[i].locator_params(axis='x', nbins=3) if i > 0: ax[i].set_yticklabels([]) # ax[0].set_xlabel("GR") # ax[0].set_xlim(0, 150) # ax[1].set_xlabel("RESD") # ax[1].set_xscale('log') # ax[1].set_xlim(0.2, 2000) # ax[1].set_yticklabels([]) f.suptitle('Well: {}'.format(well_name), fontsize=14, y=0.94) return f, ax def add_predictions(ax, predictions): """ Add predicted bands onto plt axes""" # Scatter plot ax.scatter(predictions['value'], predictions['TVDSS'], marker='+') # Shaded bands tvds = predictions[predictions.model_name == 'high']['TVDSS'] x_hi = predictions[predictions.model_name == 'high']['value'] x_lo = predictions[predictions.model_name == 'low']['value'] ax.fill(np.concatenate([x_lo, x_hi[::-1]]), np.concatenate([tvds, tvds[::-1]]), alpha=0.5)
28.289474
105
0.58093
f2f8aa778931cc06d7071bcf8a708498a3154677
5,244
py
Python
cc_plugin_eustace/eustace_global_attrs.py
eustace-data/cc-plugin-eustace
4b44d287433b632ea6f859cd72d5dd4b8c361cee
[ "BSD-2-Clause" ]
null
null
null
cc_plugin_eustace/eustace_global_attrs.py
eustace-data/cc-plugin-eustace
4b44d287433b632ea6f859cd72d5dd4b8c361cee
[ "BSD-2-Clause" ]
null
null
null
cc_plugin_eustace/eustace_global_attrs.py
eustace-data/cc-plugin-eustace
4b44d287433b632ea6f859cd72d5dd4b8c361cee
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python """ cc_plugin_eustace.eustace_global_attrs Compliance Test Suite: Check core global attributes in EUSTACE files """ import os from netCDF4 import Dataset # Import base objects from compliance checker from compliance_checker.base import Result, BaseNCCheck, GenericFile # Restrict which vocabs will load (for efficiency) os.environ["ESSV_VOCABS_ACTIVE"] = "eustace-team" # Import checklib import checklib.register.nc_file_checks_register as check_package
46.821429
153
0.474256
f2fc68a089e1541439b963f873f1136d0c533af5
705
py
Python
final_project/machinetranslation/tests/tests.py
NicoFRizzo/xzceb-flask_eng_fr
71c8a4c970e7a179f496ff0960d5fae2bba0ffc1
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/tests.py
NicoFRizzo/xzceb-flask_eng_fr
71c8a4c970e7a179f496ff0960d5fae2bba0ffc1
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/tests.py
NicoFRizzo/xzceb-flask_eng_fr
71c8a4c970e7a179f496ff0960d5fae2bba0ffc1
[ "Apache-2.0" ]
null
null
null
import unittest import translator if __name__ == "__main__": unittest.main()
32.045455
66
0.695035
f2fc8f6f95ceeb8cf32d3eeed59de008b87d73f7
556
py
Python
src/appi/oop/classes/class_attributes.py
Kaju-Bubanja/APPI
011afc872a0055ff56001547be6da73017042ad5
[ "MIT" ]
null
null
null
src/appi/oop/classes/class_attributes.py
Kaju-Bubanja/APPI
011afc872a0055ff56001547be6da73017042ad5
[ "MIT" ]
null
null
null
src/appi/oop/classes/class_attributes.py
Kaju-Bubanja/APPI
011afc872a0055ff56001547be6da73017042ad5
[ "MIT" ]
null
null
null
s1 = Student("Harry", 12) # access instance variables print('Student:', s1.name, s1.age) # access class variable print('School name:', Student.school_name) # Modify instance variables s1.name = 'Jessa' s1.age = 14 print('Student:', s1.name, s1.age) # Modify class variables Student.school_name = 'XYZ School' print('School name:', Student.school_name)
20.592593
42
0.676259
f2fea27459e59001e49be2e7ed0478672dee266a
264
py
Python
clamor/rest/endpoints/__init__.py
TomSputz/Clamor
13222b90532938e6ebdbe8aea0430512e7d22817
[ "MIT" ]
15
2019-07-05T20:26:18.000Z
2020-09-18T12:44:16.000Z
clamor/rest/endpoints/__init__.py
TomSputz/Clamor
13222b90532938e6ebdbe8aea0430512e7d22817
[ "MIT" ]
7
2019-07-07T19:55:07.000Z
2019-08-20T22:07:31.000Z
clamor/rest/endpoints/__init__.py
TomSputz/Clamor
13222b90532938e6ebdbe8aea0430512e7d22817
[ "MIT" ]
6
2019-07-07T20:39:29.000Z
2020-11-06T10:12:20.000Z
# -*- coding: utf-8 -*- from . import base from .audit_log import * from .channel import * from .emoji import * from .gateway import * from .guild import * from .invite import * from .oauth import * from .user import * from .voice import * from .webhook import *
18.857143
24
0.69697
f2feb8df0aea648f82fd8f4f86ab95ad219d052f
1,878
py
Python
hamster2pdf.py
vleg1991/hamster2pdf
1dda22a39b65a0f24b76d278f3d708ac51d3c262
[ "MIT" ]
null
null
null
hamster2pdf.py
vleg1991/hamster2pdf
1dda22a39b65a0f24b76d278f3d708ac51d3c262
[ "MIT" ]
null
null
null
hamster2pdf.py
vleg1991/hamster2pdf
1dda22a39b65a0f24b76d278f3d708ac51d3c262
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import os import datetime import hamster.client import reports import argparse import pdfkit import gettext gettext.install('brainz', '../datas/translations/') # custom settings: reportTitle = "My Activities Report" activityFilter = "unfiled" # find dates: today = datetime.date.today() first = today.replace(day=1) previousLast = first - datetime.timedelta(days=1) previousFirst = previousLast.replace(day=1) # assign arguments: parser = argparse.ArgumentParser(description="export the hamster database to pdf") parser.add_argument("--thismonth", action="store_true", help="export this month's records") parser.add_argument("--lastmonth", action="store_true", help="export last month's records") parser.add_argument("-s", dest="startDate", default=today, help="start date (default: today)", type=valid_date) parser.add_argument("-e", dest="endDate", default=today, help="end date (default: today)", type=valid_date) parser.add_argument("-o", dest="reportFile", default="report.pdf", help="output file (default: report.pdf)") # parse arguments: args = parser.parse_args() if args.thismonth: args.startDate = first args.endDate = today if args.lastmonth: args.startDate = previousFirst args.endDate = previousLast # prepare filenames: htmlFilename = os.path.splitext(args.reportFile)[0]+".html" pdfFilename = os.path.splitext(args.reportFile)[0]+".pdf" storage = hamster.client.Storage() facts = storage.get_facts(args.startDate, args.endDate) # generate report reports.simple(facts, args.startDate, args.endDate, htmlFilename) # convert .html to .pdf file: pdfkit.from_file(htmlFilename, pdfFilename)
27.617647
111
0.736954
f2ff24739f7d32b20b931df9776f794aac82539a
589
py
Python
SingleTon.py
SuperLeis/meituan
71d521826bc50cb8e7bee5617f84e2c26dce1394
[ "MIT" ]
1
2020-05-02T14:30:18.000Z
2020-05-02T14:30:18.000Z
SingleTon.py
SuperLeis/meituan
71d521826bc50cb8e7bee5617f84e2c26dce1394
[ "MIT" ]
null
null
null
SingleTon.py
SuperLeis/meituan
71d521826bc50cb8e7bee5617f84e2c26dce1394
[ "MIT" ]
null
null
null
from functools import wraps # created by PL # git hello world if __name__ == '__main__': s = SingleTon(1) t = SingleTon(2) print (s is t) print (s.a, t.a) print (s.val, t.val) print ('test') print ("git test")
19.633333
50
0.550085
840025939ea1c2adbcc0cc3524f18c7230eb6fad
374
py
Python
exercicios-python/ex031.py
anavesilva/python-introduction
d85fb9381e348262584fd2942e4818ee822adbe5
[ "MIT" ]
null
null
null
exercicios-python/ex031.py
anavesilva/python-introduction
d85fb9381e348262584fd2942e4818ee822adbe5
[ "MIT" ]
null
null
null
exercicios-python/ex031.py
anavesilva/python-introduction
d85fb9381e348262584fd2942e4818ee822adbe5
[ "MIT" ]
null
null
null
# Custo da viagem distancia = float(input('Qual a distncia da sua viagem? ')) valor1 = distancia * 0.5 valor2 = distancia * 0.45 print('Voc est prestes a comear uma viagem de {}Km/h.'.format(distancia)) if distancia <= 200: print('O preo de sua passagem ser de R${:.2f}.'.format(valor1)) else: print('O preo de sua passagem ser de R${:.2f}.'.format(valor2))
37.4
76
0.687166
8401761cbdcacb5f4d5eb5531d513247beb5261b
10,254
py
Python
datatest/differences.py
ajhynes7/datatest
78742e98de992807286655f5685a2dc33a7b452e
[ "Apache-2.0" ]
277
2016-05-12T13:22:49.000Z
2022-03-11T00:18:32.000Z
datatest/differences.py
ajhynes7/datatest
78742e98de992807286655f5685a2dc33a7b452e
[ "Apache-2.0" ]
57
2016-05-18T01:03:32.000Z
2022-02-17T13:48:43.000Z
datatest/differences.py
ajhynes7/datatest
78742e98de992807286655f5685a2dc33a7b452e
[ "Apache-2.0" ]
16
2016-05-22T11:35:19.000Z
2021-12-01T19:41:42.000Z
"""Difference classes.""" __all__ = [ 'BaseDifference', 'Missing', 'Extra', 'Invalid', 'Deviation', ] from cmath import isnan from datetime import timedelta from ._compatibility.builtins import * from ._compatibility import abc from ._compatibility.contextlib import suppress from ._utils import _make_token from ._utils import pretty_timedelta_repr NOVALUE = _make_token( 'NoValueType', '<no value>', 'Token to mark when a value does not exist.', truthy=False, ) NANTOKEN = _make_token( 'NanTokenType', '<nan token>', 'Token for comparing differences that contain not-a-number values.', ) def _nan_to_token(value): """Return NANTOKEN if *value* is NaN else return value unchanged.""" if isinstance(value, tuple): return tuple(func(x) for x in value) return func(value) def _safe_isnan(x): """Wrapper for isnan() so it won't fail on non-numeric values.""" try: return isnan(x) except TypeError: return False def _slice_datetime_repr_prefix(obj_repr): """Takes a default "datetime", "date", or "timedelta" repr and returns it with the module prefix sliced-off:: >>> _slice_datetime_repr_prefix('datetime.date(2020, 12, 25)') 'date(2020, 12, 25)' """ # The following implementation (using "startswith" and "[9:]") # may look clumsy but it can run up to 10 times faster than a # more concise "re.compile()" and "regex.sub()" approach. In # some situations, this function can get called many, many # times. DON'T GET CLEVER--KEEP THIS FUNCTION FAST. if obj_repr.startswith('datetime.datetime(') \ or obj_repr.startswith('datetime.date(') \ or obj_repr.startswith('datetime.timedelta('): return obj_repr[9:] return obj_repr class Deviation(BaseDifference): """Created when a quantative value deviates from its expected value. In the following example, the dictionary item ``'C': 33`` does not satisfy the required item ``'C': 30``:: data = {'A': 10, 'B': 20, 'C': 33} requirement = {'A': 10, 'B': 20, 'C': 30} datatest.validate(data, requirement) Running this example raises the following error: .. code-block:: none :emphasize-lines: 2 ValidationError: does not satisfy mapping requirement (1 difference): { 'C': Deviation(+3, 30), } """ __slots__ = ('_deviation', '_expected') def __repr__(self): cls_name = self.__class__.__name__ deviation = self._deviation if _safe_isnan(deviation): deviation_repr = "float('nan')" elif isinstance(deviation, timedelta): deviation_repr = pretty_timedelta_repr(deviation) else: try: deviation_repr = '{0:+}'.format(deviation) # Apply +/- sign except (TypeError, ValueError): deviation_repr = repr(deviation) expected = self._expected if _safe_isnan(expected): expected_repr = "float('nan')" else: expected_repr = repr(expected) if expected_repr.startswith('datetime.'): expected_repr = _slice_datetime_repr_prefix(expected_repr) return '{0}({1}, {2})'.format(cls_name, deviation_repr, expected_repr) def _make_difference(actual, expected, show_expected=True): """Returns an appropriate difference for *actual* and *expected* values that are known to be unequal. Setting *show_expected* to False, signals that the *expected* argument should be omitted when creating an Invalid difference (this is useful for reducing duplication when validating data against a single function or object). """ if actual is NOVALUE: return Missing(expected) if expected is NOVALUE: return Extra(actual) if isinstance(expected, bool) or isinstance(actual, bool): if show_expected: return Invalid(actual, expected) return Invalid(actual) try: deviation = actual - expected return Deviation(deviation, expected) except (TypeError, ValueError): if show_expected: return Invalid(actual, expected) return Invalid(actual)
29.048159
91
0.610396
8401c1577e1e3475bf83b16d801193d6422761d2
2,735
py
Python
dashboard/urls.py
playfulMIT/kimchi
66802cc333770932a8c8b1a44ea5d235d916a8f1
[ "MIT" ]
null
null
null
dashboard/urls.py
playfulMIT/kimchi
66802cc333770932a8c8b1a44ea5d235d916a8f1
[ "MIT" ]
16
2019-12-10T19:40:27.000Z
2022-02-10T11:51:06.000Z
dashboard/urls.py
playfulMIT/kimchi
66802cc333770932a8c8b1a44ea5d235d916a8f1
[ "MIT" ]
null
null
null
from django.conf.urls import include, url, re_path from rest_framework import routers from . import views urlpatterns = [ re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/versiontime", views.get_last_processed_time), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/players", views.get_player_list), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/sessions", views.get_player_to_session_map), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/puzzles", views.get_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/puzzlekeys", views.get_puzzle_keys), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/snapshotsperpuzzle", views.get_snapshot_metrics), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/attempted", views.get_attempted_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/completed", views.get_completed_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/timeperpuzzle", views.get_time_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/funnelperpuzzle", views.get_funnel_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/shapesperpuzzle", views.get_shapes_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/modesperpuzzle", views.get_modes_per_puzzle), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/levelsofactivity", views.get_levels_of_activity), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/sequencebetweenpuzzles", views.get_sequence_between_puzzles), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/mloutliers", views.get_machine_learning_outliers), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/persistence", views.get_persistence_by_attempt_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/puzzlepersistence", views.get_persistence_by_puzzle_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/insights", views.get_insights), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/difficulty", views.get_puzzle_difficulty_mapping), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/misconceptions", views.get_misconceptions_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/competency", views.get_competency_data), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/report/(?P<start>[0-9]+)/(?P<end>[0-9]+)", views.get_report_summary), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/report", views.get_report_summary), re_path(r"^api/dashboard/(?P<slug>[a-zA-Z0-9-_]+)/(?P<player>[a-zA-Z0-9-_.]+)/(?P<level>[a-zA-Z0-9-_.]+)/replayurls", views.get_replay_urls), re_path(r"^(?P<slug>[a-zA-Z0-9-_]+)/dashboard/", views.dashboard), re_path(r"^(?P<slug>[a-zA-Z0-9-_]+)/thesisdashboard/", views.thesis_dashboard) ]
80.441176
145
0.697623
8403354322f3d276144123191c8e910a521e71d2
1,945
py
Python
VQ2D/vq2d/baselines/predictor.py
emulhall/episodic-memory
27bafec6e09c108f0efe5ac899eabde9d1ac40cc
[ "MIT" ]
27
2021-10-16T02:39:17.000Z
2022-03-31T11:16:11.000Z
VQ2D/vq2d/baselines/predictor.py
emulhall/episodic-memory
27bafec6e09c108f0efe5ac899eabde9d1ac40cc
[ "MIT" ]
5
2022-03-23T04:53:36.000Z
2022-03-29T23:39:07.000Z
VQ2D/vq2d/baselines/predictor.py
emulhall/episodic-memory
27bafec6e09c108f0efe5ac899eabde9d1ac40cc
[ "MIT" ]
13
2021-11-25T19:17:29.000Z
2022-03-25T14:01:47.000Z
from typing import Any, Dict, List, Sequence import numpy as np import torch from detectron2.engine import DefaultPredictor
38.9
93
0.519794
84050b8c0b169a6bad0d62fb6d1d81572077e370
109
py
Python
user_agent2/__init__.py
dytttf/user_agent2
311bfc5c820ed8233207f57f27bfd7b789040d9d
[ "MIT" ]
null
null
null
user_agent2/__init__.py
dytttf/user_agent2
311bfc5c820ed8233207f57f27bfd7b789040d9d
[ "MIT" ]
1
2022-02-08T11:58:15.000Z
2022-02-08T16:59:37.000Z
user_agent2/__init__.py
dytttf/user_agent2
311bfc5c820ed8233207f57f27bfd7b789040d9d
[ "MIT" ]
3
2021-11-21T22:47:43.000Z
2022-02-15T00:45:40.000Z
from user_agent2.base import ( generate_user_agent, generate_navigator, generate_navigator_js, )
18.166667
30
0.761468
840519afb7f020a56b84911fb8113394b9946381
7,626
py
Python
mutagene/benchmark/multiple_benchmark.py
neksa/pymutagene
1122d64a5ab843a4960124933f78f3c2e388a792
[ "CC0-1.0" ]
3
2020-05-18T07:00:46.000Z
2022-02-20T02:55:48.000Z
mutagene/benchmark/multiple_benchmark.py
neksa/pymutagene
1122d64a5ab843a4960124933f78f3c2e388a792
[ "CC0-1.0" ]
31
2020-03-13T16:28:34.000Z
2021-02-27T22:12:15.000Z
mutagene/benchmark/multiple_benchmark.py
neksa/pymutagene
1122d64a5ab843a4960124933f78f3c2e388a792
[ "CC0-1.0" ]
3
2020-03-24T20:01:44.000Z
2020-11-26T17:30:39.000Z
import glob import random import uuid import numpy as np from multiprocessing import Pool from sklearn.metrics import ( recall_score, precision_score, accuracy_score, f1_score, mean_squared_error) from mutagene.io.profile import read_profile_file, write_profile, read_signatures from mutagene.signatures.identify import NegLogLik from mutagene.benchmark.deconstructsigs import deconstruct_sigs_custom from mutagene.benchmark.generate_benchmark import * # from mutagene.identify import decompose_mutational_profile_counts
35.142857
141
0.560976
8406877949c3d33a1b17a8c7fd596cba40c180cf
3,542
py
Python
Restaurant_Finder_App/restaurant_finder_app/restaurant_finder_app/restaurant/migrations/0001_initial.py
midhun3112/restaurant_locator
6ab5e906f26476352176059a8952c2c3f5b127bf
[ "Apache-2.0" ]
null
null
null
Restaurant_Finder_App/restaurant_finder_app/restaurant_finder_app/restaurant/migrations/0001_initial.py
midhun3112/restaurant_locator
6ab5e906f26476352176059a8952c2c3f5b127bf
[ "Apache-2.0" ]
null
null
null
Restaurant_Finder_App/restaurant_finder_app/restaurant_finder_app/restaurant/migrations/0001_initial.py
midhun3112/restaurant_locator
6ab5e906f26476352176059a8952c2c3f5b127bf
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-01 13:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
38.5
168
0.559006
8407722043fe4e1043792c735a7c99de2eae2b6e
1,807
py
Python
ckl/run.py
damianbrunold/checkerlang-py
97abe5eda5f692ef61acf906a5f596c65688b582
[ "MIT" ]
null
null
null
ckl/run.py
damianbrunold/checkerlang-py
97abe5eda5f692ef61acf906a5f596c65688b582
[ "MIT" ]
null
null
null
ckl/run.py
damianbrunold/checkerlang-py
97abe5eda5f692ef61acf906a5f596c65688b582
[ "MIT" ]
null
null
null
import argparse import os import sys from ckl.values import ( ValueList, ValueString, NULL ) from ckl.errors import ( CklSyntaxError, CklRuntimeError ) from ckl.interpreter import Interpreter if __name__ == "__main__": main()
28.234375
72
0.633094
840a373b87a5269d4b1deb705abae42b6703a996
21,190
py
Python
Justice-Engine-source/security_monkey/alerters/custom/JusticeEngine.py
sendgrid/JusticeEngine
9b39618c836bfcb120db5fb75557cc45c0105e9f
[ "MIT" ]
1
2019-03-27T18:52:54.000Z
2019-03-27T18:52:54.000Z
Justice-Engine-source/security_monkey/alerters/custom/JusticeEngine.py
sendgrid/JusticeEngine
9b39618c836bfcb120db5fb75557cc45c0105e9f
[ "MIT" ]
4
2018-08-17T19:10:05.000Z
2018-11-16T16:46:04.000Z
Justice-Engine-source/security_monkey/alerters/custom/JusticeEngine.py
sendgrid/JusticeEngine
9b39618c836bfcb120db5fb75557cc45c0105e9f
[ "MIT" ]
2
2018-10-24T19:19:52.000Z
2018-11-16T16:38:23.000Z
import datetime import fnmatch import hashlib import json import time import arrow import os from botocore.exceptions import ClientError from boto.s3.key import Key from security_monkey.alerters import custom_alerter from security_monkey.common.sts_connect import connect from security_monkey import app, db from security_monkey.datastore import Account from security_monkey.task_scheduler.alert_scheduler import schedule_krampus_alerts
39.313544
131
0.612081
840ab1d9437aeb791d935b51fa2d0357a65758ff
623
py
Python
bot/markups/inline_keyboards.py
Im-zeus/Stickers
f2484a1ecc9a3e4a2029eaadbde4ae1b0fe74536
[ "MIT" ]
44
2018-10-30T14:47:14.000Z
2022-03-26T15:17:52.000Z
bot/markups/inline_keyboards.py
Im-zeus/Stickers
f2484a1ecc9a3e4a2029eaadbde4ae1b0fe74536
[ "MIT" ]
37
2018-11-09T11:51:15.000Z
2021-12-27T15:08:48.000Z
bot/markups/inline_keyboards.py
Im-zeus/Stickers
f2484a1ecc9a3e4a2029eaadbde4ae1b0fe74536
[ "MIT" ]
38
2019-03-27T21:12:23.000Z
2022-01-08T07:57:39.000Z
# noinspection PyPackageRequirements from telegram import InlineKeyboardMarkup, InlineKeyboardButton
29.666667
71
0.658106
840d053d29d25ef335ed6bf8148849bf05df3d8b
596
py
Python
guitar-package/guitar/guitar/fetcher/__init__.py
django-stars/guitar
9bddfd2d7b555c97dd9470b458a5f43bd805b026
[ "MIT" ]
null
null
null
guitar-package/guitar/guitar/fetcher/__init__.py
django-stars/guitar
9bddfd2d7b555c97dd9470b458a5f43bd805b026
[ "MIT" ]
null
null
null
guitar-package/guitar/guitar/fetcher/__init__.py
django-stars/guitar
9bddfd2d7b555c97dd9470b458a5f43bd805b026
[ "MIT" ]
null
null
null
import urllib2 import json FAKE_PACKAGES = ( 'south', 'django-debug-toolbar', 'django-extensions', 'django-social-auth', ) fetcher = GuitarWebAPI('http://localhost:8000/api/v1/')
20.551724
55
0.587248
840d5087c07149f28ccd99ef85cfdb7e07ab4198
1,005
py
Python
src/deterministicpasswordgenerator/compile.py
jelford/deterministic-password-generator
ad839a2e0d82e1742227a686c248d2ad03ef2fc1
[ "MIT" ]
1
2016-08-22T22:48:50.000Z
2016-08-22T22:48:50.000Z
src/deterministicpasswordgenerator/compile.py
jelford/deterministic-password-generator
ad839a2e0d82e1742227a686c248d2ad03ef2fc1
[ "MIT" ]
null
null
null
src/deterministicpasswordgenerator/compile.py
jelford/deterministic-password-generator
ad839a2e0d82e1742227a686c248d2ad03ef2fc1
[ "MIT" ]
null
null
null
import zipfile from getpass import getpass import os import stat import tempfile from os import path from .crypto import encrypt
34.655172
120
0.769154
840ed8b2d962e67e5075227c8b5fb7a2d2b1513b
553
py
Python
python/dp/min_cost_climbing_stairs.py
googege/algo-learn
054d05e8037005c5810906d837de889108dad107
[ "MIT" ]
153
2020-09-24T12:46:51.000Z
2022-03-31T21:30:44.000Z
python/dp/min_cost_climbing_stairs.py
googege/algo-learn
054d05e8037005c5810906d837de889108dad107
[ "MIT" ]
null
null
null
python/dp/min_cost_climbing_stairs.py
googege/algo-learn
054d05e8037005c5810906d837de889108dad107
[ "MIT" ]
35
2020-12-22T11:07:06.000Z
2022-03-09T03:25:08.000Z
from typing import List #
26.333333
62
0.529837
840f7e43205d6e7a06e7d699111b144ac79f0338
10,289
py
Python
pages/graph.py
lmason98/PyGraph
22d734cfd97333578c91ba4e331716df0aec668e
[ "MIT" ]
null
null
null
pages/graph.py
lmason98/PyGraph
22d734cfd97333578c91ba4e331716df0aec668e
[ "MIT" ]
null
null
null
pages/graph.py
lmason98/PyGraph
22d734cfd97333578c91ba4e331716df0aec668e
[ "MIT" ]
null
null
null
""" File: pages/page.py Author: Luke Mason Description: Main part of the application, the actual graph page. """ # Application imports from message import log, error, success from settings import APP_NAME, COLOR, FONT, FONT_SIZE, SCREEN_WIDTH, SCREEN_HEIGHT, WIDTH, HEIGHT, PAD, _QUIT from sprites.vertex import Vertex from sprites.edge import Edge from pages.page import Page from graph import Graph as G # Pygame imports from pygame import draw, sprite, event, mouse, display, init, key, MOUSEBUTTONUP, MOUSEBUTTONDOWN, MOUSEMOTION, QUIT, \ KEYDOWN, K_BACKSPACE, K_DELETE, KMOD_SHIFT # Python imports from math import atan2, degrees, cos, sin
28.035422
119
0.666051
8412473069d247b24941bba95ee50eaf3af4a33f
521
py
Python
tests/forked/test_update.py
rarity-adventure/rarity-names
e940b8bea296823faf003ecb9ab8735820ff54d1
[ "MIT" ]
null
null
null
tests/forked/test_update.py
rarity-adventure/rarity-names
e940b8bea296823faf003ecb9ab8735820ff54d1
[ "MIT" ]
null
null
null
tests/forked/test_update.py
rarity-adventure/rarity-names
e940b8bea296823faf003ecb9ab8735820ff54d1
[ "MIT" ]
2
2021-09-22T01:34:17.000Z
2022-02-09T06:04:51.000Z
import brownie
32.5625
69
0.662188
8413787081f15c4a41a8417aa64436712a8f0d85
603
py
Python
pakcrack/__init__.py
Alpha-Demon404/RE-14
b5b46a9f0eee218f2a642b615c77135c33c6f4ad
[ "MIT" ]
39
2020-02-26T09:44:36.000Z
2022-03-23T00:18:25.000Z
pakcrack/__init__.py
B4BY-DG/reverse-enginnering
b5b46a9f0eee218f2a642b615c77135c33c6f4ad
[ "MIT" ]
15
2020-05-14T10:07:26.000Z
2022-01-06T02:55:32.000Z
pakcrack/__init__.py
B4BY-DG/reverse-enginnering
b5b46a9f0eee218f2a642b615c77135c33c6f4ad
[ "MIT" ]
41
2020-03-16T22:36:38.000Z
2022-03-17T14:47:19.000Z
# Filenames : <tahm1d> # Python bytecode : 2.7 # Time decompiled : Thu Sep 10 23:29:38 2020 # Selector <module> in line 4 file <tahm1d> # Timestamp in code: 2020-09-02 17:33:14 import os, sys, time from os import system from time import sleep if __name__ == '__main__': menu()
21.535714
101
0.623549