repo_name
stringlengths 7
111
| __id__
int64 16.6k
19,705B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
151
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_url
stringlengths 26
130
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 14.6k
687M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 12
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
10.2M
⌀ | gha_stargazers_count
int32 0
178k
⌀ | gha_forks_count
int32 0
88.9k
⌀ | gha_open_issues_count
int32 0
2.72k
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 10
2.95M
| src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 10
2.95M
| extension
stringclasses 19
values | num_repo_files
int64 1
202k
| filename
stringlengths 4
112
| num_lang_files
int64 1
202k
| alphanum_fraction
float64 0.26
0.89
| alpha_fraction
float64 0.2
0.89
| hex_fraction
float64 0
0.09
| num_lines
int32 1
93.6k
| avg_line_length
float64 4.57
103
| max_line_length
int64 7
931
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
raft-tech/cfgov-refresh | 5,755,256,192,655 | 93e50273e3c0db0ec4b679380815727d779b5540 | fa38abb2f030c8e22c98c71f66ffd950a6b70c60 | /cfgov/data_research/views.py | 705d464371a2e37ef685b49a384955abb03b54c5 | [
"CC0-1.0"
]
| permissive | https://github.com/raft-tech/cfgov-refresh | 5a06619ccd59f9799829a9abb976ea5ae059715a | 7c63c31fd6bb95ed4f7d368f1e1252175f0c71ca | refs/heads/my-money-calendar | 2023-08-22T17:43:46.716172 | 2020-09-21T18:36:46 | 2020-09-21T18:36:46 | 236,096,029 | 4 | 0 | CC0-1.0 | true | 2023-09-06T00:46:04 | 2020-01-24T22:44:07 | 2020-09-21T18:36:54 | 2023-09-06T00:46:03 | 631,509 | 3 | 0 | 337 | Python | false | false | import datetime
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from data_research.models import (
County, CountyMortgageData, MetroArea, MortgageMetaData, MSAMortgageData,
NationalMortgageData, NonMSAMortgageData, State, StateMortgageData
)
DAYS_LATE_RANGE = ['30-89', '90']
class MetaData(APIView):
"""
View for delivering mortgage metadata based on latest data update.
"""
renderer_classes = (JSONRenderer,)
def get(self, request, meta_name):
try:
record = MortgageMetaData.objects.get(name=meta_name)
except MortgageMetaData.DoesNotExist:
return Response("No metadata object found.")
meta_json = record.json_value
return Response(meta_json)
class TimeSeriesNational(APIView):
"""
View for delivering national time-series data
from the mortgage performance dataset.
"""
renderer_classes = (JSONRenderer,) # , rfc_renderers.CSVRenderer)
def get(self, request, days_late):
if days_late not in DAYS_LATE_RANGE:
return Response("Unknown delinquency range")
records = NationalMortgageData.objects.all()
data = {'meta': {'name': 'United States',
'fips_type': 'national'},
'data': [record.time_series(days_late)
for record in records]}
return Response(data)
class TimeSeriesData(APIView):
"""
View for delivering geo-based time-series data
from the mortgage performance dataset.
"""
renderer_classes = (JSONRenderer,)
def get(self, request, days_late, fips):
"""
Return a FIPS-based slice of base data as a json timeseries.
"""
if days_late not in DAYS_LATE_RANGE:
return Response("Unknown delinquency range")
reference_lists = {
entry: MortgageMetaData.objects.get(name=entry).json_value
for entry in ['allowlist', 'msa_fips', 'non_msa_fips']}
if fips not in reference_lists['allowlist']:
return Response("FIPS code not found or not valid.")
if len(fips) == 2:
state = State.objects.get(fips=fips)
records = StateMortgageData.objects.filter(
fips=fips)
data = {'meta': {'fips': fips,
'name': state.name,
'fips_type': 'state'},
'data': [record.time_series(days_late)
for record in records]}
return Response(data)
if 'non' in fips:
records = NonMSAMortgageData.objects.filter(
fips=fips)
data = {'meta': {'fips': fips,
'name': "Non-metro area of {}".format(
records.first().state.name),
'fips_type': 'non_msa'},
'data': [record.time_series(days_late)
for record in records]}
return Response(data)
if fips in reference_lists['msa_fips']:
metro_area = MetroArea.objects.get(fips=fips, valid=True)
records = MSAMortgageData.objects.filter(fips=fips)
data = {'meta': {'fips': fips,
'name': metro_area.name,
'fips_type': 'msa'},
'data': [record.time_series(days_late)
for record in records]}
return Response(data)
else: # must be a county request
try:
county = County.objects.get(fips=fips, valid=True)
except County.DoesNotExist:
return Response("County is below display threshold.")
records = CountyMortgageData.objects.filter(fips=fips)
name = "{}, {}".format(county.name, county.state.abbr)
data = {'meta': {'fips': fips,
'name': name,
'fips_type': 'county'},
'data': [record.time_series(days_late)
for record in records]}
return Response(data)
def validate_year_month(year_month):
"""Trap non-integers, malformatted entries, and out-of-range dates."""
current_year = datetime.date.today().year
split = year_month.split('-')
if len(split) != 2:
return None
try:
year = int(split[0])
month = int(split[1])
except ValueError:
return None
if year > current_year or month not in range(1, 13):
return None
if year < 1998:
return None
return datetime.date(year, month, 1)
class MapData(APIView):
"""
View for delivering geo-based map data by date
from the mortgage performance dataset.
"""
renderer_classes = (JSONRenderer,)
def get(self, request, days_late, geo, year_month):
date = validate_year_month(year_month)
if date is None:
return Response("Invalid year-month pair")
if days_late not in DAYS_LATE_RANGE:
return Response("Unknown delinquency range")
geo_dict = {
'national':
{'queryset': NationalMortgageData.objects.get(date=date),
'fips_type': 'nation',
'geo_obj': ''},
'states':
{'queryset': StateMortgageData.objects.filter(
date=date),
'fips_type': 'state',
'geo_obj': 'state'},
'counties':
{'queryset': CountyMortgageData.objects.filter(
date=date, county__valid=True),
'fips_type': 'county',
'geo_obj': 'county'},
'metros':
{'queryset': MSAMortgageData.objects.filter(
date=date),
'fips_type': 'msa',
'geo_obj': 'msa'},
}
if geo not in geo_dict:
return Response("Unkown geographic unit")
nat_records = geo_dict['national']['queryset']
nat_data_series = nat_records.time_series(days_late)
if geo == 'national':
payload = {'meta': {'fips_type': geo_dict[geo]['fips_type'],
'date': '{}'.format(date)},
'data': {}}
nat_data_series.update({'name': 'United States'})
del(nat_data_series['date'])
payload['data'].update(nat_data_series)
else:
records = geo_dict[geo]['queryset']
payload = {'meta': {'fips_type': geo_dict[geo]['fips_type'],
'date': '{}'.format(date),
'national_average': nat_data_series['value']},
'data': {}}
for record in records:
data_series = record.time_series(days_late)
geo_parent = getattr(record, geo_dict[geo]['geo_obj'])
if geo == 'counties':
name = "{}, {}".format(
geo_parent.name, geo_parent.state.abbr)
else:
name = geo_parent.name
data_series.update(
{'name': name})
del(data_series['date'])
payload['data'].update({record.fips: data_series})
if geo == 'metros':
for metro in MetroArea.objects.filter(valid=False):
payload['data'][metro.fips]['value'] = None
for record in NonMSAMortgageData.objects.filter(date=date):
non_data_series = record.time_series(days_late)
if record.state.non_msa_valid is False:
non_data_series['value'] = None
non_name = "Non-metro area of {}".format(record.state.name)
non_data_series.update({'name': non_name})
del non_data_series['date']
payload['data'].update({record.fips: non_data_series})
return Response(payload)
| UTF-8 | Python | false | false | 8,153 | py | 1,557 | views.py | 998 | 0.52447 | 0.522262 | 0 | 205 | 38.770732 | 79 |
ace-racer/ReviewAnalysis | 12,498,354,838,327 | 27e2db4b2ab30b8ff4e8f6f8691f8462fb9d02b3 | 54fc549a8af5bad5cfeb97af92a02448297f1ea9 | /src/gather_reviews/flipkart_crawler.py | a0433a94589599117c30ce98456d4f1c576bcd65 | []
| no_license | https://github.com/ace-racer/ReviewAnalysis | 35659ba09917a345edb3e3701aa12ae78602333b | 95fee3407791b5bbbc47619b06e603689e2249ed | refs/heads/master | 2020-07-26T06:10:05.563327 | 2019-10-26T14:58:12 | 2019-10-26T14:58:12 | 208,559,897 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import requests
from bs4 import BeautifulSoup
import sys
import os
import utils
from template import ReviewTemplate
from review_template_filler import ReviewTemplateFiller
MAX_REVIEW_PAGES = 50
def get_num_pages_of_reviews(html_soup):
num_pages = 1
navigation_details = html_soup.find("div", class_ = "_2zg3yZ _3KSYCY")
if navigation_details:
num_pages_span = navigation_details.find("span")
if num_pages_span:
num_pages_text = num_pages_span.text
num_pages = (num_pages_text.replace("Page 1 of", "").strip())
num_pages = int(num_pages.replace(",", ""))
if num_pages > MAX_REVIEW_PAGES:
num_pages = MAX_REVIEW_PAGES
print(f"Number of pages for this product is {num_pages}")
return num_pages
def save_reviews_for_flipkart_product(url, generated_files_base_location):
if "reviews" not in url:
print("The URL is not related to product reviews")
sys.exit(1)
generated_file_name = utils.get_product_name_from_url(url)
generated_file_location = generated_files_base_location + generated_file_name + ".json"
if os.path.exists(generated_file_location):
print("Reviews already obtained for {0}".format(url))
return generated_file_location
flipkart_review_template_filler = ReviewTemplateFiller()
path = os.path.abspath(__file__)
print(path)
dir_path = os.path.dirname(path)
parse_specs_loc = os.path.join(dir_path, "parse_specs", "flipkart_reviews_html_parse_spec.json")
print(parse_specs_loc)
html_parse_spec = utils.get_json_file_contents_as_dict(parse_specs_loc)
response = requests.get(url)
print(f"Response code: {response.status_code}")
html_soup = BeautifulSoup(response.text, 'html.parser')
num_pages = get_num_pages_of_reviews(html_soup)
# Get reviews from the first page
all_product_reviews = []
# Get reviews from the other pages with the reviews
current_page = 1
while current_page <= num_pages:
product_review_url = url + "&page=" + str(current_page)
response = requests.get(product_review_url)
if response.status_code == 200:
# print(f"Response code: {response.status_code}")
html_soup = BeautifulSoup(response.text, 'html.parser')
product_reviews = flipkart_review_template_filler.get_all_reviews_from_soup(html_soup, html_parse_spec)
all_product_reviews.extend(product_reviews)
current_page += 1
print("Number of reviews retrieved")
print(len(all_product_reviews))
utils.create_json_file_from_dict(generated_file_location, all_product_reviews)
return generated_file_location
if __name__ == "__main__":
# url="https://www.flipkart.com/samsung-super-6-108cm-43-inch-ultra-hd-4k-led-smart-tv/p/itmfdzq6khv2pcvz"
url="https://www.flipkart.com/samsung-galaxy-a70-black-128-gb/product-reviews/itmffhc79jwkwzrw?pid=MOBFFHC7GQZCF8YM"
save_reviews_for_flipkart_product(url, "../data/reviews_received/")
| UTF-8 | Python | false | false | 3,015 | py | 7 | flipkart_crawler.py | 4 | 0.68325 | 0.672305 | 0 | 78 | 37.628205 | 120 |
AtzeDeVries/medialib-restore | 9,646,496,596,798 | 6243bc2ea21550d5a3e314ea85f72344e17c6072 | a17d266cf304f4c254565103180342b108316918 | /index_tars.py | 00fd1992291d642fad6b3dff8a899bcbf42eb6b1 | [
"Apache-2.0"
]
| permissive | https://github.com/AtzeDeVries/medialib-restore | cfef655ee449efdf86482c8fecf01b0801547cf9 | 25d2f3e853dfb7a9cfd4af4c1423b85ef6ac9509 | refs/heads/master | 2021-01-18T20:24:03.110254 | 2014-08-29T13:30:46 | 2014-08-29T13:30:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
from lib import *
import os
path = '/data/tar/'
filelist = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f)) ]
for file in filelist:
try:
restore.indexTar(path+file)
except Exception as e:
log.logger.error('Could not index tar')
| UTF-8 | Python | false | false | 287 | py | 6 | index_tars.py | 4 | 0.679443 | 0.679443 | 0 | 14 | 19.5 | 82 |
MD58/Udacity_FSND_5 | 2,748,779,086,303 | fd6c3a1852f0a9e0f4f7aa674249554bd4a63ca0 | 25ec7d592e93b1196ff44dca01b062f381155045 | /migrations/versions/5876f7116045_.py | 025dfb027291155a42ffc38b45b66ad5be656e3c | []
| no_license | https://github.com/MD58/Udacity_FSND_5 | d47e57ff03414271df6d2662875e9ef6df793a60 | a109a8df90c77842d4964b0565856ce05f817d0a | refs/heads/master | 2023-03-17T08:07:10.020285 | 2021-03-06T11:57:56 | 2021-03-06T11:57:56 | 344,796,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """empty message
Revision ID: 5876f7116045
Revises:
Create Date: 2021-03-05 21:39:32.116726
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5876f7116045'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
'Actor',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('gender', sa.String(), nullable=False),
sa.Column('date_of_birth', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_table('Movie', sa.Column('id', sa.Integer(),
nullable=False), sa.Column('title', sa.String(),
nullable=False), sa.Column('release_date',
sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'))
op.create_table(
'MovieActor',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('movie_id', sa.Integer(), nullable=True),
sa.Column('artist_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['artist_id'], ['Actor.id']),
sa.ForeignKeyConstraint(['movie_id'], ['Movie.id']),
sa.PrimaryKeyConstraint('id'),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('MovieActor')
op.drop_table('Movie')
op.drop_table('Actor')
# ### end Alembic commands ###
| UTF-8 | Python | false | false | 1,612 | py | 7 | 5876f7116045_.py | 6 | 0.595533 | 0.569479 | 0 | 58 | 26.793103 | 68 |
TonyPod/Two-CILs | 16,621,523,463,298 | 8edfb3b6b4e1905f4abbf7699f990b3d6fe9d6c4 | 2662ec80bc48697b3041fdf00a3afcb55c531b7b | /networks/backbones/imagenet64x64_mobilenetv2.py | f5de4c359a8320f1cb457988820c5b77038bc1b2 | []
| no_license | https://github.com/TonyPod/Two-CILs | b3ae7b3298688d714fdb7378864b33a37f993313 | 0bcd19e52dddafc8fb1b4043db8a799a258c60d9 | refs/heads/main | 2023-06-01T04:49:40.146258 | 2021-06-23T08:35:33 | 2021-06-23T08:35:33 | 357,801,755 | 7 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding:utf-8 -*-
"""
@time: 3/3/21 10:05 PM
@author: Chen He
@site:
@file: imagenet64x64_mobilenetv2.py
@description:
"""
from tensorflow.python.keras import backend, Model, layers, regularizers
def _make_divisible(v, divisor, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
def mobilenet_64x64(weight_decay=1e-4,
final_relu=True,
alpha=1.0,
pooling='avg'):
"""Instantiates the MobileNetV2 architecture.
Reference:
- [MobileNetV2: Inverted Residuals and Linear Bottlenecks](
https://arxiv.org/abs/1801.04381) (CVPR 2018)
Optionally loads weights pre-trained on ImageNet.
Note: each Keras Application expects a specific kind of input preprocessing.
For MobileNetV2, call `tf.keras.applications.mobilenet_v2.preprocess_input`
on your inputs before passing them to the model.
Arguments:
alpha: Float between 0 and 1. controls the width of the network.
This is known as the width multiplier in the MobileNetV2 paper,
but the name is kept for consistency with `applications.MobileNetV1`
model in Keras.
- If `alpha` < 1.0, proportionally decreases the number
of filters in each layer.
- If `alpha` > 1.0, proportionally increases the number
of filters in each layer.
- If `alpha` = 1, default number of filters from the paper
are used at each layer.
pooling: String, optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model
will be the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a
2D tensor.
- `max` means that global max pooling will
be applied.
**kwargs: For backwards compatibility only.
Returns:
A `keras.Model` instance.
Raises:
ValueError: in case of invalid argument for `weights`,
or invalid input shape or invalid alpha, rows when
weights='imagenet'
ValueError: if `classifier_activation` is not `softmax` or `None` when
using a pretrained top layer.
"""
img_input = layers.Input(shape=(64, 64, 3))
channel_axis = 1 if backend.image_data_format() == 'channels_first' else -1
first_block_filters = _make_divisible(32 * alpha, 8)
x = layers.Conv2D(
first_block_filters,
kernel_size=3,
strides=(2, 2),
padding='same',
use_bias=False,
kernel_regularizer=regularizers.l2(weight_decay),
name='Conv1')(img_input)
x = layers.BatchNormalization(
axis=channel_axis, epsilon=1e-3, momentum=0.999, name='bn_Conv1')(
x)
x = layers.ReLU(6., name='Conv1_relu')(x)
x = _inverted_res_block(
x, filters=16, alpha=alpha, stride=1, expansion=1, block_id=0, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=24, alpha=alpha, stride=2, expansion=6, block_id=1, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=24, alpha=alpha, stride=1, expansion=6, block_id=2, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=32, alpha=alpha, stride=2, expansion=6, block_id=3, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=32, alpha=alpha, stride=1, expansion=6, block_id=4, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=32, alpha=alpha, stride=1, expansion=6, block_id=5, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=64, alpha=alpha, stride=2, expansion=6, block_id=6, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=64, alpha=alpha, stride=1, expansion=6, block_id=7, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=64, alpha=alpha, stride=1, expansion=6, block_id=8, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=64, alpha=alpha, stride=1, expansion=6, block_id=9, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=96, alpha=alpha, stride=1, expansion=6, block_id=10, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=96, alpha=alpha, stride=1, expansion=6, block_id=11, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=96, alpha=alpha, stride=1, expansion=6, block_id=12, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=160, alpha=alpha, stride=2, expansion=6, block_id=13, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=160, alpha=alpha, stride=1, expansion=6, block_id=14, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=160, alpha=alpha, stride=1, expansion=6, block_id=15, weight_decay=weight_decay)
x = _inverted_res_block(
x, filters=320, alpha=alpha, stride=1, expansion=6, block_id=16, weight_decay=weight_decay)
# no alpha applied to last conv as stated in the paper:
# if the width multiplier is greater than 1 we
# increase the number of output channels
if alpha > 1.0:
last_block_filters = _make_divisible(1280 * alpha, 8)
else:
last_block_filters = 1280
x = layers.Conv2D(
last_block_filters, kernel_size=1, use_bias=False, name='Conv_1',
kernel_regularizer=regularizers.l2(weight_decay))(
x)
x = layers.BatchNormalization(
axis=channel_axis, epsilon=1e-3, momentum=0.999, name='Conv_1_bn')(
x)
if final_relu:
x = layers.ReLU(6., name='out_relu')(x)
if pooling == 'avg':
x = layers.GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = layers.GlobalMaxPooling2D()(x)
else:
raise Exception()
x = layers.Flatten()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
inputs = img_input
# Create model.
model = Model(inputs, x, name='mobilenetv2_%0.2f' % alpha)
return model
def _correct_pad(inputs, kernel_size):
"""Returns a tuple for zero-padding for 2D convolution with downsampling.
Arguments:
inputs: Input tensor.
kernel_size: An integer or tuple/list of 2 integers.
Returns:
A tuple.
"""
img_dim = 2 if backend.image_data_format() == 'channels_first' else 1
input_size = backend.int_shape(inputs)[img_dim:(img_dim + 2)]
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
if input_size[0] is None:
adjust = (1, 1)
else:
adjust = (1 - input_size[0] % 2, 1 - input_size[1] % 2)
correct = (kernel_size[0] // 2, kernel_size[1] // 2)
return ((correct[0] - adjust[0], correct[0]),
(correct[1] - adjust[1], correct[1]))
def _inverted_res_block(inputs, expansion, stride, alpha, filters, block_id, weight_decay):
"""Inverted ResNet block."""
channel_axis = 1 if backend.image_data_format() == 'channels_first' else -1
in_channels = backend.int_shape(inputs)[channel_axis]
pointwise_conv_filters = int(filters * alpha)
pointwise_filters = _make_divisible(pointwise_conv_filters, 8)
x = inputs
prefix = 'block_{}_'.format(block_id)
if block_id:
# Expand
x = layers.Conv2D(
expansion * in_channels,
kernel_size=1,
padding='same',
use_bias=False,
activation=None,
kernel_regularizer=regularizers.l2(weight_decay),
name=prefix + 'expand')(
x)
x = layers.BatchNormalization(
axis=channel_axis,
epsilon=1e-3,
momentum=0.999,
name=prefix + 'expand_BN')(
x)
x = layers.ReLU(6., name=prefix + 'expand_relu')(x)
else:
prefix = 'expanded_conv_'
# Depthwise
if stride == 2:
x = layers.ZeroPadding2D(
padding=_correct_pad(x, 3),
name=prefix + 'pad')(x)
x = layers.DepthwiseConv2D(
kernel_size=3,
strides=stride,
activation=None,
use_bias=False,
kernel_regularizer=regularizers.l2(weight_decay),
padding='same' if stride == 1 else 'valid',
name=prefix + 'depthwise')(
x)
x = layers.BatchNormalization(
axis=channel_axis,
epsilon=1e-3,
momentum=0.999,
name=prefix + 'depthwise_BN')(
x)
x = layers.ReLU(6., name=prefix + 'depthwise_relu')(x)
# Project
x = layers.Conv2D(
pointwise_filters,
kernel_size=1,
padding='same',
use_bias=False,
kernel_regularizer=regularizers.l2(weight_decay),
activation=None,
name=prefix + 'project')(
x)
x = layers.BatchNormalization(
axis=channel_axis,
epsilon=1e-3,
momentum=0.999,
name=prefix + 'project_BN')(
x)
if in_channels == pointwise_filters and stride == 1:
return layers.Add(name=prefix + 'add')([inputs, x])
return x
| UTF-8 | Python | false | false | 9,454 | py | 34 | imagenet64x64_mobilenetv2.py | 26 | 0.614343 | 0.586207 | 0 | 260 | 35.361538 | 99 |
gurbanli/OOP_task1 | 10,024,453,670,935 | 5e3f6cd55dc12df9877d0c17b5f11f26d2649b92 | 7f50192d2a6efdf0ddfb8b3994f43af926ee22f6 | /master.py | cf1491218e5a387821de4bb0352e6e1c4a78846c | []
| no_license | https://github.com/gurbanli/OOP_task1 | 5f64e446f20d771c6b009c0d75d6dc923167c708 | 51713474353d8172cb01b21350c82cbd7a2b55a1 | refs/heads/master | 2023-03-23T03:19:52.079969 | 2020-04-17T20:24:32 | 2020-04-17T20:24:32 | 256,599,221 | 0 | 0 | null | false | 2021-03-20T03:36:10 | 2020-04-17T20:07:30 | 2020-04-17T20:24:55 | 2021-03-20T03:36:10 | 3 | 0 | 0 | 1 | Python | false | false | class Master:
def __init__(self, num_of_masters):
self.salary = 100
self.price_of_masters = int(num_of_masters) * self.salary
| UTF-8 | Python | false | false | 146 | py | 7 | master.py | 4 | 0.616438 | 0.59589 | 0 | 4 | 35.5 | 65 |
LD250/pyconweb2018workshop | 13,460,427,552,367 | e5a6a92dfed160ba6b22415be5b4ed1a3ee42239 | 4d0872809a121d31e895ca2c71862bc6ed89f866 | /polls/management/commands/import_questions.py | 1dbe8cd51fa9a4e8bacbbcb889b8ffef3268d9e4 | []
| no_license | https://github.com/LD250/pyconweb2018workshop | 07b18db19506758cfaf7e7ad77c833b4c5843ebd | 63b9ed81969cec6338e8d773acdae2b27a80377d | refs/heads/master | 2020-03-21T03:09:19.405400 | 2018-06-30T13:40:19 | 2018-06-30T13:40:19 | 138,038,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import json
from datetime import datetime
from django.utils import timezone
from time import time
from django.core.management.base import BaseCommand, CommandError
from polls.models import Question, Choice, QuestionInfo
class Command(BaseCommand):
help = 'Import Questions from file'
def handle(self, *args, **options):
"""
{"choices": [["Choice 0 0", 9], ["Choice 0 1", 7],
["Choice 0 2", 10], ["Choice 0 3", 11]],
"author": "Author 0", "value": 30, "question_text": "Question N 0"}
:param args:
:param options:
:return:
"""
start = time()
self.stdout.write(self.style.SUCCESS('Successfully imported. Time "%s"' % time() - start))
| UTF-8 | Python | false | false | 751 | py | 11 | import_questions.py | 8 | 0.59787 | 0.573901 | 0 | 23 | 31.608696 | 98 |
L00J/Django | 8,589,934,633,040 | 04a21617570abc8eb7ebbd33c6b980540ed55352 | 5a5829c0bb3cf3efb5bf944acacce0d0055e52cd | /2.数据增删改查的操作/blog/migrations/0001_initial.py | c2a9a422e39e3ef22b68088b1929dde2fe7343bf | []
| no_license | https://github.com/L00J/Django | 4c198efde9f6ffb9e04d7ab40ce10ced0a38947b | 1da4eadc05da02a1846bde27c0fdbc568a542d7b | refs/heads/master | 2019-03-16T18:11:56.520973 | 2018-05-21T12:44:52 | 2018-05-21T12:44:52 | 122,968,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-03 16:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=70)),
('body', models.TextField(blank=True, null=True)),
('digest', models.CharField(blank=True, max_length=200)),
('publish', models.DateTimeField(default=django.utils.timezone.now)),
('mod_date', models.DateField(auto_now=True)),
('view', models.BigIntegerField(default=0)),
('comment', models.BigIntegerField(default=0)),
('picture', models.CharField(blank=True, max_length=200, null=True)),
('author', models.CharField(default='anonymous', editable=False, max_length=128)),
],
options={
'ordering': ['-publish'],
},
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose_name='标题')),
('source_id', models.CharField(max_length=25, verbose_name='文章id或source名称')),
('create_time', models.DateTimeField(auto_now=True, verbose_name='评论时间')),
('user_name', models.CharField(max_length=25, verbose_name='评论用户')),
('url', models.CharField(max_length=100, verbose_name='链接')),
('comment', models.CharField(max_length=500, verbose_name='评论内容')),
],
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.AddField(
model_name='article',
name='category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Category', verbose_name='文章类型'),
),
migrations.AddField(
model_name='article',
name='tags',
field=models.ManyToManyField(blank=True, to='blog.Tag', verbose_name='标签'),
),
]
| UTF-8 | Python | false | false | 3,053 | py | 18 | 0001_initial.py | 7 | 0.554518 | 0.538513 | 0 | 72 | 40.652778 | 122 |
NoiseBaphomet/python | 5,145,370,835,946 | 07baa39698e573b0bc0fda0e38466bab4356de5f | 3272f846772d725644f54c3e4b109ea71707435f | /NoiseBot.py | 867361e36066e6252fee1366798a1b109cd3961c | []
| no_license | https://github.com/NoiseBaphomet/python | c76ae4c0f77dcaafa4a56ab264d569daf39176b0 | 48cc408c71116bbe88b3cb662caad59cceba56ee | refs/heads/main | 2023-03-01T12:56:30.391108 | 2021-02-12T22:33:06 | 2021-02-12T22:33:06 | 337,807,700 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import discord
from discord.ext import commands
import youtube_dl
import os
import datetime
from urllib import parse, request
import re
#para que funcione hay que instalar youtube_dl y FFmpeg
client = commands.Bot(command_prefix=">", description="Hi")
@client.event
async def on_ready():
print('logueado como {0.user}'.format(client))
activity = discord.Game(name=">ayuda ó >help",url="https://www.youtube.com/watch?v=V2hlQkVJZhE")
await client.change_presence(status=discord.Status.online, activity=activity) #idle, online
@client.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.channels, name='general')
await channel.send(f'**Welcome {member.mention}!** Listo para jugar? See `>ayuda` para detalles y comandos!')
@client.command()
async def info(ctx):
autor = str(ctx.message.author) + " se la come!"
embed = discord.Embed(title=f"{ctx.guild.name}", description= autor, timestamp=datetime.datetime.utcnow(), color=discord.Color.green())
embed.add_field(name="Server creado a las", value=f"{ctx.guild.created_at}")
embed.add_field(name="Server poseído", value=f"{ctx.guild.owner}")
embed.add_field(name="Server Region", value=f"{ctx.guild.region}")
embed.add_field(name="Server ID", value=f"{ctx.guild.id}")
# embed.set_thumbnail(url=f"{ctx.guild.icon}")
embed.set_thumbnail(url="https://pluralsight.imgix.net/paths/python-7be70baaac.png")
await ctx.send(embed=embed)
@client.command()
async def youtube(ctx, *, search):
query_string = parse.urlencode({'search_query': search})
html_content = request.urlopen('http://www.youtube.com/results?' + query_string)
search_results = re.findall( r"watch\?v=(\S{11})", html_content.read().decode())
print(search_results)
await ctx.send('https://www.youtube.com/watch?v=' + search_results[0])
@client.command()
async def play(ctx, *, search): #play
query_string = parse.urlencode({'search_query': search})
html_content = request.urlopen('http://www.youtube.com/results?' + query_string)
search_results = re.findall( r"watch\?v=(\S{11})", html_content.read().decode())
print(search_results)
await ctx.send('https://www.youtube.com/watch?v=' + search_results[0])
canal = ctx.message.author.voice.channel
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except PermissionError:
await ctx.send("Espera a la lista de reproduccion o escribe >stop")
return
#voiceChannel = discord.utils.get(ctx.guild.voice_channels, name = "GTA V Online")
#await voiceChannel.connect()
await canal.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '320', #192 default
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl: #parece que se instancia como ydl_opts
url = 'https://www.youtube.com/watch?v=' + search_results[0]
ydl.download([url]) #Aqui podria poner la busqueda sin url para que sea mas facil
for file in os.listdir("./"):
if file.endswith(".mp3"):
name = file
print("Renombrando archivo {file}")
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"),after=lambda e: print("ha termina la canción")) #play a la canción
print("**La canción se ha reproducido**")
await ctx.send("**Escuchando** "+str(name))
#lo de abajo solo es para controlar el audio pero no es tan necesario
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 1.00 #1.00 es mucho
@client.command()
async def disconnect(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
else:
await ctx.send("Bop Bom... No estoy connectado en un canal de voz. 😁")
@client.command()
async def pause(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
await ctx.send("Musica pausada")
else:
await ctx.send("Ningun audio actualmente.")
@client.command()
async def resume(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
await ctx.send("Musica Resumida")
else:
await ctx.send("El audio no esta pausado.")
@client.command()
async def stop(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
await ctx.send("Musica Detenida")
await ctx.send(":( ya no hablo hasta que me saques, esque ando bug")
else:
print("no se esta reproduciendo, no se puede detener")
await ctx.send("Nada reproduciendose, no se puede detener uwu")
client.run('ODA4ODEyMjQ1OTczOTkxNDM0.YCL_Gg.WomxToYbTNbL5r3XtTygbRj7hpw') | UTF-8 | Python | false | false | 5,114 | py | 2 | NoiseBot.py | 2 | 0.666079 | 0.659029 | 0 | 151 | 32.821192 | 139 |
stevenconnorg/GDB_DataReview | 4,801,773,437,057 | 12f088ec56412745051b39b40c0072032afcce53 | bbb9a40bbe78e4dc94db118a6fe9d663442f423c | /py/exportMetadata.py | 35b866a7aa0a28e5f98cb8df25d36c66602c0f49 | [
"MIT"
]
| permissive | https://github.com/stevenconnorg/GDB_DataReview | a6e13f6f95fcd6bf7c1ddd325c6d95dbd720128a | 1ff294a27b18554b644eea2ea83272789d8e6902 | refs/heads/master | 2020-03-14T17:39:49.606793 | 2018-05-24T15:19:06 | 2018-05-24T15:19:06 | 131,725,576 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 12:39:46 2018
@author: stevenconnorg
"""
import arcpy
gdb = arcpy.GetParameterAsText(0)
translator = arcpy.GetParameterAsText(1)
outDir = arcpy.GetParameterAsText(2)
# =============================================================================
# gdb = r"C:\Users\stevenconnorg\Documents\knight-federal-solutions\CIP_DataReview\archive\ANG_Peoria - Copy\Non_Network_CIP\ANG_Peoria_CIP.gdb"
# translator = r"C:\Program Files (x86)\ArcGIS\Desktop10.6\Metadata\Translator\ARCGIS2FGDC.xml"
# outDir = r"C:\Users\stevenconnorg\Documents\knight-federal-solutions\CIP_DataReview\archive\ANG_Peoria - Copy\Non_Network_CIP\METADATA"
#
# =============================================================================
arcpy.env.workspace = gdb
FDSs = arcpy.ListDatasets()
arcpy.AddMessage(FDSs)
if not FDSs:
FCs = arcpy.ListFeatureClasses(gdb)
for fc in FCs:
outFile = outDir+"/"+fc+".xml"
if arcpy.Exists(outFile):
arcpy.Delete_management(outFile)
arcpy.ExportMetadata_conversion(fc,Translator = translator,Output_File = outDir+"/"+fc+".xml")
else:
for fds in FDSs:
outFile = outDir+"/"+fds+".xml"
if arcpy.Exists(outFile):
arcpy.Delete_management(outFile)
arcpy.ExportMetadata_conversion(fds,Translator = translator,Output_File = outFile)
FCs = arcpy.ListFeatureClasses(feature_dataset = fds)
for fc in FCs:
outFile = outDir+"/"+fds+"_"+fc+".xml"
if arcpy.Exists(outFile):
arcpy.Delete_management(outFile)
arcpy.ExportMetadata_conversion(fc,Translator = translator,Output_File = outFile)
| UTF-8 | Python | false | false | 1,693 | py | 27 | exportMetadata.py | 22 | 0.618429 | 0.605434 | 0 | 43 | 38.372093 | 145 |
ctb/STRONG | 15,659,450,767,015 | 101c568d41dba4e51b49201409a40194ea42521e | d5406d6bb844ff90380818757a4a8cb2a59ee6f0 | /SnakeNest/scripts/Bandage_Cov_correction.py | 8386c79ac56d2b810f297d8a8e645db2b2b7e0ef | [
"MIT"
]
| permissive | https://github.com/ctb/STRONG | d24676edbf9f10a9d98019b44ddd1453cd163a36 | 2a7771804afc9d72c33e4957e311193df6beb485 | refs/heads/master | 2022-12-09T13:49:01.314122 | 2020-09-03T20:19:12 | 2020-09-03T20:19:12 | 294,188,112 | 1 | 0 | MIT | true | 2020-09-09T17:53:34 | 2020-09-09T17:53:33 | 2020-09-03T20:19:32 | 2020-09-03T20:19:30 | 25,092 | 0 | 0 | 0 | null | false | false | #!/usr/bin/env python
# -*- coding: latin-1 -*-
import argparse
import os
from subprocess import Popen, PIPE
from random import randint
from Bio.SeqIO.FastaIO import *
def gfa_correction(gfa_file, kmer, output):
def correct_KC(split_line, kmer):
KC = next(element for element in split_line if "KC:i:" in element)
L = len(split_line[2])
index = split_line.index(KC)
corected_KC = 'KC:i:'+str(float(KC.split('KC:i:')[1])*L/(L-kmer))
split_line[index] = corected_KC
NewGfa = ""
for line in open(gfa_file):
line = line.rstrip().split('\t')
if line[0] == "S":
correct_KC(line, kmer)
line.append('\n')
NewGfa += "\t".join(line)
with open(output, 'w') as H:
H.write(NewGfa)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("gfa_file", help="gfa file you want to correct")
parser.add_argument("kmer", help="kmer length")
parser.add_argument("output", help="corrected gfa file")
args = parser.parse_args()
gfa_file = args.gfa_file
kmer = int(args.kmer)
output = args.output
gfa_correction(gfa_file, kmer, output)
| UTF-8 | Python | false | false | 1,185 | py | 52 | Bandage_Cov_correction.py | 38 | 0.608439 | 0.605063 | 0 | 37 | 31.027027 | 74 |
timbailey74/python-utilities | 5,772,436,060,559 | c44a97daf82d86cde77944bed0a1ab6cf58f3391 | eafeb2e54ba2f98bc6c41acfe53dffd5fa97f7f1 | /sandbox/scaling.py | 607757f44c0af361398490621299a4752f347006 | []
| no_license | https://github.com/timbailey74/python-utilities | 812b4fb3fff0ae460f1446634d39e249311b96e9 | ba2e676acbb484d5923929e015058a5518999af6 | refs/heads/master | 2020-04-16T16:40:33.112317 | 2016-12-10T01:17:08 | 2016-12-10T01:17:08 | 34,838,591 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Test the effect of scaling and other transformations on numerical accuracy of
# least-squares, numerical differentiation, etc.
import numpy as np
| UTF-8 | Python | false | false | 150 | py | 10 | scaling.py | 9 | 0.8 | 0.8 | 0 | 4 | 36.25 | 79 |
CS1803-SE/The-First-Subsystem | 12,214,887,028,253 | 2edefecafa3d4590a9cd1faf4fa337e0f5d4192b | bccfab4d853f7417401a084be95de293e66ccd2a | /mySpider/spiders/Exhibition170.py | d0df88857cd1f3ca2af0a6e325ef8f92b292bde7 | []
| no_license | https://github.com/CS1803-SE/The-First-Subsystem | a8af03ce04a9de72a6b78ece6411bac4c02ae170 | 4829ffd6a83133479c385d6afc3101339d279ed6 | refs/heads/main | 2023-05-06T02:32:08.751139 | 2021-05-24T06:09:37 | 2021-05-24T06:09:37 | 363,400,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #
from ..items import *
from ..str_filter import *
class Exhibition170(scrapy.Spider):
name = "Exhibition170"
allowed_domains = ['jinshasitemuseum.com']
start_urls = ['http://www.jinshasitemuseum.com/Exhibition/ExhibitionSpecial']
custom_settings = {
'ITEM_PIPELINES': {
'mySpider.pipelines.ExhibitionPipeLine': 302,
},
'DOWNLOADER_MIDDLEWARES': {
'mySpider.middlewares.DefaultMiddleware': 0,
},
}
def parse(self, response, **kwargs):
li_list = response.xpath(
"/html/body/div[3]/div/div[2]/div[2]/div[2]/div/div/div/div")
print(len(li_list))
for li in li_list:
item = ExhibitionItem()
item["museumID"] = 170
item["museumName"] = "5·12汶川特大地震纪念馆"
item["exhibitionImageLink"] ='https://baike.baidu.com'+str(li.xpath(
"/html/body/div[3]/div[2]/div/div[1]/div[58]/div/a/@href").extract_first())
item["exhibitionName"] = StrFilter.filter_2(li.xpath("/html/body/div[3]/div[2]/div/div[1]/div[58]/div/span/text()").extract_first())
item["exhibitionTime"] = None
item['exhibitionIntroduction'] = StrFilter.filter_2(li.xpath("/html/body/div[3]/div[2]/div/div[1]/div[58]/text()").extract_first())
print(item)
#yield item
| UTF-8 | Python | false | false | 1,372 | py | 310 | Exhibition170.py | 309 | 0.586105 | 0.558758 | 0 | 33 | 40 | 144 |
VatsalRaina/HATM | 343,597,420,620 | f5845ac7327f15119511ca87e5b303e1d6bf1c2b | ae6ca0239e319553dee8a4949604af3577f58381 | /preprocessing/magic_preprocess_raw.py | 46a7e5462eae9e97ac697036c5fc8272a3df8aa2 | []
| no_license | https://github.com/VatsalRaina/HATM | 61d2d751e0d130cfc9e08af32aafae46a7040adc | b06a06d31cea60e597b2d4ee45ad9604d4622a11 | refs/heads/master | 2020-09-16T01:03:25.563275 | 2020-05-22T11:23:14 | 2020-05-22T11:23:14 | 223,604,488 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #! /usr/bin/env python
"""
Preprocess 'raw' mlf transcription and scripts files into prompt-response pairs and save them
alongside with grades, speaker-ids and other meta-data into human-readable .txt in the destination directory.
-----
Generates files:
responses.txt prompts.txt speakers.txt conf.txt sections.txt prompt_ids.txt
-----
The jargon used in the documentation of this code that might be non-trivial to infer:
The expected format of the prompt identifiers in the .mlf script file looks like:
"ABC111-XXXXX-XXXXXXXX-SA0001-en.lab"
of which:
ABC111 - is being referred to as location_id
SA0001 - is being referred to as section_id where A is the actual section
If a section is composed of an overall question with multiple subquestion, the section is being referred to as
multi-section. The overall section question that should prepend all the subquestion is referred to as master question.
Some other quirks:
If the prompt section id number is above that of a master section id given in the flag, it will be set to be that of
the flag.
"""
from __future__ import print_function
import sys
import os
import re
import time
import argparse
parser = argparse.ArgumentParser(
description="Preprocess 'raw' mlf transcription and scripts files into prompt-response pairs and save them "
"alongside with grades, speaker-ids and other meta-data into human-readable .txt in the "
"destination directory.")
parser.add_argument('scripts_path', type=str, help='Path to a scripts (prompts) .mlf file')
parser.add_argument('responses_path', type=str, help='Path to a transcript of responses .mlf file')
parser.add_argument('save_dir', type=str, help='Path to the directory in which to save the processed files.')
parser.add_argument('--fixed_sections', nargs='*', type=str, default=['A', 'B'],
help='Which sections if any are fixed (questions are always the same). Takes space separated '
'indentifiers, e.g. --fixed_sections A B')
parser.add_argument('--exclude_sections', nargs='*', type=str, default=['A', 'B'],
help='Sections to exclude from the output. '
'Takes space separated identifiers, e.g. --exclude_sections A B')
parser.add_argument('--multi_sections', nargs='*', type=str, default=['E'],
help='Which sections if any are multisections, i.e. when generating prompts a master question '
'should be pre-pended before each subquestion. Takes space separated '
'indentifiers, e.g. --multi_sections E F')
parser.add_argument('--multi_sections_master', nargs='*', type=str, default=['SE0006'],
help='The master question section id for each multi-section. For instance, if two sections '
'E and F are multi-sections with section ids SE0006 and SF0008 for the master or "parent"'
'questions to be prepended before subquestion, use:'
'--multi_sections_master SE0006 SF0008')
parser.add_argument('--speaker_grades_path', type=str, help='Path to a .lst file with speaker ids and '
'their grades for each section', default='')
parser.add_argument('--num_sections', type=int, help='Number of sections in the test '
'(e.g. in BULATS: A, B, C, D, E -> 5 sections).')
parser.add_argument('--exclude_grades_below', type=float, help='Exclude all the responses from sections '
'with grades below a certain value', default=0.0)
# The separator to use between the master prompt and subprompt for sections specified with --multi_sections flag
sub_prompt_separator = "</s> <s>"
no_grade_filler = '-1'
def generate_grade_dict(speaker_grade_path):
"""Crate a dict from speaker id to a dict that maps section to grade that the speaker got on this section."""
grade_dict = dict()
with open(speaker_grade_path, 'r') as file:
for line in file.readlines():
line = line.replace('\n', '').split()
speaker_id = line[0]
section_dict = {}
for i, section in zip(range(1, 7), ['A', 'B', 'C', 'D', 'E']):
# todo: replace with a non-manual labeling of sections
grade = line[i]
if grade == '' or grade =='.':
grade = no_grade_filler
section_dict[section] = grade
grade_dict[speaker_id] = section_dict
return grade_dict
def extract_uniq_identifier(prompt_id, args):
"""
Extract a unique identifier for each prompt.
"""
location_id, section_id = prompt_id.split('-')
##### The manual rules: ###
if (section_id[1] == 'C' or section_id[1] == 'D') and int(section_id[2:]) > 1:
section_id = section_id[:2] + '0001'
print("Prompt id: {} is being mapped to {} with manual rules.".format(prompt_id, '-'.join((location_id, section_id))))
#####
# If the prompt is from a fixed section or is a fixed question
if section_id[1] in args.fixed_sections:
return section_id
# Consider whether the prompt is a master question (must be exclusive from fixed section
if section_id[1] in args.multi_sections:
idx = args.multi_sections.index(section_id[1])
# Assume if question number is larger than that of a master question, it is a master question
if int(section_id[2:]) > int(args.multi_sections_master[idx][2:]):
section_id = args.multi_sections_master[idx]
return '-'.join((location_id, section_id))
def generate_mappings(prompts, prompt_ids, args):
"""
Assumes the mapping from prompt_ids to prompts is surjective, but not necessarily injective: many prompt_ids
can point to the same prompt. Hence in the inverse mapping, each prompt points to a list of prompt_ids that point
to it.
The prompt id's take the form:
prompt_id = 'ABC999-SA0001' where ABC999 is the location_id and SA0001 the question number:
A indicates the section, and 0001 indicates question 1 within that section.
For prompts that have been marked with a fixed_sections flag, i.e. the corresponding question of each section is
always the same, we store additional prompt_id key pointing to the prompt which is just the section identifier
without the location identifier, i.e.:
If 'A' is in fixed_section:
'ABC999-SA0001' -> prompt1
and also:
'SA0001' -> prompt1
:return: mapping dict, inv_mapping dict
"""
mapping = {} # Mapping from prompts to a list of identifiers
inv_mapping = {} # Mapping from identifiers to prompts
for prompt, full_id in zip(prompts, prompt_ids):
# Process the prompt_id line
assert re.match(r'[A-Z0-9]+-[X-]*[A-Z0-9]+-[a-z]*$', full_id) # The expected format of the line
full_id = full_id.split('-')
location_id, section_id = full_id[0], full_id[-2]
prompt_id = '-'.join((location_id, section_id))
_add_pair_to_mapping(mapping, inv_mapping, prompt_id, prompt)
_add_pair_to_mapping(mapping, inv_mapping, extract_uniq_identifier(prompt_id, args), prompt)
return mapping, inv_mapping
def _add_pair_to_mapping(mapping, inv_mapping, prompt_id, prompt):
mapping.setdefault(prompt, [])
mapping[prompt].append(prompt_id)
inv_mapping[prompt_id] = prompt
return
def process_mlf_scripts(mlf_path, word_pattern=r"[%A-Za-z'\\_.]+$"):
"""Process the mlf script file pointed to by path mlf_path and return a list of prompts and a list of
corresponding ids associated with that prompt."""
sentences = []
ids = []
with open(mlf_path, 'r') as file:
words = []
for line in file.readlines():
line = line.strip() # Remove the \n at the end of line
if line == '#!MLF!#':
# Ignore the file type prefix line
continue
elif ".lab" in line or ".rec" in line:
assert re.match(r'"[a-zA-Z0-9-]+.lab"$', line) or re.match(r'"[a-zA-Z0-9-]+.rec"$', line)
assert len(sentences) == len(ids)
# Get rid of the " at the beginning and the .lab" at the end
line = line[1:-5]
ids.append(line)
elif line == ".":
# A "." indicates end of utternace -> add the sentence to list
sentence = " ".join(words)
assert len(sentence) > 0
sentences.append(sentence)
# Reset the words temporary list
words = []
elif re.match(word_pattern, line):
word = line.replace("\\'", "'")
words.append(word)
else:
raise ValueError("Unexpected pattern in file: " + line)
return sentences, ids
def process_mlf_responses(mlf_path, word_line_pattern=r"[0-9]* [0-9]* [\"%A-Za-z'\\_.]+ [0-9.]*$"):
"""Processes the .mlf file with the transcription of responses and returns lists with corresponding:
responses, ids, response confidences"""
sentences = []
ids = []
confidences = []
with open(mlf_path, 'r') as file:
words_temp = []
confs_temp = []
for line in file.readlines():
line = line.strip() # Remove the \n at the end of line
if line == '#!MLF!#':
# Ignore the file type prefix line
continue
elif ".lab" in line or ".rec" in line:
assert re.match(r'"[a-zA-Z0-9-_]+.lab"$', line) or re.match(r'"[a-zA-Z0-9-_]+.rec"$', line)
assert len(sentences) == len(ids)
# Get rid of the " at the beginning and the .lab" at the end
line = line[1:-5]
ids.append(line)
elif line == ".":
# A "." indicates end of utterance -> add the sentence to list
sentence = " ".join(words_temp)
sentence_confs = " ".join(confs_temp)
if len(sentence) == 0:
# If the response is empty, skip
del ids[-1]
else:
sentences.append(sentence)
confidences.append(sentence_confs)
# Reset the temp variables
words_temp, confs_temp = [], []
elif len(line.split()) > 1:
# assert re.match(word_line_pattern, line)
line_split = line.split()
words_temp.append(line_split[-2])
confs_temp.append(line_split[-1])
else:
raise ValueError("Unexpected pattern in file: " + line)
return sentences, ids, confidences
# def fixed_section_filter(prompt_id, fixed_sections, fixed_questions):
# section_id = prompt_id.split('-')[1] # Extracts the section id, for example 'SA0001'
# if section_id[1] in fixed_sections or section_id in fixed_questions:
# print("Id lookup reduced: , ", prompt_id)
# return section_id
# else:
# return prompt_id
def filter_hesitations_and_partial(responses, confidences):
"""Remove all the hesitations and partial words from responses and the corresponding confidences from the
confidences list."""
filtered_responses, filtered_confidences = [], []
# Filter out the %HESITATION% and partial words
for response, conf_line in zip(responses, confidences):
filtered = zip(*((word, conf) for word, conf in zip(response.split(), conf_line.split()) if
not re.match('(%HESITATION%)|(\S*_%partial%)', word)))
if len(filtered) != 0:
new_response, new_conf_line = filtered
filtered_responses.append(' '.join(new_response))
filtered_confidences.append(' '.join(new_conf_line))
else:
filtered_responses.append(None)
filtered_confidences.append(None)
return filtered_responses, filtered_confidences
def main(args):
# Check the input flag arguments are correct:
try:
for section in args.fixed_sections + args.exclude_sections + args.multi_sections:
assert re.match(r'[A-Z]', section)
for section_id in args.multi_sections_master:
assert re.match(r'[A-Z0-9]', section_id)
assert len(args.multi_sections) == len(args.multi_sections_master)
except AssertionError:
raise ValueError(
"The flag arguments provided don't match the expected format. Use --help to see expected arguments.")
# Cache the command:
if not os.path.isdir(os.path.join(args.save_dir, 'CMDs')):
os.makedirs(os.path.join(args.save_dir, 'CMDs'))
with open(os.path.join(args.save_dir, 'CMDs/preprocessing.cmd'), 'a') as f:
f.write(' '.join(sys.argv) + '\n')
f.write('--------------------------------\n')
start_time = time.time()
# Process the prompts (scripts) file
prompts_list, prompt_ids_list = process_mlf_scripts(args.scripts_path)
print('Prompts script file processed. Time eta: ', time.time() - start_time)
# Generate mappings
mapping, inv_mapping = generate_mappings(prompts_list, prompt_ids_list, args)
print("Mappings generated. Time elapsed: ", time.time() - start_time)
# Generate the grades dictionary
if args.speaker_grades_path:
grades_dict = generate_grade_dict(args.speaker_grades_path)
processing_grades = True
print('Generated the speaker grades dictionary.')
else:
processing_grades = False
# Process the responses
responses, full_ids, confidences = process_mlf_responses(args.responses_path)
print("Responses mlf file processed. Time elapsed: ", time.time() - start_time)
# Filter out the hesitations and partial words from responses:
responses, confidences = filter_hesitations_and_partial(responses, confidences)
responses, confidences, full_ids = zip(*filter(lambda x: x[0] is not None, zip(responses, confidences, full_ids)))
print("Hesitations and partial words filtered. Time elapsed: ", time.time() - start_time)
# Extract the relevant data from full ids (see on top of the document for full_id format)
section_ids = map(lambda full_id: full_id.split('-')[3], full_ids)
location_ids_temp = map(lambda full_id: full_id.split('-')[0], full_ids)
speaker_numbers_temp = map(lambda full_id: full_id.split('-')[1], full_ids)
speaker_ids = map(lambda loc_id, spkr_num: '-'.join((loc_id, spkr_num)), location_ids_temp, speaker_numbers_temp)
prompt_ids = map(lambda loc_id, sec_id: '-'.join((loc_id, sec_id)), location_ids_temp, section_ids)
sections = map(lambda sec_id: sec_id[1], section_ids)
print("Relevant data extracted from full ids. Time elapsed: ", time.time() - start_time)
# Filter responses that are in sections to exclude
sections, responses, full_ids, confidences, section_ids, speaker_ids, prompt_ids = zip(
*filter(lambda x: x[0] not in args.exclude_sections,
zip(sections, responses, full_ids, confidences, section_ids, speaker_ids, prompt_ids)))
print("Examples filtered by section (sections excluded: {}). Time elapsed: ".format(args.exclude_sections), time.time() - start_time)
# Get the matching prompt for each response
prompts = map(lambda prompt_id: inv_mapping.get(extract_uniq_identifier(prompt_id, args), None), prompt_ids)
# Filter based on whether a corresponding prompts was found
prompts, responses, full_ids, confidences, sections, section_ids, speaker_ids, prompt_ids = zip(
*filter(lambda x: x[0] is not None,
zip(prompts, responses, full_ids, confidences, sections, section_ids, speaker_ids, prompt_ids)))
print("Prompts acquired for each response: Time elapsed: ", time.time() - start_time)
# Process the grades
if processing_grades:
# Set the grade to -1 (no_grade_filler) if no grade found for this response
grades = map(lambda speaker, section: grades_dict.get(speaker, {}).get(section, no_grade_filler), speaker_ids, sections)
else:
grades = [no_grade_filler] * len(sections)
print("Grades acquired for each response: Time elapsed: ", time.time() - start_time)
# Filter based on grade
if args.exclude_grades_below > 0.:
print("Excluding grades below: {}".format(args.exclude_grades_below))
grades, prompts, responses, full_ids, confidences, sections, section_ids, speaker_ids, prompt_ids = zip(
*filter(lambda x: float(x[0]) >= args.exclude_grades_below,
zip(grades, prompts, responses, full_ids, confidences, sections, section_ids, speaker_ids, prompt_ids)))
print("Responses filtered by grade: Time elapsed: ", time.time() - start_time)
assert len({len(grades), len(responses), len(confidences), len(speaker_ids), len(prompt_ids), len(prompts), len(sections)}) == 1
print("Responses transcription processed. Time elapsed: ", time.time() - start_time)
# Convert to lists
grades, prompts, responses, full_ids, confidences, sections, section_ids, speaker_ids, prompt_ids = map(
lambda x: list(x),
[grades, prompts, responses, full_ids, confidences, sections, section_ids, speaker_ids, prompt_ids])
# Handle the multi subquestion prompts
for i in range(len(sections)):
if sections[i] in args.multi_sections:
# Get the section_id of the master question
master_section_id = args.multi_sections_master[args.multi_sections.index(sections[i])]
# Get the whole prompt id of the master question
location_id = prompt_ids[i].split('-')[0]
master_prompt_id = '-'.join((location_id, master_section_id))
# Prepend the master prompt to the subquestion prompts.
try:
subquestion_prompt = prompts[i]
master_prompt = inv_mapping[master_prompt_id]
new_prompt = ' '.join([master_prompt, sub_prompt_separator, subquestion_prompt])
prompts[i] = new_prompt
except KeyError:
print("No master question: " + master_prompt_id + " in the scripts file!!")
# todo: Potentially delete or do something
print("Multiquestions processed (master questions prepended before subquestions). Time elapsed: ", time.time() - start_time)
# Write the data to the save directory:
suffix = '.txt'
# Make sure the directory exists:
if not os.path.exists(args.save_dir):
os.makedirs(args.save_dir)
for data, filename in zip([responses, confidences, speaker_ids, prompts, prompt_ids, sections, grades],
['responses', 'confidences', 'speakers', 'prompts', 'prompt_ids', 'sections', 'grades']):
file_path = os.path.join(args.save_dir, filename + suffix)
with open(file_path, 'w') as file:
file.write('\n'.join(data))
print("Data saved succesfully. Time elapsed: ", time.time() - start_time)
return
if __name__ == '__main__':
args = parser.parse_args()
main(args)
| UTF-8 | Python | false | false | 19,298 | py | 50 | magic_preprocess_raw.py | 46 | 0.623225 | 0.616074 | 0 | 403 | 46.885856 | 137 |
V4riableZ/Python | 1,597,727,848,831 | c4c50aa92059b945ddda31f52f7d8d5e78b0c421 | 9aacf52f308de0f84448a7f1c6cd60c69823ed02 | /Homework/Ext2_t2.py | 4219cf0cb503ed0002003aeb5dfaaa730fe725a3 | []
| no_license | https://github.com/V4riableZ/Python | 9d8fa3b7a32ea74d8736a0b9d7b22d5fabc3c2f8 | 7ae787884894127114d0d1c19d83ea8b028c9a3d | refs/heads/master | 2020-05-03T04:08:16.429945 | 2020-01-21T12:17:47 | 2020-01-21T12:17:47 | 178,413,756 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
import os
os.system('clear')
str1=input("Enter a word:")
str2=input("Enter another word:")
num=int(input(("Choose a number: [1,2,3] ")))
if len(str1) > len(str2):
print("Longest word '%s'"%str1)
elif len(str1) < len(str2):
print("Longest word '%s'"%str2)
else:
print("Words are equal in length")
if str1 in str2 or str2 in str1:
print("The first word contains a string from the second word!")
else:
print("Words are different in letters")
str3=input("Enter a new word: ")
print(str3[:num])
| UTF-8 | Python | false | false | 537 | py | 9 | Ext2_t2.py | 9 | 0.662942 | 0.629423 | 0 | 27 | 18.740741 | 64 |
arthur-samarin/SoftwareDesignProject | 15,908,558,900,245 | 5d884b8a695b71c8f1f414f0694dd0fa75e4a154 | e14b357df0b8dc66bcc00690406121b57b09df79 | /src/app/bot/reqhandler/exception_handling_request_handler.py | 4f1a5a384186f1d74172525b5b6e438ac8824af5 | []
| no_license | https://github.com/arthur-samarin/SoftwareDesignProject | 102f295627651bdf710ea6ad9ee069057f8ff41f | 9858fcb16d98c2e5950214d3c839c7ae2c2a4912 | refs/heads/master | 2020-04-06T15:33:46.678018 | 2018-12-08T00:39:50 | 2018-12-08T00:39:50 | 157,583,298 | 0 | 0 | null | false | 2018-12-05T15:48:05 | 2018-11-14T17:08:02 | 2018-12-05T13:56:22 | 2018-12-05T15:48:05 | 68 | 0 | 0 | 0 | Python | false | null | import logging
import sys
from typing import Callable
from app.bot.mvc import RequestHandler, RequestContainer, Request
from app.bot.reqhandler import BotException
logger = logging.getLogger(__name__)
class ExceptionHandlingRequestHandler(RequestHandler):
def __init__(self, wrapped: RequestHandler, internal_exception_handler: Callable[[Request, tuple], None]):
self.wrapped = wrapped
self.internal_exception_handler = internal_exception_handler
def handle(self, container: RequestContainer) -> None:
try:
self.wrapped.handle(container)
except BotException as ex:
container.stop_handling()
self.__handle_bot_exception(container, ex)
except Exception:
self.__handle_exception(container)
@staticmethod
def __handle_bot_exception(container: RequestContainer, ex: BotException):
response = ex.to_response()
container.responses.append(response)
def __handle_exception(self, container: RequestContainer):
self.internal_exception_handler(container.request, sys.exc_info())
| UTF-8 | Python | false | false | 1,106 | py | 72 | exception_handling_request_handler.py | 68 | 0.706148 | 0.706148 | 0 | 31 | 34.677419 | 110 |
topherCantrell/pixelHat | 1,056,561,964,089 | 333050c379f6de09ff8ea127404b58fd19c06ba7 | 1ddcf47817f8bb0f21a671bfef041929aab4dbb0 | /movieMaker/StillMovie.py | 0d1ecb8a5eb607f8e86e01a8e4fd866ca45542a2 | []
| no_license | https://github.com/topherCantrell/pixelHat | bd42c4f2076451c98d169934420bf02557706b20 | d23243bee31d730d3dcc9c93cbeef9a460e867a1 | refs/heads/master | 2018-09-12T04:26:42.977355 | 2018-06-27T00:03:14 | 2018-06-27T00:03:14 | 104,479,810 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import SpriteLoader
import HatFrame
sprites = SpriteLoader.SpriteLoader()
ghostMap = ['#', 1, '*', 2]
ghost = sprites.colorSprite("ghostc",ghostMap)
pacMap = ['#', 3]
pac = sprites.colorSprite("pac2", pacMap)
f = HatFrame.HatFrame()
f.draw_sprite(32-15+32, 1, ghost)
f.draw_sprite(32+1+32,2,pac)
f.set_ring(0, 4)
f.set_ring(1, 5)
f.set_ring(2, 4)
f.set_ring(3, 5)
f.set_ring(4, 4)
f.set_ring(5, 5)
f.set_ring(6, 4)
f.set_ring(7, 5)
f.set_ring(8, 4)
f.set_ring(9, 5)
f.set_ring(10, 4)
f.set_ring(11, 5)
f.set_ring(28, 4)
f.set_ring(29, 5)
f.set_ring(30, 4)
f.set_ring(31, 5)
f.set_ring(32, 4)
f.set_ring(33, 5)
f.set_ring(34, 4)
f.set_ring(35, 5)
with open("stillGEN.txt","w") as ps:
ps.write(f.to_string()+"\n")
| UTF-8 | Python | false | false | 772 | py | 26 | StillMovie.py | 10 | 0.59456 | 0.507772 | 0 | 41 | 16.731707 | 46 |
PPTMiao/mtl-ssl | 3,109,556,370,727 | f580d7851d08c11f520ed058d11f883bda267025 | c7279303a225334c7ed3c1aa32e499f508d4f6b8 | /object_detection/core/mask_predictor.py | a02dd9944e3068fbde1ee7d7b298146891bcbe10 | [
"Apache-2.0"
]
| permissive | https://github.com/PPTMiao/mtl-ssl | b501f835b79112b5a754345bf10b3f299abc6f59 | b61449c3f902414304657de6ec217077e441a6b9 | refs/heads/master | 2023-08-23T05:39:26.520032 | 2021-10-17T16:02:45 | 2021-10-17T16:02:45 | 418,143,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Mask predictor for object detectors.
Mask predictors are classes that take a high level
image feature map as input and produce one prediction,
(1) a tensor encoding classwise mask.
These components are passed directly to loss functions in our detection models.
"""
import functools
from abc import abstractmethod
import tensorflow as tf
from tensorflow.python.framework import ops as framework_ops
from object_detection.utils import ops
from object_detection.utils import shape_utils
from object_detection.utils import static_shape
from object_detection.utils import kwargs_util
slim = tf.contrib.slim
MASK_PREDICTIONS = 'mask_predictions'
class MaskPredictor(object):
"""MaskPredictor."""
def __init__(self, conv_hyperparams, is_training, num_classes, kernel_size, reuse_weights=None, channels=1):
"""Constructor.
Args:
is_training: Indicates whether the MaskPredictor is in training mode.
num_classes: number of classes. Note that num_classes *does not*
include the background category, so if groundtruth labels take values
in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
assigned classification targets can range from {0,... K}).
"""
self._conv_hyperparams = conv_hyperparams
self._is_training = is_training
self._num_classes = num_classes
self._scope = None
self._reuse_weights = reuse_weights
self._kernel_size = kernel_size
self._channels = channels
@property
def num_classes(self):
return self._num_classes
def set_scope(self, scope):
self._scope = scope
def predict(self, image_features, scope, **params):
"""Computes encoded object locations and corresponding confidences.
Takes a high level image feature map as input and produce one prediction,
(1) a tensor encoding classwise mask.
Args:
image_features: A float tensor of shape [batch_size, height, width,
channels] containing features for a batch of images.
scope: Variable and Op scope name.
**params: Additional keyword arguments for specific implementations of
MaskPredictor.
Returns:
A dictionary containing at least the following tensor.
mask_predictions: A float tensor of shape
[batch_size, height, width, num_classes] representing the classwise mask prediction.
"""
with tf.variable_scope(scope, reuse=self._reuse_weights) as var_scope:
self.set_scope(var_scope)
return self._predict(image_features, **params)
def _predict(self, image_features):
"""Implementations must override this method.
Args:
image_features: A float tensor of shape [batch_size, height, width,
channels] containing features for a batch of images.
**params: Additional keyword arguments for specific implementations of
MaskPredictor.
Returns:
A dictionary containing at least the following tensor.
mask_predictions: A float tensor of shape
[batch_size, height, width, num_classes] representing the classwise mask prediction.
"""
output_depth = self._num_classes * self._channels # channels 2 is for x, y
net = image_features
end_points_collection = self._scope.name + '_end_points'
with slim.arg_scope(self._conv_hyperparams), \
slim.arg_scope([slim.conv2d],
trainable=self._is_training,
activation_fn=tf.nn.tanh,
normalizer_fn=None,
normalizer_params=None,
outputs_collections=end_points_collection):
mask_predictions = slim.conv2d(net, output_depth, [self._kernel_size, self._kernel_size],
scope='BoxEncodingPredictor')
return {MASK_PREDICTIONS: mask_predictions}
| UTF-8 | Python | false | false | 4,465 | py | 33 | mask_predictor.py | 21 | 0.688242 | 0.683987 | 0 | 119 | 36.521008 | 110 |
taliasman/kitsune | 13,537,736,935,760 | 8aad852cd5c9374fd721013314e4296f5dffcd22 | 99b6faa1e31b9b18755e90070e24787632cd4776 | /apps/twitter/middleware.py | 6ffd1e838cd876461f44a1c560d423ce57f67fc0 | []
| no_license | https://github.com/taliasman/kitsune | d6743ef9e5b26951a87638a963e7429abf1d0327 | f8085205eef143011adb4c52d1f183da06c1c58e | refs/heads/master | 2021-05-28T19:50:40.670060 | 2013-03-11T13:55:15 | 2013-03-11T13:55:15 | 8,706,741 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import logging
import re
from django import http
from django.conf import settings
import tweepy
from twitter import url, Session, REQUEST_KEY_NAME, REQUEST_SECRET_NAME
log = logging.getLogger('k')
def validate_token(token):
return bool(token and (len(token) < 100) and re.search('\w+', token))
class SessionMiddleware(object):
def process_request(self, request):
request.twitter = Session.from_request(request)
# If is_secure is True (should always be true except for local dev),
# we will be redirected back to https and all cookies set will be
# secure only.
is_secure = settings.TWITTER_COOKIE_SECURE
ssl_url = url(request, {'scheme': 'https' if is_secure else 'http'})
auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET,
ssl_url,
secure=True)
if request.REQUEST.get('twitter_delete_auth'):
request.twitter = Session()
return http.HttpResponseRedirect(url(request))
elif request.twitter.authed:
auth.set_access_token(request.twitter.key, request.twitter.secret)
request.twitter.api = tweepy.API(auth)
else:
verifier = request.GET.get('oauth_verifier')
if verifier:
# We are completing an OAuth login
request_key = request.COOKIES.get(REQUEST_KEY_NAME)
request_secret = request.COOKIES.get(REQUEST_SECRET_NAME)
if (validate_token(request_key) and
validate_token(request_secret)):
auth.set_request_token(request_key, request_secret)
try:
auth.get_access_token(verifier)
except tweepy.TweepError:
log.warning('Tweepy Error with verifier token')
pass
else:
# Override path to drop query string.
ssl_url = url(
request,
{'scheme': 'https' if is_secure else 'http',
'path': request.path})
response = http.HttpResponseRedirect(ssl_url)
Session(
auth.access_token.key,
auth.access_token.secret).save(request, response)
return response
else:
# request tokens didn't validate
log.warning("Twitter Oauth request tokens didn't validate")
elif request.REQUEST.get('twitter_auth_request'):
# We are requesting Twitter auth
try:
redirect_url = auth.get_authorization_url()
except tweepy.TweepError:
log.warning('Tweepy error while getting authorization url')
else:
response = http.HttpResponseRedirect(redirect_url)
response.set_cookie(
REQUEST_KEY_NAME,
auth.request_token.key,
secure=is_secure)
response.set_cookie(
REQUEST_SECRET_NAME,
auth.request_token.secret,
secure=is_secure)
return response
def process_response(self, request, response):
if getattr(request, 'twitter', False):
if request.REQUEST.get('twitter_delete_auth'):
request.twitter.delete(request, response)
if request.twitter.authed and REQUEST_KEY_NAME in request.COOKIES:
response.delete_cookie(REQUEST_KEY_NAME)
response.delete_cookie(REQUEST_SECRET_NAME)
request.twitter.save(request, response)
return response
| UTF-8 | Python | false | false | 4,001 | py | 106 | middleware.py | 76 | 0.532117 | 0.531367 | 0 | 105 | 37.104762 | 79 |
zj-Cloudia/StructurePlaneCluster | 14,388,140,485,820 | 08ea77db5c2afb20bcd995f3a2b3b739d085ba18 | 3b5f1b969dd9fcdc9a439db585ee72e4b0fe451d | /test/testDbscan.py | de09785bc987efe65225e6dcc08e214fdc0508d2 | []
| no_license | https://github.com/zj-Cloudia/StructurePlaneCluster | 9d0ecc0561cfdce355378bd14c61e6119bb08833 | 9591ac8a4b795fec308fbc1307b5dda395f1c1d5 | refs/heads/master | 2020-05-20T11:59:56.404151 | 2017-10-28T16:23:04 | 2017-10-28T16:23:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from importlib import reload
import numpy as np
import plotGraph as plt, helper as hp
import dbscan as dbs
# ####### Parameters #########
eps = 0.05
min_pts = 10
file_name = "_dataSet.txt" # file name of Test Data, should be in the same folder of program
plot_origin = 0 # plot origin graph or clustered graph, 1 = origin, else = clustered
sieve_angle = 90 # Data which intersection angle with mean vector larger than that will be removed
# ############################
reload(dbs)
reload(plt)
reload(hp)
test_data = np.mat(hp.loadDataSet(file_name))
if plot_origin == 1:
test_data_show = hp.degree2radian(test_data, 0)
plt.createOrigin(test_data_show.A)
else:
# get and transfer Data
test_data_radian = hp.degree2radian(test_data, -1)
test_data_vector = hp.orientation2vector(test_data_radian)
# run dbscan Algorithm
print("******************* start dbscan ********************")
print("")
cluster_result, noise_result, k = dbs.dbscan(test_data_vector, eps, min_pts)
# transfer result
result_data = np.mat(np.zeros((cluster_result.shape[0], 3)))
result_data[:, 0:2] = hp.vector2orientation(cluster_result[:, 0:3])
result_data[:, -1] = cluster_result[:, -1]
result_data = hp.degree2radian(result_data, 0)
noise_data = hp.vector2orientation(noise_result[:, 0:3])
noise_data = hp.degree2radian(noise_data, 0)
# print ang plot result
print("****************** cluster result ******************")
print("")
print(result_data)
print("")
print("****************** cluster result ******************")
print("")
print(noise_data)
print("number of cluster: ", k)
plt.createClusterDBSCAN(result_data.A, noise_data.A)
| UTF-8 | Python | false | false | 1,721 | py | 14 | testDbscan.py | 11 | 0.617664 | 0.599651 | 0 | 50 | 33.42 | 99 |
sray0309/SI-507-homework5 | 14,697,378,107,853 | 8ad5546f0dfa9ef07641ff3e090a8ac66ffd96de | af22f9953750bfd28980893e27504cdce5888769 | /hw5_tests_ec2.py | b33187293b3c6e58658d0294ffa9f120aa2ad127 | []
| no_license | https://github.com/sray0309/SI-507-homework5 | 205cd78005342515b2b8d8a8e891e7d95722088c | ff755cea3e083eff78fb3524a79a54aca56364f9 | refs/heads/main | 2023-03-26T18:07:07.275432 | 2021-03-14T19:31:35 | 2021-03-14T19:31:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import random, unittest
import hw5_cards_ec2
class Testec2(unittest.TestCase):
def test1(self):
d = hw5_cards_ec2.Deck() # create a deck
d.shuffle() # shuffle the deck
hand_size = random.randint(1,51) # generate a random hand size
hand = d.deal_hand(hand_size) # create a temp hand list from deck also update the deck
h = hw5_cards_ec2.Hand(hand) # create hand object
h.remove_pairs() # remove pairs in this hand
card_list = [i.rank for i in h.cards] # create a list of rank
for rank in card_list:
self.assertFalse(card_list.count(rank)==2)
self.assertFalse(card_list.count(rank)==4)
def test2(self):
d1 = hw5_cards_ec2.Deck() # create a deck for test num_cards_per_hand is not -1
d1.shuffle() # shuffle the deck
d2 = hw5_cards_ec2.Deck() # create a deck for test num_cards_per_hand is -1
d2.shuffle() # shuffle the deck
num_hands = random.randint(1,51)
# test num_cards_per_hand is not -1
num_cards = random.randint(1,52//num_hands)
hand_list = d1.deal(num_hands, num_cards)
for i in hand_list:
self.assertEqual(len(i.cards),num_cards)
# test num_cards_per_hand is -1
num_cards = 52//num_hands
hand_list = d2.deal(num_hands)
for i in hand_list:
self.assertTrue(len(i.cards) in [num_cards, num_cards+1])
if __name__=="__main__":
unittest.main() | UTF-8 | Python | false | false | 1,482 | py | 5 | hw5_tests_ec2.py | 4 | 0.604588 | 0.579622 | 0 | 40 | 36.075 | 94 |
sken10/tpow | 3,805,341,053,291 | 1f71be91b287abc84d829419ab585e9f3519c002 | 5666d371d4fe78d4bb0f7a63ae2f5d9465e7d1b5 | /tpow/__init__.py | e72b75325bda5b9749981968df382317163b2462 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | https://github.com/sken10/tpow | 095dd53d60413b86a14fa0f387a96e592bce715c | 6accbfe133a41959c2d35d5c8401e622d4f9efc2 | refs/heads/master | 2021-05-10T15:56:29.163286 | 2018-01-28T05:49:51 | 2018-01-28T05:49:51 | 118,565,827 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | __version__ = "0.2.0"
__license__ = "MIT License"
__author__ = "Kenichi SHIRAKAWA"
| UTF-8 | Python | false | false | 83 | py | 15 | __init__.py | 12 | 0.590361 | 0.554217 | 0 | 3 | 26.666667 | 32 |
EdenShuker/kaggle_project | 18,528,488,940,274 | a6ec40e5e2f0015f0cbf084c2cb9faa5c7f7f28f | cff6e0ef8ffb58b22fe378eb25c2c03b1b61a016 | /data/create_csv_data.py | 01a70a3a276c69d04532e96e34a54ade88d201ab | []
| no_license | https://github.com/EdenShuker/kaggle_project | 99ddfee8fcc6154c5e843ac46a830f23d2c4dc3b | be2038ffe58e5c4b3a0f9c3cb2d3c1dd51420143 | refs/heads/master | 2021-04-06T08:26:29.707781 | 2018-06-12T13:57:40 | 2018-06-12T13:57:40 | 124,678,518 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from csv import DictReader
label2dir = {'5': 'Benign', '1': 'Gatak', '2': 'Kelihos', '3': 'Kryptik', '4': 'Lollipop', '6': 'Ramnit', '7': 'Simda',
'8': 'Vundo', '9': 'Zbot'}
file2label = open('allLabels.csv')
with open('files2label.csv', 'w') as f:
for row in file2label:
file_name, label = row.split()
f.write('{}/{},{}\n'.format(label2dir[label], file_name, label))
f.close()
| UTF-8 | Python | false | false | 413 | py | 19 | create_csv_data.py | 14 | 0.559322 | 0.525424 | 0 | 11 | 36.545455 | 119 |
georgerapeanu/adibot | 9,431,748,198,999 | af6f3204633765aaa89b66a7ff54b86f9c11e89a | ae68a11dbae17ebc13127993003bad3953d199b4 | /scripts/preprocess.py | 5de5274c417405553d6f9fe3b7fa880e7c35177e | []
| no_license | https://github.com/georgerapeanu/adibot | e10db530a57333ccff7d07dc81b8377079ea25b0 | e3f7ce4812f2f0723def936d7f8b3820ab1aefaa | refs/heads/master | 2022-06-03T03:55:57.230452 | 2020-04-30T21:54:27 | 2020-04-30T21:54:27 | 259,831,622 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python3
# push test
import cv2;
import os;
import matplotlib.pyplot as plt;
import numpy as np;
R_MIN = (93,84,96)
R_MAX = (255,255,255);
def process(IMAGE_DIR,OUTPUT_DIR):
for filename in sorted(os.listdir(IMAGE_DIR)):
if(True or filename.endswith(".jpg")):
im = cv2.imread(os.path.join(IMAGE_DIR,filename));
thresh = cv2.inRange(im,R_MIN,R_MAX);
thresh_rgb = cv2.cvtColor(thresh,cv2.COLOR_GRAY2RGB);
print(filename);
contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
bst_rect = [];bst_area = 0;
for contour in contours:
rect = cv2.minAreaRect(contour);
center,size,theta = rect;
if(size[0] * size[1] > bst_area):
bst_rect = rect;
bst_area = size[0] * size[1];
center,size,theta = bst_rect;
center,size = tuple(map(int,center)),tuple(map(int,size));
print(theta);
if(theta + 45 < 0):
theta = theta + 90;
size = (size[1],size[0]);
elif(theta - 45 > 0):
theta = theta - 90;
size = (size[1],size[0]);
bordersize = int(max(im.shape[0],im.shape[1]) / 2 + 1);
im = cv2.copyMakeBorder(im,top=bordersize,bottom=bordersize,left=bordersize,right=bordersize,borderType=cv2.BORDER_CONSTANT,value = [0,0,0])
center = (center[0] + bordersize,center[1] + bordersize);
M = cv2.getRotationMatrix2D( center, -theta, 1)
big_dist = (im.shape[0] ** 2 + im.shape[1] ** 2) ** 0.5;
extract = cv2.warpAffine(im, M, (int(big_dist),int(big_dist)));
extract = cv2.getRectSubPix(extract, size, center);
while True:
cv2.imshow(filename,extract);
k = cv2.waitKey(0);
if(k == ord('s')):
cv2.destroyAllWindows();
break;
elif(k == ord('r')):
cv2.destroyAllWindows();
extract = cv2.rotate(extract,cv2.ROTATE_90_CLOCKWISE);
cv2.imwrite(os.path.join(OUTPUT_DIR,filename),extract);
| UTF-8 | Python | false | false | 2,259 | py | 5 | preprocess.py | 3 | 0.520142 | 0.486056 | 0 | 60 | 36.65 | 152 |
eost/pfi-utils | 10,866,267,283,476 | 22d85be407f784319e50d580ba15af2ee2ccbd55 | fff0fb30b1329ca88d69a6005d4a02197a01643e | /pyseQC/qc_repimp.py | bd95c4ee77ec3d1955ddf85a012f867bdc5b9901 | []
| no_license | https://github.com/eost/pfi-utils | 61ee5e98b1f0e2d6c3a5aaf8dbbc02fbb701ab64 | cb1902faeda32d5fdaba6cc0ad2e966efc173690 | refs/heads/master | 2018-01-04T08:09:00.944711 | 2017-12-06T16:17:04 | 2017-12-06T16:17:04 | 71,113,485 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
:author:
Maxime Bès de Berc (mbesdeberc@unistra.fr)
:copyright:
Maxime Bès de Berc (mbesdeberc@unistra.fr)
:license:
The Beerware License
(https://tldrlegal.com/license/beerware-license)
"""
from matplotlib import pyplot
import numpy as np
from obspy.core import UTCDateTime
from pyRepImp import repImp
def _qc_repimp(repimp_requests, server, error, sensor_period, sensor_damping,
sample_rate):
periods = np.array([])
periods_std = np.array([])
dampings = np.array([])
dampings_std = np.array([])
if len(repimp_requests) > 0:
i = 0
for request in repimp_requests:
print("%d %s" % (i, request))
i += 1
words = request.split(' ')
t1 = UTCDateTime(words[2])
t2 = UTCDateTime(words[3])
if sample_rate == 'HH':
stream = words[4].replace('BH', 'HH')
elif sample_rate == 'BH':
stream = words[4].replace('HH', 'BH')
else:
stream = words[4]
seed_codes = stream.split('.')
try:
wf = server.get_waveforms(seed_codes[0], seed_codes[1],
seed_codes[2], seed_codes[3], t1, t2,
route=False)
wf.merge()
for tr in wf:
(P, Ps, D, Ds, SNR) = repImp(tr, verbose=False,
plotting=False,
synchro_coils=True)
if P > sensor_period*(1+error) or\
P < sensor_period*(1-error) or\
D > sensor_damping*(1+error) or\
D < sensor_damping*(1-error) or\
SNR < 500:
print("Result out of range")
else:
periods = np.append(periods, P)
periods_std = np.append(periods_std, Ps)
dampings = np.append(dampings, D)
dampings_std = np.append(dampings_std, Ds)
except:
print("Bad request")
max_error_thperiod = np.abs(1 - periods/sensor_period).max()*100
max_error_avperiod = np.abs(1 - periods/periods.mean()).max()*100
max_error_thdamping = np.abs(1 - dampings/sensor_damping).max()*100
max_error_avdamping = np.abs(1 -
dampings/dampings.mean()).max()*100
if len(periods) == len(periods_std) and\
len(periods) == len(dampings) and\
len(periods) == len(dampings_std) and len(periods) > 0:
print("Repimp statistics:")
print("Average period: %.3f seconds" % (periods.mean()))
print("St. deviation of periods: %.3f seconds" %
(periods.std()))
print("Average damping: %.6f" % (dampings.mean()))
print("St. deviation of dampings: %.6f" % (dampings.std()))
print("Max error from theorical period: %.3f percent" %
(max_error_thperiod))
print("Max error from average period: %.3f percent" %
(max_error_avperiod))
print("Max error from theorical damping: %.3f percent" %
(max_error_thdamping))
print("Max error from average damping: %.3f percent" %
(max_error_avdamping))
print("")
fr = pyplot.figure('repimp', dpi=150)
ax = fr.gca()
ax.plot(dampings, periods, '.b')
ax.plot(sensor_damping, sensor_period, 'vr',
label='Theorical')
ax.errorbar(dampings.mean(), periods.mean(),
xerr=dampings.std(), yerr=periods.std(), fmt='or',
ecolor='r', label='Average/deviation')
ax.set_xlabel("Damping")
ax.set_ylabel("Period (s)")
ax.grid()
ax.legend(loc='best')
| UTF-8 | Python | false | false | 4,103 | py | 24 | qc_repimp.py | 18 | 0.481834 | 0.469154 | 0 | 103 | 38.815534 | 79 |
femalemoustache/python_test_tasks | 15,204,184,244,570 | cefae10c66f9127a7620a7968340c4f798ab05e4 | e35e325b29378b137f674529446c476449db32d1 | /task4.py | b3d1dc19ca705560421aab27df26e3adfcc34128 | []
| no_license | https://github.com/femalemoustache/python_test_tasks | 8ababb5ca42f0b66cfe79dc0da4378cb69012459 | 29170e33d0bf1b62bc2f5824bf98c5dac935b196 | refs/heads/master | 2016-08-07T11:44:11.219181 | 2015-04-17T13:30:13 | 2015-04-17T13:30:13 | 34,118,130 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class A(object):
def __init__(self):
print "A"
class B(A):
def __init__(self):
super(B, self).__init__() # Python 2.7
print "B"
b = B()
| UTF-8 | Python | false | false | 154 | py | 6 | task4.py | 5 | 0.5 | 0.487013 | 0 | 10 | 14.4 | 42 |
CharlieBliss/spellbook | 16,260,746,196,895 | 9c1ef2a53d6ec55d4e863811f8350650032a65a4 | b07adcac0a50f9047c4e4148c8986122ff1bb871 | /spellbook/spells/migrations/0003_auto_20181212_0404.py | fec4fdbed2e0e53d683d94513bbb106249e97540 | []
| no_license | https://github.com/CharlieBliss/spellbook | f60bd93ea42c3218d8ce020b7a8cca772688d491 | 49938e7ea74b0317f43ec2c45fa7dd53b71b111b | refs/heads/master | 2020-04-20T22:36:01.882065 | 2019-02-07T17:23:10 | 2019-02-07T17:23:10 | 169,145,462 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.1.4 on 2018-12-12 04:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spells', '0002_auto_20181212_0401'),
]
operations = [
migrations.AlterField(
model_name='spell',
name='area',
field=models.CharField(max_length=50),
),
migrations.AlterField(
model_name='spell',
name='range',
field=models.CharField(max_length=50),
),
migrations.AlterField(
model_name='spell',
name='target',
field=models.CharField(max_length=50),
),
]
| UTF-8 | Python | false | false | 685 | py | 49 | 0003_auto_20181212_0404.py | 46 | 0.541606 | 0.487591 | 0 | 28 | 23.464286 | 50 |
nhchenfeng/mmt | 11,106,785,476,308 | ad4ee0f2d3944720765bf58fba74a37f5909bf7a | 55db00c7a234176d7647c17719eee8a3268dcd1c | /draw/mmtest/linux.py | 6aadd569474c208b5e321a466ac9f692cb1ebd11 | []
| no_license | https://github.com/nhchenfeng/mmt | c9cee700eeba5ec7a3e4ea075fde541d356b366d | 1a1bce734b3febea8823b0e3068cc229ebf23d66 | refs/heads/master | 2021-10-14T07:03:34.178529 | 2016-12-26T14:35:25 | 2016-12-26T14:35:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
from curses.ascii import isdigit
from lib import *
from app import *
from view import *
from linux_cmd import linux
class device:
meminfo = ""
vmstat = ""
def init_device_info(self, Param):
local_linux = linux()
device.meminfo = local_linux.cmd("adb shell cat /proc/meminfo")
device.vmstat = local_linux.cmd("adb shell cat /proc/vmstat")
#print device.meminfo
#print device.vmstat
def get_device_info(self, Param):
local_lib = lib()
local_device = device()
local_device.init_device_info("");
#print "get info " + Param
i = 0
for i in range(len(device.meminfo)):
#print "look " + Param + " in meminfo " + str(device.meminfo[i])
if Param in str(device.meminfo[i]):
number = int(local_lib.get_str_first_value(device.meminfo[i]))
#print number
#print Param + str(number) + " " + "in meminfo"
return number
i = 0
for i in range(len(device.vmstat)):
#print "look " + Param + " in vmstat " + str(device.vmstat[i])
if Param in str(device.vmstat[i]):
number = int(local_lib.get_str_first_value(device.vmstat[i]))
#print number
#print Param + str(number) + " " + "in vmstat"
return number
def get_list_info(self, infolist):
local_device = device()
valuelist = []
for i in range(len(infolist)):
info = local_device.get_device_info(str(infolist[i]))
valuelist.append(str(infolist[i]) + " " + str(info) + " ")
return str("".join(valuelist))
if __name__ == '__main__':
local_device = device()
local_app = app()
local_view = view()
orig = "without"
new = "withpatch"
app_list = open("./littleapp.txt").readlines()
orig_log = open(orig, "a+")
new_log = open(new, "a+")
infolist = ["nr_free_pages","nr_inactive_anon","nr_active_anon","nr_inactive_file",
"nr_active_file", "nr_unevictable", "nr_mlock", "nr_anon_pages",
"nr_mapped", "nr_file_pages", "compact_migrate_scanned", "compact_isolated",
"pgrefill_dma32", "pgrefill_normal", "pgsteral_kswapd_dma32", "pgsteal_kswapd_normal",
"pgsteal_direct_dma32", "pgsteal_direct_normal", "pgscan_kswapd_dma32", "pgscan_kswapd_normal",
"pgscan_direct_dma32", "pgscan_direct_normal", "slabs_scanned", "unevictable_pgs_munlocked",
"MemFree", "MemAvailable", "slabs_scanned"]
# infolist = ["slabs_scanned", "pgscan_direct_normal", "pgscan_kswapd_normal", "MemFree"]
# infolist = ["slabs_scanned"]
# for i in range(len(app_list)):
# local_app.lunch_app(app_list[i])
# to_write = local_device.get_list_info(infolist)
# orig_log.write(str(to_write) + "\n")
# orig_log.close()
#
# for i in range(len(app_list)):
# local_app.lunch_app(app_list[i])
# to_write = local_device.get_list_info(infolist)
# new_log.write(str(to_write) + "\n")
# new_log.close()
local_view.draw_compare_figure(orig, new)
| UTF-8 | Python | false | false | 3,283 | py | 22 | linux.py | 17 | 0.553457 | 0.549802 | 0 | 84 | 38.071429 | 111 |
VaRkanar/werk24-python | 7,490,422,977,349 | b77e8024c8983d470b4fe615749273663041b6b9 | 8aea9f7c00947b43cd8309ba003a7e4cc1475388 | /werk24/gui/worker.py | 9da5f71ce95fdb0df073bb8e4be8cacb66a1aae7 | []
| no_license | https://github.com/VaRkanar/werk24-python | 7d8917037e242161362d878d7f66de80bc655c63 | 4a8ddcf5b0e08293262b842faf7c094ba1fa368f | refs/heads/master | 2023-06-07T10:42:10.778329 | 2021-07-06T19:16:53 | 2021-07-06T19:16:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from typing import List, Dict, Any, Callable
from PyQt5.QtCore import (QObject, QRunnable, pyqtSlot, pyqtSignal)
class W24GuiWorker(QRunnable):
""" Small worker class to execute non-blocking calls in
the background. Used to call the API while keeping the
GUI responsive
"""
def __init__(
self,
function: Callable,
*args: List[Any],
**kwargs: Dict[Any, Any]
) -> None:
""" Initiate a new 'thread' that calls
function when run() is executed
Args:
function: funcation to be called
"""
super(W24GuiWorker, self).__init__()
self.function = function
self.args = args
self.kwargs = kwargs
@pyqtSlot() # type: ignore # There is little we can do about that
def run(self) -> None:
"""
Run the predefined fucntion
"""
if self.function is not None:
self.function(*self.args, **self.kwargs)
class W24GuiWorkerSignals(QObject):
""" Defines the signals available from a running worker thread.
"""
result = pyqtSignal(object)
completion = pyqtSignal()
| UTF-8 | Python | false | false | 1,162 | py | 51 | worker.py | 42 | 0.594664 | 0.58864 | 0 | 42 | 26.642857 | 70 |
Dans-labs/dariah | 8,495,445,327,265 | 5366cf903810cbae300c37cb4502d72c825d34f1 | e75cbecd7cd419b7cc1ac911de42befa1f014124 | /server/index.py | 81825b3e581f1b8b5e1e5fbb78d79411b97cb96d | [
"MIT"
]
| permissive | https://github.com/Dans-labs/dariah | 7646504724b2b6a9ef62c22b574f13ec4440711b | 07c9b1a8efd60bda177c1276043209a1c6c55f02 | refs/heads/master | 2021-11-30T15:54:43.110269 | 2021-11-24T14:20:06 | 2021-11-24T14:20:06 | 53,429,449 | 0 | 1 | MIT | false | 2020-03-15T09:11:14 | 2016-03-08T16:57:21 | 2020-03-13T08:54:46 | 2020-03-15T09:11:13 | 155,763 | 0 | 0 | 3 | HTML | false | false | from flask import (
Flask,
render_template,
redirect,
)
from controllers.utils import dbjson
from controllers.db import DbAccess
from controllers.info import getInfo, selectContrib
from controllers.review import getReview, modReview
from controllers.cons import getCons
from controllers.file import FileApi
from controllers.controller import Controller
from controllers.auth import AuthApi
from controllers.perm import PermApi
def factory():
app = Flask(__name__, static_url_path="/xxx")
File = FileApi()
DB = DbAccess()
Auth = AuthApi(DB, app, "/opt/web-apps/dariah_jwt.secret")
Control = Controller(DB)
infoPages = set(
"""
ourcountry
ourcountry.tsv
""".strip().split()
)
reviewPages = set(
"""
my
""".strip().split()
)
@app.route("/static/<path:filepath>")
def serveStatic(filepath):
return File.static(filepath)
@app.route("/favicons/<path:filepath>")
def serveFavicons(filepath):
return File.static("favicons/{}".format(filepath))
@app.route("/index.html")
def serveIndex():
return render_template("index.html", css=Auth.CSS, js=Auth.JS)
@app.route("/info/<string:verb>")
def serveInfo(verb):
Auth.authenticate()
DB.addGroupInfo(Auth.userInfo)
if verb in infoPages:
asTsv = verb.endswith(".tsv")
data = getInfo(verb, Auth.userInfo, asTsv)
return (
data
if asTsv
else render_template("info.html", userInfo=Auth.userInfo, **data)
)
return render_template("index.html", css=Auth.CSS, js=Auth.JS)
@app.route("/review/<string:verb>")
def serveReview(verb):
Auth.authenticate()
DB.addGroupInfo(Auth.userInfo)
if verb in reviewPages:
data = getReview(verb, Auth.userInfo)
return render_template("review.html", userInfo=Auth.userInfo, **data)
return render_template("index.html", css=Auth.CSS, js=Auth.JS)
@app.route("/cons/<path:contribId>")
def serveCons(contribId):
Auth.authenticate()
data = getCons(contribId, Auth.userInfo)
return render_template("cons.html", css=Auth.CSS, js=Auth.JS, **data)
@app.route("/api/json/<path:doc>")
def serveApiJson(doc):
return dbjson(File.json(doc))
@app.route("/api/file/<path:doc>")
def serveApiFile(doc):
return File.static(doc)
@app.route("/api/db/who/ami")
def serveApiDbWho():
Auth.authenticate()
return dbjson(Auth.deliver())
@app.route("/api/db/selectc", methods=["GET", "POST"])
def selectC():
Auth.authenticate()
return dbjson(selectContrib(Auth.userInfo))
@app.route("/api/db/reviewmod", methods=["GET", "POST"])
def reviewMod():
Auth.authenticate()
return dbjson(modReview(Auth.userInfo))
@app.route("/api/db/<path:verb>", methods=["GET", "POST"])
def serveApiDb(verb):
Auth.authenticate()
Perm = PermApi(Auth)
return dbjson(Control.data(verb, Perm))
@app.route("/slogout")
def serveSlogout():
Auth.deauthenticate()
return redirect("/Shibboleth.sso/Logout")
@app.route("/login")
def serveLogin():
Auth.authenticate(login=True)
return render_template("index.html", css=Auth.CSS, js=Auth.JS)
@app.route("/logout")
def serveLogout():
Auth.deauthenticate()
return render_template("index.html", css=Auth.CSS, js=Auth.JS)
@app.route("/")
@app.route("/<path:anything>")
def client(anything=None):
Auth.authenticate()
return render_template("index.html", css=Auth.CSS, js=Auth.JS)
return app
if __name__ == "__main__":
app = factory()
| UTF-8 | Python | false | false | 3,809 | py | 233 | index.py | 117 | 0.61696 | 0.61696 | 0 | 134 | 27.425373 | 81 |
veryamini/Treehouse-Python | 8,169,027,818,101 | 649889062e1aaaa1c3a0381b6c411949f5dd8a6e | c3c6bf1377f7110fb8a648b5a91350b86e0cb876 | /Python Collections/Dictionaries/word_count2.py | c90c0bf524cdc5b3f2ba73dc8265ed3073ad51d0 | []
| no_license | https://github.com/veryamini/Treehouse-Python | 0975739ab5f29435e9278658f875d60752f73417 | 60f8ee1a2cb87b2202f701e2ab244b833bfce80e | refs/heads/master | 2020-03-21T20:50:31.345367 | 2018-07-10T15:42:36 | 2018-07-10T15:42:36 | 139,031,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.
def word_count(new_string):
words = list(new_string.lower().split())
words.sort()
print(words)
dictionary = {}
while True:
for i in range(len(words)-2):
count = 1
#print(i)
if words[i] == words[i+1]:
count += 1
i += 2
print(words[i])
pass
elif i == len(words) - 2:
break
dictionary[words[i]] = count
print(dictionary)
return dictionary
print(word_count("I do not like it Sam I Am"))
| UTF-8 | Python | false | false | 783 | py | 12 | word_count2.py | 11 | 0.469987 | 0.453384 | 0 | 26 | 28.115385 | 75 |
wesenu/udacity | 9,887,014,757,992 | 4fb5d7115f89b4092e79124a850bf7ea33cf5476 | 339afd37aa6ce68d61d5ec0fc512c3ebede0a016 | /basic_algorithms/problem_1.py | b6dbd648602db1ca35b0577de982321325549d64 | []
| no_license | https://github.com/wesenu/udacity | 174c5d48886b6c6ae4c4272140becabf9d3bfaa3 | 6657e0658082a885cce63d5fdb1a8046e27c0e7f | refs/heads/master | 2023-03-16T17:18:31.507001 | 2019-11-09T21:05:26 | 2019-11-09T21:05:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if (number is None) or (not isinstance(number, int)) or (number < 0):
print("The input should be an integer greater than 0")
return
start = 1
end = number
if (number == 0) or (number == 1):
return number
while start <= end:
mid = (start + end) // 2
# Found a match, return it
if (mid * mid == number):
return mid
# update range to lower partition
if (mid * mid > number):
end = mid - 1
# Update range to upper partition
else:
start = mid + 1
result = mid
return result
# Provided example
print ("Pass" if (3 == sqrt(9)) else "Fail")
print ("Pass" if (0 == sqrt(0)) else "Fail")
print ("Pass" if (4 == sqrt(16)) else "Fail")
print ("Pass" if (1 == sqrt(1)) else "Fail")
print ("Pass" if (5 == sqrt(27)) else "Fail")
# Test cases
print("Test case 1")
print ("Pass" if (None == sqrt(-100)) else "Fail") # Expects None when input is a negative number
print("Test case 2")
print ("Pass" if (None == sqrt(None)) else "Fail") # Expects None when input is None
print("Test case 3")
print ("Pass" if (None == sqrt("abcdefg")) else "Fail") # Expects None when input is a string type
print("Test case 4")
print ("Pass" if (0 == sqrt(0)) else "Fail") # Expects 0 when input is 0
print("Test case 5")
print ("Pass" if (1 == sqrt(1)) else "Fail") # Expects 1 when input is 1
print("Test case 6")
print ("Pass" if (None == sqrt(16.5)) else "Fail") # Expects None when input a decimal number | UTF-8 | Python | false | false | 1,758 | py | 24 | problem_1.py | 11 | 0.580205 | 0.557452 | 0 | 62 | 27.370968 | 100 |
LuisAngelGonzalezA/TTI | 12,163,347,406,410 | 682f8030cd56a2c4d685aa55ef1c964407c1c323 | 7f61a702ec89c0084e492db3dd2ee4dd0a7cc7b0 | /TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/vista.py | 7ced160acfe0d72ac2fbfb0f6e2d748aec07f215 | []
| no_license | https://github.com/LuisAngelGonzalezA/TTI | dee50b6500dd5b5fb30987dcfd27e82c8ca6b5c8 | bc69b627b3c67a48182485fc02a4f5679ee6a415 | refs/heads/master | 2020-03-30T08:32:41.419281 | 2019-06-11T07:57:14 | 2019-06-11T07:57:14 | 151,023,323 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from tkinter import *
import tkinter as Tk
import mysql_conection
from tkinter import ttk
import tkinter.font as tkFont
import vista as vis
import cerrar_ven
import table
import insert
import update_ventana
import mostrar_grafica
import eliminar
from functools import partial
from tkinter import messagebox
def vista_select_tabla(self):
self.dialogo = Toplevel(self.parent)
cerrar_select_dialogo=cerrar_ven.cerrar_select(self.dialogo)
self.dialogo.transient(master=self.parent)
Letrero=Tk.Label(self.dialogo,text="Tornasol",fg="green",font=("Arial",18))
img = Tk.PhotoImage(file="/home/pi/TTI/TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/panel2.gif")
imagen_inicio = Tk.Label(self.dialogo, image=img)
boton_regresar = Tk.Button(self.dialogo, text='Regresar',command=self.dialogo.destroy,relief=Tk.SOLID,font="Times 12",bd=4,width=20, height=1,activebackground="red")
boton_aceptar =Tk.Button(self.dialogo, text='Cerrar',command=self.dialogo.destroy)
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("desc bateria")
print("--->",type(cursor))
print("\n\n")
lista=tuple()
for row in cursor:
lista=list(lista)
lista.append(row[0])
lista=tuple(lista)
#lista.extend(row[0])
#print(row[0])
lista=list(lista)
del lista[0]
del lista[0]
del lista[6]
del lista[6]
lista=tuple(lista)
print(lista)
tabla_baterias = table.Table(self.dialogo, title="Baterias registradas", headers=lista)
lista=tuple()
cursor.execute("select*from bateria where isEliminado=0")
for row in cursor:
lista=list(row)
del lista[0]
del lista[0]
del lista[6]
del lista[6]
lista=tuple(lista)
tabla_baterias.add_row(lista)
cursor.execute("desc panel_solar")
print("--->",type(cursor))
print("\n\n")
lista=tuple()
for row in cursor:
lista=list(lista)
lista.append(row[0])
lista=tuple(lista)
#lista.extend(row[0])
#print(row[0])
lista=list(lista)
del lista[0]
del lista[0]
del lista[3]
lista=tuple(lista)
print(lista)
tabla_panel = table.Table(self.dialogo, title="Paneles Fotovoltaicos registradas", headers=lista)
lista=tuple()
cursor.execute("select*from panel_solar where isEliminado=0")
for row in cursor:
lista=list(row)
del lista[0]
del lista[0]
del lista[3]
lista=tuple(lista)
tabla_panel.add_row(lista)
boton_regresar.pack(side=BOTTOM,padx=10, pady=5)
tabla_baterias.pack(side=BOTTOM, fill=BOTH, expand=True,padx=10, pady=5)
tabla_panel.pack(side=BOTTOM, fill=BOTH, expand=True,padx=10, pady=5)
Letrero.pack(side=LEFT, fill=BOTH, expand=True,padx=10, pady=5)
imagen_inicio.pack(side=RIGHT, fill=BOTH, expand=True,padx=10, pady=5)
self.dialogo.minsize(width=380, height=400)
self.dialogo.maxsize(width=1200, height=850)
width=500
heigth=700
x=(self.dialogo.winfo_width()//2)+30+(width//2)
y=(self.dialogo.winfo_height()//2)-(heigth//2)
self.dialogo.geometry('{}x{}+{}+{}'.format(width,heigth,x,y))
self.dialogo.overrideredirect(0)
# El método grab_set() asegura que no haya eventos
# de ratón o teclado que se envíen a otra ventana
# diferente a 'self.dialogo'. Se utiliza para
# crear una ventana de tipo modal que será
# necesario cerrar para poder trabajar con otra
# diferente. Con ello, también se impide que la
# misma ventana se abra varias veces.
self.dialogo.grab_set()
self.parent.wait_window(self.dialogo)
def vista_insertar(self):
self.dialogo = Toplevel(self.parent)
cerrar_select_dialogo=cerrar_ven.cerrar_select(self.dialogo)
self.dialogo.transient(master=self.parent)
Letrero=Tk.Label(self.dialogo,text="Tornasol",fg="green",font=("Arial",18))
img = Tk.PhotoImage(file="/home/pi/TTI/TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/panel.gif")
action_insert_ventana_bateria = partial(insert.insert_bateria, self.dialogo)
action_insert_ventana_panel = partial(insert.insert_panel, self.dialogo)
imagen_inicio = Tk.Label(self.dialogo, image=img)
boton_regresar = Tk.Button(self.dialogo, text='Regresar',command=self.dialogo.destroy,relief=Tk.SOLID,font="Times 12",bd=4,width=20, height=1,activebackground="red")
Boton_PANEL=Tk.Button(self.dialogo, text ="Insertar Panel Fotovoltaicos", command =action_insert_ventana_panel, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
Boton_Baterias=Tk.Button(self.dialogo, text ="Insertar Bateria", command = action_insert_ventana_bateria, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
Letrero.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
imagen_inicio.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
Boton_PANEL.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
Boton_Baterias.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
boton_regresar.pack(side=TOP,padx=10, pady=5)
self.dialogo.minsize(width=380, height=400)
self.dialogo.maxsize(width=500, height=650)
width=450
heigth=500
x=(self.dialogo.winfo_width()//2)+30+(width//2)
y=(self.dialogo.winfo_height()//2)-(heigth//2)
self.dialogo.geometry('{}x{}+{}+{}'.format(width,heigth,x,y))
self.dialogo.overrideredirect(0)
# El método grab_set() asegura que no haya eventos
# de ratón o teclado que se envíen a otra ventana
# diferente a 'self.dialogo'. Se utiliza para
# crear una ventana de tipo modal que será
# necesario cerrar para poder trabajar con otra
# diferente. Con ello, también se impide que la
# misma ventana se abra varias veces.
self.dialogo.grab_set()
self.parent.wait_window(self.dialogo)
def vista_uodate_panel(self):
self.dialogo = Toplevel(self.parent)
cerrar_select_dialogo=cerrar_ven.cerrar_select(self.dialogo)
self.dialogo.transient(master=self.parent)
Letrero=Tk.Label(self.dialogo,text="Tornasol",fg="green",font=("Arial",18))
img = Tk.PhotoImage(file="/home/pi/TTI/TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/panel.gif")
action_insert_ventana_bateria = partial(update_ventana.update_ven_bateria, self.dialogo)
action_insert_ventana_panel = partial(update_ventana.update_ven, self.dialogo)
imagen_inicio = Tk.Label(self.dialogo, image=img)
boton_regresar = Tk.Button(self.dialogo, text='Regresar',command=self.dialogo.destroy,relief=Tk.SOLID,font="Times 12",bd=4,width=20, height=1,activebackground="red")
Boton_PANEL=Tk.Button(self.dialogo, text ="Actualizar Panel Fotovoltaicos", command =action_insert_ventana_panel, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
Boton_Baterias=Tk.Button(self.dialogo, text ="Actualizar Bateria", command = action_insert_ventana_bateria, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
Letrero.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
imagen_inicio.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
Boton_PANEL.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
Boton_Baterias.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
boton_regresar.pack(side=TOP,padx=10, pady=5)
self.dialogo.minsize(width=380, height=550)
self.dialogo.maxsize(width=500, height=650)
width=450
heigth=550
x=(self.dialogo.winfo_width()//2)+30+(width//2)
y=(self.dialogo.winfo_height()//2)-(heigth//2)
self.dialogo.geometry('{}x{}+{}+{}'.format(width,heigth,x,y))
self.dialogo.overrideredirect(0)
# El método grab_set() asegura que no haya eventos
# de ratón o teclado que se envíen a otra ventana
# diferente a 'self.dialogo'. Se utiliza para
# crear una ventana de tipo modal que será
# necesario cerrar para poder trabajar con otra
# diferente. Con ello, también se impide que la
# misma ventana se abra varias veces.
self.dialogo.grab_set()
self.parent.wait_window(self.dialogo)
def vista_gfrafica(self):
self.dialogo = Toplevel(self.parent)
cerrar_select_dialogo=cerrar_ven.cerrar_select(self.dialogo)
self.dialogo.transient(master=self.parent)
Letrero=Tk.Label(self.dialogo,text="Tornasol",fg="green",font=("Arial",18))
img = Tk.PhotoImage(file="/home/pi/TTI/TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/panel.gif")
action_insert_ventana_bateria = partial(update_ventana.update_ven_bateria, self.dialogo)
action_insert_ventana_panel = partial(update_ventana.update_ven, self.dialogo)
imagen_inicio = Tk.Label(self.dialogo, image=img)
boton_regresar = Tk.Button(self.dialogo, text='Regresar',command=self.dialogo.destroy,relief=Tk.SOLID,font="Times 12",bd=4,width=20, height=1,activebackground="red")
Boton_PANEL=Tk.Button(self.dialogo, text ="Gráfica de Panel", command =mostrar_grafica.panel, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
Boton_Baterias=Tk.Button(self.dialogo, text ="Gráficar de Bateria", command = mostrar_grafica.bateria, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
#Boton_Baterias_descarga=Tk.Button(self.dialogo, text ="Gráficar de Bateria descarga", command = action_insert_ventana_bateria, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
Letrero.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
imagen_inicio.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
Boton_PANEL.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
Boton_Baterias.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
Boton_Baterias_descarga.pack(side=TOP, fill=BOTH, expand=True,padx=5, pady=5)
boton_regresar.pack(side=TOP,padx=10, pady=5)
self.dialogo.minsize(width=380, height=550)
self.dialogo.maxsize(width=500, height=650)
width=450
heigth=550
x=(self.dialogo.winfo_width()//2)+30+(width//2)
y=(self.dialogo.winfo_height()//2)-(heigth//2)
self.dialogo.geometry('{}x{}+{}+{}'.format(width,heigth,x,y))
self.dialogo.overrideredirect(0)
# El método grab_set() asegura que no haya eventos
# de ratón o teclado que se envíen a otra ventana
# diferente a 'self.dialogo'. Se utiliza para
# crear una ventana de tipo modal que será
# necesario cerrar para poder trabajar con otra
# diferente. Con ello, también se impide que la
# misma ventana se abra varias veces.
self.dialogo.grab_set()
self.parent.wait_window(self.dialogo)
def vista_eliminar(self):
self.dialogo = Toplevel(self.parent)
self.panel_eliminado=StringVar()
self.bateria_eliminado=StringVar()
cerrar_select_dialogo=cerrar_ven.cerrar_select(self.dialogo)
self.dialogo.transient(master=self.parent)
Letrero=Tk.Label(self.dialogo,text="Tornasol",fg="green",font=("Arial",18))
img = Tk.PhotoImage(file="/home/pi/TTI/TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/panel.gif")
action_insert_ventana_bateria = partial(update_ventana.update_ven_bateria, self.dialogo)
action_insert_ventana_panel = partial(update_ventana.update_ven, self.dialogo)
action_eliminar_panel = partial(eliminar.eliminar_panel,self)
action_eliminar_bateria = partial(eliminar.eliminar_bateria,self)
imagen_inicio = Tk.Label(self.dialogo, image=img)
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("select nombre from panel_solar where isEliminado=0")
print("--->",type(cursor))
print("\n\n")
lista=tuple()
for row in cursor:
lista=list(lista)
lista.append(row[0])
lista=tuple(lista)
#lista.extend(row[0])
#print(row[0])
lista=list(lista)
if len(lista) <=0:
lista.append("No hay paneles para eliminar ")
db.close()
self.panel=Tk.Label(self.dialogo, text="Eliminar panel",font="Arial 14",justify=Tk.CENTER)
self.panel_select= Tk.OptionMenu(self.dialogo, self.panel_eliminado,*lista)
self.Boton_aceptar_eliminar_panel=Tk.Button(self.dialogo, text ="Eliminar panel", command =action_eliminar_panel , activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("select nombre from bateria where isEliminado=0")
print("--->",type(cursor))
print("\n\n")
lista=tuple()
for row in cursor:
lista=list(lista)
lista.append(row[0])
lista=tuple(lista)
#lista.extend(row[0])
#print(row[0])
lista=list(lista)
if len(lista) <=0:
lista.append("No hay paneles para eliminar ")
db.close()
self.bateria=Tk.Label(self.dialogo, text="Eliminar panel",font="Arial 14",justify=Tk.CENTER)
self.bateria_select= Tk.OptionMenu(self.dialogo, self.bateria_eliminado,*lista)
self.Boton_aceptar_eliminar_bateria=Tk.Button(self.dialogo, text ="Eliminar batería", command =action_eliminar_bateria , activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
boton_regresar = Tk.Button(self.dialogo, text='Regresar',command=self.dialogo.destroy,relief=Tk.SOLID,font="Times 12",bd=4,width=20, height=1,activebackground="red")
Letrero.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.panel.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.panel_select.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.Boton_aceptar_eliminar_panel.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.bateria.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.bateria_select.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.Boton_aceptar_eliminar_bateria.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
boton_regresar.pack(side=TOP,padx=10, pady=5)
self.dialogo.minsize(width=380, height=550)
self.dialogo.maxsize(width=500, height=650)
width=450
heigth=550
x=(self.dialogo.winfo_width()//2)+30+(width//2)
y=(self.dialogo.winfo_height()//2)-(heigth//2)
self.dialogo.geometry('{}x{}+{}+{}'.format(width,heigth,x,y))
self.dialogo.overrideredirect(0)
# El método grab_set() asegura que no haya eventos
# de ratón o teclado que se envíen a otra ventana
# diferente a 'self.dialogo'. Se utiliza para
# crear una ventana de tipo modal que será
# necesario cerrar para poder trabajar con otra
# diferente. Con ello, también se impide que la
# misma ventana se abra varias veces.
self.dialogo.grab_set()
self.parent.wait_window(self.dialogo)
def usar_panel_bateria(self):
self.dialogo = Toplevel(self.parent)
self.panel_eliminado=StringVar()
self.bateria_eliminado=StringVar()
cerrar_select_dialogo=cerrar_ven.cerrar_select(self.dialogo)
self.dialogo.transient(master=self.parent)
Letrero=Tk.Label(self.dialogo,text="Tornasol",fg="green",font=("Arial",18))
img = Tk.PhotoImage(file="/home/pi/TTI/TTI/Interfaz_grafica_python/Documentos/pruebas_python/sistema/panel.gif")
imagen_inicio = Tk.Label(self.dialogo, image=img)
action_insert_ventana_bateria = partial(update_ventana.update_ven_bateria, self.dialogo)
action_insert_ventana_panel = partial(update_ventana.update_ven, self.dialogo)
action_usar = partial(usar_panel_bateria_vista,self)
imagen_inicio = Tk.Label(self.dialogo, image=img)
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("select nombre from panel_solar where isEliminado=0")
print("--->",type(cursor))
print("\n\n")
lista=tuple()
for row in cursor:
lista=list(lista)
lista.append(row[0])
lista=tuple(lista)
#lista.extend(row[0])
#print(row[0])
lista=list(lista)
db.close()
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("select b.nombre from bateria b,historial_bateria_panel hpb where hpb.id_bateria=b.id_bateria and hpb.activo=1")
print("--->",type(cursor))
print("\n\n")
nombre_noti="No hay bateria usada actualmente"
for row in cursor:
nombre_noti="Actualmente se usa \n '{nombre_bateria}'".format(nombre_bateria=row[0])
#lista.extend(row[0])
#print(row[0])
db.close()
self.panel_notificacion=Tk.Label(self.dialogo, text=nombre_noti,font="Arial 14",justify=Tk.CENTER)
self.panel=Tk.Label(self.dialogo, text="Usar panel",font="Arial 14",justify=Tk.CENTER)
self.panel_select= Tk.OptionMenu(self.dialogo, self.panel_eliminado,*lista)
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("select nombre from bateria where isEliminado=0")
print("--->",type(cursor))
print("\n\n")
lista=tuple()
for row in cursor:
lista=list(lista)
lista.append(row[0])
lista=tuple(lista)
#lista.extend(row[0])
#print(row[0])
lista=list(lista)
db.close()
self.bateria=Tk.Label(self.dialogo, text="Usar panel",font="Arial 14",justify=Tk.CENTER)
self.bateria_select= Tk.OptionMenu(self.dialogo, self.bateria_eliminado,*lista)
self.Boton_aceptar_eliminar_bateria=Tk.Button(self.dialogo, text ="Usar", command = action_usar, activebackground="yellow",relief=Tk.SOLID,bg="green",font="Times 12",bd=4)
boton_regresar = Tk.Button(self.dialogo, text='Regresar',command=self.dialogo.destroy,relief=Tk.SOLID,font="Times 12",bd=4,width=20, height=1,activebackground="red")
Letrero.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
imagen_inicio.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.panel_notificacion.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.panel.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.panel_select.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.bateria.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.bateria_select.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
self.Boton_aceptar_eliminar_bateria.pack(side=TOP, fill=BOTH, expand=True,padx=10, pady=5)
boton_regresar.pack(side=TOP,padx=10, pady=5)
self.dialogo.minsize(width=380, height=680)
self.dialogo.maxsize(width=500, height=680)
width=450
heigth=680
x=(self.dialogo.winfo_width()//2)+30+(width//2)
y=(self.dialogo.winfo_height()//2)-(heigth//2)
self.dialogo.geometry('{}x{}+{}+{}'.format(width,heigth,x,y))
self.dialogo.overrideredirect(0)
# El método grab_set() asegura que no haya eventos
# de ratón o teclado que se envíen a otra ventana
# diferente a 'self.dialogo'. Se utiliza para
# crear una ventana de tipo modal que será
# necesario cerrar para poder trabajar con otra
# diferente. Con ello, también se impide que la
# misma ventana se abra varias veces.
self.dialogo.grab_set()
self.parent.wait_window(self.dialogo)
def usar_panel_bateria_vista(self):
if not self.panel_eliminado.get().strip() and not self.bateria_eliminado.get().strip():
messagebox.showinfo("Error","No ha seleccionado panel y bateria a usar")
elif not self.panel_eliminado.get().strip() :
messagebox.showinfo("Error","No ha seleccionado panel a usar")
elif not self.bateria_eliminado.get().strip():
messagebox.showinfo("Error","No ha seleccionado bateria a usar")
else:
consulta="update historial_bateria_panel set activo ='0' where activo='1'"
print(consulta)
mysql=mysql_conection.mysql_conexion_tornasol()
cursor = mysql.cursor()
resultado=cursor.execute(consulta)
mysql.commit()
mysql.close
consulta="insert into historial_bateria_panel values(null,(select id_panel from panel_solar where nombre='{nombre_panel}' and isEliminado=0),(select id_bateria from bateria where nombre='{nombre_bateria}' and isEliminado=0),now(),1)".format(nombre_panel=self.panel_eliminado.get(),nombre_bateria=self.bateria_eliminado.get())
print(consulta)
mysql=mysql_conection.mysql_conexion_tornasol()
cursor = mysql.cursor()
resultado=cursor.execute(consulta)
mysql.commit()
print(resultado)
if resultado>=1:
messagebox.showinfo("OK","Se seleccionado panel y bateria a usar")
else:
messagebox.showinfo("Error","No ha seleccionado panel y bateria a usar")
mysql.close()
db =mysql_conection.mysql_conexion_tornasol()
cursor = db.cursor()
cursor.execute("select b.nombre from bateria b,historial_bateria_panel hpb where hpb.id_bateria=b.id_bateria and hpb.activo=1")
print("--->",type(cursor))
print("\n\n")
nombre_noti="No hay bateria usada actualmente"
for row in cursor:
nombre_noti="Actualmente se usa \n '{nombre_bateria}'".format(nombre_bateria=row[0])
#lista.extend(row[0])
#print(row[0])
db.close()
self.panel_notificacion.configure(text=nombre_noti)
| UTF-8 | Python | false | false | 20,608 | py | 149 | vista.py | 57 | 0.715029 | 0.695538 | 0 | 523 | 38.33652 | 327 |
Naatoo/advent_of_code_2020 | 15,590,731,296,245 | 9ec9f2f8990f223be722eed3bb14d20641f83a4e | 802b6999fe759954d0de4b3793bb4bd34e03f87d | /day9/solution.py | 0e0c47541fb2075232171e806ef8b86694a8ffc1 | []
| no_license | https://github.com/Naatoo/advent_of_code_2020 | bbe977f4ec7335a95c0898e65616ccb838bac9ba | 880e8a948852de9e33da4c216a42979d627b3cd0 | refs/heads/master | 2023-02-28T00:36:38.374187 | 2021-01-31T21:39:27 | 2021-01-31T21:39:27 | 317,694,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import collections
import itertools
from typing import Generator, Tuple
def parse_file() -> Generator[int, None, None]:
with open("input.txt") as file:
yield from map(int, file.readlines())
def part_1(preamble: int = 25) -> int:
program: Generator[int, None, None] = parse_file()
current_values: collections.deque = collections.deque((next(program) for _ in range(preamble)), maxlen=preamble)
while (num := next(program)) in set(map(sum, itertools.combinations(current_values, 2))):
current_values.append(num)
return num
def part_2(val: int) -> int:
program: Tuple[int] = tuple(parse_file())
for basic_index in itertools.count():
for index in itertools.count(basic_index):
zxc = sum(program[basic_index: index])
if zxc > val:
break
elif zxc == val:
vbn = program[basic_index: index]
return min(vbn) + max(vbn)
part_1_res: int = part_1()
print("Part 1:", part_1_res)
print("Part 2:", part_2(part_1_res))
| UTF-8 | Python | false | false | 1,047 | py | 12 | solution.py | 12 | 0.618911 | 0.60745 | 0 | 33 | 30.727273 | 116 |
PythonCoderAS/ProgramWorker | 16,707,422,790,476 | 37489d2e63f56c5f59a3aa848aae0d509eeb93a7 | 894e9e3b4a3dc2a7e1a602babaf3398866369776 | /filecleaner.py | f4f3199a337f0a916be36077fb679dcb4596128f | [
"MIT"
]
| permissive | https://github.com/PythonCoderAS/ProgramWorker | a6c9bee331e799294bded4b9a40b4d21eb3932e3 | 74902f6327072e12d460259098a275d5c28bfc03 | refs/heads/master | 2020-03-16T23:57:19.133607 | 2018-05-11T23:57:58 | 2018-05-11T23:57:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
from .utils import *
temp = getvar('temp')
windowstemp =
| UTF-8 | Python | false | false | 69 | py | 5 | filecleaner.py | 5 | 0.695652 | 0.695652 | 0 | 5 | 12.6 | 21 |
quantum-compiler/quartz-artifact | 17,867,063,973,086 | d7865df1e866bb43e927c1f03cb08fad86e68621 | a085153abaf16eae2a0f9bdbb14540aa42959b23 | /extract_results.py | 0cce73c524fa2820e36d2869bc9741a15a2761a2 | []
| no_license | https://github.com/quantum-compiler/quartz-artifact | c76779821303c1ab52870717c85186708bed4f70 | 20f6747d8f1ffb943fa017fe84bec342f22441cf | refs/heads/main | 2023-04-16T01:40:58.078260 | 2022-08-05T00:58:58 | 2022-08-05T00:58:58 | 464,661,620 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
import os
from natsort import natsorted
verbose = True
original_val = [900, 58, 114, 170, 450, 170, 420, 225, 347, 495, 669, 883, 1095, 1347, 63, 119, 278, 521, 443, 884, 200, 45, 75, 105, 255, 150]
circuit_names = ['adder_8', 'barenco_tof_3', 'barenco_tof_4', 'barenco_tof_5', 'barenco_tof_10', 'csla_mux_3', 'csum_mux_9', 'gf2^4_mult', 'gf2^5_mult', 'gf2^6_mult', 'gf2^7_mult', 'gf2^8_mult', 'gf2^9_mult', 'gf2^10_mult', 'mod5_4', 'mod_mult_55', 'mod_red_21', 'qcla_adder_10', 'qcla_com_7', 'qcla_mod_7', 'rc_adder_6', 'tof_3', 'tof_4', 'tof_5', 'tof_10', 'vbe_adder_3']
circuit_name_map = {}
for i in range(26):
circuit_name_map[circuit_names[i]] = i
original_product = 1
for val in original_val:
original_product *= val
num_timestamps = 73
timestamps = [i * 900 if i < 48 else (i - 24) * 1800 for i in range(num_timestamps)]
default_timeout = 86400
mod54 = False
def extract_results(content, max_timeout=default_timeout, output_filename=None):
flag = False
tot_time = 0
tot_gate = 0
num_finished = 0
gate_product = 1
key = ''
result = {}
result_timestamps = [{} for _ in range(num_timestamps)]
iters_data = {}
for line in content:
line = line.strip()
data = line.split()
if len(data) >= 2 and data[1].startswith('bestCost('):
if float(data[-2]) > max_timeout:
continue
key = data[0].split('.')[0]
val_float = float(data[1].split('.')[0][9:])
val = data[1].split('.')[0][9:] + ' (at ' + data[-2] + ' seconds)'
if not mod54:
val_reduction = 1 - val_float / original_val[circuit_name_map[key]]
else:
val_reduction = 1 - val_float / 63
result[key] = val
if key not in result_timestamps[0]: # first time
for i in range(num_timestamps):
result_timestamps[i][key] = val_float
iters_data[key] = [val_reduction]
else:
for i in range(num_timestamps - 1, -1, -1):
if timestamps[i] < float(data[-2]):
break
result_timestamps[i][key] = val_float
iters_data[key].append(val_reduction)
if mod54:
continue
if flag:
pos = line.find(':')
pos2 = line.find(',', pos)
pos3 = line.find('s', pos2)
if not line[pos + 2:pos2].isnumeric():
continue
val = line[pos + 2:pos2]
result[key] = val
num_finished += 1
tot_gate += int(line[pos + 2:pos2])
gate_product *= int(line[pos + 2:pos2])
tot_time += float(line[pos2 + 2:pos3])
if line.startswith('Optimization'):
flag = True
pos = line.find('.qasm')
pos2 = line.rfind(' ', 0, pos)
key = line[pos2 + 1:pos]
else:
flag = False
if len(data) >= 2 and data[1] == 'Timeout.' and max_timeout == default_timeout:
key = data[0].split('.')[0]
val = data[-1].split('.')[0] + ' (timeout)'
result[key] = val
num_finished += 1
tot_gate += int(float(data[-1]))
gate_product *= int(float(data[-1]))
tot_time += max_timeout
for k, v in natsorted(result.items()):
print(k.ljust(15), v)
print('num_circuits (finished) =', num_finished)
print('tot_gate =', tot_gate)
if num_finished > 0:
print('geomean_gatecount =', gate_product ** (1 / num_finished))
print('tot_time =', tot_time)
if not verbose:
return
print('[', end='')
for k, v in natsorted(result.items()): # easy paste to Python script to plot
if v.isnumeric():
print(v, end=', ')
else:
print(v.split(' ')[0], end=', ')
print('],')
if (len(result_timestamps[0]) == 26 or mod54) and not output_filename.startswith('Rigetti'):
result_timestamps_geomean_reduction = []
result_timestamps_reduction = {}
for i in range(num_timestamps):
val = 1.0 / (63**len(result_timestamps[0]) if mod54 else original_product)
assert len(result_timestamps[i]) == 26 or mod54
cnt = 0
for k, v in natsorted(result_timestamps[i].items()):
val *= v
if i == 0:
result_timestamps_reduction[k] = []
result_timestamps_reduction[k].append(1 - v / (63 if mod54 else original_val[cnt]))
cnt += 1
val = val ** (1.0 / len(result_timestamps[i]))
val = 1 - val
result_timestamps_geomean_reduction.append(val)
print(result_timestamps_geomean_reduction, ',')
print(result_timestamps_reduction, ',')
with open('plot-scripts/' + output_filename + '_iterations.log', 'w') as f:
print(iters_data, file=f)
print('Wrote iteration data to the file plot-scripts/' + output_filename + '_iterations.log')
def extract_results_from_file(filename):
with open(filename) as f:
content = f.readlines()
extract_results(content, output_filename=filename)
def extract_results_from_files(prefix, max_timeout=default_timeout):
global mod54
if 'mod5_4' in prefix:
mod54 = True
files = [f for f in os.listdir('.') if f.startswith(prefix) and f.endswith('log')]
content = []
for filename in files:
with open(filename) as f:
if mod54:
lns = f.readlines()
for line in lns:
content.append(filename + line)
else:
content += f.readlines()
extract_results(content, max_timeout, output_filename=prefix)
if __name__ == '__main__':
if len(sys.argv) < 2 or len(sys.argv) > 3:
print('Usage:')
print('For final result: python extract_results.py [result file name (need to be a .txt file), e.g., scalability_32.txt]')
print('For intermediate result: python extract_results.py [ECC set name, i.e., Nam_6_3/IBM_4_3/Rigetti_6_3] [Max running time (s) (default=86400)]')
exit()
if sys.argv[1].endswith('.txt'):
extract_results_from_file(sys.argv[1])
else:
if len(sys.argv) == 3:
extract_results_from_files(sys.argv[1], float(sys.argv[2]))
else:
extract_results_from_files(sys.argv[1])
| UTF-8 | Python | false | false | 6,486 | py | 174 | extract_results.py | 108 | 0.539778 | 0.500154 | 0 | 163 | 38.791411 | 373 |
mojtaba-arvin/video-service | 6,863,357,788,430 | 5ca26553b293b6e50c6f1e00b0ba88770092ed7e | 9a6eae37a03647aae2d590d8dd96cae2b558181f | /video-streaming/video_streaming/grpc/exceptions.py | a03dd0ca7987334229d7a9e9f66ba1cced9fb242 | [
"MIT"
]
| permissive | https://github.com/mojtaba-arvin/video-service | 35382dc4e93c4f8afc591c83d12e6d00b1bea6f9 | d75bd59d8203277fc6a50440d3f0b34693958ee1 | refs/heads/develop | 2023-04-02T02:59:36.888720 | 2021-04-01T10:11:50 | 2021-04-01T10:11:50 | 340,950,715 | 25 | 5 | MIT | false | 2021-04-01T10:11:50 | 2021-02-21T16:42:37 | 2021-03-31T20:17:16 | 2021-04-01T10:11:50 | 407 | 5 | 0 | 0 | Python | false | false | from video_streaming.core.constants import ErrorMessages, ErrorCodes
from video_streaming.core.exceptions import GrpcBaseException
__all__ = [
'S3KeyCanNotBeEmptyException',
'BucketNameIsNotValidException',
'DuplicateOutputLocationsException',
'OneOutputIsRequiredException',
'JobNotFoundException',
'JobIsFailedException',
'JobIsRevokedException',
'JobIsFinishedException',
'NoWatermarkToUseException'
]
class S3KeyCanNotBeEmptyException(GrpcBaseException):
status_code = ErrorCodes.S3_KEY_CAN_NOT_BE_EMPTY
message = ErrorMessages.S3_KEY_CAN_NOT_BE_EMPTY
class BucketNameIsNotValidException(GrpcBaseException):
status_code = ErrorCodes.S3_BUCKET_NAME_IS_NOT_VALID
message = ErrorMessages.S3_BUCKET_NAME_IS_NOT_VALID
class DuplicateOutputLocationsException(GrpcBaseException):
status_code = ErrorCodes.DUPLICATE_OUTPUT_LOCATIONS
message = ErrorMessages.DUPLICATE_OUTPUT_LOCATIONS
class OneOutputIsRequiredException(GrpcBaseException):
status_code = ErrorCodes.ONE_OUTPUT_IS_REQUIRED
message = ErrorMessages.ONE_OUTPUT_IS_REQUIRED
class JobNotFoundException(GrpcBaseException):
status_code = ErrorCodes.JOB_NOT_FOUND_BY_TRACKING_ID
message = ErrorMessages.JOB_NOT_FOUND_BY_TRACKING_ID
class JobIsFailedException(GrpcBaseException):
status_code = ErrorCodes.JOB_IS_FAILED
message = ErrorMessages.JOB_IS_FAILED
class JobIsRevokedException(GrpcBaseException):
status_code = ErrorCodes.JOB_IS_REVOKED
message = ErrorMessages.JOB_IS_REVOKED
class JobIsFinishedException(GrpcBaseException):
status_code = ErrorCodes.JOB_IS_FINISHED
message = ErrorMessages.JOB_IS_FINISHED
class NoWatermarkToUseException(GrpcBaseException):
status_code = ErrorCodes.NO_WATERMARK_TO_USE
message = ErrorMessages.NO_WATERMARK_TO_USE
| UTF-8 | Python | false | false | 1,834 | py | 89 | exceptions.py | 79 | 0.78626 | 0.782988 | 0 | 60 | 29.566667 | 68 |
v-komarov/psv3 | 10,462,540,381,775 | af220385d50552951648db6d6173885d2f352ac4 | bc550f6966e30de27987bc803b2447bf02a2e44b | /report/UlDom.py | e593ad33df18c849095f53eea1cccf70fac1a9d2 | []
| no_license | https://github.com/v-komarov/psv3 | afe2a50a5498ee66f4146802ecbbb62bef5a9173 | deca97a9fac0865163f7c2d4fd5110caccb00a80 | refs/heads/master | 2021-01-18T10:52:35.444429 | 2016-06-06T09:19:27 | 2016-06-06T09:19:27 | 59,651,228 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding:utf-8
""" Вспомогательные интерфейсы для отчетных форм """
import RWCfg
import wx
import sys
from report.RunSQL import GetUlDom
class ListUlDom(wx.ListCtrl):
def __init__(self, parent, ID, pos=(0,0),
size=(270,200), style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
self.InsertColumn(0, "Улица")
self.InsertColumn(1, "Дом")
self.SetColumnWidth(0, 200)
self.SetColumnWidth(1, 70)
def Populate(self):
self.DeleteAllItems()
#### --- Отображение данных в форме ---
self.kod_record=[] # массив идентификаторов записей
for row in GetUlDom():
str0=row[0]
str1=row[1]
index=self.InsertStringItem(sys.maxint, str0)
self.SetStringItem( index, 0, str0)
self.SetStringItem( index, 1, str1)
# -- Заполнение массива идентификаторов записей ---
self.kod_record.append(row[0]+":"+row[1])
self.currentItem=0
class ListUlDom2(wx.ListCtrl):
def __init__(self, parent, ID, pos=(0,0),
size=(270,200), style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
self.InsertColumn(0, "Улица")
self.InsertColumn(1, "Дом")
self.SetColumnWidth(0, 300)
self.SetColumnWidth(1, 100)
def Populate(self):
self.DeleteAllItems()
#### --- Отображение данных в форме ---
self.kod_record=[] # массив идентификаторов записей
for row in GetUlDom():
str0=row[0]
str1=row[1]
index=self.InsertStringItem(sys.maxint, str0)
self.SetStringItem( index, 0, str0)
self.SetStringItem( index, 1, str1)
# -- Заполнение массива идентификаторов записей ---
self.kod_record.append(row[0]+":"+row[1])
self.currentItem=0
class ListServiceMonthSum(wx.ListCtrl):
def __init__(self, parent, ID, pos=(0,0),
size=(400,150), style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
self.InsertColumn(0, "Услуга")
self.InsertColumn(1, "Мес.долг")
self.InsertColumn(2, "Сум.долг")
self.SetColumnWidth(0, 200)
self.SetColumnWidth(1, 100)
self.SetColumnWidth(2, 100)
def Populate(self,item):
self.DeleteAllItems()
#### --- Отображение данных в форме ---
self.kod_record=[] # массив идентификаторов записей
if len(item)!=0:
for row in item:
index=self.InsertStringItem(sys.maxint, row[0])
self.SetStringItem( index, 0, row[0])
self.SetStringItem( index, 1, row[1])
self.SetStringItem( index, 2, row[2])
# -- Заполнение массива идентификаторов записей ---
self.kod_record.append(row[0])
self.currentItem=0
| UTF-8 | Python | false | false | 2,988 | py | 158 | UlDom.py | 79 | 0.628409 | 0.591667 | 0 | 140 | 17.842857 | 64 |
Aasthaengg/IBMdataset | 652,835,035,306 | 362c3c6b265ede2a7a3565275a917f338f7c85a0 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02936/s652606703.py | 34938dac1bd96621de52b33622a25f321bce4fb5 | []
| no_license | https://github.com/Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
input = sys.stdin.readline
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def main():
mod=10**9+7
import queue
N,Q=MI()
adj=[[]for _ in range(N)]
for _ in range(N-1):
a,b=MI()
a-=1
b-=1
adj[a].append(b)
adj[b].append(a)
ans=[0]*N
for _ in range(Q):
p,x=MI()
p-=1
ans[p]+=x
q=queue.Queue()
q.put((0,-1))
while not q.empty():
v,p=q.get()
for nv in adj[v]:
if nv!=p:
ans[nv]+=ans[v]
q.put((nv,v))
print(' '.join(map(str, ans)))
main()
| UTF-8 | Python | false | false | 742 | py | 202,060 | s652606703.py | 202,055 | 0.416442 | 0.401617 | 0 | 40 | 17.55 | 48 |
Sikerdebaard/dcmrtstruct2nii | 2,714,419,358,646 | 66b4a9460b796ad0a8b11bbe0f59174f515611bb | f964bb231431aad5b5e90d05679adb89a985dc56 | /dcmrtstruct2nii/adapters/output/niioutputadapter.py | b3249a10eff2137d617bcbcfdce5676e402a4cb9 | [
"MIT"
]
| permissive | https://github.com/Sikerdebaard/dcmrtstruct2nii | 1a95e954e064e8d236e6b97d293d712ee1291dde | 9a6669bf73454f1cb2550664d42faabf58776f7d | refs/heads/master | 2023-03-15T21:12:49.408885 | 2023-03-07T14:44:08 | 2023-03-07T14:44:08 | 166,835,376 | 75 | 25 | Apache-2.0 | false | 2023-03-07T10:56:16 | 2019-01-21T15:19:54 | 2023-02-03T12:20:27 | 2023-03-07T10:56:13 | 4,268 | 61 | 20 | 7 | Python | false | false | from dcmrtstruct2nii.adapters.output.abstractoutputadapter import AbstractOutputAdapter
import SimpleITK as sitk
class NiiOutputAdapter(AbstractOutputAdapter):
def write(self, image, output_path, gzip):
if gzip:
sitk.WriteImage(image, output_path + '.nii.gz')
else:
sitk.WriteImage(image, output_path + '.nii')
| UTF-8 | Python | false | false | 358 | py | 33 | niioutputadapter.py | 30 | 0.701117 | 0.698324 | 0 | 11 | 31.545455 | 87 |
nkmurli/vasuNKproj | 14,628,658,635,591 | 292eca8002bbe96a173e8ed2255e54a822d172e9 | 4b0d1d7e61455587483cc60c3adab1ccf068ae02 | /app/views.py | bacf0ac44fd55d3f31cde43e65170c608fd9156f | [
"MIT"
]
| permissive | https://github.com/nkmurli/vasuNKproj | 95548f7f11081fd54203bcd8b79fd633a324cf4f | 543f87d5ed2812d50b39867bca60c893a4d906d8 | refs/heads/master | 2022-12-10T15:47:53.890614 | 2020-01-30T12:46:31 | 2020-01-30T12:46:31 | 237,213,578 | 0 | 0 | MIT | false | 2022-12-08T03:31:39 | 2020-01-30T12:58:36 | 2020-01-30T13:12:52 | 2022-12-08T03:31:39 | 76 | 0 | 0 | 7 | Python | false | false |
from django.shortcuts import render, redirect,HttpResponseRedirect
from django.db.models import Q
from django.http import JsonResponse, request
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from . import models
import sqlite3,json
import pandas as pd
from django.db.models import Count
from Tools.scripts.objgraph import flat
from django.http.request import QueryDict, HttpRequest
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib import messages,auth
from django.core.exceptions import ObjectDoesNotExist
from django.http.response import HttpResponseRedirect
from rest_framework.request import Request
from django.template import RequestContext
def nkang(request):
return render(request,'vasuapp/nkang.html')
def Home(request):
return render(request,'vasuapp/Home.html')
def tlogin(request):
print("in LOGGGGGGGGGGGGGGGG")
if request.method == "POST":
usr = request.POST['username']
pwd = request.POST['password']
user =auth.authenticate(username=usr,password=pwd)
if user is not None:
auth.login(request, user)
return redirect('/main')
else:
messages.error(request,"User Name or Password Does not Match")
return render(request,"Home.html")
def ibmcs90Home(request):
dmname=models.StaffingMaster.objects.values('DMName').distinct()
# print(dmname)
return render(request,'vasuapp/ibmcs90home.html',{'dmn':dmname})
#return render(request,'vasuapp/.html',{'dmn':dmname})
def Hellow(request):
return render(request,'vasuapp/hallow.html')
def Empview(request):
employees=models.Employee.objects.all()
return render(request,'vasuapp/empview.html',{'employees':employees})
def ICS90Empview(request):
#query1= request.POST["ddsel"]
#print("Query one is : ",query1)
employees=models.StaffingMaster.objects.all().order_by('DMName')
ba=models.StaffingMaster.objects.values('BudgetArea').annotate(cnt=Count('BudgetArea'))
data = list(employees)
myowndict = {
'employees':employees,
'ba':ba
}
print("From ICS90EMPView :::: ")
print(data)
x=request.POST.get('idmn')
print("in ICS90 View ::::: Murali : ",x)
return render(request,'vasuapp/cs90Staff.html',myowndict)
def nkredirect():
print ("Murali I am here")
def CS90Empview(request):
print ("Murali I am here")
#print("Murali : ",kwargs.Get("slug"))
if request.method == 'POST':
print("POST")
#pd=request.POST["Nkoption"]
st= request.POST.get("Dnm")
else:
print("GET")
st=request.session.get('dname')
print("989898 ::::",st)
if st == "allData":
return redirect('/cs90')
employees=models.StaffingMaster.objects.order_by("BudgetArea").filter(DMName=st)
print("MNMNNMMMMM",list(employees))
ba=models.StaffingMaster.objects.values('BudgetArea').annotate(cnt=Count('BudgetArea')).filter(DMName=st)
print (ba)
myowndict = {
"employees":employees,
"dm":1,
"dm_name":st,
'ba':ba
}
print("Print Dictionary Now Be ready")
print (type(myowndict))
print("Printeddddddddddd Dictionary Now Be ready")
#return HttpResponse(json.dumps(myowndict), content_type='application/json')
#return JsonResponse(json.dumps(list(myowndict)))
#return redirect('http://127.0.0.1:8000/myredirect')
#return redirect('myredirect/',permanent=True)
#return HttpResponseRedirect('myredirect/')
#return render_to_response('vasuapp/cs90Staff.html',myowndict,context_instance=RequestContext(request))
return render(request,'vasuapp/cs90Staff.html',myowndict)
def myredirect(request):
print('in Mydict')
return render(request,'vasuapp/Home.html')
def CS90EmpviewBack(request,st):
#print("Murali : ",kwargs.Get("slug"))
print("Fetching in CS90 View for ::::: Murali : ",st)
employees=models.StaffingMaster.objects.order_by("BudgetArea").filter(DMName=st)
print("MNMNNMMMMM",list(employees))
ba=models.StaffingMaster.objects.values('BudgetArea').annotate(cnt=Count('BudgetArea')).filter(DMName=st)
print (ba)
myowndict = {
"employees":employees,
"dm":1,
"dm_name":st,
'ba':ba
}
print (myowndict)
return render(request,'vasuapp/cs90Staff.html',myowndict)
def AngCS90Empview(request):
#print("Murali : ",kwargs.Get("slug"))
st=request.POST['dmn']
print("in CS90 View ::::: Murali : ",st)
employees=models.StaffingMaster.objects.order_by("BudgetArea").filter(DMName=st)
dmname=models.StaffingMaster.objects.values('DMName').distinct()
ba=models.StaffingMaster.objects.values('BudgetArea').annotate(cnt=Count('BudgetArea')).filter(DMName=st)
print (ba)
myowndict = {
"employees":employees,
"dm":1,
"dm_name":st,
'dmn':dmname,
'ba':ba
}
#print (myowndict)
#return render(request,'vasuapp/cs90Staff.html',myowndict)
return HttpResponse(json.dumps(list(myowndict)), content_type='application/json')
def index(request):
for i in request.POST.keys():
print('murali','key: {0} value: {1}'.format(i, request.POST[i]))
if "GET" == request.method:
return render(request, 'vasuapp/index.html', {})
else:
excel_file = request.FILES["excel_file"]
wb = pd.read_excel(excel_file,'WorkSheet')
df= pd.DataFrame(wb)
df=df[(df['SECTION']=='Active')]
#df=df.drop([df.columns[9],df.columns[10],df.columns[11],df.columns[12]],axis=1)
#6-Employee number, 2->Section, 11
cols = [6,2,11,9,17,18,19,23]
df = df[df.columns[cols]]
exdd=df.to_dict('records')
# print(exdd)
stfmtx=df.values
fs=0
fs=Add2MasterStaff(stfmtx,fs)
print("Sccess Files..................",fs)
if fs==1:
print("Sccess Files..................")
msg={"msg":"Successfully Uploaded Data"}
else:
msg={"msg":"Problem with File"}
return render(request, 'vasuapp/index.html', msg)
def Add2MasterStaff(stfmtx,fs):
conn =sqlite3.connect('StaffingMaster.db')
c=conn.cursor()
dsql="delete from vasuapp_staffingmaster"
c.execute(dsql)
conn.commit
print("The Data to be uploaded")
print(stfmtx)
insqry='INSERT INTO vasuapp_staffingmaster(Eno,Ename,DMName,BudgetArea,IBMMailID,OfficeNumber,MobileNumber,ClientMailID) values (?,?,?,?,?,?,?,?)'
try:
c.executemany(insqry,stfmtx)
fs=1
print("Loaded data")
except:
print("Problem with Data")
pass
conn.commit()
conn.close()
return(fs)
def SrchView(request):
query1= request.POST["srchinput"]
query= request.GET.get("srchinput","murali")
print("Murali in SRCH ::: ",query,"Query 2",query1)
lookups= Q(Eno__icontains=query1) | Q(Ename__icontains=query1) | Q(IBMMailID__icontains=query1) | Q(ClientMailID__icontains=query1)
employees= models.StaffingMaster.objects.filter(lookups).distinct()
return render(request,'vasuapp/hallow.html',{"employees":employees})
def getdmnames(request):
x=request.POST.get('x')
print("::::::::::I am in getdmnames:::::::::::::::",x)
dmname=models.StaffingMaster.objects.values('DMName').distinct()
dmbudget=models.StaffingMaster.objects.order_by('DMName').values_list('DMName','BudgetArea')
x=dmbudget.values('DMName','BudgetArea')
dbdf=pd.DataFrame.from_records(x)
dbdf=dbdf.drop_duplicates();
#print("eeeeeeeeeeeeeeeeeeekkkkkkkkkkkk: ",dbdf)
dbf=list(dbdf.groupby(['DMName']))
dbdd=dict(dbf)
dmdict=dbdf.groupby('DMName')['BudgetArea'].apply(lambda g:g.values.tolist()).to_dict()
data = json.dumps(list(dmname))
print('dmname::::',data)
#data = json.dumps(dmname)
#print("k88888888kkkkkkkkkkk: ",data)
#json_data=serialize('json', [dmname,])
#print("kkkkkkkkkkkk--kkkk: ",json_data)
return HttpResponse(data, content_type='application/json')
def getAppNames(request):
#ap=request.POST.get('ap')
print("::::::::::I am in Get APP Name :::::::::::::::")
#ba=models.StaffingMaster.objects.values('BudgetArea').distinct()
ba=models.StaffingMaster.objects.values('BudgetArea','DMName').distinct()
#data = json.dumps(ba)
m1={}
data = list(ba)
print('lklk---------------',data)
for e in data:
v=e['BudgetArea']
k=e['DMName']
m1.setdefault(k,[]).append(v)
#print("Loop Starting...........")
#for k,vl in m1.items():
# for v in vl:
# print(k,"----",v)
return HttpResponse(json.dumps(m1), content_type='application/json')
#return JsonResponse(data, content_type='application/json')
def getEmpAppwise(request):
st= request.POST.get("barea")
st1= request.POST.get("dnm")
print("Fetching in CS90 View for ::::: Murali : ",st,"===",st1)
if st1 is not None:
request.session['dname']=st1
return redirect('/cs90a')
if st == 'allData':
return redirect('/cs90')
else:
employees=models.StaffingMaster.objects.order_by("BudgetArea").filter(BudgetArea=st)
ba=models.StaffingMaster.objects.values('BudgetArea').annotate(cnt=Count('BudgetArea')).filter(BudgetArea=st)
print (ba)
myowndict = {
"employees":employees,
"dm":1,
"dm_name":st,
'ba':ba
}
print (myowndict)
return render(request,'vasuapp/cs90Staff.html',myowndict)
def EnoEname(request):
cs90data=models.StaffingMaster.objects.values("Eno","Ename")
# print(cs90data)
#data = json.dumps(list(cs90data))
#return JsonResponse(data, safe=False)
return HttpResponse(json.dumps(list(cs90data)), content_type='application/json') | UTF-8 | Python | false | false | 10,082 | py | 22 | views.py | 10 | 0.642134 | 0.629538 | 0 | 292 | 33.520548 | 150 |
SrdjanStankov/DRS_Asteroidi | 1,039,382,091,286 | 533d3a1911e50b00847365cb6384fe3feaf1ef1e | 724a58f72e4f82262bd63c09f65cad36646619f1 | /Game/Asteroid.py | 39472bd11d2e3af1f3c4ac9c8a97688854ee4150 | []
| no_license | https://github.com/SrdjanStankov/DRS_Asteroidi | 4a748511071f3e6d85d3eeed04986d18ead13d58 | 392d53458629f9feeea0a2fa5c6b068ad8734be4 | refs/heads/master | 2020-09-14T15:40:13.015684 | 2020-01-17T22:55:43 | 2020-01-17T22:55:43 | 223,171,906 | 0 | 0 | null | false | 2020-01-03T19:24:08 | 2019-11-21T12:43:47 | 2020-01-03T02:52:27 | 2020-01-03T19:24:07 | 32,533 | 0 | 0 | 0 | Python | false | false | from GameObject import GameObject
from PyQt5.QtCore import QObject
import types
import Transform as transform
import Managers as mng
class Asteroid(QObject):
def __init__(self,type,x,y,rotation,speed,signalCollision):
super(Asteroid,self).__init__()
tempTransform = transform.Transform()
tempTransform.x = x
tempTransform.y = y
tempTransform.rotation = rotation
tempTransform.speed = speed
self.asteroid = mng.Managers.getInstance().objects.Instantiate("Asteroid",asteroidType = type,transform = tempTransform,name = "",callable = self.update)
self.asteroid.Render.rotateItem()
self.signalCollision = signalCollision
def update(self):
try:
self.asteroid.transform.move(1)
for ind,item in enumerate(self.asteroid.collisionsType):
if item == "Spaceship":
self.signalCollision.emit(self.asteroid.collisions[ind])
except:
pass
| UTF-8 | Python | false | false | 995 | py | 45 | Asteroid.py | 42 | 0.660302 | 0.658291 | 0 | 28 | 34.535714 | 161 |
alanyamuzu/py-etherscan-api | 15,384,572,857,830 | 9798063284843ee08a81c12ba8872241069daddd | 29767f4fbe9b52fa65a37d7406855d0aa4b1b8f7 | /examples/accounts/get_all_transactions.py | 5386e94b6a794f23ae13bd862a79657079f963b5 | [
"MIT"
]
| permissive | https://github.com/alanyamuzu/py-etherscan-api | 7c7be17e93b6baeb5e008fc1c48b3ff466f79c01 | eca11d9eb8d9376ecca964046571cdd80f33375d | refs/heads/master | 2023-01-22T10:41:09.169872 | 2020-12-06T20:02:00 | 2020-12-06T20:02:00 | 319,119,946 | 1 | 0 | MIT | true | 2020-12-06T20:00:27 | 2020-12-06T20:00:26 | 2020-12-06T19:54:11 | 2020-04-16T07:56:00 | 217 | 0 | 0 | 0 | null | false | false | from etherscan.accounts import Account
import json
with open('../../api_key.json', mode='r') as key_file:
key = json.loads(key_file.read())['key']
address = '0x49edf201c1e139282643d5e7c6fb0c7219ad1db7'
api = Account(address=address, api_key=key)
transactions = api.get_all_transactions(offset=10000, sort='asc',
internal=False)
print(transactions[0])
| UTF-8 | Python | false | false | 399 | py | 39 | get_all_transactions.py | 31 | 0.666667 | 0.586466 | 0 | 13 | 29.692308 | 65 |
jerrylance/LeetCode | 867,583,394,465 | 638984cc617bc3a7d94bc7ce39ee784d2e50b786 | e28009b0a4584e8d128ed6fbd4ba84a1db11d1b9 | /278.First Bad Version/278.First Bad Version.py | 2846c079b87b211233d4d72a5e599ba39b3d66a5 | []
| no_license | https://github.com/jerrylance/LeetCode | 509d16e4285296167feb51a80d6c382b3833405e | 06ed3e9b27a3f1c0c517710d57fbbd794fd83e45 | refs/heads/master | 2020-12-02T23:10:27.382142 | 2020-08-02T02:03:54 | 2020-08-02T02:03:54 | 231,141,551 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # LeetCode Solution
# Zeyu Liu
# 2019.3.17
# 278.First Bad Version
from typing import List
# method 1 binary lterative,快
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
def isBadVersion(version):
if version >= 4:
return True
else:
return False
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
l = 1
r = n
while l < r:
mid = (l + r) // 2
if isBadVersion(mid) == True:
r = mid
else:
l = mid + 1
return r
# transfer method
solve = Solution()
print(solve.firstBadVersion(5))
# method 2 recursive
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
return self.binarysearch(1,n)
def binarysearch(self,l,r):
if l == r:
return l
mid = (l + r)//2
if isBadVersion(mid) == True:
return self.binarysearch(l,mid)
else:
return self.binarysearch(mid+1,r)
# transfer method
solve = Solution()
print(solve.firstBadVersion(5)) | UTF-8 | Python | false | false | 1,281 | py | 191 | 278.First Bad Version.py | 190 | 0.521535 | 0.50509 | 0 | 55 | 21.254545 | 50 |
hemanthsoma/BigData | 5,789,615,934,948 | a3d2f0f246fcd4ebce3ad4df1404a8af86b803b1 | 61ec8269904b03e13fa3d44cd44db3324145f6d2 | /Assignment02/printItemsInDict.py | 9d897add686b031ac275941fbc58c63993368f27 | []
| no_license | https://github.com/hemanthsoma/BigData | 4f72b260cd54132c48a9680ed5e0225f80c03e26 | c58432e59858a0f33e86a9e68281ac343f0714cd | refs/heads/main | 2023-06-08T18:17:21.228177 | 2021-06-29T15:38:51 | 2021-06-29T15:38:51 | 381,094,430 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | Dict = {
'a':1,
'b':2,
'c':3
}
for i,j in Dict.items():
print(i, ":", j) | UTF-8 | Python | false | false | 82 | py | 37 | printItemsInDict.py | 37 | 0.402439 | 0.365854 | 0 | 7 | 10 | 24 |
cavealix/Udacity | 2,937,757,656,746 | 657ee35225a3c5806f77660621ff5ff92922f681 | c47cb4fe48cdaf5702bc06a3f329a7c896e8bf4f | /FullStack/Backend_Intro/Elements of SQL/quizzes.py | f2321544fee8774ff3fdc1979a3009f1cd97ca72 | []
| no_license | https://github.com/cavealix/Udacity | 749103b2423bf10ccfc4ac3e1f9cae4e249b0976 | 20b96665e88e206f61f8e51aa316791eac5efd74 | refs/heads/master | 2020-02-26T16:04:45.730335 | 2017-01-10T06:08:23 | 2017-01-10T06:08:23 | 68,942,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Write a query that returns all the species in the zoo, and how many animals of
# each species there are, sorted with the most populous species at the top.
#
# The result should have two columns: species and number.
#
# The animals table has columns (name, species, birthdate) for each individual.
#
QUERY = "select count(species) as num, species from animals group by species order by num desc"
############################################################################
#
# Insert a newborn baby opossum into the animals table and verify that it's been added.
# To do this, fill in the rest of SELECT_QUERY and INSERT_QUERY.
#
# SELECT_QUERY should find the names and birthdates of all opossums.
#
# INSERT_QUERY should add a new opossum to the table, whose birthdate is today.
# (Or you can choose any other date you like.)
#
# The animals table has columns (name, species, birthdate) for each individual.
#
SELECT_QUERY = "select name, birthdate from animals where species = 'opossum';"
INSERT_QUERY = "insert into animals values('alix', 'opossum', '2016-09-16')"
############################################################################
#
# Find the names of the individual animals that eat fish.
#
# The animals table has columns (name, species, birthdate) for each individual.
# The diet table has columns (species, food) for each food that a species eats.
#
QUERY = '''
select animals.name from animals, diet where animals.species = diet.species and food = 'fish';
'''
############################################################################
#
# Find the one food that is eaten by only one animal.
#
# The animals table has columns (name, species, birthdate) for each individual.
# The diet table has columns (species, food) for each food that a species eats.
#
QUERY = '''
select diet.food, count(diet.food) as num from animals, diet where animals.species = diet.species group by food having num=1;
'''
############################################################################
#
# List all the taxonomic orders, using their common names, sorted by the number of
# animals of that order that the zoo has.
#
# The animals table has (name, species, birthdate) for each individual.
# The taxonomy table has (name, species, genus, family, t_order) for each species.
# The ordernames table has (t_order, name) for each order.
#
# Be careful: Each of these tables has a column "name", but they don't have the
# same meaning! animals.name is an animal's individual name. taxonomy.name is
# a species' common name (like 'brown bear'). And ordernames.name is the common
# name of an order (like 'Carnivores').
QUERY = '''
select ordernames.name, count (taxonomy.t_order) as t_orders
from animals, taxonomy, ordernames
where animals.species = taxonomy.name and taxonomy.t_order = ordernames.t_order
group by taxonomy.t_order
order by t_orders desc
;
'''
############################################################################
# To see how the various functions in the DB-API work, take a look at this code,
# then the results that it prints when you press "Test Run".
#
# Then modify this code so that the student records are fetched in sorted order
# by student's name.
#
import sqlite3
# Fetch some student records from the database.
db = sqlite3.connect("students")
c = db.cursor()
query = "select name, id from students order by name asc;"
c.execute(query)
rows = c.fetchall()
# First, what data structure did we get?
print "Row data:"
print rows
# And let's loop over it too:
print
print "Student names:"
for row in rows:
print " ", row[0]
db.close()
############################################################################
# This code attempts to insert a new row into the database, but doesn't
# commit the insertion. Add a commit call in the right place to make
# it work properly.
#
import sqlite3
db = sqlite3.connect("testdb")
c = db.cursor()
c.execute("insert into balloons values ('blue', 'water') ")
db.commit()
db.close()
############################################################################
#
# Roommate Finder v0.9
#
# This query is intended to find pairs of roommates. It almost works!
# There's something not quite right about it, though. Find and fix the bug.
#
QUERY = '''
select a.id, b.id, a.building, a.room
from residences as a, residences as b
where a.building = b.building
and a.room = b.room ''' +
#don't show results of students as their own roommates
#and don't show duplicates a/b and b/a, therefore group by room
'''and a.id != b.id
group by a.room
order by a.building, a.room;
'''
#
# To see the complete residences table, uncomment this query and press "Test Run":
#
# QUERY = "select id, building, room from residences;"
#
######################################################################
# Here are two tables describing bugs found in some programs.
# The "programs" table gives the name of each program and the files
# that it's made of. The "bugs" table gives the file in which each
# bug was found.
#
# create table programs (
# name text,
# filename text
# );
# create table bugs (
# filename text,
# description text,
# id serial primary key
# );
#
# The query below is intended to count the number of bugs in each
# program. But it doesn't return a row for any program that has zero
# bugs. Try running it as it is. Then change it so that the results
# will also include rows for the programs with no bugs. These rows
# should have a 0 in the "bugs" column.
select programs.name, count(bugs.filename) as num
from programs left join bugs
on programs.filename = bugs.filename
group by programs.name
order by num;
######################################################################
# Find the players whose weight is less than the average.
#
# The function below performs two database queries in order to find the right players.
# Refactor this code so that it performs only one query.
#
def lightweights(cursor):
"""Returns a list of the players in the db whose weight is less than the average."""
#original way in two queries
#cursor.execute("select avg(weight) as av from players;")
#av = cursor.fetchall()[0][0] # first column of first (and only) row
#cursor.execute("select name, weight from players where weight < " + str(av))"""
#perform in single query
cursor.execute("select name, weight from players where weight < (select avg(weight) as av from players) ;")
return cursor.fetchall()
| UTF-8 | Python | false | false | 6,516 | py | 37 | quizzes.py | 18 | 0.642265 | 0.639349 | 0 | 197 | 32.076142 | 125 |
br8696/first | 17,626,545,809,382 | 33e0374a1b5c906e1982d83231f5f6f7b8a47e8c | c9fd281ce06da24f8a912a553c40b9dba59f5736 | /xlrd2.py | 49b6d4b44d81478de171f79699ca899eec6030ef | []
| no_license | https://github.com/br8696/first | 2b09bcb534edf8c55285394f249db7942ea90c5f | 679be9a4db6f4acb663128c8586c91cb5253678b | refs/heads/master | 2020-03-21T05:26:18.160670 | 2018-06-21T13:30:51 | 2018-06-21T13:30:51 | 138,160,432 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import xlrd
for i in range(0,3,1):
for j in range(0,1,1):
s=xlrd.open_workbook("student.xlsx","r")
sh=s.sheet_by_index(0)
print sh.cell(i,j), sh.cell(i,j+1), sh.cell(i,j+2),"\n"
"""for display all names we have to use loop to display all]
to print onlyname we use print cell.value
"""
| UTF-8 | Python | false | false | 334 | py | 5 | xlrd2.py | 5 | 0.580838 | 0.553892 | 0 | 12 | 25.333333 | 63 |
karadenizli-koefte/Repos | 5,746,666,245,431 | 08a7c5d36a3218dfd902b4893e2bd2572def489f | 456c19ad6051e86a418968a90400eaafd0aea6e8 | /Image_Processing/Image Processing/CannyEdgeDetection2.py | 5b2fa2c38210ae0579ab1521b5d2986dbc381901 | []
| no_license | https://github.com/karadenizli-koefte/Repos | c8c31ece7a074fa16c8fc42cc2f1614ac11f1cfe | 9b136a140165258d080540b225800d3fdb6767a7 | refs/heads/main | 2023-08-15T06:24:34.555752 | 2021-09-18T18:14:09 | 2021-09-18T18:14:09 | 358,521,074 | 0 | 0 | null | false | 2021-06-22T08:12:52 | 2021-04-16T07:57:40 | 2021-06-21T08:09:59 | 2021-06-22T08:12:52 | 22,888 | 0 | 0 | 0 | C# | false | false | import cv2
import numpy as np
from matplotlib import pyplot as plt
imgPath = 'D:/img/lena_full.jpg'
# Load two images
img = cv2.imread(imgPath)
img = cv2.resize(img, (int(img.shape[1] / 2), int(img.shape[0] / 2)))
def nothing(x):
pass
# Create a black image, a window
cv2.namedWindow('image')
cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE);
# create trackbars for color change
cv2.createTrackbar('T1', 'image', 0, 255, nothing)
cv2.createTrackbar('T2', 'image', 0, 255, nothing)
while 1:
# get current positions of four trackbars
threshold1 = cv2.getTrackbarPos('T1', 'image')
threshold2 = cv2.getTrackbarPos('T2', 'image')
edges = cv2.Canny(img, threshold1, threshold2)
cv2.imshow('image', edges)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
| UTF-8 | Python | false | false | 818 | py | 68 | CannyEdgeDetection2.py | 27 | 0.674817 | 0.627139 | 0 | 37 | 21.081081 | 69 |
huster-wgm/web_simu | 12,214,887,025,740 | b90669b682a7d262b68d03a8927153b993e223e6 | 1ac2a5b527850cd78f7e7b49e7528103134d0145 | /portfolios/bio_calc.py | 4cdc184f2561253c1bc2f615736c5c59973a373f | []
| no_license | https://github.com/huster-wgm/web_simu | eaea90121a1117d9cf5c1f0b4ec9618719f0f53a | e6310f8a7e17cb48fdeec634db0f807c4259c5fc | refs/heads/master | 2020-09-16T15:04:09.367377 | 2017-06-27T06:11:35 | 2017-06-27T06:11:35 | 66,014,637 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 13 22:25:05 2016
@author: huster-wgm
"""
import numpy as np
import pandas as pd
from math import pi
from bokeh.plotting import figure
from bokeh.models import NumeralTickFormatter, HoverTool, ColumnDataSource
from bokeh.embed import components
def create_freq_map(df):
# df columns=['Amino', 'codon', 'freq', 'optimal_codon', 'optimal_freq'])
position = list(range(1, df.shape[0]+1))
# assign values to data
amino = df['Amino']
codon = df['codon']
freq = df['freq'].values
optimal_codon = df['optimal_codon']
optimal_freq = df['optimal_freq'].values
source = ColumnDataSource(
data=dict(position=position, amino=amino,
codon=codon, freq=freq,
optimal_codon=optimal_codon, optimal_freq=optimal_freq)
)
TOOLS = "hover,save,pan,box_zoom,wheel_zoom,reset"
p = figure(responsive=True, plot_width=750, plot_height=400,
x_range=(0, df.shape[0]+2), tools=TOOLS)
# add a line renderer
p.line(x='position', y='optimal_freq',
line_width=2, line_color="purple",
source=source, legend='Optimal codon map')
p.line(x='position', y='freq',
line_width=2, source=source,
legend='Actual codon map')
p.line(x=position, y=0.1,
line_color="red", legend="10% baseline")
# change just some things about the x-axes
p.title.text = 'Codon frequency to refer species'
p.title.text_font_size = '36pt'
p.title.align = 'center'
p.xaxis.axis_label = "No. of the Amino acid residue"
p.xaxis.axis_label_text_font_size = '20pt'
p.xaxis.major_label_orientation = pi/4
p.yaxis.axis_label = 'Refer codon frequency'
p.yaxis.axis_label_text_font_size = '20pt'
p.yaxis[0].formatter = NumeralTickFormatter(format="0.0%")
p.select_one(HoverTool).tooltips = [
('Position', '@position'),
('Amino acid', '@amino'),
('Codon', '@codon'),
('Frequency', '@freq'),
('Optimal_codon', '@optimal_codon'),
('Optimal frequency', '@optimal_freq'),
]
the_script, the_div = components(p)
assert isinstance(the_div, object)
return the_script, the_div
# refer to https://en.wikipedia.org/wiki/DNA_codon_table
aa_code_dict = {
'A': ['GCT', 'GCC', 'GCA', 'GCG'],
'R': ['CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'],
'N': ['AAT', 'AAC'],
'D': ['GAT', 'GAC'],
'C': ['TGT', 'TGC'],
'Q': ['CAA', 'CAG'],
'E': ['GAA', 'GAG'],
'G': ['GGT', 'GGC', 'GGA', 'GGG'],
'H': ['CAT', 'CAC'],
'I': ['ATT', 'ATC', 'ATA'],
'M': ['ATG'],
'L': ['TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG'],
'K': ['AAA', 'AAG'],
'F': ['TTT', 'TTC'],
'P': ['CCT', 'CCC', 'CCA', 'CCG'],
'S': ['TCT', 'TCC', 'TCA', 'TCG', 'AGT', 'AGC'],
'T': ['ACT', 'ACC', 'ACA', 'ACG'],
'W': ['TGG'],
'Y': ['TAT', 'TAC'],
'V': ['GTT', 'GTC', 'GTA', 'GTG'],
'*': ['TAA', 'TGA', 'TAG'], # represents stop codon
}
gc_reduce_dict = {
'A': ['GCT', 'GCA', 'GCG'],
'R': ['AGA'],
'N': ['AAT'],
'D': ['GAT'],
'C': ['TGT'],
'Q': ['CAA'],
'E': ['GAA'],
'G': ['GGT', 'GGA'],
'H': ['CAT'],
'I': ['ATT'],
'M': ['ATG'],
'L': ['TTA', 'TTG', 'CTT', 'CTA'],
'K': ['AAA'],
'F': ['TTT', 'TTC'],
'P': ['CCT', 'CCA'],
'S': ['TCT', 'TCA', 'AGT'],
'T': ['ACT', 'ACA'],
'W': ['TGG'],
'Y': ['TAT'],
'V': ['GTT', 'GTA'],
'*': ['TAA', 'TGA', 'TAG'], # represents stop codon
}
def key_by_value(dicts, search_value):
for key, values in dicts.items():
if search_value in values:
return key
def get_optimal_codon(freq_dict):
# return optimal codon for each every amino acid
optimal_codon = []
for aa, codons in aa_code_dict.items():
if len(codons) == 1:
optimal_code = codons[0]
optimal_freq = freq_dict[optimal_code]
else:
optimal_freq = 0
optimal_code = None
for i in codons:
if optimal_freq < freq_dict[i]:
optimal_code = i
optimal_freq = freq_dict[i]
optimal_codon.append([aa, optimal_code, optimal_freq])
return np.array(optimal_codon)
def dna_to_aa(seq, codon_frequency):
"""
:param seq: numpy array
:param codon_frequency: dict
"""
aa_seq = []
coding_len = len(seq) // 3
for i in range(0, coding_len):
DNA_code = seq[i*3:i*3+3]
DNA_code = ''.join(DNA_code)
# match DNA_code to Amino acid
aa = key_by_value(aa_code_dict, DNA_code)
# bool(codon_freq) is false when empty
if bool(codon_frequency):
# get [amino_acid,optimal_codon,optimal_freq]
optimal_ref = get_optimal_codon(codon_frequency)
# extract [amino_acid,optimal_freq] dictionary
optimal_freq_ref = dict(zip(optimal_ref[:, 0], optimal_ref[:, 2]))
# extract [amino_acid,optimal_codon] dictionary
optimal_codon_ref = dict(zip(optimal_ref[:, 0], optimal_ref[:, 1]))
# show codon frequency of aa
freq = round(codon_frequency[DNA_code], 3)
optimal_freq = round(float(optimal_freq_ref[aa]), 3)
optimal_codon = optimal_codon_ref[aa]
aa_seq.append([aa, DNA_code, freq, optimal_codon, optimal_freq])
else:
# no refer codon freq
aa_seq.append(aa)
# be careful freq will be converted to 'str'
return np.array(aa_seq)
def calc_dna_mw(seq, dna_len):
# calculate molecular weight of DNA sequence
# Molecular Weight = (An x 313.21) + (Tn x 304.2) + (Cn x 289.18) + \
# (Gn x 329.21) - 61.96 + 79.0
# refer to http://biotools.nubic.northwestern.edu/OligoCalc.html
GC_num = sum(seq == 'G')+sum(seq == 'C')
AT_num = sum(seq == 'A')+sum(seq == 'T')
assert GC_num + AT_num == dna_len, 'Sequence mix with none DNA code'
gc_rate = round(GC_num / dna_len*100, 1)
dna_mw = round(GC_num*(313.21+304.2)+AT_num*(289.18+329.21)+17.04*2, 1)
return dna_mw, gc_rate
def calc_protein_mw(aa_components):
# Make a dictionary for AA acid residue weight
# refer to http://www.its.caltech.edu/~ppmal/sample_prep/work3.html
aa_weight_dict = {
'G': 57.052,
'A': 71.079,
'S': 87.078,
'P': 97.117,
'V': 99.133,
'T': 101.105,
'C': 103.144,
'I': 113.16,
'L': 113.16,
'N': 114.104,
'D': 115.089,
'Q': 128.131,
'K': 128.174,
'E': 129.116,
'M': 131.198,
'H': 137.142,
'F': 147.177,
'R': 156.188,
'Y': 163.17,
'W': 186.213,
'*': 0, # represent stop codon
}
aa_mw = 0
# calculate molecular weight of Protein sequence
for i in aa_weight_dict.keys():
aa_num = aa_components[i]
aa_mw += aa_num*aa_weight_dict[i]
# add one H2O
aa_mw += 18.0
return round(aa_mw, 2)
def protein_components(seq):
# initial amino acid component to zeros
aa_component = {
'G': 0,
'A': 0,
'S': 0,
'P': 0,
'V': 0,
'T': 0,
'C': 0,
'I': 0,
'L': 0,
'N': 0,
'D': 0,
'Q': 0,
'K': 0,
'E': 0,
'M': 0,
'H': 0,
'F': 0,
'R': 0,
'Y': 0,
'W': 0,
'*': 0, # represent for stop
}
for i in seq:
aa_component[i] += 1
# ε = (nW×5500) + (nY×1490) + (nC×125)
# refer to https://tools.thermofisher.com/content/sfs/brochures/ \
# TR0006-Extinction-coefficients.pdf
abs_coeff = (aa_component['W']*5500 +
aa_component['Y']*1490 +
aa_component['C']*125)
return aa_component, abs_coeff
def reduce_gc(seq):
# input sequence should be amino acid sequence
# seq is a list
reduce_seq = ''
for aa in seq:
# if amino acid is not a stop codon
if aa != '*':
possible_codons = aa_code_dict[aa]
if len(possible_codons) > 1:
codon_gc = []
for codon in possible_codons:
gc_num = codon.count('G')+codon.count('C')
codon_gc.append(gc_num)
# return the index of min value
low_gc_idx = codon_gc.index(min(codon_gc))
reduce_gc_codon = possible_codons[low_gc_idx]
reduce_seq += reduce_gc_codon
else:
reduce_seq += possible_codons[0]
else:
# using '*' to represent stop codon
reduce_seq += 'TAA'
return reduce_seq
class BioCalculator:
# initialize
def __init__(self, seq, seq_type, refer_freq=None):
# DNA related parameters
self.gc_rate = None
self.dna_mw = None
self.dna_seq = None
self.dna_len = None
# Amino acid related parameters
self.aa_seq = None
self.aa_len = None
self.aa_mw = None
self.aa_components = None
self.abs_coeff = None
self.nb_met = None
self.nb_stop = None
# protein concentration
self.pro_con = None
self.molar_con = None
self.dilution = None
# codon usage reference species
self.freq_to_refer = None
self.optimal_seq = None
# remove empty spaces
seq = seq.replace(' ', '')
# remove change line mark
seq = seq.replace('\n', '')
# remove comma
seq = seq.replace('\r', '')
seq = list(seq)
self.seq_type = seq_type
self.seq = np.array(seq)
self.refer_freq = refer_freq
assert self.seq_type in ['DNA', 'Protein'], "Wrong sequence type"
def dna_calculator(self):
seq_type = self.seq_type
if seq_type == 'DNA':
# DNA sequence
dna_len = len(self.seq)
trans_result = dna_to_aa(self.seq, self.refer_freq)
dna_mw, gc_rate = calc_dna_mw(self.seq, dna_len)
# assign parameters to self object
self.dna_seq = ''.join(self.seq)
self.dna_len = dna_len
self.dna_mw = dna_mw
self.gc_rate = gc_rate
if self.refer_freq:
self.freq_to_refer = trans_result
self.aa_seq = ''.join(trans_result[:, 0])
else:
self.aa_seq = ''.join(trans_result)
else:
# calculate DNA length
self.dna_len = len(self.seq)*3
self.aa_seq = ''.join(self.seq)
# amino acid sequence
aa_len = len(self.seq)
self.aa_len = aa_len
return 0
def protein_calculator(self):
# get protein molecular weight
aa_components, abs_coeff = protein_components(list(self.aa_seq))
aa_mw = calc_protein_mw(aa_components)
self.aa_len = len(list(self.aa_seq))-aa_components['*']
self.aa_mw = aa_mw
self.aa_components = aa_components
self.abs_coeff = abs_coeff
# Record number of important Amino acid
self.nb_stop = aa_components['*']
self.nb_met = aa_components['M']
return 0
def protein_con(self, width, a_280, dilution):
# refer to https://tools.thermofisher.com/content/sfs/brochures/ \
# TR0006-Extinction-coefficients.pdf
# c = A / ε L ( = A / ε when L = 1 cm)
# unit of molar concentration is 'μM/L'
molar_con = round(a_280 / (self.abs_coeff * width) * dilution*10**6, 2)
# protein concentration (unit is 'mg/mL')
pro_con = round(molar_con * self.aa_mw/(10**6), 2)
self.pro_con = pro_con
self.molar_con = molar_con
self.dilution = dilution
return 0
def codon_optimize(self, method):
if method == 'reduce gc':
optimal_seq = reduce_gc(self.aa_seq)
elif method == 'codon usage':
optimal_seq = ''.join(self.freq_to_refer[:, -2])
else:
optimal_seq = None
self.optimal_seq = optimal_seq
return 0
if __name__ == '__main__':
# test with GAPDH sequence
seq_test = ('ATGACTATCAAAGTAGGTATCAACGGTTTTGGCCGTATCGGTCGCATTGTTTTCCGTGCTGCTCAGAAACGTTCT\
GACATCGAGATCGTTGCAATCAACGACCTGTTAGACGCTGATTACATGGCATACATGCTGAAATATGACTCCACT\
CACGGCCGTTTCGACGGTACCGTTGAAGTGAAAGACGGTCATCTGATCGTTAACGGTAAAAAAATCCGTGTTACC\
GCTGAACGTGATCCGGCTAACCTGAAATGGGACGAAGTTGGTGTTGACGTTGTCGCTGAAGCAACTGGTCTGTTC\
CTGACTGACGAAACTGCTCGTAAACACATCACCGCTGGTGCGAAGAAAGTGGTTATGACTGGTCCGTCTAAAGAC\
AACACTCCGATGTTCGTTAAAGGCGCTAACTTCGACAAATATGCTGGCCAGGACATCGTTTCCAACGCTTCCTGC\
ACCACCAACTGCCTGGCTCCGCTGGCTAAAGTTATCAACGATAACTTCGGCATCATCGAAGGTCTGATGACCACC\
GTTCACGCTACTACCGCTACTCAGAAAACCGTTGATGGCCCGTCTCACAAAGACTGGCGCGGCGGCCGCGGCGCT\
TCCCAGAACATCATCCCGTCCTCTACCGGTGCTGCTAAAGCTGTAGGTAAAGTACTGCCAGAACTGAATGGCAAA\
CTGACTGGTATGGCGTTCCGCGTTCCGACCCCGAACGTATCTGTAGTTGACCTGACCGTTCGTCTGGAAAAAGCT\
GCAACTTACGAGCAGATCAAAGCTGCCGTTAAAGCTGCTGCTGAAGGCGAAATGAAAGGCGTTCTGGGCTACACC\
GAAGATGACGTAGTATCTACCGATTTCAACGGCGAAGTTTGCACTTCCGTGTTCGATGCTAAAGCTGGTATCGCT\
CTGAACGACAACTTCGTGAAACTGGTATCCTGGTACGACAACGAAACCGGTTACTCCAACAAAGTTCTGGACCTG\
ATCGCTCACATCTCCAAATAA')
seq_type_test = 'DNA'
# ref_freq = {}
# path = '../static/K12_codon_freq.csv' # local path
path = 'https://docs.google.com/spreadsheets/d/1PaitzLRv3VIR0lTuI86eFLwzupdZpYwY8VPBaAS0WJc/pub?gid=0&single=true' \
'&output=csv '
codon_freq = pd.read_csv(path)
ref_freq = dict(codon_freq.values)
test = BioCalculator(seq_test, seq_type_test, ref_freq)
print('Perform DNA calculation')
test.dna_calculator()
print('DNA SEQ:', test.dna_seq, '\n',
'DNA_LEN:', test.dna_len, ' bp', '\n',
'DNA_MW:', test.dna_mw, ' g/mol', '\n',
'DNA_gc_rate:', test.gc_rate, '%', '\n',
'Amino_acid SEQ:', test.aa_seq, '\n',
)
print('Perform Protein calculation')
test.protein_calculator()
test.codon_optimize('codon usage')
print('Amino_acid LEN:', test.aa_len, '\n'
'Protein_MW:', test.aa_mw, ' g/mol', '\n',
'Protein components:', test.aa_components, '\n',
'Protein absorbance coeff:', test.abs_coeff, '\n',
'Optimal seq:', test.optimal_seq, )
if test.refer_freq:
data = pd.DataFrame(test.freq_to_refer,
columns=['Amino', 'codon', 'freq',
'optimal_codon', 'optimal_freq'])
script, div = create_freq_map(data)
| UTF-8 | Python | false | false | 15,892 | py | 21 | bio_calc.py | 11 | 0.510796 | 0.49084 | 0 | 434 | 35.601382 | 120 |
Pyton-Projects/My-All-Tkinter-Projects | 9,929,964,438,675 | bde8be562b884d079f1e01ab79e59f2a088a10ec | a2bf461dad0bd0139a408b6f22c56db1d78a01fa | /Music Player/main.py | 2a93a6272f285dffe88e8df8ccbae3a37a4d4936 | []
| no_license | https://github.com/Pyton-Projects/My-All-Tkinter-Projects | 4f5f456d81f986b51efb0ced5d1c15fb26ead5e8 | dd653589246713c48226abe772d4d819a6ff71e4 | refs/heads/main | 2023-05-08T22:31:14.329240 | 2022-02-04T13:17:27 | 2022-02-04T13:17:27 | 367,537,541 | 1 | 0 | null | false | 2021-05-15T04:24:59 | 2021-05-15T04:18:08 | 2021-05-15T04:21:10 | 2021-05-15T04:24:35 | 0 | 0 | 0 | 0 | Python | false | false | from tkinter.ttk import*
import shutil
from tkinter import simpledialog
from tkinter import dialog#plz import!
from tkinter import PhotoImage,mainloop,Entry,StringVar,Button,HORIZONTAL,Scale,Listbox,ACTIVE,Menu,END,filedialog,Toplevel
from ttkthemes import ThemedTk
import os
import pygame
from tkinter import messagebox
root=ThemedTk(themebg=True)
root.title('Playlist- Default')
root.set_theme('black')
root.geometry('800x635')
song_Data=StringVar()
val12=0
check=False
has=False
val=0
file=''
times_playlist_created=0
your_playlist=[]
names=[]
c=[]
check1000='NOPE!'
times_called=0
Recent_Media=[]
Recent_Playlist=[]
timessss12=0
def open__():
Named_to_be=path1.rfind('\\')
print(os.listdir(path1))
if list_.get(ACTIVE)==root.title()[13::]:
messagebox.showinfo('Info','Playlist Is Opened! In The App!!')
else:
pass#p;z@
def save_name():# healteh bar
global path1,play_list_name,name,timessss12
if name.get()=='':
pass
else:
r=list(list_.get(0,END))
pos=r.index(list_.get(ACTIVE))
print(list_.get(ACTIVE))
names[pos]=name.get()
for i in names:
old=path1[path1.rfind('\\')+1:len(path1)]
returned_string=(path1.replace(old,i))
Named_to_be=path1.rfind('\\')
print(path1[:Named_to_be:]+name.get())
path1=''
path1+=returned_string
play_list_name=''
play_list_name+=returned_string
c.append(returned_string)
your_playlist[pos]=returned_string
name12=path1[path1.rfind('\\')+1:len(path1)]
if root.title()=='Playlist- Default':
boyaah=path1[:Named_to_be:]+"\\"+name.get()
os.rename(boyaah,path1[:Named_to_be:]+"\\"+name.get())#root.title()
if root.title()!='Playlist- Default':
print('yo!2')
boyaah=path1[:Named_to_be:]+"\\"+name.get()
root.title(f'Playlist - {boyaah}')
os.rename(path1[:Named_to_be:]+"\\"+F'{list_.get(ACTIVE)}',path1[:Named_to_be:]+"\\"+name.get())#root.title()
play_List_indict['text']=f'Playlist - {boyaah}'
Recentmenu.entryconfig(timessss12,label=boyaah)
lisst=[]
x1254=0
list_.delete(pos)
list_.insert(pos,names[pos])
x1254+=1
lisst.append(list_.get(0,END))
Recentmenu.entryconfig(pos,label=play_List_indict['text'])
timessss12+=1
t3.destroy()# create a fun fact option option when user lose in my pygame game!! boi!sssk
def edit():#entry config font
global name,t3
t3=Toplevel()
t3.title('Edit')
t3.config(bg='#3C3C3C')
edit_label=Label(t3,text='Edit Playlist Name Here:',font=('Arial',25,'bold')).pack()
name=Entry(t3,bg='#3C3C3C',fg='yellow',font=('Arial Rounded MT bold',14,'bold'))
name.pack()
done=Button(t3,text='Done',font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=save_name)
done.pack()
def question1(dedo):
d = dialog.Dialog(None, {'title': 'Question',
'text':'Which Type Of Task You Want To Do In This Selected Playlist'.title(),
'bitmap': dialog.DIALOG_ICON,
'default': 'None',
'strings': ('Open',
'Edit Name',
'Delete!')})
if d.num==0:
open__()
if d.num==1:
edit()
if d.num==2:
pass
def Savee():
global check1000
check1000='YUP!'
def show_user_own_playlist():
global list_,times_called,t1
t1=Toplevel()
t1.config(bg='#3C3C3C')
t1.title("Your Created Playlists Are Here!")
t2=Label(t1,text='Here Is The List Of Playlist You Created:',font=('Arial Rounded MT bold',25,'bold'))
t2.pack()
list_=Listbox(t1,width=32,bg="#3C3C3C",fg='cyan',font=('Arial',17,'bold'))
list_.pack()
x124=0
lisst=[]
for i1 in names:
list_.insert(x124,i1)
lisst.append(list_.get(0,END))
print(lisst)
x124+=1
list_.bind('<Double-Button>',question1)
def CLOSE():
pygame.mixer.music.stop()
exit()
root.protocol('WM_DELETE_WINDOW',CLOSE)
open_dir_paths=[]
play_ing_song_name=[]
pygame.mixer.init()
def active_all():
play['state']='active'
prev['state']='active'
next1['state']='active'
stop['state']='active'
def _add_folder():
global dir_name,open_dir_paths,mp3_wav_ogg,val,folder_name
dir_name=filedialog.askdirectory()
open_dir_paths.append(dir_name)
good_boiii=[]
mp3_wav_ogg=os.listdir(dir_name)
val=0
play_List_indict.config(text=f'Playlist - {dir_name}')
for x in mp3_wav_ogg:
if str(x).endswith('.mp3') or str(x).endswith('.wav') or str(x).endswith('.ogg'):
play_list.insert(val,x)
val+=1
def upause():
pygame.mixer.music.unpause()
play['image']=pause_image
play['command']=pause
playing_label['text']='Paused - '+play_list.get(ACTIVE)
play.place(y=500,x=340)
def pause():
pygame.mixer.music.pause()
play['image']=play_image
play['command']=upause
play.place(y=500,x=340)
def play_the_song():
global is_playing
active_all()
play['image']=pause_image
try:
if play['image']==pause_image:
pause()
else:
upause()
play.place(x=340,y=500)
try:
pygame.mixer.music.stop()
pygame.mixer.music.load(dir_name.replace('/','\\')+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
except:
pass
playing_label['text']='Playing - '+play_list.get(ACTIVE)
play_ing_song_name.append(dir_name.replace('/','\\')+'\\'+play_list.get(ACTIVE))
if play_ing_song_name[0]==play_list.get(ACTIVE):
pygame.mixer.music.load(dir_name.replace('/','\\')+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
else:
pass
except Exception as e:
raise e
try:
for x in range(len(dir_name)):
pygame.mixer.music.load(dir_name[x].replace('/','\\')+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
except:
messagebox.showinfo('Error','Error Occured!')
raise e
hmm=0
hmm12=0
def set_volume1(self):
pygame.mixer.music.set_volume(float(volume.get()) /100)
def prev_song():
global posxD1,hmm12
a123=play_list.get(0,'end')
list_fromXd5=list(a123)
posxD1=list_fromXd5.index(play_list.get(ACTIVE))
posxD1+=1
hmm12+=1
xdd1=play_list.get(0,'end')
pos1=list(xdd1)
YOOOoooYoo12=pos1.index(play_list.get(ACTIVE))
if hmm12<=1:
play_list.selection_set(YOOOoooYoo12-1)
play_list.selection_clear(YOOOoooYoo12)
play_list.activate(posxD1-1-1)
play_list.see(YOOOoooYoo12-1)#ACTIVATE 'R' SEE
upause()
try:
print('FIX THIS: 3')
play_the_song()
except:
print('FIX THIS: 4')
play_the_song_for_own_playlist_with_button()
else:
play_list.selection_set(YOOOoooYoo12-1)
play_list.selection_clear(YOOOoooYoo12)
play_list.activate(posxD1-1-1)
play_list.see(YOOOoooYoo12-1)#ACTIVATE 'R' SEE
upause()
try:
print('FIX THIS: 5')
play_the_song()
except:
print('FIX THIS: 5')
play_the_song_for_own_playlist_with_button()
def play_the_song_for_own_playlist_with_button():
pygame.mixer.music.stop()
pygame.mixer.music.load(path1+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
playing_label['text']='Playing - '+play_list.get(ACTIVE)
play['image']=pause_image
if play['image']==pause_image:
pause()
playing_label['text']='Paused - '+play_list.get(ACTIVE)
else:
upause()
play.place(x=340,y=500)
def play_the_song_for_own_playlist(head_ahce):
pygame.mixer.music.stop()
pygame.mixer.music.load(path1+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
playing_label['text']='Playing - '+play_list.get(ACTIVE)
play['image']=pause_image
if play['image']==pause_image:
playing_label['text']='Paused - '+play_list.get(ACTIVE)
pause()
else:
upause()
play.place(x=340,y=500)
def add_song1():
global dir_name,open_dir_paths,mp3_wav_ogg,val,val12,folder_name
dir_name123=filedialog.askopenfilename()
times_called=0
open_dir_paths12=[]
open_dir_paths12.append(dir_name123)
for x in open_dir_paths12:
if str(x).endswith('.mp3') or str(x).endswith('.wav') or str(x).endswith('.ogg'):
play_list.insert(val12,x[x.rfind('/')+1:len(x)])
val12+=1
shutil.copyfile(x,path1+'\\'+x[x.rfind('/')+1:len(x)])
play_list.delete(val12+1)
if play_list.get(0)!='':
active_all()
else:
pass
file.entryconfig(0,command=add_song1)
play['command']=play_the_song_for_own_playlist_with_button
# play_List_indict['text']=f'Playlist - {play_list_name}'
def next_song():
#########Next################
global posxD,posxD,pos,B,hmm,xd_bop
a12=play_list.get(0,'end')
list_fromXd=list(a12)
posxD=list_fromXd.index(play_list.get(ACTIVE))
posxD+=1
hmm+=1
xdd=play_list.get(0,'end')
pos=list(xdd)
YOOOoooYoo=pos.index(play_list.get(ACTIVE))
if hmm<=1:
print('1')
play_list.selection_set(YOOOoooYoo+1)
play_list.selection_clear(YOOOoooYoo)
play_list.activate(posxD)
play_list.see(posxD+1)#ACTIVATE 'R' SEE
play.place(x=350,y=500)
upause()
play['image']=pause_image
try:
print('FIX THIS: 1')
play_the_song()
except:
print('FIX THIS: 2')
play_the_song_for_own_playlist_with_button()
else:
play_list.activate(posxD)
play_list.selection_set(YOOOoooYoo+1)
play_list.selection_clear(posxD-1)
play_list.see(posxD+1)
play.place(x=350,y=500)
upause()
try:
play_the_song()
except:
play_the_song_for_own_playlist_with_button()
def Play_The_Slected_Song(BTS_IS_MY_FAV_KPOP_GROUP_AND_EXO_ALSO_AND_STRAY_KIDS_AND_BLOCK_B_ALSO):
pygame.mixer.music.stop()
try:
for x in range(len(open_dir_paths)):
try:
try:
print(5+'fff')
except:
try:
pygame.mixer.music.stop()
pygame.mixer.music.load(dir_name.replace('/','\\')+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
except:
pass
except Exception as e:
messagebox.showinfo('Error','Error Occured!')
raise e
except Exception as r1:
raise r1
try:
pygame.mixer.music.stop()
pygame.mixer.music.load(path1+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
except:
print('I WORKED!')
pygame.mixer.music.stop()
try:
pygame.mixer.music.load(dir_name+'\\'+play_list.get(ACTIVE))
pygame.mixer.music.play()
except:
print('I WORKED!')
playing_label['text']='Playing - '+play_list.get(ACTIVE)
play['image']=pause_image
play['command']=pause
play['state']='active'
prev['state']='active'
next1['state']='active'
stop['state']='active'
play.place(y=500,x=340)
def stop():
pygame.mixer.music.stop()
play['text']='Play'
play['command']=play_the_song
playing_label['text']=''
play.place(y=500,x=350)
def del_playlist():
question=messagebox.askquestion('Info!!','Are Your Sure To Clear Playlist It Will Delete The Playlist!')#rip me!
pygame.mixer.music.stop()
playing_label['text']=''
play_List_indict['text']='Playlist'
play['text']='Play'
open_dir_paths.clear()
try:
open_dir_paths12.clear()
except:
pass
play_list.delete(0,'end')
files=os.listdir(path1)
for i in files:
print('Deleting...')
os.remove(path1+'\\'+i)
print('Playlist Deleted!')
def show_created_window_playlist():
root.title(f'Playlist- {path1}')
play_list.delete(0,'end')
playing_label['text']=''
pygame.mixer.music.stop()
play_List_indict['text']=f'Playlist- {path1}'
Recentmenu.add_command(label=play_List_indict['text'])
add_song['text']='Add song'
add_song['command']=add_song1
def ask_dir_name_to_save():
global check,path1,dir_name12
check=True
timessss=0
dir_name12=simpledialog.askstring("Enter Path To Save The Playlist.",prompt='Enter Path To Save The Playlist.')
while check:
if dir_name12==None:
break
if len(dir_name12)<=0:
ask_dir_name_to_save()
else:
path1=dir_name12+play_list_name.replace('\\','\\')
try:
os.mkdir(path1)
your_playlist.append(path1)
timessss+=1
except OSError:
your_playlist.clear()
ask_dir_name_to_save()
show_created_window_playlist()
# messagebox.showinfo('Info','Playlist Created Successfully!!')
break
def create_playlist():
global play_list_name,Looping
Looping=True
play_list_name=simpledialog.askstring("Enter Your Playlist Name",prompt='Enter Your Playlist Name.')
while True:
try:
if play_list_name==None:
break
try:
if len(play_list_name)<=0:
create_playlist()
else:
messagebox.showinfo("Info",'Playlist Named Successfully!')
if play_list_name.count('/') or play_list_name.count('\\') or play_list_name.count('<') or play_list_name.count('>') or play_list_name.count('''"''') or play_list_name.count('?') or play_list_name.count('*') or play_list_name.count(':') or play_list_name.count('|'): #/\ <> " ? * : |
messagebox.showinfo('Info!!','Your Playlist Name Cannot Contains These Charecters:- /\ <> " ? * : | ')
create_playlist()
else:
names.append(play_list_name)
ask_dir_name_to_save()
break
except Exception as test1000:
raise test1000
create_playlist()
except Exception as test:
raise test
create_playlist()
def open_single_file():
global file_name
file_name=filedialog.askopenfilename()
if str(file_name).endswith('.mp3') or str(file_name).endswith('.wav') or str(file_name).endswith('.ogg'):
opened_file_name=file_name[file_name.rfind('/')+1:len(file_name)]
try:
play_list.insert(val+1,opened_file_name)# ide that set the prtioty of a vairable like the varaible name is file_name but ide is suggeted file varioable but i need file_name variable
messagebox.showinfo('Info',f'{opened_file_name} Added To {folder_name} Playlist')
except:
play_list.insert(val+1,opened_file_name)
open_dir_paths.append(opened_file_name)
prev_image=PhotoImage(file='previous.png')
play_image=PhotoImage(file='play.png')
next_image=PhotoImage(file='next.png')
# stop_image=PhotoImage(file='stop.png')
pause_image=PhotoImage(file='pause.png')
prev=Button(root,image=prev_image,font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=prev_song,state='disabled')
prev.place(y=500,x=231)
play=Button(root,image=play_image,font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=play_the_song,state='disabled')
play.place(y=500,x=350)
next1=Button(root,image=next_image,font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=next_song,state='disabled')
next1.place(y=500,x=330+130)
stop=Button(root,text='Stop',font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=stop,state='disabled')
stop.place(y=570,x=347)# we can increase image size in tkinter by chaing the font size!!,entry conifg,#image creator like a person need a image of cat he/she write the requirment of image like i want a image in black color blue eyes etc.
progressbar=Progressbar(root,length=545)
progressbar.start(10)
progressbar.place(x=1,y=465)
volume_indict_=Label(root,text='Volume:',font=('Arial',15,'bold'))
volume_indict_.place(y=500)
volume=Scale(root,from_=0,to=100,orient=HORIZONTAL,tickinterval=20,length=150,background='#3C3C3C',fg='white',activebackground='#3C3C3C',command=set_volume1)
volume.place(y=530,x=1)
volume.set(50)
lyrics_indict=Label(root,text='Lyrics',font=('Arial',20,'bold'))
lyrics_indict.place(x=200,y=150)
lyrics=Listbox(root,bg='#3C3C3C',width=55,fg='orange',font=('Arial',12,'bold'))
lyrics.place(x=1,y=200)
lyrics.insert(0,"blackpink!".upper())
play_list=Listbox(root,width=32,bg="#3C3C3C",fg='cyan',font=('Arial',12,'bold'),listvar=song_Data)
play_list.place(x=505,y=60)
play_List_indict=Label(root,text='Playlist - Default',font=('Arial',20,'bold'))
play_List_indict.place(x=400,y=10)
add_song=Button(root,text='Add Folder',font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=_add_folder)
add_song.place(x=555,y=270)
playing_label=Label(root,text='',font=('Arial',15,'bold'))
playing_label.place(x=1,y=425)
clear=Button(root,text='Clear Playlist',font=('Arial',20,'bold'),fg='white',bg='#3C3C3C',activeforeground='white',activebackground='#3C3C3C',command=del_playlist)
clear.place(x=545,y=350)
menubar = Menu(root)
Recentmenu=Menu(root,tearoff=0)
file = Menu(menubar, tearoff=0)
file.add_command(label="Open Media",command=open_single_file)
file.add_command(label="Create Playlist",command=create_playlist)
file.add_cascade(label="Recent", menu=Recentmenu)
for name in names:
Recentmenu.add_command(label=name)
file.add_command(label="Your Playlists",command=show_user_own_playlist)
menubar.add_cascade(label="File", menu=file)
root.config(menu=menubar)
# filepath and player vs player.!
# fix resu me pause bug and complete menu options.
# add player vs player and crete a bouncing effect when user get 1 point rock paper sicors.
# send this project to pyguru
# create aplying sound label
play_list.bind('<Double-Button>',Play_The_Slected_Song)
mainloop()
# # create a player vs player mode...!
# # from musixmatch import musixmatch
# # api_key='ffb75ae490c3bfde65848de87864a7d8'
# # musixmatch=musixmatch.Musixmatch(api_key)
# # print(musixmatch.matcher_lyrics_get('blackpink', 'du du du du '))
# import tkinter as tk
# from tkinter import ttk
# from tkinter.messagebox import showinfo
# # create the root window
# root = tk.Tk()
# root.geometry('200x100')
# root.resizable(False, False)
# root.title('Listbox')
# root.columnconfigure(0, weight=1)
# root.rowconfigure(0, weight=1)
# # create a list box
# langs = ('Java', 'C#', 'C', 'C++', 'Python',
# 'Go', 'JavaScript', 'PHP', 'Swift')
# langs_var = tk.StringVar(value=langs)
# listbox = tk.Listbox(
# root,
# height=6,
# selectmode='single')
# for x in langs:
# val=0
# listbox.insert(0,x)
# val+=1
# listbox.grid(
# column=0,
# row=0,
# sticky='nwes'
# )
# def op():
# global val
# val+=1
# listbox.select_set(val)
# listbox.itemconfig(val-1,fg='black')
# listbox.select_clear(val-1)
# listbox.itemconfig(val-1,fg='grey')
# root.after(1000,op)
# val=0
# listbox.selection_set(0)
# listbox.itemconfig(len(langs)-1,fg='grey')
# root.after(1000,op)
# # everthing in python is object and pop() removes the elemtnt and return its. and del delte the keyword
# # handle event
# # slection_set method is op.
# # select_clear is alos op.
# def items_selected(event):
# """ handle item selected event
# """
# # get selected indices
# selected_indices = listbox.curselection()
# # get selected items
# selected_langs = ",".join([listbox.get(i) for i in selected_indices])
# msg = f'Your selected: {selected_langs}'
# showinfo(
# title='Information',
# message=msg)
# create own module bitch!
# root.mainloop()
# learn about audio and coced and explore tkinter more!
# speed function
| UTF-8 | Python | false | false | 18,360 | py | 19 | main.py | 18 | 0.684477 | 0.652996 | 0 | 610 | 29.096721 | 288 |
mooja/dailyprogrammer | 9,216,999,857,249 | 005fcfdf7249bbff6abb1f53abeb8302be6bebba | b4dd760e79de0db39792b947bacfe2b27c2a89ee | /kata_fizzbuzz.py | f1afd8cc021452d494755bade5ec6800965dd695 | []
| no_license | https://github.com/mooja/dailyprogrammer | c23f1a0c5d6e4269b6c03b47d8cc18f6d857a6e1 | d12fcb6744ac3b4a5e651f37ea0b3f20ca062f7d | refs/heads/master | 2021-01-16T23:47:28.955660 | 2018-04-09T18:03:50 | 2018-04-09T18:03:50 | 23,394,207 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# encoding: utf-8
import unittest
def fizzbuzz(n):
a, b, c = 0, 0, 0
for i in xrange(1, n):
if i % 3 == 0 and i % 5 == 0:
c += 1
elif i % 3 == 0:
a += 1
elif i % 5 == 0:
b += 1
return [a, b, c]
class TestFizzBuzz(unittest.TestCase):
def test_fizzbuzz1(self):
self.assertEqual((fizzbuzz(20)), [5,2,1])
def test_fizzbuzz2(self):
self.assertEqual((fizzbuzz(2)), [0,0,0])
def test_fizzbuzz3(self):
self.assertEqual((fizzbuzz(30)), [8,4,1])
def test_fizzbuzz4(self):
self.assertEqual((fizzbuzz(300)), [80,40,19])
if __name__ == '__main__':
unittest.main()
| UTF-8 | Python | false | false | 710 | py | 379 | kata_fizzbuzz.py | 369 | 0.511268 | 0.450704 | 0 | 37 | 18.189189 | 53 |
wcheung8/halite-3-DL-project | 16,415,365,031,100 | 11adbceed48e5db345ecbed7715809af6909f628 | b0d445c5d64a0e199e40de547d776d13017974e4 | /MyBot.py | 24dcc9d69ba4aa671cd1e255a5adafdd191e4c6c | []
| no_license | https://github.com/wcheung8/halite-3-DL-project | 86613c14b5dd217733d6012454b5773f9cfcc6ca | 6f4e05c47e83d3a216fa41e6bc4b32f47a950431 | refs/heads/master | 2020-04-09T01:09:24.095525 | 2018-12-08T21:57:57 | 2018-12-08T21:57:57 | 159,893,754 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
import os
import sys
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
from MLBot import *
class NN_Bot(MLBot):
def __init__(self):
super().__init__(sys.argv[1]+".nn")
if __name__ == '__main__':
bot = NN_Bot()
bot.run()
| UTF-8 | Python | false | false | 290 | py | 6 | MyBot.py | 4 | 0.613793 | 0.606897 | 0 | 17 | 16.058824 | 55 |
17600117041/my_Django | 11,330,123,746,261 | 73eeebc3fa73ca7ca24bdc434e3af1064e61df0f | 021c21281665ef4ed6b18bb2c84d1c0f9429dec0 | /adminweb/migrations/0001_initial.py | a054447bd43852e98a4121e657ec830acada7595 | []
| no_license | https://github.com/17600117041/my_Django | f28dfcb959218bfaef4c89736107692a7007fedc | c2cd2e1c321157687b6f6dc3a87879a35e71c421 | refs/heads/master | 2021-06-24T07:01:08.072179 | 2017-09-13T09:33:37 | 2017-09-13T09:33:37 | 103,378,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-12 07:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Admin',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50)),
('pwd', models.CharField(max_length=50)),
('add_time', models.IntegerField(default=0)),
],
),
migrations.CreateModel(
name='ArtSingle',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50)),
('content', models.TextField()),
],
),
migrations.CreateModel(
name='Data',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50)),
('content', models.TextField()),
('add_time', models.IntegerField(default=0)),
('sort', models.IntegerField(default=0)),
('type', models.IntegerField(default=0)),
('hits', models.IntegerField(default=0)),
('picture', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='DataClass',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50)),
('parent_id', models.IntegerField(default=0)),
('sort', models.IntegerField(default=0)),
('type', models.IntegerField(default=0)),
],
),
migrations.AddField(
model_name='data',
name='dataclass',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='adminweb.DataClass'),
),
]
| UTF-8 | Python | false | false | 2,177 | py | 5 | 0001_initial.py | 5 | 0.519982 | 0.502986 | 0 | 62 | 34.112903 | 106 |
Dauphin-NWU/Leetcode-Practice | 17,703,855,209,689 | 7aeb1ee8ea3b12e9b00d9d124f4fc3e1adee2fe1 | d1ebc64bc9c817b1d7b2a55e7964e68c60c813cf | /301-400/371-380/py/375_guess_number_higher_or_lower_2.py | 137fcaa3048584f8e5cb2014b1c0db0b9620c82f | []
| no_license | https://github.com/Dauphin-NWU/Leetcode-Practice | d213a844cd4be9c736fbc5cb93822c087f1f96bc | 614d8e7afc9761bded794d4c5df6800bcdb5f710 | refs/heads/master | 2017-04-26T17:22:34.770608 | 2017-04-21T18:01:37 | 2017-04-21T18:01:37 | 44,287,169 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
# start coding at 10:28
INF = 0x7fffffff;
dp = [[INF for i in range(n+1)] for j in range(n+1)];
def gen(dp, left, right):
if dp[left][right] != INF: return dp[left][right];
if left == right:
dp[left][right] = 0;
return dp[left][right];
if left+1 == right:
dp[left][right] = left;
return dp[left][right];
for i in range(left+1, right):
dp[left][right] = min(dp[left][right], i + max(gen(dp, left, i-1), gen(dp, i+1, right)));
return dp[left][right];
return gen(dp, 1, n);
# pass at 10:33 | UTF-8 | Python | false | false | 828 | py | 577 | 375_guess_number_higher_or_lower_2.py | 576 | 0.440821 | 0.419082 | 0 | 25 | 32.16 | 105 |
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | 5,214,090,299,848 | 7b4ace370871dc81adb62d38021bd608023f57bc | 422dd5d3c48a608b093cbfa92085e95a105a5752 | /students/srepking/lesson06/water-regulation/waterregulation/decider.py | df4eb7c25c2a8c9a7fe95323d3470444888faafc | []
| no_license | https://github.com/UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | a2052fdecd187d7dd6dbe6f1387b4f7341623e93 | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | refs/heads/master | 2021-06-07T09:06:21.100330 | 2019-11-08T23:42:42 | 2019-11-08T23:42:42 | 130,731,872 | 4 | 70 | null | false | 2021-06-01T22:29:19 | 2018-04-23T17:24:22 | 2019-11-08T23:42:45 | 2021-06-01T22:29:16 | 43,341 | 3 | 65 | 8 | Python | false | false | """
Encapsulates decision making in the water-regulation module
"""
import logging
logging.basicConfig(level=logging.DEBUG)
class Decider:
"""
Encapsulates decision making in the water-regulation module
"""
def __init__(self, target_height, margin):
"""
Create a new decider instance for this tank.
:param target_height: the target height for liquid in this tank
:param margin: the margin of liquid above and below the target height
for which the pump should not turn on. Ex: .05 represents a
5% margin above and below the target_height.
"""
self.target_height = target_height
self.margin = margin
# If the pump is off and the height is below the margin region,
# then the pump should be turned to PUMP_IN.
if self.target_height < 0:
raise Exception('Bad Height Setting.')
def decide(self, current_height, current_action, actions):
"""
Decide a new action for the pump, given the current height of liquid
in the tank and the current action of the pump.
Note that the new action for the pump MAY be the same as the current
action of the pump.
The *decide* method shall obey the following behaviors:
1. If the pump is off and the height is below the margin region,
then the
pump should be turned to PUMP_IN.
2. If the pump is off and the height is above the margin region,
then the
pump should be turned to PUMP_OUT.
3. If the pump is off and the height is within the margin region
or on
the exact boundary of the margin region, then the pump shall
remain at
PUMP_OFF.
4. If the pump is performing PUMP_IN and the height is above the
target
height, then the pump shall be turned to PUMP_OFF, otherwise
the pump
shall remain at PUMP_IN.
5. If the pump is performing PUMP_OUT and the height is below
the target
height, then the pump shall be turned to PUMP_OFF, otherwise,
the pump
shall remain at PUMP_OUT.
:param current_height: the current height of liquid in the tank
:param current_action: the current action of the pump
:param actions: a dictionary containing the keys 'PUMP_IN', 'PUMP_OFF',
and 'PUMP_OUT'
:return: The new action for the pump: one of actions['PUMP_IN'],
actions['PUMP_OUT'], actions['PUMP_OFF']
"""
new_action = current_action
if current_height < 0:
raise Exception('Sensor reading cannot be less than 0.')
if current_action not in (-1, 0, 1):
logging.debug('In Decider, the pump status is %s', current_action)
raise Exception('Bad Pump Status')
if current_action == 0 and current_height < (self.target_height -
self.margin):
logging.debug('In Decider, the value of current_height is %s',
current_height)
logging.debug('In Decider, the value of current_action is %s',
current_action)
logging.debug('In Decider, the value of target_height is %s',
self.target_height)
logging.debug('In Decider, the return value is %s',
actions['PUMP_IN'])
new_action = actions['PUMP_IN']
# If the pump is off and the height is above the margin region, then the
# pump should be
# turned to PUMP_OUT.
if current_action == 0 and current_height > (self.target_height +
self.margin):
new_action = actions['PUMP_OUT']
# If the pump is off and the height is within the margin region or on
# the exact boundary of the margin region, then the pump shall remain at
# PUMP_OFF
if current_action == 0 and (self.target_height - self.margin) \
<= current_height <= (self.target_height + self.margin):
new_action = actions['PUMP_OFF']
# If the pump is performing PUMP_IN and the height is above the target
# height, then the pump shall be turned to PUMP_OFF, otherwise the pump shall
# remain at PUMP_IN.
if current_action == 1 and (self.target_height) < current_height:
new_action = actions['PUMP_OFF']
# If the pump is performing PUMP_IN and the height is less than or equal to
# target
# height plus margin, then the pump shall remain at PUMP_IN.
if current_action == 1 and (self.target_height) >= current_height:
new_action = actions['PUMP_IN']
# If the pump is performing PUMP_OUT and the height is below the target
# height, then the pump shall
# be turned to PUMP_OFF, otherwise, the pump shall remain at PUMP_OUT
if current_action == -1 and self.target_height > current_height:
new_action = actions['PUMP_OFF']
if current_action == -1 and self.target_height <= current_height:
new_action = actions['PUMP_OUT']
return new_action
| UTF-8 | Python | false | false | 5,240 | py | 2,050 | decider.py | 1,627 | 0.60458 | 0.600573 | 0 | 124 | 41.258065 | 79 |
nEDM-TUM/Sis3302Datahandling | 16,707,422,801,341 | c4790443d8063ea96d3cc23515beecfb9e89bb7a | a3406f9ac9fa840daffe9df3a0bbc8c643d692bd | /sis3302Datahandling.py | 7c1a5271ca1194d2a3d0db7659802d4e7112a87d | []
| no_license | https://github.com/nEDM-TUM/Sis3302Datahandling | f0309371f6fbb30aad093e6ee8b25b52865abaf3 | 3a764bd2b514d5b1ae48e4ac75b6fcd6b3a7986e | refs/heads/master | 2021-01-13T01:40:57.996865 | 2014-04-16T15:27:53 | 2014-04-16T15:27:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 8 10:35:34 2012
@author: bernd
"""
import numpy
import ROOT
import os
import sys
import array
import pathfinder
from convert_sis3302_files import WFConvert
ROOT.gSystem.Load(pathfinder.libPyOrcaROOT)
ROOT.gSystem.Load(pathfinder.libWaveWaveBase)
class orcadatamanipulation(object):
def __init__(self, orcafile='', rootfile='', channelnum=0, numtriggers=1):
"""
functions to transform Orca files to root) or ascii(averaged) files
"""
self.orcafile=str(pathfinder.OrcaFileFolder)+'/'+orcafile
self.channelnum=channelnum
self.rootfile=pathfinder.ROOTFileFolder+rootfile
self.numtriggers=numtriggers
ROOT.gSystem.Load(pathfinder.libWaveWaveBase)
self.rootfilefolder=pathfinder.ROOTFileFolder
self.orcafilefolder=pathfinder.OrcaFileFolder
self.npyfilefolder=pathfinder.NpyFileFolder
self.index=self.orcafile.rfind("/",0,len(self.orcafile))
#self.txtfilepath=self.orcafile[0:self.index+1]
#self.txtfilepath="/Users/nedmdaq/Desktop/Data/Txtified/"
self.txtfilefolder=pathfinder.TxtFileFolder
def rootify(self):
""" obsolete , use rooter """
# os.system("export ROOTSYS=/home/bernd/Desktop/bernd/root/root")
#os.system("export PYTHONPATH=${ROOTSYS}/lib")
#os.system("export LD_LIBRARY_PATH=${ROOTSYS}/lib:${LD_LIBRARY_PATH}")
#os.system("export LD_LIBRARY_PATH=/home/bernd/root/TWaveform/lib:${LD_LIBRARY_PATH}")
#os.system("export LD_LIBRARY_PATH=/home/bernd/root/OrcaROOT/lib:${LD_LIBRARY_PATH}")
#os.export("export PATH=${ROOTSYS}/bin:${PATH}")
os.system("/home/bernd/Dropbox/EXC_BerndShare/AnalyzeThis/orcaroot_WF "+self.orcafile)
index=self.orcafile.rfind("/",0,len(self.orcafile))
runnumber=self.orcafile[index+1:len(self.orcafile)].lower()
runnumber.lower()
self.rootfile=self.rootfilefolder+runnumber+".root"
print self.rootfile
def rooter(self):
reader = ROOT.ORFileReader()
#for afile in self.orcafile: reader.AddFileToProcess(afile)
if self.orcafile:
print 'this file is used:'
print self.orcafile
else:
print "no orcafile loaded"
return
reader.AddFileToProcess(str(self.orcafile))
mgr = ROOT.ORDataProcManager(reader)
# fw = ROOT.ORFileWriter('/Users/nedmdaq/Desktop/Data/Rootified/pref')
fw = ROOT.ORFileWriter(self.rootfilefolder+"pref")
run_notes = ROOT.ORRunNotesProcessor()
xycom = ROOT.ORXYCom564Decoder()
rdTree = ROOT.ORBasicRDTreeWriter(xycom, "xyCom")
sisGen = ROOT.ORSIS3302GenericDecoder()
wf = WFConvert(sisGen, "sisDec")
mgr.AddProcessor(fw)
mgr.AddProcessor(run_notes)
mgr.AddProcessor(wf)
mgr.ProcessDataStream()
index=self.orcafile.rfind("/",0,len(self.orcafile))
runnumber=self.orcafile[index+1:len(self.orcafile)].lower()
runnumber.lower()
self.rootfile=self.rootfilefolder+"pref_"+runnumber+".root"
print self.rootfile
def draw_all_counts(self, event=None):
if self.channelnum and self.numtriggers:
event=self.channelnum+8*self.numtriggers
else:
event=None
if self.rootfile:
print "this rootfile is used: "+self.rootfile
else:
if self.orcafile:
self.rooter()
print "orcafile used: "+self.orcafile
else:
print "no file loaded"
return
self.feil=ROOT.TFile(self.rootfile)
self.feil.Get('sisDec')
if event:
self.feil.sisDec.GetEntry(event)
self.feil.sisDec.wf.GimmeHist().Draw()
raw_input("jump ma die leider weider")
else:
#for n in range(self.channelnum, self.channelnum*8+self.numtriggers*8, 8):
n=self.channelnum
while self.feil.sisDec.GetEntry(n):
self.feil.sisDec.GetEntry(n)
self.feil.sisDec.wf.GimmeHist().Draw()
raw_input("jump ma die leider weider")
n=n+8
def numpyfy(self, event=None):
"""
save counts as numpy arrays
"""
if self.rootfile:
print "this rootfile is used: "+self.rootfile
else:
if self.orcafile:
self.rooter()
print "orcafile used: "+self.orcafile
else:
print "no file loaded"
return
if self.channelnum and self.numtriggers!=None:
event=self.channelnum+8*self.numtriggers
else:
event=None
feil=ROOT.TFile(self.rootfile)
feil.Get('sisDec')
index=self.rootfile.rfind("_",0,len(self.rootfile))
run=self.rootfile[index+1:len(self.rootfile)].lower()[0:-5]
run.lower()
print "event:"
print event
if event != None:
feil.sisDec.GetEntry(event)
FILE=self.npyfilefolder+run+"count"+str(event)
#arr=numpy.array(feil.sisDec.wf,dtype="uint16")
arr = numpy.frombuffer(feil.sisDec.wf.GetData(),count=len(feil.sisDec.wf),dtype=numpy.uint16)
numpy.save(FILE,arr)
else:
# for n in range(self.channelnum, self.channelnum*8+self.numtriggers*8, 8):
n=self.channelnum
while feil.sisDec.GetEntry(n):
feil.sisDec.GetEntry(n)
FILE=self.npyfilefolder+run+"count"+str(n)
#arr=numpy.array(feil.sisDec.wf,dtype="uint16")
arr = numpy.frombuffer(feil.sisDec.wf.GetData(),count=len(feil.sisDec.wf),dtype=numpy.uint16)
numpy.save(FILE,arr)
n=n+8
print arr.dtype
print "done"
def txtify(self, averages=10, event=None):
"""
save each count to a .txt file
"""
# if orcafile:
# run=self.orcafile[self.index+1:len(self.orcafile)]
if self.rootfile:
print "this rootfile is used: "+self.rootfile
else:
if self.orcafile:
self.rooter()
print "orcafile used: "+self.orcafile
else:
print "no file loaded"
return
if self.channelnum and self.numtriggers:
event=channelnum+8*numtriggers
else:
event=None
feil=ROOT.TFile(self.rootfile)
feil.Get('sisDec')
index=self.rootfile.rfind("_",0,len(self.rootfile))
run=self.rootfile[index+1:len(self.rootfile)].lower()[0:-5]
run.lower()
# if event:
# feil.sisDec.GetEntry(event)
# feil.sisDec.GetEntry(event)
# if event:
# feil.sisDec.GetEntry(event)
# feil.Get('sisDec')
if event:
feil.sisDec.GetEntry(event)
FILE=open(self.txtfilefolder+run+"count"+str(event)+".txt","w")
data=feil.sisDec.wf.GetData()
for i in range(0,feil.sisDec.wf.GetLength(),averages):
avg=0
for j in range (averages):
avg=avg+data.__getitem__(i+j)
FILE.write(str(avg/averages)+"\n")
FILE.close()
else:
# for n in range(self.channelnum, self.channelnum*8+self.numtriggers*8, 8):
n=self.channelnum
while feil.sisDec.GetEntry(n):
feil.sisDec.GetEntry(n)
FILE=open(self.txtfilefolder+run+"count"+str(n)+".txt","w")
data=feil.sisDec.wf.GetData()
for i in range(0,feil.sisDec.wf.GetLength(),averages):
avg=0
for j in range (averages):
avg=avg+data.__getitem__(i+j)
FILE.write(str(avg/averages)+"\n")
FILE.close()
n=n+8
| UTF-8 | Python | false | false | 7,047 | py | 4 | sis3302Datahandling.py | 2 | 0.658294 | 0.648361 | 0 | 214 | 31.929907 | 95 |
lanister58/readme1 | 206,158,444,757 | 845f13c3b3fdecf7dc8324d62df17d02db37244c | fa527d9bfb076aa8ec3aa14ea924d7eab78b5562 | /evenodd1.py | d78cce8fe4ee7f698ce142a222a00bb6c2d7700f | []
| no_license | https://github.com/lanister58/readme1 | 05ea1afc5751b2afd0a05c084e52d6c78f77076e | 5ae16090618d5ac937f5e04ec44b9e8e44a87489 | refs/heads/master | 2020-12-06T15:09:23.782592 | 2020-01-25T11:53:21 | 2020-01-25T11:53:21 | 232,493,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | i=[1,2,3,4,5,10]
for a in i:
if a % 2 == 0:
print(a, "is even")
else:
print(a,"is odd") | UTF-8 | Python | false | false | 117 | py | 5 | evenodd1.py | 2 | 0.401709 | 0.324786 | 0 | 8 | 13.75 | 27 |
TitechMeister/mikan | 16,922,171,157,751 | b5de46660dc3e0649bbf3f9a9896066e3a317f6c | 7d7bbaea128d521c40d2d0890b025ca05c258547 | /members/views.py | 03d0d89be8d9d87d7b00daf318ea9f190d4c2048 | []
| no_license | https://github.com/TitechMeister/mikan | 43c27a267cc24c5c26464454de5443f6a7e8c567 | f51878b0fc18ab74b37c8a045e1a0d7c6877dcfb | refs/heads/develop | 2022-12-12T19:23:31.168911 | 2021-10-28T14:38:26 | 2021-10-28T14:38:26 | 123,887,409 | 0 | 0 | null | false | 2022-12-08T03:15:00 | 2018-03-05T08:19:26 | 2021-10-28T14:45:14 | 2022-12-08T03:14:59 | 202 | 0 | 0 | 6 | Python | false | false | from rest_framework import viewsets, permissions
from members.models import Member, Team
from members.serializers import MemberSerializer, TeamSerializer
class MemberViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = Member.objects.all()
serializer_class = MemberSerializer
class TeamViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = Team.objects.all()
serializer_class = TeamSerializer
permission_classes = (permissions.AllowAny,)
| UTF-8 | Python | false | false | 701 | py | 45 | views.py | 42 | 0.728959 | 0.728959 | 0 | 22 | 30.863636 | 69 |
MichaelMikeJones/HackerRank_Challenges | 936,302,893,304 | 7f3310b8f9d1f2ee744c26e5511848c3ea35801a | 09c2f19d50b53a9b742e97cb3d1b131d4c6feb8e | /Python/16-Numpy/Mean_Var_and_Std.py | e5a80ddf2dbbbeec1b3e529e4d9b3002b187cfdd | []
| no_license | https://github.com/MichaelMikeJones/HackerRank_Challenges | d5a2a90cd6f71065312ce69eca7e4ee1845ea95a | 9e651aab4a9d2e5a646c7ecbf051435f58e6dbb0 | refs/heads/master | 2022-01-26T23:33:51.441722 | 2019-06-30T19:31:55 | 2019-06-30T19:31:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy
numpy.set_printoptions(legacy='1.13')
n, m = map(int, input(). split())
A = [list(map(int, input().split())) for _ in range(n)]
print(numpy.mean(A, axis=1))
print(numpy.var(A, axis=0))
print(numpy.std(A, axis=None))
| UTF-8 | Python | false | false | 233 | py | 71 | Mean_Var_and_Std.py | 68 | 0.648069 | 0.626609 | 0 | 11 | 20.181818 | 55 |
tomsiadev/spinup-vpg | 1,786,706,406,206 | 7368499f16701c8fb69afe44426a6be691eff585 | d8b59251d526e5ff3d9c9c31fdc8e5d2f39c2ec8 | /train.py | 315d4d2c4dd90d1b9e3798bfa22c09819e4b8bed | []
| no_license | https://github.com/tomsiadev/spinup-vpg | 25c35736efa54cfb2fe8c8c2e5ba36616a86a83b | 19b0f7dadf65563d24fe3426a61ccd8aadaa99b1 | refs/heads/master | 2023-06-13T02:01:33.592271 | 2021-07-07T11:10:27 | 2021-07-07T11:10:27 | 383,769,868 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import gym
import torch.cuda
from torch.optim import Adam
from models import *
from vpg import *
def train():
env_name = 'CartPole-v1'
epochs = 2000
max_ep_length = 2000
save_freq = 200
value_updates_per_trajectory = 80
actor_hidden_sizes = [64, 64]
value_hidden_sizes = [64, 64]
actor_lr = 0.001
value_lr = 0.001
gamma = 0.99
lambd = 0.97
env = gym.make(env_name)
obs_size = env.observation_space.shape[0]
act_size = env.action_space.n
actor_net = ActorNet(obs_size, actor_hidden_sizes, act_size).float()
value_net = ValueNet(obs_size, value_hidden_sizes).float()
actor_optim = Adam(actor_net.parameters(), actor_lr)
value_optim = Adam(value_net.parameters(), value_lr)
for i in range(epochs):
print("EPOCH {}".format(i))
train_one_epoch(env, actor_net, value_net, actor_optim, value_optim, gamma, lambd,
value_updates_per_trajectory=value_updates_per_trajectory,
max_epoch_length=max_ep_length, render=False)
if (i+1) % save_freq == 0:
torch.save(actor_net.state_dict(), "models/actor_{}".format(i + 1))
torch.save(value_net.state_dict(), "models/value_{}".format(i + 1))
if __name__=='__main__':
train()
| UTF-8 | Python | false | false | 1,299 | py | 4 | train.py | 4 | 0.605851 | 0.574288 | 0 | 50 | 24.98 | 90 |
mabelzhang/sandbox | 1,013,612,282,953 | 81afa74e6ecdd9628bb96a690267f15868af8328 | d5647d7196a6c215914c3b0e64ac0f6b55e00023 | /catkin_ws/src/grasp_collection/src/grasp_collection/config_consts.py | fbf27c2f6a0ec4eff80d23e14eb6110012b885ee | []
| no_license | https://github.com/mabelzhang/sandbox | 2862073bd776a62d6b508302770d347effbff4d4 | 6c501b57ec39bd84daec913a1683d5f53cf43f9b | refs/heads/master | 2021-07-17T23:27:25.483704 | 2020-05-04T05:08:48 | 2020-05-04T05:08:48 | 146,808,872 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# Mabel Zhang
# 1 Oct 2018
#
# Constants for GraspIt grasp planning.
#
# GraspIt world files in GraspIt installation path worlds/ to load
# Use this instead of YAML in depth_scene_rendering, `.` grasps don't need to
# be re-generated all the time! Only need to generate once! Grasps are the
# same for any camera angle.
worlds = [
'dexnet/bar_clamp',
'dexnet/gearbox',
'dexnet/nozzle',
'dexnet/part1',
'dexnet/part3',
'dexnet/pawn',
'dexnet/turbine_housing',
'dexnet/vase']
def world_to_object_base (world):
return world.split ('/') [1]
# Quality measure for GraspIt planning.
# Default quality measure: search_energy="GUIDED_POTENTIAL_QUALITY_ENERGY"
# Defined in $GRASPIT/src/EGPlanner/energy/searchEnergyFactory.cpp
# Key: Constant for calling GraspIt
# Value: Abbreviation for .npz label files' prefix for ML predictor
energies_abbrevs = {
'CONTACT_ENERGY': 'cte', # 0
'POTENTIAL_QUALITY_ENERGY': 'pqe', # 1
'AUTO_GRASP_QUALITY_ENERGY': 'agqe', # 2
'GUIDED_POTENTIAL_QUALITY_ENERGY': 'gpqe', # 3. Default
'GUIDED_AUTO_GRASP_QUALITY_ENERGY': 'gagqe', # 4
'STRICT_AUTO_GRASP_ENERGY': 'sage', # 5
'COMPLIANT_ENERGY': 'cge', # 6
'DYNAMIC_AUTO_GRASP_ENERGY': 'dage', # 7
}
# Select the search energy to use
SEARCH_ENERGY = 'GUIDED_POTENTIAL_QUALITY_ENERGY'
ENERGY_ABBREV = energies_abbrevs [SEARCH_ENERGY]
# Grasps with energy above this value can be skipped when writing training data
# in tactile_occlusion_heatmaps png_to_npz.py.
# Rough observation from gpqe. Positive energy definitely bad.
THRESH_INVALID_ENERGY = 0
# Number of pose parameters for different orientation parameterizations
# Quaternions (3 translational + 4 orientational)
N_PARAMS_QUAT = 7
# Select the parameteraization to use for gripper pose
N_POSE_PARAMS = N_PARAMS_QUAT
| UTF-8 | Python | false | false | 1,829 | py | 103 | config_consts.py | 57 | 0.722253 | 0.711318 | 0 | 57 | 31.052632 | 79 |
Zrealshadow/Matrixslow | 6,897,717,491,972 | 6e71a3d570a66ba8a4ea7a033e20b83eb419c3fd | 207bcb19c0bd0392c707873909e4daaded4ff732 | /demo/logistic.py | 6e409789cdf97200286ff34f573140ab8a2ef4d2 | []
| no_license | https://github.com/Zrealshadow/Matrixslow | c09c7de3df329836eb8374c83e216e48c5820e91 | 19d62cd640f0c6b52630981b65c748855ac45cb2 | refs/heads/main | 2023-03-18T07:41:24.490703 | 2021-03-07T14:30:50 | 2021-03-07T14:30:50 | 341,768,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
* @author Waldinsamkeit
* @email Zenglz_pro@163.com
* @create date 2021-02-25 15:01:47
* @desc
'''
import matrixslow as ms
from matrixslow.core import Variable
import numpy as np
import matrixslow.optimizer as optim
male_heights = np.random.normal(171, 6, 500)
female_heights = np.random.normal(158, 5, 500)
male_weights = np.random.normal(70, 10, 500)
female_weights = np.random.normal(57, 8, 500)
male_bfrs = np.random.normal(16, 2, 500)
female_bfrs = np.random.normal(22, 2, 500)
male_labels = [1] * 500
female_labels = [-1] * 500
train_set = np.array(
[
np.concatenate([male_heights, female_heights]),
np.concatenate([male_weights, female_weights]),
np.concatenate([male_bfrs, female_bfrs]),
np.concatenate([male_labels, female_labels])
]
).T
np.random.shuffle(train_set)
x = Variable(dim = (3, 1), init=False, trainable=False)
label = Variable(dim = (1, 1), init=False, trainable=False)
w = Variable(dim = (1, 3), init=True, trainable=True)
b = Variable(dim = (1, 1), init=True, trainable=True)
output = ms.ops.Add(ms.ops.MatMul(w,x), b)
predict = ms.ops.Sigmoid(output)
loss = ms.loss.LogLoss(ms.ops.MatMul(predict,label))
learning_rate = 1e-4
opt = optim.Adam(ms.default_graph, loss, learning_rate=learning_rate)
batch_size = 16
for epoch in range(200):
batch_count = 0
for i in range(len(train_set)):
features = np.mat(train_set[i,:-1]).T
l = np.mat(train_set[i,-1])
x.set_value(features)
label.set_value(l)
opt.one_step()
batch_count += 1
if batch_count == batch_size:
batch_count = 0
opt.update()
pred = []
for i in range(len(train_set)):
features = np.mat(train_set[i, :-1]).T
x.set_value(features)
predict.forward()
pred.append(predict.value[0,0])
pred = np.where(np.array(pred) > 0.5, 1, -1)
y = train_set[:,-1]
accuracy = np.where(y * pred > 0.0 , 1.0, 0.0)
accuracy = np.sum(accuracy) * 1.00 / accuracy.size
print("epoch :{:d}, accuracy :{:.3f}".format(epoch+1, accuracy))
| UTF-8 | Python | false | false | 2,122 | py | 15 | logistic.py | 15 | 0.618756 | 0.570217 | 0 | 88 | 23.102273 | 69 |
CarlLOL01/Python_Coding | 11,751,030,546,878 | e18a9ae520c88ced67a758523e7f95042197c20d | 0c84154dac47431b8e58b52cae40002b11ebadc3 | /Spider/01_requests/07.cookie_session_3.py | 572b0ec8d6bbb1366fc665348a93c16a2fde1690 | []
| no_license | https://github.com/CarlLOL01/Python_Coding | 61671ed6f4361a2377f3f67a542ec05e2d3ea7f4 | cb6a1194e65fad30b1fde5713bc1fd8e51a21f77 | refs/heads/master | 2022-05-11T18:56:43.515378 | 2019-03-25T04:29:49 | 2019-03-25T04:29:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import requests
def main():
# session = requests.session()
post_url = "http://www.renren.com/PLogin.do"
post_headers = {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
}
cookie_str = "anonymid=jqevq93zwqvvhs; depovince=GW; _r01_=1; JSESSIONID=abc0mItCOXmxI8FBiInGw; ick_login=f1af75ef-cfe3-4af9-af54-e58452e529f6; ick=e4b0d79e-7024-473c-8ce4-ea4b993f680f; XNESSESSIONID=39fe09866f75; jebecookies=1b47c69f-e6ed-469c-b763-6430f7b1ebd2|||||; _de=292313AA6F309B3C75AC6BB1D7847ADE; p=e801b4b0b153fec6e258c1b5917688da4; first_login_flag=1; ln_uact=17623702688; ln_hurl=http://head.xiaonei.com/photos/0/0/men_main.gif; t=c55af692f435895e0a7889e16c8603d84; societyguester=c55af692f435895e0a7889e16c8603d84; id=969328524; xnsid=f1511da4; ver=7.0; loginfrom=null; wp_fold=0; vip=1; arp_scroll_position=0"
cookies = { i.split("=")[0] :i.split("=")[1] for i in cookie_str.split("; ")}
# post_data = {"email":"17623702688",
# "password":"3NR,/nen8P,Wr2qf,"}
# session.post(post_url, headers= post_headers, data= post_data)
# r = session.get("http://www.renren.com/969328524", headers = post_headers )
r = requests.get("http://www.renren.com/969328524", headers= post_headers, cookies= cookies)
with open('renren2.html', "w", encoding="utf8") as f:
f.write(r.content.decode())
if __name__ == "__main__":
main() | UTF-8 | Python | false | false | 1,486 | py | 209 | 07.cookie_session_3.py | 185 | 0.697174 | 0.527591 | 0 | 25 | 58.44 | 628 |
daniel-lozano/Machine-Learning | 18,150,531,821,075 | 7c191e2c53057055ba7c792dff648d2e6bc5a578 | 067f7fc1f4380d61bbc07c6e8bca12229fedf78b | /Classifying/CPP/XY_model/kpca_xy.py | d8705fbe5f03a27179da1fe314330ace429e2da3 | []
| no_license | https://github.com/daniel-lozano/Machine-Learning | e07c5a8a13a3adac5e992280c67eb8966dc9f9bc | c403212045602e3a2e313807a2ee5c62e666881d | refs/heads/master | 2020-05-02T01:51:48.579628 | 2020-04-29T19:50:52 | 2020-04-29T19:50:52 | 177,693,311 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
number=input("Enter the number of configurations=")
file_name_configs_mattis="spin_configurations_mattis_L"+number+".bin"
file_name_labels_mattis="spin_labels_mattis_L"+number+".bin"
file_name_temps_mattis="spin_T_mattis_L"+number+".bin" #"spin_labels_mattis_L"+number+".txt"
Spins=np.loadtxt(file_name_configs_mattis)
T=np.loadtxt(file_name_labels_mattis)
Temp=np.loadtxt(file_name_temps_mattis )
print(Spins.shape)
######################################################################
############################ Data Parameters ########################
######################################################################
N_data=Spins.shape[0]
N_spins=Spins.shape[1]
print(Spins[:,:N_spins].shape)
print("There are %d configurations and %d spins in each configuration" %(N_data,N_spins))
print(Spins.shape)
K=(Spins@Spins.T)**2
ENN=np.ones(K.shape)
K_pca= K - ENN@K/N_data - K@ENN/N_data + ENN@K@ENN/N_data**2
print("Shape of K_pca",K_pca.shape)
X_c=np.array(K_pca)
eigen_vals,eigen_vects=np.linalg.eig(X_c) #.T@X_c/(N_data-1))
eigen_vals*=1./sum(eigen_vals)
print(eigen_vals[:10])
X_prime=X_c@eigen_vects
print("Size of X_prime = K@eigen_vect",X_prime.shape)
#######################################################################
################ First two principal components #######################
#######################################################################
plt.figure(figsize=(10,7))
plt.subplot(231)
plt.scatter(X_prime[:,0].real,X_prime[:,1].real,c=Temp,s=5)#c=T
plt.xlabel("$ \\mathrm{First\ PC} $")
plt.ylabel("$ \\mathrm{Second\ PC} $")
plt.colorbar(values=Temp[::-1])#,boundaries=list(set(Temp[::-1])))
plt.subplot(232)
plt.scatter(X_prime[:,0].real,X_prime[:,2].real,c=Temp,s=5)#c=T
plt.xlabel("$ \\mathrm{First\ PC} $")
plt.ylabel("$ \\mathrm{Third\ PC} $")
plt.subplot(233)
plt.scatter(X_prime[:,1].real,X_prime[:,2].real,c=Temp,s=5)#c=T
plt.xlabel("$ \\mathrm{Second\ PC} $")
plt.ylabel("$ \\mathrm{Third\ PC} $")
plt.subplot(234)
plt.plot(eigen_vals[:20],"o-")
plt.xlabel("Eigen values")
plt.subplot(235)
total_explained=np.zeros(len(eigen_vals))
for i in range(len(eigen_vals)):
total_explained[i]=sum(eigen_vals[:i].real)
plt.plot(total_explained,"o-",label="Explained variance")
plt.legend()
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X_prime[:,1].real,-X_prime[:,0].real,-X_prime[:,2].real,c=Temp)
ax.set_xlabel("$ P_{2} $")
ax.set_ylabel("$ P_{1} $")
ax.set_zlabel("$ P_{3} $")
plt.show()
#
#
#plt.subplot(131)
#plt.title("First eigen vect")
#plt.scatter(range(len(eigen_vects[:,0])),eigen_vects[:,0],s=5)
#plt.scatter(range(len(eigen_vects_X[:,0])),eigen_vects_X[:,0],s=5,c="r",alpha=0.5,label="X")
#plt.scatter(range(len(eigen_vects_X[:,0])),eigen_vects_Y[:,0],s=5,c="g",alpha=0.5,label="Y")
#plt.legend()
#plt.subplot(132)
#plt.title("Second eigen vect")
#plt.scatter(range(len(eigen_vects[:,0])),eigen_vects[:,1],s=5)
#plt.scatter(range(len(eigen_vects_X[:,0])),eigen_vects_X[:,1],s=5,c="r",alpha=0.5,label="X")
#plt.scatter(range(len(eigen_vects_Y[:,0])),eigen_vects_Y[:,1],s=5,c="g",alpha=0.5,label="Y")
#plt.legend()
#plt.subplot(133)
#plt.title("Third eigen vect")
#plt.scatter(range(len(eigen_vects[:,0])),eigen_vects[:,2],s=5)
#plt.scatter(range(len(eigen_vects_X[:,0])),eigen_vects_X[:,2],s=5,c="r",alpha=0.5,label="X")
#plt.scatter(range(len(eigen_vects_Y[:,0])),eigen_vects_Y[:,2],s=5,c="g",alpha=0.5,label="Y")
#plt.legend()
#plt.show()
#
#plt.subplot(131)
#plt.title("First principal component")
#plt.scatter(Temp ,X_prime[:,0],s=5)
#plt.xlabel("T/J")
#plt.subplot(132)
#plt.title("First principal component X")
#plt.scatter(Temp,X_prime_X[:,0],s=5)
#plt.xlabel("T/J")
#plt.subplot(133)
#plt.title("First principal component Y")
#plt.scatter(Temp,X_prime_Y[:,0],s=5)
#plt.xlabel("T/J")
#plt.show()
#
#
#plt.subplot(131)
#plt.title("First principal component")
#plt.scatter(Temp ,X_prime[:,0],s=5)
#plt.legend()
#plt.xlabel("$ T $")
#plt.subplot(132)
#plt.title("Second principal component")
#plt.scatter(Temp ,X_prime[:,1],s=5)
#plt.legend()
#plt.xlabel("$ T $")
#plt.subplot(133)
#plt.title("SThird principal component")
#plt.scatter(Temp ,X_prime[:,2],s=5)
#plt.legend()
#plt.xlabel("$ T $")
#plt.show()
#
| UTF-8 | Python | false | false | 4,326 | py | 42 | kpca_xy.py | 33 | 0.612344 | 0.582524 | 0 | 140 | 29.892857 | 93 |
Pabloc98/Regresion_Predictiva | 12,171,937,335,131 | c4a54639645db322b7fe42e7e8e0a12b8bc3f9ca | 196d70bc1da67be81805f8f302b0a8af5a01b0e9 | /Process/Models/utils.py | c5a0a4a8d726855b10c0f1134d9be90e096d8bb4 | []
| no_license | https://github.com/Pabloc98/Regresion_Predictiva | 7894e5f798281d20ee53264f6a91449c89b688de | b4ff9dabee86e375fc817e6d707e11bf612a5db9 | refs/heads/main | 2023-05-04T21:30:59.335242 | 2021-05-26T01:17:54 | 2021-05-26T01:17:54 | 370,846,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from sklearn.model_selection import GroupKFold
from sklearn.model_selection import KFold
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.model_selection import ShuffleSplit
seed = 0
def split(tipo="KFold", n_splits=5 ,random_state=seed, n_repeats=10 ,shuffle=True, test_size=None, train_size=None):
"""Esta función realiza la selección del metodo de separación de los datos a partir del tipo de separación que se desea
------------
tipo: string
Nombre del metodo de separación de los datos
n_splits: int
Numero de separaciones, este parametro lo utilizan todos los metodos de división de datos integrados en al funcion
random_state: int
Semilla de aletoriedad. Aplica para: KFold, RepeatedStratifiedKFold, ShuffleSplit
n_repeats: int
Repeticiones para el metodo de RepeatedStratifiedKFold
shuffle: bool
True o False para indicar si se desea que la seleccion sea aleatoria. Aplica para: KFold
test_size: int o float
Si se ingresa un int se toma como la cantidad de registros que debe tener el conjunto de test, si es un float se parte por la cantidad registros correspondientes al porcentaje
train_size: int o float
Si se ingresa un int se toma como la cantidad de registros que debe tener el conjunto de train, si es un float se parte por la cantidad registros correspondientes al porcentaje
Returns
------------
cv
Modelo de selección de sklearn
"""
if tipo == "KFold":
cv = KFold(n_splits=n_splits, shuffle=shuffle, random_state=random_state)
if tipo == "GroupKFold":
cv = GroupKFold(n_splits=n_splits)
if tipo == "RepeatedStratifiedKFold":
cv = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=n_repeats, random_state=random_state)
if tipo == "ShuffleSplit":
cv = ShuffleSplit(n_splits=n_splits, test_size=test_size, train_size=train_size, random_state=random_state)
return cv
| UTF-8 | Python | false | false | 1,906 | py | 27 | utils.py | 21 | 0.749342 | 0.747235 | 0 | 39 | 47.666667 | 180 |
janiszewskibartlomiej/Python_Code_Me_Gda | 5,832,565,617,375 | 6ad04c84c93960a898cd14d144510b46a5cc88bc | f8ffa8ff257266df3de9d20d95b291e393f88434 | /Python from scratch/Warsztaty/Warsztaty01/info o mnie na Linked/linkedinWer3.py | fb6d1bae10d910d0af76c6872414c08a9b1418d4 | []
| no_license | https://github.com/janiszewskibartlomiej/Python_Code_Me_Gda | c0583c068ef08b6130398ddf93c3a3d1a843b487 | 7568de2a9acf80bab1429bb55bafd89daad9b729 | refs/heads/master | 2020-03-30T05:06:26.757033 | 2020-03-02T08:53:28 | 2020-03-02T08:53:28 | 150,781,356 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | obecnie = {'Python': 'SQL', 'w szkole CODE:ME': 'in infoShare Academy'}
staz = 'FNX Group'
k = 'Tester oprogramowania'
c = 'ISTQB FL'
while True:
dzien = input('Wpisz dzień: ')
miesiac = input('Wpisz miesiąc: ')
rok = input('Wpisz rok: ')
try:
liczba_z_dzien = int(dzien)
liczba_z_miesiac = int(miesiac)
liczba_z_rok = int(rok)
break
except ValueError:
print('Wprowadzone wartość nie są liczbami całkowitymi, proszę wpisać je ponownie!')
if liczba_z_dzien <= 30 and liczba_z_miesiac <= 11 and liczba_z_rok <= 2018:
print('Ukończyłem kurs: {}. Posiadam certyfikat: {}.\n'
'\nObecnie odbywam staż w {}.'.format(k, c, staz), end='\n')
if liczba_z_dzien <= 31 and liczba_z_miesiac <= 10 and liczba_z_rok <= 2018:
print('\nUczę się języka {}'.format(' '.join(obecnie)))
else:
print('\nUkończyłem, również kurs: {}.'.format(' '.join(obecnie)))
else:
print('Odbyłem staż w FNX Group. Ukończyłem m.in. kurs: {}, {}. '
'\nPosiadam certyfikat: {}.'
'\n\nJestem otwarty na nowe wyzwania :)'.format(' '.join(obecnie), k, c))
if liczba_z_dzien >= 14 and liczba_z_miesiac >= 11 and liczba_z_rok >= 2018:
print('\nI\'m lerning', obecnie['Python'], obecnie['w szkole CODE:ME'])
print('\nDużą radość sprawia mi, jak kod zacznie działać ! :}')
znam = ['\nProgramy które znam to: Python, Pycharm, Git, Selenium IDE, Katalon Recorder,'
'\nJira, Enterprise Architect, Photoshop, MS FrondPage, Slack, Skitch, Podio']
while True:
pytanie = input('\nCzy chcesz wiedzieć jakie znam programy ? [napisz Tak lub Nie]: ')
if pytanie == 'tak' or pytanie == 'Tak':
for programy in znam:
print(programy)
break
while True:
meetup = input('\nCzy chcesz wiedzieć jaki jestem? [napisz Tak lub Nie]:')
if meetup == 'tak' or meetup == 'Tak':
jestem = ('\nSpotkajmy się i porozmawiajmy, to najlepszy sposób aby potwierdzić że jestem:\n'
'Komunikatywny, Obowiązkowy, Punktualny, Pogodny,\n'
'posiadam zdolności Analityczne,'
' Dyplomatyczne oraz lubię pracować w Team\'ie.')
print(jestem)
break
moge_pracowac = 'Gdańsku, Gdyni, Sopocie i okolicach Trójmiasta.'
print('\nZe względu na moją elastyczność mogę pracować w: {}'
.format(moge_pracowac))
| UTF-8 | Python | false | false | 2,411 | py | 435 | linkedinWer3.py | 349 | 0.626904 | 0.616751 | 0 | 56 | 41.214286 | 99 |
cagdas9696/casestudy | 6,210,522,742,981 | 44c90084320816fbbe23a1a5f158a7825b31c541 | 57e4f917a2b0006fa821ad35c632386aec53f19b | /label_control.py | 8dd50cb5e3f9a2ff97e9cd1e5875571eaf8f7b17 | []
| no_license | https://github.com/cagdas9696/casestudy | 464d7167d20081c534a64fa79eb44520dd9033f4 | 7475e99916431ca485736dd2643e273e35ad9f7d | refs/heads/master | 2023-02-02T11:07:04.354044 | 2020-12-23T17:46:51 | 2020-12-23T17:46:51 | 323,644,301 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: can
"""
import os
import cv2
import argparse
FLAGS = None
if __name__ == '__main__':
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
parser.add_argument('folder', type=str, default='', help='path to folder that contains images and labels')
parser.add_argument('names', type=str, help='path to label names file')
FLAGS = parser.parse_args()
folder = FLAGS.folder
if not folder.endswith('/'):
folder = folder + '/'
control_folder = folder+'control/'
if not os.path.exists(control_folder):
os.makedirs(control_folder)
names_path = FLAGS.names
with open(names_path, 'r') as f:
label_names = [line.replace('\n','') for line in f.readlines()]
image_list = os.listdir(folder+'images/')
image_without_label = []
for image in image_list:
image_name = image.split('.png')[0]
label_path = folder+'labels/'+image_name+'.txt'
print(label_path)
if os.path.exists(label_path):
image = cv2.imread(folder+'images/'+image)
height,width,_ = image.shape
with open(label_path, 'r') as f:
lines = f.readlines()
for line in lines:
bbox = line.split(' ')
if float(bbox[1])<0 or float(bbox[2])<0 or float(bbox[1])>1 or float(bbox[2])>1 or float(bbox[3])<0 or float(bbox[4])<0:
lines = 'del'
break
klas = bbox[0]
x0 = int(width * float(bbox[1]))
y0 = int(height * float(bbox[2]))
w = int(width * float(bbox[3]))
h = int(height * float(bbox[4]))
x1 = int(x0 - w/2)
y1 = int(y0 - h/2)
thickness = 1+int(w/50.0)
cv2.rectangle(image, (x1,y1),(x1 + w, y1 + h),(0,255,0),thickness)
cv2.putText(image,
label_names[int(klas)],
(x1, y1 - 1), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
[0, 0, 255], 2)
cv2.imwrite(control_folder+image_name+'.png', image)
else:
if not os.path.exists(folder+'unlabeled'):
os.makedirs(folder+'unlabeled')
os.rename(folder+'images/'+ image_name+'.png', folder+'unlabeled/'+ image_name+'.png')
| UTF-8 | Python | false | false | 2,447 | py | 4,413 | label_control.py | 14 | 0.515325 | 0.491622 | 0 | 72 | 32.986111 | 136 |
chenkuo0716/Text-similarity-detection-system | 11,295,764,006,292 | 560ba8277e64c3ddadf30ffb9d2f82606889c459 | ec014345f5ef6191bb349352aef1701e2ed40abd | /english.py | e3f9793191a06d7fa8ab124f2ce776313a15f48a | []
| no_license | https://github.com/chenkuo0716/Text-similarity-detection-system | 9d6aa067078cea174250ed140c4e13b8e5d1fded | 45bfd79ef1b6f9a40c6b35faf362637d3d9b0f61 | refs/heads/master | 2021-01-14T18:24:28.452569 | 2020-02-24T13:46:18 | 2020-02-24T13:46:18 | 242,711,032 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
from collections import defaultdict
from gensim import models, similarities, corpora
def English(documents):
# Log
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# Reference text file processing
texts = [[word for word in document.lower().split()] for document in documents[1:]]
print(texts)
# Statistically restricted word frequency
frequency = defaultdict(int)
for text in texts:
for token in text:
frequency[token] += 1
texts1 = [[token for token in text if frequency[token] > 1] for text in texts]
print(texts1)
# Build a corpus
dictionary = corpora.Dictionary(texts1)
print(dictionary.token2id)
# Doc2bow the dictionary to get a new corpus
corpus = [dictionary.doc2bow(text) for text in texts1]
# Building a TF-IDF model
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
for doc in corpus_tfidf:
print(doc)
# Depth-first search
print(tfidf.dfs)
print(tfidf.idfs)
# Training the Lsi model
lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2)
lsi.print_topics(2)
# Map documents into two-dimensional topic space with Lsi model
corpus_lsi = lsi[corpus_tfidf]
for doc in corpus_lsi:
print(doc)
# Calculate sparse matrix similarity
index = similarities.MatrixSimilarity(lsi[corpus])
# Object text file processing
query = documents[0]
print(query)
# doc2bow builds a bag of words model, turning the file into a sparse vector
query_bow = dictionary.doc2bow(query.lower().split())
print(query_bow)
# Map documents into 2D topic space with Lsi model
query_lsi = lsi[query_bow]
print(query_lsi)
# Calculate cosine similarity
sims = index[query_lsi]
sims = list(sims)
return sims
| UTF-8 | Python | false | false | 1,930 | py | 3 | english.py | 3 | 0.676166 | 0.666321 | 0 | 68 | 27.382353 | 95 |
pythias/sublime-insertdatestring | 8,907,762,202,849 | 608d1305206070284d16e73e149d601d4ec212af | 24e9cce550e0feb2e831bc44ac173b6514d7ff54 | /tests/test_plugin_load.py | 447407e63285899706bf773f67f21b67b18f0351 | [
"MIT"
]
| permissive | https://github.com/pythias/sublime-insertdatestring | a633b6c00407fb19db3c3802963a0974dae8bd11 | 8aae9be80ed351fe10f6ff0994a6f5f6c0aa232f | refs/heads/master | 2021-05-27T12:02:56.063134 | 2020-04-09T05:12:40 | 2020-04-09T05:12:40 | 254,266,893 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import time
import sublime
from unittesting import DeferrableTestCase
class TestPluginLoad(DeferrableTestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
self.settings = sublime.load_settings('InsertDateString.sublime-settings')
def tearDown(self):
if self.view:
self.view.set_scratch(True)
self.view.window().run_command("close_file")
def testPluginIsLoaded(self):
yield 1000
self.view.window().focus_view(self.view)
self.view.run_command('insert_date_string', 'date')
yield 1000
date = time.strftime(self.settings.get("formatDate"))
self.assertIsNotNone(self.view.find(date, 0))
| UTF-8 | Python | false | false | 714 | py | 8 | test_plugin_load.py | 2 | 0.666667 | 0.654062 | 0 | 21 | 33 | 82 |
Jeroen-Weber/HetGroteTMspel | 18,820,546,722,415 | 993f9e0c76273da98b3a3d447ca2e6f562775929 | 17edbd22036f67dbce7e6b65ba230be80925617f | /Hoofdprogamma.py | 9ce914f84b00987fdb6c6697fdc7ad27b90eb33b | []
| no_license | https://github.com/Jeroen-Weber/HetGroteTMspel | 18afa6551ab92bb319c8e83712ecc1764d7511aa | eda483050d1d2a9d37cf671062904e08ffc7054c | refs/heads/master | 2020-09-26T14:55:43.451877 | 2020-03-09T14:22:42 | 2020-03-09T14:22:42 | 226,277,976 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | ######################
# HET GROTE KUT SPEL #
# Copy Jeroen Weber #
######################
# Project op Github te vinden op: https://github.com/Jeroen-Weber/HetGroteTMspel
# -*- coding: utf-8 -*-
# een aantal imports om bepaalde functie's en variabele te laten werken
import webbrowser
import time
from colorama import Fore
# een leuk kleurtje voor de STOP zin
kleur = "BLUE"
# ERRORS en Prints alvast vast leggen om onnodige prints te voorkomen en moeite te besparen.
spel_STOP = "Okay, bedankt voor het spelen! Het spelletje is gedaan (c) Jeroen Weber Student @ Thomas More"
jammer = "Hahah dat is nou eens jammerv"
goed_gedaan = "Dat heb je goed gedaan! Het spel is trots op je! Jahoor."
extra_uitleg = "TER INFO: Alles werkt om het spel te starten, behalve nee of iets waar dat op lijkt."
pedo_zin = "Pas wel op he, met minder jarige meisjes, kan je problemen mee krijgen. Ze doen er soms moeilijk om , maar je weet hoe dichter bij de 0.. hoe strakker om de lul"
leeftijds_verschil = "Er zit wel groot leeftijdsverschil tussen jullie. Maar boeie ruud"
verkracht_vriendin = "Weet je zeker dat je niet verkracht word door je vriendin? :P"
ja_gedaan = "Dat is wel lekker hoor, zeker wel gemist? Heb je het wel een beetje goed opgeruimd? Anders ziet je mama dat ;p en dat willen we niet!"
# FUNCTIE Tinder
def tinder():
bestand_tinder = open("tinder.txt")
print(bestand_tinder.read())
bestand_tinder.close()
# einde Functie Tinder
# FUNCTIE: Pedochecker
def pedochecker():
if int(leeftijd) >= 18 and leeftijd_meisje <= 16:
print(pedo_zin)
print("https://nl.wikipedia.org/wiki/Verkrachting")
elif int(leeftijd) - leeftijd_meisje >= 5 or leeftijd_meisje - int(leeftijd) >= 5:
print(leeftijds_verschil)
elif int(leeftijd) < 18 <= leeftijd_meisje:
print(verkracht_vriendin)
# einde funcie pedochecker
# FUNCTIE: vriendje/vriendin
def vriendin_vriendje():
"""Dit checkt of je een vriendje of een vriendin hebt, nagelang je geslacht."""
if jongen_meisje == "jongen":
print("vriendinnen")
if jongen_meisje == "meisje":
print("vriendjes")
print()
# Einde Functie vriendje/vriendin
# FUNCTIE: No Not November
def nnn():
"""Progamma van No-Nut-November, deze checkt of je dat hebt overleefd, en hoe leuk je de challange vond. En print dan al je antwoorden"""
print(jammer)
NNN = input(
"Hahaha, wat een maagd dat je bent, heb je nog nooit mogen prikken.. Heb je no not november overleeft? ").strip()
print("")
if NNN == "ja":
print(goed_gedaan)
gedaan = input("Heb je het in december al gedaan? ").strip()
print("")
if gedaan == "ja":
print(ja_gedaan)
else:
lekker = input("Gast slecht dat je bent, was het wel lekker? ").strip()
print("")
if lekker == "ja":
print('Lekker man , genieten is dat hoor. Heb je leuke video gevonden om jezelf te helpen? ')
videos = input("Wil je een lijst hebben met goede website's in je mail? ").strip()
if videos == "ja":
print("Helaas dat kan ik nog niet progammeren.")
print(Fore.BLUE + spel_STOP)
if lekker == "nee":
print("Hier heb je een aantal super goede website's ")
# open bestand met alle porno site's en write nieuwe en user er 1 weet
pornsites = open('pornsites.txt', 'r+')
print(pornsites.read())
print("Weet je misschien nog een leuke site? jij viezerik! Kan je hieronder invullen..")
site = input("Naam van de website: ")
pornsites.write(site + "\n")
pornsites.close()
time.sleep(2)
if site == "nee":
print("SAAAAAAAAAAIIII")
else:
print("Bedankt, viezerik. Het is aan het lijstje toegevoegd.")
return Fore.BLUE + spel_STOP
# EINDE Functie NNN
# De titel en de spelregels laden in een apart bestand om overbodige prints te voorkomen.
bestand = open("Hoofdprogamma_OPENING.txt")
print(bestand.read())
bestand.close()
# spatie
print("")
# vragen of de gebruiker klaar is om het spel te starten.
print(extra_uitleg)
spel_begin = input("Heb je de spelregels gelezen en ben je klaar om met het spel te beginnen? ")
# de input verlagen naar kleine letters
spel_begin = spel_begin.lower()
# spatie
print("")
# als de gebruiker nee zegt, of iets wat daar op lijkt. stopt het spel, en krijgt ook een video te zien over bij je moeder huilen :P
if "nee" in spel_begin or "nop" in spel_begin or "nehh" in spel_begin or "neee" in spel_begin or "ne" in spel_begin:
print("Okay, fijn dat je het aangeeft. MIETJE. Ga lekker bij je mama huilen.")
stop = 1
time.sleep(1)
print("https://www.youtube.com/watch?v=9cRiNplRH2g")
webbrowser.open('https://www.youtube.com/watch?v=9cRiNplRH2g')
# als de gebruiker iets anders ingeeft. begint het spel.
else:
# nog even checken of de input niet belachelijk lang is.
if len(spel_begin) > 3:
print(
"Vul alsjeblieft bij de volgende vragen iets fatsoenlijks in, het spel is niet gedaan maar niet te enthousiast doen he :P")
# standaard informatie vragen zoals naam en leeftijd
naam = input("Simpele vraag, om te beginnen: Wat is je voor en achternaam? ").strip()
split = naam.split(" ", 1)
voornaam = split[0]
leeftijd = input("Wat is je leeftijd, " + voornaam + "? ").strip()
# eerst, kijken of je wel een int hebt ingevuld bij de leeftijd en een str bij de naam
if naam.isdigit():
print("Gast, sinds wanneer heb je als een naam een getal? SPEEL NORMAAL!")
naam = input("Wat is je echte naam? ").strip()
if not leeftijd.isdigit():
print("Wow wacht even... heb je nu dat fout ingevuld, je leeftijd?! kom op zeg.. HOMO")
leeftijd = int(input("Hoeveel jaar ben je echt? "))
# vervolgens, kijken dat je niet te jong of te oud bent. zie spelregels.
if int(leeftijd) < 15:
print("Sorry, je bent te jong om mee te doen met dit spel.")
stop = 1
if int(leeftijd) > 100:
print("gast, klootzaak. vul even je echte leeftijd in")
stop = 0
if int(leeftijd) > 25:
print("HAHAHA gast, je bent ", leeftijd, "jaar. Ga wat nuttigs doen in je leven.")
print("Leuk gedicht: 2 neven in een pizza oven!")
stop = 1
print(Fore.BLUE + spel_STOP)
else:
stop = 0
# nog even vragen na het geslacht
jongen_meisje = input(
"Ben je een jongen, meisje, mongooltje, autist of wil je het niet vertellen? (mietje) ").strip()
# kijken welk geslacht de speler heeft, en een passend bericht bij geven ALS stop niet 1 is. zie leeftijd checker.
if "mongool" in jongen_meisje:
print("Hahahahaha , jajaja even de grapjas uithangen in mijn game he, jajajaaj. We weten allebei dat",
jongen_meisje, "geen geslacht is. Dus even normaal doen aub")
time.sleep(2)
webbrowser.open('https://pbs.twimg.com/profile_images/1732374435/2dv1icy_400x400.png')
# spatie
print("")
# als je autist invuld
if "autist" in jongen_meisje:
print(
"Ik denk dat je dan even je mama erbij moet halen, dit is een spelletje voor MENSEN MET HERSENENEN!!!!!")
time.sleep(1)
print(Fore.BLUE + spel_STOP)
stop = 1
# als je niet wilt vertellen
if "vertellen" in jongen_meisje:
print("Wat een godverdomme mietje ben jij nou weer. wees een een man en zegt wat je tussen je benen hebt!")
time.sleep(1)
print("Okay, vooruit je mag weer verder doen van mij. iedereen verdiend een tweede kans, toch?!")
stop = 0
# spatie
print("")
if jongen_meisje == "jongen":
print("hoeveel scharrel(s) heeft '", voornaam, "' al gehad? ")
geef_in_aantal = int(input("...... Eerlijk zijn, hoeveel (¬‿¬)? "))
if geef_in_aantal > 4:
print("Sow! PLAYEEEERRRR SPOTTED... ¬_¬")
elif jongen_meisje == "meisje":
print("Welkom", naam, ", hoeveel vriendjes heb je al gehad? ")
geef_in_aantal = int(input("...... Eerlijk zijn, hoeveel (¬‿¬)? "))
if geef_in_aantal > 4:
print("Sow! PLAYEEEERRRR SPOTTED... ¬_¬")
# extra controle
if geef_in_aantal > 4:
print("Sow! PLAYEEEERRRR SPOTTED... ¬_¬")
# spatie
print("")
# kijken of de speler geen stop = 1 heeft gekregen, want dan is het spel gestopt, en mag onderstaand niet meer worden uitgevoerd
if not stop == 1:
# kijken of de speler een vriendin heeft op dit moment.
momenteel = input("Dus heb je momenteel een scharrel? ")
momenteel = momenteel.lower()
# als je momenteel vriendin hebt dan..
if "ja" in momenteel:
# informatie over de vriendin
naam_vriendin = input("Wat is de naam van je vriendin? ")
print(naam_vriendin, ", dat is een schattige naam. ")
leeftijd_meisje = int(input("Hoe oud is je vriendin? "))
# de PEDO-CHECKER: zie functie bovenaan progamma
pedochecker()
# als je momenteel geen vriendin hebt RUN de functie tinder
else:
tinder()
# spatie
print("")
# extra bericht als eerste vriendin is. ( geef_in_aantal error weet ik = normaal )
if momenteel == "ja" and geef_in_aantal == 1:
print("Cute, is dit je eerste relatie? wat schattig. URGH")
print("")
# extra bericht als je ouder bent als 21 en dit je eerste vriendin zou zijn.
if momenteel == "ja" and geef_in_aantal == 1 and int(leeftijd) > 20:
print("Godverdomme is dit je eerste vriendin? Wtf hahahaha werd tijd jonguh ")
# seks checker voor de volgende vragen
seks = input("Heb je ooit seks gehad? ").lower()
# kijken of seks goed is ingevuld
if not seks == "nee" and not seks == "ja":
print("vul alsjeblieft gewoon even ja of nee in..")
seks = input("Dus.. heb je ooit seks gehad? ").lower()
# als je nog geen vriendinnetjes hebt gehad
if geef_in_aantal == "0":
# als je nog geen seks hebt gehad
if seks != "nee":
print("Owh wat een gelukzak dat je bent! Was ze blind dan of?")
# als je wel seks hebt gehad, of iets waar dat op lijkt
else:
print(nnn())
# als je geen vriendinnetjes hebt gehad dan run je dit
else:
# checken wat antwoord was op de seks vraag
if "nee" in spel_begin or "nop" in spel_begin or "nehh" in spel_begin or "neee" in spel_begin or "ne" in seks:
print(nnn())
# vragen als het antwoord ja (of iets anders) was op de seks vraag
else:
condoom = input("Dat is wel erg lekker , wel met condoom hoop ik voor je? ").strip().lower()
print("")
# als je condoom hebt gebruikt
if "ja" in spel_begin or "jha" in spel_begin in condoom:
print("Goedzo! geen kindjes voor jou! Knan je nog even genieten van je luxe leventje!")
print(Fore.BLUE + spel_STOP)
# als er geen condoom word gebruikt...
else:
print("Sow dus je wilt vader worden? yes! mini", naam, "tjes!")
# vragen of de pil word gebruikt
pil = input("Gebruik je vriendin de pil? ")
if "ja" in spel_begin or "jha" in spel_begin in pil:
print("Gelukkig, dan ga je toch geen kinderen krijgen :) , of wil je wel graag kinderen? neeeh")
# leeftijd checker, kijken of kinderen goede leeftijd is
if int(leeftijd) >= 21:
print(
"Opzich kinderen zou wel kunnen, je bent ouder dan 21 opzich mooie leeftijd. NEUKEN!!!!!!!")
elif int(leeftijd) <= 16:
print("Wow, je bent jonger dan 16, niet echt slim om nu kinderen te nemen... beeeeetje vroeg")
elif 21 > int(leeftijd) > 16:
print(
"Hmmm ja geen idee.. die leeftijd die je hebt ingegeven in het systeem. geen idee of je kinderen op die leeftijd wilt.")
print(Fore.BLUE + spel_STOP)
else:
MJ = input("Word het een jongetje of een meisje ;p? m/j ").strip().lower()
if MJ == "j":
print("Yes kan je samen naar PSV gaan kijken in eindhoven")
print(Fore.BLUE + spel_STOP)
elif MJ == "m":
print("Meisje is ook leuk, niet?")
print(Fore.BLUE + spel_STOP)
else:
print("Wat voor raar monster ga jij maken?")
print(Fore.BLUE + spel_STOP)
| UTF-8 | Python | false | false | 13,338 | py | 5 | Hoofdprogamma.py | 2 | 0.589012 | 0.582933 | 0 | 325 | 38.996923 | 173 |
subhash-pujari/PubSearchApp | 249,108,124,834 | b35b82de2102ffbe7ac1335f97f01f71f828b44a | 84f594088af97a757f81bf749fbdad088e5c1bdf | /dataAnalysis/commTopCit.py | 26e5c79f5687ab939110fcb7fe65a70b6fd5042d | []
| no_license | https://github.com/subhash-pujari/PubSearchApp | 255ac269e5ed1062155604f6be039903dcef35c0 | 84c1856863d3aca9703eaac297d45be47402bfba | refs/heads/master | 2020-05-18T10:54:20.882481 | 2014-05-27T15:30:15 | 2014-05-27T15:30:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
This script is to get the top citation publication in a community.
'''
import database
from operator import itemgetter
dataDir = "../../PubDataSet/"
commFile = "nodeComm.tsv"
def main():
db = database.DatabaseHandler()
# create a dict of comm with pub and cit count
print "hello"
commDict = dict()
fileR = open(dataDir + commFile)
for line in fileR:
line = line.replace("\n", "")
tokens = line.split("\t")
_id = tokens[0]
comm = tokens[1]
if comm not in commDict:
commDict[comm] = list()
else:
citCount = db.getCitCount(_id)
title = db.getTitle(_id)
if title is None or citCount is None:
continue
commDict[comm].append((title, citCount))
fileW = open(dataDir + "topPub.tsv", "w")
for comm in commDict:
pubList = commDict[comm]
pubList = sorted(pubList,key=itemgetter(1))
if len(pubList) > 10:
for i in range(10):
item = pubList[(i+1)*-1]
print comm +">>"+str(item)
fileW.write(comm+"\t"+str(item[0])+">>"+str(item[1]) + "\n")
if __name__ == "__main__":
main()
| UTF-8 | Python | false | false | 1,048 | py | 10 | commTopCit.py | 9 | 0.626908 | 0.616412 | 0 | 54 | 18.407407 | 67 |
sumedhbala/catalog | 4,131,758,568,113 | 831eafb1e86d0cdd8fe794f4aeb2652dc4618a14 | b8545dfa0cbf29a0174ab9deb5677c78bf9ae0bd | /app/models/models.py | 5c9ccca2301e163f64eb3a1645a3d1410e1b0343 | [
"MIT"
]
| permissive | https://github.com/sumedhbala/catalog | e79b91b7454f5a7990ce47bf0f7ccbd6948901af | ab969ccf39ce343ba0172e92221f56c18478f743 | refs/heads/master | 2020-03-28T16:16:16.859689 | 2018-12-05T09:21:33 | 2018-12-05T09:21:33 | 148,676,359 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from app import db, login
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
class Catalog(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
def __init__(self, name):
self.name = name
class Items(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
description = db.Column(db.Text)
catalog_id = db.Column(db.Integer, db.ForeignKey("catalog.id"))
catalog = db.relationship("Catalog")
def __init__(self, name, description, catalog_id):
self.name = name
self.description = description
self.catalog_id = catalog_id
def as_dict(self):
return {"id": self.id,
"name": self.name,
"description":self.description,
"catalog_id":self.catalog_id}
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
email = db.Column(db.String(80))
password_hash = db.Column(db.String(128))
def __init__(self, name, email, password):
self.name = name
self.email = email
self.set_password(password)
def __repr__(self):
return "<User {}>".format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
@login.user_loader
def load_user(id):
return User.query.get(int(id))
| UTF-8 | Python | false | false | 1,624 | py | 14 | models.py | 8 | 0.636084 | 0.62931 | 0 | 56 | 28 | 73 |
yarko/django | 11,261,404,292,016 | d62a415b06c24dbb4517bd74eda00de8469a3ef5 | 18953e688e5ad09880e10d03fcd95a09e423cae9 | /tests/regressiontests/localflavor/mk/models.py | 244f396b52a362f47f2125355a4f7268f4b9d926 | [
"BSD-3-Clause"
]
| permissive | https://github.com/yarko/django | 64d5604ea1c2e6fdc0621310f9e22919a5abe9eb | 90b6240c8753ece3e52cafc37e1088b0646b843f | refs/heads/djangocon2011-sec | 2021-01-24T04:13:07.209945 | 2011-09-19T16:23:35 | 2011-09-19T16:23:35 | 2,358,407 | 3 | 1 | NOASSERTION | true | 2019-11-18T04:24:08 | 2011-09-09T22:05:56 | 2014-10-15T12:52:29 | 2011-09-19T16:23:45 | 40,851 | 5 | 0 | 1 | Python | false | false | from django.db import models
from django.contrib.localflavor.mk.models import (
MKIdentityCardNumberField, MKMunicipalityField, UMCNField)
class MKPerson(models.Model):
first_name = models.CharField(max_length = 20)
last_name = models.CharField(max_length = 20)
umcn = UMCNField()
id_number = MKIdentityCardNumberField()
municipality = MKMunicipalityField(blank = True)
municipality_req = MKMunicipalityField(blank = False)
class Meta:
app_label = 'localflavor'
| UTF-8 | Python | false | false | 505 | py | 74 | models.py | 54 | 0.732673 | 0.724752 | 0 | 14 | 35.071429 | 62 |
GamesDoneQuick/donation-tracker | 11,081,015,638,207 | 42d0aeada0d61e56b4bc0f3843ee5c9da54e85ea | 7cdcd244cb576f9bb689d6fef9c3428d67364274 | /tracker/models/prize.py | 6d5d2f471a31960171fabcf822bdb0bfdbf6c22e | [
"Apache-2.0"
]
| permissive | https://github.com/GamesDoneQuick/donation-tracker | 9728579531961eb556d7acd4564c6fe4deaffbff | 4d231bae7d00ee990ca9086400d926da59b0598d | refs/heads/master | 2023-08-31T21:37:41.015548 | 2023-08-22T22:03:47 | 2023-08-22T22:03:47 | 44,652,980 | 48 | 39 | Apache-2.0 | false | 2023-09-11T14:10:57 | 2015-10-21T04:38:00 | 2023-09-09T23:14:01 | 2023-09-11T14:10:57 | 7,439 | 44 | 32 | 15 | Python | false | false | import datetime
from decimal import Decimal
import pytz
from django.contrib.auth.models import User
from django.contrib.sites import shortcuts as sites
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.db.models import Q, Sum
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django.urls import reverse
from tracker import settings, util
from tracker.models import Donation, Event, SpeedRun
from tracker.validators import nonzero, positive
from .fields import TimestampField
from .util import LatestEvent
__all__ = [
'Prize',
'PrizeKey',
'PrizeWinner',
'PrizeCategory',
'DonorPrizeEntry',
]
USER_MODEL_NAME = getattr(settings, 'AUTH_USER_MODEL', User)
class PrizeManager(models.Manager):
def get_by_natural_key(self, name, event):
return self.get(name=name, event=Event.objects.get_by_natural_key(*event))
class Prize(models.Model):
objects = PrizeManager()
name = models.CharField(max_length=64)
category = models.ForeignKey(
'PrizeCategory', on_delete=models.PROTECT, null=True, blank=True
)
image = models.URLField(max_length=1024, blank=True)
altimage = models.URLField(
max_length=1024,
blank=True,
verbose_name='Alternate Image',
help_text='A second image to display in situations where the default image is not appropriate (tight spaces, stream, etc...)',
)
imagefile = models.FileField(upload_to='prizes', null=True, blank=True)
description = models.TextField(max_length=1024, blank=True)
shortdescription = models.TextField(
max_length=256,
blank=True,
verbose_name='Short Description',
help_text='Alternative description text to display in tight spaces',
)
extrainfo = models.TextField(max_length=1024, blank=True)
estimatedvalue = models.DecimalField(
decimal_places=2,
max_digits=20,
null=True,
blank=True,
verbose_name='Estimated Value',
validators=[positive, nonzero],
)
minimumbid = models.DecimalField(
decimal_places=2,
max_digits=20,
default=Decimal('5.00'),
verbose_name='Minimum Bid',
validators=[positive, nonzero],
)
maximumbid = models.DecimalField(
decimal_places=2,
max_digits=20,
null=True,
blank=True,
default=Decimal('5.00'),
verbose_name='Maximum Bid',
validators=[positive, nonzero],
)
sumdonations = models.BooleanField(default=False, verbose_name='Sum Donations')
randomdraw = models.BooleanField(default=True, verbose_name='Random Draw')
event = models.ForeignKey('Event', on_delete=models.PROTECT, default=LatestEvent)
startrun = models.ForeignKey(
'SpeedRun',
on_delete=models.PROTECT,
related_name='prize_start',
null=True,
blank=True,
verbose_name='Start Run',
)
prev_run = models.ForeignKey(
'SpeedRun',
on_delete=models.SET_NULL,
related_name='+',
null=True,
blank=True,
serialize=False,
editable=False,
)
endrun = models.ForeignKey(
'SpeedRun',
on_delete=models.PROTECT,
related_name='prize_end',
null=True,
blank=True,
verbose_name='End Run',
)
next_run = models.ForeignKey(
'SpeedRun',
on_delete=models.SET_NULL,
related_name='+',
null=True,
blank=True,
serialize=False,
editable=False,
)
starttime = models.DateTimeField(null=True, blank=True, verbose_name='Start Time')
endtime = models.DateTimeField(null=True, blank=True, verbose_name='End Time')
maxwinners = models.IntegerField(
default=1,
verbose_name='Max Winners',
validators=[positive, nonzero],
blank=False,
null=False,
)
maxmultiwin = models.IntegerField(
default=1,
verbose_name='Max Wins per Donor',
validators=[positive, nonzero],
blank=False,
null=False,
)
provider = models.CharField(
max_length=64,
blank=True,
help_text='Name of the person who provided the prize to the event',
)
handler = models.ForeignKey(
USER_MODEL_NAME,
null=True,
help_text='User account responsible for prize shipping',
on_delete=models.PROTECT,
)
acceptemailsent = models.BooleanField(
default=False, verbose_name='Accept/Deny Email Sent'
)
creator = models.CharField(
max_length=64, blank=True, null=True, verbose_name='Creator'
)
creatoremail = models.EmailField(
max_length=128, blank=True, null=True, verbose_name='Creator Email'
)
creatorwebsite = models.CharField(
max_length=128, blank=True, null=True, verbose_name='Creator Website'
)
state = models.CharField(
max_length=32,
choices=(
('PENDING', 'Pending'),
('ACCEPTED', 'Accepted'),
('DENIED', 'Denied'),
('FLAGGED', 'Flagged'),
),
default='PENDING',
)
requiresshipping = models.BooleanField(
default=True, verbose_name='Requires Postal Shipping'
)
reviewnotes = models.TextField(
max_length=1024,
null=False,
blank=True,
verbose_name='Review Notes',
help_text='Notes for the contributor (for example, why a particular prize was denied)',
)
custom_country_filter = models.BooleanField(
default=False,
verbose_name='Use Custom Country Filter',
help_text='If checked, use a different country filter than that of the event.',
)
allowed_prize_countries = models.ManyToManyField(
'Country',
blank=True,
verbose_name='Prize Countries',
help_text='List of countries whose residents are allowed to receive prizes (leave blank to allow all countries)',
)
disallowed_prize_regions = models.ManyToManyField(
'CountryRegion',
blank=True,
verbose_name='Disallowed Regions',
help_text='A blacklist of regions within allowed countries that are not allowed for drawings (e.g. Quebec in Canada)',
)
key_code = models.BooleanField(
default=False,
help_text='If true, this prize is a key code of some kind rather '
'than a physical prize. Disables multiwin and locks max '
'winners to the number of keys available.',
)
class Meta:
app_label = 'tracker'
ordering = ['event__datetime', 'startrun__starttime', 'starttime', 'name']
unique_together = ('name', 'event')
def natural_key(self):
return self.name, self.event.natural_key()
def get_absolute_url(self):
return reverse('tracker:prize', args=(self.id,))
def __str__(self):
return str(self.name)
def clean(self, winner=None):
if not settings.TRACKER_SWEEPSTAKES_URL:
raise ValidationError(
'Cannot create prizes without a TRACKER_SWEEPSTAKES_URL in settings'
)
if self.maxmultiwin > 1 and self.category is not None:
raise ValidationError(
{
'maxmultiwin': 'A donor may not win more than one prize of any category, so setting a prize '
'to have multiple wins per single donor with a non-null category is incompatible.'
}
)
if (not self.startrun) != (not self.endrun):
raise ValidationError(
{'startrun': 'Must have both Start Run and End Run set, or neither.'}
)
if self.startrun and self.event != self.startrun.event:
raise ValidationError(
{'event': 'Prize Event must be the same as Start Run Event'}
)
if self.endrun and self.event != self.endrun.event:
raise ValidationError(
{'event': 'Prize Event must be the same as End Run Event'}
)
if self.startrun and self.startrun.starttime > self.endrun.starttime:
raise ValidationError(
{'startrun': 'Start Run must begin sooner than End Run'}
)
if (not self.starttime) != (not self.endtime):
raise ValidationError(
{'starttime': 'Must have both Start Time and End Time set, or neither'}
)
if self.starttime and self.starttime > self.endtime:
raise ValidationError(
{'starttime': 'Prize Start Time must be later than End Time'}
)
if self.startrun and self.starttime:
raise ValidationError(
{'starttime': 'Cannot have both Start/End Run and Start/End Time set'}
)
def save(self, *args, **kwargs):
if not settings.TRACKER_SWEEPSTAKES_URL:
raise ImproperlyConfigured(
'Cannot create prizes without a TRACKER_SWEEPSTAKES_URL in settings'
)
using = kwargs.get('using', None)
self.maximumbid = self.minimumbid
if self.startrun and self.startrun.order and self.endrun and self.endrun.order:
self.prev_run = (
SpeedRun.objects.using(using)
.filter(event=self.startrun.event_id, order__lt=self.startrun.order)
.order_by('order')
.last()
)
self.next_run = (
SpeedRun.objects.using(using)
.filter(event=self.endrun.event_id, order__gt=self.endrun.order)
.order_by('order')
.first()
)
else:
self.prev_run = self.next_run = None
super(Prize, self).save(*args, **kwargs)
def eligible_donors(self):
donationSet = Donation.objects.filter(
event=self.event, transactionstate='COMPLETED'
).select_related('donor')
# remove all donations from donors who have won a prize under the same category for this event
if self.category is not None:
donationSet = donationSet.exclude(
Q(
donor__prizewinner__prize__category=self.category,
donor__prizewinner__prize__event=self.event,
)
)
# Apply the country/region filter to the drawing
if self.custom_country_filter:
countryFilter = self.allowed_prize_countries.all()
regionBlacklist = self.disallowed_prize_regions.all()
else:
countryFilter = self.event.allowed_prize_countries.all()
regionBlacklist = self.event.disallowed_prize_regions.all()
if countryFilter.exists():
donationSet = donationSet.filter(donor__addresscountry__in=countryFilter)
if regionBlacklist.exists():
for region in regionBlacklist:
donationSet = donationSet.exclude(
donor__addresscountry=region.country,
donor__addressstate__iexact=region.name,
)
fullDonors = PrizeWinner.objects.filter(prize=self, sumcount=self.maxmultiwin)
donationSet = donationSet.exclude(donor__in=[w.winner for w in fullDonors])
if self.has_draw_time():
donationSet = donationSet.filter(
timereceived__gte=self.start_draw_time(),
timereceived__lte=self.end_draw_time(),
)
donors = {}
for donation in donationSet:
if self.sumdonations:
donors.setdefault(donation.donor, Decimal('0.0'))
donors[donation.donor] += donation.amount
else:
donors[donation.donor] = max(
donation.amount, donors.get(donation.donor, Decimal('0.0'))
)
directEntries = DonorPrizeEntry.objects.filter(prize=self).exclude(
donor__in=[w.winner for w in fullDonors]
)
for entry in directEntries:
donors.setdefault(entry.donor, Decimal('0.0'))
donors[entry.donor] = max(
entry.weight * self.minimumbid, donors[entry.donor]
)
if self.maximumbid:
donors[entry.donor] = min(donors[entry.donor], self.maximumbid)
if not donors:
return []
elif self.randomdraw:
def weight(mn, mx, a):
if mx is not None and a > mx:
return float(mx / mn)
return float(a / mn)
return sorted(
[
{
'donor': d[0].id,
'amount': d[1],
'weight': weight(self.minimumbid, self.maximumbid, d[1]),
}
for d in donors.items()
if self.minimumbid <= d[1]
],
key=lambda d: d['donor'],
)
else:
m = max(donors.items(), key=lambda d: d[1])
return [{'donor': m[0].id, 'amount': m[1], 'weight': 1.0}]
def is_donor_allowed_to_receive(self, donor):
return self.is_country_region_allowed(donor.addresscountry, donor.addressstate)
def is_country_region_allowed(self, country, region):
return self.is_country_allowed(
country
) and not self.is_country_region_disallowed(country, region)
def is_country_allowed(self, country):
if self.requiresshipping:
if self.custom_country_filter:
allowedCountries = self.allowed_prize_countries.all()
else:
allowedCountries = self.event.allowed_prize_countries.all()
if allowedCountries.exists() and country not in allowedCountries:
return False
return True
def is_country_region_disallowed(self, country, region):
if self.requiresshipping:
if self.custom_country_filter:
disallowedRegions = self.disallowed_prize_regions.all()
else:
disallowedRegions = self.event.disallowed_prize_regions.all()
for badRegion in disallowedRegions:
if (
country == badRegion.country
and region.lower() == badRegion.name.lower()
):
return True
return False
def games_based_drawing(self):
return self.startrun and self.endrun
def games_range(self):
if self.games_based_drawing():
# TODO: fix me to use order... is this even used at all outside of tests?
return SpeedRun.objects.filter(
event=self.event,
starttime__gte=self.startrun.starttime,
endtime__lte=self.endrun.endtime,
)
else:
return SpeedRun.objects.none()
def has_draw_time(self):
return self.start_draw_time() and self.end_draw_time()
def start_draw_time(self):
if self.startrun and self.startrun.order:
if self.prev_run:
return self.prev_run.endtime - datetime.timedelta(
milliseconds=TimestampField.time_string_to_int(
self.prev_run.setup_time
)
)
return self.startrun.starttime.replace(tzinfo=pytz.utc)
elif self.starttime:
return self.starttime.replace(tzinfo=pytz.utc)
else:
return None
def end_draw_time(self):
if self.endrun and self.endrun.order:
if not self.next_run:
# covers finale speeches
return self.endrun.endtime.replace(
tzinfo=pytz.utc
) + datetime.timedelta(hours=1)
return self.endrun.endtime.replace(tzinfo=pytz.utc)
elif self.endtime:
return self.endtime.replace(tzinfo=pytz.utc)
else:
return None
def contains_draw_time(self, time):
return not self.has_draw_time() or (
self.start_draw_time() <= time <= self.end_draw_time()
)
def current_win_count(self):
return sum(
[
x
for x in self.get_prize_winners()
.aggregate(Sum('pendingcount'), Sum('acceptcount'))
.values()
if x is not None
]
)
def maxed_winners(self):
return self.current_win_count() == self.maxwinners
def get_prize_winners(self, time=None):
time = time or datetime.datetime.now(tz=pytz.utc)
return self.prizewinner_set.filter(
Q(acceptcount__gt=0)
| (
Q(pendingcount__gt=0)
& (Q(acceptdeadline=None) | Q(acceptdeadline__gt=time))
)
)
def get_expired_winners(self, time=None):
time = time or datetime.datetime.utcnow().astimezone(pytz.utc)
return self.prizewinner_set.filter(pendingcount__gt=0, acceptdeadline__lt=time)
def get_accepted_winners(self):
return self.prizewinner_set.filter(Q(acceptcount__gt=0))
def has_accepted_winners(self):
return self.get_accepted_winners().exists()
def is_pending_shipping(self):
return self.get_accepted_winners().filter(Q(shippingstate='PENDING')).exists()
def is_fully_shipped(self):
return self.maxed_winners() and not self.is_pending_shipping()
def get_prize_winner(self):
if self.maxwinners == 1:
return self.get_prize_winners().first()
else:
raise Exception('Cannot get single winner for multi-winner prize')
def get_winners(self):
return [w.winner for w in self.get_prize_winners()]
def get_winner(self):
prizeWinner = self.get_prize_winner()
if prizeWinner:
return prizeWinner.winner
else:
return None
@receiver(post_save, sender=SpeedRun)
def fix_prev_and_next_run_save(sender, instance, created, raw, using, **kwargs):
if raw:
return
fix_prev_and_next_run(instance, using)
@receiver(post_delete, sender=SpeedRun)
def fix_prev_and_next_run_delete(sender, instance, using, **kwargs):
fix_prev_and_next_run(instance, using)
def fix_prev_and_next_run(instance, using):
prev_run = instance.order and (
SpeedRun.objects.filter(event=instance.event_id, order__lt=instance.order)
.using(using)
.order_by('order')
.last()
)
next_run = instance.order and (
SpeedRun.objects.filter(event=instance.event_id, order__gt=instance.order)
.using(using)
.order_by('order')
.first()
)
prizes = Prize.objects.using(using).filter(
Q(prev_run=instance)
| Q(next_run=instance)
| Q(startrun=instance)
| Q(endrun=instance)
)
if prev_run:
prizes = prizes | Prize.objects.using(using).filter(
Q(startrun=next_run) | Q(endrun=prev_run)
)
for prize in prizes:
prize.save(using=using)
class PrizeKey(models.Model):
prize = models.ForeignKey('Prize', on_delete=models.PROTECT)
prize_winner = models.OneToOneField(
'PrizeWinner', on_delete=models.PROTECT, null=True, blank=True
)
key = models.CharField(max_length=64, unique=True)
class Meta:
app_label = 'tracker'
verbose_name = 'Prize Key'
ordering = ['prize']
# TODO: permissions are currently useless, consider removing
permissions = (
('edit_prize_key_keys', 'Can edit existing prize keys'),
('remove_prize_key_winners', 'Can remove winners from prize keys'),
)
@property
def winner(self):
return self.prize_winner_id and self.prize_winner.winner
def __str__(self):
return f'{self.prize}: ****{self.key[-4:]}'
@receiver(post_save, sender=Prize)
@receiver(post_save, sender=PrizeKey)
def set_max_winners(sender, instance, created, raw, **kwargs):
if raw:
return
if sender == Prize:
if not instance.key_code:
return
prize = instance
elif sender == PrizeKey:
if not created:
return
prize = instance.prize
else:
raise Exception('insanity')
count = prize.prizekey_set.count()
changed = False
if prize.maxwinners != count:
prize.maxwinners = count
changed = True
if prize.maxmultiwin != 1:
prize.maxmultiwin = 1
changed = True
if changed:
prize.save()
class PrizeWinner(models.Model):
winner = models.ForeignKey(
'Donor', null=False, blank=False, on_delete=models.PROTECT
)
pendingcount = models.IntegerField(
default=1,
null=False,
blank=False,
validators=[positive],
verbose_name='Pending Count',
help_text='The number of pending wins this donor has on this prize.',
)
acceptcount = models.IntegerField(
default=0,
null=False,
blank=False,
validators=[positive],
verbose_name='Accept Count',
help_text='The number of copied this winner has won and accepted.',
)
declinecount = models.IntegerField(
default=0,
null=False,
blank=False,
validators=[positive],
verbose_name='Decline Count',
help_text='The number of declines this donor has put towards this prize. '
'Set it to the max prize multi win amount to prevent this donor '
'from being entered from future drawings.',
)
sumcount = models.IntegerField(
default=1,
null=False,
blank=False,
editable=False,
validators=[positive],
verbose_name='Sum Counts',
help_text='The total number of prize instances associated with this winner',
)
prize = models.ForeignKey(
'Prize', null=False, blank=False, on_delete=models.PROTECT
)
emailsent = models.BooleanField(
default=False, verbose_name='Notification Email Sent'
)
# this is an integer because we want to re-send on each different number of accepts
acceptemailsentcount = models.IntegerField(
default=0,
null=False,
blank=False,
validators=[positive],
verbose_name='Accept Count Sent For',
help_text='The number of accepts that the previous e-mail was sent '
'for (or 0 if none were sent yet).',
)
shippingemailsent = models.BooleanField(
default=False, verbose_name='Shipping Email Sent'
)
couriername = models.CharField(
max_length=64,
verbose_name='Courier Service Name',
help_text='e.g. FedEx, DHL, ...',
blank=True,
null=False,
)
trackingnumber = models.CharField(
max_length=64, verbose_name='Tracking Number', blank=True, null=False
)
shippingstate = models.CharField(
max_length=64,
verbose_name='Shipping State',
choices=(('PENDING', 'Pending'), ('SHIPPED', 'Shipped')),
default='PENDING',
)
shippingcost = models.DecimalField(
decimal_places=2,
max_digits=20,
null=True,
blank=True,
verbose_name='Shipping Cost',
validators=[positive, nonzero],
)
winnernotes = models.TextField(
max_length=1024, verbose_name='Winner Notes', null=False, blank=True
)
shippingnotes = models.TextField(
max_length=2048, verbose_name='Shipping Notes', null=False, blank=True
)
acceptdeadline = models.DateTimeField(
verbose_name='Winner Accept Deadline',
default=None,
null=True,
blank=True,
help_text='The deadline for this winner to accept their prize '
'(leave blank for no deadline)',
)
auth_code = models.CharField(
max_length=64,
blank=False,
null=False,
editable=False,
default=util.make_auth_code,
help_text='Used instead of a login for winners to manage prizes.',
)
shipping_receipt_url = models.URLField(
max_length=1024,
blank=True,
null=False,
verbose_name='Shipping Receipt Image URL',
help_text='The URL of an image of the shipping receipt',
)
class Meta:
app_label = 'tracker'
verbose_name = 'Prize Winner'
unique_together = (
'prize',
'winner',
)
def make_winner_url(self):
import warnings
warnings.warn(
'`make_winner_url` is deprecated, please use `claim_url` instead',
DeprecationWarning,
)
return self.claim_url
def create_claim_url(self, request):
self._claim_url = f'https://{sites.get_current_site(request).domain}{reverse("tracker:prize_winner", args=[self.pk])}?auth_code={self.auth_code}'
@property
def claim_url(self):
if not hasattr(self, '_claim_url'):
raise AttributeError(
'you must call `create_claim_url` with the proper request before retrieving this property'
)
return self._claim_url
@property
def donor_cache(self):
# accounts for people who mail-in entry and never donated
return self.winner.cache_for(self.prize.event_id) or self.winner
def accept_deadline_date(self):
"""Return the actual calendar date associated with the accept deadline"""
if self.acceptdeadline:
return self.acceptdeadline.astimezone(util.anywhere_on_earth_tz()).date()
else:
return None
def check_multiwin(self, value):
if value > self.prize.maxmultiwin:
raise ValidationError(
'Count must not exceed the prize multi win amount ({0})'.format(
self.prize.maxmultiwin
)
)
return value
def clean_pendingcount(self):
return self.check_multiwin(self.pendingcount)
def clean_acceptcount(self):
return self.check_multiwin(self.acceptcount)
def clean_declinecount(self):
return self.check_multiwin(self.declinecount)
def clean(self):
self.sumcount = self.pendingcount + self.acceptcount + self.declinecount
if self.sumcount == 0:
raise ValidationError('Sum of counts must be greater than zero')
if self.sumcount > self.prize.maxmultiwin:
raise ValidationError(
'Sum of counts must be at most the prize multi-win multiplicity'
)
prizeSum = self.acceptcount + self.pendingcount
for winner in self.prize.prizewinner_set.exclude(pk=self.pk):
prizeSum += winner.acceptcount + winner.pendingcount
if prizeSum > self.prize.maxwinners:
raise ValidationError(
'Number of prize winners is greater than the maximum for this prize.'
)
if self.trackingnumber and not self.couriername:
raise ValidationError(
'A tracking number is only useful with a courier name as well!'
)
if self.winner and self.acceptcount > 0 and self.prize.requiresshipping:
if not self.prize.is_country_region_allowed(
self.winner.addresscountry, self.winner.addressstate
):
message = 'Unfortunately, for legal or logistical reasons, we cannot ship this prize to that region. Please accept our deepest apologies.'
coordinator = self.prize.event.prizecoordinator
if coordinator:
message += ' If you have any questions, please contact our prize coordinator at {0}'.format(
coordinator.email
)
raise ValidationError(message)
if self.prize.key_code and not hasattr(self, 'prize_key'):
raise ValidationError(
'Prize winners attached to key code prizes need a prize key attached as well.'
)
def validate_unique(self, **kwargs):
if (
'winner' not in kwargs
and 'prize' not in kwargs
and self.prize.category is not None
):
for prizeWon in PrizeWinner.objects.filter(
prize__category=self.prize.category,
winner=self.winner,
prize__event=self.prize.event,
):
if prizeWon.id != self.id:
raise ValidationError(
'Category, winner, and prize must be unique together'
)
def save(self, *args, **kwargs):
self.sumcount = self.pendingcount + self.acceptcount + self.declinecount
super(PrizeWinner, self).save(*args, **kwargs)
@property
def event(self):
return self.prize.event
def __str__(self):
return f'{self.prize} -- {self.winner}'
class PrizeCategoryManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
def get_or_create_by_natural_key(self, name):
return self.get_or_create(name=name)
class PrizeCategory(models.Model):
objects = PrizeCategoryManager()
name = models.CharField(max_length=64, unique=True)
class Meta:
app_label = 'tracker'
verbose_name = 'Prize Category'
verbose_name_plural = 'Prize Categories'
def natural_key(self):
return (self.name,)
def __str__(self):
return self.name
class DonorPrizeEntry(models.Model):
donor = models.ForeignKey(
'Donor', null=False, blank=False, on_delete=models.PROTECT
)
prize = models.ForeignKey(
'Prize', null=False, blank=False, on_delete=models.PROTECT
)
weight = models.DecimalField(
decimal_places=2,
max_digits=20,
default=Decimal('1.0'),
verbose_name='Entry Weight',
validators=[positive, nonzero],
help_text='This is the weight to apply this entry in the drawing (if weight is applicable).',
)
class Meta:
app_label = 'tracker'
verbose_name = 'Donor Prize Entry'
verbose_name_plural = 'Donor Prize Entries'
unique_together = (
'prize',
'donor',
)
@property
def event(self):
return self.prize.event
def __str__(self):
return f'{self.donor} entered to win {self.prize}'
| UTF-8 | Python | false | false | 30,566 | py | 541 | prize.py | 278 | 0.593404 | 0.589446 | 0 | 881 | 33.694665 | 154 |
neequole/docvite | 9,414,568,346,198 | 9e06590255299cf986a20664fc9049651625d71b | bebc333c753f2f50e527f3f3b90c319e09d7c59f | /backoffice/tests/test_client.py | 9021481e45767acc1a4a47dec7dc2f5ffed8fd80 | []
| no_license | https://github.com/neequole/docvite | ba11148edd5454553860d3deaae0d80f4e521576 | 9a84f062893fe506e9904ded2d9881acea0c7faf | refs/heads/master | 2021-09-01T20:10:39.250879 | 2017-12-07T09:17:44 | 2017-12-07T09:17:44 | 113,398,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from rest_framework import status
from rest_framework.test import APITestCase
from backoffice.models import Client, Doctor, Invitation
from .decorators import needs_doctor_login, needs_client_login
class ClientTests(APITestCase):
API_URL = '/api/clients'
DOCTOR_ACCOUNT = {'username': 'foo', 'password': 'foo'}
CLIENT_ACCOUNT = {'username': 'bar', 'password': 'bar'}
def setUp(self):
self.client.doctor = Doctor.objects.create_user(**self.DOCTOR_ACCOUNT)
self.client.client = Client.objects.create_user(
**self.CLIENT_ACCOUNT, email='bar@gmail.com')
def test_anonymous_invite(self):
""" Ensure anonymous users cannot perform invite """
url = '{}/invite/'.format(self.API_URL)
response = self.client.post(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
@needs_client_login
def test_client_invite(self):
""" Ensure clients cannot perform invite """
url = '{}/invite/'.format(self.API_URL)
response = self.client.post(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
@needs_doctor_login
def test_invite_missing_email(self):
""" Ensure we require e-mail during invite """
url = '{}/invite/'.format(self.API_URL)
response = self.client.post(url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('email', response.data)
@needs_doctor_login
def test_invite_nonclient_email(self):
""" Ensure we check that the e-mail belongs to a Client """
url = '{}/invite/'.format(self.API_URL)
request_data = {'email': 'test@gmail.com'}
response = self.client.post(url, request_data, format='json')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('email', response.data)
@needs_doctor_login
def test_invite(self):
""" Ensure we create new invitations """
url = '{}/invite/'.format(self.API_URL)
request_data = {'email': 'bar@gmail.com'}
response = self.client.post(url, request_data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['doctor'], self.client.doctor.pk)
self.assertEqual(response.data['client'], self.client.client.pk)
self.assertIn('created', response.data)
self.assertEqual(response.data['status'], Invitation.STATUS_PENDING)
self.assertTrue(response.data['is_sent'])
| UTF-8 | Python | false | false | 2,557 | py | 15 | test_client.py | 13 | 0.658193 | 0.652327 | 0 | 60 | 41.616667 | 78 |
bootchk/GimpFu-v3 | 1,717,986,951,020 | 3c564b25c3398a86e5998999386dadeb9d0e21c7 | 0c26cde921259189fa38a28092054f931f62ffc1 | /gimpfu/adaption/adapted_property.py | 882d6bc37b62b5828b17588ac3e9708a6a895f00 | []
| no_license | https://github.com/bootchk/GimpFu-v3 | e3f570588c411c55bf171f13f19677d9af7d39ef | 7e6e08a2acb34fe2dce6631f9f255dae5ab34a6b | refs/heads/master | 2022-08-10T08:24:58.858898 | 2022-07-27T19:42:24 | 2022-07-27T19:42:24 | 231,368,472 | 21 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import logging
class AdaptedProperty():
'''
Understands how to dynamically adapt properties.
Properties on Adaptee must be called using call syntax (with parens)
e.g. "foo = adaptee.get_property()" or "property()"
In the statement dynamically generated by this class.
Properties on AdaptedAdaptee use non-call syntax (without parens)
e.g. "foo = adaptedAdaptee.property"
In the Author's plugin source code.
An access to an AdaptedProperty is intercepted by the Python __getattr__
mechanism.
AdaptedProperty's are defined in AdaptedAdaptee's
by a property name like "Dynamic..."
that is a tuple of names of Adaptee properties (sic) that can be
dynamically adapted.
Some Adaptee properties cannot be dynamically adapted,
(because the syntax or semantic differences are too great to be automated.)
and are instead 'manually' adapted by code in AdaptedAdaptee
implemented as Python properties i.e. using "@property"
'''
'''
Kinds of adapted properties:
ReadOnly: get_<property>() defined by adaptee
Writeable: set_ and get_<property>() defined by adaptee
True: <property>() defined by adaptee
!!! An AdaptedProperty is NOT an access to a *field* of the adaptee, but a *method* of the adaptee.
An AdaptedAdaptee may define properties that give r/w access to fields of property.
But it is so rare (see GimpfuRGB) we don't do it programatically.
'''
'''
Inheritance and AdaptedProperty(s)
An Adaptee instance inherits from a chain of classes.
When we ask whether a name is on an instance of adaptee,
GI must search the chain.
An AdaptedAdaptee (which defines dynamic properties)
also inherits from a chain of classes.
E.g. GimpfuLayer=>GimpfuDrawable=>GimpfuItem.
Each class may define its own Dynamic... properties,
but when asked, must return the totaled properties of
its own class plus its inherited classes.
(Alternatively we could traverse the MRO)
'''
logger = logging.getLogger("GimpFu.AdaptedProperty")
@classmethod
def is_dynamic_writeable_property_name(cls, instance, name):
''' is name a writeable dynamic property on instance? '''
''' !!! instance is-a AdaptedAdaptee, not an Adaptee '''
# raises AttributeError if DynamicWriteableAdaptedProperties not defined by AdaptedAdaptee
#OLD delegated_property_names = getattr(instance, 'DynamicWriteableAdaptedProperties')
delegated_property_names = instance.DynamicWriteableAdaptedProperties()
# ensure delegated_property_names is not None, but could be empty
return name in delegated_property_names
@classmethod
def is_dynamic_readonly_property_name(cls, instance, name):
# raises AttributeError if DynamicWriteableAdaptedProperties not defined by AdaptedAdaptee
#OLD delegated_property_names = getattr(instance, 'DynamicReadOnlyAdaptedProperties')
delegated_property_names = instance.DynamicReadOnlyAdaptedProperties()
# ensure delegated_property_names is not None, but could be empty
return name in delegated_property_names
@classmethod
def is_dynamic_true_property_name(cls, instance, name):
''' Is <name> accessed like <name>() ? '''
delegated_property_names = instance.DynamicTrueAdaptedProperties()
result = name in delegated_property_names
AdaptedProperty.logger.debug(f"is_dynamic_true_property_name: {result} for name: {name} on instance: {instance}")
return result
@classmethod
def is_dynamic_readable_property_name(cls, instance, name):
''' Is <name> accessed like get_<name>() ? '''
return (cls.is_dynamic_readonly_property_name(instance, name)
or cls.is_dynamic_writeable_property_name(instance, name)
)
'''
!!! This does not mean that the callable has arguments.
When the callable does not have args i.e. <name>(void)
it is indistinguishable from what we might adapt as a property.
!!! This is too weak.
We should retrieve the attr and check that it is a gi.FunctionInfo,
else the attribute is not a callable.
Gimp and GI does have properties that are not callables?
'''
@classmethod
def is_callable_name_on_instance(cls, instance, name):
''' Is <name> an attribute on instance, accessed like <name>() ? '''
return hasattr(instance, name)
# Private
@classmethod
def _eval_statement_on_adaptee(cls, adaptee, name, prefix = '', setting_value=None):
'''
Create and eval() a statement to access a method on adaptee
that looks like a property i.e. has no args.
'''
assert prefix in ("get_", "set_", "")
# FUTURE rather than trust that DynamicReadOnlyAdaptedProperties is correct,
# preflight get_name on dictionary of adaptee
# So we can use a more specific error than AttributeError, e.g. "is not a *property* name"
# Method on adaptee is like "[get,set]_name"
# Method on adaptee is a callable having no arguments
# eval occurs in current context, so formal args are in scope
if prefix == 'set_':
# setStatement is a call with arg
statement = 'adaptee.set_' + name + '(setting_value)'
else:
# is a get (prefix is 'get_') or a read (prefix is '')
# getStatement is a call without arg
statement = 'adaptee.' + prefix + name + '()'
result = eval(statement)
AdaptedProperty.logger.debug(f"eval {statement} result: {result}")
return result
@classmethod
def get(cls, adaptee, method_name ):
''' Call method_name of adaptee to get a property value. '''
unwrapped_result = cls._eval_statement_on_adaptee(adaptee, method_name, prefix = 'get_')
# !!! result can be a container of wrappable types. Usually a fundamental type.
from gimpfu.adaption.marshal import Marshal
result = Marshal.wrap_adaptee_results(unwrapped_result)
return result
@classmethod
def set(cls, adaptee, method_name, value):
''' Call method_name of adaptee to set a property value. '''
from gimpfu.adaption.marshal import Marshal
unwrapped_value = Marshal.unwrap(value)
return cls._eval_statement_on_adaptee(adaptee, method_name, prefix = 'set_', setting_value = unwrapped_value)
@classmethod
def read(cls, adaptee, method_name ):
''' Call method_name of adaptee to get a property value. '''
# TODO marshal
return cls._eval_statement_on_adaptee(adaptee, method_name, prefix = '')
| UTF-8 | Python | false | false | 6,716 | py | 113 | adapted_property.py | 83 | 0.675253 | 0.675253 | 0 | 168 | 38.964286 | 121 |
ibkalokoh/cbc_adas | 4,234,837,771,965 | b4c6ad4df62fa827b3ccdd015150165410a74a44 | 3a733c3cb60ef69f2c7ccf342a51e6e38ce4d535 | /code/human_driver_model/evaluation/storm/mini.py | 45a997bd19f2c8a3e2a9d5f4b0605dda0e41cb14 | []
| no_license | https://github.com/ibkalokoh/cbc_adas | 6e00716b85034424077ce51d23297fb8bb6dcd92 | 83b661b39fbc8a5babe0571bc4828086e25056ed | refs/heads/master | 2020-09-12T17:02:40.316327 | 2018-10-09T19:04:03 | 2018-10-09T19:04:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os, random
f = open('test_cases.csv', 'w')
f.write("d_type,v,v1,x1_0\n")
N = 10
for i in range(0,N):
while True:
d_type = random.randint(1,3)
v = random.randint(15,34)
v1 = random.randint(15,34)
x1_0 = random.randint(30,85)
if v >= v1:
break
f.write("%d,%d,%d,%d\n"%(d_type,v,v1,x1_0))
f.close() | UTF-8 | Python | false | false | 323 | py | 556 | mini.py | 13 | 0.588235 | 0.504644 | 0 | 20 | 15.2 | 44 |
simonsobs/acondbs | 10,840,497,482,020 | 013910e7d6203cf32bdc818dbee32010bbd283d1 | caa175a933aca08a475c6277e22cdde1654aca7b | /tests/schema/product/gql/queries/query_all_product_types.py | b5da1173ab9f8889fbc160c6abfe39551e4de117 | [
"MIT"
]
| permissive | https://github.com/simonsobs/acondbs | 01d68ae40866461b85a6c9fcabdfbea46ef5f920 | d18c7b06474b0dacb1dcf1c6dbd1e743407645e2 | refs/heads/main | 2023-07-07T04:33:40.561273 | 2023-06-28T22:08:00 | 2023-06-28T22:08:00 | 239,022,783 | 0 | 1 | MIT | false | 2023-06-26T20:36:39 | 2020-02-07T21:07:46 | 2023-06-22T15:38:54 | 2023-06-26T20:36:02 | 1,478 | 0 | 1 | 13 | Python | false | false | from ..fragments import FRAGMENT_PRODUCT_TYPE_CONNECTION
QUERY_ALL_PRODUCT_TYPES = (
"""
query AllProductTypes($sort: [ProductTypeSortEnum] = [ORDER_ASC]) {
allProductTypes(sort: $sort) {
...fragmentProductTypeConnection
}
}
"""
+ FRAGMENT_PRODUCT_TYPE_CONNECTION
)
| UTF-8 | Python | false | false | 283 | py | 338 | query_all_product_types.py | 316 | 0.706714 | 0.706714 | 0 | 12 | 22.583333 | 67 |
denyami/StPython | 16,836,271,824,744 | 31a1e1786aee74a077435823679ce739b810453a | e115e7f508dcb1df8cc77de64f39a4551900e914 | /Matplotlib/sample2.py | 71124eef6c23584e9d257dcdc52e0a1926ace26d | []
| no_license | https://github.com/denyami/StPython | cd4e935843d5d6a778942ef88702f4c41e07f11e | 47b834fa7ee98de395b75c760247b7e050681eba | refs/heads/master | 2022-06-20T03:24:42.953990 | 2019-07-19T04:34:59 | 2019-07-19T04:34:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3,4]
y = [5,6,7,8]
plt.plot(x,y, 'o-', label = "my data")
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc = 'best')
plt.show()
| UTF-8 | Python | false | false | 187 | py | 10 | sample2.py | 10 | 0.620321 | 0.57754 | 0 | 10 | 17.7 | 38 |
xdreamseeker/Asystem | 9,577,777,093,796 | df02910c6838e4f5e0361bf23e44e8437b1dac2a | 5a5280a532111fafcc79b36fa6e75db0e81b8d5a | /Wroker.py | 5c2b65f4b73fb94a97e9f9cf93fea348dbb0bc8d | []
| no_license | https://github.com/xdreamseeker/Asystem | d99842c44f429594717fac07cea19608b98b261d | b7e7b0583e6ba5df41892118d3932ec5ef7ee52d | refs/heads/master | 2019-04-20T17:23:42.690423 | 2017-08-24T09:14:04 | 2017-08-24T09:14:04 | 93,318,058 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import multiprocessing
import time
import socket
class Worker(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
def run(self):
host=('127.0.0.1',8888)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
sock.bind(host)
sock.listen(0)
except Exception as e:
print("already start worker")
exit(-1)
print("start worker....")
while True:
time.sleep(5)
if __name__ == '__main__':
p = Worker()
p.start()
print("end") | UTF-8 | Python | false | false | 599 | py | 15 | Wroker.py | 8 | 0.539232 | 0.517529 | 0 | 31 | 18.354839 | 63 |
ki4070ma/leetcode | 13,984,413,550,978 | bac40e2e0f9a5fc8dbcad7405b238dc868c40242 | 1626839892713a4ff453b46ae55d51c224d9e866 | /atcoder/20191005_AGC/1_A_ConnectionAndDisconnection.py | e317a1e446d50a8b8d1b4008eacf70cfa5ecf894 | []
| no_license | https://github.com/ki4070ma/leetcode | c317ce72b62cd44420ee1abe629386f048582266 | 2e9db241cb32d746bb0061d5d1e7c9d170101daf | refs/heads/master | 2021-06-13T17:06:41.033873 | 2021-03-21T14:14:20 | 2021-03-21T14:14:20 | 161,972,630 | 1 | 0 | null | false | 2019-11-11T08:42:01 | 2018-12-16T05:59:50 | 2019-10-06T10:48:11 | 2019-11-11T08:42:00 | 67 | 1 | 0 | 0 | Python | false | false | #!/usr/bin/python3
from sys import stdin
for _ in range(13):
S = stdin.readline().rstrip()
K = int(stdin.readline().rstrip())
pre_str = ""
count = 1
base_count = 0
for a in list(S):
if pre_str == a:
count += 1
else:
base_count += int(count / 2)
count = 1
pre_str = a
base_count += int(count / 2)
ret = 0
if not S:
ret = 0
if len(list(set(list(S)))) == 1:
ret = int(len(S) * K / 2)
elif len(S) > 2 and S[0] != S[1] and S[-1] != S[-2] and S[0] == S[-1]:
ret = base_count * K
ret += K - 1
else:
ret = base_count * K
print(ret)
# for _ in range(3):
# S = stdin.readline().rstrip()
# K = int(stdin.readline().rstrip())
#
# string = S*K
# print(string)
#
# pre_str = ''
# count = 1
# ret = 0
# for a in list(string):
# if pre_str == a:
# count += 1
# else:
# ret += int(count / 2)
# count = 1
# pre_str = a
# ret += int(count / 2)
# print(ret)
| UTF-8 | Python | false | false | 1,102 | py | 199 | 1_A_ConnectionAndDisconnection.py | 136 | 0.42922 | 0.403811 | 0 | 50 | 21.04 | 74 |
Kohodeus/lol-account-checker | 18,760,417,171,730 | c2f086a5425a91406f9daf09ed6c07f0449a6807 | 2a908be0e7c801898d1d8d164f475bd7174843c6 | /lolchecker.py | 3017e27e5a8fbb99feb8fbe85e288543830b7ddd | []
| no_license | https://github.com/Kohodeus/lol-account-checker | 746b9b2089da15e770824f7e6d26170d8c487919 | 05943e860162b62d3ebd49296d90e67a5cfe4210 | refs/heads/main | 2023-07-10T18:24:36.115849 | 2021-08-26T19:45:58 | 2021-08-26T19:45:58 | 414,004,502 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from datetime import datetime
import requests, concurrent.futures, re, time
'''
Paste you accounts below separated by commas
'''
ACCOUNTS = "user:pass, user1:pass1,user2:pass2"
class AccountChecker:
AUTH_URL = "https://auth.riotgames.com/api/v1/authorization"
INFO_URL = "https://auth.riotgames.com/userinfo"
CHAMPION_DATA_URL = "https://cdn.communitydragon.org/latest/champion/"
INVENTORY_TYPES = [
'TOURNAMENT_TROPHY', 'TOURNAMENT_FLAG', 'TOURNAMENT_FRAME',
'TOURNAMENT_LOGO', 'GEAR', 'SKIN_UPGRADE_RECALL',
'SPELL_BOOK_PAGE', 'BOOST', 'BUNDLES', 'CHAMPION',
'CHAMPION_SKIN', 'EMOTE', 'GIFT', 'HEXTECH_CRAFTING',
'MYSTERY', 'RUNE', 'STATSTONE', 'SUMMONER_CUSTOMIZATION',
'SUMMONER_ICON', 'TEAM_SKIN_PURCHASE', 'TRANSFER',
'COMPANION', 'TFT_MAP_SKIN', 'WARD_SKIN', 'AUGMENT_SLOT'
]
def __init__(self, username, password):
self.username = username
self.password = password
self.session = requests.Session()
auth_data = {
"client_id": "riot-client",
"nonce": "1",
"redirect_uri": "http://localhost/redirect",
"response_type": "token id_token",
"scope":"openid link ban lol_region",
}
self.session.post(
url=self.AUTH_URL,
json=auth_data
)
self._get_tokens()
self._get_user_info()
def _get_tokens(self):
json_data = {
"type": "auth",
"username": self.username,
"password": self.password,
}
response = self.session.put(
url=self.AUTH_URL,
json=json_data
)
response = response.json()
# print (response, '-=-=-')
# uri format
# "http://local/redirect#access_token=...
# &scope=...&id_token=...&token_type=
# &expires_in=...
try:
uri = response['response']['parameters']['uri']
infos = uri.split('=')
infos = [x.split('&')[0] for x in infos]
self.access_token = infos[1]
self.id_token = infos[3]
except:
print(f"Authorization error on {self.username}")
print(response)
def _get_user_info(self):
auth = {"Authorization": f"Bearer {self.access_token}"}
self.session.headers.update(auth)
response = self.session.post(url=self.INFO_URL)
self.user_info = response.json()
self.region_id = self.user_info['region']['id']
self.region_tag = self.user_info['region']['tag']
return response.json()['ban']['code'] == ''
def get_inventory(self, types=INVENTORY_TYPES):
invt_url = f"https://{self.region_id}.cap.riotgames.com/lolinventoryservice/v2/inventories/simple?"
#detail_invt_url = f"https://{self.region_id}.cap.riotgames.com/lolinventoryservice/v2/inventoriesWithLoyalty?"
LOCATION_PARAMETERS = {
"BR1": "lolriot.mia1.br1",
"EUN1": "lolriot.euc1.eun1",
"EUW1": "lolriot.ams1.euw1",
"JP1": "lolriot.nrt1.jp1",
"LA1": "lolriot.mia1.la1",
"LA2": "lolriot.mia1.la2",
"NA1": "lolriot.pdx2.na1",
"OC1": "lolriot.pdx1.oc1",
"RU": "lolriot.euc1.ru",
"TR1": "lolriot.euc1.tr1"
}
query = {
"puuid": self.user_info['sub'],
"location": LOCATION_PARAMETERS[self.region_id],
"accountId": self.user_info['lol']['cuid'],
}
query_string = [f"{k}={v}" for k, v in query.items()]
for t in types:
query_string.append(f"inventoryTypes={t}")
query_string = '&'.join(query_string)
URL = invt_url + query_string
auth = {"Authorization": f"Bearer {self.access_token}"}
self.session.headers.update(auth)
response = self.session.get(url=URL)
try:
result = response.json()['data']['items']
except:
print(f"Failed to get inventory data on {self.username}")
print(response)
return
champion_names = []
champion_skins = []
champion_urls = [self.CHAMPION_DATA_URL + str(champion_id) + "/data" for champion_id in result['CHAMPION']]
def load_url(url):
champion_data = requests.get(url)
return champion_data
with concurrent.futures.ThreadPoolExecutor() as executor:
future_to_url = (executor.submit(load_url, url) for url in champion_urls)
for future in concurrent.futures.as_completed(future_to_url):
try:
data = future.result().json()
champion_skins.extend([skin['name'] for skin in data['skins'] if skin['id'] in result['CHAMPION_SKIN']])
champion_names.append(data['name'])
except:
print("Champion/skin conversion failed for 1 champion")
result['CHAMPION'] = champion_names
result['CHAMPION_SKIN'] = champion_skins
return result
def get_balance(self):
store_url = f"https://{self.user_info['region']['tag']}.store.leagueoflegends.com/storefront/v3/view/misc?language=en_US"
auth = {"Authorization": f"Bearer {self.access_token}"}
self.session.headers.update(auth)
response = self.session.get(store_url)
result = response.json()['player']
return result
def get_purchase_history(self):
hist_url = f"https://{self.user_info['region']['tag']}.store.leagueoflegends.com/storefront/v3/history/purchase"
auth = {"Authorization": f"Bearer {self.access_token}"}
self.session.headers.update(auth)
response = self.session.get(url=hist_url)
result = response.json()
return result
def refundable_RP(self):
history = self.get_purchase_history()
refund_num = history['refundCreditsRemaining']
refundables = [x['amountSpent']
for x in history['transactions']
if x['refundable'] and
x['currencyType']=='RP']
result = sum(sorted(refundables, reverse=True)[:refund_num])
return result
def refundable_IP(self):
history = self.get_purchase_history()
refund_num = history['refundCreditsRemaining']
refundables = [x['amountSpent']
for x in history['transactions']
if x['refundable'] and
x['currencyType']=='IP']
result = sum(sorted(refundables, reverse=True)[:refund_num])
return result
def last_play(self):
matches_url = "https://acs.leagueoflegends.com/v1/stats/player_history/auth?begIndex=0&endIndex=1"
auth = {"Authorization": f"Bearer {self.access_token}"}
self.session.headers.update(auth)
response = self.session.get(url=matches_url)
return (self._date_readable(response.json()))
def get_rank(self):
rank_url = f"https://lolprofile.net/index.php?page=summoner&ajaxr=1®ion={self.region_tag}&name={self.user_info['lol_account']['summoner_name']}"
page = requests.get(rank_url).text
pattern = '((?<="tier">)(.*?)(?=<)|(?<="lp">)(.*?)(?=<))'
rank = re.findall(pattern, page)
return ' '.join([rank[0][0], rank[1][0]]) if rank else "Unranked"
def print_info(self):
inventory_data = self.get_inventory()
ip_value = self.refundable_IP()
rp_value = self.refundable_RP()
region = self.region_tag.upper()
ban_status = f"True ({self.user_info['ban']['code']})" if self.user_info['ban']['code'] else "False"
name = self.user_info['lol_account']['summoner_name']
level = self.user_info['lol_account']['summoner_level']
balance = self.get_balance()
last_game = self.last_play()
champions = ', '.join(inventory_data['CHAMPION'])
champion_skins = ', '.join(inventory_data['CHAMPION_SKIN'])
rp_curr = balance['rp']
ip_curr = balance['ip']
rank = self.get_rank()
ret_str = [f" | Region: {region}", f"Name: {name}", f"Login: {self.username}:{self.password}", f"Last Game: {last_game}", f"Level: {level}", f"Rank: {rank}", f"IP: {ip_curr} - Refundable {ip_value}", f"RP: {rp_curr} - Refundable {rp_value}", f"Banned: {ban_status}", "\n", "\n", f"Champions ({len(inventory_data['CHAMPION'])}): {champions}", "\n", "\n", f"Skins ({len(inventory_data['CHAMPION_SKIN'])}): {champion_skins}", "\n", "\n", "\n"]
return ' | '.join(ret_str)
def _date_readable(self, variable):
try:
timeCreation = variable['games']['games'][0]['gameCreation']
dateTime = datetime.datetime.fromtimestamp(
int(timeCreation /1000)
).strftime('%Y-%m-%d %H:%M:%S')
return dateTime
except:
return "No previous games"
account_list = [i for i in ACCOUNTS.replace(" ", "").split(",")]
def load_account(account):
user, pw = account.split(":")
account_checker = AccountChecker(user, pw)
return account_checker
time1 = time.time()
print(f"Checking accounts, please wait...")
with concurrent.futures.ThreadPoolExecutor() as executor:
future_to_acc = (executor.submit(load_account, acc) for acc in account_list)
for future in concurrent.futures.as_completed(future_to_acc):
try:
data = future.result()
with open(f"accounts-{str(time1)}.txt", 'a', encoding="utf-8") as account_writer:
account_writer.write(data.print_info())
except Exception as exc:
print("Failed to retrieve account.")
time2 = time.time()
print(f"Complete! Account information located in accounts-{str(time1)}.txt")
print(f'Took {time2-time1:.2f} s')
| UTF-8 | Python | false | false | 10,295 | py | 2 | lolchecker.py | 1 | 0.55085 | 0.54473 | 0 | 252 | 38.853175 | 448 |
juhanikataja/SAPPORO-web | 13,348,758,386,035 | 12d2cdb28389706e03191b104f00ba870a5e4bfd | d39b5fe0d87f28a28d14b8004a3f3a40cd7ccab7 | /src/app/lib/mixin.py | 5f7d2f904ccb83260784ca6beee7757f4b9bafc7 | [
"Apache-2.0"
]
| permissive | https://github.com/juhanikataja/SAPPORO-web | 4bfb7d9ea720e18f2bc4d8fdb00234438ed32621 | 1b070a2338e36a25d8b7af3c12b6bafe86003dad | refs/heads/master | 2020-09-13T03:47:09.029647 | 2019-11-18T23:51:29 | 2019-11-18T23:51:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # coding: utf-8
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
class MyLoginRequiredMixin(LoginRequiredMixin):
raise_excrption = True
permission_denied_message = "You do not have permission to access this page." # NOQA
def handle_not_authenticated(self):
return redirect_to_login(self.request.get_full_path(),
self.get_login_url(),
self.get_redirect_field_name())
def handle_exception(self):
raise PermissionDenied(self.get_permission_denied_message())
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_not_authenticated()
if self.raise_exception:
return self.handle_exception()
return super().dispatch(request, *args, **kwargs)
| UTF-8 | Python | false | false | 957 | py | 63 | mixin.py | 31 | 0.668757 | 0.667712 | 0 | 24 | 38.875 | 89 |
Zynoz/BachelorsThesis | 14,388,140,470,361 | d7da206b87d19359bc6017d142da0fbbb40caaae | 36e3e6a12c71c738ed69da8a45b633a71faa4a3c | /src/Utility/__init__.py | 1a961d4ed42fee362f8bd7b8f62f2d322a9d2550 | []
| no_license | https://github.com/Zynoz/BachelorsThesis | 2aa4006294a3b74068ce5e80356a00336e539d54 | 9b5289b947f1eab9b22f5129e8fc7c6f578408d2 | refs/heads/master | 2022-12-24T15:05:53.890638 | 2020-10-02T18:03:55 | 2020-10-02T18:03:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from src.Utility.Exceptions import *
from src.Utility.Constants import *
from src.Utility.Util import *
| UTF-8 | Python | false | false | 105 | py | 20 | __init__.py | 17 | 0.790476 | 0.790476 | 0 | 3 | 33.666667 | 36 |
AdamsStWeb/Advent2020 | 11,802,570,149,230 | a978141173ca0dc251a02c225c87b5c02361cc52 | 1aff385b10cd334384c92a8b28b9b9c7865d3bb1 | /Day2/Day2.py | 153719f95d43234432f22b453046c7412e4d0886 | []
| no_license | https://github.com/AdamsStWeb/Advent2020 | cac2f31737e40149ea92ca334e0ef61c71ab6db6 | bbf91b018d13cb6bf17787fed98b374caf428cd0 | refs/heads/main | 2023-01-24T17:34:15.614741 | 2020-12-06T17:46:49 | 2020-12-06T17:46:49 | 317,702,613 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | with open("Day2Input.txt") as f:
data = f.readlines()
data = [x.strip() for x in data]
#### Part 1
arr = []
for line in data:
arr.append(line.split(' '))
valid_count = 0
for line in arr:
pw_range = line[0].split('-')
min_len = int(pw_range[0])
max_len = int(pw_range[1])
letter = line[1]
letter = letter[0]
count = 0
pw = line[2]
for i in pw:
if i == letter:
count = count + 1
if count >= min_len and count <= max_len:
valid_count = valid_count + 1
print(valid_count)
### Part 2
valid_count = 0
for line in arr:
pw_indexs = line[0].split('-')
index_1 = int(pw_indexs[0]) - 1
index_2 = int(pw_indexs[1]) - 1
letter = line[1]
letter = letter[0]
pw = line[2]
if pw[index_1] == letter and pw[index_2] != letter:
valid_count = valid_count + 1
if pw[index_1] != letter and pw[index_2] == letter:
valid_count = valid_count + 1
print(valid_count) | UTF-8 | Python | false | false | 983 | py | 7 | Day2.py | 7 | 0.54527 | 0.514751 | 0 | 47 | 19.93617 | 55 |
fankiat/598rl-fa20_fchan5 | 4,123,168,647,605 | c83b620be3433fcbb2d68eba10e62dfa15e16d49 | 1fda9ceb5eaa5cd19e520127dcc0a577a9a5a47f | /hw1/hw1_fchan5/train.py | c2ab890a58b128058b14bbcfb669c398c94a8c8c | []
| no_license | https://github.com/fankiat/598rl-fa20_fchan5 | 786c17bf8629acb723113e5c29f1ccbc09874e6a | 828d6cb4ec70fc995b30ef24aeb9f010a8d05ec4 | refs/heads/main | 2023-02-17T04:08:40.562642 | 2021-01-12T22:00:36 | 2021-01-12T22:00:36 | 328,705,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import numpy as np
from learning_algorithms import policy_evaluation, policy_improvement
from learning_algorithms import value_iteration
from learning_algorithms import sarsa_td0, qlearning_td0, value_evaluation_td0
GAMMA = 0.95
def train_policy_iteration(env, save_dir, gamma=GAMMA, *args, **kwargs):
# Create environment
# env = discrete_pendulum.Pendulum(n_theta=21, n_thetadot=21, n_tau=21)
# env = gridworld.GridWorld(hard_version=False)
# initializing
# V = np.zeros(env.num_states)
# equal probability of taking any action
Q = np.ones((env.num_states, env.num_actions)) / env.num_actions
# Q = np.zeros((env.num_states, env.num_actions))
policy_stable = False
meanV_trajectory = []
while not policy_stable:
V, Q, meanV = policy_evaluation(env, Q, gamma)
V, Q, policy_stable = policy_improvement(env, V, Q, gamma)
meanV_trajectory.extend(meanV)
np.save(
os.path.join(save_dir, 'policy_iteration_learning_curve.npy'),
meanV_trajectory, allow_pickle=False)
np.save(
os.path.join(save_dir, 'policy_iteration_Q.npy'),
Q, allow_pickle=False)
np.save(
os.path.join(save_dir, 'policy_iteration_V.npy'),
V, allow_pickle=False)
return
def train_value_iteration(env, save_dir, gamma=GAMMA, theta=1e-8, *args, **kwargs):
# Create environment
# env = discrete_pendulum.Pendulum(n_theta=21, n_thetadot=21, n_tau=21)
# env = gridworld.GridWorld(hard_version=False)
# initializing
V = np.zeros(env.num_states)
# equal probability of taking any action
Q = np.ones((env.num_states, env.num_actions)) / env.num_actions
# Q = np.zeros((env.num_states, env.num_actions))
V, Q, meanV_trajectory = value_iteration(env, V, Q, gamma, theta)
np.save(
os.path.join(SAVEDIR, 'value_iteration_learning_curve.npy'),
meanV_trajectory, allow_pickle=False)
np.save(
os.path.join(SAVEDIR, 'value_iteration_Q.npy'),
Q, allow_pickle=False)
np.save(
os.path.join(SAVEDIR, 'value_iteration_V.npy'),
V, allow_pickle=False)
return
def train_sarsa(inputParams):
# print("Worker id: {}".format(os.getpid()))
env = inputParams[0]
alpha = inputParams[1]
epsilon = inputParams[2]
# Create environment
# env = discrete_pendulum.Pendulum(n_theta=21, n_thetadot=21, n_tau=21)
# env = gridworld.GridWorld(hard_version=False)
# initializing
V = np.zeros(env.num_states)
# equal probability of taking any action
Q = np.ones((env.num_states, env.num_actions)) / env.num_actions
# Q = np.zeros((env.num_states, env.num_actions))
# V, Q = value_iteration(env, V, Q, gamma, theta)
Q, reward_trajectory = sarsa_td0(
env, Q, num_episodes=NEPISODES, gamma=GAMMA, alpha=alpha,
epsilon=epsilon)
V = value_evaluation_td0(
env, V, Q, num_episodes=NEPISODES, gamma=GAMMA, alpha=alpha)
np.save(
os.path.join(SAVEDIR, 'sarsa_alpha{:.2f}_epsilon{:.2f}_Q.npy'.format(alpha, epsilon)),
Q, allow_pickle=False)
np.save(
os.path.join(SAVEDIR, 'sarsa_alpha{:.2f}_epsilon{:.2f}_learning_curve.npy'.format(alpha, epsilon)),
reward_trajectory, allow_pickle=False)
np.save(
os.path.join(SAVEDIR, 'sarsa_alpha{:.2f}_epsilon{:.2f}_V.npy'.format(alpha, epsilon)),
V, allow_pickle=False)
# print("working pid {} done".format(os.getpid()))
return
def train_qlearning(inputParams):
alpha = inputParams[0]
epsilon = inputParams[1]
# Create environment
# env = discrete_pendulum.Pendulum(n_theta=21, n_thetadot=21, n_tau=21)
env = gridworld.GridWorld(hard_version=False)
# initializing
V = np.zeros(env.num_states)
# equal probability of taking any action
Q = np.ones((env.num_states, env.num_actions)) / env.num_actions
# Q = np.zeros((env.num_states, env.num_actions))
# V, Q = value_iteration(env, V, Q, gamma, theta)
Q, reward_trajectory = qlearning_td0(
env, Q, num_episodes=NEPISODES, gamma=GAMMA, alpha=alpha,
epsilon=epsilon)
V = value_evaluation_td0(
env, V, Q, num_episodes=NEPISODES, gamma=GAMMA, alpha=alpha)
np.save(
os.path.join(SAVEDIR, 'qlearning_alpha{:.2f}_epsilon{:.2f}_Q.npy'.format(alpha, epsilon)),
Q, allow_pickle=False)
np.save(
os.path.join(SAVEDIR, 'qlearning_alpha{:.2f}_epsilon{:.2f}_learning_curve.npy'.format(alpha, epsilon)),
reward_trajectory, allow_pickle=False)
np.save(
os.path.join(SAVEDIR, 'qlearning_alpha{:.2f}_epsilon{:.2f}_V.npy'.format(alpha, epsilon)),
V, allow_pickle=False)
# print("working pid {} done".format(os.getpid()))
return
| UTF-8 | Python | false | false | 4,763 | py | 46 | train.py | 30 | 0.648541 | 0.637413 | 0 | 134 | 34.544776 | 111 |
neerraghuwanshi/interview-prep | 19,464,791,809,250 | 7c8cf1f38492b622ed388177040db96629b2dd6f | f85b35dd09cb42c82200be6a68685a7b09bbbd80 | /treeAndGraph/11.py | 6553550e32e2cf1d4eb8bbb47e5a5234afcbbbf1 | []
| no_license | https://github.com/neerraghuwanshi/interview-prep | ba6ffc9bc4bdf1c6bd8a89a0a7d0f19c04c5688e | c196d831de1bc8363a8585f4e8a6d76a737f1449 | refs/heads/main | 2023-04-29T19:56:43.713886 | 2021-05-12T14:42:05 | 2021-05-12T14:42:05 | 316,802,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Random Node: You are implementing a binary tree class from scratch which, in addition to insert, find, and delete, has a method getRandomNode() which returns a random node from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm for getRandomNode, and explain how you would implement the rest of the methods.
import random
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.parent = None
self.size = 1
@property
def leftSize(self):
if self.left:
return self.left.size
return 0
@property
def rightSize(self):
if self.right:
return self.right.size
return 0
class Tree:
def __init__(self, root=None):
self.root = root
def findNode(self, value):
if self.root:
A = [self.root]
while len(A) > 0:
node = A.pop(0)
if node.value == value:
return node
if node.left:
A.append(node.left)
if node.right:
A.append(node.right)
def findLeaf(self, startNode):
if self.root:
A = [startNode]
while len(A) > 0:
node = A.pop(0)
if not node.left or not node.right:
return node
A.append(node.left)
A.append(node.right)
def incrementParentsSize(self, node):
if node.parent:
node.parent.size += 1
self.incrementParentsSize(node.parent)
def decrementParentsSize(self, node):
if node.parent:
node.parent.size -= 1
self.decrementParentsSize(node.parent)
def insert(self, value):
newNode = Node(value)
if self.root:
leaf = self.findLeaf(self.root)
if not leaf.left:
leaf.left = newNode
else:
leaf.right = newNode
newNode.parent = leaf
else:
self.root = newNode
self.incrementParentsSize(newNode)
def removeNodeFromParent(self, node, substitute=None, decrement=True):
parent = node.parent
if parent.left == node:
parent.left = substitute
else:
parent.right = substitute
if decrement:
self.decrementParentsSize(node)
def deleteNode(self, value):
if self.root.value == value:
node = self.root
if not node.left and not node.right:
self.root = None
elif node.left and not node.right:
self.root = node.left
node.left = None
elif node.right and not node.left:
self.root = node.right
node.right = None
else:
leaf = self.findLeaf(self.root)
if leaf.left:
leaf = leaf.left
elif leaf.right:
leaf = leaf.right
self.removeNodeFromParent(leaf)
self.root = leaf
leaf.left = node.left
leaf.right = node.right
leaf.size = node.size
if leaf.left:
leaf.left.parent = leaf
if leaf.right:
leaf.right.parent = leaf
node.left = None
node.right = None
self.root.parent = None
else:
node = self.findNode(value)
if not node.left and not node.right:
self.removeNodeFromParent(node)
elif node.left and not node.right:
self.removeNodeFromParent(node, node.left)
node.left.parent = node.parent
node.left = None
elif node.right and not node.left:
self.removeNodeFromParent(node, node.right)
node.right.parent = node.parent
node.right = None
else:
leaf = self.findLeaf(node)
if leaf.left:
leaf = leaf.left
self.removeNodeFromParent(leaf)
elif leaf.right:
leaf = leaf.right
self.removeNodeFromParent(leaf)
else:
self.removeNodeFromParent(leaf)
self.removeNodeFromParent(node, leaf, False)
leaf.left = node.left
leaf.right = node.right
leaf.size = node.size
leaf.parent = node.parent
if leaf.left:
leaf.left.parent = leaf
if leaf.right:
leaf.right.parent = leaf
node.left = None
node.right = None
node.parent = None
return node
def printTree(self):
if self.root:
currentDepth = [self.root]
newDepth = []
while len(currentDepth) > 0:
node = currentDepth.pop(0)
if node.left:
newDepth.append(node.left)
if node.right:
newDepth.append(node.right)
if len(currentDepth) > 0:
print(node.value, end=' ')
else:
currentDepth = newDepth
newDepth = []
print(node.value)
def randomNode(self):
current = self.root
while current:
options = ['self', 'left', 'right']
weights = [1, current.leftSize, current.rightSize]
outcome = random.choices(options, weights)[0]
if outcome == 'self':
return current
elif outcome == 'left':
current = current.left
else:
current = current.right | UTF-8 | Python | false | false | 6,016 | py | 49 | 11.py | 49 | 0.488364 | 0.486037 | 0 | 177 | 32.99435 | 351 |
sembly1985/Sembly_LIB | 17,892,833,757,276 | ec630e9e3638d48770038443a560dee5541ba079 | de93d65c044ea5d27324c63658ca328c095ac4fe | /Software/Python/EmbeddedSystem/runTime.py | 402947f2b3207ce55dc80b4dc0c0f111a3ea64c0 | []
| no_license | https://github.com/sembly1985/Sembly_LIB | b99d326917bfc63619b7f686b9d867347cd05cf5 | ac8e0a5d7ae7a92f1667e962a3890b653bffe6bf | refs/heads/master | 2021-06-01T17:49:55.136022 | 2020-07-31T07:34:17 | 2020-07-31T07:34:17 | 94,499,009 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 06 14:54:14 2016
@author: WANGSP1
"""
from datetime import datetime
class runTime:
startTime=datetime.now();
def __init__(self):
self.startTime=datetime.now();
def DeltaMiniTime(self):
curTime=datetime.now();
delta=curTime-self.startTime;
return (delta.seconds*1000000+delta.microseconds)*1.0/1000; | UTF-8 | Python | false | false | 391 | py | 23 | runTime.py | 10 | 0.649616 | 0.580563 | 0 | 16 | 23.5 | 67 |
chiluen/ManTraNet_2020 | 10,316,511,462,274 | d0b6f6c13cce124802e69f9594fea3d89b059c4e | b6c3362907ed756f4b831b90ae14551b24f6133a | /removal.py | f0fb55237bd35d817017cc17f4cec0bf38d48961 | []
| no_license | https://github.com/chiluen/ManTraNet_2020 | 3d1e142c468d65939a0f55139bac8c7fe7e4f37e | 8183af6874c53ca0a8250c83b32ffa54d665de44 | refs/heads/master | 2022-12-02T09:45:14.387607 | 2020-08-14T06:46:32 | 2020-08-14T06:46:32 | 276,780,522 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import numpy as np
import cv2
from PIL import Image
import random
from torchvision import transforms as T
def translate(image, x, y):
M = np.float32([[1, 0, x], [0, 1, y]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
return shifted
def rotate(image, angle, center=None, scale=1.0):
# 获取图像尺寸
(h, w) = image.shape[:2]
# 若未指定旋转中心,则将图像中心设为旋转中心
if center is None:
center = (w / 2, h / 2)
# 执行旋转
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
# 返回旋转后的图像
return rotated
def get_random_crop(image, crop_height, crop_width):
max_x = image.shape[1] - crop_width
max_y = image.shape[0] - crop_height
x = np.random.randint(0, max_x)
y = np.random.randint(0, max_y)
crop = image[y: y + crop_height, x: x + crop_width]
return crop
class Mask():
def __init__(self, mask_folder):
self.mask_folder = mask_folder
self.masks = os.listdir(mask_folder)
def __call__(self):
pth = os.path.join(self.mask_folder, random.choice(self.masks))
mk = cv2.imread( pth, cv2.IMREAD_GRAYSCALE)[...,::-1]
mk = (1-mk)/255
_,thsh = cv2.threshold(mk, 0.6, 1, cv2.THRESH_BINARY)
num = random.randint(3, 7)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(num, num))
dilated = cv2.dilate(thsh, kernel)
num = [random.randint(-100,100)for i in range(2)]
shifted = translate(dilated, num[0], num[1])
num = random.randint(0, 180)
rotated = rotate(shifted, num)
cropped = get_random_crop(rotated, 256, 256)
if np.array_equal(np.zeros((256,256)), cropped):
masking = self.__call__()
else:
masking = cropped
return masking.astype('float32')
# def removal(img_folder = '/home/jayda960825/Documents/Dresden/Dresden_JPEG/',
# removal_folder = '/home/jayda960825/Documents/removal/'):
# imgs = os.listdir(img_folder)
# for i in imgs:
# masking = mask()
# masking = masking.astype('uint8')
# pth = img_folder + i
# img = cv2.imread(pth, 1)[...,::-1]
# img = get_random_crop(img, 256, 256)
# output = cv2.inpaint(img,masking,3,cv2.INPAINT_NS)
# cv2.imwrite(removal_folder + i[:-4] + '.jpg', output)
# masking = masking*255
# cv2.imwrite(removal_folder+ i[:-4] + '_mask.png', masking)
class Removal():
def __init__(self, mask_folder):
self.mask = Mask(mask_folder)
def __call__(self, img):
masking = self.mask()
output = cv2.inpaint(np.uint8(img),masking.astype('uint8'),3,cv2.INPAINT_NS)
return output, masking
class RemoveTransform():
def __init__(self, mask_folder):
self.removal = Removal(mask_folder)
def __call__(self, img):
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) # from PIL Image to cv2
img, masking = self.removal(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return Image.fromarray(img), masking
# Usage Example
# from torchvision import transforms
# data_transforms = transforms.Compose([
# RemoveTransform('path/to/mask_folder'),
# transforms.ToTensor()
# ])
def removal(img, mask_folder):
masking = mask(mask_folder)
masking = masking.astype('uint8')
output = cv2.inpaint(np.uint8(img),masking,3,cv2.INPAINT_NS)
#cv2.imwrite('/home/jayda960825/Desktop/mask.png', masking*255)
return output
def rm_transform(mask_folder = '/home/jayda960825/Documents/irregular_mask/disocclusion_img_mask/'):
data_transforms = T.Compose([
T.Lambda(lambda img: removal(img, mask_folder)),
T.ToTensor()
])
return data_transforms
| UTF-8 | Python | false | false | 3,849 | py | 57 | removal.py | 49 | 0.612039 | 0.5773 | 0 | 122 | 29.909836 | 100 |
wall-e-08/medigap-wagtail | 7,765,300,912,793 | a47d0743d7ce18ee7dfb9c5e8c2cb81d26c08c0c | bfa100593b7fc67ae65593bdddb357fa3d9e27cf | /quotes/forms.py | a4bc688ba983395813b3940fa3e374002e2f0380 | []
| no_license | https://github.com/wall-e-08/medigap-wagtail | e2342631004de047a4b3d09571dd88f2a6fc2286 | 1d7b77759f071eec89e29591e814523d4c433655 | refs/heads/master | 2020-05-20T17:27:43.966094 | 2019-04-30T06:25:58 | 2019-04-30T06:25:58 | 185,688,386 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import string
import datetime
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from .models import Lead
class LeadForm(forms.Form):
APPLICANT_MAX_AGE = 64
APPLICANT_MIN_AGE = 2
first_name = forms.CharField(required=True,)
# middle_name = forms.CharField(required=False,)
last_name = forms.CharField(required=True,)
email = forms.CharField(required=True,)
phone = forms.CharField(required=True,)
state = forms.ChoiceField(
choices=settings.US_STATES,
required=True
)
# alternate_phone = forms.CharField(required=True,)
# date_of_birth = forms.DateField(
# input_formats=['%m-%d-%Y', '%m/%d/%Y'],
# required=True,
# )
zip_code = forms.CharField(required=True,)
# @staticmethod
# def age(date_of_birth):
# today = datetime.date.today()
# if today.month < date_of_birth.month or (today.month == date_of_birth.month and today.day < date_of_birth.day):
# return today.year - date_of_birth.year - 1
# return today.year - date_of_birth.year
def clean_zip_code(self):
zip_code = self.cleaned_data['zip_code']
if not zip_code:
return None
for char in zip_code:
if char not in string.digits:
raise forms.ValidationError(_("Invalid zip code"))
if len(zip_code) != 5:
raise forms.ValidationError(_('Invalid zip code'))
return zip_code
# def clean_date_of_birth(self):
# date_of_birth = self.cleaned_data['date_of_birth']
# if not date_of_birth:
# return None
# if date_of_birth > datetime.date.today():
# print(datetime.date.today())
# raise forms.ValidationError(_("Future Date is not a valid Date of Birth"), code='invalid')
# if self.age(date_of_birth) > self.APPLICANT_MAX_AGE:
# raise forms.ValidationError(_("Applicant maximum age is {} years.".format(self.APPLICANT_MAX_AGE)), code='limit')
# if self.age(date_of_birth) < self.APPLICANT_MIN_AGE:
# raise forms.ValidationError(_("Applicant minimum age is {} years.".format(self.APPLICANT_MIN_AGE)), code='limit')
# return date_of_birth
| UTF-8 | Python | false | false | 2,287 | py | 77 | forms.py | 65 | 0.623087 | 0.620901 | 0 | 59 | 37.762712 | 127 |
danoctavian/fuckarounds | 7,739,531,072,845 | 36aa1a85ee2c259937d2bf4de74321b2c15cd3ba | eb8608848fac8585754aea87f9efa8f683e33c25 | /codeforces/A.py | 456102ab269583da81a25cb0eec8dac46d20ceb6 | []
| no_license | https://github.com/danoctavian/fuckarounds | 5f9eabc0e58030e50940dca138ea429025d365eb | 565a1d6131148f45604b155fb187ca1ac07a11b8 | refs/heads/master | 2020-04-16T07:19:32.416654 | 2014-02-06T03:09:40 | 2014-02-06T03:09:40 | 10,093,991 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | nums = raw_input()
[a, b] = map(lambda x: int(x), nums.split())
h = 0
while a >= b:
h = h + b
a = a - b
a += 1
h = h + a
print h
| UTF-8 | Python | false | false | 141 | py | 55 | A.py | 31 | 0.446809 | 0.432624 | 0 | 10 | 12.8 | 44 |
tojewel/MAMS-for-ABSA | 5,342,939,359,251 | ec81211e92fe24af003b5fff5ee3cda22c2f0129 | efa42f7fe156db3a61e2d0c74a7daca7c2b0d6a0 | /src/module/utils/constants.py | 4b2cbfc91fe56da9262935a41cb1bc130eeecb47 | [
"Apache-2.0"
]
| permissive | https://github.com/tojewel/MAMS-for-ABSA | 7b707736801d499ef797d5e240d7692d8b00e59f | d4e4dda751161f729ca9cce7cea2e58845e46f04 | refs/heads/master | 2022-11-14T01:19:29.897269 | 2020-07-08T09:09:23 | 2020-07-08T09:09:23 | 278,039,394 | 0 | 0 | Apache-2.0 | true | 2020-07-08T08:54:21 | 2020-07-08T08:54:21 | 2020-07-01T01:09:08 | 2019-11-04T08:10:21 | 936 | 0 | 0 | 0 | null | false | false | PAD = '<pad>'
UNK = '<unk>'
ASPECT = '<aspect>'
PAD_INDEX = 0
UNK_INDEX = 1
ASPECT_INDEX = 2
INF = 1e9 | UTF-8 | Python | false | false | 104 | py | 21 | constants.py | 19 | 0.576923 | 0.528846 | 0 | 9 | 10.666667 | 19 |
AshenHermit/get_off_this_board | 4,123,168,615,296 | aac5289f6caf0fed63e00af2a8d1d76d965a5dcf | 42190f68d748c42b281e9765c03b870989dd958d | /launcher.py | bf6fe1a54a0261c607171094efb92770940f50db | []
| no_license | https://github.com/AshenHermit/get_off_this_board | 46156f251a4b008299ea39ef261054cc5784906e | 04658c0c0bbf44b26b8cecc9dde9ed010e1e0a22 | refs/heads/master | 2023-04-07T12:09:27.162697 | 2021-04-17T12:01:10 | 2021-04-17T12:01:10 | 352,336,813 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import time
import os
import argparse
import requests
import json
import subprocess
import ctypes
from threading import Timer
import math
class Launcher():
def __init__(self, raw_files_root_url="", _debug=False):
self.raw_files_root_url = raw_files_root_url
self.DEBUG = _debug
with open("launcher_config.json", "r+") as file:
self.config = json.load(file)
self.src_path = self.config['src_path']
def update_src_config(self):
src_config = None
with open(self.src_path+"/config.json", "r+") as file:
src_config = json.load(file)
src_config['debug'] = self.DEBUG
with open(self.src_path+"/config.json", "w+") as file:
json.dump(src_config, file)
def get_download_files_list(self):
url = self.raw_files_root_url + "/files_list.txt"
config = requests.get(url).text
config = config.split("\n")
config = list(filter(lambda x: x.replace(" ", "")!="", config))
return config
def make_dirs(self, path):
path = path[:path.rfind("/")]
os.makedirs(path, exist_ok=True)
def download_files(self, files_list):
print('downloading...')
count = 0
for file_path in files_list:
count+=1
print(f'[ {math.floor((count / len(files_list))*100)}% ] Downloading: {file_path} ...')
raw_file_url = self.raw_files_root_url + "/" + file_path
file_path = self.src_path + file_path[file_path.find("/"):]
self.make_dirs(file_path)
with open(file_path, "wb") as file:
content = requests.get(raw_file_url).content
file.write(content)
print("done.")
def download_required_files(self):
files_list = self.get_download_files_list()
self.download_files(files_list)
def launch_without_console(self, command):
"""Launches 'command' windowless and waits until finished"""
def hide_console():
pass
subprocess.call(command, shell=True)
# os.system(command)
def launch(self):
self.update_src_config()
run_commands = ""
with open(f"./{self.src_path}/run_commands.txt", "r+", encoding="utf-8") as file:
run_commands = file.read()
run_commands = run_commands.split("\n")
os.chdir(self.src_path)
for command in run_commands:
self.launch_without_console(command)
def debug_main():
launcher = Launcher("", True)
launcher.launch()
def main():
launcher = Launcher("https://raw.githubusercontent.com/AshenHermit/get_off_this_board/master", False)
launcher.download_required_files()
launcher.launch()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", action="store_true")
args = parser.parse_args()
# constant debug argument
# args.debug = True
if not args.debug:
main()
else:
debug_main() | UTF-8 | Python | false | false | 3,054 | py | 16 | launcher.py | 10 | 0.582187 | 0.580223 | 0 | 108 | 27.287037 | 105 |
pablovillauy/pythonbasics | 10,376,640,991,048 | 56f149010630a94d381d348fa45cf7cd753dc99e | 2748f72fd485f3d569a19a2c30a2061545a1f54e | /dictionaries.py | 220e2d238a4fbafd546a82ad143cbd9254dd8051 | []
| no_license | https://github.com/pablovillauy/pythonbasics | ff3e956a8f1136650163439a43cb17e8585b6e2d | 80b49b528d6697f91a2f93639419c3857e11ee27 | refs/heads/master | 2021-03-08T13:08:23.836774 | 2020-04-10T13:59:13 | 2020-04-10T13:59:13 | 246,347,525 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # key-value pairs
cart = {
"name":"book",
"quantity":3,
"price": 4.99
}
person ={
"first_name":"ryan",
"last_name":"ray"
}
print(dir(cart))
print(person.keys())
print(person.items())
# list of dictionaries
products = [
{"name":"book", "price":10.99},
{"name":"laptop", "price":1000}
] | UTF-8 | Python | false | false | 339 | py | 17 | dictionaries.py | 15 | 0.522124 | 0.486726 | 0 | 23 | 12.826087 | 35 |
ozamanan/teHmm | 14,963,666,082,419 | 5360408f4c45b4bf7b93a930c2ee98fedf7786b8 | d8529efc2bfbd58531e4e0bca786b68370a215da | /bin/cleanRM.py | b1c3674abca35f4b0e37e77ab94fadecdb36754d | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
]
| permissive | https://github.com/ozamanan/teHmm | c4ae4a89252623f75a66af661b8e0dadb5f82766 | bb82e891b5c1562929c43845f4f467f24ff21e29 | refs/heads/master | 2020-09-11T19:45:44.040920 | 2015-05-21T21:41:30 | 2015-05-21T21:41:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
#Copyright (C) 2013 by Glenn Hickey
#
#Released under the MIT license, see LICENSE.txt
import sys
import os
import argparse
import re
from pybedtools import BedTool, Interval
from teHmm.common import myLog, EPSILON, initBedTool, cleanBedTool
from teHmm.common import runShellCommand, getLocalTempPath
"""
Remove everything past the first occurence of | / ? _ in the name column
This is used to clean the names from the various RepeatMasker
(via repeatmasker_to_bed.sh) tracks (formerly called cleanChaux.py)
"""
def main(argv=None):
if argv is None:
argv = sys.argv
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Cut names off at first |, /, ?, or _")
parser.add_argument("inBed", help="bed with chaux results to process")
parser.add_argument("--keepSlash", help="dont strip anything after slash "
"ex: DNA/HELITRONY1C -> DNA", action="store_true",
default=False)
parser.add_argument("--keepUnderscore", help="dont strip anything after _ ",
action="store_true", default=False)
parser.add_argument("--leaveNumbers", help="by default, numbers as the end"
" of names are trimmed off. ex: DNA/HELITRONY1C -> "
" DNA/HELITRONY. This option disables this behaviour",
default=False)
parser.add_argument("--mapPrefix", help="Rename all strings with given "
"prefix to just the prefix. ex: --mapPrefix DNA/HELI"
" would cause any instance of DNA/HELITRONY1C or "
"HELITRON2 to be mapped to just DNA/HELI. This option"
" overrides --keepSlash and --leaveNumbers for the"
" elements to which it applies. This option can be"
" specified more than once. ex --mapPrefix DNA/HELI "
"--maxPrefix DNA/ASINE.", action="append")
parser.add_argument("--minScore", help="Minimum score value to not filter"
" out", default=-sys.maxint, type=float)
parser.add_argument("--maxScore", help="Maximum score value to not filter"
" out", default=sys.maxint, type=float)
parser.add_argument("--overlap", help="Dont run removeBedOverlaps.py",
action="store_true", default=False)
args = parser.parse_args()
assert os.path.exists(args.inBed)
assert args.minScore <= args.maxScore
tempBedToolPath = initBedTool()
tempPath = getLocalTempPath("Temp_cleanOut", ".bed")
tempPath2 = getLocalTempPath("Temp2_", ".bed")
tempFile = open(tempPath, "w")
for interval in BedTool(args.inBed).sort():
# filter score if exists
try:
if interval.score is not None and\
(float(interval.score) < args.minScore or
float(interval.score) > args.maxScore):
continue
except:
pass
prefix = findPrefix(interval.name, args.mapPrefix)
if prefix is not None:
# prefix was specified with --mapPrefix, that's what we use
interval.name = prefix
else:
# otherwise, strip after |
if "|" in interval.name:
interval.name = interval.name[:interval.name.find("|")]
# strip after ?
if "?" in interval.name:
interval.name = interval.name[:interval.name.find("?")]
#strip after _ unlerss told not to
if "_" in interval.name and args.keepUnderscore is False:
interval.name = interval.name[:interval.name.find("_")]
# strip after "/" unless told not to
if "/" in interval.name and args.keepSlash is False:
interval.name = interval.name[:interval.name.find("/")]
# strip trailing digits (and anything after) unless told not to
if args.leaveNumbers is False:
m = re.search("\d", interval.name)
if m is not None:
interval.name = interval.name[:m.start()]
tempFile.write(str(interval))
tempFile.close()
if not args.overlap:
runShellCommand("removeBedOverlaps.py %s --rm > %s" % (tempPath,
tempPath2))
tempPath, tempPath2, = tempPath2, tempPath
tempFile = open(tempPath, "r")
for line in tempFile:
sys.stdout.write(line)
tempFile.close()
runShellCommand("rm -f %s %s" % (tempPath, tempPath2))
cleanBedTool(tempBedToolPath)
# should be a prefix tree...
def findPrefix(name, plist):
if plist is None:
return None
for p in plist:
if name[:len(p)] == p:
return p
return None
if __name__ == "__main__":
sys.exit(main())
| UTF-8 | Python | false | false | 4,982 | py | 149 | cleanRM.py | 78 | 0.5833 | 0.58049 | 0 | 121 | 40.173554 | 80 |
wewendeng/webdriver_guid | 7,851,200,231,499 | a9756a3b956e4079d1c4da74f2601d528735b3a1 | 7d7bc02851bd5a3a99652c2bcd82e4549be67736 | /03maximize_browser.py | 17f23796f52656c56559b5fe5b7d7065d952aa37 | []
| no_license | https://github.com/wewendeng/webdriver_guid | 2f840e7933fd4f3444c71de53dec0c0dd58f31e0 | 985377bc697e92ac7eb3e5cc24af195ac3be5fbf | refs/heads/master | 2020-06-12T17:51:53.375338 | 2019-06-29T07:43:48 | 2019-06-29T07:43:48 | 194,378,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from selenium import webdriver
import time
driver = webdriver.Chrome()
time.sleep(2)
print("maximize browser")
driver.maximize_window()
time.sleep(2)
print("close browser")
driver.quit()
| UTF-8 | Python | false | false | 191 | py | 34 | 03maximize_browser.py | 34 | 0.759162 | 0.748691 | 0 | 13 | 13.692308 | 30 |
Marrrcy/uap | 10,780,367,935,115 | 5abd0d975d80357f0ec85f7fa0dc4d26e74cf169 | 283ee2715d095e2a832104a5613a1dbb4e3d7f57 | /MetodeBayar.py | 630377953cfa751f141b3cd844b1217d4304b23a | []
| no_license | https://github.com/Marrrcy/uap | 9a957a4a2d5039f5e96881d53d19b9d104e3a889 | 8e189f2e23dbb05af54119c08fe91ff01916d190 | refs/heads/master | 2020-08-28T08:43:32.642701 | 2020-04-29T04:46:05 | 2020-04-29T04:46:05 | 217,652,441 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import Review
import os
#Tambahan baru:
import time
import random
# cek pembayaran
def CekBayar(ListReview,GameName):
codes = ["XXYY12", "BQQPR1", "MMR20K", "MMR900", "MMR1DI", "MMRR69", "69A420"]
while True:
print("\n>>>Misalkan user mendapatkan email yang berisi kode pembayarannya<<<\n")
print(">>>Di dalam email user:<<<\n")
print("Thank you for purchase, congratulations on your new game.")
print("We hope you can enjoy the game to its fulless.")
print("This is your payment code:", codes[random.randint(0,len(codes)-1)])
print("\n>>>Akhir dari email user<<<\n")
time.sleep(5)
print("Please check your email for your payment code.")
code = input("\nPlease enter the payment code (enter 2 to cancel): ")
code = code.upper()
if(code in codes):
Review.PendapatGame(ListReview,GameName)
break
elif (code == "2"):
return None
else:
print("The payment code is wrong.")
def Transfer(ListReview,GameName):
print("\n1. BCB\t4. Mundiri \n2. BMI\t5. Berlian \n3. BERI\t6. Cancel\n")
pilih1 = int(input("Please choose the destination Bank: "))
if(pilih1 == 1):
print("Please transfer to account number: 1234567890 (Uap Beruap) of bank BCB")
print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
CekBayar(ListReview,GameName)
elif(pilih1 == 2):
print("Please transfer to account number: 2345678901 (Uap Beruap) of bank Mundiri")
print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
CekBayar(ListReview,GameName)
elif(pilih1 == 3):
print("Please transfer to account number: 3456789010 (Uap Beruap) of bank BMI")
print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
CekBayar(ListReview,GameName)
elif(pilih1 == 4):
print("Please transfer to account number: 4567890101 (Uap Beruap) of bank Berlian")
print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
CekBayar(ListReview,GameName)
elif(pilih1 == 5):
print("Please transfer to account number: 5678901011 (Uap Beruap) of bank Beri")
print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
CekBayar(ListReview,GameName)
elif(pilih1 == 6):
print("The payment method has been canceled.")
return None
else:
# print("Masukkan angka 1 sampai 6 saja.")
# print("Mohon maaf untuk pilihan bank lain masih belum tersedia, silahkan pilih cara pembayaran lainnya.")
print("Please only input number 1 through 6.")
print("We are sorry, but the bank of your choice is not yet available, please choose another payment option.")
def Pulsa():
# print("\n1.Buka menu panggilan dan ketikkan kode *858# dan tekan panggil/OK \n2.Ketik angka 1 untuk pilihan Transfer Pulsa \n3.Masukkan 081233558800 dan nominal pulsa yang harus dibayarkan \n4.Setelah muncul notifkasi pada layar, masukkan angka 1 untuk konfirmasi ")
print("\n1.Open the menu Calls on your phone and insert code *858# and press call/OK \n2.Press number 1 to choose transferthe credit \n3.Insert 081233558800 and the amount of credits to be paid \n4.After a notification appeared on your screen, press number 1 to confirm. A code will then be send to you.")
def Ovo():
# print("\n1.Buka aplikasi OPO anda \n2.Masukkan security pin anda \n3.Pilih menu transfer \n4.Masukkan nominal yang harus dibayarkan \n5.Pilih antar OPO \n6.Masukkan nomor 085335588811 \n7.Konfirmasi\n8.Masukkan kode security pin ")
print("\n1.Open your OPO application \n2.Insert your security pin \n3.Choose transfer \n4.Insert the amount that has to be paid \n5.Choose Between OPO \n6.Insert number 085335588811 \n7.Confirm\n8.Insert your security pin. A code will then be send to you")
def Gopay():
# print("\n1.Buka aplikasi Gopek anda \n2.Masukkan security pin anda \n3.Pilih menu bayar \n4.Masukkan nomor 081233565700 \n5.Masukkan nominal yang harus dibayarkan \n6.Klik konfirmasi \n7.Pilih bayar \n8.Masukkan kode security pin ")
print("\n1.Open your Gopek application \n2.Insert your security pin \n3.Choose the pay option \n4.Insert the number 081233565700 \n5.Insert the amount that has to be paid \n6.Click confirm \n7.Choose pay \n8.Insert your security pin")
def Dana():
# print("\n1.Buka aplikasi DANAS anda \n2.Masukkan security pin anda \n3.Pilih menu send \n4.Masukkan nominal yang harus dibayarkan \n5.Masukkan nomor 0833575800 \n6.Pilih send DANAS \n7.Konfirmasi\n8.Masukkan kode security pin")
print("\n1.Open your DANAS application \n2.Insert your security pin \n3.Choose the send menu \n4.Insert the amount that has to be paid \n5.Insert the number 0833575800 \n6.Choose send DANAS \n7.Confirm \n8.Insert your security pin")
# def main():
# while True:
# print("Payment methods:")
# print("\n1. Money Transfer\t4. Prepaid telephone credit (Telekomunikasi only) \n2. OPO\t\t\t5. Gopek \n3. DANAS\t\t6. Cancel")
# pilih0 = int(input("Your choice: "))
# if(pilih0 == 1):
# print("\n1. BCB\t4. Mundiri \n2. BMI\t5. Berlian \n3. BERI\t6. Cancel")
# pilih1 = int(input("Please choose the destination Bank: "))
# if(pilih1 == 1):
# print("Please transfer to account number: 1234567890 (Uap Beruap) of bank BCB")
# print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
# CekBayar()
# elif(pilih1 == 2):
# print("Please transfer to account number: 2345678901 (Uap Beruap) of bank Mundiri")
# print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
# CekBayar()
# elif(pilih1 == 3):
# print("Please transfer to account number: 3456789010 (Uap Beruap) of bank BMI")
# print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
# CekBayar()
# elif(pilih1 == 4):
# print("Please transfer to account number: 4567890101 (Uap Beruap) of bank Berlian")
# print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
# CekBayar()
# elif(pilih1 == 5):
# print("Please transfer to account number: 5678901011 (Uap Beruap) of bank Beri")
# print("After that send the payment confirmation to our customer service and then you will recieve the payment code")
# CekBayar()
# elif(pilih1 == 6):
# print("The payment method has been canceled.")
# else:
# print("Masukkan angka 1 sampai 6 saja.")
# print("Mohon maaf untuk pilihan bank lain masih belum tersedia, silahkan pilih cara pembayaran lainnya.")
# elif(pilih0 == 2):
# print("\n1.Buka aplikasi OPO anda \n2.Masukkan security pin anda \n3.Pilih menu transfer \n4.Masukkan nominal yang harus dibayarkan \n5.Pilih antar OPO \n6.Masukkan nomor 085335588811 \n7.Konfirmasi\n8.Masukkan kode security pin ")
# CekBayar()
# elif(pilih0 == 3):
# print("\n1.Buka aplikasi DANAS anda \n2.Masukkan security pin anda \n3.Pilih menu send \n4.Masukkan nominal yang harus dibayarkan \n5.Masukkan nomor 0833575800 \n6.Pilih send DANAS \n7.Konfirmasi\n8.Masukkan kode security pin")
# CekBayar()
# elif(pilih0 == 4):
# print("\n1.Buka menu panggilan dan ketikkan kode *858# dan tekan panggil/OK \n2.Ketik angka 1 untuk pilihan Transfer Pulsa \n3.Masukkan 081233558800 dan nominal pulsa yang harus dibayarkan \n4.Setelah muncul notifkasi pada layar, masukkan angka 1 untuk konfirmasi ")
# CekBayar()
# elif(pilih0 == 5):
# print("\n1.Buka aplikasi Gopek anda \n2.Masukkan security pin anda \n3.Pilih menu bayar \n4.Masukkan nomor 081233565700 \n5.Masukkan nominal yang harus dibayarkan \n6.Klik konfirmasi \n7.Pilih bayar \n8.Masukkan kode security pin ")
# CekBayar()
# elif(pilih0 == 6):
# print("Pembayaran telah dibatalkan.")
# os.system("clear")
# # os.system("cls")
# break
# else:
# print("Maaf metode pembayaran yang anda inginkan masih belum ada, silahkan memilih salah satu dari cara-cara diatas.") | UTF-8 | Python | false | false | 9,044 | py | 8 | MetodeBayar.py | 6 | 0.656457 | 0.609907 | 0 | 135 | 65.007407 | 311 |
janikgar/protonmail-cli | 5,815,385,733,543 | bc812126607469aa0cf7df2c76e5069f88d530b3 | 468bcafa4a6e173a6d52c1ccf671b3c96d2dcefe | /protonmail-cli.py | 8334a8f4e2b76a5339c8566e16946f872193efd1 | []
| no_license | https://github.com/janikgar/protonmail-cli | e8b1adfa013afb99990ea08fc6a532e81a9a567b | f5bf9e84e9c9659707415bd56456ccea5a08795b | refs/heads/master | 2020-03-28T02:11:59.417297 | 2018-09-05T00:04:10 | 2018-09-05T00:04:10 | 147,554,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os, datetime, time, hashlib, sys
import settings
from bs4 import BeautifulSoup as bs4
from pyvirtualdisplay.display import Display
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
def tail(filename, n):
"""Keep last :n lines of file specified by :filename"""
tmpf = "pr-cli.tmp"
(os.system(cmd) for cmd in [
"tail -%d %s > %s" % (n, filename, tmpf),
"cp %s %s; rm %s" % (tmpf, filename, tmpf)
])
def log(msg, reason="DEBUG"):
"""If settings.logfile is set write :msg in logfile else
write in standard output"""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = "[%s] %s: %s" % (reason, timestamp, msg)
if settings.logfile and os.path.exists(settings.logfile):
tail(settings.logfile, settings.logfile_rows_keep)
if settings.logfile:
open_type = 'w'
if os.path.exists(settings.logfile):
open_type = 'a'
print(log_entry, file=open(settings.logfile, open_type))
else:
print(log_entry)
def try_until_elem_appears(elem_val, elem_type="id"):
"""web driver helper utility used to wait until the page is fully
loaded.
Tries to find the element specified by :elem_val
where :elem_val can be of :elem_type 'id', 'class' or 'css'.
Returns True if element was found in time else False
After :settings.max_retries number of times stops trying"""
retries = 0
time.sleep(0.5)
while True:
try:
if retries > settings.max_retries:
break
if elem_type == "id":
driver.find_element_by_id(elem_val)
elif elem_type == "class":
driver.find_element_by_class_name(elem_val)
elif elem_type == "css":
driver.find_element_by_css_selector(elem_val)
else:
raise ValueError("Unknown elem_type")
return True
except NoSuchElementException:
log("waiting...")
retries += 1
time.sleep(settings.load_wait)
return False
def login():
"""Login to protonmail panel
using credentials from :settings.py
Returns True or False wether login was succesful
"""
log("Open login page")
driver.get("https://protonmail.com/login")
try_until_elem_appears("username")
log("Login page loaded")
username_input = driver.find_element_by_id("username")
password_input = driver.find_element_by_id("password")
username_input.send_keys(settings.username)
password_input.send_keys(settings.password)
password_input.send_keys(Keys.RETURN)
log("Login credentials sent")
return try_until_elem_appears("conversation-meta", "class")
def read_mails():
"""Read and return a list of mails from the main
protonmail page (after login)"""
soup = bs4(driver.page_source, "html.parser")
mails_soup = soup.select(".conversation-meta")
mails = []
for mail in mails_soup:
try:
mails.append({
"title": mail.select(".subject")[0].get("title"),
"time": mail.select(".time")[0].string,
"name": mail.select(".senders-name")[0].string,
"mail": mail.select(".senders-name")[0].get("title")
})
except Exception as e:
log(str(e), "ERROR")
continue
mails = mails[:settings.mails_read_num]
if settings.date_order == "asc":
return reversed(mails)
return mails
def check_for_new_mail(mails):
"""Receives a list of mails and generates a unique hash.
If the hash is different from the previous call of this function
then a new mail was received.
@TODO @BUG in case we delete an email then the hash will be changed
and we'll get a new mail notification.
"""
hash_filename = ".protonmail-cli-mails-hash"
old_hash = ""
if os.path.exists(hash_filename):
old_hash = open(hash_filename, "r").readline()
new_hash = hashlib.sha256(str(mails).encode()).hexdigest()
if old_hash and new_hash != old_hash:
log("New message arrived")
os.system("notify-send 'You received a new message on your ProtonMail inbox'")
else:
log("You don't have new messages")
with open(hash_filename, "w") as f:
f.write(new_hash)
def print_usage():
print("""
NAME
protonmail-cli - Protonmail CLI tool
SYNOPSIS
protonmail-cli [OPTION]
DESCRIPTION
protonmail-cli list-inbox
Prints the latest mail titles
protonmail-cli check-inbox
Checks for new message and displays a system notification
check period is defined in settings.py
protonmail-cli help
Prints this dialog
""")
def print_mail(mail):
"""Prints a mail entry as described in :read_mails"""
out = "[" + mail.get("time") + "] " + mail.get("name")
if mail.get("mail") != mail.get("name"):
out += " " + mail.get("mail")
out += "\n" + mail.get("title") + "\n"
print(out)
def run():
if len(sys.argv) > 1:
if login():
log("Logged in succesfully")
else:
log("Unable to login", "ERROR")
return
op = sys.argv[1]
if op == "list-inbox":
for mail in read_mails():
print_mail(mail)
elif op == "check-inbox":
while True:
mails = read_mails()
check_for_new_mail(mails)
if settings.check_mail_period == 0:
break
else:
time.sleep(settings.check_mail_period)
elif op == "help":
print_usage()
else:
print("Operation not valid")
print_usage()
return
print_usage()
if __name__ == "__main__":
display = None
if not settings.show_browser:
display = Display(visible=0, size=(1366, 768))
display.start()
driver = webdriver.Firefox()
try:
run()
except Exception as e:
log(str(e), "ERROR")
driver.close()
if display is not None:
display.stop()
| UTF-8 | Python | false | false | 6,349 | py | 3 | protonmail-cli.py | 2 | 0.579461 | 0.575524 | 0 | 229 | 26.724891 | 86 |
dsc-upt/opportunity-backend | 10,771,777,994,080 | 5947221c2a1448d20783b08138c3ca3d22a3c34d | 810e01b2d7f45e69cf34c7eca3d845ab1c1092a3 | /src/createsuperuser.py | dc2ddb9910866f132ececd4ff0587b7da123e530 | [
"Apache-2.0"
]
| permissive | https://github.com/dsc-upt/opportunity-backend | 5fcf101196eb10a4013ee95e48b6bce51cbb0341 | 571bee2d8ba4bd43d0ca8c46cad346d055745108 | refs/heads/main | 2023-08-02T15:54:15.311824 | 2021-10-06T05:33:14 | 2021-10-06T05:33:14 | 318,819,417 | 5 | 2 | Apache-2.0 | false | 2021-01-29T23:07:11 | 2020-12-05T15:16:44 | 2021-01-29T16:25:04 | 2021-01-29T23:07:10 | 760 | 1 | 1 | 6 | Python | false | false | from django.contrib.auth import get_user_model
from django.db.utils import IntegrityError
username = 'admin'
email = 'admin@example.com'
password = 'admin'
try:
get_user_model().objects.create_superuser(username, email, password)
except IntegrityError:
print("User '%s <%s>' already exists" % (username, email))
else:
print("Created superuser '%s <%s>' with password '%s'" % (username, email, password))
| UTF-8 | Python | false | false | 418 | py | 42 | createsuperuser.py | 31 | 0.712919 | 0.712919 | 0 | 13 | 31.153846 | 89 |
rfsip/learnpython | 19,705,309,955,618 | d770dae2364d0f0a7acc73025f435ae720dde4d3 | 76df8b5fbbafaafeba585db013f29fb05427df44 | /STRING.py | 7cbf02f0f88a4c43007e21240d9156fd0c487594 | []
| no_license | https://github.com/rfsip/learnpython | f911750719e8314d4440380890b023c5e04bee9b | ffecdb2ca1d169741948b9eeab6a38ecbfaa3687 | refs/heads/master | 2021-01-20T12:22:59.619955 | 2017-06-02T12:51:26 | 2017-06-02T12:51:26 | 90,357,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding:utf-8
'''
UTF-8:可变长编码
在计算机内存中,统一使用unicode编码,保存到硬盘或传输时转换为UTF-8.
python3 的字符串是采用unicode 编码
对于单个字符,ord() 获取字符的整数表示,chr()把整数编码转化为相应字符。
>>>ord('A')
65
>>>chr(65)
'A'
采用十六进制编码形式表示
>>>'\u4e2d'
'中'
对字符串进行编码和解码:
>>>'中文'.encode('UTF-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('UTF-8')
'中文'
str函数:
len()计算字符数,换为bytes,计算字节数
>>> len('中文')
2
>>> len('zhong文')
6
>>> len('中'.encode('UTF-8'))
3
格式化字符串:%d %f %s %x(十六进制整数),不确定用什么就用%s
>>> '%.2f'%3.1415926
'3.14'
转义'%':%%
'''
#练习,字符格式化为'xx.x%'
s1 = 72
s2 = 85
r = (85-72)/85*100
print('%.1f%%'%r)
| UTF-8 | Python | false | false | 959 | py | 7 | STRING.py | 7 | 0.534669 | 0.4453 | 0.01849 | 38 | 16.078947 | 52 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.