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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
austintwang/sc_scripts | 13,091,060,350,034 | c56a45d51e23da91777d3655de72ea9caf339c72 | 203ef5dfaaa727c7e247d8cc86c59caf203c436b | /make_star_vcf.py | 444b0b044410f727af8c5ceffc272abdbb8beb53 | [] | no_license | https://github.com/austintwang/sc_scripts | 981f11347d3d98b7263bb158ae73574f12e29820 | c570aea63e816eaa74c0bc50c5db7dc3b57d86d5 | refs/heads/master | 2021-06-27T06:17:07.623384 | 2021-06-11T19:00:46 | 2021-06-11T19:00:46 | 234,782,559 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import pysam
def make_star_vcf(in_path, out_path, min_af):
with open(in_path, "r") as in_file, open(out_path, "w") as out_file:
for line in in_file:
if line.startswith("##"):
continue
cols = line.strip().split()
if cols[0] == "#CHROM":
joined = '\t'.join(cols)
out_file.write(f"{joined}\tFORMAT\tVCF\n")
else:
fields = cols[-1].split(";")
for f in fields:
if f.startswith("AF="):
af = float(f.split("=")[1])
if min_af <= af <= (1 - min_af):
joined = '\t'.join(cols)
out_file.write(f"{joined}\tGT\t0/1\n")
if __name__ == '__main__':
genotypes_dir = "/agusevlab/awang/sc_le/genotypes/"
if not os.path.exists(genotypes_dir):
os.makedirs(genotypes_dir)
in_path = os.path.join(genotypes_dir, "HRC.r1-1.GRCh37.wgs.mac5.sites.vcf")
out_path = "/agusevlab/awang/sc_data/HRC.r1-1.GRCh37.wgs.mac5.maf05.sites.vcf"
make_star_vcf(in_path, out_path, 0.05)
| UTF-8 | Python | false | false | 1,123 | py | 58 | make_star_vcf.py | 58 | 0.505788 | 0.487088 | 0 | 28 | 39.107143 | 82 |
mecrowley/Other-Places-server | 17,033,840,305,921 | 641efab85ae6d757120a1b672822afe243160361 | 35d39ffca4095283e352a53e76d01fc7a65212f9 | /otherplacesapi/views/profile.py | f5ecc65274f90d234daa6195f21eada619e06554 | [] | no_license | https://github.com/mecrowley/Other-Places-server | d3633a4a6e4123795b136e62df823a3022af6de5 | a21199b3cc5fc6d841d92038c5f6637bd565a186 | refs/heads/main | 2023-08-02T10:26:37.192287 | 2021-09-23T14:40:59 | 2021-09-23T14:40:59 | 406,410,676 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """View module for handling requests about park areas"""
import uuid
import base64
from django.core.files.base import ContentFile
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from django.http import HttpResponseServerError
from rest_framework import status, serializers
from django.db.models import Q
from django.contrib.auth.models import User
from otherplacesapi.models import OtherPlacesUser, Follow
class OtherPlacesProfileView(ViewSet):
"""Other Places users"""
def retrieve(self, request, pk=None):
"""Handle GET requests for single user
Returns:
Response -- JSON serialized other places user instance
"""
try:
authuser = OtherPlacesUser.objects.get(user=request.auth.user)
opuser = OtherPlacesUser.objects.get(pk=pk)
following = Follow.objects.filter(Q(opuser=opuser) & Q(follower=authuser))
if following:
opuser.following = True
else:
opuser.following = False
if authuser == opuser:
opuser.isMe = True
else:
opuser.isMe = False
serializer = OtherPlacesUserSerializer(opuser, context={'request': request})
return Response(serializer.data)
except OtherPlacesUser.DoesNotExist as ex:
return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)
except Exception as ex:
return HttpResponseServerError(ex)
def update(self, request, pk=None):
"""Handle PUT requests for a user
Returns:
Response -- Empty body with 204 status code
"""
opuser = OtherPlacesUser.objects.get(user=request.auth.user)
opuser.bio = request.data["bio"]
splitprofilepic = request.data["profile_pic"].split("/")
if splitprofilepic[0] == "http:":
pass
else:
format, imgstr = request.data["profile_pic"].split(';base64,')
ext = format.split('/')[-1]
data = ContentFile(base64.b64decode(imgstr), name=f'{uuid.uuid4()}.{ext}')
opuser.profile_pic = data
opuser.save()
return Response({}, status=status.HTTP_204_NO_CONTENT)
def list(self, request):
"""Handle GET requests to user resource
Returns:
Response -- JSON serialized list of Other Places users
"""
opusers = OtherPlacesUser.objects.all()
authuser = OtherPlacesUser.objects.get(user=request.auth.user)
for opuser in opusers:
if opuser == authuser:
opuser.isMe = True
else:
opuser.isMe = False
serializer = OtherPlacesUserSerializer(
opusers, many=True, context={'request': request})
return Response(serializer.data)
@action(methods=['get'], detail=False)
def myprofile(self, request):
"""Retrieve logged in user's profile"""
try:
opuser = OtherPlacesUser.objects.get(user=request.auth.user)
opuser.isMe = True
serializer = OtherPlacesUserSerializer(opuser, context={'request': request})
return Response(serializer.data)
except OtherPlacesUser.DoesNotExist as ex:
return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)
except Exception as ex:
return HttpResponseServerError(ex)
@action(methods=['post', 'delete'], detail=True)
def follow(self, request, pk=None):
"""Managing users saving a place"""
authuser = OtherPlacesUser.objects.get(user=request.auth.user)
opuser = None
try:
opuser = OtherPlacesUser.objects.get(pk=pk)
except OtherPlacesUser.DoesNotExist:
return Response(
{'message': 'Place does not exist.'},
status=status.HTTP_400_BAD_REQUEST
)
if request.method == "POST":
try:
follow = Follow()
follow.follower = authuser
follow.opuser = opuser
follow.save()
return Response({}, status=status.HTTP_201_CREATED)
except Exception as ex:
return Response({'message': ex.args[0]})
elif request.method == "DELETE":
try:
follow = Follow.objects.filter(Q(opuser=opuser) & Q(follower=authuser))
follow.delete()
return Response(None, status=status.HTTP_204_NO_CONTENT)
except Exception as ex:
return Response({'message': ex.args[0]})
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'date_joined')
class OtherPlacesUserSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False)
class Meta:
model = OtherPlacesUser
fields = ('id', 'user', 'bio', 'profile_pic', 'isMe', 'following')
| UTF-8 | Python | false | false | 5,119 | py | 28 | profile.py | 19 | 0.605978 | 0.598945 | 0 | 138 | 36.094203 | 88 |
hp310780/user-survey-api | 6,184,752,921,842 | ade0239637dfa4ee37a32a6f0982aade232fbbeb | f89a621de86ec3a3ca2f5784988357db9d112f85 | /tests/test_surveys.py | 54d939cc834485f40ffdf6e742cd40d1b51a998a | [
"MIT"
] | permissive | https://github.com/hp310780/user-survey-api | f4345e2dd910300a4903542af061bd03b9a34a62 | 392a94919fac792d88b7ec37521b2e4ce1a9eb08 | refs/heads/master | 2022-12-14T07:25:24.195046 | 2020-09-21T07:21:26 | 2020-09-21T07:21:26 | 295,807,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import mock
TEST_JSON = "tests/test_data/test_surveys.json"
@mock.patch("os.getenv", return_value=TEST_JSON)
def test_survey_get(mock_db,
client):
"""Tests that 1 survey linked to 1 question is returned
from the survey/ endpoint."""
id = 1
response = client.get("/surveys/{}".format(id))
assert response.status_code == 201
assert response.json == {
"id": 1,
"questions": [
2
]
}
| UTF-8 | Python | false | false | 466 | py | 17 | test_surveys.py | 12 | 0.572961 | 0.555794 | 0 | 19 | 23.526316 | 59 |
CreativeOthman/hipeac | 6,210,522,716,605 | 932c7634df45d3cc6886bb0543d2c33993db0e7c | 3fda3ff2e9334433554b6cf923506f428d9e9366 | /hipeac/site/admin/_legacy/internships.py | e28d61a4455ab781b623568117ae66101b5c7ae8 | [
"MIT"
] | permissive | https://github.com/CreativeOthman/hipeac | 12adb61099886a6719dfccfa5ce26fdec8951bf9 | 2ce98da17cac2c6a87ec88df1b7676db4c200607 | refs/heads/master | 2022-07-20T10:06:58.771811 | 2020-05-07T11:39:13 | 2020-05-07T11:44:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.contrib import admin
from hipeac.models._legacy.internships import InternshipCall, Internship, InternshipApplication
@admin.register(InternshipCall)
class InternshipCallAdmin(admin.ModelAdmin):
list_display = ("id", "start_date", "application_deadline", "is_frozen")
@admin.register(Internship)
class InternshipAdmin(admin.ModelAdmin):
list_display = ("id", "title", "institution", "location", "country")
list_filter = ("call",)
autocomplete_fields = ("institution",)
raw_id_fields = ("call",)
@admin.register(InternshipApplication)
class InternshipApplicationAdmin(admin.ModelAdmin):
date_hierarchy = "internship__call__start_date"
list_display = ("id", "internship", "status", "selected")
search_fields = (
"created_by__first_name",
"created_by__last_name",
"internship__title",
"internship__institution__name",
)
raw_id_fields = ("internship", "created_by")
def get_queryset(self, request):
return (
super()
.get_queryset(request)
.prefetch_related("internship__call", "internship__institution")
.prefetch_related("created_by__profile")
)
| UTF-8 | Python | false | false | 1,204 | py | 435 | internships.py | 275 | 0.657807 | 0.657807 | 0 | 39 | 29.871795 | 95 |
SometimesNoReply/GB_PythonBases_A | 4,501,125,750,929 | ae3304ae17453184d7a83f15f801694723abd791 | e66729b6ca2e21d773edb3a4abf60bc3288722fa | /Lesson_8/hw_8_7.py | ea6803e5d28469f152f32c52f35e0d15bc710d97 | [] | no_license | https://github.com/SometimesNoReply/GB_PythonBases_A | 4b23549ee84aac22b7bfaadc70814b925be93bd1 | a2bf282d3ce11cb0dce285553c550fe163342538 | refs/heads/master | 2020-12-19T07:29:05.106319 | 2020-02-24T19:41:20 | 2020-02-24T19:41:20 | 235,664,211 | 0 | 0 | null | false | 2020-02-24T19:41:22 | 2020-01-22T20:50:53 | 2020-02-24T19:41:00 | 2020-02-24T19:41:21 | 41 | 0 | 0 | 0 | Python | false | false | # Homework: Lesson 8. Task 7
"""
Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное
число», реализуйте перегрузку методов сложения и умножения комплексных чисел.
Проверьте работу проекта, создав экземпляры класса (комплексные числа) и выполнив
сложение и умножение созданных экземпляров. Проверьте корректность полученного
результата.
"""
class MyComplex:
def __init__(self, r: float, i: float):
"""
Конструктор
:param r: действительная часть комплексного числа
:param i: мнимая часть комплексного числа
"""
self.r = r
self.i = i
def __str__(self):
return f"(_ {self.r} {'+' if self.i > 0 else '-'} {abs(self.i)}j _)"
def __add__(self, other):
if other.__class__ == MyComplex:
return MyComplex(self.r + other.r, self.i + other.i)
elif other.__class__ in {int, float}:
return MyComplex(self.r + other, self.i)
else:
raise TypeError
def __mul__(self, other):
if other.__class__ == MyComplex:
return MyComplex(self.r * other.r - self.i * other.i,
self.r * other.i + other.r * self.i)
elif other.__class__ in {int, float}:
return MyComplex(self.r * other, self.i * other)
else:
raise TypeError
mc_x = MyComplex(2, 3)
mc_y = MyComplex(5, 7)
print(mc_x)
print(mc_y)
print(mc_x + mc_y)
print(mc_x + 0.1)
print(mc_x + 10)
print(mc_x * mc_y)
print(mc_y * mc_x)
print(mc_x * -100)
| UTF-8 | Python | false | false | 1,935 | py | 50 | hw_8_7.py | 45 | 0.577608 | 0.568702 | 0 | 52 | 29.230769 | 90 |
brugger/pipeliners | 15,753,940,064,302 | c100dc2197a15a58f38ca39a0854a29842bfb17b | 4e66ff87ab64398f3c5a53b94653d647ff528483 | /pipeliners/backend.py | 81c31ee318ab65963dcd2d19797c48d4d79a78cd | [
"MIT"
] | permissive | https://github.com/brugger/pipeliners | 167f48582ab7dbc1737b762e46f4482e4553f23f | 5d22c657bda5c0ecb1f0d2fbc76064f90e02dcfb | refs/heads/master | 2021-05-01T22:58:45.181641 | 2018-06-01T07:58:33 | 2018-06-01T07:58:33 | 120,926,579 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Backend(object):
def name(self):
""" returns name of the backend
Args:
None
Returns:
backend name (str)
"""
return "base backend class"
def submit(self, job):
""" submits/starts a job
Args:
Job (obj): job object
Returns:
job (obj)
"""
print("submit_job is not implemented for this backend\n")
def status(self, job ):
""" Updates the status of a job
See executer.Job_status for possible statuses
Args:
Job (obj): job object
Returns:
job status (Job_status )
"""
print("status is not implemented for this backend\n")
def kill(self, job):
""" Kills/terminate/cancels a job
job.status is set to Job_status.KILLED
Args:
Job (obj): job object
Returns:
job (obj)
"""
print("kill is not implemented for this backend\n")
def available(self):
""" See if the backend is available for use by the framework
Returns:
boolean
"""
print("available is not implemented for this backend\n")
return False
| UTF-8 | Python | false | false | 1,252 | py | 24 | backend.py | 13 | 0.519169 | 0.519169 | 0 | 62 | 19.145161 | 68 |
cm107/common_utils | 429,496,748,991 | 4e348e968f7fb096c0140f2b3b3f9bae20bc4a46 | 2a1b9b1f6c0e581a67007eb93ea622aa343d7e01 | /test/spirograph_test.py | 307f672d158b48b9f06d771cc702d506a639062f | [
"MIT"
] | permissive | https://github.com/cm107/common_utils | 71fe08eb15050f0afa19e7dbe073cf2db95267fc | 4b911efe9f8cdec16ecb2a983e16f772be05076c | refs/heads/master | 2021-12-30T13:03:57.019319 | 2021-12-29T07:41:43 | 2021-12-29T07:41:43 | 193,836,099 | 0 | 0 | null | false | 2019-10-23T01:58:03 | 2019-06-26T05:35:28 | 2019-10-17T02:10:24 | 2019-10-23T01:58:02 | 62 | 0 | 0 | 0 | Python | false | false | from math import pi
from common_utils.cv_drawing_utils import Spirograph
from streamer.cv_viewer import cv_simple_image_viewer
spirograph = Spirograph(r=200, partitions=12, nodes=[0, pi/2, pi, 3*pi/2])
quit_flag = cv_simple_image_viewer(img=spirograph.sample(), preview_width=1000) | UTF-8 | Python | false | false | 282 | py | 65 | spirograph_test.py | 62 | 0.776596 | 0.730496 | 0 | 6 | 46.166667 | 79 |
alexisduque/kodo-network-coding | 19,490,561,612,619 | ef8df72132fa793a758ebff86b33d7d7677d1b7f | 98bb8950b3087ccaba0cdf6b90d0ffbc2a5a77ff | /python/benchmark.py | 5e8a279d11c0bec550ca8ed69ee5eab3a03223d8 | [] | no_license | https://github.com/alexisduque/kodo-network-coding | 4767114bacc7618d70d98f000a128ffb7282dc90 | d58a4ea086b0a686d226efa34e4db399c9e7b2ce | refs/heads/master | 2020-07-04T11:33:51.630664 | 2016-09-08T11:35:25 | 2016-09-08T11:35:25 | 67,336,656 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #! /usr/bin/env python
# encoding: utf-8
import time
import os
import sys
import argparse
import kodo
def run_coding_test(algorithm, field, symbols, symbol_size):
"""Run a timed encoding and decoding benchmark."""
# First, we measure the combined setup time for the encoder and decoder
start = time.clock()
encoder_factory = kodo.encoder_factory(
algorithm=algorithm,
field=field,
max_symbols=symbols,
max_symbol_size=symbol_size)
decoder_factory = kodo.decoder_factory(
algorithm=algorithm,
field=field,
max_symbols=symbols,
max_symbol_size=symbol_size)
encoder = encoder_factory.build()
decoder = decoder_factory.build()
# Stop the setup timer
stop = time.clock()
# Calculate interval in microseconds
setup_time = 1e6 * (stop - start)
# We measure pure coding, so we always turn off the systematic mode
if 'set_systematic_off' in dir(encoder):
encoder.set_systematic_off()
# Create random data to encode
data_in = os.urandom(encoder.block_size())
# The generated payloads will be stored in this list
payloads = []
# Generate an ample number of coded symbols (considering kodo_binary)
payload_count = 2 * symbols
# Start the encoding timer
start = time.clock()
# Copy the input data to the encoder
encoder.set_const_symbols(data_in)
# Generate coded symbols with the encoder
for i in range(payload_count):
payload = encoder.write_payload()
payloads.append(payload)
# Stop the encoding timer
stop = time.clock()
# Calculate interval in microseconds
encoding_time = 1e6 * (stop - start)
# Calculate the encoding rate in megabytes / seconds
encoded_bytes = payload_count * symbol_size
encoding_rate = encoded_bytes / encoding_time
# Start the decoding timer
start = time.clock()
# Feed the coded symbols to the decoder
for i in range(payload_count):
if decoder.is_complete():
break
decoder.read_payload(payloads[i])
# Copy the symbols from the decoder
data_out = decoder.copy_from_symbols()
# Stop the decoding timer
stop = time.clock()
# Calculate interval in microseconds
decoding_time = 1e6 * (stop - start)
# Calculate the decoding rate in megabytes / seconds
decoded_bytes = symbols * symbol_size
decoding_rate = decoded_bytes / decoding_time
if data_out == data_in:
success = True
else:
success = False
print("Setup time: {} microsec".format(setup_time))
print("Encoding time: {} microsec".format(encoding_time))
print("Decoding time: {} microsec".format(decoding_time))
return (success, encoding_rate, decoding_rate)
def main():
parser = argparse.ArgumentParser(description=run_coding_test.__doc__)
# Disable the algorithms that do not work with the benchmark code
algorithms = list(kodo.algorithms)
algorithms.remove(kodo.no_code)
algorithms.remove(kodo.sparse_full_vector)
parser.add_argument(
'--algorithm',
type=str,
help='The algorithm to use',
choices=algorithms,
default=kodo.full_vector)
parser.add_argument(
'--field',
type=str,
help='The finite field to use',
choices=kodo.fields,
default=kodo.binary8)
parser.add_argument(
'--symbols',
type=int,
help='The number of symbols',
default=16)
parser.add_argument(
'--symbol_size',
type=int,
help='The size of each symbol',
default=1600)
parser.add_argument(
'--dry-run',
action='store_true',
help='Run without the actual benchmark.')
args = parser.parse_args()
if args.dry_run:
sys.exit(0)
print("Algorithm: {} / Finite field: {}".format(
args.algorithm, args.field))
print("Symbols: {} / Symbol size: {}".format(
args.symbols, args.symbol_size))
decoding_success, encoding_rate, decoding_rate = run_coding_test(
args.algorithm,
args.field,
args.symbols,
args.symbol_size)
print("Encoding rate: {} MB/s".format(encoding_rate))
print("Decoding rate: {} MB/s".format(decoding_rate))
if decoding_success:
print("Data decoded correctly.")
else:
print("Decoding failed.")
if __name__ == "__main__":
main()
| UTF-8 | Python | false | false | 4,458 | py | 29 | benchmark.py | 23 | 0.633917 | 0.630328 | 0 | 167 | 25.694611 | 75 |
zorzalerrante/datagramas | 12,223,476,943,465 | 6776b707e9c3ce03dcf1928fb926b14b0e96ea08 | 5d51244fa70ccf2794b1c50d0cacd798e7f78db5 | /datagramas/sketch.py | 8a0d24f9b9c028c48db7a93aa7a200790b38324b | [
"BSD-3-Clause"
] | permissive | https://github.com/zorzalerrante/datagramas | 4e3cf7f99203e788f6d7fd91e96f34d7736b468a | d1ea8ae8d9d69f26d6d62f5d9cbc63d230773205 | refs/heads/master | 2021-05-31T17:29:05.807823 | 2016-05-06T01:54:25 | 2016-05-06T01:54:25 | 20,466,491 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from __future__ import unicode_literals
import uuid
import jinja2
import os
import copy
from IPython.display import HTML
from cytoolz.dicttoolz import valmap, merge
from IPython.display import display_html
from seaborn import color_palette
from matplotlib.colors import rgb2hex
from .js_utils import _dump_json, d3jsObject, JSCode
DATAGRAMAS_TEMPLATE_FILES = {'base.js', 'base.attributes.js', 'base.colorables.js',
'base.html', 'multiples.html', 'select-categories.html',
'scaffold.js'}
def _load_template(filename):
if filename in DATAGRAMAS_TEMPLATE_FILES:
filename = '{0}/templates/{1}'.format(SRC_DIR, filename)
with open(filename, 'r') as f:
code = f.read()
# the lambda avoids template caching
return (code, filename, lambda *a, **k: False)
SRC_DIR = os.path.dirname(os.path.realpath(__file__))
env = jinja2.environment.Environment()
env.loader = jinja2.FunctionLoader(_load_template)
class sketch(object):
"""
A sketch represents the state of a visualization before being rendered or scaffolded. It is built from a
configuration dictionary provided by each visualization. See build_sketch.
"""
datagram_events = ['datagram_start', 'datagram_end']
def __init__(self, **kwargs):
if not 'container_type' in kwargs:
raise Exception('need to define a container element')
if not 'data' in kwargs or kwargs['data'] is None:
raise Exception('you need to define at least one data variable')
self.configuration = kwargs.copy()
if not 'visualization_css' in kwargs:
self.configuration['visualization_css'] = '{0}/templates/{1}.css'.format(SRC_DIR, self.configuration['visualization_name'])
if not 'visualization_js' in kwargs:
self.configuration['visualization_js'] = '{0}/templates/{1}.js'.format(SRC_DIR, self.configuration['visualization_name'])
self.configuration['visualization_name'] = self.configuration['visualization_name'].replace('-', '_').replace('.', '_')
self.configuration['variables'] = valmap(self.process_variable, self.configuration['variables'])
if 'objects' in self.configuration:
self.configuration['objects'] = valmap(self.process_objects, self.configuration['objects'])
if 'attributes' in self.configuration:
self.configuration['attributes'] = valmap(self.process_attribute, self.configuration['attributes'])
else:
self.configuration['attributes'] = {}
if 'colorables' in self.configuration:
self.configuration['colorables'] = valmap(self.process_colorable, self.configuration['colorables'])
else:
self.configuration['colorables'] = {}
if 'allowed_events' in self.configuration['options'] and self.configuration['options']['allowed_events']:
if 'events' in self.configuration:
self.configuration['events'] = {k: self.process_event(k, v) for k, v in self.configuration['events'].items() if v is not None}
self.configuration['__data_variables__'] = list(self.configuration['data'].keys())
self.configuration['data'] = _dump_json(self.configuration['data'])
if 'facets' in self.configuration:
self.configuration['facets'] = _dump_json(self.configuration['facets'])
self.configuration['datagram_events'] = self.datagram_events
def process_variable(self, variable):
if type(variable) != JSCode:
return _dump_json(variable)
return variable.render(context=self.configuration)
def process_event(self, key, variable):
if type(variable) != JSCode:
raise Exception('Events can only be of JSCode type.')
if key not in self.configuration['options']['allowed_events'] and key not in self.datagram_events:
raise Exception('Unsupported event: {0}.'.format(key))
rendered = variable.render(context=self.configuration)
return rendered
def process_objects(self, variable):
if type(variable) != d3jsObject:
raise Exception('Non-object passed as object argument.')
rendered = variable.render(context=self.configuration)
return rendered
def process_attribute(self, attribute):
if 'legend' not in attribute:
attribute['legend'] = False
if 'legend_location' not in attribute:
attribute['legend_location'] = None
if 'legend_orientation' not in attribute:
attribute['legend_orientation'] = None
return valmap(self.process_variable, attribute)
def process_colorable(self, colorable):
if 'domain' not in colorable:
colorable['domain'] = None
if 'n_colors' not in colorable or colorable['n_colors'] is None:
if colorable['domain'] is None:
# this is the seaborn default
colorable['n_colors'] = 6
else:
colorable['n_colors'] = len(colorable['domain'])
else:
if type(colorable['n_colors']) != int or colorable['n_colors'] < 1:
raise Exception('Number of colors must be an integer greater or equal than 1.')
if 'palette' in colorable and colorable['palette'] is not None:
if type(colorable['palette']) == str:
# a palette name
palette = color_palette(colorable['palette'], n_colors=colorable['n_colors'])
colorable['palette'] = list(map(rgb2hex, palette))
else:
# a list of colors. we override n_colors
colorable['palette'] = list(map(rgb2hex, colorable['palette']))
colorable['n_colors'] = len(colorable['palette'])
else:
colorable['palette'] = None
if 'legend' not in colorable:
colorable['legend'] = False
if 'legend_location' not in colorable:
colorable['legend_location'] = None
if 'legend_orientation' not in colorable:
colorable['legend_orientation'] = None
return valmap(self.process_variable, colorable)
def _render_(self, template_name='base.html', **extra_args):
repr_args = merge(self.configuration.copy(), extra_args)
if self.configuration['visualization_js']:
repr_args['visualization_js'] = env.get_template(self.configuration['visualization_js']).render(**repr_args)
else:
raise Exception('Empty Visualization code!')
if 'functions_js' in self.configuration and self.configuration['functions_js'] is not None:
repr_args['functions_js'] = env.get_template(self.configuration['functions_js']).render(**repr_args)
template = env.get_template(template_name)
if not 'figure_id' in repr_args or not repr_args['figure_id']:
repr_args['figure_id'] = 'fig-{0}'.format(uuid.uuid4())
if not 'vis_uuid' in repr_args or not repr_args['vis_uuid']:
repr_args['vis_uuid'] = 'datagram-vis-{0}'.format(uuid.uuid4())
if not 'define_js_module' in repr_args:
repr_args['define_js_module'] = True
if self.configuration['visualization_css']:
try:
repr_args['visualization_css'] = env.get_template(self.configuration['visualization_css']).render(**repr_args)
except IOError:
repr_args['visualization_css'] = None
# some dependencies have names with invalid characters for variable names in Javascript
repr_args['requirements_as_args'] = list(map(lambda x: x.replace('-', '_'), repr_args['requirements']))
# if there are defined events, we merge them here
repr_args['event_names'] = []
if 'allowed_events' in repr_args['options'] and repr_args['options']['allowed_events']:
repr_args['event_names'].extend(repr_args['options']['allowed_events'])
repr_args['event_names'].extend(self.datagram_events)
repr_args['event_names'] = list(set(repr_args['event_names']))
return template.render(**repr_args)
def _ipython_display_(self):
"""
Automatically displays the sketch when returned on a notebook cell.
"""
self.show()
def show(self, multiples=None):
"""
Displays the sketch on the notebook.
"""
if multiples == 'small-multiples':
template_name = 'multiples.html'
elif multiples == 'select-categories':
template_name = 'select-categories.html'
else:
template_name = 'base.html'
rendered = self._render_(template_name)
display_html(HTML(rendered))
return None
def scaffold(self, filename=None, define_js_module=True, style=None, append=False, author_comment=None):
rendered = self._render_('scaffold.js', define_js_module=define_js_module, author_comment=author_comment)
if filename is None:
return rendered
with open(filename, 'w') as f:
f.write(rendered)
if style is not None:
mode = 'a' if append is True else 'w'
with open(style, mode) as f:
f.write(env.get_template(self.configuration['visualization_css']).render(**self.configuration))
sketch_doc_string_template = jinja2.Template('''{{ summary }}
Data Arguments:
{% for key, value in data.items() %}{{ key }} -- (default: {{ value }})
{% endfor %}
{% if variables %}Keyword Arguments:
{% for key, value in variables.items() %}{{ key }} -- (default: {{ value }})
{% endfor %}{% endif %}
{% if options %}Sketch Arguments:
{% for key, value in options.items() %}{{ key }} -- (default: {{ value }})
{% endfor %}{% endif %}
{% if attributes %}Mappeable Attributes:
{% for key, value in attributes.items() %}{{ key }} -- (default: {{ value }})
{% endfor %}{% endif %}
{% if colorables %}Colorable Attributes:
{% for key, value in colorables.items() %}{{ key }} -- (default: {{ value }})
{% endfor %}{% endif %}
''')
def build_sketch(default_args, opt_process=None):
"""
Receives a visualization config and returns a sketch function that can be used to display or scaffold
visualizations.
The sketch function is not a visualization per-se. Instead, it gets called with parameters that can replace
or update the default configuration provided by default_args, and the updated configuration is used to
display/scaffold a visualization.
"""
def sketch_fn(**kwargs):
"""
This is the function executed each time a visualization is displayed or scaffolded.
The default arguments used when defining the visualization will be updated with those from the
keyword arguments. However, not all elements of default_args can be overwritten.
This also includes logic to decide when to update an entire setting or just a sub-element of it.
:param kwargs: arguments for the visualization.
:return: sketch
"""
sketch_args = copy.deepcopy(default_args)
for key, value in kwargs.items():
if key in sketch_args:
sketch_args[key] = value
elif key == 'events' and 'options' in sketch_args and 'allowed_events' in sketch_args['options']:
sketch_args[key] = value
elif key in sketch_args['data']:
sketch_args['data'][key] = value
elif key in sketch_args['options']:
if type(sketch_args['options'][key]) == dict:
sketch_args['options'][key].update(value)
else:
sketch_args['options'][key] = value
elif key in sketch_args['variables']:
if type(sketch_args['variables'][key]) == dict:
sketch_args['variables'][key].update(value)
else:
sketch_args['variables'][key] = value
elif 'attributes' in sketch_args and key in sketch_args['attributes']:
if type(value) == dict:
sketch_args['attributes'][key].update(value)
elif type(value) in (int, float):
sketch_args['attributes'][key]['value'] = value
elif value is None or type(value) == str:
sketch_args['attributes'][key]['value'] = value
else:
raise Exception('Not supported value for attribute {0}: {1}'.format(key, value))
elif 'colorables' in sketch_args and key in sketch_args['colorables']:
if type(value) == dict:
sketch_args['colorables'][key].update(value)
elif type(value) in (int, float):
sketch_args['colorables'][key]['value'] = value
elif value is None or type(value) == str:
sketch_args['colorables'][key]['value'] = value
else:
raise Exception('Not supported value for colorable {0}: {1}'.format(key, value))
elif key in ('figure_id', 'facets'):
sketch_args[key] = value
else:
raise Exception('Invalid argument: {0}'.format(key))
if callable(opt_process):
opt_process(sketch_args)
return sketch(**sketch_args)
if not 'summary' in default_args:
default_args['summary'] = default_args['visualization_name']
sketch_fn.__doc__ = sketch_doc_string_template.render(default_args)
sketch_fn.variable_names = list(default_args['data'].keys())
return sketch_fn
| UTF-8 | Python | false | false | 13,639 | py | 50 | sketch.py | 40 | 0.612362 | 0.610309 | 0 | 341 | 38.997067 | 142 |
chainsawcr/mozio-proj | 15,522,011,834,875 | 868997a060b9d90dc470a3f90100f6211a1a26a5 | 7da23446d2f78d0ce6ee2a167e0e729bb3627947 | /mozio_app/mixins.py | 545af2891f4f4802a9a36740a0b9fd5e368b0416 | [] | no_license | https://github.com/chainsawcr/mozio-proj | 4ea5d48794e35cba21c4cc2d100262cc68ec3810 | 7decda64e93af427982865e7ec3df2e9822cbd4d | refs/heads/master | 2021-01-18T14:36:29.878290 | 2014-05-05T05:24:00 | 2014-05-05T05:24:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.contrib import messages
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse_lazy
from rnd_itr_app import models
class MessageMixin(object):
@property
def success_message(self):
return ''
def form_valid(self, form):
messages.add_message(
self.request, messages.SUCCESS, self.success_message)
return super(MessageMixin, self).form_valid(form)
def form_invalid(self, form):
messages.add_message(
self.request, messages.ERROR, self.error_message)
return super(MessageMixin, self).form_invalid(form)
class TemplateValuesMixin(object):
@property
def template_valuespage(self):
return {}
def get_context_data(self, **kwargs):
context = super(TemplateValuesMixin, self).get_context_data(**kwargs)
for each in self.template_values.keys():
context[each] = self.template_values[each]
return context
class ExtraDatasetMixin(object):
@property
def extra_dataset(self):
return None
def __init__(self):
self._extra_dataset = {
'frequency': {
'data': models.Frequency.objects.all(),
'link': str(reverse_lazy('frequency-create'))
},
'technology': {
'data': models.Technology.objects.all(),
'link': str(reverse_lazy('technology-create'))
},
'user': {
'data': User.objects.filter(is_superuser=False),
'link': str(reverse_lazy('user-create'))
}
}
def get_extra_dataset(self, extra_dataset=None):
"""
if extra_dataset is set:
Return a dict with datasets including only models in extra_dataset
if extra_dataset is not set:
Return all datasets defined in __init__
"""
# Parameter override class property
if extra_dataset:
self.extra_dataset = extra_dataset
if self.extra_dataset:
filtered = {}
for each in self.extra_dataset:
filtered[each] = self._extra_dataset[each]
return filtered
else:
return self._extra_dataset
def get_context_data(self, **kwargs):
context = super(ExtraDatasetMixin, self).get_context_data(**kwargs)
context['dataset'] = self.get_extra_dataset()
return context
| UTF-8 | Python | false | false | 2,462 | py | 16 | mixins.py | 10 | 0.592201 | 0.592201 | 0 | 80 | 29.775 | 78 |
nsmith0310/Programming-Challenges | 4,982,162,079,200 | 4699eb447a7dc1d036cb4fee96f04ae2ea2fd69f | 4351a81d4a4fae778711643cb9644534e595920d | /Python 3/LeetCode/lc387.py | b310f1b719a23f1460f9004c489a712b26fbd435 | [] | no_license | https://github.com/nsmith0310/Programming-Challenges | ba1281127d6fa295310347a9110a0f8998cd89ce | 7aabed082826f8df555bf6e97046ee077becf759 | refs/heads/main | 2023-08-13T14:47:10.490254 | 2021-10-13T04:35:57 | 2021-10-13T04:35:57 | 416,565,430 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution:
def firstUniqChar(self, s: str) -> int:
if s=="":
return -1
s2 = list(set(s))
l=[]
l2=[]
for x in s2:
l.append([s.count(x),x])
for x in l:
if x[0]==1:
l2.append(x)
if l2==[]:
return -1
l3=[]
for x in l2:
l3.append(s.index(x[1]))
return min(l3)
| UTF-8 | Python | false | false | 459 | py | 910 | lc387.py | 660 | 0.337691 | 0.30719 | 0 | 20 | 21.3 | 43 |
FergusFettes/wien_networking | 17,051,020,201,864 | aee5e584ec6c818ec7bf0ebdf18053ab51454ff1 | a424e751eb4c31af7ef1088053e9dbe5af81f71e | /quotesbot/flohmarketbot/spiders/toscrape-css.py | a305167c2dbe1a57db2985c9b97cf88fc7b752d5 | [] | no_license | https://github.com/FergusFettes/wien_networking | 1f093f6eaf229adb874b39922aadbfcdd4254212 | dbd5f1d3219fec0cd0e68176bb0428934801cb95 | refs/heads/master | 2021-07-22T03:08:47.364320 | 2020-09-23T21:11:19 | 2020-09-23T21:11:19 | 216,395,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
import scrapy
class ToScrapeCSSSpider(scrapy.Spider):
name = "toscrape-css"
start_urls = [
'http://quotes.toscrape.com/',
]
def parse(self, response):
for quote in response.css("div.quote"):
yield {
'text': quote.css("span.text::text").extract_first(),
'author': quote.css("small.author::text").extract_first(),
'tags': quote.css("div.tags > a.tag::text").extract()
}
next_page_url = response.css("li.next > a::attr(href)").extract_first()
if next_page_url is not None:
yield scrapy.Request(response.urljoin(next_page_url))
class FlohScraper(scrapy.Spider):
name = "flohscraper"
start_urls = [
f"https://www.flohmarkt.at/flohmaerkte/wien/{i}"
for i in range(0, 121, 15)
]
even_titles = [
f"td:nth-child(1) div:nth-child(1) div.terminBox:nth-child({i}) div.terminTitel:nth-child(2) > a:nth-child(1)::text"
for i in range(2, 17, 2)
]
odd_titles = [
f"td:nth-child(1) div:nth-child(1) div:nth-child({i}) div.terminTitel:nth-child(2) > a:nth-child(1)::text"
for i in range(3, 17, 2)
]
even_urls = [
f"td:nth-child(1) div:nth-child(1) div.terminBox:nth-child({i}) div.terminTitel:nth-child(2) > a:nth-child(1)::href"
for i in range(2, 17, 2)
]
odd_urls = [
f"td:nth-child(1) div:nth-child(1) div:nth-child({i}) div.terminTitel:nth-child(2) > a:nth-child(1)::href"
for i in range(3, 17, 2)
]
even_text = [
f"td:nth-child(1) div:nth-child(1) div.terminBox:nth-child({i})::text"
for i in range(2, 17, 2)
]
odd_text = [
f"td:nth-child(1) div:nth-child(1) div:nth-child({i})::text"
for i in range(3, 17, 2)
]
titles = [*even_titles, *odd_titles]
text = [*even_text, *odd_text]
urls = [*even_urls, *odd_urls]
def parse(self, response):
for j, title in enumerate(self.titles):
yield {
'title': response.css(title).extract(),
'date': response.css(self.text[j]).extract()[0].strip(),
'short_info': response.css(self.text[j]).extract()[2].strip(),
'url': response.css(self.urls[j]).extract()
}
| UTF-8 | Python | false | false | 2,388 | py | 6 | toscrape-css.py | 4 | 0.535595 | 0.5134 | 0 | 67 | 34.641791 | 124 |
acse-7ccead1f/ci_mpm | 12,704,513,266,872 | d357ae42030a931adc7de3882424d24e5802b42a | bdd730f92ea5b8d2583342443057d23c9c3c137f | /tests/test_sin.py | ab83fd0094e4c29b7618efec9102810591bc06b9 | [] | no_license | https://github.com/acse-7ccead1f/ci_mpm | 0ab39ff68207bdbaee51dc1d97de082d1caccc85 | 1867ccfd4e9ad7022c7879147d652418bfed1074 | refs/heads/master | 2023-09-04T19:05:23.290976 | 2021-10-26T02:14:18 | 2021-10-26T02:14:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
from simple_functions import my_sin
class TestPi(object):
'''Class to test our constants are computed correctly'''
def test_sin(self):
'''Test computation of pi'''
mysin = my_sin(2)
assert np.isclose(mysin, np.sin(2), atol=1e-12)
| UTF-8 | Python | false | false | 285 | py | 3 | test_sin.py | 2 | 0.642105 | 0.624561 | 0 | 11 | 24.818182 | 60 |
RubenMeijs/WISB256 | 953,482,760,260 | 581292e48b0c1b2cb8b420b8ac579dc62f37d959 | 77fc4e319443c60d914e61ab08909fa82a202588 | /EulerOpdrachten/euler3.py | 1e2ca8d7ac333154ea7e49cddebf78134d5be860 | [] | no_license | https://github.com/RubenMeijs/WISB256 | dc8aad84610b749e0e4263dbcf6e8772546dac65 | 3239811c93f21c23cb31930c2d809fe64db9a215 | refs/heads/master | 2020-05-17T00:20:32.108106 | 2015-06-09T09:33:31 | 2015-06-09T09:33:31 | 34,315,122 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import math
getal = float(input())
wortel = int(math.ceil(math.sqrt(getal)))
delers = range(2,wortel+1)
priemdeler =[]
for i in delers:
if getal % i == 0:
priemdeler.append(i)
print(priemdeler)
for i in priemdeler:
if i != 0:
for n in range(0, len(priemdeler)):
if priemdeler[n]%i == 0 and priemdeler[n] != i:
priemdeler[n] = 0
priemdeler=list(set(priemdeler))
print(max(priemdeler)) | UTF-8 | Python | false | false | 460 | py | 18 | euler3.py | 18 | 0.584783 | 0.569565 | 0 | 24 | 18.208333 | 60 |
Charolf/Charlie1998 | 7,387,343,799,762 | c5a1ff0fc0694f516e6bfad97e7f09b63326c594 | 49f7b617500e6d263fd3bcc916faa40eec36f618 | /cpe101/lab6/char/char.py | ab8a107fd11730e403cee26353f83653acbd8389 | [
"MIT"
] | permissive | https://github.com/Charolf/Charlie1998 | c2d0f6e75ab4c6f45f572f6679c13eaa1a767cfe | ca858a7b6c22d961068a1c7395676c7f5f6fdf58 | refs/heads/master | 2019-07-02T12:56:13.475336 | 2018-06-29T20:07:33 | 2018-06-29T20:07:33 | 122,789,759 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Lab 6 char
#
# Name: Charlie Huang
# Instructor: S. Einakian
# Section: CPE-101-05/06
def is_lower_101(letter):
number = ord(letter)
if 65 <= number <= 90:
return False
elif 97 <= number <= 122:
return True
def char_rot_13(letter):
number = ord(letter)
new_number = number + 13
if 65 <= number <= 90:
if new_number > 90:
return chr(new_number-90+64)
else:
return chr(new_number)
elif 97 <= number <= 122:
if new_number > 122:
return chr(new_number-122+96)
else:
return chr(new_number)
else:
return letter | UTF-8 | Python | false | false | 542 | py | 180 | char.py | 88 | 0.647601 | 0.560886 | 0 | 28 | 18.392857 | 32 |
Sabbirdiu/Django-ml-Healthcare-Prediction-Website | 17,317,308,147,806 | a0fb082172691ca881a8fab2914f4812be4b552f | 9faa9d0eb2cbc8e6252240ffa5bb8a44d1e650f0 | /accounts/urls.py | 331bebdf9f0711e48d46d7ef841161b4f9c869b7 | [] | no_license | https://github.com/Sabbirdiu/Django-ml-Healthcare-Prediction-Website | 5af507f95f046efbac047b986b46088484f2cc77 | 5ee6a102630cf7ee30470dad5637adb4e9ffd744 | refs/heads/main | 2023-07-22T18:12:45.085836 | 2020-12-25T06:33:38 | 2020-12-25T06:33:38 | 322,766,976 | 8 | 2 | null | false | 2023-07-10T19:49:55 | 2020-12-19T04:34:10 | 2023-05-23T13:55:36 | 2023-07-10T19:48:12 | 4,758 | 4 | 3 | 1 | CSS | false | false | from django.urls import path
from .views import *
urlpatterns = [
path('patient/register', RegisterPatientView.as_view(), name='patient-register'),
path('login', LoginView.as_view(), name='login'),
path('logout', LogoutView.as_view(), name='logout'),
path('doctor/register', RegisterDoctorView.as_view(), name='doctor-register'),
path('patient/profile/update/', EditPatientProfileView.as_view(), name='patient-profile-update'),
path('doctor/profile/update/', EditDoctorProfileView.as_view(), name='doctor-profile-update'),
] | UTF-8 | Python | false | false | 560 | py | 28 | urls.py | 11 | 0.698214 | 0.698214 | 0 | 14 | 39.071429 | 101 |
24HeuresINSA/issue-web-service | 18,691,697,695,290 | 39eb81024628cb6d3f00997894b8247b93d3a7b0 | 05e0439cbaaf29343020e8966da71de1d21dc8ae | /src/Issue.py | 4087918a383b8c96d55d41136a76e8b31f764ff0 | [] | no_license | https://github.com/24HeuresINSA/issue-web-service | 809355b4de37f0a39f0df24ad058e6074885d135 | 928b0c9849d1f8d5ab39efd5d5814d534499540d | refs/heads/main | 2023-07-14T12:39:31.900679 | 2021-08-24T20:20:52 | 2021-08-24T20:20:52 | 324,833,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os.path
import requests
import json
import datetime
class Issue:
def __init__(self, repo, token, data=None, milestone=None, git_platform=None):
"""
:param repo: the github repository to push issues with format username|organisation/project for github
and username|organisation/[subproject]/project for gitlab
:param token: the github token with repo scope ( to get one : https://github.com/settings/tokens/new)
:param data: the json structure of the issue
:param git_platform: String "github" or "gitlab". Platform to push issue
"""
self.repo = repo
self.token = token
self.data = {} if not data else data
self.data["attachment"] = []
self.body = None # Need to call one md generator
self.milestone = milestone
if not git_platform:
raise ValueError("git_platform not define")
elif git_platform not in ["github", "gitlab"]:
raise ValueError("git_platform should be github or gitlab")
else:
self.git_platform = git_platform
def pushIssue(self):
"""
Push one issue to github or gitlab
:return: the http response of push requests
"""
if not self.body:
raise ValueError("body not define, call MD generator first")
if isinstance(self.data, list):
raise TypeError("Use pushIssues for multiple issues")
if self.checkDuplicateTitle():
return "Issue already exists"
url = f"https://api.github.com/repos/{self.repo}/issues" if self.git_platform == "github" else \
f"https://gitlab.com/api/v4/projects/{self.repo.replace('/', '%2F')}/issues"
payload = {
'title': self.data["title"],
'body' if self.git_platform == "github" else 'description': self.body,
'labels': self.data["tags"],
'milestone' if self.git_platform == "github" else 'milestone_id': self.milestone
}
headers = {
'Authorization': f'Bearer {self.token}',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
return response
def pushIssues(self):
issueList = self.data.copy()
for issue in issueList:
self.data = issue
if not self.checkDuplicateTitle():
self.generateMDIssue()
print(self.pushIssue())
def getIssues(self):
"""
Get issues to github or gitlab
:return: the list of github or gitlab issues
"""
url = f"https://api.github.com/repos/{self.repo}/issues?state=all" if self.git_platform == "github" else \
f"https://gitlab.com/api/v4/projects/{self.repo.replace('/', '%2F')}/issues?scope=all"
payload = {}
headers = {
'Authorization': f'Bearer {self.token}'
}
response = requests.request("GET", url, headers=headers, data=payload)
jsonResponse = json.loads(response.text)
return [jsonIssue["title"] for jsonIssue in jsonResponse]
def uploadImage(self, image):
"""
Upload an image to gitlab for issue attachment
:param image: byte image
:return: markdown code
"""
url = f"https://gitlab.com/api/v4/projects/{self.repo.replace('/', '%2F')}/uploads"
files = [('file',
(image.filename, image, f'{image.content_type}'))
]
headers = {
'Authorization': f'Bearer {self.token}'
}
response = requests.request("POST", url, headers=headers, files=files)
self.data["attachment"].append(json.loads(response.text)["markdown"])
def checkDuplicateTitle(self):
"""
Check if one issue title already exists in github or gitlab
:return: boolean
"""
return self.data["title"] in self.getIssues()
def MDTestList(self):
"""
:return: string of md test list format
"""
return '\n'.join([f" - [ ] {test}" for test in self.data["tests"]])
def MDUserBadge(self):
"""
:return: string of md "badge"
"""
return ' '.join([f"``{user}``" for user in self.data["scope"]])
def MDNumberList(self):
"""
:return: string of md number list
"""
return '\n'.join(f"1. {step}" for step in self.data['steps'])
def loadDataFromMD(self, mdfile):
"""
Parse MD file to get json user story format
:param mdfile: list of user story like this
```json
{
"title": "X",
"author": "X",
}
```
:return: json object
"""
with open(mdfile, "r") as f:
file = f.read()
items = file[file.index("<!-- start DO NOT DELETE THIS COMMENT -->"):]
items = items.split("```json")[1:]
for i in range(len(items)):
items[i] = items[i].replace("//LEAVE AS IT IS", "")
items[i] = items[i].replace("// FILL THE LIST", "")
items[i] = items[i].replace("```", "")
items[i] = items[i].replace("\n", "")
items[i] = items[i].strip()
db = json.loads(items[i])
items[i] = db
self.data = items
def loadDataFromJson(self, jsonfile):
"""
:param jsonfile: path to the json file
:return: load json object in self.data
"""
with open(jsonfile, "r") as file:
self.data = json.load(file)
def descriptionSwitcher(self):
"""
:return: string for type of issue
"""
if "bug" in self.data['tags']:
return "Bug"
elif "feature" in self.data['tags']:
return "Feature"
else:
return "Issue"
def generateMDIssue(self):
"""
:return: string of md structure for bug issue
"""
try:
comments = self.data["comments"]
except KeyError:
comments = ""
try:
_ = self.data["steps"]
bugsSteps = self.MDNumberList()
except KeyError:
bugsSteps = ""
try:
_ = self.data["tests"]
testsSteps = self.MDTestList()
except KeyError:
testsSteps = ""
try:
_ = self.data["url"]
url = self.MDTestList()
except KeyError:
url = ""
try:
attachment = self.data['attachment']
except KeyError:
attachment = ""
self.body = f"# Date {datetime.date.today().strftime('%d/%m/%Y')}\n\n" \
f"#{'URL' if url != '' else ''} {url} \n\n" \
f"# Author {self.data['author']} \n\n" \
f"# Scope : {self.MDUserBadge()} \n\n" \
f"# {self.descriptionSwitcher()} description \n\n" \
f"{self.data['description']} \n\n" \
f"{'# Etapes de validation' if testsSteps != '' else ''} \n" \
f"{testsSteps}" \
f"{'# Etapes pour reproduire le bug' if bugsSteps != '' else ''} \n" \
f"{bugsSteps}" \
f"{'## Comments' if comments != '' else ''} \n" \
f"{comments}" \
f"{'# Attachment' if attachment != '' else ''} \n" \
f"{' '.join([image for image in self.data['attachment']]) if attachment != '' else ''}"
| UTF-8 | Python | false | false | 7,590 | py | 14 | Issue.py | 4 | 0.524506 | 0.523452 | 0 | 223 | 33.035874 | 114 |
pedcremo/wifibytes-server-django | 17,729,625,030,909 | 64b738c5c4aefb42cbb7b773c4b2c73f95768450 | da7451bf1fc8f72e9fe400e71543f2f51f79c399 | /wifibytes/pagina/models.py | 1034a23d5aa183916dea5a12311c9abb1f62d74e | [] | no_license | https://github.com/pedcremo/wifibytes-server-django | f507a2b5539d6854467754ede7e4ea823a684e09 | d815d663f3ccb8b2741ff7afda27c3e16d526722 | refs/heads/master | 2020-04-01T14:07:24.070611 | 2019-02-20T19:18:23 | 2019-02-20T19:18:23 | 153,281,271 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # encoding:utf-8
from django.db import models
from tinymce.models import HTMLField
class Home(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
titulo = models.CharField(verbose_name=("titulo"), max_length=100, blank=False)
subtitulo = models.CharField(verbose_name=("subtitulo"), max_length=100, blank=False)
caja_izquierda_titulo = models.CharField(verbose_name=("caja_izquierda_titulo"), max_length=100, blank=False)
caja_izquierda_texto = HTMLField()
caja_derecha_titulo = models.CharField(verbose_name=("caja_derecha_titulo"), max_length=100, blank=False)
caja_derecha_texto = HTMLField()
activo = models.BooleanField(default=False, editable=True, null=False)
idioma = models.ForeignKey('internationalization.Idioma', null=True,on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class Meta:
verbose_name="Textos Inicio"
def save(self, *args, **kwargs):
if not self.id:
no = self.__class__.objects.count()
if no == 0:
self.id = 1
else:
self.id = self.__class__.objects.all().order_by(
"-id")[0].id + 1
super(Home, self).save(*args, **kwargs)
class TarifaDescriptorGenerico(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
pretitulo = models.CharField(verbose_name=("pretitulo"), max_length=100, blank=False)
titulo = models.CharField(verbose_name=("titulo"), max_length=100, blank=False)
caja_1_titulo = models.CharField(verbose_name=("caja_1_titulo"), max_length=100, blank=False)
caja_1_texto = HTMLField()
caja_1_icono = models.FileField(upload_to="pagina_tarifas")
caja_2_titulo = models.CharField(verbose_name=("caja_2_titulo"), max_length=100, blank=False)
caja_2_texto = HTMLField()
caja_2_icono = models.FileField(upload_to="pagina_tarifas")
caja_3_titulo = models.CharField(verbose_name=("caja_3_titulo"), max_length=100, blank=False)
caja_3_texto = HTMLField()
caja_3_icono = models.FileField(upload_to="pagina_tarifas")
caja_4_titulo = models.CharField(verbose_name=("caja_4_titulo"), max_length=100, blank=False)
caja_4_texto = HTMLField()
caja_4_icono = models.FileField(upload_to="pagina_tarifas")
activo = models.BooleanField(default=False, editable=True, null=False)
idioma = models.ForeignKey('internationalization.Idioma', null=True,on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class Meta:
verbose_name = "Textos cajitas tarifa"
def save(self, *args, **kwargs):
if not self.id:
no = self.__class__.objects.count()
if no == 0:
self.id = 1
else:
self.id = self.__class__.objects.all().order_by(
"-id")[0].id + 1
super(TarifaDescriptorGenerico, self).save(*args, **kwargs)
class PaletaColores(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
titulo = models.CharField(verbose_name=("titulo"), max_length=100, blank=False)
hexadecimal = models.CharField(verbose_name=("hexadecimal"), max_length=100, blank=False)
def __str__(self):
return str(self.titulo)
def save(self, *args, **kwargs):
if not self.id:
no = self.__class__.objects.count()
if no == 0:
self.id = 1
else:
self.id = self.__class__.objects.all().order_by("-id")[0].id + 1
super(PaletaColores, self).save(*args, **kwargs)
class TxtContacto(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
email = models.CharField(verbose_name=("email"), max_length=100, blank=False)
telefono = models.CharField(verbose_name=("telefono"), max_length=100, blank=False)
provincia = models.CharField(verbose_name=("provincia"), max_length=100, blank=False)
codigo_postal = models.CharField(verbose_name=("codigo_postal"), max_length=100, blank=False)
calle = models.CharField(verbose_name=("calle"), max_length=100, blank=False)
activo = models.BooleanField(default=False, editable=True, null=False)
idioma = models.ForeignKey('internationalization.Idioma', null=True,on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
def save(self, *args, **kwargs):
if not self.id:
no = self.__class__.objects.count()
if no == 0:
self.id = 1
else:
self.id = self.__class__.objects.all().order_by(
"-id")[0].id + 1
super(TxtContacto, self).save(*args, **kwargs)
| UTF-8 | Python | false | false | 4,721 | py | 128 | models.py | 102 | 0.633129 | 0.615336 | 0 | 122 | 37.696721 | 113 |
saerdnaer/emf-camp-website | 3,650,722,205,967 | 9747bf3a4517e242a33f8136ac4127bc516908ec | 71fd6e7e59933831d751a7b084afcdae4bacd223 | /apps/volunteer/training.py | 7b04f34dfb1433fd5545ea9000808bfd3208ae28 | [] | no_license | https://github.com/saerdnaer/emf-camp-website | ebe47400c211f5bfad54f66f8571ae35e41e08a4 | d76cd25dea056e09f24f627b1387c537e0a56282 | refs/heads/master | 2020-03-27T19:37:00.072034 | 2018-09-01T11:25:01 | 2018-09-01T11:25:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # coding=utf-8
from flask import render_template, flash, current_app as app, redirect, url_for
from wtforms import SubmitField, BooleanField, FormField, FieldList
from wtforms.validators import InputRequired
from main import db
from models.volunteer.role import Role
from models.volunteer.volunteer import Volunteer
from . import v_admin_required, volunteer
from ..common.forms import Form, HiddenIntegerField
class VolunteerSelectForm(Form):
volunteer_id = HiddenIntegerField('Volunteer ID', [InputRequired()])
trained = BooleanField('Volunteer')
class TrainingForm(Form):
volunteers = FieldList(FormField(VolunteerSelectForm))
submit = SubmitField('Train these volunteers.')
def add_volunteers(self, volunteers):
# Don't add roles if some have already been set (this will get called
# on POST as well as GET)
if len(self.volunteers) == 0:
for v in volunteers:
self.volunteers.append_entry()
self.volunteers[-1].volunteer_id.data = v.id
volunteer_dict = {v.id: v for v in volunteers}
# Enrich the field data
for field in self.volunteers:
field._volunteer = volunteer_dict[field.volunteer_id.data]
field.label = field._volunteer.nickname
@volunteer.route('/train-users')
@v_admin_required
def select_training():
return render_template('volunteer/training/select_training.html', roles=Role.get_all())
@volunteer.route('/train-users/<role_id>', methods=['GET', 'POST'])
@v_admin_required
def train_users(role_id):
role = Role.get_by_id(role_id)
form = TrainingForm()
form.add_volunteers(Volunteer.get_all())
if form.validate_on_submit():
changes = 0
for v in form.volunteers:
if v.trained.data and v._volunteer not in role.trained_volunteers:
changes += 1
role.trained_volunteers.append(v._volunteer)
elif not v.trained.data and v._volunteer in role.trained_volunteers:
changes += 1
role.trained_volunteers.remove(v._volunteer)
db.session.commit()
flash('Trained %d volunteers' % changes)
app.logger.info('Trained %d volunteers' % changes)
return redirect(url_for('.train_users', role_id=role_id))
for v in role.trained_volunteers:
for f in form.volunteers:
if f.volunteer_id.data == v.id:
f.trained.data = True
break
# Sort people who've been trained to the top then by nickname
form.volunteers = sorted(form.volunteers, key=lambda f: (-1 if f.trained.data else 1, f._volunteer.nickname))
return render_template('volunteer/training/train_users.html', role=role, form=form)
| UTF-8 | Python | false | false | 2,756 | py | 45 | training.py | 31 | 0.664369 | 0.661466 | 0 | 81 | 33.012346 | 113 |
anonymousAuthors2023/GRU_fusion_COVID-19 | 15,547,781,621,262 | 2fd288b000419ebaca9b8f0fdee869787ad475af | 8376fbbd1b10750c7ca02aecc300f15b133a77ff | /SEIR.py | 8c63e4816532b17620e6e6e31ed330b26c697448 | [] | no_license | https://github.com/anonymousAuthors2023/GRU_fusion_COVID-19 | 117d7de06a42351fd16c975c42641e3b24a84097 | 7a262ff61dfe2b230325baf2fa6281354a1b3a41 | refs/heads/main | 2023-08-22T03:24:56.732662 | 2021-10-22T06:04:23 | 2021-10-22T06:04:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import pandas as pd
from scipy.integrate import solve_ivp
from scipy.optimize import basinhopping
data_dir = "../data/Italy.csv"
# Population of selected countries:
# Italy = 60431283
# Germany = 82927922
# Russia = 145934462
# Denmark = 5792202
# Austria = 9006398
# Switzerland = 8654622
N = 60431283
predict_range = 150
iter_num = 1
loss_weight = 0.3
class SEIRfit(object):
def __init__(self, loss, predict_range):
self.loss = loss
self.predict_range = predict_range
def load_confirmed(self):
df = pd.read_csv(data_dir)
dff = df["D"]
i_0 = dff[0]
return dff.T, i_0
def load_removed(self):
df = pd.read_csv(data_dir)
dff1 = df["R"]
dff2 = df["A"]
dff = dff1 + dff2
r_0 = dff[0]
return dff.T, r_0
def predict(self, beta, alpha, gamma, k, E_0, I_0, R_0, D_actual):
size = len(D_actual) + predict_range
S_0 = N*k - I_0 - R_0 - E_0
def SEIR(t, y):
S = y[0]
E = y[1]
I = y[2]
R = y[3]
return [-beta*S*I/N, beta*S*I/N-alpha*E, alpha*E-gamma*I, gamma*I]
return solve_ivp(SEIR, [0, size], [S_0, E_0, I_0, R_0], t_eval=np.arange(0, size, 1))
def fit(self):
D_actual, I_0 = self.load_confirmed()
R_actual, R_0 = self.load_removed()
print("Start\n")
optimal = basinhopping(loss, [0.001, 0.001, 0.001, 0.001, 1],
niter=iter_num,
minimizer_kwargs = {
"method": "L-BFGS-B",
"args":(D_actual, R_actual, loss_weight, I_0, R_0),
"bounds":[(0.00000001, 50.), (0.00000001, 1.), (0.00000001, 1.), (0.0000000001, 1.), (0, 312)]
})
print(optimal)
beta, alpha, gamma, k, E_0 = optimal.x
print(f" beta={beta:.8f}, alpha={alpha:.8f}, gamma={gamma:.8f}, k:{k:.8f}, E_0:{E_0:.8f}")
prediction = self.predict(beta, alpha, gamma, k, E_0, I_0, R_0, D_actual)
D = prediction.y[2]
R = prediction.y[3]
result = pd.DataFrame({'D': D, 'R': R})
result.to_csv('./output/result_SEIR.csv', encoding='gbk')
def loss(param, D_actual, R_actual, w, I_0, R_0):
size = len(D_actual)
beta, alpha, gamma, k, E_0 = param
S_0 = N*k - I_0 - R_0 - E_0
def SEIR(t, y):
S = y[0]
E = y[1]
I = y[2]
R = y[3]
return [-beta*S*I/N, beta*S*I/N-alpha*E, alpha*E-gamma*I, gamma*I]
solution = solve_ivp(SEIR, [0, size], [S_0, E_0, I_0, R_0], t_eval=np.arange(0, size, 1), vectorized=True)
loss1 = np.mean((solution.y[2] - D_actual) ** 2)
loss2 = np.mean((solution.y[3] - R_actual) ** 2)
return (1-w)*loss1 + w*loss2
def main():
SEIRfitter = SEIRfit(loss, predict_range)
SEIRfitter.fit()
if __name__ == '__main__':
main() | UTF-8 | Python | false | false | 3,109 | py | 3 | SEIR.py | 3 | 0.485365 | 0.422322 | 0 | 99 | 29.424242 | 129 |
kljushin/cursor_homeworks | 12,352,325,958,690 | 04fe09787d371707c39f71eb4c8367bdc0dd25cc | 13b73966ba258a23fe8e911280943c701510bece | /hw14/hw14.py | 1ef2c4cdb46265db0bac7fc9490c5b3f1b8aea22 | [] | no_license | https://github.com/kljushin/cursor_homeworks | e270c23ff6de6e9b3fa3758be545e8efcea33a55 | f54f0ad69ecef08cad939b1ebea88b3f2d0e8875 | refs/heads/master | 2023-04-01T13:00:22.484305 | 2021-04-14T09:33:44 | 2021-04-14T09:33:44 | 341,910,947 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import time
import glob
import concurrent.futures
def find_pattern_line(path, pattern):
result = set()
with open(path) as file:
for line in file:
if pattern in line:
result.add(line)
return result
def find_by_pattern_threads(path, pattern):
files = glob.glob(f'{path}**/*.py', recursive=True)
result = set()
with concurrent.futures.ThreadPoolExecutor() as thread_pool:
find_res = thread_pool.map(find_pattern_line, files, [pattern] * len(files))
for res in find_res:
result.update(res)
return result
def find_by_pattern_process(path, pattern):
files = glob.glob(f'{path}**/*.py', recursive=True)
result = set()
with concurrent.futures.ProcessPoolExecutor() as process_pool:
find_res = process_pool.map(find_pattern_line, files, [pattern] * len(files))
for res in find_res:
result.update(res)
return result
if __name__ == '__main__':
print('Threads')
start = time.time()
print(find_by_pattern_threads('/home/klush/PycharmProjects/cursor_homeworks/', pattern='import'))
end = time.time()
print(f'Execution time {end-start}')
print('Processes')
start = time.time()
print(find_by_pattern_threads('/home/klush/PycharmProjects/cursor_homeworks/', pattern='import'))
end = time.time()
print(f'Execution time {end - start}')
| UTF-8 | Python | false | false | 1,402 | py | 25 | hw14.py | 21 | 0.638374 | 0.638374 | 0 | 46 | 29.478261 | 101 |
TheCatWalk/precipitation_prediction_using_bdlstm_in_bangladesh | 5,033,701,700,893 | bdccdb5fd270b07214506612491e0d35067edfa2 | f3febe869118736ed313879997439b01af861529 | /rainfall_tutorial_withcomments.py | 623c70e363523856235920291ddc57114376cbae | [] | no_license | https://github.com/TheCatWalk/precipitation_prediction_using_bdlstm_in_bangladesh | 4963f9393a6a966f76bf5cd3d739628b2cdcb325 | a0ea3185c717a40967faeeecf6dadfa970fa6da3 | refs/heads/main | 2023-01-04T11:37:18.617674 | 2020-10-31T10:48:10 | 2020-10-31T10:48:10 | 308,818,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
from pandas.plotting import register_matplotlib_converters
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rc
from pylab import rcParams
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from keras.layers import (
Input,
Dense,
LSTM,
AveragePooling1D,
TimeDistributed,
Flatten,
Bidirectional,
Dropout
)
from sklearn import metrics
from keras.models import Model
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import load_model
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from keras.callbacks import CSVLogger
#mape
def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
tf.keras.backend.clear_session()
register_matplotlib_converters()
sns.set(style='whitegrid', palette='muted', font_scale=1.5)
rcParams['figure.figsize'] = 22, 10
RANDOM_SEED = 42
np.random.seed(RANDOM_SEED)
#reading from CSV
df = pd.read_csv("D:\RUET\Thesis Papers\Agri\Data\yosef\customized_daily_rainfall_data_Copy.csv")
#droping bad data
df = df[df.Rainfall != -999]
#droping dates (leapyear, wrong day numbers of month)
df.drop(df[(df['Day']>28) & (df['Month']==2) & (df['Year']%4!=0)].index,inplace=True)
df.drop(df[(df['Day']>29) & (df['Month']==2) & (df['Year']%4==0)].index,inplace=True)
df.drop(df[(df['Day']>30) & ((df['Month']==4)|(df['Month']==6)|(df['Month']==9)|(df['Month']==11))].index,inplace=True)
#date parcing (Index)
date = [str(y)+'-'+str(m)+'-'+str(d) for y, m, d in zip(df.Year, df.Month, df.Day)]
df.index = pd.to_datetime(date)
df['Date'] = df.index
df['Dayofyear']=df['Date'].dt.dayofyear
df.drop('Date',axis=1,inplace=True)
df.drop(['Station'],axis=1,inplace=True)
df.head()
#limiting the dataframe to just rows where StationIndex is X
datarange = df.loc[df['StationIndex'] == 1]
#splitting train and test set
train_size = int(len(datarange) * 0.9)
test_size = len(datarange) - train_size
train, test = df.iloc[0:train_size], df.iloc[train_size:len(datarange)]
#Scaling the feature and label columns of the dataset
from sklearn.preprocessing import RobustScaler
f_columns = ['Year', 'Month','Day','Dayofyear']
f_transformer = RobustScaler()
l_transformer = RobustScaler()
f_transformer = f_transformer.fit(train[f_columns].to_numpy())
l_transformer = l_transformer.fit(train[['Rainfall']])
train.loc[:, f_columns] = f_transformer.transform(train[f_columns].to_numpy())
train['Rainfall'] = l_transformer.transform(train[['Rainfall']])
test.loc[:, f_columns] = f_transformer.transform(test[f_columns].to_numpy())
test['Rainfall'] = l_transformer.transform(test[['Rainfall']])
#making smaller train and test sections withing the dataset
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
v = X.iloc[i:(i + time_steps)].to_numpy()
Xs.append(v)
ys.append(y.iloc[i + time_steps])
return np.array(Xs), np.array(ys)
time_steps = 10
# define and prepare the dataset
def get_data():
# reshape to [samples, time_steps, n_features]
X_train, y_train = create_dataset(train, train.Rainfall, time_steps)
X_test, y_test = create_dataset(test, test.Rainfall, time_steps)
return X_train, y_train, X_test, y_test
#testing
#X_test[0][0]
# define and fit the model
def get_model(X_train, y_train):
#model code
model = keras.Sequential()
#3 biderectional LSTM layers
model.add(keras.layers.Bidirectional(keras.layers.LSTM(units=128, input_shape=(X_train.shape[1], X_train.shape[2]), return_sequences = True)))
model.add(keras.layers.Dropout(rate=0.1))
model.add(keras.layers.Bidirectional(keras.layers.LSTM(units=128, return_sequences = True)))
model.add(keras.layers.Dropout(rate=0.1))
model.add(keras.layers.Bidirectional(keras.layers.LSTM(units=128 )))
model.add(keras.layers.Dropout(rate=0.1))
model.add(keras.layers.Dense(units=1, activation="relu"))
model.compile(loss="mse", optimizer="Adam",metrics=['acc'])
#training the model
#csv_logger = CSVLogger('D:\RUET\ModelSave\ModelHistory\historyStation17.csv', append=True, separator=',')
history = model.fit(
X_train, y_train,
epochs=500,
batch_size=1200,
validation_split=0.2,
shuffle=False,
#callbacks=[csv_logger]
)
return model
#get data and model
X_train, y_train, X_test, y_test = get_data()
model = get_model(X_train, y_train)
#saving the model
model.save("D:\RUET\ModelSave\ModelHistory\station17.h5")
#load a model - not needed for new epoch run
#from keras.models import load_model
keras.models.load_model('D:\RUET\ModelSave\ModelHistory\station1.h5', compile = True)
loaded_model.summary()
#Using text dataset to do a prediction
y_pred = model.predict(X_test, verbose=0)
y_pred_classes = model.predict_classes(X_test, verbose=0)
#inverst transformation
y_train_inv = l_transformer.inverse_transform(y_train.reshape(1, -1))
y_test_inv = l_transformer.inverse_transform(y_test.reshape(1, -1))
y_pred_inv = l_transformer.inverse_transform(y_pred)
y_pred_classes_inv = l_transformer.inverse_transform(y_pred_classes)
# reduce to 1d array
y_pred_inv = y_pred_inv[:, 0]
y_pred_classes_inv = y_pred_classes_inv[:, 0]
y_test_inv = y_test_inv[0, :]
#scoring and metrics section
# accuracy: (tp + tn) / (p + n)
accuracy = accuracy_score(y_test_inv, y_pred_classes_inv)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test_inv, y_pred_classes_inv, average='weighted', labels=np.unique(y_pred_classes_inv))
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test_inv, y_pred_classes_inv, average='weighted')
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test_inv, y_pred_classes_inv, average='weighted')
print('F1 score: %f' % f1)
#score
mse_score = np.sqrt(metrics.mean_squared_error(y_pred_inv,y_test_inv))
print('MSE: %f' %mse_score)
mae_score = np.sqrt(metrics.mean_absolute_error(y_pred_inv,y_test_inv))
print('MAE: %f' %mae_score)
report = classification_report(y_test_inv, y_pred_classes_inv,labels=np.unique(y_pred_classes_inv), output_dict=True)
dfscore = pd.DataFrame(report).transpose()
dfscore.to_csv('D:\RUET\ModelSave\ModelHistory\historyStation17_classification_report.csv', sep = ',')
#plot and figure section
#plot true vs pred together
plt.plot(y_test_inv.flatten(), 'b', marker='o', label="true")
plt.plot(y_pred_inv.flatten(), 'r', label="prediction")
plt.ylabel('Rainfall')
plt.xlabel('Time Step')
plt.legend()
plt.show();
#plot true vs pred separately
plt.subplot(221)
plt.plot(y_test_inv.flatten(), 'b', label="true")
plt.legend()
plt.subplot(222)
plt.plot(y_pred_inv.flatten(), 'r', label="prediction")
plt.ylabel('Rainfall')
plt.xlabel('Time Step')
plt.legend()
plt.show();
#plot full timeline
plt.plot(np.arange(0, len(y_train)), y_train_inv.flatten(), 'g', label="history")
plt.plot(np.arange(len(y_train), len(y_train) + len(y_test)), y_test_inv.flatten(), marker='.', label="true")
plt.plot(np.arange(len(y_train), len(y_train) + len(y_test)), y_pred_inv.flatten(), 'r', label="prediction")
plt.ylabel('Rainfall')
plt.xlabel('Time Step')
plt.legend()
plt.show();
#plot loss total
loss = model.history.history['loss']
epochs=range(len(loss))
plt.plot(epochs, loss, 'r', linewidth=5)
plt.title('Training loss', fontsize=40)
plt.xlabel("Epochs", fontsize=40)
plt.ylabel("Loss", fontsize=40)
plt.legend(["Loss"], fontsize=40)
plt.figure()
#plot loss zoomed
zoomed_loss = loss[300:]
zoomed_epochs = range(300,500)
plt.plot(zoomed_epochs, zoomed_loss, 'r', linewidth=5)
plt.title('Training loss', fontsize=40)
plt.xlabel("Epochs", fontsize=40)
plt.ylabel("Loss", fontsize=40)
plt.legend(["Loss"], fontsize=40)
plt.figure()
#plot loss vs validation
val_loss = model.history.history['val_loss']
epochs=range(len(val_loss))
plt.plot(epochs, val_loss, 'r')
plt.plot(epochs, loss, 'b')
plt.xlabel("Epochs")
plt.ylabel("Loss vs val_loss")
plt.legend()
plt.figure()
#plot loss vs validation
zoomed_val_loss = val_loss[300:]
zoomed_epochs = range(300,500)
plt.plot(zoomed_epochs, zoomed_val_loss, 'r')
plt.plot(zoomed_epochs, zoomed_loss, 'b')
plt.xlabel("Epochs")
plt.ylabel("Loss vs val_loss")
plt.legend()
plt.figure()
| UTF-8 | Python | false | false | 8,945 | py | 108 | rainfall_tutorial_withcomments.py | 1 | 0.681945 | 0.666182 | 0 | 273 | 30.758242 | 146 |
openstack/charm-neutron-gateway | 3,547,643,033,525 | 72156fca5247df7839b2d4e0f48ba9dd73fdb3a3 | acddbd8b628ed865aba3b8f7dc06d44090206ee0 | /actions/actions.py | 6ad5d0152d8fde81e7b6a4462c9936225ec68bfd | [
"GPL-3.0-only",
"GPL-1.0-or-later",
"Apache-2.0"
] | permissive | https://github.com/openstack/charm-neutron-gateway | a01c12625adb17f7be1a43acce28558e9f101bc3 | 500a8bd029be78558b84fa3a7d1552e82e8970eb | refs/heads/master | 2023-08-16T23:18:17.505227 | 2023-08-09T00:37:46 | 2023-08-09T00:37:46 | 52,858,829 | 26 | 20 | Apache-2.0 | false | 2023-05-01T02:17:42 | 2016-03-01T07:55:41 | 2023-04-30T18:40:42 | 2023-04-30T10:30:40 | 2,892 | 19 | 14 | 0 | Python | false | false | #!/usr/bin/env python3
import os
import socket
import sys
from keystoneauth1 import identity
from keystoneauth1 import session
from neutronclient.v2_0 import client
import yaml
_path = os.path.dirname(os.path.realpath(__file__))
_hooks_dir = os.path.abspath(os.path.join(_path, "..", "hooks"))
def _add_path(path):
if path not in sys.path:
sys.path.insert(1, path)
_add_path(_hooks_dir)
from charmhelpers.core.hookenv import (
relation_get,
relation_ids,
related_units,
)
import charmhelpers.contrib.openstack.utils as os_utils
from charmhelpers.core.hookenv import (
DEBUG,
action_get,
action_fail,
function_set,
log,
)
from neutron_utils import (
assess_status,
pause_unit_helper,
resume_unit_helper,
register_configs,
)
def pause(args):
"""Pause the Ceilometer services.
@raises Exception should the service fail to stop.
"""
pause_unit_helper(register_configs())
def resume(args):
"""Resume the Ceilometer services.
@raises Exception should the service fail to start."""
resume_unit_helper(register_configs())
def restart(args):
"""Restart services.
:param args: Unused
:type args: List[str]
"""
deferred_only = action_get("deferred-only")
services = action_get("services").split()
# Check input
if deferred_only and services:
action_fail("Cannot set deferred-only and services")
return
if not (deferred_only or services):
action_fail("Please specify deferred-only or services")
return
if action_get('run-hooks'):
log("Charm does not defer any hooks at present", DEBUG)
if deferred_only:
os_utils.restart_services_action(deferred_only=True)
else:
os_utils.restart_services_action(services=services)
assess_status(register_configs())
def run_deferred_hooks(args):
"""Run deferred hooks.
:param args: Unused
:type args: List[str]
"""
# Charm defers restarts on a case-by-case basis so no full
# hook deferalls are needed.
action_fail("Charm does not defer any hooks at present")
def show_deferred_events(args):
"""Show the deferred events.
:param args: Unused
:type args: List[str]
"""
os_utils.show_deferred_events_action_helper()
def get_neutron():
"""Return authenticated neutron client.
:return: neutron client
:rtype: neutronclient.v2_0.client.Client
:raises RuntimeError: Exception is raised if authentication of neutron
client fails. This can be either because this unit does not have a
"neutron-plugin-api" relation which should contain credentials or
the credentials are wrong or keystone service is not available.
"""
rel_name = "neutron-plugin-api"
neutron = None
for rid in relation_ids(rel_name):
for unit in related_units(rid):
rdata = relation_get(rid=rid, unit=unit)
if rdata is None:
continue
protocol = rdata.get("auth_protocol")
host = rdata.get("auth_host")
port = rdata.get("auth_port")
username = rdata.get("service_username")
password = rdata.get("service_password")
project = rdata.get("service_tenant")
project_domain = rdata.get("service_domain", "default")
user_domain_name = rdata.get("service_domain", "default")
if protocol and host and port \
and username and password and project:
auth_url = "{}://{}:{}/".format(protocol,
host,
port)
auth = identity.Password(auth_url=auth_url,
username=username,
password=password,
project_name=project,
project_domain_name=project_domain,
user_domain_name=user_domain_name)
sess = session.Session(auth=auth)
neutron = client.Client(session=sess)
break
if neutron is not None:
break
if neutron is None:
raise RuntimeError("Relation '{}' is either missing or does not "
"contain neutron credentials".format(rel_name))
return neutron
def get_network_agents_on_host(hostname, neutron, agent_type=None):
"""Fetch list of neutron agents on specified host.
:param hostname: name of host on which the agents are running
:param neutron: authenticated neutron client
:param agent_type: If provided, filter only agents of selected type
:return: List of agents matching given criteria
:rtype: list[dict]
"""
params = {'host': hostname}
if agent_type is not None:
params['agent_type'] = agent_type
agent_list = neutron.list_agents(**params)["agents"]
return agent_list
def get_resource_list_on_agents(agent_list,
list_resource_function,
resource_name):
"""Fetch resources hosted on neutron agents combined into single list.
:param agent_list: List of agents on which to search for resources
:type agent_list: list[dict]
:param list_resource_function: function that takes agent ID and returns
resources present on that agent.
:type list_resource_function: Callable
:param resource_name: filter only resources with given name (e.g.:
"networks", "routers", ...)
:type resource_name: str
:return: List of neutron resources.
:rtype: list[dict]
"""
agent_id_list = [agent["id"] for agent in agent_list]
resource_list = []
for agent_id in agent_id_list:
resource_list.extend(list_resource_function(agent_id)[resource_name])
return resource_list
def clean_resource_list(resource_list, allowed_keys=None):
"""Strip resources of all fields except those in 'allowed_keys.'
resource_list is a list where each resources is represented as a dict with
many attributes. This function strips all but those defined in
'allowed_keys'
:param resource_list: List of resources to strip
:param allowed_keys: keys allowed in the resulting dictionary for each
resource
:return: List of stripped resources
:rtype: list[dict]
"""
if allowed_keys is None:
allowed_keys = ["id", "status"]
clean_data_list = []
for resource in resource_list:
clean_data = {key: value for key, value in resource.items()
if key in allowed_keys}
clean_data_list.append(clean_data)
return clean_data_list
def format_status_output(data, key_attribute="id"):
"""Reformat data from the neutron api into human-readable yaml.
Input data are expected to be list of dictionaries (as returned by neutron
api). This list is transformed into dict where "id" of a resource is key
and rest of the resource attributes are value (in form of dictionary). The
resulting structure is dumped as yaml text.
:param data: List of dictionaires representing neutron resources
:param key_attribute: attribute that will be used as a key in the
result. (default=id)
:return: yaml string representing input data.
"""
output = {}
for entry in data:
header = entry.pop(key_attribute)
output[header] = {}
for attribute, value in entry.items():
output[header][attribute] = value
return yaml.dump(output)
def get_routers(args):
"""Implementation of 'show-routers' action."""
neutron = get_neutron()
agent_list = get_network_agents_on_host(socket.gethostname(), neutron,
"L3 agent")
router_list = get_resource_list_on_agents(agent_list,
neutron.list_routers_on_l3_agent,
"routers")
clean_data = clean_resource_list(router_list,
allowed_keys=["id",
"status",
"ha",
"name"])
function_set({"router-list": format_status_output(clean_data)})
def get_dhcp_networks(args):
"""Implementation of 'show-dhcp-networks' action."""
neutron = get_neutron()
agent_list = get_network_agents_on_host(socket.gethostname(), neutron,
"DHCP agent")
list_func = neutron.list_networks_on_dhcp_agent
dhcp_network_list = get_resource_list_on_agents(agent_list,
list_func,
"networks")
clean_data = clean_resource_list(dhcp_network_list,
allowed_keys=["id", "status", "name"])
function_set({"dhcp-networks": format_status_output(clean_data)})
def get_lbaasv2_lb(args):
"""Implementation of 'show-loadbalancers' action."""
neutron = get_neutron()
agent_list = get_network_agents_on_host(socket.gethostname(),
neutron,
"Loadbalancerv2 agent")
list_func = neutron.list_loadbalancers_on_lbaas_agent
lb_list = get_resource_list_on_agents(agent_list,
list_func,
"loadbalancers")
clean_data = clean_resource_list(lb_list, allowed_keys=["id",
"status",
"name"])
function_set({"load-balancers": format_status_output(clean_data)})
# A dictionary of all the defined actions to callables (which take
# parsed arguments).
ACTIONS = {"pause": pause,
"resume": resume,
"restart-services": restart,
"show-deferred-events": show_deferred_events,
"run-deferred-hooks": run_deferred_hooks,
"show-routers": get_routers,
"show-dhcp-networks": get_dhcp_networks,
"show-loadbalancers": get_lbaasv2_lb,
}
def main(args):
action_name = os.path.basename(args[0])
try:
action = ACTIONS[action_name]
except KeyError:
s = "Action {} undefined".format(action_name)
action_fail(s)
return s
else:
try:
action(args)
except Exception as e:
action_fail("Action {} failed: {}".format(action_name, str(e)))
if __name__ == "__main__":
sys.exit(main(sys.argv))
| UTF-8 | Python | false | false | 10,804 | py | 154 | actions.py | 112 | 0.585709 | 0.584413 | 0 | 321 | 32.657321 | 79 |
MikkieR/fermi | 2,946,347,603,032 | 380a27d967adace226999b474e884f4013d6f83a | 0513bc323766be3fc14f2800d5fb095dc8a4eaa9 | /Deconvolution/simulate.py | 7c6ef988a52a68616b33669c1c3fabec654420e0 | [] | no_license | https://github.com/MikkieR/fermi | ad4a4e10f2e741b2c7b4013b5f6b9d9ef89b1d5b | 33417bf41771f46c7537e106aff5dce5a74e9d77 | refs/heads/master | 2020-04-08T13:52:12.001081 | 2019-04-19T16:09:50 | 2019-04-19T16:09:50 | 159,410,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import random
import math
#import cv2 as cv2
from astropy.io import fits
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing
from ds9_cmap import *
from make_fermi_maps import *
_fname_prefold = '/media/mariia/Maxtor/'
_fname_data = 'database5/'
_fname_database = _fname_prefold + _fname_data
def makeNoisy(model_map_name):
os.system('cp '+model_map_name+' '+model_map_name+'.noisy')
with pyfits.open(model_map_name+'.noisy','update') as f:
print(f[0].data)
f[0].data = numpy.random.poisson( lam=f[0].data)
print(f[0].data)
def simulateObjects(sim=1):
ra = random.random() * 360
dec = random.random() * 180-90
#ra = random.random() * 360
#dec = random.random() * 180 - 90
real_xml = simulateMaps(ra=ra, dec=dec, database=_fname_data, prefold=_fname_prefold, sim=sim, xml=1)
diffuse_f = False
diff_res = ""
if (real_xml):
k = 0
f_real = open(real_xml)
lines = f_real.readlines()
min_v = 1e4
max_v = 1e-4
max_scale = 0
max_index= 0
for i in lines:
#print(i.find("degrees away from ROI center -->") >= 0.0)
if (i.find("degrees away from ROI center -->") >= 0.0):
#print(i)
k = k + 1
if (i.find('max="1e4" min="1e-4" name="Prefactor"') >= 0.0):
value_str = i.split(" ")[-1]
first = value_str.find('"')+1
second = first + 10#value_str.rfind('"')+1
value = float(value_str[first:second])
value_scale = i.split(" ")[-2]
value_s = float(value_scale[value_scale.find('"')+1 : value_scale.rfind('"')])
koef = value_s/(1e-13)
print(value_s)
if value*koef < min_v:
min_v = value*koef
if value*koef > max_v:
max_v = value*koef
if (i.find('name="Scale" scale=') >= 0.0):
value_scale_str = i.split(" ")[-1]
value_scale = float(value_scale_str[value_scale_str.find('"')+1 : value_scale_str.rfind('"')])
if max_scale < value_scale:
max_scale = value_scale
if (i.find(' name="Index" scale="') >= 0.0):
value_scale_str = i.split(" ")[-1]
value_scale = float(value_scale_str[value_scale_str.find('"')+1 : value_scale_str.rfind('"')])
if max_index < value_scale:
max_index = value_scale
if (i.find('<!-- Diffuse Sources -->') >= 0.0):
diffuse_f = True
if (diffuse_f):
diff_res += i
print(min_v)
print(max_v)
#print(k)
i_range = random.randint(a=-2, b=2)
res = '''<?xml version="1.0" ?>
<source_library title="source library">
<!-- Point Sources -->
<!-- Sources between [0.0,3.4142135624) degrees of ROI center -->
'''
res0 = '''<?xml version="1.0" ?>
<source_library title="source library">
<!-- Point Sources -->
<!-- Sources between [0.0,3.4142135624) degrees of ROI center -->
'''
if (k+i_range > 0):
k = k + i_range
for i in range(k):
r = random.random()#(np.exp(3.0*np.log(r)))
r2 = random.random()#(np.exp(3.0*np.log(r)))
val1 = np.exp(5.0*np.log(r2))*(max_v*1.15-min_v*0.1) + min_v*0.1
val2 = random.random() * (max_index-0) + 0
val3 = np.exp(5.0*np.log(r)) * (max_scale*1.15-30) + 30
val4 = random.random() * (9.98-0)*2-4.99*2 + ra
if val4>360:
val4 = val4-360
if val4<0:
val4 = val4+360
val5 = random.random() * (9.98-0)-4.99 + dec
if val5>90:
val5 = val5-90
if val5 < -90:
val5 = val5 + 90
sc_val = len(str(int(math.floor(val1))))-1
sc_val = 0
val1 = val1*1e-13
while not math.floor(val1):
sc_val = sc_val + 1
val1 = val1 * 10
print(val1)
print(sc_val)
s = '''<source ROI_Center_Distance="8.583" name="obj_''' + str(i) + '''" type="PointSource">
<spectrum apply_edisp="false" type="PowerLaw">
<!-- Source is 8.582976793871993 degrees away from ROI center -->
<!-- Source is outside ROI, all parameters should remain fixed -->
<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e-''' + str(sc_val) + '''" value="'''+str(val1)+'''"/>
<parameter free="0" max="10.0" min="0.0" name="Index" scale="-1.0" value="'''+str(val2)+'''"/>
<parameter free="0" max="5e5" min="30" name="Scale" scale="1.0" value="'''+str(val3)+'''"/>
</spectrum>
<spatialModel type="SkyDirFunction">
<parameter free="0" max="360.0" min="-360.0" name="RA" scale="1.0" value="'''+str(val4)+'''"/>
<parameter free="0" max="90" min="-90" name="DEC" scale="1.0" value="'''+str(val5)+'''"/>
</spatialModel>
</source>
'''
res = res + s
res = res +'''\n<!-- Diffuse Sources -->
</source_library>\n'''
end = '''
<!-- Diffuse Sources -->
<source name="gll_iem_v06" type="DiffuseSource">
<spectrum apply_edisp="false" type="PowerLaw">
<parameter free="1" max="100" min="0" name="Prefactor" scale="1" value="1"/>
<parameter free="0" max="1" min="-1" name="Index" scale="1.0" value="0"/>
<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>
</spectrum>
<spatialModel file="glprp.fits" type="MapCubeFunction">
<parameter free="0" max="1e3" min="1e-3" name="Normalization" scale="1.0" value="1.0"/>
</spatialModel>
</source>
<source name="iso_P8R2_CLEAN_V6_v06" type="DiffuseSource">
<spectrum apply_edisp="false" file="iso_P8R2_CLEAN_V6_v06.txt" type="FileFunction">
<parameter free="1" max="100" min="0" name="Normalization" scale="1" value="1"/>
</spectrum>
<spatialModel type="ConstantValue">
<parameter free="0" max="10.0" min="0.0" name="Value" scale="1.0" value="1.0"/>
</spatialModel>
</source>
</source_library>'''
res = res
xml_name = _fname_database + 'sky' + str(sim) + '_coord_ra' + str(ra)+'_dec' + str(dec) + '_points_src_model_const.xml'
f = open(xml_name, 'w')
f.write(res)
f.close()
simulateMaps(ra=ra, dec=dec, database=_fname_data, prefold=_fname_prefold, sim=sim, xml=0, flag='_points')
makeNoisy(_fname_database + 'sky' + str(sim) + '_coord_ra' + str(ra)+'_dec' + str(dec) + '_points_model_map.fits')
res = res0 + diff_res
xml_name = _fname_database + 'sky' + str(sim) + '_coord_ra' + str(ra)+'_dec' + str(dec) + '_back_src_model_const.xml'
f = open(xml_name, 'w')
f.write(res)
f.close()
simulateMaps(ra=ra, dec=dec, database=_fname_data, prefold=_fname_prefold, sim=sim, xml=0, flag='_back')
makeNoisy(_fname_database + 'sky' + str(sim) + '_coord_ra' + str(ra)+'_dec' + str(dec) + '_back_model_map.fits')
pool = multiprocessing.Pool(8)
offset=1
zip(*pool.map(simulateObjects, range(400, 400 + 2 * offset, offset)))
| UTF-8 | Python | false | false | 7,464 | py | 21 | simulate.py | 14 | 0.51313 | 0.469453 | 0 | 180 | 40.466667 | 136 |
Tnek/binaryninja-moxie | 15,444,702,416,770 | 0fdaa9bf0163249a679a4c1286d7fc69bd1770ab | 2a4620f6f36d94fb7de879c97af6b6442690f0ba | /__init__.py | 45923975f13a50bf878e861e19e4908942d4df2f | [] | no_license | https://github.com/Tnek/binaryninja-moxie | e0819d79a4579803fb0f77a5cfe842692631aec1 | 02cc6fdd5dd79d3c8cc8918eb3cacb36b00b6861 | refs/heads/master | 2020-04-03T07:31:04.543687 | 2018-10-29T15:10:24 | 2018-10-29T15:10:24 | 155,105,011 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from binaryninja import Architecture, BinaryViewType, Endianness
from Moxie import *
Moxie.register()
BinaryViewType['ELF'].register_arch(0xdf, Endianness.BigEndian, Architecture["moxie"])
| UTF-8 | Python | false | false | 191 | py | 5 | __init__.py | 4 | 0.806283 | 0.801047 | 0 | 5 | 37 | 86 |
k3vinfoo/NBAi | 18,476,949,330,717 | 0717b274f171b34facd09f13d0ffa572bdc0a10d | f5ed1c51e35b6ca91c86289f8b4718e1453ab045 | /tensorflow_start.py | 13f5df5b41ea40e172711c8e9c8908e61e5795e6 | [] | no_license | https://github.com/k3vinfoo/NBAi | 81a1b9d367f36873e1556440f8e4a1a3fd59a767 | 4d3948f3fb184c59ac9a0e23982afc0658dcb2c8 | refs/heads/master | 2021-05-10T19:00:58.959449 | 2017-09-24T12:29:07 | 2017-09-24T12:29:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import tensorflow as tf
filename = "scrapped_withRuns.csv"
filename_queue = tf.train.string_input_producer([filename])
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def prediction_model(n=1, log_progress=False):
with tf.Session() as session:
hp = tf.placeholder(tf.float32, [n], name=’home_pts’)
vp = tf.placeholder(tf.float32, [n], name=’visitor_pts’)
hp = tf.string_to_number(hp)
vp = tf.string_to_number(vp)
hp_t= tf.Variable([1.0], trainable=True) # training variable: slope
vp_t = tf.Variable([1.0], trainable=True) # training variable: intercept
y = tf.add(tf.mul(m, x), b) # fit y_i = m * x_i + b
# actual values (for training)
y_act = tf.placeholder(tf.float32, [n], name=’y_’)
# minimize sum of squared error between trained and actual.
error = tf.sqrt((y – y_act) * (y – y_act))
# train_step = tf.train.GradientDescentOptimizer(0.01).minimize(error)
train_step = tf.train.AdamOptimizer(0.05).minimize(error)
# generate input and output data with a little random noise.
x_in, y_star = make_data(n)
init = tf.initialize_all_variables()
session.run(init)
feed_dict = {x: x_in, y_act: y_star}
for i in range(30 * n):
y_i, m_i, b_i, _ = session.run([y, m, b, train_step], feed_dict)
err = np.linalg.norm(y_i – y_star, 2)
if log_progress:
print(“%3d | %.4f %.4f %.4e” % (i, m_i, b_i, err))
print(“Done! m = %f, b = %f, err = %e, iterations = %d”
% (m_i, b_i, err, i))
print(” x: %s” % x_in)
print(“Trained: %s” % y_i)
print(” Actual: %s” % y_star)
def main():
reader = tf.TextLineReader(skip_header_lines=1)
key, value = reader.read(filename_queue)
file_length = file_len(filename)
############For Sample File test##############
#record_defaults = [["home_team"],["home_team2"],["home_team3"],["home_team4"],["home_team5"]]
#col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults)
#features = tf.stack([col1, col2, col3, col4, col5])
############END OF SAMPLE FILE TEST###########
# Default values, in case of empty columns. Also specifies the type of the
# decoded result.
record_defaults = [["home_team"], ["home_team_abbrv"], ["away_team"], ["away_team_abbrv"], ["period"], ["play_clock_time"], ["team_committing_action"], ["p1"], ["p2"], ["p3"],["p4"], ["p5"], ["p6"], ["p7"], ["p8"],["p9"], ["p10"],\
["gen_desc"], ["shot_value"], ["rebound_designation"],["overall_desc"], ["home_pts"], ["visitor_pts"],["run?"],["in run"]]
col1, col2, col3, col4, col5, col6, col7,col8,col9,col10,col11,col12,col13,col14,col15,col16,col17,col18,col19, col20, col21, col22, col23, col24, col25 = tf.decode_csv(value, record_defaults)
print(record_defaults)
features = tf.stack([col1, col2, col3, col4, col5, col6, col7,col8,col9,col10,col11,col12,col13,col14,col15,col16,col17,col18,col19, col20, col21, col22, col23, col24, col25])
with tf.Session() as sess:
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(file_length):
# Retrieve a single instance:
example, label = sess.run([features, col25])
print("Example:", example)
print("Label:", label)
coord.request_stop()
coord.join(threads)
print("done loading")
main()
| UTF-8 | Python | false | false | 3,623 | py | 7 | tensorflow_start.py | 4 | 0.585495 | 0.547838 | 0 | 80 | 43.8125 | 232 |
hchache/Data-Incubator-Challenge | 12,859,132,093,040 | 31e77cdd292e8ea124bc9e229a7ac8c28fbccfef | aa44c3bada1eb6dad2207c635dcae90611a09d5c | /Question 2.py | 67bd87c92a027a499a3d0182f4fb29de2882a3c5 | [] | no_license | https://github.com/hchache/Data-Incubator-Challenge | 01a91bc7b31389704b09c4102bc04ea5bbf65ce9 | 3f6b316f57c60dca50e475e2972cd6756902d11e | refs/heads/master | 2020-03-14T05:42:21.381294 | 2018-04-30T14:59:45 | 2018-04-30T14:59:45 | 131,469,880 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
###### Author: Hitesh Sahadeo Chache
#
# Jupyter Link: https://github.com/hchache/Data-Incubator-Challenge/blob/master/Question%202.ipynb
#
###### Code - Start
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy import interpolate
from scipy.stats import chisquare
from scipy import stats
from sklearn import linear_model
pd.options.display.float_format = '{:,.10f}'.format
# Read input CSV file - Montana
df_mt = pd.read_csv("MT-clean.csv", low_memory=False)
# df_mt.head()
# Read input CSV file - Vermont
df_vt = pd.read_csv("VT-clean.csv", low_memory=False)
# df_vt.head()
# #### What proportion of traffic stops in Montana involved male drivers? In other words, divide the number of traffic stops involving male drivers by the total number of stops.
male_prop, female_prop = df_mt.driver_gender.value_counts()/df_mt.driver_gender.count()
print("proportion of traffic stops in Montana involved male drivers: ",format(male_prop, '.10g'))
# #### How many more times likely are you to be arrested in Montana during a traffic stop if you have out of state plates?
out_of_state_false, out_of_state_true = df_mt.out_of_state.value_counts()/df_mt.out_of_state.count()
print("if you have out of state plates, you are ", format(out_of_state_true/out_of_state_false, '.10g'),
" times more likely to be arrested in Montana during a traffic stop")
m = df_mt.is_arrested.value_counts()/df_mt.is_arrested.count()
v = df_vt.is_arrested.value_counts()/df_vt.is_arrested.count()
# #### Perform a (χ2) test to determine whether the proportions of arrests in these two populations are equal. What is the value of the test statistic?
#
# | | Arrested | Not Arrested |
# |------|------|------|
# | MT | 17195| 807923 |
# | VT | 3331| 279954 |
#
chi_squared_stat = (((m-v)**2)/v).sum()
print(format(chi_squared_stat, '.10g'))
observed = np.array(m)
expected = np.array(v)
chisquare_value, pvalue = chisquare(observed, expected)
print("value of the test statistic: ",format(chisquare_value, '.10g'))
# #### What proportion of traffic stops in Montana resulted in speeding violations? In other words, find the number of violations that include "Speeding" in the violation description and divide that number by the total number of stops (or rows in the Montana dataset).
print("proportion of traffic stops in Montana resulted in speeding violations: ",
format(df_mt.violation.value_counts()['Speeding']/df_mt.violation.count(), '.10g'))
# #### How much more likely does a traffic stop in Montana result in a DUI than a traffic stop in Vermont? To compute the proportion of traffic stops that result in a DUI, divide the number of stops with "DUI" in the violation description by the total number of stops.
m_DUI = (df_mt['violation'].str.contains("DUI") == True).sum()/df_mt.violation.count()
v_DUI = (df_vt['violation'].str.contains("DUI") == True).sum()/df_vt.violation.count()
print("a traffic stop in Montana result in a DUI than a traffic stop in Vermont: ",format(m_DUI/v_DUI, '.10g'))
# #### What is the extrapolated, average manufacture year of vehicles involved in traffic stops in Montana in 2020? To answer this question, calculate the average vehicle manufacture year for each year's traffic stops. Extrapolate using a linear regression.
# Assign previous value to NaN in column stop_date
df_mt_ext = df_mt
stop_date_col= df_mt_ext['stop_date']
is_stop_date_null = stop_date_col.isnull()
stop_date_null_true = stop_date_col[is_stop_date_null]
a = int(stop_date_null_true.index[0])
df_mt_ext['stop_date'].fillna(df_mt_ext['stop_date'][a-1], inplace = True)
df_mt_ext["stop_date"] = pd.to_datetime(df_mt_ext["stop_date"])
df_mt_ext["stop_year"] = df_mt_ext['stop_date'].dt.year
# Remove all rows which contains vehicle year as UNK, NON and NaN
df_mt_ext['vehicle_year'].fillna('0', inplace = True)
a = df_mt_ext['vehicle_year'].isin(['UNK','NON-','0'])
b = df_mt_ext[a]
c = b.index
df_mt_ext = df_mt_ext.drop(c)
# Groupby stopyear and calculate mean vehicle year
df_mt_ext['vehicle_year'] = df_mt_ext['vehicle_year'].astype(int)
ab = df_mt_ext.groupby('stop_year')['vehicle_year'].mean().reset_index()
# Using interpolate
x = ab['stop_year']
y = ab['vehicle_year']
f = interpolate.interp1d(x, y,kind='linear', fill_value='extrapolate', bounds_error=False)
xnew = int(2020)
# Answer
y_predicted_interpolate = float(f(xnew))
print("Using interpolate - the average vehicle manufacture year: ",format(y_predicted_interpolate, '.10g'))
# Using stats.linregress
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
# Answer
y_predicted_stats = 2020*slope + intercept
print("Using Stats - the average vehicle manufacture year: ",format(y_predicted_stats, '.10g'))
# Answer tot next question
print("the p-value of this linear regression: ",format(p_value, '.10g'))
regr = linear_model.LinearRegression()
x_train = x.values.reshape((-1, 1))
y_train = y.values.reshape((-1, 1))
regr.fit(x_train, y_train)
xnew1 = [2020]
xnew1 = np.reshape(xnew1, (-1, 1))
ynew1 = regr.predict(xnew1)
print("Using sklearn linear model - the average vehicle manufacture year: ",ynew1)
# #### Combining both the Vermont and Montana datasets, find the hours when the most and least number of traffic stops occurred. What is the difference in the total number of stops that occurred in these two hours? Hours range from 00 to 23. Round stop times down to compute this difference.
# Merge two datasets
df_mt_merge = pd.read_csv("MT-clean.csv", low_memory=False)
df_merged = pd.merge(df_mt_merge, df_vt, how='outer', suffixes=('_mt', '_vt'))
df_merged['stop_hour'] = df_merged.stop_time.str[:2]
stop_hours = df_merged['stop_hour'].value_counts()
print("Difference in the total number of stops that occurred in these two hours: ",
format(stop_hours[0] - stop_hours[len(stop_hours)-1], '.10g'))
# #### We can use the traffic stop locations to estimate the areas of the counties in Montana. Represent each county as an ellipse with semi-axes given by a single standard deviation of the longitude and latitude of stops within that county. What is the area, in square kilometers, of the largest county measured in this manner? Please ignore unrealistic latitude and longitude coordinates
df_area = df_mt[['id','county_name','lat','lon']]
# id 825118
# county_name 821062
# lat 824682
# lon 824682
# Filling the county name would cost unnecessary computational power.
# by deleting NaN records in county column, we are loosing 0.4% Data
county_col= df_area['county_name']
is_county_col_null = county_col.isnull()
county_col_null_true = county_col[is_county_col_null]
df_area = df_area.drop(county_col_null_true.index)
df_area_std = df_area.groupby('county_name')['lat','lon'].std().reset_index()
# Considering each lan degree equals to 111.321 kilometers
lat_in_km = (df_area_std['lat'] * math.pi / 180)* 111.321
lon_in_km = (df_area_std['lon'] * math.pi / 180) * 111.321
df_area_std['area'] = math.pi * lat_in_km * lon_in_km
print("Area of the largest county: ",format(df_area_std['area'].max(), '.10g'))
| UTF-8 | Python | false | false | 7,152 | py | 6 | Question 2.py | 3 | 0.711649 | 0.692071 | 0 | 176 | 39.619318 | 389 |
theromis/mlpiper | 15,676,630,654,301 | bced8b0ff19d07380c70622f9838e32ff82dd0e5 | 6e423cddd8698bc662bcc3208eb7a8fdb2eb0d72 | /mlops/parallelm/mlops/stats/table.py | 8bd3b851455f58bc97cb91825d0b9bedbf96f8ec | [
"Apache-2.0"
] | permissive | https://github.com/theromis/mlpiper | 7d435343af7b739767f662b97a988c2ccc7665ed | 738356ce6d5e691a5d813acafa3f0ff730e76136 | refs/heads/master | 2020-05-05T04:44:00.494105 | 2019-04-03T19:53:01 | 2019-04-03T22:02:53 | 179,722,926 | 0 | 0 | Apache-2.0 | true | 2019-04-05T17:06:02 | 2019-04-05T17:06:01 | 2019-04-03T22:02:57 | 2019-04-05T17:02:52 | 14,857 | 0 | 0 | 0 | null | false | false | """
MLOps supports propagating a table up to the PM system. This file contains table definition methods.
"""
import os
import copy
import six
from parallelm.mlops.mlops_env_constants import MLOpsEnvConstants
from parallelm.mlops.stats.mlops_stat import MLOpsStat
from parallelm.mlops.stats_category import StatGraphType, StatsMode
from parallelm.mlops.mlops_exception import MLOpsException
from parallelm.mlops.stats.mlops_stat_getter import MLOpsStatGetter
from parallelm.protobuf import InfoType_pb2
from collections import OrderedDict
def verify_table_from_list_of_lists(tbl_data):
"""
Verify that tbl_data is in the format expected
:param tbl_data:
:return: Throws an exception in case of badly formatted table data
"""
if not isinstance(tbl_data, list):
raise MLOpsException("Table data is not in the format of list of lists")
row_idx = 0
for item in tbl_data:
if not isinstance(item, list):
raise MLOpsException("Each item of tbl_data should be a list - row {} is not a list".format(row_idx))
row_idx += 1
if len(tbl_data) < 2:
raise MLOpsException("Table data must contain at least column names and one row of data")
nr_cols = len(tbl_data[0])
row_idx = 0
for row in tbl_data:
if len(row) != nr_cols:
raise MLOpsException("Row {} items number is {} which is not equal to number of columns provided {}".
format(row_idx, len(row), nr_cols))
row_idx += 1
def is_list_of_lists(tbl_data):
"""
Check if tbl_data is list of lists
:param tbl_data:
:return:
"""
if not isinstance(tbl_data, list):
return False
return all(isinstance(item, list) for item in tbl_data)
class Table(MLOpsStatGetter):
"""
A container for tabular/matrix data object.
By using Table it is possible to report tabular data to MLOps.
:Example:
>>> tbl = Table().name("MyTable").cols(["Iteration number", "Error"])
>>> for iter_id in range(0, 100):
>>> error_value = do_calculation()
>>> row_name = join(["row num",iter_id])
>>> tbl.add_row(row_name, error_value])
>>> mlops.set_stat(tbl)
The above example creates a Table object and populates it with data.
The call .name("MyTable") sets the name of the table. This name will be used when the table
is displayed in the MLOps UI. The .cols() method will set the names of the cols, and also
the expected number of columns.
By calling .add_row() the user can add rows to the table, where the argument provided is the row name and a list of
data items to add to the row. The number of data items in the list should be the same as the number of columns.
Finally, the call to mlops.set_stat(tbl) generates the table statistics and pushes it to MLOps
for further processing.
"""
def __init__(self):
self._name = "Table"
self._cols_names = []
self._rows_names = []
self._tbl_rows = []
def name(self, name):
"""
Set the name of the table/matrix
:param name: table name
:return: the Table object
"""
self._name = name
return self
def _to_dict(self):
tbl_dict = OrderedDict()
row_names = list(self._rows_names)
for line in self._tbl_rows:
if len(row_names) > 0:
row_name = row_names.pop(0)
else:
row_name = ""
tbl_dict[row_name] = OrderedDict()
col_idx = 0
for col in line:
tbl_dict[row_name][self._cols_names[col_idx]] = col
col_idx += 1
return tbl_dict
def columns_names(self, name_list):
"""
Set the table column names
:param name_list: List of names
:return: self
"""
if not isinstance(name_list, list):
raise MLOpsException("Columns names should be provided as a list")
if len(self._tbl_rows) > 0:
row_len = len(self._tbl_rows[0])
if len(name_list) != row_len:
raise MLOpsException("Number of columns names provided must match number of columns")
self._cols_names = name_list
return self
def cols(self, name_list):
"""
Set the table column names
:param name_list: List of names
:return: self
"""
return self.columns_names(name_list)
def add_row(self, arg1, arg2=None):
"""
Add a row to the table.
:param arg1: Name of the row, or list of data items
:param arg2: List of data items (if argument 1 was provided)
:return: self
"""
row_name = ""
row_data = []
if isinstance(arg1, six.string_types):
# The case where we get the name of the row as the first argument
row_name = copy.deepcopy(arg1)
if arg2 is None:
raise MLOpsException("no data provided for row")
if not isinstance(arg2, list):
raise MLOpsException("Data should be provided as a list")
row_data = copy.deepcopy(arg2)
elif isinstance(arg1, list):
# The case where we get only data without the line/row name
row_data = copy.deepcopy(arg1)
else:
raise MLOpsException("Either provide row_name, data or just data")
if len(self._tbl_rows) > 0:
if len(self._tbl_rows[0]) != len(row_data):
raise MLOpsException("row length must be equal to length of previously provided rows")
self._tbl_rows.append(row_data)
self._rows_names.append(row_name)
return self
def add_rows(self, rows):
if not isinstance(rows, list):
raise MLOpsException("Rows data should be provided as list of lists")
for row in rows:
self.add_row(row)
return self
def _to_semi_json(self, escape=True):
"""
Convert to string that can be inserted into database and visualized by UI.
:param escape: indicates whether to escape double quotes
When escape=True, format is:
"{\"row1\":{\"col1\":1.0,\"col2\":2.0}, \"row2\":{\"col1\":3.0,\"col2\":4.0}}"
When escape=False, format is:
"{"row1":{"col1":1.0,"col2":2.0}, "row2":{"col1":3.0,"col2":4.0}}"
:return: string with table in the above format
"""
# This is a workaround for REF-4151. It adds a unique label to each row that is removed by the UI.
unique_label = True
if os.environ.get(MLOpsEnvConstants.MLOPS_MODE, "STAND_ALONE") is "STAND_ALONE":
unique_label = False
num_rows = len(self._tbl_rows)
if len(self._rows_names) != num_rows:
raise MLOpsException("Number of row names {} must match number of rows {}"
.format(self._rows_names, num_rows))
num_col_names = len(self._cols_names)
num_cols = 0
if num_rows > 0:
num_cols = len(self._tbl_rows[0])
if num_cols > 0 and num_col_names > 0 and num_cols != num_col_names:
raise MLOpsException("Number of column names {} must match number of columns {}"
.format(num_col_names, num_cols))
uniq_row_label_start = ""
uniq_row_label_end = ""
if unique_label:
uniq_row_label_start = "__REMOVE"
uniq_row_label_end = "LABEL__"
if escape:
row_name_start = '\\\"' + uniq_row_label_start
row_name_end = '\\\":{'
col_name_start = '\\\"'
col_name_end = '\\\":'
string_entry_start = '\\"'
string_entry_end = '\\\"'
else:
row_name_start = '"' + uniq_row_label_start
row_name_end = '":{'
col_name_start = '"'
col_name_end = '":'
string_entry_start = '"'
string_entry_end = '"'
s = '{'
for i in range(num_rows):
s += row_name_start
if unique_label:
s += str(i) + uniq_row_label_end
s += self._rows_names[i]
s += row_name_end
for j in range(num_cols):
s += col_name_start
if num_col_names > 0:
s += self._cols_names[j]
s += col_name_end
if isinstance(self._tbl_rows[i][j], six.string_types):
s += string_entry_start
s += self._tbl_rows[i][j]
s += string_entry_end
else:
s += str(self._tbl_rows[i][j])
if j < (num_cols - 1):
s += ', '
else:
s += '}'
if i < (num_rows - 1):
s += ', '
else:
s += '}'
return s
def get_mlops_stat(self, model_id):
if len(self._tbl_rows) == 0:
raise MLOpsException("No rows data found in table object")
tbl_data = self._to_semi_json(escape=False)
semi_json = self._to_semi_json()
mlops_stat = MLOpsStat(name=self._name,
stat_type=InfoType_pb2.General,
graph_type=StatGraphType.MATRIX,
mode=StatsMode.Instant,
data=tbl_data,
string_data=semi_json,
json_data_dump = tbl_data,
model_id=model_id)
return mlops_stat
| UTF-8 | Python | false | false | 9,702 | py | 712 | table.py | 323 | 0.546794 | 0.53927 | 0 | 289 | 32.570934 | 119 |
fujiazhiyu/pdfcontract | 3,856,880,641,508 | be191ac539ef692e9b9380f1b3cfd3de3aa96631 | 62adbf5107f65094a70e40cbcefa5c8db71283c3 | /flaskr/contract.py | de6767e47c33c602aeed50818ec7d170a7624c00 | [
"Apache-2.0"
] | permissive | https://github.com/fujiazhiyu/pdfcontract | 9156c6afb960f8ea4e6b75c2aaefc09f4858449f | 2952662fceb4d907c72a74e24dae1fb364fefdf9 | refs/heads/master | 2022-11-25T14:30:31.539822 | 2020-02-15T06:39:35 | 2020-02-15T06:39:35 | 201,868,928 | 0 | 0 | Apache-2.0 | false | 2022-11-22T03:57:19 | 2019-08-12T06:14:41 | 2020-02-15T06:39:37 | 2022-11-22T03:57:16 | 10,561 | 0 | 0 | 4 | HTML | false | false | # -*- coding: utf-8 -*-
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for, Flask, make_response
)
from flask_weasyprint import HTML, CSS, render_pdf
from urllib.parse import quote
from xpinyin import Pinyin
import os
import sys
import time
# from flask import current_app as app
bp = Blueprint('contract', __name__)
@bp.route('/', methods=['GET', 'POST'])
def onlinepreview():
return redirect(url_for('contract.select'))
@bp.route('/contracttype', methods=['GET', 'POST'])
def select():
return render_template('type-selection.html')
@bp.route('/application-contract/<contract_title>', methods=['GET', 'POST'])
def application(contract_title):
html = render_template('application_contract.html')
pdf_file = render_contract(html).write_pdf()
return contract_response(pdf_file, contract_title)
@bp.route('/commission-contract/<contract_title>', methods=['GET', 'POST'])
def commission(contract_title):
html = render_template('commissioned_contract.html')
commission_document = render_contract(html)
teacherlevel_document = teacherlevel_attachment()
# 添加附件
all_pages = [p for doc in [commission_document, teacherlevel_document] for p in doc.pages]
pdf_file = commission_document.copy(all_pages).write_pdf()
return contract_response(pdf_file, contract_title)
@bp.route('/instruction-contract/<contract_title>', methods=['GET', 'POST'])
def instruction(contract_title):
html = render_template('instruction_contract.html')
instruction_document = render_contract(html)
hygge_document = hygge_contract(contract_title)
# 合并两个pdf 见:https://weasyprint.readthedocs.io/en/latest/api.html#weasyprint.document.Document.copy
# 以及:https://stackoverflow.com/questions/38987854/django-and-weasyprint-merge-pdf
all_pages = [p for doc in [instruction_document, hygge_document] for p in doc.pages]
pdf_file = instruction_document.copy(all_pages).write_pdf()
return contract_response(pdf_file, contract_title)
@bp.route('/application-commission-contract/<contract_title>', methods=['GET', 'POST'])
def application_commission(contract_title):
html = render_template('application_commissioned_contract.html')
pdf_file = render_contract(html).write_pdf()
return contract_response(pdf_file, contract_title)
# 生成灰格教育咨询合同(单页那个)的css文件
def hygge_contract(contract_title):
sdf = Pinyin().get_pinyin(contract_title.split('-')[0], '').upper()
# 页眉和日期
with open('flaskr/static/hyggeadd.css', 'w') as hygge_css:
hygge_css.write("@media print { @page { @top-left { content: '咨询服务合同号: " + Pinyin().get_initials(contract_title.split("-")[0], '') + time.strftime(
"%Y%m%d", time.localtime()) + "'}} " + ".sign-date::before { content: '" + time.strftime(" %Y 年 %m 月 %d 日", time.localtime()) + "'; }" + ".contract-series::before { content: 'T-" + time.strftime("%Y%m%d", time.localtime()) + "-" + Pinyin().get_pinyin(contract_title.split("-")[0], "").upper() + "';}}")
html = render_template('hygge_contract.html')
cssfile = CSS(url_for("static", filename='hyggeadd.css'))
return HTML(string=html).render(stylesheets=[cssfile])
def teacherlevel_attachment():
html = render_template('teacherlevel.html')
return HTML(string=html).render()
def render_contract(html):
userstylesheet_url = url_for("static", filename='userStyles.css')
cssfile = CSS(url_for("static", filename="sample.css"))
if os.path.exists("flaskr/" + userstylesheet_url):
cssfile = CSS(userstylesheet_url)
return HTML(string=html).render(stylesheets=[cssfile])
def contract_response(pdf_file, contract_title):
# quote为url编码,这种写法也避免了safari下载中文文件名乱码
http_response = make_response(pdf_file)
http_response.headers["Content-Type"] = "application/octet-stream; charset=utf-8"
http_response.headers['Content-Disposition'] = (
"attachment; filename*=UTF-8''{}").format(quote(contract_title))
return http_response
| UTF-8 | Python | false | false | 4,122 | py | 20 | contract.py | 3 | 0.697289 | 0.693775 | 0 | 95 | 40.936842 | 314 |
MyPlanTodo/DeepStudy | 11,123,965,312,737 | 717074552e4b4394bd262574a968388ba4aa680d | 3ab6f9b780fe6bbe5c0e59d2d098ef912d1b087b | /connection.py | d6caa6afe6141034fb2d62f9459e8d052d0e3215 | [] | no_license | https://github.com/MyPlanTodo/DeepStudy | 663546e250c5c520e1dbcaa22c0e112308e66e06 | 7ddea4306352c3a5416007ff461ccb19dab94f4a | refs/heads/master | 2021-01-20T12:55:44.075466 | 2017-02-05T16:46:46 | 2017-02-05T16:46:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding=utf-8
#!/usr/bin/env python
import random
class Connection(object):
def __init__(self,upstream_node,downstream_node):
'''
初始化连接,权重初始化为一个很小的随机值
:param upstream_node: 上游节点
:param downstream_node: 下游节点
'''
self.upstream_node = upstream_node
self.downstream_node = downstream_node
self.weight = random.uniform(-0.1,0.1)
self.gradient = 0.0
def calc_gradient(self):
'''
计算梯度
:return:
'''
self.gradient = self.downstream_node.delta * self.upstream_node.output
def get_gradient(self):
return self.gradient
def update_weight(self,rate):
'''
根据梯度下降算法更新权重
:param rate:
:return:
'''
self.calc_gradient()
self.weight += rate * self.gradient
def __str__(self):
'''
打印连接信息
:return:
'''
return '(%u-%u)->(%u-%u) = %f' %(
self.upstream_node.layer_index,
self.upstream_node.node_index,
self.downstream_node.layer_index,
self.downstream_node.node_index,
self.weight )
class Connections(object):
def __init__(self):
self.connections = []
def add_connection(self,connection):
self.connections.append(connection)
def dump(self):
for conn in self.connections:
print conn
| UTF-8 | Python | false | false | 1,510 | py | 15 | connection.py | 15 | 0.549645 | 0.544681 | 0 | 58 | 23.310345 | 78 |
katerina7479/python-units-of-measure | 3,281,355,052,909 | df0912566fd22229441647afbeb37bbe00fffe9b | a48271319207e2e178c41ab29dbaecb04bc5963c | /pyuom/Angle.py | ece13af44f58621a352815297fccd3067c0c4aed | [
"MIT"
] | permissive | https://github.com/katerina7479/python-units-of-measure | eee8ea8fcb9aec98a6eb0cd872069c01dd921c1e | 436829f7aeeec75999bece3736f0eb4e39daf0ad | refs/heads/master | 2016-08-07T02:20:39.713168 | 2013-05-31T04:35:04 | 2013-05-31T04:35:04 | 10,397,077 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | from PhysicalQuantity import PhysicalQuantity
from UnitOfMeasure import UnitOfMeasure
from math import pi
class Angle(PhysicalQuantity):
def __init__(self, value, unit):
super(Angle, self).__init__(value, unit)
# Degrees
new_unit = UnitOfMeasure(
u"\u00b0",
lambda x: x,
lambda y: y
)
new_unit.addAlias('deg')
new_unit.addAlias('degs')
new_unit.addAlias('degree')
new_unit.addAlias('degrees')
self.registerUnitOfMeasure(new_unit)
# Radians
new_unit = UnitOfMeasure(
'rad',
lambda x: x * pi / 180,
lambda y: y / pi * 180
)
new_unit.addAlias('rads')
new_unit.addAlias('radian')
new_unit.addAlias('radians')
self.registerUnitOfMeasure(new_unit)
| UTF-8 | Python | false | false | 853 | py | 17 | Angle.py | 16 | 0.560375 | 0.549824 | 0 | 34 | 24.088235 | 48 |
bbc94/Algorithm | 1,065,151,932,057 | 1a953e16910865eff618050b632cde9006a4ec1e | 618a7393d82099bc70fcda5ff248d11103e1756b | /Next_bigger_Num.py | ea46b1310bfdb0d920082a60883d9b797e10ac93 | [] | no_license | https://github.com/bbc94/Algorithm | fd3bddb6e6fc58b565fa3298b498342ddeace574 | 90d846343d3115a97f90024fda3cfeef3f476f6c | refs/heads/master | 2020-04-20T05:23:36.591255 | 2019-02-17T06:03:22 | 2019-02-17T06:03:22 | 168,655,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def solution(n):
n_bi = bin(n).count('1')
a=n+1
while a>n:
b=str(bin(a)).count('1')
if b==n_bi:
return a
else:a+=1
print(solution(78)) | UTF-8 | Python | false | false | 184 | py | 28 | Next_bigger_Num.py | 27 | 0.451087 | 0.418478 | 0 | 11 | 15.818182 | 32 |
SkyThes/lilygo-t5-4.7-image-webserver | 15,925,738,761,636 | 80ff61c8f304c2acbfeab143704252dcffd051d4 | 16fb24ec28de28557188b67c70117eed20c9d056 | /server/utils.py | c845c197d7d383c409bbb9a8b67b8ddccdeae275 | [] | no_license | https://github.com/SkyThes/lilygo-t5-4.7-image-webserver | dfcf6a2496a74d32ffca54c31111cdbb0f076cf6 | 880d50b847bd89db97ff0c96835eb91f538683d3 | refs/heads/master | 2023-05-08T02:28:43.216167 | 2021-05-31T18:24:19 | 2021-05-31T18:24:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import cv2
import numpy as np
def resize(img, max_width, max_height):
'''Resize image so it fits within our '''
ratio = float(img.shape[1]) / float(img.shape[0])
ratio_resize = float(max_width) / float(max_height)
if ratio < ratio_resize:
# we can scale to max height
# calculate the target width
target_width = int(max_height * ratio)
if target_width % 2 == 1:
target_width = target_width + 1
img = cv2.resize(img, (target_width, max_height))
else:
# we can do max height
target_height = int(max_width / ratio)
if target_height % 2 == 1:
target_height = target_height + 1
img = cv2.resize(img, (max_width, target_height))
# diffH = int((self.character_size[0] - img.shape[0]) / 2)
# diffW = int((self.character_size[1] - img.shape[1]) / 2)
# img = cv2.copyMakeBorder(
# img, diffH, diffH, diffW, diffW, cv2.BORDER_CONSTANT, value=255)
return img
def prepare_image(img):
# LilyGo T5 4.7 has a resolution of 960x540
# resize the image to fit on the screen
HOR_RES, VERT_RES = 960, 540
img2 = resize(img, HOR_RES, VERT_RES)
# cv2.imshow('img', img2)
# cv2.waitKey(0)
# map the image to one contigous array
# default dtype is uint8 -> 8 bits per integer (0-255)
img3 = img2.reshape(-1)
# we need to go to 4 bit integers since that is wat the e-ink display supports
# remap in range 0 - 15
img3 = (img3 / 16).astype(np.uint8)
# remap every value below 250 to 0 (black) and everything above to 15 (white)
# img3[img3 <= 250] = 0
# img3[img3 > 250] = 15
# pack two pixels per byte
img4 = np.empty((img3.shape[0] // 2,), np.uint8)
for i in range(0, img3.shape[0], 2):
img4[i // 2] = img3[i+1] << 4 | img3[i]
return img4, img2.shape[1], img2.shape[0] | UTF-8 | Python | false | false | 1,868 | py | 4 | utils.py | 3 | 0.602784 | 0.549786 | 0 | 47 | 38.765957 | 82 |
szonespider/wuhan | 17,136,919,534,276 | a47d9624638e2465c68a7ede1c09a430c4480e13 | b8bf930189a3cfd60924edc69f2735d388f91e36 | /work/zhu/shandong/tengzhou.py | 67b539dc5e67b6e8d87b7ad6cc41f0b3d7976baf | [] | no_license | https://github.com/szonespider/wuhan | 170c4795d48fe47294276d3ad7ff5841186ee613 | 25d40929f7b451d36a34a1e44fe376c47e04d04e | refs/heads/master | 2020-04-01T22:40:54.602013 | 2019-01-29T08:46:45 | 2019-01-29T08:46:45 | 153,721,750 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import time
import pandas as pd
import re
from lxml import etree
from selenium import webdriver
from bs4 import BeautifulSoup
from lmf.dbv2 import db_write
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from zhulong.util.etl import est_html,est_meta
# __conp=["postgres","since2015","192.168.3.171","hunan","zhuzhou"]
_name_="tengzhou"
def f1(driver, num):
"""
进行翻页,并获取数据
:param driver: 已经访问了url
:param num: 返回的是从第一页一直到最后一页
:return:
"""
locator = (By.XPATH, '(//td[@class="line2"]//a)[1]')
val = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text
# 获取当前页的url
url = driver.current_url
# print(url)
cnum = int(re.findall(r"_(\d+)", url)[0])
if num != cnum:
if num == 1:
url = re.sub("_[0-9]*", "_1", url)
else:
s = "_%d" % (num) if num > 1 else "_1"
url = re.sub("_[0-9]*", s, url)
# print(cnum)
# print(url)
driver.get(url)
try:
locator = (By.XPATH, "(//td[@class='line2']//a)[1][string()='%s']" % val)
WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))
except:
time.sleep(3)
page = driver.page_source
soup = BeautifulSoup(page, 'lxml')
ul = soup.find("td", class_="nr")
trs = ul.find_all("td", class_="line2")
data = []
for li in trs:
a = li.find("a")
link = "http://www.tzccgp.gov.cn" + a["href"]
try:
span1 = li.find("td", width="12%").text
except:
span1 = ""
tmp = [a.text.strip(), span1.strip(), link]
data.append(tmp)
df = pd.DataFrame(data=data)
df["info"]=None
return df
def f2(driver):
"""
返回总页数
:param driver:
:return:
"""
locator = (By.XPATH, '(//td[@class="line2"]//a)[1]')
WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))
try:
locator = (By.XPATH, "(//td[@class='f15']/span)[1]")
page_all = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator)).text
page = re.findall(r'共(\d+) 页', page_all)[0]
# print(page)
except Exception as e:
page = "1"
driver.quit()
return int(page)
def f3(driver,url):
driver.get(url)
locator=(By.CLASS_NAME,"nr")
WebDriverWait(driver,10).until(EC.presence_of_all_elements_located(locator))
before=len(driver.page_source)
time.sleep(0.1)
after=len(driver.page_source)
i=0
while before!=after:
before=len(driver.page_source)
time.sleep(0.1)
after=len(driver.page_source)
i+=1
if i>5:break
page=driver.page_source
soup=BeautifulSoup(page,'lxml')
div=soup.find('td',class_='nr')
#div=div.find_all('div',class_='ewb-article')[0]
return div
data = [
["zhaobiao_gg","http://www.tzccgp.gov.cn/list/?3_1.html",
["name", "ggstart_time", "href","info"],f1,f2],
["zhongbiao_gg", "http://www.tzccgp.gov.cn/list/?4_1.html",
["name", "ggstart_time", "href","info"],f1,f2],
["yanshou_gg", "http://www.tzccgp.gov.cn/list/?113_1.html",
["name", "ggstart_time", "href","info"],f1,f2],
["hetong_gg", "http://www.tzccgp.gov.cn/list/?112_1.html",
["name", "ggstart_time", "href","info"],f1,f2],
["xuqiu_gg", "http://www.tzccgp.gov.cn/list/?111_1.html",
["name", "ggstart_time", "href","info"],f1,f2],
["biangeng_feibiao_gg", "http://www.tzccgp.gov.cn/list/?109_1.html",
["name", "ggstart_time", "href","info"],f1,f2],
]
def work(conp,**args):
est_meta(conp,data=data,diqu="山东省滕州市",**args)
est_html(conp,f=f3,**args)
if __name__=='__main__':
work(conp=["postgres","since2015","127.0.0.1","shandong","tengzhou"]) | UTF-8 | Python | false | false | 4,264 | py | 310 | tengzhou.py | 290 | 0.581853 | 0.556169 | 0 | 154 | 26.058442 | 96 |
wongcyrus/ite3101_introduction_to_programming | 8,478,265,460,675 | 0ff60b8270b7e7a6eb108fc88e59325d6c6302a3 | c9952dcac5658940508ddc139344a7243a591c87 | /tests/lab05/test_ch05_t02_input.py | eac080cd260056a9dfdd0512147b72e5eb5e8ec2 | [] | no_license | https://github.com/wongcyrus/ite3101_introduction_to_programming | 5da1c15212528423b3df91997327fe148abef4de | 7cd76d0861d5355db5a6e2e171735bee2e78f829 | refs/heads/master | 2023-08-31T17:27:06.193049 | 2023-08-21T08:30:26 | 2023-08-21T08:30:26 | 136,574,036 | 3 | 2 | null | false | 2023-08-21T08:30:28 | 2018-06-08T06:06:49 | 2022-11-30T13:01:32 | 2023-08-21T08:30:27 | 368 | 3 | 3 | 0 | Python | false | false | import unittest
from unittest.mock import patch
from tests.unit_test_helper.console_test_helper import *
class TestOutput(unittest.TestCase):
def test(self):
user_input = ["Cyrus"]
with patch('builtins.input', side_effect=user_input):
temp_globals, temp_locals, content, output = execfile("lab05/ch05_t02_input.py")
self.assertEqual(temp_locals["original"], "Cyrus")
if __name__ == '__main__':
unittest.main()
| UTF-8 | Python | false | false | 461 | py | 341 | test_ch05_t02_input.py | 334 | 0.661605 | 0.64859 | 0 | 18 | 24.611111 | 92 |
jason-su/UCGNet | 15,522,011,853,725 | cd40631e9702901bc5d183825d7a23f129b515dc | 70261e072dbabe585aedcfa1da6373cb8651ee65 | /custom/iii_1_extract_name.py | faef951493481fcc4cdd90237a9475f213db2766 | [
"BSD-3-Clause"
] | permissive | https://github.com/jason-su/UCGNet | a6081463c0a039db68a1567efe09b2b44cb2aeed | 649209404119fb96cbf8b8f172575d025c1e9fb6 | refs/heads/main | 2023-02-20T13:11:07.830124 | 2021-01-22T13:32:35 | 2021-01-22T13:32:35 | 331,953,165 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding:utf-8
# P02 批量读取文件名(不带后缀)
import os
from Constants import crop_1000_xml_dir,train_name_txt_1000
path_list = os.listdir(crop_1000_xml_dir) # os.listdir(file)会历遍文件夹内的文件并返回一个列表
fp = open(train_name_txt_1000,"w")
num =0
for file_name in path_list:
fp.write(file_name.split(".")[0] + "\n")
num +=1
fp.close()
print("save to ",train_name_txt_1000)
print("total file:",num)
| UTF-8 | Python | false | false | 452 | py | 26 | iii_1_extract_name.py | 25 | 0.681122 | 0.614796 | 0 | 18 | 20.722222 | 79 |
kinow/decyclify | 10,539,849,789,950 | 7ebf400df32c6b903d08e43ece283d8f6fc9b84d | 0ce0beb29c4c3cdfce946987944a3b7ab8513018 | /setup.py | 8a011cf19941d60291ead0d2e2097991becc48d3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | https://github.com/kinow/decyclify | f8b42eb2a7a2304c4b3d9f73f06c6fe7d0b669c0 | e37d7eaec5dd85483572c4065e1840a0498bd14e | refs/heads/master | 2023-02-11T00:24:23.927988 | 2020-12-29T05:43:11 | 2020-12-29T05:43:11 | 280,767,787 | 3 | 0 | Apache-2.0 | false | 2020-07-25T05:46:01 | 2020-07-19T01:08:45 | 2020-07-22T06:12:06 | 2020-07-25T05:46:00 | 18 | 2 | 0 | 7 | Python | false | false | #!/usr/bin/env python
# Copyright 2020 Bruno P. Kinoshita
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
import re, io
# https://stackoverflow.com/questions/17583443/what-is-the-correct-way-to-share-package-version-with-setup-py-and-the-package
__version__ = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
io.open('decyclify/__init__.py', encoding='utf_8_sig').read(),
re.MULTILINE)[1]
install_requires = [
'networkx==2.4.*',
'numpy==1.19.*',
'tabulate==0.8.*'
]
tests_require = [
'pytest==5.4.*',
'coverage==5.2.*',
'pytest-cov==2.10.*'
]
extras_require = {
'all': []
}
extras_require['all'] = (
tests_require
+ list({
req
for reqs in extras_require.values()
for req in reqs
})
)
setup(
long_description=open('README.md').read(),
long_description_content_type="text/markdown",
version=__version__,
packages=find_packages(include=["decyclify"]),
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
project_urls={
"Documentation": "https://github.com/kinow/decyclify",
"Source": "https://github.com/kinow/decyclify",
"Tracker": "https://github.com/kinow/decyclify/issues"
}
)
| UTF-8 | Python | false | false | 1,809 | py | 13 | setup.py | 7 | 0.658928 | 0.641238 | 0 | 65 | 26.830769 | 125 |
joaduo/python-simplerpc | 15,762,529,995,012 | b225eb440bd6f86c0b8dae9802029bbe49627ab5 | 872a7212f72e1a2ca267ba69d858fa46f53ff5a6 | /simplerpc/expose_api/javascript/ClassToJsUnitTest.py | 1366a606d28213787b46c8ffaa1899d984417253 | [] | no_license | https://github.com/joaduo/python-simplerpc | fc57d3d53689c8c4ee565461c7c0e99a157b4886 | 4b935f5ada52e575f0097e85229e6e879e9981af | refs/heads/master | 2016-09-05T10:22:45.352915 | 2014-12-06T02:21:48 | 2014-12-06T02:21:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
'''
Simple RPC
Copyright (c) 2013, Joaquin G. Duo
'''
from simplerpc.base.SimpleRpcLogicBase import SimpleRpcLogicBase
from simplerpc.expose_api.javascript.ClassToJs import ClassToJs
from simplerpc.expose_api.javascript.TemplatesCollector import TemplatesCollector
from string import Template
import os
from simplerpc.common.FileManager import FileManager
class ClassToJsUnitTest(SimpleRpcLogicBase):
'''
#TODO: document
'''
def __post_init__(self):
self.class_to_js = ClassToJs(self.context)
self.templates = TemplatesCollector(self.context)
self.file_manager = FileManager(self.context)
def translateClass(self, class_):
''' '''
ast_tree = self.class_to_js.translateClass(class_)
templates_set = 'js_unittest_templates'
templates = self.templates.collectBuiltIn(templates_set)
js_str = ast_tree.getString(templates)
return js_str
def translateToFile(self, tested_class, file_path, overwrite=False):
js_str = self.__getClassJsUnit(tested_class)
#create directory just in case
test_dir = os.path.dirname(file_path)
self.file_manager.makedirs(test_dir)
#Say where it is in a pretty way
path = self.file_manager.formatFilePath(file_path)
name = tested_class.__name__
self.log.d('Creating js for %s test at:\n %s' % (name, path))
#save file
self.file_manager.saveTextFile(file_path, js_str, overwrite)
def __getClassJsUnit(self, tested_class):
js_str = self.translateClass(tested_class)
translate = dict(EXPOSED_RPC_API_CLASS=self.context.js_rpc_file)
js_str = Template(js_str).safe_substitute(translate)
return js_str
def smokeTestModule():
from simplerpc.context.SimpleRpcContext import SimpleRpcContext
context = SimpleRpcContext('smoke test')
from example_rpc.exposed_api.images.ImagesBrowser import ImagesBrowser
js_str = ClassToJsUnitTest(context).translateClass(ImagesBrowser)
context.log(js_str)
if __name__ == "__main__":
smokeTestModule()
| UTF-8 | Python | false | false | 2,114 | py | 70 | ClassToJsUnitTest.py | 66 | 0.69158 | 0.689215 | 0 | 57 | 36.087719 | 81 |
giorgoschionas/IEEEXtreme15.0 | 17,274,358,481,967 | dc65b553e042a906b6aaadc88212f8d2d30c5b88 | 6b933209fc52ccbd02461bb5bf68d2bfb5e3f8ae | /wordsearch.py | 52d769082f312bc4aff681d3e5c8d6f71e710fe9 | [] | no_license | https://github.com/giorgoschionas/IEEEXtreme15.0 | 4ec1441f4dcc84417cfd1321ef6c1f12bf6c3057 | 84a0308d7860dc8bd22cacf5ae2d2df81b9868d8 | refs/heads/master | 2023-08-27T12:56:20.808748 | 2021-10-26T13:53:55 | 2021-10-26T13:53:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # a simple parser for python. use get_number() and get_word() to read
def parser():
while 1:
data = list(input().split(' '))
for number in data:
if len(number) > 0:
yield(number)
input_parser = parser()
def get_word():
global input_parser
return next(input_parser)
def get_number():
data = get_word()
try:
return int(data)
except ValueError:
return float(data)
R = get_number()
C = get_number()
Q = get_number()
table = []
for i in range(R):
word = get_word()
row = []
for j in range(C):
row.append(word[j])
table.append(row)
table = np.array(table)
for _ in range(Q):
sol = (R*C,R*C,R*C,R*C)
found = False
word = get_word()
for i in range(R):
c = 0
while (c + len(word) <= C):
if "".join(table[i][c:c+len(word)]) == word:
found = True
sol = min(sol,(i, c, i, c+len(word)-1))
if "".join(table[i][c:c+len(word)]) == word[::-1]:
found = True
sol = min(sol,(i, c+len(word)-1, i, c))
c += 1
for j in range(C):
r = 0
while (r + len(word) <= R):
if "".join(table[r:r+len(word),j]) == word:
found = True
sol = min(sol,(r, j, r+len(word)-1, j))
if "".join(table[r:r+len(word),j]) == word[::-1]:
found = True
sol = min(sol,(r+len(word)-1, j, r, j))
r += 1
for i in range(R):
for j in range(C):
if (i + len(word) <= R) and (j + len(word) <= C):
diag = []
antidiag = []
for k in range(len(word)):
element1 = table[i+k][j+k]
diag.append(element1)
element2 = table[i+k][j+len(word)-1-k]
antidiag.append(element2)
if "".join(diag) == word:
found = True
sol = min(sol,(i,j,i+len(word)-1,j+len(word)-1))
if "".join(diag) == word[::-1]:
found = True
sol = min(sol,(i+len(word)-1,j+len(word)-1,i,j))
if "".join(antidiag) == word:
found = True
sol = min(sol,(i,j+len(word)-1,i+len(word)-1,j))
if "".join(antidiag) == word[::-1]:
found = True
sol = min(sol,(i+len(word)-1,j,i,j+len(word)-1))
if not found:
print(-1)
else:
print(*sol)
| UTF-8 | Python | false | false | 2,606 | py | 17 | wordsearch.py | 16 | 0.423638 | 0.412893 | 0 | 102 | 24.490196 | 69 |
LeGaulois/soc | 10,075,993,323,117 | bbfb6c3c075d99e920906b0e2240f2400918995f | 0a1a404329a164c9fd240b5a6a48f2967b6cc7c6 | /sources/applications/formulaires.py | 7c425c9ecc971cb283f509c0c6a03ccb5fa7d7cb | [] | no_license | https://github.com/LeGaulois/soc | 52247e9ba24fb542b6abf1c31e8b9c39114d4c65 | 8111620f43b5e0e1d12925de2c03892c7f013e64 | refs/heads/master | 2021-01-17T14:40:38.944322 | 2016-05-17T13:09:23 | 2016-05-17T13:09:23 | 51,772,843 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #-*- coding: utf-8 -*-
from django import forms
from django.conf import settings
import ConfigParser
import codecs
BASE=settings.BASE_DIR+'/'
class formFiltreApplis(forms.Form):
'''
Formulaire de filtrage des applications
'''
def __init__(self,*args,**kwargs):
self.criticite=kwargs.pop('criticite')
CHOIX_CRITICITE=[]
for m in range(len(self.criticite)):
CHOIX_CRITICITE.append((self.criticite[m].get('criticite'), self.criticite[m].get('criticite')) )
super(formFiltreApplis,self).__init__(*args,**kwargs)
self.fields['criticite']=forms.CharField(label='Criticite',initial=None,widget=forms.Select(choices=CHOIX_CRITICITE),required=False)
def clean_criticite(self):
niveauCriticite=self.cleaned_data['criticite']
criticite_valide=["",None]
for j in range(len(self.criticite)):
criticite_valide.append(self.criticite[j].get('criticite'))
if niveauCriticite in criticite_valide:
return niveauCriticite
else:
raise forms.ValidationError('Criticite non valide')
def is_valid(self):
is_valid = super(formFiltreApplis,self).is_valid()
if not is_valid:
for field in self.errors.keys():
print "ValidationError: %s[%s] <- \"%s\" %s" % (
type(self),
field,
self.data[field],
self.errors[field].as_text()
)
return is_valid
class formEditApplication(forms.Form):
'''
Formulaire d'ajout et d'édition d'une application
'''
def __init__(self,*args,**kwargs):
try:
appli=kwargs.pop('dic')
self.nom=appli[0].get("nom")
desc=appli[0].get("description")
criticite=appli[0].get("criticite")
nb_utilisateurs=appli[0]['nb_utilisateurs']
type_appli=appli[0]['type']
technologies=appli[0]['technologies']
except:
self.nom=None
desc=None
criticite=None
nb_utilisateurs=None
type_appli=None
technologies=None
self.noms=kwargs.pop('dic_noms')
Config = ConfigParser.ConfigParser()
Config.readfp(codecs.open(BASE+"soc/default.cfg","r","utf-8"))
self.CHOIX_CRITICITE=Config.items('CRITICITE')
self.CHOIX_CRITICITE.append((None,'A definir'))
self.mode=kwargs.pop('mode')
super(formEditApplication,self).__init__(*args,**kwargs)
self.fields['nom']=forms.CharField(label="Nom",initial=self.nom,required=True,max_length=50)
self.fields['criticite']=forms.CharField(label='Criticite',initial=criticite,widget=forms.Select( choices=self.CHOIX_CRITICITE),required=True,max_length=10)
self.fields['desc']=forms.CharField(label="Description",widget=forms.Textarea(attrs={'rows': 15,'cols': 80,'style': 'height: 12em; width:30em;'}),initial=desc,max_length=65536,required=False)
self.fields['nb_utilisateurs']=forms.IntegerField(label="Nombre Utilisateurs",initial=nb_utilisateurs,required=False)
self.fields['type_appli']=forms.CharField(label="Type",initial=type_appli,max_length=50,required=False)
self.fields['technologies']=forms.CharField(label="Technologies",widget=forms.Textarea(attrs={'rows': 15,'cols': 80,'style': 'height: 12em; width:30em;'}),initial=technologies,max_length=250,required=False)
def clean_criticite(self):
criticite=self.cleaned_data['criticite']
liste_criticite=[]
for crit in self.CHOIX_CRITICITE:
liste_criticite.append(crit[0])
if criticite in liste_criticite:
return criticite
else:
raise forms.ValidationError('criticite non valide')
def clean_nom(self):
nom=str(self.cleaned_data['nom'])
NOM_EXISTANT=[]
if nom==None:
return forms.ValidationError('Le nom ne peut etre vide')
for m in range(len(self.noms)):
NOM_EXISTANT.append((self.noms[m].get('nom')))
for j in range(len(self.noms)):
NOM_EXISTANT.append(self.noms[j].get('nom'))
if (self.mode=='edit' and nom!=str(self.nom)) or self.mode=='ajout':
if nom in NOM_EXISTANT:
raise forms.ValidationError('Application déjà présente dans la base')
else:
return nom
else:
return nom
def is_valid(self):
is_valid = super(formEditApplication,self).is_valid()
if not is_valid:
for field in self.errors.keys():
print "ValidationError: %s[%s] <- \"%s\" %s" % (
type(self),
field,
self.data[field],
self.errors[field].as_text()
)
return is_valid
| UTF-8 | Python | false | false | 5,209 | py | 90 | formulaires.py | 56 | 0.56196 | 0.554467 | 0 | 150 | 33.606667 | 214 |
Gaur2025/face-detection-and-counting | 14,035,953,131,194 | 6d344e9c01cc58ee955754f03cbb0503c92e2f35 | 86ea6871edd69256d74afce754e278318bbb6229 | /face_and_eye_detection_using_webcam.py | 4ed1bf4898d785ade45173830adf56f6ce336a28 | [] | no_license | https://github.com/Gaur2025/face-detection-and-counting | dc9d09359734fd1038b04ce7971f525ca9944551 | 4efe9ca4239e719d97bf0516fe4076175663eb5a | refs/heads/master | 2023-06-28T02:36:21.634149 | 2021-07-28T10:57:44 | 2021-07-28T10:57:44 | 388,875,012 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import cv2
# We point OpenCV's Cascade classifier function to where our classifier (XML file format) is stored.
face_cascade = cv2.CascadeClassifier(
'Haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('Haarcascades/haarcascade_eye.xml')
# Defining a function that would do the detections.
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
# Drawing a rectangle on the face.
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Now to detect the eyes, we need to crop the face.
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
# Detecting eyes in the cropped area.
eyes = eye_cascade.detectMultiScale(roi_gray, 1.1, 3)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
return frame
# Doing face recognition with the webcam.
video_capture = cv2.VideoCapture(0) # 0 => used to use default webcam.
while True: # To get continuous frames.
_, frame = video_capture.read() # frames are captured.
# Converting above frames into Grayscale coz RGM frames take lot of time to process.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame) # Detect function is defined above.
cv2.imshow('Video', canvas)
# Unless user presses 'enter' or 'q'; it would not brake.
if cv2.waitKey(13) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows() # press 'q' to quit.
| UTF-8 | Python | false | false | 1,611 | py | 11 | face_and_eye_detection_using_webcam.py | 7 | 0.655493 | 0.633768 | 0 | 39 | 40.307692 | 100 |
jumbobumbo/flask-db | 8,392,366,096,980 | 03bad21d92e87a1be5cc6f509bad1f8c3aa6e79e | 2919931ff5c7aa5ecedb45f6ee66bebe83f6b5b0 | /app/common/hashing.py | 67e23c5dd6d17bfda9dc03f3ad4c5ef90facf08a | [] | no_license | https://github.com/jumbobumbo/flask-db | 5fff9298299ab8fcb00ff1b79df25eec83f957f0 | 8f0eea2f8bb9a6efc9631e2708d2fcd0630e3ac3 | refs/heads/main | 2023-06-21T20:25:23.791961 | 2021-07-20T17:03:23 | 2021-07-20T17:03:23 | 330,432,029 | 1 | 0 | null | false | 2021-07-20T17:03:24 | 2021-01-17T16:14:38 | 2021-07-20T00:10:12 | 2021-07-20T17:03:23 | 100 | 0 | 0 | 0 | Python | false | false | """Password hasher and validation functions"""
from bcrypt import hashpw, checkpw, gensalt
def hasher(string: str) -> str:
"""Hashes a string with a salty salt, default encoding of utf-8 (we live in a modern world)
Args:
string (str): The string to hash.
Returns:
str: The hashed string
"""
return hashpw(str(string).encode('utf8'), gensalt(rounds=15))
def validate_pw(plain_string: str, hashed_string: str) -> bool:
"""
Validates password against a hashed_string from the DB
Args:
plain_string (str): the provided string
hashed_string (str): a pre-generated hashed string
Returns:
bool: True if strings match else False
"""
return checkpw(password=str(plain_string).encode('utf8'), hashed_password=hashed_string.encode('utf8'))
| UTF-8 | Python | false | false | 822 | py | 29 | hashing.py | 20 | 0.664234 | 0.656934 | 0 | 29 | 27.344828 | 107 |
jpdickert/CTI110 | 9,216,999,834,086 | 4249c20ee7acbb4a8122545c7f79f7c3f1e02d65 | fc4ac2a12243c78c27c0a0a87ec614ded9658055 | /P2T1_SalesPrediction_DickertJason.py | 2a60dc9f1d57593387f80af58379d1a06040086a | [] | no_license | https://github.com/jpdickert/CTI110 | 238dd58a48f99f926226b26141ddf8fe2db599d5 | 168e0915b198e1be20db29ca3ba4c5b0ef85c2e4 | refs/heads/master | 2020-03-20T20:46:40.693607 | 2018-07-21T19:10:57 | 2018-07-21T19:10:57 | 137,705,893 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # CTI-110
# P2T1 - Sales Prediction
# Jason Dickert
# 07 June 2018
#
print('Enter your projected amount of total sales.')
number = float(input("Projected amount of total sales: $"))
print('Your projected amount of total sales is $', (number), '.')
print('Your projected annual profit will be about $', (number*.23), '.')
| UTF-8 | Python | false | false | 330 | py | 22 | P2T1_SalesPrediction_DickertJason.py | 18 | 0.678788 | 0.639394 | 0 | 9 | 34.666667 | 72 |
bhowiebkr/simple-node-editor | 8,383,776,199,442 | 376b4589a26ac4614fdd9e69e2668aa4bf726b77 | c1f4aaaed63053c380ee0af63ee3cd929575698c | /node_editor/gui/port.py | 2db842d8889e0c4720a8e6d3e8cfa2a4421b20f0 | [
"MIT"
] | permissive | https://github.com/bhowiebkr/simple-node-editor | 635199ca0c77b5948463bd590a53eada4f57e45f | 845c1f790005496c412769864809ab790f06bfea | refs/heads/master | 2023-04-04T23:25:27.365081 | 2023-03-19T08:46:11 | 2023-03-19T08:46:11 | 219,095,033 | 11 | 5 | MIT | false | 2023-04-05T22:23:00 | 2019-11-02T02:54:25 | 2023-04-04T14:55:37 | 2023-04-05T22:23:00 | 219 | 78 | 27 | 0 | Python | false | false | from PySide6 import QtCore, QtGui, QtWidgets
class Port(QtWidgets.QGraphicsPathItem):
"""A graphics item representing an input or output port for a node in a node-based graphical user interface.
Attributes:
radius_ (int): The radius of the port circle.
margin (int): The margin between the port circle and the port name text.
port_text_height (int): The height of the port name text.
port_text_width (int): The width of the port name text.
_is_output (bool): True if the port is an output port, False if it is an input port.
_name (str): The name of the port.
m_node (Node): The node to which the port belongs.
connection (Connection): The connection attached to the port, if any.
text_path (QPainterPath): The path used to draw the port name text.
Methods:
set_is_output(is_output: bool) -> None: Set the output status of the port.
set_name(name: str) -> None: Set the name of the port.
set_node(node: Node) -> None: Set the node to which the port belongs.
set_port_flags(flags: int) -> None: Set the port flags.
set_ptr(ptr: Any) -> None: Set the pointer to the port.
name() -> str: Get the name of the port.
is_output() -> bool: Check if the port is an output port.
node() -> Node: Get the node to which the port belongs.
paint(painter: QtGui.QPainter, option: QtWidgets.QStyleOptionGraphicsItem, widget: Optional[QtWidgets.QWidget]) -> None: Paint the port.
clear_connection() -> None: Clear the connection attached to the port.
can_connect_to(port: Port) -> bool: Check if the port can be connected to another port.
is_connected() -> bool: Check if the port is connected to another port.
itemChange(change: QtWidgets.QGraphicsItem.GraphicsItemChange, value: Any) -> Any: Handle item change events.
"""
def __init__(self, parent, scene):
super().__init__(parent)
self.radius_ = 5
self.margin = 2
path = QtGui.QPainterPath()
path.addEllipse(-self.radius_, -self.radius_, 2 * self.radius_, 2 * self.radius_)
self.setPath(path)
self.setFlag(QtWidgets.QGraphicsPathItem.ItemSendsScenePositionChanges)
self.font = QtGui.QFont()
self.font_metrics = QtGui.QFontMetrics(self.font)
self.port_text_height = self.font_metrics.height()
self._is_output = False
self._name = None
self.margin = 2
self.m_node = None
self.connection = None
self.text_path = QtGui.QPainterPath()
def set_is_output(self, is_output):
self._is_output = is_output
def set_name(self, name):
self._name = name
nice_name = self._name.replace("_", " ").title()
self.port_text_width = self.font_metrics.horizontalAdvance(nice_name)
if self._is_output:
x = -self.radius_ - self.margin - self.port_text_width
else:
x = self.radius_ + self.margin
y = self.port_text_height / 4
self.text_path.addText(x, y, self.font, nice_name)
def set_node(self, node):
self.m_node = node
def set_port_flags(self, flags):
self.m_port_flags = flags
def set_ptr(self, ptr):
self.m_ptr = ptr
def name(self):
return self._name
def is_output(self):
return self._is_output
def node(self):
return self.m_node
def paint(self, painter, option=None, widget=None):
painter.setPen(QtGui.QPen(1))
painter.setBrush(QtCore.Qt.green)
painter.drawPath(self.path())
painter.setPen(QtCore.Qt.NoPen)
painter.setBrush(QtCore.Qt.white)
painter.drawPath(self.text_path)
def clear_connection(self):
if self.connection:
self.connection.delete()
def can_connect_to(self, port):
print(port.node(), self.node())
if not port:
return False
if port.node() == self.node():
return False
return self._is_output != port._is_output
def is_connected(self):
return bool(self.connection)
def itemChange(self, change, value):
if change == QtWidgets.QGraphicsItem.ItemScenePositionHasChanged and self.connection:
self.connection.update_start_and_end_pos()
return value
| UTF-8 | Python | false | false | 4,373 | py | 10 | port.py | 9 | 0.623828 | 0.621999 | 0 | 123 | 34.552846 | 144 |
dabbott/scmap | 10,969,346,480,589 | eeff4707d5ffccd364989810a4e4be402b9d45e9 | 2d83f7d2ca5359debf48a64faff2ce90798f3916 | /scmap/chk.py | 297711632f4e333c1d1443ef46e4e6091341d6c3 | [] | no_license | https://github.com/dabbott/scmap | d92377ea9349972f1fcb628e3d3b76b73bd37726 | b5559fa6abd6e0bf06b44d9d42b3c982d9e2a580 | refs/heads/master | 2021-01-20T05:47:23.733656 | 2010-07-28T02:23:24 | 2010-07-28T02:23:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import struct
import mpq
import StringIO
tilesets = {
0: "badlands",
1: "platform",
2: "install",
3: "ashworld",
4: "jungle",
5: "desert",
6: "ice",
7: "twilight",
}
tileset_numbers = dict((v,k) for k,v in tilesets.iteritems())
def load(filename):
mf = StringIO.StringIO(mpq.Archive(filename)['staredit\\scenario.chk'])
maps = {}
while True:
title = mf.read(4)
if title == "": break
data = mf.read(struct.unpack("<L",mf.read(4))[0])
maps[title.strip(" ")] = data
mapdim = struct.unpack("<2H", maps["DIM"])
tileset = tilesets[struct.unpack("<H",maps["ERA"])[0]]
tiles = struct.unpack("<"+str(len(maps["MTXM"])/2)+"H",maps["MTXM"])
tiles = [tiles[x::mapdim[0]] for x in range(0,mapdim[0])]
doodads = []
thingy = StringIO.StringIO(maps["THG2"])
while 1:
raw = thingy.read(10)
if raw == "": break
number, x, y, owner, unknown, flag = struct.unpack("<HHHBBH", raw)
doodads.append((number,x,y))
unit = StringIO.StringIO(maps["UNIT"])
units = []
while 1:
raw = unit.read(36)
if raw == "": break
serial, x, y, type, unknown, flag, validflag, owner, hp, shield, energy, resource, hanger, state, unknown2, unknown3 = struct.unpack("<LHHHHHHBBBBLHHLL", raw)
units.append((type, (x, y), owner, resource))
return mapdim, tileset, tiles, doodads, units
| UTF-8 | Python | false | false | 1,478 | py | 27 | chk.py | 25 | 0.558187 | 0.540595 | 0 | 51 | 27.882353 | 166 |
kchennen/metadome | 6,365,141,556,611 | 8d48f4665fb2f6b642eb727f8a326b334695fcd5 | 140bf2d656191194f4f1b0c81e66e64b43de712a | /metadome/factory.py | 6d61244e5023893fd48bbce66f1f0cc741675265 | [
"MIT"
] | permissive | https://github.com/kchennen/metadome | abf8e33b5cea20ca6d5bff07674211000dcc8714 | 2b4448b33cbc5512b56f5aaa7453d0a255ee1628 | refs/heads/master | 2023-03-27T01:28:30.287401 | 2019-08-22T14:19:10 | 2019-08-22T14:19:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import logging
from flask import Flask
import flask_jsglue
from metadome.domain.services.mail.mail import mail
from metadome.default_settings import MAIL_SERVER
from celery import Celery
_log = logging.getLogger(__name__)
def create_app(settings=None):
_log.info("Creating flask app")
app = Flask(__name__, static_folder='presentation/web/static', static_url_path='/metadome/static',
template_folder='presentation/web/templates')
app.config.from_object('metadome.default_settings')
if settings:
app.config.update(settings)
# Ignore Flask's built-in logging
# app.logger is accessed here so Flask tries to create it
app.logger_name = "nowhere"
app.logger
# Configure logging.
#
# It is somewhat dubious to get _log from the root package, but I can't see
# a better way. Having the email handler configured at the root means all
# child loggers inherit it.
from metadome import _log as metadom_logger
# Only log to the console during development and production, but not during
# testing.
if app.testing:
metadom_logger.setLevel(logging.DEBUG)
else:
ch = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
metadom_logger.addHandler(ch)
if app.debug:
metadom_logger.setLevel(logging.DEBUG)
else:
metadom_logger.setLevel(logging.INFO)
# Add mail instance
if not MAIL_SERVER is None:
mail.init_app(app)
else:
_log.warn('MAILSERVER is not set in default_settings.py')
# Initialize extensions
from metadome import toolbar
toolbar.init_app(app)
# Specify the Blueprints
from metadome.presentation.web.routes import bp as web_bp
from metadome.presentation.api.routes import bp as api_bp
# Register the Blueprints
app.register_blueprint(api_bp, url_prefix='/metadome/api')
app.register_blueprint(web_bp, url_prefix='/metadome')
# Database
from metadome.database import db
db.init_app(app)
with app.app_context():
db.create_all()
from flask_jsglue import JSGlue
flask_jsglue.JSGLUE_JS_PATH = '/metadome/static/js/JSGlue.js'
jsglue = JSGlue(app)
return app
def make_celery(app):
_log.info("Creating celery app")
app = app or create_app()
celery = Celery(__name__, backend=app.config['CELERY_RESULT_BACKEND'],
broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
# needed here to register celery tasks, this should not be anywhere else
import metadome.tasks
return celery
| UTF-8 | Python | false | false | 2,985 | py | 69 | factory.py | 61 | 0.660972 | 0.660972 | 0 | 102 | 28.264706 | 102 |
smaystr/rails_reactor | 5,961,414,613,561 | f5ba8af8fa844fd5777d41bfcd1239962866564b | 1f0831db24ae2772d4944faf05289599bb37aca7 | /linear_models/04/models/logistic_regression.py | b00f306c7e7a4eaba97eaa03a670283c1a66ebdf | [] | no_license | https://github.com/smaystr/rails_reactor | 2123f39ae97f38acb647363979fe4a09b896670e | 69c8aac5860527768b4a8b7bce027b9dea6b1989 | refs/heads/master | 2022-08-19T05:35:21.535933 | 2019-08-28T12:46:22 | 2019-08-28T12:46:22 | 189,264,026 | 1 | 0 | null | false | 2022-07-29T22:34:56 | 2019-05-29T16:47:08 | 2019-08-28T13:03:28 | 2022-07-29T22:34:53 | 76,416 | 1 | 0 | 7 | Jupyter Notebook | false | false | import numpy as np
from typing import List
from utils.gradient_descent import gradient_descent
from utils.classification_metrics import get_metric
from utils.dataset_processing import add_ones_column
np.random.seed(42)
class LogisticReg:
def __init__(
self,
*,
fit_intercept: bool = True,
learning_rate: float = 0.01,
num_iterations: int = 100,
C: float = 1,
):
self.fit_intercept = fit_intercept
self.learning_rate = learning_rate
self.num_iterations = num_iterations
self.reg_param = C
self.theta = None
self.cost_history = None
def fit(self, X: np.ndarray, y: np.ndarray) -> None:
if self.fit_intercept:
X = add_ones_column(X)
y = y.reshape(-1, 1)
self.theta, self.cost_history = gradient_descent(
X,
y,
self.num_iterations,
self.learning_rate,
self.reg_param,
self._decision_function,
)
def predict(self, X: np.ndarray) -> np.ndarray:
if self.fit_intercept:
X = add_ones_column(X)
predictions = self._decision_function(X, self.theta)
return predictions.reshape((-1,))
def predict_proba(self, X: np.ndarray) -> np.ndarray:
if self.fit_intercept:
X = add_ones_column(X)
predictions = self._decision_function(X, self.theta, round=False)
return predictions.reshape((-1,))
def score(
self, X: np.ndarray, y: np.ndarray, metric_type: str = "accuracy"
) -> float:
metric = get_metric(metric_type)
y_pred = self.predict(X)
return metric(y, y_pred)
def get_cost_history(self) -> List:
return self.cost_history
@staticmethod
def _decision_function(X: np.ndarray, theta: np.ndarray, round: bool = True) -> np.ndarray:
if round:
return LogisticReg._sigmoid(LogisticReg._hypothesis(X, theta)).round().astype(int)
else:
return LogisticReg._sigmoid(LogisticReg._hypothesis(X, theta))
@staticmethod
def _sigmoid(z: np.ndarray) -> np.ndarray:
return 1 / (1 + np.e ** (-z))
@staticmethod
def _hypothesis(data: np.ndarray, theta: np.ndarray) -> np.ndarray:
return data @ theta
| UTF-8 | Python | false | false | 2,310 | py | 419 | logistic_regression.py | 311 | 0.592208 | 0.585714 | 0 | 75 | 29.8 | 95 |
Shrumdog/pubg | 14,551,349,243,526 | 84b1bf4fcd4d8547dd6bbfdc03ab82d78348f798 | b457d19ab546f3ddd3a3647d0cd071ce42c55ac8 | /app/bin/something.py | 4ad31bc8fce91b2208e935b3c67757c386a5041a | [] | no_license | https://github.com/Shrumdog/pubg | 879348e5aa481a9f554b74db5b8fc2b942e2f645 | 82ca209646f63aef60191c7296e9546c4ac18122 | refs/heads/master | 2020-12-03T00:39:59.381423 | 2017-07-03T06:24:40 | 2017-07-03T06:24:40 | 96,059,622 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import PIL
from PIL import ImageGrab
from PIL import Image
import sys
import subprocess
import numpy
import time
import datetime
PATH = "G:\\AtomProjects\\dev\\pubg\\data\\inbound\\gameplay\\"
TIME = time.time()
game_time = datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M')
print(PATH)
#automate screen grabs on system timer. ingest to data\gameplay
def set_up():
mkgdir_command=['mkdir', PATH+"games\\"+game_time+'\\']
subprocess.call(mkgdir_command)
subdirs=['gameplay','toInv','toMap']
for s in subdirs:
command=['mkdir', PATH+"games\\"+game_time+'\\'+s]
subprocess.call(command)
return(1)
def get_data(p):
return open(p, 'r')
def write_data(path, data):
#implement writing screen to file at ?path?
with open(path, 'w') as f:
f.write(data)
f.close()
def get_grab():
img = ImageGrab.grab()
return img
def save_grab(img, n, t):
name = n #timestamp accurate to seconds
st = datetime.datetime.fromtimestamp(n).strftime('%Y%m%dH%HM%MS%S')
ty = t
img.save(PATH+"games\\"+game_time+'\\'+st+'.'+ty, ty.upper())
# Image(img).save(PATH+name,type)
def process():
# takes image object as input, performs processes
img = get_grab()
save_grab(img,time.time(),'png')
# img.show()
def timer(s):
time.sleep(s)
return True
def print_time():
subprocess.call('clear')
difftime = time.time() - TIME
print(difftime)
def controller():
set_up()
while(True):
print_time()
t = timer(5)
if(t):
process()
# process()
controller()
# img = get_grab()
# print ("the size of the Image is: ")
# print(img.format, img.size, img.mode)
#
# write_data(PATH+'stamp.bmp', img)
#
#
| UTF-8 | Python | false | false | 1,748 | py | 3 | something.py | 2 | 0.622998 | 0.621854 | 0 | 78 | 21.410256 | 79 |
lololololoki/dataprocess_pansharpening | 12,094,627,948,728 | 4894a5e094ba875a3fddf9f2757548d3338caf0a | 640f303bf5a72a28a797f4f49523b5b897a2310c | /preprocessing_classify/tifClassify.py | da14d37230e098d2b7c20009564394c31a4b030b | [] | no_license | https://github.com/lololololoki/dataprocess_pansharpening | 9abf8ca9a5c2e5f6460a192ebf0658603cc548c3 | 0ca44bceac061477ddb479ca788d6a9df303b1a4 | refs/heads/master | 2020-11-30T09:46:55.232449 | 2019-12-27T04:08:02 | 2019-12-27T04:08:02 | 230,368,371 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-\
#分类存放 rural suburban urban .tif文件
import os
import shutil
ruralNum = [7, 22, 23, 24, 26, 28, 29, 31, 38, 48]
suburbanNum = [1, 2, 3, 4, 6, 8, 15, 20, 25, 27]
urbanNum = [5, 10, 11, 12, 13, 14, 16, 17, 18, 19]
fileType = ['.tif', '_boxes', '_points']
def tifClassify(srcDir, dstDir):
r"""
srcFile: tif文件夹
"""
os.chdir(srcDir)
if not os.path.exists(dstDir):
os.mkdir(dstDir)
count = 0
# rural
for num in ruralNum:
newNum = '0' + str(count)
count = count + 1
for type in fileType:
srcFile = srcDir + str(num) + type
dstFile = dstDir + newNum + type
print (dstFile)
shutil.copy(srcFile, dstFile)
# suburban
for num in suburbanNum:
newNum = '1' + str(count)
count = count + 1
for type in fileType:
srcFile = srcDir + str(num) + type
dstFile = dstDir + newNum + type
print (dstFile)
shutil.copy(srcFile, dstFile)
# urban
for num in urbanNum:
newNum = '2' + str(count)
count = count + 1
for type in fileType:
srcFile = srcDir + str(num) + type
dstFile = dstDir + newNum + type
print (dstFile)
shutil.copy(srcFile, dstFile)
tifClassify('/home/jky/jky/tool/dataprocess/VOCdevkit_fujianNew/txt/', '/home/jky/jky/tool/dataprocess/VOCdevkit_fujianNew/txt_classify/') | UTF-8 | Python | false | false | 1,590 | py | 20 | tifClassify.py | 18 | 0.513995 | 0.475827 | 0 | 56 | 26.107143 | 138 |
Aasthaengg/IBMdataset | 1,382,979,475,589 | c52ca2a39106b9a0250d0cb3fdbfe1b331b7b777 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03609/s179671047.py | bbe358a226e3273ffa46b2fc0d578499bf906373 | [] | 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 | X, t = map(int, input().split())
print(0 if X <= t else X-t) | UTF-8 | Python | false | false | 60 | py | 202,060 | s179671047.py | 202,055 | 0.566667 | 0.55 | 0 | 2 | 29.5 | 32 |
mariemsmaoui/kms | 1,735,166,802,858 | 03b72a74f81e84b54f7bc41f65ced26d9e6a47a0 | 960b65f627df15e893a2b7e95e835fba7e0a8df2 | /kms/migrations/0017_auto_20210525_1241.py | 98856a45dca027a8ba1b893c11075a25a7923198 | [] | no_license | https://github.com/mariemsmaoui/kms | 22c7c6b04c76b419660297b2e90fa1b61b9e388c | bfc94bbc1c547fde446d28e2978cf4a4dfd65860 | refs/heads/master | 2023-05-05T06:18:02.451747 | 2021-05-27T09:01:41 | 2021-05-27T09:01:41 | 371,308,865 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 3.1.7 on 2021-05-25 10:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('kms', '0016_auto_20210525_1238'),
]
operations = [
migrations.AlterField(
model_name='responsable',
name='tachesRp',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tachesrp', to='kms.tache'),
),
]
| UTF-8 | Python | false | false | 505 | py | 16 | 0017_auto_20210525_1241.py | 16 | 0.635644 | 0.574257 | 0 | 19 | 25.578947 | 133 |
bojan211/PA-svee | 4,535,485,475,337 | 55a46ce2b493f9a9600954e0690555a22f5621cf | 1faf0781d9129c04568743cef7e23ade5cef1bfd | /vezba05-rad/vezba05-rad/class_example.py | 8c4f4f75de16caa7649fc317b4ce5a8fd31c8151 | [] | no_license | https://github.com/bojan211/PA-svee | cd16fd5b938b27b9e229296a57ce7dbc8c89ba79 | 7b9f0c40faa87468b9c00451fcb96ea0855bcb93 | refs/heads/master | 2020-03-18T03:40:17.501206 | 2018-05-21T09:55:22 | 2018-05-21T09:55:22 | 134,250,660 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, l = None, r = None, d = None, p = None):
"""
Node constructor
@param A node data object
"""
self.left = l
self.right = r
self.data = d
self.parrent = p
class Data:
"""
Tree data: Any object which is used as a tree node data
"""
def __init__(self, val1, val2):
"""
Data constructor
@param A list of values assigned to object's attributes
"""
self.a1 = val1
self.a2 = val2
class Tree:
def __init__(self, val1):
self.root = val1
def TreeInsert(self,z):
y = None
x = self.root
while x != None:
y = x
if z.data.a1 < x.data.a1:
x = x.left
else:
x = x.right
z.parrent = y
if y == None:
self.root = z
print("AAAAA")
elif z.data.a1 < y.data.a1:
y.left = z
else:
y.right = z
d = Data(1, 2)
#print(d.a1, d.a2) | UTF-8 | Python | false | false | 1,128 | py | 12 | class_example.py | 10 | 0.444149 | 0.429965 | 0 | 52 | 20.711538 | 63 |
raj174/Assistive_Robot_with_EMG-ROS | 3,015,067,084,194 | dbef829f8cfd5a2f395a3477aa6d1702aff60ab3 | c89fb572dc76983eb6d14a5cd01554efa3350c91 | /scripts/ik.py | 1b8f0b3605668157b81ea77203b88dd8b0d81c6d | [] | no_license | https://github.com/raj174/Assistive_Robot_with_EMG-ROS | a19d971db3c16ba40da7f41958597eb7f9dd788c | 92b4600a1617a48c402c3d1ca350d27447e6b08b | refs/heads/master | 2021-03-31T03:51:51.361250 | 2018-05-18T15:21:11 | 2018-05-18T15:21:11 | 124,863,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# Copyright (c) 2013-2017, Rethink Robotics Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Intera RSDK Inverse Kinematics Example
"""
import sys
import rospy
import intera_interface
import tf
import struct
import numpy as np
from geometry_msgs.msg import (
PoseStamped,
Pose,
Point,
Quaternion,
)
from std_msgs.msg import Header
from sensor_msgs.msg import JointState
from intera_core_msgs.srv import (
SolvePositionIK,
SolvePositionIKRequest,
)
def constrain(x, min_x, max_x):
return min(max_x, max(x, min_x))
def approach():
limb_mv = intera_interface.Limb("right")
overhead_orientation = Quaternion(
x=-0.00142460053167,
y=0.999994209902,
z=-0.00177030764765,
w=0.00253311793936)
approach = Pose(position=Point(x=0.45, y=-0.453, z=0.240),orientation=overhead_orientation)
print (approach)
# approach with a pose the hover-distance above the requested pose
approach.position.z = approach.position.z + 0.3
joint_angles = limb_mv.ik_request(approach, "right_hand")
limb_mv.set_joint_position_speed(0.1)
limb_mv.move_to_joint_positions(joint_angles)
def ik_service_client(limb = "right", tip_name = "right_gripper_tip"):
limb_mv = intera_interface.Limb(limb)
#gripper = intera_interface.Gripper()
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService"
iksvc = rospy.ServiceProxy(ns, SolvePositionIK)
ikreq = SolvePositionIKRequest()
hdr = Header(stamp=rospy.Time.now(), frame_id='base')
# Add desired pose for inverse kinematics
current_pose = limb_mv.endpoint_pose()
#print current_pose
movement = [0.460, -0.563,0.35]
orientation = [0.0,1,0.0,0.0]
#gripper.close()
rospy.sleep(1.0)
[dx,dy,dz] = movement
[ox,oy,oz,ow] = orientation
dy = constrain(dy,-0.7596394482267009,0.7596394482267009)
dz = constrain(dz, 0.02, 1)
# up position [0.45,-0.453,0.6] 0.11 for pick up location
#poses = {'right': PoseStamped(header=hdr,pose=Pose(position=Point(x=0.450628752997,y=0.161615832271,z=0.217447307078,),
#orientation=Quaternion(x=0.704020578925,y=0.710172716916,z=0.00244101361829,w=0.00194372088834,),),),} neutral pose
#x= 0.5,y = 0.5, z= 0.5,w= 0.5 for enpoint facing forward (orientation)
#table side parametres x=0.6529605227057904, y= +-0.7596394482267009, z=0.10958623747123714)
#table straight parametres x=0.99, y=0.0, z=0.1)
poses = {
'right': PoseStamped(
header=hdr,
pose=Pose(
position=Point(
x= dx,
y= dy,
z= dz,
),
orientation=Quaternion(
x= ox,
y= oy,
z= oz,
w= ow,
),
),
),
}
ikreq.pose_stamp.append(poses[limb])
# Request inverse kinematics from base to "right_hand" link
ikreq.tip_names.append('right_gripper_tip') # right_hand, right_wrist, right_hand_camera
try:
rospy.wait_for_service(ns, 5.0)
resp = iksvc(ikreq)
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
# Check if result valid, and type of seed ultimately used to get solution
if (resp.result_type[0] > 0):
seed_str = {
ikreq.SEED_USER: 'User Provided Seed',
ikreq.SEED_CURRENT: 'Current Joint Angles',
ikreq.SEED_NS_MAP: 'Nullspace Setpoints',
}.get(resp.result_type[0], 'None')
rospy.loginfo("SUCCESS - Valid Joint Solution Found from Seed Type: %s" %
(seed_str,))
# Format solution into Limb API-compatible dictionary
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
limb_mv.set_joint_position_speed(0.05)
limb_mv.move_to_joint_positions(limb_joints)
current_pose = limb_mv.endpoint_pose()
print current_pose
rospy.loginfo("\nIK Joint Solution:\n%s", limb_joints)
rospy.loginfo("------------------")
#rospy.loginfo("Response Message:\n%s", resp)
else:
rospy.logerr("INVALID POSE - No Valid Joint Solution Found.")
rospy.logerr("Result Error %d", resp.result_type[0])
return False
return True
def main():
"""RSDK Inverse Kinematics
A simple example of using the Rethink Inverse Kinematics
Service which returns the joint angles and validity for
a requested Cartesian Pose.
Run this example, the example will use the default limb
and call the Service with a sample Cartesian
Pose, pre-defined in the example code, printing the
response of whether a valid joint solution was found,
and if so, the corresponding joint angles.
"""
rospy.init_node("rsdk_ik_service_client")
if ik_service_client():
rospy.loginfo("Simple IK call passed!")
else:
rospy.logerr("Simple IK call FAILED")
if __name__ == '__main__':
main()
| UTF-8 | Python | false | false | 5,739 | py | 13 | ik.py | 13 | 0.624499 | 0.567346 | 0 | 169 | 32.95858 | 125 |
valterUo/MultiCategory-backend-py | 1,563,368,103,755 | c0eb1c16380dfd72cae31efe1e63c6c43893c067 | 7a28fb508e3ddabe6f2cb96f93702864b16189b8 | /src/multi_model_join/file_path_functions.py | b835c813ef81011a6247b234eb5437ca94a1f022 | [] | no_license | https://github.com/valterUo/MultiCategory-backend-py | e8dd902d1d4ccb95863b1e4b39c231e03683213f | fe6a97f28ab02d9bab3c19baf2b6cb7adb2bbf34 | refs/heads/master | 2023-02-02T12:07:05.324629 | 2020-12-18T17:37:41 | 2020-12-18T17:37:41 | 258,447,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
def parse_file_path(old_path, new_file_name):
dir_name = os.path.dirname(old_path)
# base = os.path.basename(old_path)
# filename = os.path.splitext(base)[0]
file_extension = os.path.splitext(old_path)[1]
return dir_name + "//" + new_file_name + file_extension
def parse_file_name(path):
base = os.path.basename(path)
filename = os.path.splitext(base)[0]
return filename | UTF-8 | Python | false | false | 434 | py | 224 | file_path_functions.py | 201 | 0.635945 | 0.629032 | 0 | 13 | 32.461538 | 63 |
gmcclur3/PyCrashCourse | 17,248,588,678,375 | 06f6586e519defab10b4d8acb7cb8c326c843756 | 0081d06443d1e43bd30cf68fd6905b9e6f9f44bf | /Chapter_5/magic_number.py | 6fa5790097a0c939e3fdc85c37267576427362db | [] | no_license | https://github.com/gmcclur3/PyCrashCourse | 166e86cbb1e9120ca9817a9cf27f336c29a77841 | 7b5037e2140c667c49fea099778cf0550de1d7b7 | refs/heads/master | 2021-01-10T10:48:24.291033 | 2016-02-22T22:20:00 | 2016-02-22T22:20:00 | 51,034,982 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Gary McClure 2016-02-08
answer = 17
if answer != 42:
print("That is not the correct answer, please try again.")
| UTF-8 | Python | false | false | 120 | py | 33 | magic_number.py | 32 | 0.675 | 0.575 | 0 | 6 | 19 | 62 |
ypwhs/python | 4,853,313,053,192 | 60ea236d4748615361ead00b542534a9f45d3d7b | 01a38a37d064374498a3f502da00acd97a6fdb6f | /others/coursera_srt.py | 501c48522fb8fa33e604dc41722050204abdc7d1 | [] | no_license | https://github.com/ypwhs/python | d0e91a936d73f6937b20d1663dda2274330d82c5 | e8e87b741e17ff90d729ab11088d22159d3b4e94 | refs/heads/master | 2019-04-12T12:59:32.540385 | 2016-10-20T16:24:50 | 2016-10-20T16:24:50 | 32,674,034 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | # encoding: utf-8
__author__ = 'ypw'
import os
from_ = '/Users/ypw/Desktop/DeepLearning/coursera/machine-learning'
for root, dirnames, filenames in os.walk(from_):
for filename in filenames:
if filename.find('DS_Store') != -1:
os.remove(root + '/' + filename)
if filename.find('zh-CN') == -1:
if filename.find('mp4') == -1:
if filename.find('.') != filename.rfind('.'):
os.remove(root + '/' + filename)
else:
if filename.find('.') != filename.rfind('.'):
os.rename(root + '/' + filename, root + '/' + filename.replace('.zh-CN', ''))
pass
| UTF-8 | Python | false | false | 672 | py | 65 | coursera_srt.py | 61 | 0.513393 | 0.505952 | 0 | 18 | 36.333333 | 93 |
akshaybabu09/fetch-html-content | 5,617,817,235,805 | 6ed4fc5779a7af27fcf1eaad9a318215bf38c436 | 82da23b536b27e6259dde79a11cc82846399cd24 | /api/fetch_html/views.py | 4749091c4bf42d872dd1f061f0f94a123eae7e93 | [] | no_license | https://github.com/akshaybabu09/fetch-html-content | 8f02a8f7bc4c8e5e9d9f5de46017a1954099e008 | afe36fce84676c1a66c6f915b03f255fd4d0931d | refs/heads/master | 2022-02-13T18:46:18.620690 | 2019-12-13T11:57:30 | 2019-12-13T11:57:30 | 227,527,530 | 0 | 0 | null | false | 2022-01-21T20:11:11 | 2019-12-12T05:31:13 | 2019-12-13T11:57:33 | 2022-01-21T20:11:10 | 15 | 0 | 0 | 5 | Python | false | false | from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.status import *
from fetch_html.constants import *
from fetch_html.libs.fetch_html_page import fetch_html_page
from fetch_html.services import check_for_url_email
class FetchHTMLContentAPI(APIView):
def post(self, request):
try:
url, email, data = check_for_url_email(request.data)
if not (url and email):
return Response(URLS_EMAILS_FOUND, status=HTTP_412_PRECONDITION_FAILED)
if not url:
return Response(URLS_NOT_FOUND, status=HTTP_412_PRECONDITION_FAILED)
if not email:
return Response(EMAILS_NOT_FOUND, status=HTTP_412_PRECONDITION_FAILED)
fetch_html_page.apply_async(kwargs=data)
return Response(SUCCESS_MSG, status=HTTP_200_OK)
except:
return Response(ERROR_MSG, status=HTTP_400_BAD_REQUEST)
| UTF-8 | Python | false | false | 963 | py | 11 | views.py | 8 | 0.671859 | 0.656282 | 0 | 27 | 34.666667 | 87 |
mcXrd/netwo | 11,355,893,563,925 | 6e6b2416e5252e714c748849d132e46134f6c70c | 5a836faaca8453fd1527599f952cb3f6979618fc | /main/main.py | d1a49f9f4ce2854161e73b09a30626feb141493e | [] | no_license | https://github.com/mcXrd/netwo | 47f5e08ab013088eff53058a74bd7e8da5f20778 | c97aeb09cf9e05f1b137ba326ef2fdc3e50e8d9d | refs/heads/NTW1 | 2020-03-12T23:39:35.227141 | 2018-04-28T14:10:01 | 2018-04-28T15:21:06 | 130,870,488 | 0 | 0 | null | false | 2018-05-08T19:08:10 | 2018-04-24T14:51:40 | 2018-04-28T15:21:23 | 2018-05-08T19:06:58 | 20 | 0 | 0 | 5 | Python | false | null | import settings
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from urls import add_urls
from pyramid.renderers import JSONP
if __name__ == '__main__':
config = Configurator()
config.include('pyramid_rpc.jsonrpc')
config.add_renderer('jsonp', JSONP())
config.add_jsonrpc_endpoint('api', '/api/jsonrpc', default_renderer='jsonp')
add_urls(config)
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
| UTF-8 | Python | false | false | 552 | py | 13 | main.py | 10 | 0.711957 | 0.697464 | 0 | 17 | 31.470588 | 80 |
ArsPro13/Movement-of-the-body-thrown-at-the-angle-to-the-horizon | 13,838,384,663,175 | 273f8d9d2c84641d7998a5bde00c5cc5cdc4f296 | 730670d69d4e83f1f1ec69f4f6484466a29fa774 | /main.py | d3b23d4752a9853ad92d394e1074708f7eaaa378 | [] | no_license | https://github.com/ArsPro13/Movement-of-the-body-thrown-at-the-angle-to-the-horizon | 2dc58fd7cdb4471208a20084678b5f596c6dd908 | 6afa4a1eb44e23c580f8d7e921adf872b424f33e | refs/heads/master | 2023-06-25T10:14:43.745884 | 2021-04-26T19:41:46 | 2021-04-26T19:41:46 | 339,555,057 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from tkinter import *
from math import sin, cos, pi, asin, acos, atan, sqrt, tan
import datetime
from tkinter import messagebox as mb
from tkinter import filedialog as fd
root = Tk()
root.title("Движение тела, брошенного под углом к горизонту")
root.resizable(width=False, height=False)
light_theme = True
label_bg_color = '#F7DDC4'
label_text_color = '#0C136F'
button_passive_bg_color = '#79A9F1'
button_passive_fg_color = '#ffffff'
button_active_bg_color = '#99BEF4'
button_active_fg_color = '#ffffff'
graph_x = 380
graph_y = 110
c = Canvas(root, bg='#F7DDC4', width=830, height=650)
root.geometry("830x650")
c.grid(row=0, column=0, columnspan=200, rowspan=70)
grafic = Canvas(root, bg='#D7E6FE', width=400, height=240)
stroim1=True
b_home = Button(root)
vvod = []
g = 9.81
files=[]
BB=[]
cifr = "1234567890.-"
r = 4
telo=''
XY=[]
def change_theme():
global light_theme
global main_buttons
global label_bg_color
global label_text_color
global button_passive_bg_color
global button_passive_fg_color
global button_active_bg_color
global button_active_fg_color
light_theme = not light_theme
if light_theme:
label_bg_color = '#F7DDC4'
label_text_color = '#0C136F'
button_passive_bg_color = '#79A9F1'
button_passive_fg_color = '#ffffff'
button_active_bg_color = '#99BEF4'
button_active_fg_color = '#ffffff'
else:
label_bg_color = '#000247'
label_text_color = '#FFFFFF'
button_passive_bg_color = '#002280'
button_passive_fg_color = '#FFFFFF'
button_active_bg_color = '#000E3D'
button_active_fg_color = '#FFFFFF'
for a in main_buttons:
a.destroy()
start_window()
def col_znak(numObj, digits=0):
return f"{numObj:.{digits}f}"
def is_num(st):
flag=True
st.replace(' ', '')
if (st==''):
flag=False
for a in st:
if not(a in cifr):
flag=False
return(flag)
def change_button (b1, st): # Изменение конпки
global light_theme
b1['text'] = st
b1['bg'] = button_passive_bg_color
b1['activebackground'] = button_active_bg_color
b1['fg'] = button_passive_fg_color
b1['activeforeground'] = button_active_fg_color
def delete_main(): # Переход от главного окна к побочному
global main_buttons
c.delete("all")
for a in main_buttons:
a.destroy()
global b_home
b_home = Button(root, height=3, width=7)
change_button(b_home, 'HOME')
b_home.place(x=750, y=572)
b_home.config(command=start_window)
# Под углом к горизонту с земли
def vvod_by_angle_zero(x=True):
grafic.delete("all")
global V0
global A
for a in XY:
a.destroy()
global H
global T
global L
V0 = vV0.get()
A = vA.get()
H = vH.get()
T = vT.get()
L = vL.get()
col=0
V0d = False
Ad = False
Hd = False
Td = False
Ld = False
global stroim
stroim = x
flag = True
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(A)):
col += 1
Ad = True
A = float(A)
A = A * pi / 180
if (A <= 0) or (A >= pi / 2):
flag = False
if (is_num(H)):
col += 1
Hd = True
H = float(H)
if (H <= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T <= 0):
flag = False
if (is_num(L)):
col += 1
Ld = True
L = float(L)
if (L <= 0):
flag = False
if (flag):
if (V0d and Ad):
try:
L = (V0 ** 2) * sin(2 * A) / g
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
T = 2 * V0 * sin(A) / g
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Ld):
try:
A = asin((L*g)/(V0**2)) / 2
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
T = 2 * V0 * sin(A) / g
vA.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vA.insert(0, round(A*180/pi*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Hd):
try:
A = asin(sqrt(H*2*g/V0**2))
L=V0**2 * sin(2*A) / g
T = 2 * V0 * sin(A) / g
vA.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vL.insert(0, round(L * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td):
try:
A = asin(T*g/(2*V0))
L = V0 ** 2 * sin(2 * A) / g
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
vA.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*180/pi*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Ld):
try:
A=A*180/pi
V0 = sqrt(L*g/sin(2*A))
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
T = 2 * V0 * sin(A) / g
vV0.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Hd):
try:
V0 = sqrt(H*2*g/(sin(A))**2)
T = 2 * V0 * sin(A) / g
L = V0 ** 2 * sin(2 * A) ** 2 / g
vV0.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Td):
try:
V0 = T*g/(2*sin(A))
L = V0 ** 2 * sin(2 * A) / g
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
vV0.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vL.insert(0, round(L * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Td and Ld):
try:
A = atan(g*T**2/(2*L))
V0 = T*g/(2*sin(A))
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
vV0.delete(0, END)
vA.delete(0, END)
vH.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vA.insert(0, round(A*180/pi*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Hd and Ld):
try:
A=atan(4*H/L)
V0 = sqrt(H*2*g/(sin(A))**2)
L = V0 ** 2 * sin(2 * A) / g
T = 2 * V0 * sin(A) / g
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vA.insert(0, round(A*180/pi*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
global graph_x
global graph_y
k = min(370 / L, 190 / H)
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210, 10 + 30 * cos(A), 210 - 30 * sin(A), arrow=LAST)
grafic.create_text(10 + 30 * cos(A) - 2, 210 - 30 * sin(A) - 14, text="Vo")
grafic.create_line(30, 210, 10 + 20 * cos(A), 210 - 20 * sin(A))
grafic.create_text(35, 210 - 10 * sin(A) , text="A")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(10, 220, text="0")
grafic.create_text(17+len(str(round(H * 100)/100))*5, 200 - (H * k), text=str(round(H * 100)/100))
grafic.create_line(5, 210 - (H * k), 390, 210 - (H * k), dash=True)
grafic.create_text(10 + L * k, 220, text=str(round(L * 100)/100))
grafic.create_line(10 + L * k, 10, 10 + L * k, 215, dash=True)
grafic.create_text(10 + (L * k) / 2, 220, text=str(round(L/2 * 100)/100))
grafic.create_line(10 + L * k / 2, 10, 10 + L * k / 2, 215, dash=True)
global i
global telo
global xy
xy = Label(text="x=0.000 , y=0.000", font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+175, y=graph_y+350)
XY.append(xy)
telo = grafic.create_oval(10 - r, 210 - r, 10 + r, 210 + r, fill="#c00300")
i=0
root.after(10, draw_angle_by_zero)
else:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def draw_angle_by_zero():
global i
global telo
global xy, XY
if (stroim):
grafic.delete(telo)
xy.destroy()
XY=[]
x = L / 2000 * i
y = tan(A) * x - g / (2 * V0 ** 2 * cos(A) ** 2) * x ** 2
x1 = L / 2000 * (i + 1)
y1 = tan(A) * x1 - g / (2 * V0 ** 2 * cos(A) ** 2) * x1 ** 2
telo = grafic.create_oval(((x1) * k + 10) - r, 220 - ((y1) * k + 10) - r, ((x1) * k + 10) + r, 220 - ((y1) * k + 10) + r, fill="#c00300")
grafic.create_line((x) * k + 10, 220 - ((y) * k + 10), ((x1) * k + 10), 220 - ((y1) * k + 10), fill="#c00300")
i+=1
xy = Label(text="x="+str(col_znak(round(x*1000)/1000, 3))+", y="+str(col_znak(round(y*1000)/1000, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
global vvod
vvod.append(xy)
if (i<=2000):
root.after(1, draw_angle_by_zero)
def del_by_angle_zero():
vA.delete(0, END)
vH.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def save_by_angle_zero():
vvod_by_angle_zero(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vA.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок под углом к горизонту с земли \n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "A (градусов) = " + str(vA.get()) + '\n'
file.write(st)
st = "H (м) = " + str(vH.get()) + '\n'
file.write(st)
st = "L (м) = " + str(vL.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def file_by_angle_zero():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==2):
fA = st
if (is_num(fA)):
n+=1
if (colvo==3):
fH = st
if (is_num(fH)):
n+=1
if (colvo==4):
fT = st
if (is_num(fT)):
n+=1
if (colvo==5):
fL = st
if (is_num(fL)):
n+=1
st = file.readline()
if (colvo==5) and (n==2):
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vA.delete(0, END)
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fA)):
vA.insert(0, str(fA))
if (is_num(fH)):
vH.insert(0, str(fH))
if (is_num(fT)):
vT.insert(0, str(fT))
if (is_num(fL)):
vL.insert(0, str(fL))
vvod_by_angle_zero()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def by_angle_zero(): # Бросок под углом с земли
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые два значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=70)
vvod.append(l1)
l2 = Label(text="Бросок под углом с земли", font="Cricket 23")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vV0
vV0= Entry(width=13)
vV0.place(x=150, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo (м/c) =", font="Cricket 10")
bV0.place(x=64, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vA
vA= Entry(width=13)
vA.place(x=150, y=175)
vvod.append(vA)
bA = Label(text="Угол (В градусах) = ", font="Cricket 10")
bA.place(x=5, y=175)
bA.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bA)
global vH
vH = Entry(width=13)
vH.place(x=150, y=197)
vvod.append(vH)
bH = Label(text="Hmax (м) = ", font="Cricket 10")
bH.place(x=49, y=197)
bH.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bH)
global vT
vT = Entry(width=13)
vT.place(x=150, y=219)
vvod.append(vT)
bT = Label(text="Tполёта (с) = ", font="Cricket 10")
bT.place(x=46, y=219)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vL
vL = Entry(width=13)
vL.place(x=150, y=244)
vvod.append(vL)
bL = Label(text="Lполёта (с) = ", font="Cricket 10")
bL.place(x=46, y=244)
bL.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bL)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=300)
vvod.append(bvvesti)
bvvesti.config(command=vvod_by_angle_zero)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=300)
vvod.append(bdel)
bdel.config(command=del_by_angle_zero)
bopen = Button(root, height=6, width=27, font=('Cricket', 10))
change_button(bopen, 'Считать значения из файла \n(введите 2 значения, на \nместе остальных "_" в\nследующем порядке: V0, A, H, T, L \n в файл "input.txt" в столбик)')
bopen.place(x=30, y=425)
vvod.append(bopen)
bopen.config(command=file_by_angle_zero)
bsave = Button(root, height=6, width=27, font=('Cricket', 10))
change_button(bsave,'Сохранить значения\n в файл')
bsave.place(x=350, y=425)
vvod.append(bsave)
bsave.config(command=save_by_angle_zero)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=100, y=350)
vvod.append(l3)
# Вертикально вверх с земли
def vvod_vert_zero(x=True):
grafic.delete("all")
global V0, H, T
V0 = vV0.get()
H = vH.get()
T = vT.get()
col = 0
V0d = False
for a in XY:
a.destroy()
Ad = True
A = pi/2
Hd = False
Td = False
global stroim
stroim = x
flag = True
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(H)):
col += 1
Hd = True
H = float(H)
if (H <= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T <= 0):
flag = False
if (flag):
if (V0d and Ad):
try:
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
T = 2 * V0 * sin(A) / g
vH.delete(0, END)
vT.delete(0, END)
vH.insert(0, round(H * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Hd):
try:
V0 = sqrt(H * 2 * g / (sin(A)) ** 2)
T = 2 * V0 * sin(A) / g
vV0.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Td):
try:
V0 = T * g / (2 * sin(A))
H = (V0 ** 2) * (sin(A) ** 2) / (2 * g)
vV0.delete(0, END)
vH.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
vV0.delete(0, END)
vT.delete(0, END)
vH.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = 190 / H
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210, 10 + 30 * cos(A), 210 - 30 * sin(A), arrow=LAST)
grafic.create_text(10 + 30 * cos(A) - 2, 210 - 30 * sin(A) - 14, text="Vo")
grafic.create_line(30, 210, 10 + 20 * cos(A), 210 - 20 * sin(A))
grafic.create_text(35, 210 - 10 * sin(A), text="A")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(10, 220, text="0")
grafic.create_text(17 + len(str(round(H * 100) / 100)) * 5, 200 - (H * k), text=str(round(H * 100) / 100))
grafic.create_line(5, 210 - (H * k), 390, 210 - (H * k), dash=True)
global i
global telo
telo = grafic.create_oval(10 - r, 210 - r, 10 + r, 210 + r, fill="#c00300")
i = 0
global xy
xy = Label(text="x=0.000 , y=0.000", font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
root.after(10, draw_vert_zero)
else:
vV0.delete(0, END)
vT.delete(0, END)
vH.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def draw_vert_zero():
global i
global telo
global xy, XY
if (stroim):
grafic.delete(telo)
xy.destroy()
XY=[]
x = T / 2000 * i
y = V0*x-g*x**2/2
x1 = T / 2000 * (i + 1)
y1 = V0*x1 - g*x1**2/2
telo = grafic.create_oval(10 - r, 210 - y1*k - r, 10 + r, 210 - y1*k + r, fill="#c00300")
grafic.create_line(10, 210 - y*k, 10, 210 - y1*k, fill="#c00300")
i+=1
xy = Label(text="x=0.000"+ ", y=" + str(col_znak(round(y * 1000) / 1000, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
global vvod
XY.append(xy)
vvod.append(xy)
if (i<=2000):
root.after(1, draw_vert_zero)
def del_vert_zero():
vH.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def file_vert_zero():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==2):
fH = st
if (is_num(fH)):
n+=1
if (colvo==3):
fT = st
if (is_num(fT)):
n+=1
st = file.readline()
if (colvo==3) and (n==1):
vH.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fH)):
vH.insert(0, str(fH))
if (is_num(fT)):
vT.insert(0, str(fT))
vvod_vert_zero()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_vert_zero():
vvod_vert_zero(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vT.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок вертикально вверх с земли \n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "A (градусов) = 90" + '\n'
file.write(st)
st = "H (м) = " + str(vH.get()) + '\n'
file.write(st)
st = "L (м) = 0" + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def vert_zero(): # Бросок под углом с земли
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любое значение", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=70)
vvod.append(l1)
l2 = Label(text="Бросок вертикально вверх с земли", font="Cricket 23")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vV0
vV0= Entry(width=13)
vV0.place(x=164, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo (м/с) =", font="Cricket 10")
bV0.place(x=76, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vH
vH = Entry(width=13)
vH.place(x=164, y=197)
vvod.append(vH)
bH = Label(text="Hmax (м) = ", font="Cricket 10")
bH.place(x=56, y=197)
bH.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bH)
global vT
vT = Entry(width=13)
vT.place(x=164, y=174)
vvod.append(vT)
bT = Label(text="Tполёта (с) = ", font="Cricket 10")
bT.place(x=53, y=174)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=275)
vvod.append(bvvesti)
bvvesti.config(command=vvod_vert_zero)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=275)
vvod.append(bdel)
bdel.config(command=del_vert_zero)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen, 'Считать значения из файла \n(введите 1 значение, на \nместе остальных "_" в\nследующем порядке: V0, H, T \n в файл "input.txt" в столбик)' )
bopen.place(x=30, y=425)
vvod.append(bopen)
bopen.config(command=file_vert_zero)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave,'Сохранить значения\n в файл')
bsave.place(x=350, y=425)
vvod.append(bsave)
bsave.config(command=save_vert_zero)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=350)
vvod.append(l3)
# Горизонтально с высоты h
def vvod_hor_h(x=True):
grafic.delete("all")
global h, V0, T, L, stroim
V0 = vV0.get()
h = vh.get()
T = vT.get()
L = vL.get()
col = 0
for a in XY:
a.destroy()
V0d = False
hd = False
Td = False
Ld = False
flag = True
stroim = True
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h<= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T<=0):
flag = False
if (is_num(L)):
col += 1
Ld = True
L = float(L)
if (L<=0):
flag = False
if (flag):
if (V0d and hd):
try:
T = sqrt(2*h/g)
L = V0*T
vL.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td):
try:
h = T**2 * g/2
L = V0*T
vL.delete(0, END)
vh.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ld and hd):
try:
V0 = L*sqrt(g/(2*h))
T = sqrt(2 * h / g)
vV0.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Td and Ld):
try:
V0 = L/T
h=g*T**2 / 2
vV0.delete(0, END)
vh.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Ld):
try:
h = g/2 * (L/V0)**2
T = sqrt(2 * h / g)
vT.delete(0, END)
vh.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
vV0.delete(0, END)
vh.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim=False
if (stroim):
global k
k = min(370 / L, 190 / h)
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210-h*k, 30, 210 - h*k, arrow=LAST)
grafic.create_text(35, 200-h*k, text="Vo")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(10, 220, text="0")
grafic.create_text(10 + L * k, 220, text=str(round(L * 100)/100))
grafic.create_line(10 + L * k, 10, 10 + L * k, 215, dash=True)
grafic.create_text(60, 200 - h* k, text=str(round(h * 100) / 100))
grafic.create_line(10, 210-h*k, 400, 210-h*k, dash=True)
global i
global telo
global xy
xy = Label(text="x=0.000 , y=0.000", font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
telo = grafic.create_oval(10 - r, 210 - h*k - r, 10 + r, 210 - h*k + r, fill="#c00300")
i = 0
XY.append(xy)
root.after(10, draw_hor_h)
else:
vV0.delete(0, END)
vh.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def draw_hor_h():
global i
global telo
global xy, XY
global stroim
if (stroim):
grafic.delete(telo)
xy.destroy()
XY=[]
x = L / 2000 * i
y = h - g * x ** 2 / (2 * V0 ** 2)
x1 = L / 2000 * (i + 1)
y1 = h - g * x1 ** 2 / (2 * V0 ** 2)
grafic.create_line((x) * k + 10, 220 - ((y) * k + 10), ((x1) * k + 10), 220 - ((y1) * k + 10),fill="#c00300")
telo = grafic.create_oval(((x1) * k + 10) - r, 220 - ((y1) * k + 10) - r, ((x1) * k + 10) + r, 220 - ((y1) * k + 10) + r, fill="#c00300")
i+=1
xy = Label(text="x="+str(col_znak(round(x*1000)/1000, 3))+", y="+str(col_znak(round(y*1000)/1000, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
global vvod
XY.append(xy)
vvod.append(xy)
if (i<=2000):
root.after(1, draw_hor_h)
def del_hor_h():
vh.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def file_hor_h():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==2):
fh = st
if (is_num(fh)):
n+=1
if (colvo==3):
fL= st
if (is_num(fL)):
n+=1
if (colvo==4):
fT= st
if (is_num(fT)):
n+=1
st = file.readline()
if (colvo==4) and (n==2):
vh.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fL)):
vL.insert(0, str(fL))
if (is_num(fT)):
vT.insert(0, str(fT))
vvod_hor_h()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_hor_h():
vvod_hor_h(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vh.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок горизонтально с высоты \n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "L (м) = " + str(vL.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def hor_h():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые два значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=70)
vvod.append(l1)
l2 = Label(text="Бросок горизонтально с высоты", font="Cricket 23")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vV0
vV0 = Entry(width=13)
vV0.place(x=164, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo(м/с) =", font="Cricket 10")
bV0.place(x=76, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vh
vh = Entry(width=13)
vh.place(x=164, y=175)
vvod.append(vh)
bh = Label(text="Начальная высота (м) = ", font="Cricket 10")
bh.place(x=4, y=175)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vL
vL = Entry(width=13)
vL.place(x=164, y=197)
vvod.append(vL)
bL = Label(text=" L(м) =", font="Cricket 10")
bL.place(x=60, y=197)
bL.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bL)
global vT
vT = Entry(width=13)
vT.place(x=164, y=219)
vvod.append(vT)
bT = Label(text="Tполёта(с) = ", font="Cricket 10")
bT.place(x=54, y=219)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=275)
vvod.append(bvvesti)
bvvesti.config(command=vvod_hor_h)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=275)
vvod.append(bdel)
bdel.config(command=del_hor_h)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen,
'Считать значения из файла \n(введите 2 значения, на \nместе остальных "_" в\nследующем порядке: V0, h, L, T \n в файл "input.txt" в столбик)')
bopen.place(x=30, y=425)
vvod.append(bopen)
bopen.config(command=file_hor_h)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave, 'Сохранить значения\n в файл')
bsave.place(x=350, y=425)
vvod.append(bsave)
bsave.config(command=save_hor_h)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=350)
vvod.append(l3)
# вертикально вверх с высоты
def vvod_vert_v_h(x=True):
grafic.delete("all")
global V0, h, H, T, Vk
V0 = vV0.get()
h = vh.get()
for a in XY:
a.destroy()
H = vH.get()
T = vT.get()
Vk = vVk.get()
col=0
V0d = False
hd = False
Hd = False
Td = False
Vkd = False
global stroim
stroim = x
flag = True
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h <= 0):
flag = False
if (is_num(H)):
col += 1
Hd = True
H = float(H)
if (H <= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T <= 0):
flag = False
if (is_num(Vk)):
col += 1
Vkd = True
Vk = float(Vk)
if (Vk <= 0):
flag = False
if (flag):
if (V0d and Vkd):
if (Vk < V0):
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
try:
h = (Vk**2-V0**2)/(2*g)
H = h + V0**2/(2*g)
T = (V0+sqrt(V0**2+2*g*h))/g
vh.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vh.insert(0, round(h*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and hd):
try:
T=(V0+sqrt(V0**2+2*g*h))/g
H = h + V0 ** 2 / (2 * g)
Vk=sqrt(V0**2+2*g*h)
vVk.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Hd):
try:
h = H-V0**2/(2*g)
T = (V0 + sqrt(V0 ** 2 + 2 * g * h)) / g
Vk = sqrt(V0 ** 2 + 2 * g * h)
vVk.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td):
try:
h = (g**2*(T-V0/g)**2-V0**2)/(2*g)
H = h + V0 ** 2 / (2 * g)
Vk = sqrt(V0 ** 2 + 2 * g * h)
vVk.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Hd):
if (H-h<0):
mb.showerror("Ошибка", "Расчеты невозможны")
stroim = False
else:
try:
V0 = sqrt((H - h) * 2 * g)
T = (V0 + sqrt(V0 ** 2 + 2 * g * h)) / g
Vk = sqrt(V0 ** 2 + 2 * g * h)
vVk.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Td):
try:
V0 = (T**2*g-2*h)/(2*T)
Vk = sqrt(V0 ** 2 + 2 * g * h)
H = h + V0 ** 2 / (2 * g)
vVk.delete(0, END)
vH.delete(0, END)
vV0.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Vkd):
if (Vk**2-2*g*h <0):
mb.showerror("Ошибка", "Расчеты невзможны")
stroim = False
else:
try:
V0 = sqrt(Vk**2-2*g*h)
H = h + V0 ** 2 / (2 * g)
T = (V0 + sqrt(V0 ** 2 + 2 * g * h)) / g
vT.delete(0, END)
vH.delete(0, END)
vV0.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Hd and Td):
try:
V0 = T*g-sqrt(2*g*H)
h = (2*g*H-V0**2)/(2*g)
Vk = sqrt(V0**2+2*g*h)
vVk.delete(0, END)
vh.delete(0, END)
vV0.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Td and Vkd):
try:
V0 = T*g-Vk
h = (Vk**2-V0**2)/(2*g)
H = h + V0 ** 2 / (2 * g)
vH.delete(0, END)
vh.delete(0, END)
vV0.delete(0, END)
vH.insert(0, round(H * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
vV0.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = 190 / H
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210-h*k, 10 , 210 - 30-h*k, arrow=LAST)
grafic.create_text(19, 210 - 30 - h*k, text="Vo")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(24, 210-h*k, text=str(round(h*1000)/1000))
grafic.create_text(10, 220, text="0")
grafic.create_text(17 + len(str(round(H * 100) / 100)) * 5, 200 - (H * k), text=str(round(H * 100) / 100))
grafic.create_line(5, 210 - (H * k), 390, 210 - (H * k), dash=True)
global i
global telo
telo = grafic.create_oval(10 - r, 210-h*k - r, 10 + r, 210-h*k + r, fill="#c00300")
i = 0
global xy
xy = Label(text="x=0.000 , y="+str(h), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
root.after(1, draw_vert_v_h)
else:
vV0.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def draw_vert_v_h():
global i
global telo
global xy
global stroim
global h, k
if (stroim):
grafic.delete(telo)
xy.destroy()
x = T / 2000 * i
y = h+ V0*x-g*x**2/2
x1 = T / 2000 * (i + 1)
y1 = h+ V0*x1 - g*x1**2/2
telo = grafic.create_oval(10 - r, 210 - y1*k - r, 10 + r, 210 - y1*k + r, fill="#c00300")
grafic.create_line(10, 210 - y*k, 10, 210 - y1*k, fill="#c00300")
i+=1
xy = Label(text="x=0.000"+ ", y=" + str(col_znak(y1, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
global vvod
vvod.append(xy)
if (i<2000):
root.after(1, draw_vert_v_h)
def del_vert_v_h():
vH.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
vh.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def file_vert_v_h():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo += 1
st = st.rstrip('\n')
if (colvo == 1):
fV0 = st
if (is_num(fV0)):
n += 1
if (colvo == 2):
fh = st
if (is_num(fh)):
n += 1
if (colvo == 3):
fH = st
if (is_num(fH)):
n += 1
if (colvo == 4):
fT = st
if (is_num(fT)):
n += 1
if (colvo == 5):
fVk = st
if (is_num(fVk)):
n += 1
st = file.readline()
if (colvo == 5) and (n == 2):
vh.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vVk.delete(0, END)
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fH)):
vL.insert(0, str(fH))
if (is_num(fT)):
vT.insert(0, str(fT))
if (is_num(fVk)):
vV0.insert(0, str(fVk))
vvod_vert_v_h()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_vert_v_h():
vvod_vert_v_h(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vh.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок вертикально вверх с высоты \n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "H (м) = " + str(vH.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
st = "Vk (м/с) = " + str(vVk.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def vert_v_h():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые два значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=70)
vvod.append(l1)
l2 = Label(text="Бросок вертикально вверх с высоты", font="Cricket 23")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vV0
vV0 = Entry(width=13)
vV0.place(x=164, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo(м/с) =", font="Cricket 10")
bV0.place(x=75, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vh
vh = Entry(width=13)
vh.place(x=164, y=175)
vvod.append(vh)
bh = Label(text="h(м) =", font="Cricket 10")
bh.place(x=83, y=175)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vH
vH = Entry(width=13)
vH.place(x=164, y=197)
vvod.append(vH)
bH = Label(text="Hmax(м) = ", font="Cricket 10")
bH.place(x=52, y=197)
bH.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bH)
global vT
vT = Entry(width=13)
vT.place(x=164, y=219)
vvod.append(vT)
bT = Label(text="Tполёта(с) = ", font="Cricket 10")
bT.place(x=53, y=219)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vVk
vVk = Entry(width=13)
vVk.place(x=164, y=244)
vvod.append(vVk)
bVk = Label(text="Vконечная(м/c) = ", font="Cricket 10")
bVk.place(x=31, y=244)
bVk.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bVk)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=275)
vvod.append(bvvesti)
bvvesti.config(command=vvod_vert_v_h)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=275)
vvod.append(bdel)
bdel.config(command=del_vert_v_h)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen,
'Считать значения из файла \n(введите 2 значения, на \nместе остальных "_" в\nследующем порядке: V0, h, H, T, Vk \n в файл "input.txt" в столбик)')
bopen.place(x=30, y=425)
vvod.append(bopen)
bopen.config(command=file_vert_v_h)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave, 'Сохранить значения\n в файл')
bsave.place(x=350, y=425)
vvod.append(bsave)
bsave.config(command=save_vert_v_h)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=350)
vvod.append(l3)
# вертикально вниз с высоты
def vvod_vert_vniz_h(x=True):
grafic.delete("all")
global V0, h, T, Vk
V0 = vV0.get()
global XY
for a in XY:
a.destroy()
h = vh.get()
T = vT.get()
Vk = vVk.get()
col=0
V0d = False
hd = False
Td = False
Vkd = False
global stroim
flag = True
stroim = x
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 < 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h < 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T < 0):
flag = False
if (is_num(Vk)):
col += 1
Vkd = True
Vk = float(Vk)
if (Vk < 0):
flag = False
if (flag):
if (V0d and Vkd):
if (Vk < V0):
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
try:
h = (Vk**2-V0**2)/(2*g)
T = (-V0+sqrt(V0**2+2*g*h))/g
vh.delete(0, END)
vT.delete(0, END)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and hd):
try:
T=(-V0+sqrt(V0**2+2*g*h))/g
Vk=sqrt(V0**2+2*g*h)
vVk.delete(0, END)
vT.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td):
try:
h = (g**2*(T+V0/g)**2-V0**2)/(2*g)
Vk = sqrt(V0 ** 2 + 2 * g * h)
vVk.delete(0, END)
vh.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Td):
try:
V0 = -1 * (T**2*g-2*h)/(2*T)
Vk = sqrt(V0 ** 2 + 2 * g * h)
vVk.delete(0, END)
vV0.delete(0, END)
vVk.insert(0, round(Vk * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Vkd):
if (Vk**2-2*g*h <0):
mb.showerror("Ошибка", "Расчеты невзможны")
stroim = False
else:
try:
V0 = sqrt(Vk**2-2*g*h)
T=(-V0+sqrt(V0**2+2*g*h))/g
vT.delete(0, END)
vV0.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Td and Vkd):
try:
V0 = -(T*g-Vk)
h = (Vk**2-V0**2)/(2*g)
vh.delete(0, END)
vV0.delete(0, END)
vh.insert(0, round(h * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
vV0.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = 190 / h
H=h
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210-h*k, 10 , 210 - 30-h*k, arrow=LAST)
grafic.create_text(19, 210 - 30 - h*k, text="Vo")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(24, 210-h*k, text=str(round(h*1000)/1000))
grafic.create_text(10, 220, text="0")
grafic.create_text(17 + len(str(round(H * 100) / 100)) * 5, 200 - (H * k), text=str(round(H * 100) / 100))
grafic.create_line(5, 210 - (h * k), 390, 210 - (h * k), dash=True)
global i
global telo
telo = grafic.create_oval(10 - r, 210-h*k - r, 10 + r, 210-h*k + r, fill="#c00300")
i = 0
global xy
xy = Label(text="x=0.000 , y="+str(h), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
root.after(1, draw_vert_vniz_h)
else:
vV0.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def draw_vert_vniz_h():
global i
global telo
global xy, XY
global stroim
global h, k
col = 1000
if (stroim):
grafic.delete(telo)
xy.destroy()
XY=[]
x = T / col * i
y = h - V0*x-g*x**2/2
x1 = T / col * (i + 1)
y1 = h - V0*x1 - g*x1**2/2
telo = grafic.create_oval(10 - r, 210 - y1*k - r, 10 + r, 210 - y1*k + r, fill="#c00300")
grafic.create_line(10, 210 - y*k, 10, 210 - y1*k, fill="#c00300")
i+=1
xy = Label(text="x=0.000"+ ", y=" + str(col_znak(y1, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
global vvod
XY.append(xy)
vvod.append(xy)
if (i<col):
root.after(1, draw_vert_vniz_h)
def del_vert_vniz_h():
vV0.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
vh.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def file_vert_vniz_h():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo += 1
st = st.rstrip('\n')
if (colvo == 1):
fV0 = st
if (is_num(fV0)):
n += 1
if (colvo == 2):
fh = st
if (is_num(fh)):
n += 1
if (colvo == 3):
fVk = st
if (is_num(fVk)):
n += 1
if (colvo == 4):
fT = st
if (is_num(fT)):
n += 1
st = file.readline()
if (colvo == 4) and (n == 2):
vh.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vVk.delete(0, END)
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fT)):
vT.insert(0, str(fT))
if (is_num(fVk)):
vV0.insert(0, str(fVk))
vvod_vert_vniz_h()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_vert_vniz_h():
vvod_vert_vniz_h(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vh.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок вертикально вниз с высоты \n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "Vk (м/с) = " + str(vVk.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def vert_vniz_h():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые два значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=70)
vvod.append(l1)
l2 = Label(text="Бросок вертикально вниз с высоты", font="Cricket 23")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vV0
vV0 = Entry(width=13)
vV0.place(x=164, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo(м/с) =", font="Cricket 10")
bV0.place(x=75, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vh
vh = Entry(width=13)
vh.place(x=164, y=175)
vvod.append(vh)
bh = Label(text="h(м) =", font="Cricket 10")
bh.place(x=83, y=175)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vT
vT = Entry(width=13)
vT.place(x=164, y=219)
vvod.append(vT)
bT = Label(text="Tполёта(с) = ", font="Cricket 10")
bT.place(x=53, y=219)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vVk
vVk = Entry(width=13)
vVk.place(x=164, y=197)
vvod.append(vVk)
bVk = Label(text="Vконечная(м/c) = ", font="Cricket 10")
bVk.place(x=31, y=197)
bVk.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bVk)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=275)
vvod.append(bvvesti)
bvvesti.config(command=vvod_vert_vniz_h)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=275)
vvod.append(bdel)
bdel.config(command=del_vert_vniz_h)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen,
'Считать значения из файла \n(введите 2 значения, на \nместе остальных "_" в\nследующем порядке: V0, h, Vk, T \n в файл "input.txt" в столбик)')
bopen.place(x=30, y=425)
vvod.append(bopen)
bopen.config(command=file_vert_vniz_h)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave, 'Сохранить значения\n в файл')
bsave.place(x=350, y=425)
vvod.append(bsave)
bsave.config(command=save_vert_vniz_h)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=350)
vvod.append(l3)
# Под углом к горизонту с высоты h
def vvod_by_angle_h(x=True):
grafic.delete("all")
global V0
global A
global H
global T
global L
global h
global XY
for a in XY:
a.destroy()
global V0, h, A, B, T, L
h = vh.get()
V0 = vV0.get()
A = vA.get()
H = vH.get()
T = vT.get()
L = vL.get()
col=0
V0d = False
Ad = False
Hd = False
Td = False
Ld = False
hd = False
flag = True
global stroim
stroim = x
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h <= 0):
flag = False
if (is_num(A)):
col += 1
Ad = True
A = float(A)
A = A * pi / 180
if (is_num(H)):
col += 1
Hd = True
H = float(H)
if (H <= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T <= 0):
flag = False
if (is_num(L)):
col += 1
Ld = True
L = float(L)
if (L <= 0):
flag = False
if (flag):
if (V0d and Ad and hd):
if (A > -pi/2) and (A < pi/2):
try:
L = (V0**2*sin(A)*cos(A)+V0*cos(A)*sqrt(V0**2*sin(A)**2+2*g*h)) / g
H = (V0**2*sin(A)**2+2*g*h)/(2 * g)
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Hd):
if (h <= H) and (V0 != 0):
try:
A=asin(sqrt(2*g*(H-h)/V0**2))
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
T = (V0 * sin(A) + sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
vL.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vA.insert(0, round(A*180/pi * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Td):
x=(T**2*g - 2*h)/ (2*T*V0)
if (x>-1) and (x<1):
try:
A=asin(x)
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
H = (V0**2*sin(A)**2+2*g*h)/(2 * g)
vL.delete(0, END)
vA.delete(0, END)
vH.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Ld):
D = (V0**2+g*h)**2 - g**2*(h**2+L**2)
if (D>0):
T = sqrt((V0**2 + g*h + sqrt(D))/(g**2/2))
if (L/(T*V0) > -1) and (L/(T*V0) < 1):
try:
A = acos(L/(T*V0))
H = (V0 ** 2 * sin(A) ** 2 + 2 * g * h) / (2 * g)
vT.delete(0, END)
vA.delete(0, END)
vH.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (hd and Ad and Hd):
if (H>=h):
try:
V0 = sqrt((H-h)*2*g/sin(A)**2)
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
T = (V0 * sin(A) + sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
vT.delete(0, END)
vA.delete(0, END)
vL.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
vL.insert(0, round(L * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (hd and Ad and Td):
V0 = (T**2*g-2*h)/(2*T*sin(A))
if (V0>0):
try:
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
H = (V0 ** 2 * sin(A) ** 2 + 2 * g * h) / (2 * g)
vL.delete(0, END)
vV0.delete(0, END)
vH.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (hd and Ad and Ld):
x = L**2*g**2/(2*(L*g*sin(A)*cos(A) + g*h*cos(A)**2))
if (x>0):
try:
V0 = sqrt(x)
H = (V0 ** 2 * sin(A) ** 2 + 2 * g * h) / (2 * g)
T = (V0 * sin(A) + sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
vT.delete(0, END)
vV0.delete(0, END)
vH.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vV0.insert(0, round(V0 * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Hd):
try:
if (A<=0):
h = H
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
T = (V0 * sin(A) + sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
else:
h = H - V0**2*sin(A)**2/(2*g)
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
T = (V0 * sin(A) + sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
vL.delete(0, END)
vT.delete(0, END)
vh.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Ad and Td):
try:
h = ((T*g-V0*sin(A))**2-V0**2*sin(A)**2)/(2*g)
L = (V0 ** 2 * sin(A) * cos(A) + V0 * cos(A) * sqrt(V0 ** 2 * sin(A) ** 2 + 2 * g * h)) / g
H = (V0 ** 2 * sin(A) ** 2 + 2 * g * h) / (2 * g)
vL.delete(0, END)
vH.delete(0, END)
vh.delete(0, END)
vL.insert(0, round(L * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Ad and Ld):
try:
T = L/(V0*cos(A))
h = ((T*g-V0*sin(A))**2-V0**2*sin(A)**2)/(2*g)
H = (V0 ** 2 * sin(A) ** 2 + 2 * g * h) / (2 * g)
vT.delete(0, END)
vH.delete(0, END)
vh.delete(0, END)
vT.insert(0, round(T * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Hd and Td):
try:
V0 = (g*T - sqrt(2*g*H))/g
h = H - V0**2*sin(A)**2/(2*g)
L = V0*cos(A)*T
vV0.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vL.insert(0, round(L * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Ad and Hd and Ld):
try:
D = (cos(A)*sqrt(2*g*H))**2 + 4*L*sin(A)*cos(A)*g
V0 = max((-1*cos(A)*sqrt(2*g*H) + sqrt(D))/(2*sin(A)*cos(A)), (-1*cos(A)*sqrt(2*g*H) - sqrt(D))/(2*sin(A)*cos(A)))
h = H - V0 ** 2 * sin(A) ** 2 / (2 * g)
T = L/(V0 * cos(A))
vV0.delete(0, END)
vT.delete(0, END)
vh.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Td and Ld and Hd):
try:
A = atan(T*(T*g- sqrt(2*g*H))/L)
V0 = L/(T*cos(A))
h = H - V0**2 * sin(A)**2/(2*g)
vh.delete(0, END)
vA.delete(0, END)
vV0.delete(0, END)
vh.insert(0, round(h * 1000) / 1000)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vV0.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Td and Ld):
V0 =sqrt((L**2 + (g*T**2/2 - h)**2)/T**2)
x = L/(V0*T)
if (x>-1) and (x<1):
try:
A = acos(x)
H = (V0 ** 2 * sin(A) ** 2 + 2 * g * h) / (2 * g)
vH.delete(0, END)
vA.delete(0, END)
vV0.delete(0, END)
vH.insert(0, round(H * 1000) / 1000)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vV0.insert(0, round(H * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Hd and Td):
x = (T*g-sqrt(2*g*H))/V0
if (x>-1)and (x<1):
try:
A = asin(x)
h = H - (V0**2*sin(A)**2)/(2*g)
L =T*V0*cos(A)
vH.delete(0, END)
vA.delete(0, END)
vL.delete(0, END)
vH.insert(0, round(H * 1000) / 1000)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vL.insert(0, round(L * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Hd and Td):
x = (T*g - sqrt(2*g*H))/V0
if (x>-1)and(x<1):
try:
A = asin(x)
h = H - V0**2*sin(A)**2/(2*g)
L = V0*cos(A)*T
vh.delete(0, END)
vA.delete(0, END)
vL.delete(0, END)
vh.insert(0, round(h * 1000) / 1000)
vA.insert(0, round(A * 180 / pi * 1000) / 1000)
vL.insert(0, round(L * 1000) / 1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ad and Td and Ld):
V0 = L/(T*cos(A))
H = (T*g - V0*sin(A))**2/(2*g)
h = H - V0**2*sin(A)**2/(2*g)
vV0.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vV0.insert(0, round(V0 * 1000) / 1000)
vH.insert(0, round(H * 1000) / 1000)
vh.insert(0, round(h * 1000) / 1000)
else:
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = min(370 / L, 190 / H)
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210 - h*k, 10 + 30 * cos(A), 210 - h*k - 30 * sin(A), arrow=LAST)
grafic.create_text(10 + 30 * cos(A) + 11, 210 - h*k - 30 * sin(A) + 5, text="Vo")
grafic.create_line(30, 210 - h*k, 10 + 20 * cos(A), 210 - h*k - 20 * sin(A))
grafic.create_line(10, 210 - h * k, 45, 210 - h * k, dash = True)
grafic.create_text(35, 210 - h*k - 10 * sin(A) , text="A")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(10, 220, text="0")
grafic.create_text(17+len(str(round(H * 100)/100))*5, 200 - (H * k), text=str(round(H * 100)/100))
grafic.create_line(5, 210 - (H * k), 390, 210 - (H * k), dash=True)
grafic.create_text(10 + L * k, 220, text=str(round(L * 100)/100))
grafic.create_line(10 + L * k, 10, 10 + L * k, 215, dash=True)
grafic.create_text(10 + (V0**2*sin(A)*cos(A)/g)*k, 220, text=str(round(V0**2*sin(A)*cos(A)/g * 100)/100))
grafic.create_line(10 + (V0**2*sin(A)*cos(A)/g)*k, 10, 10 + (V0**2*sin(A)*cos(A)/g)*k, 215, dash=True)
global i
global telo
global xy
xy = Label(text="x=0.000 , y=0.000", font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x= 400, y=320)
XY.append(xy)
telo = grafic.create_oval(10 - r, 210-h*k - r, 10 + r, 210-h*k + r, fill="#c00300")
i=0
root.after(10, draw_angle_by_h)
else:
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def draw_angle_by_h():
global i
global telo
global xy, XY
if (stroim):
grafic.delete(telo)
xy.destroy()
XY=[]
x = L / 2000 * i
y = h + tan(A) * x - g / (2 * V0 ** 2 * cos(A) ** 2) * x ** 2
x1 = L / 2000 * (i + 1)
y1 = h + tan(A) * x1 - g / (2 * V0 ** 2 * cos(A) ** 2) * x1 ** 2
telo = grafic.create_oval(((x1) * k + 10) - r, 220 - ((y1) * k + 10) - r, ((x1) * k + 10) + r, 220 - ((y1) * k + 10) + r, fill="#c00300")
grafic.create_line((x) * k + 10, 220 - ((y) * k + 10), ((x1) * k + 10), 220 - ((y1) * k + 10), fill="#c00300")
i+=1
xy = Label(text="x="+str(col_znak(round(x*1000)/1000, 3))+", y="+str(col_znak(round(y*1000)/1000, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
global vvod
vvod.append(xy)
if (i<=2000):
root.after(1, draw_angle_by_h)
def del_by_angle_h():
vA.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def file_by_angle_h():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fh = st
if (is_num(fh)):
n+=1
if (colvo==2):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==3):
fA = st
if (is_num(fA)):
n+=1
if (colvo==4):
fH = st
if (is_num(fH)):
n+=1
if (colvo==5):
fT = st
if (is_num(fT)):
n+=1
if (colvo==6):
fL = st
if (is_num(fL)):
n+=1
st = file.readline()
if (colvo==6) and (n==3):
vh.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vA.delete(0, END)
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fA)):
vA.insert(0, str(fA))
if (is_num(fH)):
vH.insert(0, str(fH))
if (is_num(fT)):
vT.insert(0, str(fT))
if (is_num(fL)):
vL.insert(0, str(fL))
vvod_by_angle_h()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_by_angle_h():
vvod_by_angle_h(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vA.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок под углом к горизонту с высоты h \n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "A (градусов) = " + str(vA.get()) + '\n'
file.write(st)
st = "H (м) = " + str(vH.get()) + '\n'
file.write(st)
st = "L (м) = " + str(vL.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def by_angle_h():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые три значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=70)
vvod.append(l1)
l2 = Label(text="Бросок под углом к горизонту с высоты", font="Cricket 20")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vh
vh = Entry(width=13)
vh.place(x=164, y=150)
vvod.append(vh)
bh = Label(text="h (м) =", font="Cricket 10")
bh.place(x=70, y=150)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vV0
vV0= Entry(width=13)
vV0.place(x=164, y=175)
vvod.append(vV0)
bV0 = Label(text="Vo (м/c) =", font="Cricket 10")
bV0.place(x=70, y=175)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vA
vA= Entry(width=13)
vA.place(x=164, y=201)
vvod.append(vA)
bA = Label(text="Угол (В градусах) = ", font="Cricket 10")
bA.place(x=17, y=201)
bA.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bA)
global vH
vH = Entry(width=13)
vH.place(x=164, y=223)
vvod.append(vH)
bH = Label(text="Hmax (м) = ", font="Cricket 10")
bH.place(x=61, y=223)
bH.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bH)
global vT
vT = Entry(width=13)
vT.place(x=164, y=248)
vvod.append(vT)
bT = Label(text="Tполёта (с) = ", font="Cricket 10")
bT.place(x=58, y=248)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vL
vL = Entry(width=13)
vL.place(x=164, y=275)
vvod.append(vL)
bL = Label(text="Lполёта (м) = ", font="Cricket 10")
bL.place(x=52, y=275)
bL.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bL)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=330)
vvod.append(bvvesti)
bvvesti.config(command=vvod_by_angle_h)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=330)
vvod.append(bdel)
bdel.config(command=del_by_angle_h)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen, 'Считать значения из файла \n(введите 2 значения, на \nместе остальных "_" в\nследующем порядке: h, V0, A, H, T, L \n в файл "input.txt" в столбик)' )
bopen.place(x=30, y=450)
vvod.append(bopen)
bopen.config(command=file_by_angle_h)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave,'Сохранить значения\n в файл')
bsave.place(x=350, y=450)
vvod.append(bsave)
bsave.config(command=save_by_angle_h)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=380)
vvod.append(l3)
# Под углом с движущегося тела
def vvod_by_angle_h_move(x=True):
grafic.delete("all")
global V0
global Vdop
global A
global H
global T
global L
global h
global XY
for a in XY:
a.destroy()
global V0, h, A, B, T, L, Vdop
h = vh.get()
V0 = vV0.get()
A = vA.get()
H = vH.get()
T = vT.get()
L = vL.get()
Vdop = vVdop.get()
col=0
V0d = False
Ad = False
Hd = False
Td = False
Ld = False
hd = False
Vdopd = False
flag = True
global stroim
stroim = x
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h <= 0):
flag = False
if (is_num(A)):
col += 1
Ad = True
A = float(A)
A = A * pi / 180
if (is_num(H)):
col += 1
Hd = True
H = float(H)
if (H <= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T <= 0):
flag = False
if (is_num(L)):
col += 1
Ld = True
L = float(L)
if (L <= 0):
flag = False
if (is_num(Vdop)):
col += 1
Vdopd = True
Vdop = float(Vdop)
if (Vdop <= 0):
flag = False
if (flag):
if (V0d and Ad and hd and Vdopd):
if (A > -pi/2) and (A < pi/2):
try:
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
L = (V0*cos(A) + Vdop)*T
H = (V0**2*sin(A)**2 + 2*g*h)/(2*g)
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Hd and Vdopd): # 15
if (A > -pi/2) and (A < pi/2):
try:
h = H - (V0 ** 2 * sin(A) ** 2) / (2 * g)
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
L = (V0*cos(A) + Vdop)*T
vL.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Td and Vdopd): # 16
if (A > -pi/2) and (A < pi/2):
try:
H = ((T - (V0 * sin(A)) / g) ** 2 * g) / 2
h = H - (V0 ** 2 * sin(A) ** 2) / (2 * g)
L = (V0*cos(A) + Vdop)*T
vH.delete(0, END)
vh.delete(0, END)
vL.delete(0, END)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Ld and Vdopd): # 17
if (A > -pi/2) and (A < pi/2):
try:
T = L / (V0 * cos(A) + Vdop)
H = ((T - (V0 * sin(A)) / g) ** 2 * g) / 2
h = H - (V0 ** 2 * sin(A) ** 2) / (2 * g)
vh.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Hd and Vdopd): # 18
try:
A = asin((sqrt((H - h) * 2 * g)) / V0)
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
L = (V0*cos(A) + Vdop)*T
vA.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and hd and Vdopd): # 19
try:
A = asin((T**2 - 2*h) / (2*T*V0))
H = h + (((V0**2)*(sin(A)**2)) / (2*g))
L = (V0*cos(A) + Vdop)*T
vA.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and Hd and Vdopd): # 20
try:
A = asin(((T - sqrt((2 * H) / g)) * g) / Vdop)
h = H - ((V0**2*sin(A)**2) / (2*g))
L = (V0*cos(A) + Vdop)*T
vA.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vh.insert(0, round(h*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and Ld and Vdopd): # 21
try:
A = acos((L - Vdop * T) / (V0*T))
H = (((T - (V0*sin(A))/g))**2*g) / 2
h = H - (V0**2*sin(A)**2) / (2*g)
vA.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Ad and hd and Ld): # 22
if (A > -pi/2) and (A < pi/2):
try:
H = h + ((V0**2)*(sin(A)**2)) / (2*g)
T = (V0*sin(A) + sqrt(2*H*g)) / g
Vdop = L/T - V0*cos(A)
vVdop.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vVdop.insert(0, round(Vdop*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Hd and Ld): # 23
if (A > -pi/2) and (A < pi/2):
try:
h = H - (V0**2*sin(A)**2) / (2*g)
T = (V0*sin(A) + sqrt(2*H*g)) / g
Vdop = L/T - V0*cos(A)
vL.delete(0, END)
vh.delete(0, END)
vVdop.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except Exception as e:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Td and Ld): # 24
if (A > -pi/2) and (A < pi/2):
try:
H = (((T - (V0*sin(A))/g))**2*g) / 2
h = H - (V0**2*sin(A)**2) / (2*g)
Vdop = L/T - V0*cos(A)
vVdop.delete(0, END)
vH.delete(0, END)
vh.delete(0, END)
vVdop.insert(0, round(Vdop*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Hd and Ld): # 25
try:
A = asin((sqrt((H - h) * 2 * g)) / V0)
T = (V0*sin(A) + sqrt(2*H*g)) / g
Vdop = L/T - V0*cos(A)
vA.delete(0, END)
vT.delete(0, END)
vVdop.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vT.insert(0, round(T*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and hd and Td and Ld): # 26
try:
A = asin((T**2*g - 2*h) / (2*T*V0))
H = h + ((V0**2*sin(A)**2) / (2*g))
Vdop = L/T - V0*cos(A)
vA.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and Hd and Ld): # 27
try:
A = asin(((T - sqrt((2 * H) / g)) * g) / V0)
h = H - (V0**2*sin(A)**2) / (2*g)
Vdop = L/T - V0*cos(A)
vA.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except Exception as e:
print(e)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Ad and Hd and Vdopd): # 28
if (A > -pi/2) and (A < pi/2):
try:
V0 = sqrt(2*g*(H-h)) / sin(A)
T = (V0*sin(A) + sqrt(2*H*g)) / g
L = (V0*cos(A) + Vdop) * T
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vT.insert(0, round(T*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Td and Ad and hd and Vdopd): # 29
if (A > -pi/2) and (A < pi/2):
try:
V0 = (T**2*g - 2*h) / (2*T*sin(A))
H = h + ((V0**2*sin(A)**2) / (2*g))
L = (V0*cos(A) + Vdop) * T
vV0.delete(0, END)
vH.delete(0, END)
vL.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and Ad and hd and Vdopd): # 30
if (A > -pi/2) and (A < pi/2):
try:
V0 = (-L*sin(A)*Vdop - 2*h*Vdop*cos(A) + sqrt((L*Vdop*sin(A) + 2*h*Vdop*cos(A))**2 - (L*sin(2*A) + 2*h*cos(A)**2)*(2*h*Vdop**2 - L**2*g))) / (L*sin(2*A) + 2*h*cos(A)**2)
H = h + ((V0**2*sin(A)**2) / (2*g))
T = (V0*sin(A) + sqrt(2*H*g)) / g
vV0.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Td and Ad and Hd and Vdopd): # 31
if (A > -pi/2) and (A < pi/2):
try:
V0 = (T*g + sqrt(2*H*g)) / sin(A)
h = H - (V0**2*sin(A)**2) / (2*g)
L = (V0*cos(A) + Vdop)*T
vV0.delete(0, END)
vh.delete(0, END)
vL.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and Ad and Hd and Vdopd): # 32
if (A > -pi/2) and (A < pi/2):
try:
V0 = (-Vdop*sin(A) - sqrt(2*H/g)*g*cos(A) + sqrt((Vdop*sin(A) + sqrt(2*H/g)*g*cos(A))**2 - 2*sin(2*A)*(4*sqrt(2*H/g)*g - L*g))) / sin(2*A)
h = H - ((V0**2*sin(A)**2) / (2*g))
T = (V0*sin(A) + sqrt(2*H*g)) / g
vV0.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and Ad and Td and Vdopd): # 33
if (A > -pi/2) and (A < pi/2):
try:
V0 = (L/T - Vdop) / cos(A)
H = (g*((T - (V0*sin(A))/g))**2) / 2
h = H - (V0**2*sin(A)**2) / (2*g)
vV0.delete(0, END)
vH.delete(0, END)
vh.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and hd and Hd and Vdopd): # 34
try:
A = acos((g*L - sqrt(2*H*g)*Vdop)/(2*g*sqrt(H*(H-h))))
V0 = sqrt(2*g*(H-h)) / sin(A)
T = (V0*sin(A) + sqrt(2*H*g)) / g
vA.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vV0.insert(0, round(V0*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except Exception as e:
print(e)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Vdopd and hd and Td and Ld): # 35
try:
A = atan((g*T**2 - 2*h)/(2*(L - Vdop*T)))
V0 = (L/T -Vdop) / cos(A)
H = h + (V0**2 * sin(A)**2)
vA.delete(0, END)
vV0.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = min(370 / L, 190 / H)
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210 - h*k, 10 + 30 * cos(A), 210 - h*k - 30 * sin(A), arrow=LAST)
grafic.create_text(10 + 30 * cos(A) + 11, 210 - h*k - 30 * sin(A) + 5, text="Vo")
grafic.create_line(30, 210 - h*k, 10 + 20 * cos(A), 210 - h*k - 20 * sin(A))
grafic.create_line(10, 210 - h * k, 45, 210 - h * k, dash = True)
grafic.create_text(35, 210 - h*k - 10 * sin(A) , text="A")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(10, 220, text="0")
grafic.create_text(17+len(str(round(H * 100)/100))*5, 200 - (H * k), text=str(round(H * 100)/100))
grafic.create_line(5, 210 - (H * k), 390, 210 - (H * k), dash=True)
grafic.create_text(10 + L * k, 220, text=str(round(L * 100)/100))
grafic.create_line(10 + L * k, 10, 10 + L * k, 215, dash=True)
grafic.create_text(10 + (V0**2*sin(A)*cos(A)/g)*k, 220, text=str(round(V0**2*sin(A)*cos(A)/g * 100)/100))
t1 = V0*sin(A)/g
grafic.create_line(10 + t1*k * (V0*cos(A) + Vdop), 10, 10 + t1*k * (V0*cos(A) + Vdop), 215, dash=True)
global i
global telo
global xy
xy = Label(text="x=0.000 , y=0.000", font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x= 400, y=320)
XY.append(xy)
telo = grafic.create_oval(10 - r, 210-h*k - r, 10 + r, 210-h*k + r, fill="#c00300")
i=0
global telo1
telo1 = grafic.create_rectangle(10-8, 210-3-h*k, 10+8, 210+3-h*k, fill="#00003d")
root.after(10, draw_angle_by_h_move)
else:
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def del_by_angle_h_move():
vA.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vVdop.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def draw_angle_by_h_move():
global i
global telo, telo1
global xy, XY
if (stroim):
grafic.delete(telo)
grafic.delete(telo1)
xy.destroy()
XY=[]
x = L / 2000 * i
t = x/(V0*cos(A) + Vdop)
y = h + V0*sin(A)*t - g*t**2/2
x1 = L / 2000 * (i + 1)
t1 = x1 / (V0 * cos(A) + Vdop)
y1 = h + V0 * sin(A) * t1 - g * t1 ** 2 / 2
telo = grafic.create_oval(((x1) * k + 10) - r, 220 - ((y1) * k + 10) - r, ((x1) * k + 10) + r, 220 - ((y1) * k + 10) + r, fill="#c00300")
telo1 = grafic.create_rectangle(10 - 15 + t1*(Vdop), 210 - 3 - h * k, 10 + 15+ t1*(Vdop), 210 + 3 - h * k, fill="#00003d")
grafic.create_line((x) * k + 10, 220 - ((y) * k + 10), ((x1) * k + 10), 220 - ((y1) * k + 10), fill="#c00300")
i+=1
xy = Label(text="x="+str(col_znak(round(x*1000)/1000, 3))+", y="+str(col_znak(round(y*1000)/1000, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
global vvod
vvod.append(xy)
if (i<=2000):
root.after(1, draw_angle_by_h_move)
def file_by_angle_h_move():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fh = st
if (is_num(fh)):
n+=1
if (colvo==2):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==3):
fA = st
if (is_num(fA)):
n+=1
if (colvo==4):
fVdop = st
if (is_num(fVdop)):
n+=1
st = file.readline()
if (colvo==4) and (n==4):
vh.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vVdop.delete(0, END)
vA.delete(0, END)
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fA)):
vA.insert(0, str(fA))
if (is_num(fVdop)):
vVdop.insert(0, str(fVdop))
vvod_by_angle_h_move()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_by_angle_h_move():
vvod_by_angle_h_move(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vA.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок под углом к горизонту с учетом ветра \n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "Vплатформы (м/с) = " + str(vVdop.get()) + '\n'
file.write(st)
st = "A (градусов) = " + str(vA.get()) + '\n'
file.write(st)
st = "H (м) = " + str(vH.get()) + '\n'
file.write(st)
st = "L (м) = " + str(vL.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def by_angle_h_move():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые четыре значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=7, y=70)
vvod.append(l1)
l2 = Label(text="Бросок под углом к горизонту с движущегося тела на высоте", font="Cricket 18")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=7, y=10)
vvod.append(l2)
delete_main()
global vh
vh = Entry(width=13)
vh.place(x=172, y=128)
vvod.append(vh)
bh = Label(text="h (м) =", font="Cricket 10")
bh.place(x=84, y=128)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vV0
vV0= Entry(width=13)
vV0.place(x=172, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo (м/с) =", font="Cricket 10")
bV0.place(x=76, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vA
vA= Entry(width=13)
vA.place(x=172, y=175)
vvod.append(vA)
bA = Label(text="Угол (В градусах) = ", font="Cricket 10")
bA.place(x=13, y=175)
bA.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bA)
global vVdop
vVdop = Entry(width=13)
vVdop.place(x=172, y=198)
vvod.append(vVdop)
bVdop = Label(text="Vdop (м/с) = ", font="Cricket 10")
bVdop.place(x=54 , y=198)
bVdop.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bVdop)
global vH
vH = Entry(width=13)
vH.place(x=172, y=221)
vvod.append(vH)
bH = Label(text="Hmax (м) = ", font="Cricket 10")
bH.place(x=73, y=221)
bH.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bH)
global vT
vT = Entry(width=13)
vT.place(x=172, y=243)
vvod.append(vT)
bT = Label(text="Tполёта (с) = ", font="Cricket 10")
bT.place(x=71, y=243)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vL
vL = Entry(width=13)
vL.place(x=172, y=266)
vvod.append(vL)
bL = Label(text="Lполёта (м) = ", font="Cricket 10")
bL.place(x=70, y=266)
bL.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bL)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=303)
vvod.append(bvvesti)
bvvesti.config(command=vvod_by_angle_h_move)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=303)
vvod.append(bdel)
bdel.config(command=del_by_angle_h_move)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen, 'Считать значения из файла \n(введите 4 значения\n в следующем порядке: h, V0, A, \nVплатформы в файл "input.txt"\n в столбик)' )
bopen.place(x=30, y=420)
vvod.append(bopen)
bopen.config(command=file_by_angle_h_move)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave,'Сохранить значения\n в файл')
bsave.place(x=350, y=420)
vvod.append(bsave)
bsave.config(command=save_by_angle_h_move)
l3 = Label(text="ИЛИ", font="Cricket 12", height=1)
l3.config(bd=12, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=360)
vvod.append(l3)
# Под углом с высоты под углом к горизонту с учетом ветра
def vvod_by_angle_h_wind(x=True):
grafic.delete("all")
global V0 # начальная скорость
global Vdop # скорость ветра
global A # angle
global H # макс. высота
global T # время
global L # дальность
global h # начальная высота
global XY
for a in XY:
a.destroy()
global V0, h, A, B, T, L, Vdop
h = vh.get()
V0 = vV0.get()
A = vA.get()
H = vH.get()
T = vT.get()
L = vL.get()
Vdop = vVdop.get()
col=0
V0d = False
Ad = False
Hd = False
Td = False
Ld = False
hd = False
Vdopd = False
flag = True
global stroim
stroim = x
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 <= 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h <= 0):
flag = False
if (is_num(A)):
col += 1
Ad = True
A = float(A)
A = A * pi / 180
if (is_num(H)):
col += 1
Hd = True
H = float(H)
if (H <= 0):
flag = False
if (is_num(T)):
col += 1
Td = True
T = float(T)
if (T <= 0):
flag = False
if (is_num(L)):
col += 1
Ld = True
L = float(L)
if (L <= 0):
flag = False
if (is_num(Vdop)):
col += 1
Vdopd = True
Vdop = float(Vdop)
if (Vdop <= 0):
flag = False
if (flag):
if (V0d and Ad and hd and Vdopd):
if (A > -pi/2) and (A < pi/2):
try:
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
L = (V0*cos(A) + Vdop)*T
H = (V0**2*sin(A)**2 + 2*g*h)/(2*g)
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Hd and Vdopd): # 15
if (A > -pi/2) and (A < pi/2):
try:
h = H - (V0 ** 2 * sin(A) ** 2) / (2 * g)
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
L = (V0*cos(A) + Vdop)*T
vL.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Td and Vdopd): # 16
if (A > -pi/2) and (A < pi/2):
try:
H = ((T - (V0 * sin(A)) / g) ** 2 * g) / 2
h = H - (V0 ** 2 * sin(A) ** 2) / (2 * g)
L = (V0*cos(A) + Vdop)*T
vH.delete(0, END)
vh.delete(0, END)
vL.delete(0, END)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Ld and Vdopd): # 17
if (A > -pi/2) and (A < pi/2):
try:
T = L / (V0 * cos(A) + Vdop)
H = ((T - (V0 * sin(A)) / g) ** 2 * g) / 2
h = H - (V0 ** 2 * sin(A) ** 2) / (2 * g)
vh.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Hd and Vdopd): # 18
try:
A = asin((sqrt((H - h) * 2 * g)) / V0)
T = (V0*sin(A)+sqrt(V0**2*sin(A)**2+2*g*h)) / g
L = (V0*cos(A) + Vdop)*T
vA.delete(0, END)
vL.delete(0, END)
vT.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and hd and Vdopd): # 19
try:
A = asin((T**2 - 2*h) / (2*T*V0))
H = h + (((V0**2)*(sin(A)**2)) / (2*g))
L = (V0*cos(A) + Vdop)*T
vA.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and Hd and Vdopd): # 20
try:
A = asin(((T - sqrt((2 * H) / g)) * g) / Vdop)
h = H - ((V0**2*sin(A)**2) / (2*g))
L = (V0*cos(A) + Vdop)*T
vA.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vL.insert(0, round(L*1000)/1000)
vh.insert(0, round(h*1000)/1000)
except Exception as e:
print(e)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and Ld and Vdopd): # 21
try:
A = acos((L - Vdop * T) / (V0*T))
H = (((T - (V0*sin(A))/g))**2*g) / 2
h = H - (V0**2*sin(A)**2) / (2*g)
vA.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Ad and hd and Ld): # 22
if (A > -pi/2) and (A < pi/2):
try:
H = h + ((V0**2)*(sin(A)**2)) / (2*g)
T = (V0*sin(A) + sqrt(2*H*g)) / g
Vdop = L/T - V0*cos(A)
vVdop.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vVdop.insert(0, round(Vdop*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Hd and Ld): # 23
if (A > -pi/2) and (A < pi/2):
try:
h = H - (V0**2*sin(A)**2) / (2*g)
T = (V0*sin(A) + sqrt(2*H*g)) / g
Vdop = L/T - V0*cos(A)
vL.delete(0, END)
vh.delete(0, END)
vVdop.delete(0, END)
vL.insert(0, round(L*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except Exception as e:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and Ad and Td and Ld): # 24
if (A > -pi/2) and (A < pi/2):
try:
H = (((T - (V0*sin(A))/g))**2*g) / 2
h = H - (V0**2*sin(A)**2) / (2*g)
Vdop = L/T - V0*cos(A)
vVdop.delete(0, END)
vH.delete(0, END)
vh.delete(0, END)
vVdop.insert(0, round(Vdop*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (V0d and hd and Hd and Ld): # 25
try:
A = asin((sqrt((H - h) * 2 * g)) / V0)
T = (V0*sin(A) + sqrt(2*H*g)) / g
Vdop = L/T - V0*cos(A)
vA.delete(0, END)
vT.delete(0, END)
vVdop.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vT.insert(0, round(T*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and hd and Td and Ld): # 26
try:
A = asin((T**2*g - 2*h) / (2*T*V0))
H = h + ((V0**2*sin(A)**2) / (2*g))
Vdop = L/T - V0*cos(A)
vA.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (V0d and Td and Hd and Ld): # 27
try:
A = asin(((T - sqrt((2 * H) / g)) * g) / V0)
h = H - (V0**2*sin(A)**2) / (2*g)
Vdop = L/T - V0*cos(A)
vA.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vVdop.insert(0, round(Vdop*1000)/1000)
except Exception as e:
print(e)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (hd and Ad and Hd and Vdopd): # 28
if (A > -pi/2) and (A < pi/2):
try:
V0 = sqrt(2*g*(H-h)) / sin(A)
T = (V0*sin(A) + sqrt(2*H*g)) / g
L = (V0*cos(A) + Vdop) * T
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vT.insert(0, round(T*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Td and Ad and hd and Vdopd): # 29
if (A > -pi/2) and (A < pi/2):
try:
V0 = (T**2*g - 2*h) / (2*T*sin(A))
H = h + ((V0**2*sin(A)**2) / (2*g))
L = (V0*cos(A) + Vdop) * T
vV0.delete(0, END)
vH.delete(0, END)
vL.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and Ad and hd and Vdopd): # 30
if (A > -pi/2) and (A < pi/2):
try:
V0 = (-L*sin(A)*Vdop - 2*h*Vdop*cos(A) + sqrt((L*Vdop*sin(A) + 2*h*Vdop*cos(A))**2 - (L*sin(2*A) + 2*h*cos(A)**2)*(2*h*Vdop**2 - L**2*g))) / (L*sin(2*A) + 2*h*cos(A)**2)
H = h + ((V0**2*sin(A)**2) / (2*g))
T = (V0*sin(A) + sqrt(2*H*g)) / g
vV0.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Td and Ad and Hd and Vdopd): # 31
if (A > -pi/2) and (A < pi/2):
try:
V0 = (T*g + sqrt(2*H*g)) / sin(A)
h = H - (V0**2*sin(A)**2) / (2*g)
L = (V0*cos(A) + Vdop)*T
vV0.delete(0, END)
vh.delete(0, END)
vL.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vL.insert(0, round(L*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and Ad and Hd and Vdopd): # 32
if (A > -pi/2) and (A < pi/2):
try:
V0 = (-Vdop*sin(A) - sqrt(2*H/g)*g*cos(A) + sqrt((Vdop*sin(A) + sqrt(2*H/g)*g*cos(A))**2 - 2*sin(2*A)*(4*sqrt(2*H/g)*g - L*g))) / sin(2*A)
h = H - ((V0**2*sin(A)**2) / (2*g))
T = (V0*sin(A) + sqrt(2*H*g)) / g
vV0.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vh.insert(0, round(h*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and Ad and Td and Vdopd): # 33
if (A > -pi/2) and (A < pi/2):
try:
V0 = (L/T - Vdop) / cos(A)
H = (g*((T - (V0*sin(A))/g))**2) / 2
h = H - (V0**2*sin(A)**2) / (2*g)
vV0.delete(0, END)
vH.delete(0, END)
vh.delete(0, END)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
vh.insert(0, round(h*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
stroim = False
mb.showerror("Неверные данные", "Расчёты невозможны")
elif (Ld and hd and Hd and Vdopd): # 34
try:
A = acos((g*L - sqrt(2*H*g)*Vdop)/(2*g*sqrt(H*(H-h))))
V0 = sqrt(2*g*(H-h)) / sin(A)
T = (V0*sin(A) + sqrt(2*H*g)) / g
vA.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vV0.insert(0, round(V0*1000)/1000)
vT.insert(0, round(T*1000)/1000)
except Exception as e:
print(e)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
elif (Vdopd and hd and Td and Ld): # 35
try:
A = atan((g*T**2 - 2*h)/(2*(L - Vdop*T)))
V0 = (L/T -Vdop) / cos(A)
H = h + (V0**2 * sin(A)**2)
vA.delete(0, END)
vV0.delete(0, END)
vH.delete(0, END)
vA.insert(0, round(A*1000)/1000)
vV0.insert(0, round(V0*1000)/1000)
vH.insert(0, round(H*1000)/1000)
except:
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
else:
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = min(370 / L, 190 / H)
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210 - h*k, 10 + 30 * cos(A), 210 - h*k - 30 * sin(A), arrow=LAST)
grafic.create_text(10 + 30 * cos(A) + 11, 210 - h*k - 30 * sin(A) + 5, text="Vo")
grafic.create_line(30, 210 - h*k, 10 + 20 * cos(A), 210 - h*k - 20 * sin(A))
grafic.create_line(10, 210 - h * k, 45, 210 - h * k, dash = True)
grafic.create_text(35, 210 - h*k - 10 * sin(A) , text="A")
grafic.create_line(370, 10, 370, 40, arrow=LAST)
grafic.create_text(361, 33, text="g")
grafic.create_text(10, 220, text="0")
grafic.create_text(17+len(str(round(H * 100)/100))*5, 200 - (H * k), text=str(round(H * 100)/100))
grafic.create_line(5, 210 - (H * k), 390, 210 - (H * k), dash=True)
grafic.create_text(10 + L * k, 220, text=str(round(L * 100)/100))
grafic.create_line(10 + L * k, 10, 10 + L * k, 215, dash=True)
grafic.create_text(10 + (V0**2*sin(A)*cos(A)/g)*k, 220, text=str(round(V0**2*sin(A)*cos(A)/g * 100)/100))
t1 = V0*sin(A)/g
grafic.create_line(10 + t1*k * (V0*cos(A) + Vdop), 10, 10 + t1*k * (V0*cos(A) + Vdop), 215, dash=True)
global i
global telo
global xy
xy = Label(text="x=0.000 , y=0.000", font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
telo = grafic.create_oval(10 - r, 210-h*k - r, 10 + r, 210-h*k + r, fill="#c00300")
i=0
global telo1
telo1 = grafic.create_line(10-8, 210 - h * k, 10 + 8, 210 - h * k, arrow=LAST)
root.after(10, draw_angle_by_h_wind)
else:
vV0.delete(0, END)
vA.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vVdop.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def del_by_angle_h_wind():
vA.delete(0, END)
vh.delete(0, END)
vH.delete(0, END)
vV0.delete(0, END)
vT.delete(0, END)
vL.delete(0, END)
vVdop.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def draw_angle_by_h_wind():
global i
global telo, telo1
global xy, XY
if (stroim):
grafic.delete(telo)
grafic.delete(telo1)
xy.destroy()
XY=[]
x = L / 2000 * i
t = x/(V0*cos(A) + Vdop)
y = h + V0*sin(A)*t - g*t**2/2
x1 = L / 2000 * (i + 1)
t1 = x1 / (V0 * cos(A) + Vdop)
y1 = h + V0 * sin(A) * t1 - g * t1 ** 2 / 2
telo = grafic.create_oval(((x1) * k + 10) - r, 220 - ((y1) * k + 10) - r, ((x1) * k + 10) + r, 220 - ((y1) * k + 10) + r, fill="#c00300")
telo1 = grafic.create_line(10 - 8 + t1*(Vdop), 210 - h * k, 10 + 8 + t1*(Vdop), 210 - h * k, arrow=LAST)
grafic.create_line((x) * k + 10, 220 - ((y) * k + 10), ((x1) * k + 10), 220 - ((y1) * k + 10), fill="#c00300")
i+=1
xy = Label(text="x="+str(col_znak(round(x*1000)/1000, 3))+", y="+str(col_znak(round(y*1000)/1000, 3)), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
global vvod
vvod.append(xy)
if (i<=2000):
root.after(1, draw_angle_by_h_wind)
def file_by_angle_h_wind():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fh = st
if (is_num(fh)):
n+=1
if (colvo==2):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==3):
fA = st
if (is_num(fA)):
n+=1
if (colvo==4):
fVdop = st
if (is_num(fVdop)):
n+=1
st = file.readline()
if (colvo==4) and (n==4):
vh.delete(0, END)
vL.delete(0, END)
vH.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vVdop.delete(0, END)
vA.delete(0, END)
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fA)):
vA.insert(0, str(fA))
if (is_num(fVdop)):
vVdop.insert(0, str(fVdop))
vvod_by_angle_h_wind()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_by_angle_h_wind():
vvod_by_angle_zero(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vA.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок под углом к горизонту с движущейся платформы \n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "Vплатформы (м/с) = " + str(vVdop.get()) + '\n'
file.write(st)
st = "A (градусов) = " + str(vA.get()) + '\n'
file.write(st)
st = "H (м) = " + str(vH.get()) + '\n'
file.write(st)
st = "L (м) = " + str(vL.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def by_angle_h_wind():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите любые четыре значения", font="Cricket 16")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=7, y=70)
vvod.append(l1)
l2 = Label(text="Бросок под углом к горизонту с высоты с учетом ветра", font="Cricket 23")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=7, y=10)
vvod.append(l2)
delete_main()
global vh
vh = Entry(width=13)
vh.place(x=172, y=128)
vvod.append(vh)
bh = Label(text="h (м) =", font="Cricket 10")
bh.place(x=84, y=128)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vV0
vV0= Entry(width=13)
vV0.place(x=172, y=152)
vvod.append(vV0)
bV0 = Label(text="Vo (м/с) =", font="Cricket 10")
bV0.place(x=76, y=152)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vA
vA= Entry(width=13)
vA.place(x=172, y=176)
vvod.append(vA)
bA = Label(text="Угол (В градусах) = ", font="Cricket 10")
bA.place(x=13, y=176)
bA.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bA)
global vVdop
vVdop = Entry(width=13)
vVdop.place(x=172, y=199)
vvod.append(vVdop)
bVdop = Label(text="Vdop (м/с) = ", font="Cricket 10")
bVdop.place(x=54 , y=199)
bVdop.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bVdop)
global vH
vH = Entry(width=13)
vH.place(x=172, y=224)
vvod.append(vH)
bH = Label(text="Hmax (м) = ", font="Cricket 10")
bH.place(x=73, y=224)
bH.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bH)
global vT
vT = Entry(width=13)
vT.place(x=172, y=248)
vvod.append(vT)
bT = Label(text="Tполёта (с) = ", font="Cricket 10")
bT.place(x=70, y=248)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vL
vL = Entry(width=13)
vL.place(x=172, y=271)
vvod.append(vL)
bL = Label(text="Lполёта (м) = ", font="Cricket 10")
bL.place(x=68, y=271)
bL.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bL)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=303)
vvod.append(bvvesti)
bvvesti.config(command=vvod_by_angle_h_wind)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=303)
vvod.append(bdel)
bdel.config(command=del_by_angle_h_wind)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen, 'Считать значения из файла \n(введите 4 значения\n в следующем порядке: h, V0, A, \nVплатформы в файл "input.txt"\n в столбик)' )
bopen.place(x=30, y=420)
vvod.append(bopen)
bopen.config(command=file_by_angle_h_wind)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave,'Сохранить значения\n в файл')
bsave.place(x=350, y=420)
vvod.append(bsave)
bsave.config(command=save_by_angle_h_wind)
l3 = Label(text="ИЛИ", font="Cricket 12", height=1)
l3.config(bd=12, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=360)
vvod.append(l3)
# Под углом к горизонту с земли к наклонной плоскости
def vvod_dop(x=True):
grafic.delete("all")
global XY
for a in XY:
a.destroy()
global V0, h, A, B, T, L
V0 = vV0.get()
h = vh.get()
A = vA.get()
B = vB.get()
col=0
V0d = False
hd = False
Td = False
Vkd = False
global stroim
flag = True
stroim = x
if (is_num(V0)):
col += 1
V0d = True
V0 = float(V0)
if (V0 < 0):
flag = False
if (is_num(h)):
col += 1
hd = True
h = float(h)
if (h < 0):
flag = False
if (is_num(A)):
col += 1
Ad = True
A = float(A)
if (A<=-90)or(A>=90):
flag = False
A = A * pi / 180
if (is_num(B)):
col += 1
Bd = True
B = float(B)
if (B <= 0)or(B>=90):
flag = False
B = B * pi / 180
if (flag):
if (V0d and hd and Ad and Bd):
D = (tan(A)-tan(B))**2 + 2*g*h/(V0**2*cos(A)**2)
L = ((tan(A)-tan(B) + sqrt(D)))/(g/(V0**2 * cos(A)**2))
T = L/(V0*cos(A))
vLx.delete(0, END)
vLpl.delete(0, END)
vT.delete(0, END)
vLx.insert(0, round(L * 1000) / 1000)
vT.insert(0, round(T * 1000) / 1000)
vLpl.insert(0, round(L/cos(B) * 1000) / 1000)
else:
vV0.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
if (stroim):
global k
k = min(190 / (h + V0**2*sin(A)**2/(2*g)), 380/L)
H=h
grafic.create_line(10, 10, 10, 210, arrow=FIRST)
grafic.create_line(10, 210, 395, 210, arrow=LAST)
grafic.create_text(15, 6, text="y(м)")
grafic.create_text(385, 200, text="x(м)")
grafic.create_line(10, 210-h*k, 10 , 210 - 30-h*k, arrow=LAST)
grafic.create_text(19, 210 - 30 - h*k, text="Vo")
grafic.create_line(390, 10, 390, 40, arrow=LAST)
grafic.create_polygon([10, 210], [370, 210-370*tan(B)], [370, 210], fill='#048B22', outline='#044412')
grafic.create_text(376, 33, text="g")
grafic.create_text(24, 210-h*k, text=str(round(h*1000)/1000))
grafic.create_text(10, 220, text="0")
grafic.create_text(17 + len(str(round(H * 100) / 100)) * 5, 200 - (H * k), text=str(round(H * 100) / 100))
grafic.create_line(5, 210 - (h * k), 390, 210 - (h * k), dash=True)
global i
global telo
telo = grafic.create_oval(10 - r, 210-h*k - r, 10 + r, 210-h*k + r, fill="#c00300")
i = 0
global xy
xy = Label(text="x=0.000 , y="+str(h), font="Cricket 12")
xy.config(bd=20, bg=label_bg_color, fg=label_text_color)
xy.place(x=graph_x+120, y=graph_y+250)
XY.append(xy)
root.after(1, draw_angle_by_h)
else:
vV0.delete(0, END)
vh.delete(0, END)
vT.delete(0, END)
vVk.delete(0, END)
mb.showerror("Неверные данные", "Расчёты невозможны")
stroim = False
def del_dop():
vh.delete(0, END)
vT.delete(0, END)
vV0.delete(0, END)
vA.delete(0, END)
vB.delete(0, END)
vLx.delete(0, END)
vLpl.delete(0, END)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
def file_dop():
colvo = 0
n = 0
f_name = fd.askopenfilename()
with open(f_name, "r") as file:
st = file.readline()
while st:
colvo+=1
st=st.rstrip('\n')
if (colvo==1):
fh = st
if (is_num(fh)):
n+=1
if (colvo==2):
fV0 = st
if (is_num(fV0)):
n+=1
if (colvo==3):
fA = st
if (is_num(fA)):
n+=1
if (colvo==4):
fB = st
if (is_num(fB)):
n+=1
st = file.readline()
if (colvo==4) and (n==4):
vh.delete(0, END)
vB.delete(0, END)
vV0.delete(0, END)
vA.delete(0, END)
if (is_num(fh)):
vh.insert(0, str(fh))
if (is_num(fV0)):
vV0.insert(0, str(fV0))
if (is_num(fA)):
vA.insert(0, str(fA))
if (is_num(fB)):
vB.insert(0, str(fB))
vvod_dop()
else:
mb.showerror("Ошибка", "Неверный формат входных данных")
def save_dop():
vvod_dop(False)
global stroim, XY
stroim = False
for a in XY:
a.destroy()
grafic.delete("all")
if (is_num(vV0.get()) and is_num(vA.get())):
f_name = fd.asksaveasfilename(filetypes=(("TXT files", "*.txt"),))
with open(f_name, "w") as file:
st = 'Бросок под углом А к горизонту с высоты h на плоскость под углом B \n'
file.write(st)
st = "h (м) = " + str(vh.get()) + '\n'
file.write(st)
st = "Vo (м/с) = " + str(vV0.get()) + '\n'
file.write(st)
st = "A (градусов) = " + str(vA.get()) + '\n'
file.write(st)
st = "B (градусов) = " + str(vB.get()) + '\n'
file.write(st)
st = "T (с) = " + str(vT.get()) + '\n'
file.write(st)
st = "L по оси ох (м) = " + str(vLx.get()) + '\n'
file.write(st)
st = "L по плоскости (м) = " + str(vLpl.get()) + '\n'
file.write(st)
mb.showinfo(
"Успешно",
"Данные сохранены")
def dop():
global vvod
vvod = []
grafic.place(x=graph_x, y=graph_y)
l1 = Label(text="Введите значения A, B, Vo, h", font="Cricket 14")
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
l1.place(x=20, y=55)
vvod.append(l1)
l2 = Label(text="Бросок под углом А к горизонту с высоты на наклонную плоскость под углом B (0°; 90°)", font="Cricket 14")
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
l2.place(x=20, y=10)
vvod.append(l2)
delete_main()
global vh
vh = Entry(width=13)
vh.place(x=163, y=116)
vvod.append(vh)
bh = Label(text="h (м) =", font="Cricket 10")
bh.place(x=82, y=116)
bh.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bh)
global vV0
vV0= Entry(width=13)
vV0.place(x=163, y=138)
vvod.append(vV0)
bV0 = Label(text="Vo (м/c) =", font="Cricket 10")
bV0.place(x=70, y=138)
bV0.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bV0)
global vA
vA= Entry(width=13)
vA.place(x=163, y=160)
vvod.append(vA)
bA = Label(text="A (В градусах) = ", font="Cricket 10")
bA.place(x=29, y=160)
bA.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bA)
global vB
vB = Entry(width=13)
vB.place(x=163, y=182)
vvod.append(vB)
bB = Label(text="B (В градусах) = ", font="Cricket 10")
bB.place(x=29, y=182)
bB.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bB)
global vT
vT = Entry(width=13)
vT.place(x=163, y=204)
vvod.append(vT)
bT = Label(text="T (c) = ", font="Cricket 10")
bT.place(x=92, y=204)
bT.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bT)
global vLx
vLx = Entry(width=13)
vLx.place(x=163, y=226)
vvod.append(vLx)
bLx = Label(text="Lx (м) = ", font="Cricket 10")
bLx.place(x=83, y=226)
bLx.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bLx)
global vLpl
vLpl = Entry(width=13)
vLpl.place(x=163, y=248)
vvod.append(vLpl)
bLpl = Label(text="Lна плоскости (м) = ", font="Cricket 10")
bLpl.place(x=12, y=248)
bLpl.config(bg=label_bg_color, fg=label_text_color)
vvod.append(bLpl)
bvvesti = Button(root, height=2, width=17)
change_button(bvvesti, "Ввести значения")
bvvesti.place(x=20, y=300)
vvod.append(bvvesti)
bvvesti.config(command=vvod_dop)
bdel = Button(root, height=2, width=10)
change_button(bdel, "Удалить\nзначения")
bdel.place(x=163, y=300)
vvod.append(bdel)
bdel.config(command=del_dop)
bopen = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bopen, 'Считать значения из файла \n(введите 4 значения \n в следующем порядке: h, V0, A, B \n в файл "input.txt" в столбик)' )
bopen.place(x=30, y=425)
vvod.append(bopen)
bopen.config(command=file_dop)
bsave = Button(root, height=5, width=30, font=('Cricket', 10))
change_button(bsave, 'Сохранить значения\n в файл')
bsave.place(x=350, y=425)
vvod.append(bsave)
bsave.config(command=save_dop)
l3 = Label(text="ИЛИ", font="Cricket 12")
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
l3.place(x=90, y=350)
vvod.append(l3)
# теория
def delete_th():
c.delete("all")
for a in vvod:
a.destroy()
def th_by_angle_zero():
delete_th()
global BB
l0 = Label(text="Бросок тела под углом к горизонту с земли", font="Cricket 18")
l0.place(x=75, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo*sinA - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = Vo*cosA - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = Vo*sinA*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo + Vo*cosA*t - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = Vo^2*(sinA)^2/(2*g) - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=280)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = Vo^2*sin(2A)/g - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = 2*Vo*sinA/g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного под углом к горизонту - парабола", font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_vert_v_zero():
delete_th()
global BB
l0 = Label(text="Бросок тела вертикально вверх с земли", font="Cricket 18")
l0.place(x=75, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = 0 - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = Vo*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = Vo^2*/(2*g) - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=275)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = 0 - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = 2*Vo/g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного вертикально вверх - прямая линия", font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_hor():
delete_th()
global BB
l0 = Label(text="Бросок тела горизонтально с высоты h", font="Cricket 18")
l0.place(x=75, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = Vo - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo + Vo*t - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = h - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=280)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = Vo*sqrt(2h/g) - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = sqrt(2h/g) - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного горизонтально с высоты \nh - парабола", font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_angle_h():
delete_th()
global BB
l0 = Label(text="Бросок тела под углом к горизонту с высоты h", font="Cricket 18")
l0.place(x=75, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo*sinA - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = Vo*cosA - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h + Vo*sinA*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo + Vo*cosA*t - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = (V0^2 * (sin(A))^2 + 2 * g * h) / (2 * g) - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=280)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = (V0^2*sin(A)*cos(A)+V0*cos(A)*sqrt(V0^2*(sin(A))^2+2*g*h))/g - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = (V0 * sin(A) + sqrt(V0^2 * (sin(A))^2 + 2 * g * h)) / g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного под углом к горизонту с высоты - \nпарабола", font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_vert_vniz():
delete_th()
global BB
l0 = Label(text="Бросок тела вертикально вниз с высоты h", font="Cricket 18")
l0.place(x=75, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = -Vo - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = 0 - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h - Vo*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = h - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=275)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = 0 - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = (-V0+sqrt(V0^2+2*g*h))/g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного вертикально вниз с высоты \nh - прямая линия", font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_vert_vverh():
delete_th()
global BB
l0 = Label(text="Бросок тела вертикально вверх с высоты h", font="Cricket 18")
l0.place(x=75, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = 0 - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h + Vo*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = h + V0^2/(2*g) - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=275)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = 0 - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = (V0+sqrt(V0^2+2*g*h))/g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного вертикально вверх с высоты \nh - прямая линия", font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_dop():
delete_th()
global BB
l0 = Label(text="Бросок тела под углом к горизонту с высоты h а наклонную плоскость\n под углом B", font="Cricket 15")
l0.place(x=5, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo*sinA - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = Vo*cosA - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h + Vo*sinA*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo + Vo*cosA*t - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l6 = Label(text="Lx = ((tan(A)-tan(B)+sqrt(D)))/(g/(V0^2*cos(A)^2)) - дальность полёта по оси ох",
font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = L/(V0*cos(A)) - время полёта",
font="Cricket 14")
l7.place(x=10, y=270)
l7.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l5 = Label(text="Lпл. = (((tan(A)-tan(B)+sqrt(D)))/(g/(V0^2*cos(A)^2)))/cos(A) - дальность полёта по плоскости",
font="Cricket 14")
l5.place(x=10, y=370)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l8 = Label(text="Траектория движения тела, брошенного под углом к горизонту с высоты - \nпарабола",
font="Cricket 14")
l8.place(x=10, y=420)
l8.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_angle_h_wind():
delete_th()
global BB
l0 = Label(text="Бросок тела под углом к горизонту с высоты h с учетом ветра", font="Cricket 18")
l0.place(x=10, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo*sinA - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = Vo*cosA + Vdop - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h + Vo*sinA*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo + (Vo*cosA+Vdop)*t - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = (V0^2 * (sin(A))^2 + 2 * g * h) / (2 * g) - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=280)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = (V0*sin(A)+sqrt(V0^2*(sin(A))^2+2*g*h))/g * (Vo*cosA+Vdop) - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = (V0 * sin(A) + sqrt(V0^2 * (sin(A))^2 + 2 * g * h)) / g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=14, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного под углом к горизонту с \n высоты с учемом ветра - парабола", font="Cricket 14")
l8.place(x=10, y=410)
l8.config(bd=14, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def th_angle_h_move():
delete_th()
global BB
l0 = Label(text="Бросок тела под углом к горизонту с движущейся платформы на высоте h", font="Cricket 16")
l0.place(x=10, y=10)
l0.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l0)
l1 = Label(text="Vy(t) = Vo*sinA - gt - скорость по оси оу через t секунд полёта", font="Cricket 14")
l1.place(x=10, y=80)
l1.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l1)
l2 = Label(text="Vx(t) = Vo*cosA + Vdop - скорость по оси ох через t секунд полёта", font="Cricket 14")
l2.place(x=10, y=130)
l2.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l2)
l3 = Label(text="y(t) = h + Vo*sinA*t - g*t^2/2 - координата по оси оу через t секунд полёта", font="Cricket 14")
l3.place(x=10, y=180)
l3.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l3)
l4 = Label(text="x(t) = xo + (Vo*cosA+Vdop)*t - координата по оси ох через t секунд полёта", font="Cricket 14")
l4.place(x=10, y=230)
l4.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l4)
l5 = Label(text="Hmax = (V0^2 * (sin(A))^2 + 2 * g * h) / (2 * g) - максимальная высота полёта", font="Cricket 14")
l5.place(x=10, y=280)
l5.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l5)
l6 = Label(text="Lmax = (V0*sin(A)+sqrt(V0^2*(sin(A))^2+2*g*h))/g * (Vo*cosA+Vdop) - дальность полёта", font="Cricket 14")
l6.place(x=10, y=320)
l6.config(bd=20, bg=label_bg_color, fg=label_text_color)
BB.append(l6)
l7 = Label(text="Tполёта = (V0 * sin(A) + sqrt(V0^2 * (sin(A))^2 + 2 * g * h)) / g - время полёта", font="Cricket 14")
l7.place(x=10, y=370)
l7.config(bd=14, bg=label_bg_color, fg=label_text_color)
BB.append(l7)
l8 = Label(text="Траектория движения тела, брошенного под углом к горизонту с \nплатформы - парабола", font="Cricket 14")
l8.place(x=10, y=410)
l8.config(bd=14, bg=label_bg_color, fg=label_text_color)
BB.append(l8)
def theory():
delete_main()
global vvod
vvod = []
for a in vvod:
a.destroy()
lth = Label(text="Теория", font="Cricket 25")
lth.config(bd=20, bg=label_bg_color, fg=label_text_color)
lth.place(x=345, y=21)
vvod.append(lth)
lx = Label(text="Выберите раздел,\n по которому хотите \nузнать больше:", font="Cricket 14")
lx.config(bd=20, bg=label_bg_color, fg=label_text_color)
#lx.place(x=33, y=111)
vvod.append(lx)
b1 = Button(root, width=21, height=4, font=('Cricket', 14))
b1.place(x=40, y=120)
change_button(b1, "Бросок под углом \n с земли")
vvod.append(b1)
b1.config(command=th_by_angle_zero)
b2 = Button(root, width=21, height=4, font=('Cricket', 14))
b2.place(x=40, y=270)
change_button(b2, "Бросок вертикально \n вверх с земли")
vvod.append(b2)
b2.config(command=th_vert_v_zero)
b3 = Button(root, width=21, height=4, font=('Cricket', 14))
b3.place(x=40, y=420)
change_button(b3, "Бросок со скоростью, \n направленной \nгоризонтально, с высоты ")
vvod.append(b3)
b3.config(command=th_hor)
b4 = Button(root, width=21, height=4, font=('Cricket', 14))
b4.place(x=295, y=120)
change_button(b4, "Бросок со скоростью, \n направленной под углом \n к горизонту, с высоты ")
vvod.append(b4)
b4.config(command=th_angle_h)
b5 = Button(root, width=21, height=4, font=('Cricket', 14))
b5.place(x=295, y=270)
change_button(b5, "Бросок с высоты со \n скоростью, направленной \nвертикально вверх")
vvod.append(b5)
b5.config(command=th_vert_vverh)
b6 = Button(root, width=21, height=4, font=('Cricket', 14))
b6.place(x=295, y=420)
change_button(b6, "Бросок с высоты со \n скоростью, направленной \nвертикально вниз")
vvod.append(b6)
b6.config(command=th_vert_vniz)
b7 = Button(root, width=21, height=4, font=('Cricket', 14))
b7.place(x=550, y=120)
change_button(b7, "Бросок под углом А к \nгоризонту с высоты h\n на наклонную плоскость\n под углом B")
vvod.append(b7)
b7.config(command=th_dop)
b8 = Button(root, width=21, height=4, font=('Cricket', 14))
b8.place(x=550, y=270)
change_button(b8, "Бросок под углом А к \nгоризонту c движущейся \nплатформы на высоте h")
vvod.append(b8)
b8.config(command=th_angle_h_move)
b9 = Button(root, width=21, height=4, font=('Cricket', 14))
b9.place(x=550, y=420)
change_button(b9, "Бросок под углом А к \nгоризонту c высоты \nс учетом ветра")
vvod.append(b9)
b9.config(command=th_angle_h_wind)
def saved_files():
f_name = fd.askopenfilename()
f = open(f_name, "r")
global vV0, vA, vh, vVdop
st = f.readline().strip()
if (st.find('Бросок под углом к горизонту с земли')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo') != -1):
global V0
V0 = float(st[10:])
if (st.find('A (градусов)') != -1):
global A
A = float(st[14:])
by_angle_zero()
vV0.insert(0, V0)
vA.insert(0, A)
vvod_by_angle_zero()
elif (st.find('Бросок вертикально вверх с земли')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo') != -1):
V0 = float(st[10:])
vert_zero()
vV0.insert(0, V0)
vvod_vert_zero()
elif (st.find('Бросок горизонтально с высоты')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo (м/с)') != -1):
V0 = float(st[10:])
if (st.find('h (м)') != -1):
h = float(st[7:])
hor_h()
vV0.insert(0, V0)
vh.insert(0, h)
vvod_hor_h()
elif (st.find('Бросок под углом к горизонту с высоты h')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo (м/с)') != -1):
V0 = float(st[10:])
if (st.find('h (м)') != -1):
h = float(st[7:])
if (st.find('A (градусов)') != -1):
A = float(st[14:])
by_angle_h()
vV0.insert(0, V0)
vh.insert(0, h)
vA.insert(0, A)
vvod_by_angle_h()
elif (st.find('Бросок вертикально вверх с высоты')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo (м/с)') != -1):
V0 = float(st[10:])
if (st.find('h (м)') != -1):
h = float(st[7:])
vert_v_h()
vV0.insert(0, V0)
vh.insert(0, h)
vvod_vert_v_h()
elif (st.find('Бросок вертикально вниз с высоты')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo (м/с)') != -1):
V0 = float(st[10:])
if (st.find('h (м)') != -1):
h = float(st[7:])
vert_vniz_h()
vV0.insert(0, V0)
vh.insert(0, h)
vvod_vert_vniz_h()
elif (st.find('Бросок под углом А к горизонту с высоты h на плоскость под углом B')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo (м/с)') != -1):
V0 = float(st[10:])
if (st.find('h (м)') != -1):
h = float(st[7:])
if (st.find('A (градусов)') != -1):
A = float(st[14:])
if (st.find('B (градусов)') != -1):
B = float(st[14:])
dop()
global vB
vV0.insert(0, V0)
vh.insert(0, h)
vA.insert(0, A)
vB.insert(0, B)
vvod_dop()
elif (st.find('Бросок под углом к горизонту с движущейся платформы')!=-1):
while (st):
st = f.readline().strip()
if (st.find('Vo (м/с)') != -1):
V0 = float(st[10:])
if (st.find('h (м)') != -1):
h = float(st[7:])
if (st.find('A (градусов)') != -1):
A = float(st[14:])
if (st.find('Vплатформы (м/с) = ') != -1):
Vdop = float(st[19:])
by_angle_h_move()
vV0.insert(0, V0)
vh.insert(0, h)
vA.insert(0, A)
vVdop.insert(0, Vdop)
vvod_by_angle_h_move()
def start_window(): # Основное меню
grafic.delete("all")
global BB
for a in BB:
a.destroy()
grafic.place(x=100000, y=70)
global stroim
stroim = False
b_home.destroy()
c.create_text(415, 60, text="Движение тела, брошенного под углом к горизонту", font=('Cricket', 23), fill=label_text_color)
c['bg'] = label_bg_color
for a in vvod:
a.destroy()
b1 = Button(root, text="1", width=21, height=4, font=('Cricket', 14))
b1.place(x=40, y=120)
b1.config(command = by_angle_zero)
change_button(b1, "Бросок под углом \n с земли")
b2 = Button(root, text="2", width=21, height=4, font=('Cricket', 14))
b2.place(x=40, y=240)
b2.config(command=vert_zero)
change_button(b2, "Бросок вертикально \n вверх с земли")
b3 = Button(root, text="3", width=21, height=4, font=('Cricket', 14))
b3.place(x=40, y=360)
b3.config(command=hor_h)
change_button(b3, "Бросок со скоростью, \n направленной \nгоризонтально, с высоты ")
b4 = Button(root, text="4", width=21, height=4, font=('Cricket', 14))
b4.place(x=295, y=120)
b4.config(command=by_angle_h)
change_button(b4, "Бросок со скоростью, \n направленной под углом \n к горизонту, с высоты ")
b5 = Button(root, text="5", width=21, height=4, font=('Cricket', 14))
b5.place(x=295, y=240)
b5.config(command=vert_v_h)
change_button(b5, "Бросок с высоты \nвертикально вверх")
b6 = Button(root, text="6", width=21, height=4, font=('Cricket', 14))
b6.place(x=550, y=240)
b6.config(command=vert_vniz_h)
change_button(b6, "Бросок с высоты \nвертикально вниз")
b10 = Button(root, text="6", width=21, height=4, font=('Cricket', 14))
b10.place(x=550, y=360)
b10.config(command=by_angle_h_move)
change_button(b10, "Бросок под углом \nс движущегося тела\n на высоте")
b11 = Button(root, text="6", width=21, height=4, font=('Cricket', 14))
b11.place(x=295, y=360)
b11.config(command=by_angle_h_wind)
change_button(b11, "Бросок под углом \nс учетом ветра")
b7 = Button(root, text="7", width=21, height=4, font=('Cricket', 14))
b7.place(x=550, y=120)
change_button(b7, "Бросок под углом А к \nгоризонту с высоты h на \nнаклонную плоскость\n под углом B")
b7.config(command=dop)
b8 = Button(root, text="8", width=21, height=4, font=('Cricket', 14))
b8.place(x=295, y=480)
change_button(b8, "СОХРАНЕННЫЕ \n РЕЗУЛЬТАТЫ")
b8.config(command=saved_files)
b9 = Button(root, text="9", width=21, height=4, font=('Cricket', 14))
b9.place(x=40, y=480)
change_button(b9, "ТЕОРИЯ")
b9.config(command=theory)
b12 = Button(root, text="bruh", width=21, height=4, font=('Cricket', 14))
b12.place(x=550, y=480)
change_button(b12, "СМЕНА ТЕМЫ")
b12.config(command=change_theme)
global main_buttons
main_buttons = {b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12}
start_window()
root.mainloop() | UTF-8 | Python | false | false | 188,176 | py | 7 | main.py | 1 | 0.475979 | 0.417822 | 0 | 4,996 | 34.281225 | 189 |
DanielHry/Python | 17,386,027,621,700 | 0a1344bba3efb6c399d75b3d2abee67a0e4b26ee | a76874216533ad00957938c40bf1bbc32d969dfb | /20 - Coin Flip Simulation/Coin_Flip_Simulation.py | f4fca538d9f5b27b7fc852b6ad872953550f1dea | [] | no_license | https://github.com/DanielHry/Python | 039df8639ee2f97000114c120756632f34f9680b | 6c5e37c207250bd89f67a499135e8eb987578823 | refs/heads/master | 2022-07-13T03:47:49.849202 | 2020-05-16T13:35:18 | 2020-05-16T13:35:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 2020
@author: Daniel Hryniewski
Coin Flip Simulation - Write some code that simulates flipping a single coin however many times the user decides.
The code should record the outcomes and count the number of tails and heads.
"""
import random
def choice():
i = 0
while True:
try:
while i < 1:
number = int(input('Enter how many time do you want play: '))
if number > 0:
i += 1
else:
print("Enter a positive integer.")
except:
print("Enter a positive integer.")
else:
break
return number
def flip(num):
n = 0
tails = 0
heads = 0
while n < num :
f = random.random()
if f < 0.5:
tails += 1
else :
heads += 1
n += 1
return tails, heads
def main():
result = flip(choice())
print('tails:', result[0])
print('heads:', result[1])
if __name__ == '__main__':
main() | UTF-8 | Python | false | false | 1,165 | py | 29 | Coin_Flip_Simulation.py | 28 | 0.466094 | 0.448069 | 0 | 60 | 17.45 | 113 |
henryeherman/elixys | 13,950,053,816,524 | 267a767ebe29ace5e76619abdc53f4754cb2dd7d | 96265682e3dfab6207be5780ef18279d6fa050c1 | /server/hardware/fakeplc/CoolingThread.py | e46d2f1be135e94d07c873cd866389f736d538e4 | [] | no_license | https://github.com/henryeherman/elixys | 1b152b8b82438c5749bfa377563e2aef362ba779 | c6954ca0fff935ce1eb8154744f6307743765dc5 | refs/heads/master | 2021-01-17T21:49:27.294996 | 2014-02-07T21:31:20 | 2014-02-07T21:31:20 | 1,531,843 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | """ CoolingThread.py
Cooling thread that adjusts the temperature of the reactors over time"""
### Imports
import threading
import time
class CoolingThread(threading.Thread):
def __init__(self):
"""Heater thread class constructor"""
super(CoolingThread, self).__init__()
self.__pStopEvent = threading.Event()
def SetParameters(self, pHardwareComm, nR1C1StartTemperature, nR1C2StartTemperature, nR1C3StartTemperature, nR2C1StartTemperature, nR2C2StartTemperature,
nR2C3StartTemperature, nR3C1StartTemperature, nR3C2StartTemperature, nR3C3StartTemperature):
"""Sets the heating thread parameters"""
self.__pHardwareComm = pHardwareComm
self.__nR1C1StartTemperature = nR1C1StartTemperature
self.__nR1C2StartTemperature = nR1C2StartTemperature
self.__nR1C3StartTemperature = nR1C3StartTemperature
self.__nR2C1StartTemperature = nR2C1StartTemperature
self.__nR2C2StartTemperature = nR2C2StartTemperature
self.__nR2C3StartTemperature = nR2C3StartTemperature
self.__nR3C1StartTemperature = nR3C1StartTemperature
self.__nR3C2StartTemperature = nR3C2StartTemperature
self.__nR3C3StartTemperature = nR3C3StartTemperature
def Stop(self):
"""Stops the running thread"""
self.__pStopEvent.set()
def run(self):
"""Thread entry point"""
# Elixys cooling rate in degrees Celsius per 100 ms
fCoolingRate = -0.471
# Lowest temperature
nBottomTemp = 27
# Reactor starting temperatures
nReactorTemperatures = [self.__nR1C1StartTemperature, self.__nR1C2StartTemperature, self.__nR1C3StartTemperature,
self.__nR2C1StartTemperature, self.__nR2C2StartTemperature, self.__nR2C3StartTemperature,
self.__nR3C1StartTemperature, self.__nR3C2StartTemperature, self.__nR3C3StartTemperature]
# Cooling loop
bCooling = True
while bCooling:
# Sleep
time.sleep(0.1)
# Clear our cooling flag
bCooling = False
# Update the temperature of each reactor
for nReactor in range(0, 3):
# Update the temperature of each collet
for nHeater in range(0, 3):
# Has this reactor fully cooled?
if nReactorTemperatures[(nReactor * 3) + nHeater] > nBottomTemp:
# No, so set our cooling flag
bCooling = True
# Adjust the temperature
nReactorTemperatures[(nReactor * 3) + nHeater] += fCoolingRate
# Update the temperature on the PLC
self.__pHardwareComm.FakePLC_SetReactorActualTemperature(nReactor + 1, nHeater + 1, nReactorTemperatures[(nReactor * 3) + nHeater])
# Check for thread termination
if self.__pStopEvent.isSet():
return
# Sleep an additional second to allow everything to settle
time.sleep(1)
| UTF-8 | Python | false | false | 3,191 | py | 275 | CoolingThread.py | 126 | 0.616421 | 0.587277 | 0 | 75 | 41.546667 | 158 |
mashelll/bioinformatics | 6,176,162,998,979 | 4d67482631bf708b8a87ca949ffd8fba337e1bcf | 7b4ad04d91003cddb40c045d5e927fe1263ec5ac | /3.py | 4fdcd4de7ca562f1f0c4f45512f9534dfa747c67 | [] | no_license | https://github.com/mashelll/bioinformatics | 1b0574749171216582361fa6f84cf2dd681e950a | 48787787865bd2e2cdd4cd209c02adb335963920 | refs/heads/master | 2020-09-23T05:00:14.139996 | 2019-12-02T15:42:46 | 2019-12-02T15:42:46 | 225,409,800 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | with open('/home/masha/Загрузки/rosalind_ba1h.txt', 'r') as f:
Pattern = str(f.readline())[:-1]
Text = str(f.readline())
d = int(f.readline())
def HammingDistance(Pattern, substring):
k = len(Pattern)
if k != len(substring):
return
d = 0
for i in range(k):
if Pattern[i] != substring[i]:
d += 1
return d
k = len(Pattern)
N = len(Text)
positions = list()
for i in range(N - k + 1):
substring = Text[i:(i + k)]
if HammingDistance(Pattern, substring) <= d:
if substring not in positions:
positions.append(i)
with open('/home/masha/Загрузки/output.txt', 'w') as f:
for i in positions:
f.write(str(i) + " ")
| UTF-8 | Python | false | false | 725 | py | 21 | 3.py | 21 | 0.566996 | 0.559944 | 0 | 29 | 23.413793 | 62 |
renzon/appengineepython | 3,831,110,837,314 | 7aaee796ac3084288e16e46d474f2742092fae27 | 6b837ccc55a4d8e4c5d0b96f8219343d825374e5 | /backend/appengine/routes/vendas/home.py | f717c6d26b6b227157c5166404920cede871cd64 | [
"MIT"
] | permissive | https://github.com/renzon/appengineepython | 2f2d88d3d5097c3e76cd22e465c6dd51b6d396f9 | ed156055c1d5e023a6b775ad448a85bf037aea8d | refs/heads/master | 2021-01-10T19:09:06.485143 | 2015-01-22T01:34:38 | 2015-01-22T01:34:38 | 22,219,180 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from tekton import router
from gaecookie.decorator import no_csrf
from venda_app import venda_facade
from routes.vendas import new, edit
from tekton.gae.middleware.redirect import RedirectResponse
@no_csrf
def index():
cmd = venda_facade.list_vendas_cmd()
vendas = cmd()
edit_path = router.to_path(edit)
delete_path = router.to_path(delete)
venda_form = venda_facade.venda_form()
def localize_venda(venda):
venda_dct = venda_form.fill_with_model(venda)
venda_dct['edit_path'] = router.to_path(edit_path, venda_dct['id'])
venda_dct['delete_path'] = router.to_path(delete_path, venda_dct['id'])
return venda_dct
localized_vendas = [localize_venda(venda) for venda in vendas]
context = {'vendas': localized_vendas,
'new_path': router.to_path(new)}
return TemplateResponse(context, 'vendas/venda_home.html')
def delete(venda_id):
venda_facade.delete_venda_cmd(venda_id)()
return RedirectResponse(router.to_path(index))
| UTF-8 | Python | false | false | 1,150 | py | 100 | home.py | 62 | 0.698261 | 0.697391 | 0 | 33 | 33.818182 | 79 |
henryjahja/python-algorithms | 11,811,160,068,647 | bf7dbef07ef542d325f65704c593408489870519 | 0ec1f27d2b5a86a29d686deccb3789ee1146a5b1 | /hackerrank/diagonalDifference.py | 8f5745ab33db766212f3df31dae64a636f364417 | [] | no_license | https://github.com/henryjahja/python-algorithms | 0220dd6b9c92eca6ba369a24e60d809a24d0bbd8 | 8378c174d2b58399103b162a357e096b73c3e171 | refs/heads/master | 2020-07-08T10:30:44.934092 | 2017-01-02T23:38:37 | 2017-01-02T23:38:37 | 67,309,796 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''by vatsalchanana
Given a square matrix of size NxN, calculate the absolute difference between the sums of its diagonals.
'''
#!/bin/python3
import sys
n = int(input().strip())
a = []
for a_i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
a.append(a_t)
primaryDiagonal = 0
secondaryDiagonal = 0
y = 0
for x in a:
#print(x[y])
primaryDiagonal += x[y]
#print(x[n-y-1])
secondaryDiagonal += x[n-y-1]
y+=1
print (abs(primaryDiagonal-secondaryDiagonal))
| UTF-8 | Python | false | false | 510 | py | 49 | diagonalDifference.py | 48 | 0.647059 | 0.633333 | 0 | 24 | 20.25 | 103 |
rashmisn96/PythonQ | 11,484,742,573,667 | 7d1a72bd9cd56c10f6021a9bc67cfdec3c9b6c86 | a46c5a6ac384ddc52edd46bfbbd1d3c2e9ee0a6d | /basics/tryexcepttwo.py | 1602515f1edb8c6ee37d1fd9f94437492f3768b1 | [] | no_license | https://github.com/rashmisn96/PythonQ | 19ffa84e5af7dd86e212c96a601ff646e5b04832 | ecf7e3b3b5530837482e27ad2594fc7a5e622fb9 | refs/heads/master | 2022-12-29T02:18:17.048908 | 2020-10-15T16:20:23 | 2020-10-15T16:20:23 | 281,990,079 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | x = input('Enter Days: ')
y = input('Enter Rate: ')
try:
print(int(x))
print(int(y))
except:
print('Please enter numeric value')
| UTF-8 | Python | false | false | 149 | py | 8 | tryexcepttwo.py | 8 | 0.57047 | 0.57047 | 0 | 7 | 19.142857 | 39 |
AlterixAsi/StellarisAutoUpdater | 3,650,722,233,758 | fb5c0cf031f2d2c96493d02d8c494433f60e158f | 25fb8bf7bd3a477beba5891e2a0d2c24b47bd4db | /moves.py | 0b13241b7e618e6995b9889cf96653176989439c | [] | no_license | https://github.com/AlterixAsi/StellarisAutoUpdater | d483e223462f20579f8d436675afa96ea235c6f9 | b6e77d70d71f2c507d70bfda27cf6aeeda9a7a11 | refs/heads/master | 2020-04-13T00:40:12.651561 | 2018-12-23T00:50:59 | 2018-12-23T00:50:59 | 162,851,621 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import shutil
import os
import zipfile
filename = "924990631"
zipf = ""
tempdir = os.listdir("temp/"+filename)
print(tempdir)
z = zipfile.ZipFile("temp/"+filename+"/"+tempdir[0])
z.extract("descriptor.mod","modfile")
z.close()
os.rename("modfile/"+"descriptor.mod","modfile/"+filename+".mod")
shutil.move("temp/"+filename,"mods") | UTF-8 | Python | false | false | 340 | py | 12 | moves.py | 9 | 0.691176 | 0.661765 | 0 | 12 | 26.5 | 65 |
dominikus1993/AlgorithmsAndDataStructFSharp | 7,155,415,555,547 | cbc62d59323bda6403ec62b78dbb987cffa92494 | 9671b2217580be77ed42c1a5d08fc3babf2cf0f9 | /Python/ProjectEuler3.py | 886d7477e726b14cfcb14bc834a194f5282aaafd | [] | no_license | https://github.com/dominikus1993/AlgorithmsAndDataStructFSharp | aa99caa7713758b826d0b9fa86734ac61c03bd9e | 58b109cd21bf5dda7e8a63f9b478c79f36555291 | refs/heads/master | 2020-12-24T06:58:26.212989 | 2016-06-10T08:15:37 | 2016-06-10T08:15:37 | 38,211,612 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import math
def findFactor(number):
upperBound = int(math.sqrt(number)) + 1
return [x for x in range(2,upperBound) if number % x == 0]
def isPrime(number):
return len(findFactor(number)) == 0
def filterList(number):
upperBound = int(math.sqrt(number)) + 1
list = range(2,upperBound)
return max(filter(lambda x: isPrime(x),filter(lambda y: number % y == 0,list)))
print(filterList(600851475143))
| UTF-8 | Python | false | false | 426 | py | 198 | ProjectEuler3.py | 58 | 0.673709 | 0.629108 | 0 | 15 | 27.4 | 83 |
hhongjoon/TIL | 10,531,259,843,040 | c9b039ffe3aeee9c9a45525bb292093e93694c63 | 9c968f7cdf390f8417912519b53f1b7f6ea8b7e8 | /HJ_AL/BAEK/B1094_막대기.py | 2b10e494daa8a1846d3555698c9c8cecf47c0382 | [] | no_license | https://github.com/hhongjoon/TIL | aa33ce2973552a0baa0e0da5bd7d20824fd2e322 | a33b20af15d3f671ea7c7b2855291e50a9036c1c | refs/heads/master | 2021-08-07T17:33:39.722880 | 2020-04-25T08:11:02 | 2020-04-25T08:11:02 | 162,099,245 | 4 | 0 | null | false | 2019-10-30T09:06:21 | 2018-12-17T08:34:07 | 2019-08-10T17:24:38 | 2019-10-30T09:06:20 | 52,347 | 2 | 0 | 1 | Jupyter Notebook | false | false | #64cm
X = int(input())
sticks=[64]
while True:
if sum(sticks) > X:
minstick = min(sticks)
sticks.remove(minstick)
if minstick/2 + sum(sticks) >= X:
sticks.append(minstick/2)
else:
sticks.append(minstick / 2)
sticks.append(minstick/2)
if sum(sticks) == X:
print(len(sticks))
break
| UTF-8 | Python | false | false | 378 | py | 427 | B1094_막대기.py | 317 | 0.52381 | 0.502646 | 0 | 15 | 23.8 | 41 |
spdkh/quera | 12,927,851,596,550 | 17b5b54b296502349f0399625b24ee03af11db64 | f23554b3dd39c2673d2baefbce32423db311233b | /help to copy.py | 179231aeb683b81557823978844d58880a8683ea | [] | no_license | https://github.com/spdkh/quera | be97a81d403aa6c5d44d9dcf1a9a804f0e036a40 | b0e2359f1d2ca334405f8f91153cdca73e01f2be | refs/heads/master | 2022-11-22T14:36:23.709030 | 2020-07-16T14:33:17 | 2020-07-16T14:33:17 | 280,170,779 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | n,s = map(str, input().split())
n = int(n)
print( n * 'copy of ' + s)
| UTF-8 | Python | false | false | 70 | py | 148 | help to copy.py | 148 | 0.514286 | 0.514286 | 0 | 3 | 22.333333 | 31 |
open-mmlab/mmagic | 14,078,902,819,402 | ba713b91325870a0570aa31c46f2eab9f25a25f3 | af101b467134e10270bb72d02f41f07daa7f57d8 | /mmagic/models/losses/loss_comps/clip_loss_comps.py | 4ae48c9bc973d4ae49eca61f16fb16607c0fd1d7 | [
"Apache-2.0"
] | permissive | https://github.com/open-mmlab/mmagic | 4d864853417db300de4dfe7e83ce380fd1557a23 | a382f143c0fd20d227e1e5524831ba26a568190d | refs/heads/main | 2023-08-31T14:40:24.936423 | 2023-08-30T05:05:56 | 2023-08-30T05:05:56 | 203,999,962 | 1,370 | 192 | Apache-2.0 | false | 2023-09-14T11:39:18 | 2019-08-23T13:04:29 | 2023-09-14T11:22:31 | 2023-09-14T11:39:17 | 26,511 | 5,729 | 962 | 22 | Jupyter Notebook | false | false | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional
import torch
import torch.nn as nn
from mmagic.registry import MODELS
from ..clip_loss import CLIPLossModel
@MODELS.register_module()
class CLIPLossComps(nn.Module):
"""Clip loss. In styleclip, this loss is used to optimize the latent code
to generate image that match the text.
In this loss, we may need to provide ``image``, ``text``. Thus,
an example of the ``data_info`` is:
.. code-block:: python
:linenos:
data_info = dict(
image='fake_imgs',
text='descriptions')
Then, the module will automatically construct this mapping from the input
data dictionary.
Args:
loss_weight (float, optional): Weight of this loss item.
Defaults to ``1.``.
data_info (dict, optional): Dictionary contains the mapping between
loss input args and data dictionary. If ``None``, this module will
directly pass the input data to the loss function.
Defaults to None.
clip_model (dict, optional): Kwargs for clip loss model. Defaults to
dict().
loss_name (str, optional): Name of the loss item. If you want this loss
item to be included into the backward graph, `loss_` must be the
prefix of the name. Defaults to 'loss_clip'.
"""
def __init__(self,
loss_weight: float = 1.0,
data_info: Optional[dict] = None,
clip_model: dict = dict(),
loss_name: str = 'loss_clip') -> None:
super().__init__()
self.loss_weight = loss_weight
self.data_info = data_info
self.net = CLIPLossModel(**clip_model)
self._loss_name = loss_name
def forward(self, *args, **kwargs) -> torch.Tensor:
"""Forward function.
If ``self.data_info`` is not ``None``, a dictionary containing all of
the data and necessary modules should be passed into this function.
If this dictionary is given as a non-keyword argument, it should be
offered as the first argument. If you are using keyword argument,
please name it as `outputs_dict`.
If ``self.data_info`` is ``None``, the input argument or key-word
argument will be directly passed to loss function,
``third_party_net_loss``.
"""
# use data_info to build computational path
if self.data_info is not None:
# parse the args and kwargs
if len(args) == 1:
assert isinstance(args[0], dict), (
'You should offer a dictionary containing network outputs '
'for building up computational graph of this loss module.')
outputs_dict = args[0]
elif 'outputs_dict' in kwargs:
assert len(args) == 0, (
'If the outputs dict is given in keyworded arguments, no'
' further non-keyworded arguments should be offered.')
outputs_dict = kwargs.pop('outputs_dict')
else:
raise NotImplementedError(
'Cannot parsing your arguments passed to this loss module.'
' Please check the usage of this module')
# link the outputs with loss input args according to self.data_info
loss_input_dict = {
k: outputs_dict[v]
for k, v in self.data_info.items()
}
kwargs.update(loss_input_dict)
return self.net(*args, **kwargs) * self.loss_weight
@staticmethod
def loss_name() -> str:
"""Loss Name.
This function must be implemented and will return the name of this
loss function. This name will be used to combine different loss items
by simple sum operation. In addition, if you want this loss item to be
included into the backward graph, `loss_` must be the prefix of the
name.
Returns:
str: The name of this loss item.
"""
return 'clip_loss'
| UTF-8 | Python | false | false | 4,124 | py | 1,249 | clip_loss_comps.py | 952 | 0.591174 | 0.589476 | 0 | 106 | 37.90566 | 79 |
JackAndrewG/Python_Project | 9,629,316,693,163 | 427cac3b8a2c3df4786a301d30bd1b52cdc19db7 | 648789f42051eb6383407b135c0f38ffc0387327 | /app1/migrations/0001_initial.py | 28668c66e3996f58af1d2c69d8621999e1d9e1cb | [] | no_license | https://github.com/JackAndrewG/Python_Project | 773f432844155238aa66385b73b8be5da7ddd103 | 4eaa85095dd8dee9b04519c78c0069e06087cf5d | refs/heads/master | 2021-07-22T01:44:30.045778 | 2019-12-08T04:23:58 | 2019-12-08T04:23:58 | 186,859,209 | 1 | 0 | null | false | 2019-07-01T00:10:41 | 2019-05-15T15:54:53 | 2019-06-17T15:17:22 | 2019-06-30T23:57:23 | 13,693 | 0 | 0 | 0 | CSS | false | false | # Generated by Django 2.2.1 on 2019-05-20 14:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Cancha',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo_cancha', models.CharField(default='001', max_length=3)),
('descripcion_cancha', models.TextField(default='cancha de futbolito', max_length=150)),
('valor_dia', models.DecimalField(decimal_places=2, max_digits=7)),
('valor_noche', models.DecimalField(decimal_places=2, max_digits=7)),
('fecha_creacion', models.DateTimeField(auto_now=True)),
('estado_cancha', models.BooleanField(default=True)),
],
),
migrations.CreateModel(
name='Reserva',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo_reserva', models.CharField(default='000123', max_length=6)),
('fecha_reserva', models.DateField()),
('hora_reserva', models.TimeField(default='12:00')),
('valor_untario', models.DecimalField(decimal_places=2, max_digits=7)),
('valor_total', models.DecimalField(decimal_places=2, max_digits=7)),
('fecha_creacion', models.DateTimeField(auto_now=True)),
('estado_reserva', models.BooleanField(default=True)),
('cancha', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app1.Cancha')),
('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Complejo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre_complejo', models.CharField(default='Complejo Deportivo ', max_length=40)),
('direccion_complejo', models.TextField(default='sector-calle principal-calle secundaria-nro-referencia', max_length=200)),
('telefono_complejo', models.CharField(default='(+593) 098-234-1334', max_length=19)),
('cantidad_canchas', models.IntegerField()),
('puntuacion_complejo', models.IntegerField(default='5')),
('estado_complejo', models.BooleanField(default=True)),
('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='cancha',
name='complejo',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app1.Complejo'),
),
]
| UTF-8 | Python | false | false | 3,142 | py | 16 | 0001_initial.py | 8 | 0.598027 | 0.577658 | 0 | 62 | 49.677419 | 139 |
loyess/Note | 7,713,761,288,172 | 957a2a7d2dcfa033b7f23cbbea01cf9ccc17c2a2 | 55fc63ba38c594c0046a9a2e239696726923afbc | /asyncio/011_同一线程的事件循环.py | 8481df3f0e48eb1c7be181c57f436062627c5433 | [] | no_license | https://github.com/loyess/Note | 7eca2bf607f7403b762d98379c121c29803f65d2 | aaa95c4acdd23be95256138c56c286600fe45e7b | refs/heads/master | 2020-04-26T09:44:53.936377 | 2019-03-02T15:50:55 | 2019-03-02T15:50:55 | 173,466,392 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import asyncio
import time
"""
在当前线程中创建一个事件循环(不启用,单纯获取标识),开启一个新的线程,在新的线程中
启动事件循环。在当前线程依据事件循环标识,可以向事件中添加协程对象。当前线程不会由于事件循环而阻塞了。
上面在一个线程中执行的事件循环,只有我们主动关闭事件close,事件循环才会结束,会阻塞。
"""
async def func1(num):
print(num, 'before---func1----')
await asyncio.sleep(num)
return "recv num %s" % num
if __name__ == "__main__":
begin = time.time()
coroutine1 = func1(5)
coroutine2 = func1(3)
coroutine3 = func1(4)
tasks = [
asyncio.ensure_future(coroutine1),
asyncio.ensure_future(coroutine2),
asyncio.ensure_future(coroutine3),
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.run_forever()
end = time.time()
print(end - begin)
| UTF-8 | Python | false | false | 1,002 | py | 29 | 011_同一线程的事件循环.py | 28 | 0.652174 | 0.633152 | 0 | 36 | 19.444444 | 51 |
buildchange/ISAC-SIMO_Django | 1,520,418,423,561 | 287ea18cf608720d54114bdabf8113ca998e3a53 | 45760f48bf8630e059e6a676453abf82e04a4284 | /projects/migrations/0003_projects_detect_model.py | 0ba131412ab5369e1776642496d499e20fa9ab64 | [
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | permissive | https://github.com/buildchange/ISAC-SIMO_Django | c7bb3cece9b19b8afdd6052a0489122f56c54d33 | 985463bfe70d386fffc254edc9eafbdc36c8790e | refs/heads/master | 2023-08-14T20:43:19.293109 | 2023-07-12T03:01:43 | 2023-07-12T03:01:43 | 250,432,048 | 0 | 0 | Apache-2.0 | false | 2023-07-25T21:07:23 | 2020-03-27T03:34:49 | 2022-01-04T10:43:03 | 2023-07-25T21:07:22 | 50,003 | 0 | 0 | 2 | JavaScript | false | false | # Generated by Django 2.0 on 2020-04-17 04:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_auto_20200407_1145'),
]
operations = [
migrations.AddField(
model_name='projects',
name='detect_model',
field=models.TextField(blank=True, null=True),
),
]
| UTF-8 | Python | false | false | 399 | py | 158 | 0003_projects_detect_model.py | 89 | 0.593985 | 0.518797 | 0 | 18 | 21.166667 | 58 |
iamshivamgoswami/Random-DSA-Questions | 15,590,731,299,476 | 7c8740f977c45ef8222ffbd54f692fda12ee7e9e | 80afa26ba73b53f38e3fc21bf395030762fe8981 | /find lonely pixel.py | f2e93031c1dcaabce8f579cecfd949caa7366bab | [] | no_license | https://github.com/iamshivamgoswami/Random-DSA-Questions | 45b402063dbd2e31da2eee7590b6991aa624637d | e36250d08cf0de59cd0a59b4f3293e55793b1a6f | refs/heads/main | 2023-07-15T15:48:36.363321 | 2021-08-26T03:40:47 | 2021-08-26T03:40:47 | 392,702,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution:
def findLonelyPixel(self, l: List[List[str]]) -> int:
def dfs(i, j):
flag = False
for row in range(len(l)):
if row == i:
continue
if l[row][j] == "B":
flag=True
for col in range(len(l[0])):
if col==j:
continue
if l[i][col]=="B":
flag=True
return 1 if not flag else 0
count=0
for i in range(len(l)):
for j in range(len(l[0])):
if l[i][j]=="B":
count+=dfs(i,j)
return count
| UTF-8 | Python | false | false | 668 | py | 118 | find lonely pixel.py | 118 | 0.36976 | 0.362275 | 0 | 23 | 27.956522 | 57 |
nikasha89/AIA | 18,537,078,851,176 | 1a627f0cea3cdb9d2028f554b1df1bade696c9fe | 10e00eea62ac14d5b2631e724b0978590b653a8b | /Entregable 2/arbolesDeDecision.py | da50996f3b0599f7c29f0267d540f1304fbe1b1e | [] | no_license | https://github.com/nikasha89/AIA | e20243055d495973de29e811edd0a53f29c947d5 | 65b00b604d06b1fd3c0cd0f32c238ce67e1cda13 | refs/heads/master | 2020-05-23T07:49:13.211836 | 2017-04-02T11:51:42 | 2017-04-02T11:51:42 | 80,447,347 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from sklearn.tree import DecisionTreeClassifier, export_graphviz
import clasificationSystem
import regresionLogistica
from sklearn.cross_validation import train_test_split
X_names = clasificationSystem.target_names
# Obtenemos datos del entrenamiento:
X_train, X_test, y_train, y_test = train_test_split(clasificationSystem.XmedicalData, clasificationSystem.ymedicalData, test_size=0.75)
# Preparamos el formato de los datos obtenidos del paso anterior:
X_train, y_train = clasificationSystem.prepare_to_fit(clasificationSystem.example, X_train, y_train)
#Declaramos el tipo de clasificador
clasificador2 = DecisionTreeClassifier(criterion='entropy', max_depth=40, min_samples_leaf=5).fit(X_train, y_train)
instancia = clasificationSystem.Xn_train
export_graphviz(clasificador2, feature_names=X_names, out_file="medicalData.dot")
print("----------------------------------------------------------------------------------------------------------------")
print("Árboles de Decisión ")
print("----------------------------------------------------------------------------------------------------------------")
print("Parámetros Ajustados: ")
print("Datos del Clasificador: \n" + str((clasificador2)))
print("----------------------------------------------------------------------------------------------------------------")
print("Árboles de Decisión - Predicción crosstab")
print("----------------------------------------------------------------------------------------------------------------")
clasificationSystem.cross_validation_(clasificador2, X_train,y_train,6)
#Anexo
#Método predict Standart Scaler:
def predict_Standart_Scaler_Trees():
print("----------------------------------------------------------------------------------------------------------------")
print("Árboles de Decisión - Método Predict SGDClassifier")
print("----------------------------------------------------------------------------------------------------------------")
print("Prediccion: {}".format(clasificador2.predict(instancia)))
print("Prediccion_proba: {}".format(clasificador2.predict_proba((instancia))))
print("Score: {}".format(clasificador2.score(X_train, y_train)))
| UTF-8 | Python | false | false | 2,195 | py | 16 | arbolesDeDecision.py | 13 | 0.533638 | 0.527231 | 0 | 40 | 53.625 | 135 |
luffingluffy/kattis | 8,959,301,813,848 | 29828cb7782e9109af9d19434490bc99813dd795 | 79c854b57055db2e6cf5e1023e3992622d52df81 | /level 1/heartrate.py | c57638529c7426958c74a2f584823e3272293907 | [] | no_license | https://github.com/luffingluffy/kattis | c5794f61bf2bc8ba7cf1c0c7c0097a3161bb477e | ffcfa13fa19de6b39f38dd28740129c1b30fdaee | refs/heads/master | 2022-11-20T17:33:46.721204 | 2020-07-20T14:06:57 | 2020-07-20T14:06:57 | 268,847,302 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | n = int(input())
for x in range(n):
b, p = map(float, input().split())
bpm = 60 * b / p
print("{:.4f} {:.4f} {:.4f}".format(bpm - 60/p, bpm, bpm + 60/p))
| UTF-8 | Python | false | false | 167 | py | 43 | heartrate.py | 43 | 0.479042 | 0.42515 | 0 | 6 | 26.833333 | 69 |
mynameismon/12thPracticals | 240,518,197,048 | 6a9e86535fb39270d6c9f201f0242d9621e8d264 | 80ae520ff4a8cffda39fb152f2330df8069d1850 | /question_11/question_11.py | 15950bac4b48920702ec44c4f64123511ba5095d | [
"MIT"
] | permissive | https://github.com/mynameismon/12thPracticals | 8b6d5db79334776fe86126e5c6cc57caa595ab84 | 1e7a5f949a8276f7fac0943d45918abb7c3f39f4 | refs/heads/main | 2023-08-23T06:21:56.758288 | 2021-10-26T12:46:55 | 2021-10-26T12:46:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pickle
import os
path = os.path.join(os.path.dirname(__file__), "student.dat")
def get_data():
try:
f = open(path, "rb")
file = pickle.load(f)
return file
except Exception as e:
print(e)
# I have assumed here that the data is stored in a list of dictionaries (refer question_10.py)
# Function to show records with marks above 75
def show_records():
data = get_data()
count = 0
for i in data:
if i["marks"] > 75:
print(i)
count += 1
print("The count of people above 75% ", count)
#alternate
import pickle
finalL=[]
def CreateFile() :
fbw=open("student.dat","wb+") # remeber to write ab+ not wb +
truthval= input("Do you want to enter records ? (y/n) : ")
while True :
if truthval == "y" or truthval== "Y" :
admn_no = int(input("enter admission number : "))
name = input("enter name : ")
percentage = int(input("enter percentage : "))
tempL = [admn_no, name, percentage]
finalL.append(tempL)
truthval= input("Do you want to enter records ? (y/n) : ")
elif truthval == "n" or truthval== "N" :
pickle.dump(finalL,fbw)
fbw.close()
break
def CountRec() :
global count
count=0
fb=open("student.dat","rb+")
fbr=pickle.load(fb)
for i in range(0,len(finalL)) :
if fbr[i][2] > 75 :
count+=1
print("Admission Number : ",finalL[i][0]," | Name : ", finalL[i][1]," | Percentage : ",finalL[i][2])
else:
break
print("Total number of students with percentage > 75 : ",count)
fb.close()
CreateFile()
CountRec()
| UTF-8 | Python | false | false | 1,772 | py | 20 | question_11.py | 15 | 0.53386 | 0.522009 | 0 | 64 | 26.6875 | 112 |
Twistedkidd22/Sprint-Challenge--Hash-Theory | 2,250,562,876,019 | 69e06889836228c7e215b4c371f252ec38fcb463 | 1b749028880195fee3cc64d00bad5f8853a8c1cd | /hash-tables/ex1/ex1.py | ed1f504661698e612fae6e736dca3ed60d563ab1 | [] | no_license | https://github.com/Twistedkidd22/Sprint-Challenge--Hash-Theory | 5514ee120473ac9820f163e893e359ad247571bf | 2e23bc8e0e1f9d6fbb3c328cd0879258a1e05af4 | refs/heads/master | 2020-04-01T02:19:10.786727 | 2018-10-12T18:09:36 | 2018-10-12T18:09:36 | 152,774,134 | 0 | 0 | null | true | 2018-10-12T15:49:05 | 2018-10-12T15:49:05 | 2018-10-05T20:33:07 | 2018-10-12T15:49:02 | 4 | 0 | 0 | 0 | null | false | null | def get_indices_of_item_weights(weights, limit):
ht = {}
if len(weights) == 1:
return ()
if len(weights) == 2:
if (weights[0] + weights[1] == limit):
if weights[0] > weights[1]:
return (0, 1)
else:
return (1, 0)
for i, w in enumerate(weights):
ht[w] = i
for key in ht:
try:
keyTest = ht[limit-key]
if (keyTest):
return (ht[limit-key], ht[key])
except KeyError:
print('searching...')
if __name__ == '__main__':
print (get_indices_of_item_weights([2], 2))
print (get_indices_of_item_weights([3, 4, 5], 9))
print (get_indices_of_item_weights([10, 14, 15, 16], 30))
print (get_indices_of_item_weights([10, 16, 15, 14], 30))
pass | UTF-8 | Python | false | false | 749 | py | 2 | ex1.py | 2 | 0.534045 | 0.485981 | 0 | 33 | 21.69697 | 59 |
evgenii-del/second-blog | 4,561,255,268,477 | eb756510a2747b6081da75249aec13fb531a7ca7 | c3629c667d155e6c60c72e12f838370f9a95193d | /users/urls.py | 6c0f9ad3e9078e1cf3b69592e60872f154b8de61 | [] | no_license | https://github.com/evgenii-del/second-blog | 185f50743516ac73cb4c2059a85ea3f79882cb2d | 532fe4851dd053723a636569bda72587422c78ee | refs/heads/master | 2020-12-20T20:04:26.602341 | 2020-04-17T12:47:49 | 2020-04-17T12:47:49 | 236,195,243 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.urls import path
from users import views as userViews
from django.contrib.auth import views as authViews
urlpatterns = [
path('registration/', userViews.register, name='reg'),
path('authentication/', authViews.LoginView.as_view(template_name='users/authentication.html'), name='auth'),
path('exit/', authViews.LogoutView.as_view(template_name='users/exit.html'), name='exit'),
path('pass-reset/', authViews.PasswordResetView.as_view(template_name='users/pass_reset.html'), name='pass-reset'),
path('password_reset_confirm/<uidb64>/<token>/',
authViews.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),
name='password_reset_confirm'),
path('password_reset_done/',
authViews.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),
name='password_reset_done'),
path('password_reset_complete/',
authViews.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),
name='password_reset_complete'),
path('profile/options/', userViews.change, name='change'),
path('profile/favourite/', userViews.favourite_list, name='favourite'),
path('profile/', userViews.profile, name='profile'),
]
| UTF-8 | Python | false | false | 1,267 | py | 42 | urls.py | 24 | 0.719021 | 0.717443 | 0 | 23 | 54.086957 | 119 |
nspyre-org/nspyre | 12,893,491,872,283 | 72d2597affe49e821b10ab109872af3a3622a632 | c8fd602e5894b04b766d5a68f1e199b9af8c747d | /src/nspyre/instrument/__init__.py | 34ae0f1be99ec6176992da39eb6a4da714028417 | [
"BSD-3-Clause"
] | permissive | https://github.com/nspyre-org/nspyre | f214ec22d80b0768a1380b0c42d3b05f71c45966 | a772070b11be129309201f250ded86b4a4843495 | refs/heads/main | 2023-08-08T19:14:10.258578 | 2023-05-29T23:42:34 | 2023-05-29T23:42:34 | 220,515,183 | 11 | 6 | BSD-3-Clause | false | 2023-08-02T14:07:06 | 2019-11-08T17:21:20 | 2023-08-02T00:40:52 | 2023-07-25T23:20:30 | 3,202 | 19 | 8 | 1 | Python | false | false | from .gateway import InstrumentGateway
from .gateway import InstrumentGatewayDevice
from .gateway import InstrumentGatewayError
from .manager import InstrumentManager
from .server import InstrumentServer
from .server import InstrumentServerDeviceExistsError
from .server import InstrumentServerError
| UTF-8 | Python | false | false | 300 | py | 73 | __init__.py | 55 | 0.883333 | 0.883333 | 0 | 7 | 41.857143 | 53 |
Gomit/Hadoop_MapReduce | 1,520,418,458,461 | 9ec1af7f4743c31f8f349c59207286f734263ab4 | 61714a18aff7a8944359a2175e4ec2f497629938 | /Students and Posting Time on Forums/reducer.py | 87232d2022cdfaccaae5d1d9c3e861d7b68e3616 | [] | no_license | https://github.com/Gomit/Hadoop_MapReduce | ebefeaa7246b758154da90959dfe2a674d94a1a5 | 30597fadb20e5ba368f4658e30ce22194683c7b5 | refs/heads/master | 2020-09-19T14:38:58.998773 | 2016-09-01T09:54:10 | 2016-09-01T09:54:10 | 66,391,249 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python
import sys
def reducer(reader):
hour_count=[0]*24
oldkey=None
for line in sys.stdin:
data=line.strip().split('\t')
if len(data) != 2:
continue
thiskey,thisHour = data
if oldkey != None and oldkey != thiskey:
for hour,count in enumerate(hour_count):
if count==max(hour_count):
print "{0}\t{1}".format(oldkey,hour)
hour_count=[0]*24
hour_count[int(thisHour)]+=1
oldkey = thiskey
if oldkey != None:
for hour,count in enumerate(hour_count):
if count==max(hour_count):
print "{0}\t{1}".format(oldkey,hour)
if __name__ == "__main__":
reducer(sys.stdin)
| UTF-8 | Python | false | false | 750 | py | 9 | reducer.py | 8 | 0.524 | 0.508 | 0 | 32 | 22.4375 | 56 |
nanoamp/agile-pi-ndicator | 6,777,458,430,200 | 221bdd30a565a32271eca15a6a44a23115ff7baa | 2f59315c5e90a2d7fa7e5e02cd2d37a98b6684e0 | /read_prices.py | 3571ed13425d9df1a4b3aef3387fe18ce8431345 | [
"BSD-3-Clause"
] | permissive | https://github.com/nanoamp/agile-pi-ndicator | 0e4a473aba263153309257c59270dbf284a734de | 5a5abd1677a9f83df2de603050a91f25cb4cf50f | refs/heads/main | 2023-03-29T19:14:21.913241 | 2021-04-06T07:05:02 | 2021-04-06T07:05:02 | 354,870,459 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
from urllib.request import pathname2url
import sqlite3
import datetime
import time
def get_prices(count: int) -> list:
prices = []
try:
# connect to the database in rw mode so we can catch the error if it doesn't exist
DB_URI = 'file:{}?mode=rw'.format(pathname2url('agileprices.sqlite'))
conn = sqlite3.connect(DB_URI, uri=True)
cur = conn.cursor()
print('Connected to database...')
except sqlite3.OperationalError as error:
# handle missing database case
raise SystemExit('Database not found - you need to run store_prices.py first.') from error
# find current time (in UTC, as stored in sqlite)
the_now = datetime.datetime.now(datetime.timezone.utc)
# create range to iterate over
slots = [the_now + datetime.timedelta(minutes=m) for m in range(0, 30*count, 30)]
for i, slot in enumerate(slots):
# convert to year month day hour segment
the_year = slot.year
the_month = slot.month
the_day = slot.day
the_hour = slot.hour
if slot.minute < 30:
the_segment = 0
else:
the_segment = 1
print("Slot", i, "at", slot.strftime("%d/%m/%Y"), "hour:", the_hour, "segment:", the_segment)
# select from db where record == the above
cur.execute("SELECT * FROM prices WHERE year=? AND month=? AND day=? AND hour=? AND segment=?",
(the_year, the_month, the_day, the_hour, the_segment))
# get price
row = cur.fetchone()
if row is None:
prices.append(999) # we don't have that price yet!
else:
# we're getting the fifth field from a hardcoded tuple on the assumption that it's price
# DON'T ADD ANY EXTRA FIELDS TO THAT TABLE on the sqlite db or everything will go wrong.
print(row[5], "p/kWh")
prices.append(row[5])
return prices | UTF-8 | Python | false | false | 1,892 | py | 9 | read_prices.py | 7 | 0.630021 | 0.61945 | 0 | 54 | 34.055556 | 101 |
CemAlpturk/DeepQNetwork | 9,612,136,849,483 | 4000f0a7b3fb7470495c697d673ebc0d9f9b2f7a | c6c182cbe029b6b031df8a04b967abd5c221ae06 | /src/Agents/QAgent.py | 6ca82b6ceb12633d5ab6af71c5728e7ec6577a5e | [] | no_license | https://github.com/CemAlpturk/DeepQNetwork | 279895208b994f5b23c3b991098683dd591698e2 | 52252eaab6a84d8733c05ac2cb8ba62b55bfb4ee | refs/heads/master | 2023-06-10T05:02:28.770694 | 2021-06-14T07:54:36 | 2021-06-14T07:54:36 | 379,201,588 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import time
import random
import os
from collections import deque
from matplotlib import pyplot as plt
from .NetworkBuilder import NetworkBuilder
from .Controller import Controller
from Logger.Logger import Logger
class QAgent:
"""
Represents a Q-Agent.
An agent that trains a network based on Q-Reinforcement Learning.
"""
def __init__(
self,
environment,
network_parameters : dict,
memory = 2000,
use_features=None):
"""
Initializes a Q-Agent.
TODO: Explain all parameters.
TODO: Add custom parameter for custom .csv scores (that are loaded for the evaluator).
"""
self.environment = environment
# Adjust used features
if use_features == None:
self.idx = [True]*environment.state_size
else:
self.idx = use_features
# For reshaping TODO: (check if it's possible to avoid reshaping in the algorithm)
#self.state_size = environment.state_size
self.state_size = sum(self.idx)
network_parameters["input_shape"] = (self.state_size,)
self.q_network = NetworkBuilder.Build(network_parameters)
self.target_network = NetworkBuilder.Build(network_parameters)
self._align_target_model()
self.Logger = Logger(environment.name)
self.episode_loss = []
self.episode_q_values = np.zeros(len(environment.action_space))
self.experience = deque(maxlen=memory)
# Save parameters for logging during training
self.params = {
"memory": memory,
"features": self.idx,
"input_shape": network_parameters["input_shape"],
"layers": network_parameters["layers"],
"step_size": environment.step_size,
"action_space": environment.action_space,
"lamb": environment.lamb,
}
self.params.update(self.q_network.optimizer.get_config())
def train(
self,
max_episodes : int,
exploration_rate=0.9,
discount=0.9,
batch_size=32,
timesteps_per_episode=200,
warm_start=False,
model_alignment_period=100,
save_animation_period=100,
save_model_period=10,
evaluate_model_period=50,
evaluation_size=10,
exploration_rate_decay=0.99,
min_exploration_rate=0.1,
epochs=1,
log_q_values=False) -> Controller:
"""
Trains the network with specified arguments.
# TODO: Describe all arguments.
returns Controller for controlling system provided by environment.
# TODO: Fix and update the summary.
# TODO: Discuss:
* should there be a condition that stops training if the evaluation reaches a "good enough" value?
* This can help avoid overtraining?
# TODO: Add input validation.
# model_alignment_period (align models once after each period, period = n number of episodes)
# save_animation_period (save animation once after each period, period = n number of episodes)
# save_model_period = (save model once after each period, period = n number of episodes)
# evaluate_model_period = (evaluate model once after each period, period = n number of episodes)
# evaluation_size = (number of simulations to run to evaluate the model)
# exploration_rate_decay = (how much the exploration rate should change after each episode)
"""
# Log training parameters
params = {
"max_episodes": max_episodes,
"exploration_rate": exploration_rate,
"discount": discount,
"batch_size": batch_size,
"timesteps_per_episode": timesteps_per_episode,
"model_alignment_period": model_alignment_period,
"evaluate_model_period": evaluate_model_period,
"evaluation_size": evaluation_size,
"exploration_rate_decay": exploration_rate_decay,
"min_exploration_rate": min_exploration_rate,
"epochs": epochs
}
self.params.update(params)
self.Logger.log_params(self.params)
# Load existing model for warm start
if warm_start:
check = self._load_model()
if not check:
print("Using default network") # TODO: temp solution
max_reward = -100
for episode in range(1, max_episodes + 1):
t1 = time.time()
total_reward = 0
eval_score = 0
terminated = False
steps = 0
state = self.environment.reset(random=True) # start from random state
# TODO: Check if possible to avoid reshape!!
state = state[self.idx].reshape(1, self.state_size)
for timestep in range(timesteps_per_episode):
# Predict which action will yield the highest reward.
action = self._act(state, exploration_rate,log_q_values)
# Take the system forward one step in time.
next_state = self.environment.step(action)
# Compute the actual reward for the new state the system is in.
current_time = timestep * self.environment.step_size
reward = self.environment.reward(next_state, current_time)
# Check whether the system has entered a terminal case.
terminated = self.environment.terminated(next_state, current_time)
# TODO: Can this be avoided?
next_state = next_state[self.idx].reshape(1, self.state_size)
# Store results for current step.
self._store(state, action, reward, next_state, terminated)
# Update statistics.
total_reward += reward
state = next_state
steps = timestep+1
if len(self.experience) >= batch_size:
self._experience_replay(batch_size, discount, epochs)
#exploration_rate *= exploration_rate_decay
# Terminate episode if the system has reached a termination state.
if terminated:
break
# Log the average loss for this episode
self.Logger.log_loss(np.mean(self.episode_loss), episode)
self.episode_loss = []
# Log the average Q-values for this episode
if log_q_values:
self.Logger.log_q_values(self.episode_q_values/steps, episode)
self.episode_q_values = np.zeros(len(self.environment.action_space))
if exploration_rate > min_exploration_rate:
exploration_rate *= exploration_rate_decay
else:
exploration_rate = min_exploration_rate
t2 = time.time()
print(
f"Episode: {episode:>5}, "
f"Score: {total_reward:>10.1f}, "
f"Steps: {steps:>4}, "
f"Simulation Time: {(steps * self.environment.step_size):>6.2f} Seconds, "
f"Computation Time: {(t2-t1):>6.2f} Seconds, "
f"Exploration Rate: {exploration_rate:>0.3f}")
if episode % model_alignment_period == 0:
self._align_target_model()
# if episode % save_animation_period == 0:
# self.environment.save(episode)
if episode % evaluate_model_period == 0:
eval_score = self._evaluate(evaluation_size, max_steps=timesteps_per_episode,episode=episode)
if eval_score > max_reward:
self._save_model("best")
max_reward = eval_score
self._save_model("latest")
# Create Controller object
controller = Controller(self.environment.get_action_space(), self.q_network, self.idx)
print("Controller Created")
return controller
def _act(
self,
state,
exploration_rate : float,
log_q_values=False):
"""
Returns index
"""
if np.random.rand() <= exploration_rate:
return self.environment.get_random_action()
q_values = self.q_network.predict(state)[0]
if log_q_values:
self.episode_q_values += q_values
return np.argmax(q_values)
def _store(
self,
state,
action,
reward,
next_state,
terminated):
"""
#TODO: Add summary.
"""
self.experience.append((state, action, reward, next_state, terminated))
def _experience_replay(self, batch_size, discount=0.9, epochs=1):
"""
Updates network weights (fits model) with data stored in memory from
executed simulations (training from experience).
#TODO: Complete summary.
"""
minibatch = random.sample(self.experience, batch_size)
# TODO: The batch_size might not bee needed as an argument here if the reshape things can be resolved.
states, actions, rewards, next_states, terminated = self._extract_data(batch_size, minibatch)
targets = self._build_targets(batch_size, states, next_states, rewards, actions, terminated, discount)
history = self.q_network.fit(states, targets, epochs=epochs, verbose=0, batch_size=1)
#print(history.history['loss'])
self.episode_loss.append(history.history['loss'][0])
def _extract_data(self, batch_size, minibatch):
"""
#TODO: Add summary and type description for variables.
#
# TODO: Complete summary.
"""
# TODO: Extract the values into numpy arrays, could be done more efficient?
states = np.array([x[0] for x in minibatch]).reshape(batch_size, self.state_size)
actions = np.array([x[1] for x in minibatch])
rewards = np.array([x[2] for x in minibatch])
next_states = np.array([x[3] for x in minibatch]).reshape(batch_size, self.state_size)
terminated = np.array([x[4] for x in minibatch])
return (states, actions, rewards, next_states, terminated)
def _build_targets(
self,
batch_size,
states,
next_states,
rewards,
actions,
terminated,
discount):
"""
TODO: Add summary.
"""
i = terminated==0 # Steps that are not terminal
#targets = self.q_network.predict(states) # Predict for each step
targets = np.zeros((batch_size,len(self.environment.action_space)))
t = self.target_network.predict(next_states[i, :]) # Predict for next steps that are not terminal
targets[range(batch_size), actions] = rewards # targets[:,action] = reward, selects the "action" column for each row
targets[i, actions[i]] += discount * np.amax(t, axis=1) # add next estimation to non terminal rows
return targets
def _align_target_model(self):
self.target_network.set_weights(self.q_network.get_weights())
#print("Target Network Realligned")
def _evaluate(self, n, max_steps, episode):
"""
TODO: Add summary
"""
print(f"Evaluating Model for {n} runs")
# max_steps = 200
total_rewards = []
#time_step = 0.1
u = []
rewards = []
term = []
t = []
states = []
times = []
current_time = 0
actions = self.environment.action_space
for play in range(n):
state = self.environment.reset(True)
state_full = state.reshape(1,-1)
state = state[self.idx].reshape(1, self.state_size)
total_reward = 0
for i in range(max_steps):
# Determine the action to take based on the current state of the system.
# TODO: Is this correct? The 'act' function actually uses a randomness to predict the action (when exploration rate is high)
# => It's not the network that predicts the action. We wan't to estimate the network here.
action = self._act(state, -1) # TODO: Discuss - using -1 to get around the random part of the '_act' method.
# Take one step in time and apply the force from the action.
next_state = self.environment.step(action)
# Compute reward for the new state.
current_time = i * self.environment.step_size
reward = self.environment.reward(next_state, current_time)
# Check wheter the new state is a termination or not.
terminated = self.environment.terminated(next_state, current_time)
#Log play
if play == 0:
u.append(actions[action])
t.append(current_time)
rewards.append(reward)
term.append(terminated)
states.append(state_full)
# Update the current state variable.
state_full = next_state.reshape(1,-1)
state = next_state[self.idx].reshape(1, self.state_size)
# Update total reward for the play.
total_reward += reward
# Terminate if the termination condition is true.
if terminated:
break
times.append(current_time)
total_rewards.append(total_reward)
average_time = np.mean(times)
median_time = np.median(times)
std_time = np.std(times)
average_reward = np.mean(total_rewards)
median_reward = np.median(total_rewards)
std_reward = np.std(times)
print(f"Average Total Reward: {average_reward:0.2f}, Median Total Reward: {median_reward:0.2f} Average Time: {average_time:0.2f} Seconds")
# Log the recorded play
self.Logger.log_episode(states,u,rewards,term,t,episode)
self.Logger.log_eval(episode, average_reward, average_time, median_reward, median_time, std_reward, std_time)
return average_reward
def _save_model(self, prefix : str):
print(f"Saving Model: '{prefix}'")
filepath = os.path.join(self.Logger.dir,f"{prefix}/q_network")
self.q_network.save(filepath)
def _load_model(self):
"""
Load pre-trained model for warm start
"""
filepath = f"Models/{self.environment.name}/q_network"
# Check if model exists in default directory
if path.exists(filepath):
self.q_network = NetworkBuilder._load_model(filepath)
self.target_network = NetworkBuilder._load_model(filepath)
print("Models loaded")
return True
else:
print(f"'{filepath}' not found")
return False
# TODO: Create dummy environment
if __name__ == "__main__":
"""
Demonstrates how to use the Q-Agent class.
"""
from Environments import PendulumOnCartEnvironment
# Setup the environment (connects the problem to the q-agent).
step_size = 0.02
environment = PendulumOnCartEnvironment(step_size)
# Setup Neural network parameters.
from tensorflow.keras.optimizers import Adam
optimizer = Adam(lr=0.02)
learning_rate = 0.01
network_parameters = {
"input_shape" : (4,), # Network input shape.
"layers" : [(20, 'relu'), (40, 'relu'), (len(environment.get_action_space()), 'linear')], # [(nodes, activation function)]
"optimizer" : optimizer, # optimizer
"loss_function" : "mse", # loss function ('mse', etc.)
}
# Create agent.
agent = QAgent(environment, network_parameters)
# Train agent - produces a controller that can be used to control the system.
training_episodes = 1
controller = agent.train(max_episodes=training_episodes)
# Simulate problem using the trained controller.
max_time_steps = 100
state = environment.reset()
t = np.linspace(0, 10, 100)
environment.solve(t, controller=controller.act)
environment.animate()
| UTF-8 | Python | false | false | 17,015 | py | 507 | QAgent.py | 27 | 0.558272 | 0.55122 | 0 | 445 | 36.235955 | 146 |
tansir1/thesis | 13,718,125,576,271 | 2f76db7fc66f82351eed956c82377902f12207eb | e7c99b703b1771edc6e27c887bfb13127be3b550 | /python_scripts/ObjectivesData.py | b0f6a6d2a6bcb97fb936e79b5ad1b44e4e0f8f46 | [] | no_license | https://github.com/tansir1/thesis | ea0d39f2a597338c9d4f97d891a80e992dbf3535 | 0764114039008bc483604595576ce5bcf57f1a5f | refs/heads/master | 2021-01-25T12:08:23.452851 | 2017-05-14T15:51:02 | 2017-05-14T15:51:02 | 43,273,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
class ObjectivesData:
def __init__(self):
self.detected = None
self.destroyed = None
self.known = None
self.plotMarker = 'o'
self.plotColor = None
self.plotLabel = None
#Data values
comm100 = ObjectivesData()
comm100.detected = np.array([ 86, 74, 111, 65, 191, 64, 205, 71, 118, 175])
#Skip world 3
#comm100.destroyed = np.array([172, 159, 160, -1, 248, 175, 307, 130, 280, 221])
comm100.destroyed = np.array([172, 159, 160, 248, 175, 307, 130, 280, 221])
comm100.known = np.array([ 85, 68, 82, 95, 16, 58, 95, 20, 63, 29])
comm100.plotColor = 'blue'
comm100.plotLabel = 'Rng 100%'
comm20 = ObjectivesData()
comm20.detected = np.array([122, 66, 176, 61, 144, 117, 238, 166, 261, 156])
comm20.destroyed = np.array([348, 168, 196, 179, 244, 238, 260, 209, 300, 251])
comm20.known = np.array([104, 76, 41, 22, 20, 107, 74, 157, 256, 47])
comm20.plotColor = 'green'
comm20.plotLabel = 'Rng 20%'
comm10 = ObjectivesData()
comm10.detected = np.array([119, 102, 217, 55, 74, 198, 119, 109, 123, 44])
#Skip world 3
#comm10.destroyed = np.array([305, 378, 294, -1, 174, 244, 170, 222, 165, 125])
comm10.destroyed = np.array([305, 378, 294, 174, 244, 170, 222, 165, 125])
comm10.known = np.array([117, 144, 104, 41, 19, 184, 91, 53, 124, 69])
comm10.plotColor = 'red'
comm10.plotLabel = 'Rng 10%'
comm5 = ObjectivesData()
comm5.detected = np.array([238, 112, 164, 55, 76, 171, 394, 172, 133, 100])
#Skip world 4
#comm5.destroyed = np.array([279, 237, 199, 351, -1, 263, 424, 440, 244, 210])
comm5.destroyed = np.array([279, 237, 199, 351, 263, 424, 440, 244, 210])
comm5.known = np.array([242, 123, 85, 65, 66, 136, 161, 142, 156, 115])
comm5.plotColor = 'black'
comm5.plotLabel = 'Rng 5%'
#comm5.plotColor = 'yellow'
comm2 = ObjectivesData()
comm2.detected = np.array([380, 167, 288, 50, 269, 261, 199, 257, 234, 103])
#Skip world 3 and 9
#comm2.destroyed = np.array([554, 498, 596, -1, 337, 299, 395, 468, 323, -1])
comm2.destroyed = np.array([554, 498, 596, 337, 299, 395, 468, 323])
comm2.known = np.array([339, 468, 233, 164, 93, 166, 332, 183, 293, 110])
comm2.plotColor = 'magenta'
comm2.plotLabel = 'Rng 2%'
#comm_ranges = np.array([100,20,10,5,2])
average_detected = np.array([116, 151, 116, 161, 221])
average_destroyed = np.array([206, 239, 231, 294, 434])
average_known = np.array([61, 90, 95, 129, 238]) | UTF-8 | Python | false | false | 2,405 | py | 302 | ObjectivesData.py | 176 | 0.639085 | 0.375468 | 0 | 65 | 36.015385 | 80 |
gitotk/python | 14,955,076,145,262 | 39e481c0272df3204a673cccb7fe7fdcef9d8911 | 679840934d19897c558aeea5f91e51295c887c6a | /60_senkei.py | 925208af337b45cfc86b0e2515a9304fdb74c49c | [] | no_license | https://github.com/gitotk/python | 00c7849761f9aba4a4aea0acaf06b001fa8f9c22 | 58dd381c8ea0cfde8c9595ed4755df421d2091b3 | refs/heads/master | 2020-06-18T23:11:00.274603 | 2019-07-12T01:38:03 | 2019-07-12T01:38:03 | 196,487,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from sklearn import datasets
from sklearn import linear_model
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
#乱数のシードを設定
np.random.seed(0)
#データ準備
x, y = datasets.make_regression(n_samples=100, n_features=1, noise=30)
#学習データとテストデータを分割
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)
e = linear_model.LinearRegression()
e.fit(x_train, y_train)
print("回帰係数は", e.coef_, "です")
print("切片は", e.intercept_, "です")
y_pred = e.predict(x_test)
print("学習データによる決定係数は", e.score(x_train, y_train), "です")
print("テストデータによる決定係数は", e.score(x_test, y_test), "です")
plt.scatter(x_train, y_train, label="train")
plt.scatter(x_test, y_test, label="test")
plt.plot(x_test, y_pred, color="magenta")
plt.legend()
plt.show()
| UTF-8 | Python | false | false | 928 | py | 41 | 60_senkei.py | 40 | 0.716837 | 0.705357 | 0 | 30 | 25.133333 | 72 |
mlabuda2/design_paterns | 16,535,624,121,371 | 200cbada9a067dac1cf53f0b738bd68a1c6154a5 | 254146114bec8f2f3ffa2f513380f93b98ad653e | /singleton/tests/metaclass_singleton.py | f4d5c93f5a5ef0d845ad4bf10041537c13188e19 | [] | no_license | https://github.com/mlabuda2/design_paterns | d047622dede6161b0d1ee020dfa300ce920108e0 | 8d73b851061f5b4e219118d5e51c07704b1d0772 | refs/heads/master | 2022-10-12T08:46:44.620470 | 2020-06-11T12:18:28 | 2020-06-11T12:18:28 | 271,536,705 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # class MyMeta(type):
# _instances = {}
# def __call__(cls, *args, **kwargs):
# if cls not in MyMeta._instances:
# MyMeta._instances[cls] = super().__call__(*args, **kwargs)
# return MyMeta._instances[cls]
# class Singleton(metaclass=MyMeta):
# pass
class Singleton(object):
def __new__(cls):
print(dir(cls))
print(cls.instance)
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
x = Singleton()
y = Singleton()
print(x is y) # Outputs True
# while x is y:
# x = Singleton()
# y = Singleton()
# print(x is y) # Outputs True
| UTF-8 | Python | false | false | 685 | py | 75 | metaclass_singleton.py | 72 | 0.557664 | 0.557664 | 0 | 29 | 22.62069 | 72 |
itspratham/Python-tutorial | 12,996,571,048,493 | 612900a12f83c3ea214728dc0d4fb21ac2e2b2d3 | 9d6091703a2814828f48127088db02d4a4124037 | /Python_Contents/DB/insert_data.py | b9565b5dba0d9df985d32f8da5f0cf7e20ed9f27 | [] | no_license | https://github.com/itspratham/Python-tutorial | 1264c47f44f55a5aa80477b1c74ca72bff894510 | b247d6222aefdb7ac9518fc3911c5df17d880946 | refs/heads/master | 2023-02-09T04:13:39.071396 | 2023-02-03T13:41:46 | 2023-02-03T13:41:46 | 199,325,040 | 2 | 1 | null | false | 2023-02-03T13:43:10 | 2019-07-28T18:49:15 | 2021-12-26T14:27:36 | 2023-02-03T13:42:05 | 8,237 | 2 | 0 | 0 | Python | false | false | import mysql.connector
# Open the db connection
db = mysql.connector.connect("localhost", "root", "password", "python_mysql")
# Open a cursor
cursor = db.cursor()
with open("hello") as fo:
for line in fo:
# print(line)
l = line.split(",")
# print(l)
cursor.execute("INSERT INTO hello VALUES('{}','{}');".format(l[0], int(l[1]), int(l[2])))
cursor.execute("commit;")
cursor.execute("SELECT * FROM hello;")
for i in cursor.fetchall():
print(i)
cursor.close()
| UTF-8 | Python | false | false | 500 | py | 259 | insert_data.py | 243 | 0.616 | 0.61 | 0 | 19 | 25.315789 | 97 |
rpatrik96/nl-causal-representations | 9,526,237,473,255 | 5ee1e88a623f66d495951ace5256dceb61de8682 | 137fe76975e51cc6b0221067389c4de70055155a | /care_nl_ica/runner.py | cd19b96a1adac0ea5e5d1f4738d7f99cc6dbca4b | [
"MIT"
] | permissive | https://github.com/rpatrik96/nl-causal-representations | 3e9d1d70a163badd9807d8071631fde13abaa979 | a5880c1e4051603d65672996b7c8ff204dabbe37 | refs/heads/master | 2023-05-01T14:04:40.019819 | 2023-04-19T05:21:28 | 2023-04-19T05:21:28 | 361,117,778 | 9 | 1 | MIT | false | 2023-04-07T05:26:55 | 2021-04-24T09:10:11 | 2022-09-24T18:31:52 | 2023-04-07T05:26:54 | 6,900 | 2 | 0 | 0 | Python | false | false | import subprocess
import sys
from os.path import dirname
import pytorch_lightning as pl
import torch
import wandb
from care_nl_ica.dep_mat import jacobians
from care_nl_ica.independence.indep_check import IndependenceChecker
from care_nl_ica.losses.utils import ContrastiveLosses
from care_nl_ica.metrics.dep_mat import (
JacobianBinnedPrecisionRecall,
)
from care_nl_ica.metrics.ica_dis import (
calc_disent_metrics,
DisentanglementMetrics,
)
from care_nl_ica.models.model import ContrastiveLearningModel
class ContrastiveICAModule(pl.LightningModule):
def __init__(
self,
lr: float = 1e-4,
latent_dim: int = 3,
device: str = "cuda" if torch.cuda.is_available() else "cpu",
verbose: bool = False,
p: float = 1,
tau: float = 1.0,
alpha: float = 0.5,
box_min: float = 0.0,
box_max: float = 1.0,
sphere_r: float = 1.0,
normalization: str = "",
start_step=None,
use_bias=False,
normalize_latents: bool = True,
log_latent_rec=False,
num_thresholds: int = 30,
log_freq=500,
offline: bool = False,
num_permutations=10,
):
"""
:param num_permutations: number of permutations for HSIC
:param offline: offline W&B run (sync at the end)
:param log_freq: gradient/weight log frequency for W&B, None turns it off
:param num_thresholds: number of thresholds for calculating the Jacobian precision-recall
:param log_latent_rec: Log the latents and their reconstructions
:param normalize_latents: normalize the latents to [0;1] (for the Jacobian calculation)
:param use_bias: Use bias in the network
:param lr: learning rate
:param latent_dim: latent dimension
:param device: device
:param verbose: Print out details, more logging
:param p: Exponent of the assumed model Lp Exponential distribution
:param tau: Print out details, more extensive logging
:param alpha: Weight factor between the two loss components
:param box_min: For box normalization only. Minimal value of box.
:param box_max: For box normalization only. Maximal value of box.
:param sphere_r: For sphere normalization only. Radius of the sphere.
:param normalization: Output normalization to use. If empty, do not normalize at all. Can be ("", "fixed_box", "learnable_box", "fixed_sphere", "learnable_sphere")
:param start_step: Starting step index to activate functions (e.g. the QR loss)
"""
super().__init__()
self.save_hyperparameters()
self.model: ContrastiveLearningModel = ContrastiveLearningModel(
self.hparams
).to(self.hparams.device)
self.dep_mat = None
self.munkres_permutation_idx = None
self.indep_checker = IndependenceChecker(self.hparams)
self.hsic_adj = None
self._configure_metrics()
def _configure_metrics(self):
self.jac_prec_recall = JacobianBinnedPrecisionRecall(
num_thresholds=self.hparams.num_thresholds
)
def on_train_start(self) -> None:
torch.cuda.empty_cache()
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
self.logger.experiment.log({f"thresholds": self.jac_prec_recall.thresholds})
if self.hparams.log_freq is not None:
self.logger.watch(self.model, log="all", log_freq=self.hparams.log_freq)
def configure_optimizers(self):
return torch.optim.Adam(self.model.parameters(), lr=self.hparams.lr)
def training_step(self, batch, batch_idx):
panel_name = "Train"
_, _, _, losses = self._forward(batch)
self.log(f"{panel_name}/losses", losses.log_dict())
return losses.total_loss
def validation_step(self, batch, batch_idx):
panel_name = "Val"
sources, mixtures, reconstructions, losses = self._forward(batch)
self.log(
f"{panel_name}/losses", losses.log_dict(), on_epoch=True, on_step=False
)
self.dep_mat = self._calc_and_log_matrices(mixtures, sources).detach()
"""Precision-Recall"""
self.jac_prec_recall.update(
self.dep_mat, self.trainer.datamodule.unmixing_jacobian
)
precisions, recalls, thresholds = self.jac_prec_recall.compute()
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
self.logger.experiment.log(
{
f"{panel_name}/jacobian/precisions": precisions,
f"{panel_name}/jacobian/recalls": recalls,
}
)
"""HSIC"""
if (
batch_idx == 0
and (
self.current_epoch % 1000 == 0
or self.current_epoch == (self.trainer.max_epochs - 1)
)
is True
):
self.hsic_adj = self.indep_checker.check_multivariate_dependence(
reconstructions[0], mixtures[0]
).float()
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
self.logger.experiment.log({f"{panel_name}/hsic_adj": self.hsic_adj})
"""Disentanglement"""
disent_metrics, self.munkres_permutation_idx = calc_disent_metrics(
sources[0], reconstructions[0]
)
self.log(
f"{panel_name}/disent",
disent_metrics.log_dict(),
on_epoch=True,
on_step=False,
)
# for sweeps
self.log("val_loss", losses.total_loss, on_epoch=True, on_step=False)
self.log("val_mcc", disent_metrics.perm_score, on_epoch=True, on_step=False)
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
self.logger.experiment.log(
{
f"{panel_name}/disent/non_perm_corr_mat": disent_metrics.non_perm_corr_mat
}
)
self.logger.experiment.log(
{f"{panel_name}/disent/perm_corr_mat": disent_metrics.perm_corr_mat}
)
self.log_scatter_latent_rec(sources[0], reconstructions[0], "n1")
self.log_scatter_latent_rec(mixtures[0], reconstructions[0], "z1_n1_rec")
return losses.total_loss
def _calc_and_log_matrices(self, mixtures, sources):
dep_mat, numerical_jacobian, enc_dec_jac = jacobians(
self.model, sources[0], mixtures[0]
)
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
self.logger.experiment.summary[
"Unmixing/unmixing_jacobian"
] = dep_mat.detach()
if self.hparams.verbose is True:
self.logger.experiment.log({"enc_dec_jacobian": enc_dec_jac.detach()})
self.logger.experiment.log(
{"numerical_jacobian": numerical_jacobian.detach()}
)
return dep_mat
def _forward(self, batch):
sources, mixtures = batch
sources, mixtures = tuple(sources), tuple(mixtures)
# forward
reconstructions = self.model(mixtures)
# create random "negative" pairs
# this is faster than sampling z3 again from the marginal distribution
# and should also yield samples as if they were sampled from the marginal
# z3 = torch.roll(sources[0], 1, 0)
# z3_rec = torch.roll(reconstructions[0], 1, 0)
_, _, [loss_pos_mean, loss_neg_mean] = self.model.loss(
*sources,
# z3,
*reconstructions,
# z3_rec
)
# estimate entropy (i.e., the baseline of the loss)
entropy_estimate, _, _ = self.model.loss(
*sources,
# z3,
*sources,
# z3
)
losses = ContrastiveLosses(
cl_pos=loss_pos_mean,
cl_neg=loss_neg_mean,
cl_entropy=entropy_estimate,
)
return sources, mixtures, reconstructions, losses
def log_scatter_latent_rec(self, latent, rec, name: str):
if (
self.hparams.log_latent_rec is True
and isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True
):
for i in range(self.hparams.latent_dim):
table = wandb.Table(
data=torch.stack((latent[:, i], rec[:, i])).T.tolist(),
columns=["latent", "rec"],
)
self.logger.experiment.log(
{
f"latent_rec_{name}_dim_{i}": wandb.plot.scatter(
table,
"latent",
"rec",
title=f"Latents vs reconstruction of {name} in dimension {i}",
)
}
)
def on_fit_start(self) -> None:
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
for key, val in self.trainer.datamodule.data_to_log.items():
self.logger.experiment.summary[key] = val
def on_fit_end(self) -> None:
if isinstance(self.logger, pl.loggers.wandb.WandbLogger) is True:
"""ICA permutation indices"""
self.logger.experiment.summary[
"munkres_permutation_idx"
] = self.munkres_permutation_idx
"""Jacobians"""
table = wandb.Table(
data=[self.dep_mat.reshape(1, -1).tolist()], columns=["dep_mat"]
)
self.logger.experiment.log({f"dep_mat_table": table})
table = wandb.Table(
data=[
self.trainer.datamodule.unmixing_jacobian.reshape(1, -1).tolist()
],
columns=["gt_unmixing_jacobian"],
)
self.logger.experiment.log({f"gt_unmixing_jacobian_table": table})
"""HSIC"""
table = wandb.Table(
data=[self.hsic_adj.reshape(1, -1).tolist()], columns=["hsic_adj"]
)
self.logger.experiment.log({f"hsic_adj_table": table})
if self.hparams.offline is True:
# Syncing W&B at the end
# 1. save sync dir (after marking a run finished, the W&B object changes (is teared down?)
sync_dir = dirname(self.logger.experiment.dir)
# 2. mark run complete
wandb.finish()
# 3. call the sync command for the run directory
subprocess.check_call(["wandb", "sync", sync_dir])
| UTF-8 | Python | false | false | 10,661 | py | 132 | runner.py | 81 | 0.573023 | 0.566926 | 0 | 285 | 36.407018 | 171 |
techolik/Algorithms | 9,062,381,034,933 | d0dd1d56538c81d92e02fcee8863db9620f60a16 | a18c9b048fdb1140f93f9c34f42abdebfc35a8fd | /hackerrank/PU/euler051.py | 24afeaa5c5886289e0f651025bac000d10fa0ba4 | [] | no_license | https://github.com/techolik/Algorithms | 490d0fb818607763a43551db0f2d6b9d443f3c03 | 9c72de3812615d644c6be178779798e0b2c427f1 | refs/heads/master | 2021-01-13T02:06:40.972144 | 2015-07-20T15:28:10 | 2015-07-20T15:28:10 | 39,391,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!python3
# -m cProfile
from itertools import *
from bisect import *
#n, k, l = [int(x) for x in input().split()]
n, k, l = 7, 1, 6
#n, k, l = 6, 6, 1
#n, k, l = 2, 1, 3
#n, k, l = 5, 2, 7
#n, k, l = 3, 2, 4
#n, k, l = 4, 3, 3
def find_prime5(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
correction = n % 6 > 1
n = {0:n, 1:n-1, 2:n+4, 3:n+3, 4:n+2, 5:n+1}[n % 6]
sieve = [True] * (n // 3)
sieve[0] = False
for i in range(int(n ** 0.5) // 3 + 1):
if sieve[i]:
k = (3 * i + 1) | 1
sieve[k*k // 3::2*k] = [False] * ((n//6 - (k*k)//6 - 1)//k + 1)
sieve[(k*k + 4*k - 2*k*(i%2)) // 3::2*k] = [False] * ((n // 6 - (k*k + 4*k - 2*k*(i%2))//6 - 1) // k + 1)
return [2, 3] + [(3 * i + 1) | 1 for i in range(1, n//3 - correction) if sieve[i]]
def combos(ls, k):
return combinations(ls, k)
def solve():
primes = find_prime5(10 ** n)
primes = primes[bisect(primes, 10 ** (n - 1)):]
set_of_primes = set(primes)
pow_of_10 = [10 ** i for i in range(n)]
#mul_of_pow_of_10 = [[pow_of_10[i] * x for i in range(n)] for x in range(10)]
ls = [x for x in range(n - 1, -1, -1)]
def swap(n, combo, i):
pass
families = []
processed = set()
for p in primes:
ttsp = []
for i in range(n):
ttsp.append(p % 10 * pow_of_10[i])
p //= 10
ttsp.reverse()
cool = False
for combo in combinations(ls, k):
tsp = ttsp[:]
mask = 0
for x in combo:
mask += pow_of_10[n - x - 1]
tsp[x] = 0
masked = sum(tsp)
if (masked, mask) in processed:
continue
else:
processed.add((masked, mask))
family = []
for i in range(10):
pp = masked + mask * i
if pp in set_of_primes:
family.append(pp)
if len(family) == l:
families.append(family)
cool = True
break
if cool:
break
if families:
smallest = []
for family in families:
print(family)
if not smallest or family[0] < smallest[0]:
smallest = family
#if len(family) == l:
for prime in smallest:
#print(prime, end=' ')
print(prime)
solve() | UTF-8 | Python | false | false | 2,682 | py | 94 | euler051.py | 69 | 0.414616 | 0.368755 | 0 | 88 | 28.5 | 117 |
SohailAhmed10/TicTacToe | 10,144,712,762,733 | ef72ea1dd2d54cc9d0447e697e76483898b07a09 | a424d2691d36c8feaebcaa0623f48b7b49033384 | /tictactoe.py | 2180c7cbeecd06bc6712078971891590c46f6e6c | [] | no_license | https://github.com/SohailAhmed10/TicTacToe | 56ed913f930f766888f318d20bcd21edf18073bf | 4a6ecb8ff95c6c2a359147c371d5689ea2fdd325 | refs/heads/master | 2020-03-14T23:45:14.726982 | 2018-05-05T02:16:29 | 2018-05-05T02:16:29 | 131,852,130 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class InvalidEntryError(Exception):
pass
class Matrix():
''' A class that represents a matrix '''
def __init__(self, values):
'''(Matrix, list of lists) -> NoneType
Create a new Matrix with values as its values.
'''
# create the instance variables values, number of rows and number of columns
self._values = values
self.num_rows = len(values)
self.num_columns = len(values[0])
def __str__(self):
output = ''
for i in range(self.num_rows):
output += '\n'
for j in range(self.num_columns):
output += str(self._values[i][j]) + '|'
return output
def set_value(self, position, value):
''' (Matrix, tuple, int/str) -> NoneType
Adds a value to a position in the matrix
'''
i = position[0] - 1
j = position[1] - 1
self._values[i][j] = value
def get_value(self, position):
''' (Matrix, tuple) -> int/str
Given a positions, returns the value in the position
'''
i = position[0] - 1
j = position[1] - 1
return self._values[i][j]
class TicTacToe(Matrix):
def __init__(self):
Matrix.__init__(self, [[0, 1, 2, 3],[1,'_','_', '_'], [2,'_','_','_'], [3,'_','_','_']])
def input_value(self, x, y, value):
self.set_value((x, y), value)
def check_row(self, row_num):
first_val = self.get_value((2, row_num))
second_val = self.get_value((3, row_num))
third_val = self.get_value((4, row_num))
if first_val == second_val == third_val == 'X' or (first_val == second_val == third_val == 'O'):
result = True
else:
result = False
return result
def check_col(self, col_num):
first_val = self.get_value((col_num, 2))
second_val = self.get_value((col_num, 3))
third_val = self.get_value((col_num, 4))
if first_val == second_val == third_val == 'X' or (first_val == second_val == third_val == 'O'):
result = True
else:
result = False
return result
def check_diag(self, l_or_r):
if l_or_r == 'right':
first_val = self.get_value((2, 2))
second_val = self.get_value((3, 3))
third_val = self.get_value((4, 4))
if l_or_r == 'left':
first_val = self.get_value((4, 2))
second_val = self.get_value((3, 3))
third_val = self.get_value((2, 4))
if (first_val == second_val == third_val == 'X') or (first_val == second_val == third_val == 'O'):
result = True
else:
result = False
return result
def is_full(self):
for i in range(4):
for j in range(4):
if self.get_value((i,j)) == '_':
return False
return True
class Play_game(TicTacToe):
def __init__(self):
TicTacToe.__init__(self)
def game(self):
entry = input("Enter START to begin: ")
if entry == "START":
Board = TicTacToe()
print(Board)
result = False
while Board.is_full() is not True and result is not True:
valid_entry = False
while valid_entry != True:
Player1 = (input("Player1:Enter a position. For example 11 or 22: "))
try:
x = int(Player1[0])
y = int(Player1[1])
if x < 1 or y < 1 or x > 3 or y > 3:
raise InvalidEntryError("The number you have entered is out of range, Try Again!")
elif Board.get_value((x+1,y+1)) != '_':
raise InvalidEntryError("That space is already taken, Try Again!")
else:
valid_entry = True
except InvalidEntryError as e:
print (str(e))
except ValueError:
print('Please input a location within the board, Try Again!')
except IndexError:
print('Please unput a location, Try Again!')
Board.set_value((x+1,y+1), 'X')
print(Board)
if (Board.check_row(y+1) or Board.check_col(x+1) or Board.check_diag('left') or Board.check_diag('right')) is True:
print('Player1 wins!!!')
result = True
elif Board.is_full() is True:
print('It is a DRAW!')
result = True
else:
valid_entry = False
while valid_entry != True:
Player2 = (input("Player2:Enter a position. For example 11 or 22: "))
try:
x = int(Player2[0])
y = int(Player2[1])
if x < 1 or y < 1 or x > 3 or y > 3:
raise InvalidEntryError("The number you have entered is out of range, Try Again!")
elif Board.get_value((x+1,y+1)) != '_':
raise InvalidEntryError("That space is already taken, Try Again!")
else:
valid_entry = True
except InvalidEntryError as e:
print (str(e))
Board.set_value((x+1,y+1), 'O')
print(Board)
if (Board.check_row(y+1) or Board.check_col(x+1) or Board.check_diag('left') or Board.check_diag('right')) is True:
print('Player2 wins!!!')
result = True
elif Board.is_full() is True:
print('It is a DRAW')
result = True
A = Play_game()
A.game()
| UTF-8 | Python | false | false | 6,354 | py | 1 | tictactoe.py | 1 | 0.4339 | 0.421624 | 0 | 160 | 37.7125 | 135 |
alisamadzadeh46/filestore | 5,480,378,297,118 | c236eb61eba4c1cff09ac8361fb80dbed239a103 | ceeeb927544c474163347254b11485cc945ea951 | /administrator/urls.py | 9e38dbc59c8fe4c04ccb9e3dab3fff1205452efe | [] | no_license | https://github.com/alisamadzadeh46/filestore | ecc8d84ca16e8a8a51af0b74446a0c3b88cda646 | 4f31e51b2d028cd5f79b6af06d05568a8af7e9e1 | refs/heads/main | 2023-06-22T18:38:08.179128 | 2021-07-26T16:03:19 | 2021-07-26T16:03:19 | 377,806,835 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.urls import path, include
from .views import *
app_name = 'administrator'
urlpatterns = [
path('', include('common.urls')),
path('ambassadors', AmbassadorAPIView.as_view(), name='ambassadors'),
path('products', ProductGenericAPIView.as_view(), name='products'),
path('products/<str:pk>', ProductGenericAPIView.as_view(), name='products'),
path('users/<str:pk>/links', LinkAPIView.as_view(), name='users'),
path('orders', OrderAPIView.as_view(), name='orders'),
]
| UTF-8 | Python | false | false | 501 | py | 6 | urls.py | 3 | 0.680639 | 0.680639 | 0 | 13 | 37.538462 | 80 |
dartoon/my_code | 11,836,929,910,011 | d0b1c81f8e8af89314b81e4b704fa70041d5f80b | 09ac6ada5c82775dd816d36709ebf6c787b690ab | /for_collbrate/John_Nancy_HSC/HSC_galaxy_example/1_read_result.py | 717943ce15aeb73f4daedb25ec450206027ca7b9 | [] | no_license | https://github.com/dartoon/my_code | 76a240345771bbea7a654390928e7731e4a357b2 | dec99ab02c78325a029068702406fbc568911f3f | refs/heads/master | 2023-08-16T20:00:12.283325 | 2023-08-10T03:50:59 | 2023-08-10T03:50:59 | 138,827,442 | 0 | 0 | null | false | 2022-12-09T06:48:12 | 2018-06-27T03:56:09 | 2022-11-13T04:47:53 | 2022-12-09T06:48:10 | 278,346 | 0 | 0 | 3 | Python | false | false | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 17:55:30 2019
@author: Dartoon
"""
import numpy as np
import matplotlib.pyplot as plt
import pickle
import corner
import glob
import astropy.io.fits as pyfits
from gen_fit_id import gen_fit_id
#image_folder = '../images_directory/'
image_folder = './image/'
folder = 'RESULTS/'
galaxy_ID = '18184'
galaxy_RA = 150.121811
galaxy_DEC = 2.394572
band = 'I'
zp = 27.0
picklename = folder+'fit_image_'+galaxy_ID+ '_HSC-{0}.pkl'.format(band)
if_file = glob.glob(picklename)
if if_file == []:
print "MCMC for {0}-{1} not performed!".format(galaxy_ID,band)
else:
result = pickle.load(open(picklename,'rb'))
best_fit, chain_result, trans_paras = result
source_result, image_host, _ =best_fit
chain_list, _ = chain_result
sampler_type, samples_mcmc, param_mcmc, dist_mcmc = chain_list[1]
_, mcmc_new_list, labels_new, _ = trans_paras
mcmc_new_list = np.asarray(mcmc_new_list)
#%%
# print "plot the overall parameter contour:"
# plot = corner.corner(samples_mcmc, labels=param_mcmc, show_titles=True)
# plt.show()
print "plot the flux contour for all the hosts"
plot = corner.corner(mcmc_new_list, labels=labels_new, show_titles=True)
plt.show()
#readout the parameter
print "=================================\noverall fitting parameters:", param_mcmc
idx = 0 #The inferred Reff of the host
v_l=np.percentile(samples_mcmc[:,idx],16,axis=0)
v_m=np.percentile(samples_mcmc[:,idx],50,axis=0)
v_h=np.percentile(samples_mcmc[:,idx],84,axis=0)
print "The inferred", param_mcmc[idx], ":"
print "lower limit:", v_l
print "The mid fit:", v_m
print "upper limit", v_h
##Readout the translated flux.
print "=================================\noverall flux components:", labels_new
mcmc_new_list = np.asarray(mcmc_new_list)
idx = 1 #The translated flux for the host
v_l=np.percentile(mcmc_new_list[:,idx],16,axis=0)
v_m=np.percentile(mcmc_new_list[:,idx],50,axis=0)
v_h=np.percentile(mcmc_new_list[:,idx],84,axis=0)
#print labels_new[idx], ":", v_l, v_m, v_h
print "The inferred", labels_new[idx], "mag:"
print "lower limit:", -2.5 * np.log10(v_h) + zp
print "The mid fit:", -2.5 * np.log10(v_m) + zp
print "upper limit", -2.5 * np.log10(v_l) + zp
#%%
print "Check the convergency of the PSO chains:"
import lenstronomy.Plots.output_plots as out_plot
for i in range(len(chain_list)):
f, axes = out_plot.plot_chain_list(chain_list,0)
plt.show()
#%%test the MCMC chain convergency
#
#import lenstronomy.Plots.output_plots as plot_mcmc_behaviour
fig = plt.figure(figsize=(20, 15))
ax = fig.add_subplot(111)
out_plot.plot_mcmc_behaviour(ax, samples_mcmc, param_mcmc, dist_mcmc)
plt.show()
#%% Plot the image again:
band_seq = ['G', 'R', 'I', 'Z', 'Y']
filename = galaxy_ID+'_HSC-{0}.fits'.format(band)
sub_bkg = True
from flux_profile import galaxy_total_compare
galaxy_im, err_map, galaxy_bkg, PSF, pix_scale, zp, qso_fr_center, fr_c_RA_DEC = gen_fit_id(image_folder, galaxy_RA, galaxy_DEC, filename, cut_frame=120, subbkl=sub_bkg)
ct = (len(galaxy_im)-len(image_host[0]))/2 # If want to cut to 61, QSO_im[ct:-ct,ct:-ct]
if len(image_host) == 1:
host = image_host[0]
label = ['data', 'QSO', 'host', 'model', 'normalized residual']
elif len(image_host) >1:
host = np.zeros_like(image_host[0])
for i in range(len(image_host)):
host += image_host[i]
label = ['data', 'QSO', 'host as {0} components'.format(i+1), 'model', 'normalized residual'] #Print the numbers of objects
agn_image = galaxy_im[ct:-ct,ct:-ct]
error_map = err_map[ct:-ct,ct:-ct]
objs_img = np.zeros_like(image_host[0])
if len(source_result)>1:
for i in range(1,len(image_host)):
objs_img += image_host[i]
flux_list = [agn_image, image_host[0]*0, image_host[0]+objs_img, error_map]
fig = galaxy_total_compare(label_list = ['data', 'model', 'normalized residual'], flux_list = flux_list, target_ID = galaxy_ID, pix_sz=pix_scale,
zp = zp, plot_compare=True, msk_image = np.ones_like(image_host[0]))
| UTF-8 | Python | false | false | 4,213 | py | 722 | 1_read_result.py | 502 | 0.633753 | 0.609305 | 0 | 117 | 34.965812 | 169 |
mhrodriguez/siita-upv-2018 | 10,660,108,838,532 | cc8ad8b6fee762fb44693f8f05559455557590dd | 5c55964dc1ba07b1484572c2becae5f83ddb6f88 | /solicitud_tuto/migrations/0001_initial.py | 83f57041d9679c29153bc6fc11f966187dd99d36 | [] | no_license | https://github.com/mhrodriguez/siita-upv-2018 | 711c3e753e00b205804dee55e81e2ad60de649a5 | 8cb6700e785235f0a2c2d5c407810be009e2cd4d | refs/heads/master | 2020-03-12T01:49:41.281218 | 2018-05-04T21:37:04 | 2018-05-04T21:37:04 | 127,964,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-04-23 16:15
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Solicitudes_citas',
fields=[
('id_cita', models.AutoField(primary_key=True, serialize=False, validators=[django.core.validators.MaxValueValidator(99999999999)])),
('id_alumno', models.IntegerField(validators=[django.core.validators.MaxValueValidator(99999999999)])),
('id_maestro', models.IntegerField(validators=[django.core.validators.MaxValueValidator(99999999999)])),
('tipo', models.CharField(max_length=15)),
('fecha', models.DateField()),
('lugar', models.CharField(max_length=45)),
('comentarios', models.CharField(max_length=225)),
],
),
]
| UTF-8 | Python | false | false | 1,041 | py | 36 | 0001_initial.py | 32 | 0.618636 | 0.563881 | 0 | 29 | 34.896552 | 149 |
applemin/Deadline_Development | 12,429,635,391,876 | f1c39f656c4d7ecc3c2a05987920357e6d3edca0 | 0a0efc02319e01b9393ac56e4bf144267510c148 | /plugins/DraftTileAssembler/DraftTileAssembler.py | 90d0cf6edeb4a69fdca15ae1ff54572a481a447e | [] | no_license | https://github.com/applemin/Deadline_Development | 791c37d44002ea6010ce45a0798ae126201f63d4 | 75ccfeaf31bc259ceb89a38e65f8f4cdc4cdb0a0 | refs/heads/master | 2022-04-14T01:34:19.623922 | 2020-02-19T04:16:04 | 2020-02-19T04:16:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from System import *
from System.Diagnostics import *
from System.IO import *
from Deadline.Plugins import *
from Deadline.Scripting import *
import filecmp
import os
import re
######################################################################
## This is the function that Deadline calls to get an instance of the
## main DeadlinePlugin class.
######################################################################
def GetDeadlinePlugin():
return DraftTileAssemblerPlugin()
def CleanupDeadlinePlugin( deadlinePlugin ):
deadlinePlugin.Cleanup()
######################################################################
## This is the main DeadlinePlugin class for the Tile Assembler plugin.
######################################################################
class DraftTileAssemblerPlugin (DeadlinePlugin):
isFolderAssembly = False
currentFile = 1
maxFiles = 1
def __init__( self ):
self.InitializeProcessCallback += self.InitializeProcess
self.StartupDirectoryCallback += self.StartupDirectory
self.RenderExecutableCallback += self.RenderExecutable
self.RenderArgumentCallback += self.RenderArgument
self.PreRenderTasksCallback += self.PreRenderTasks
self.PostRenderTasksCallback += self.PostRenderTasks
def Cleanup(self):
for stdoutHandler in self.StdoutHandlers:
del stdoutHandler.HandleCallback
del self.InitializeProcessCallback
del self.StartupDirectoryCallback
del self.RenderExecutableCallback
del self.RenderArgumentCallback
del self.PreRenderTasksCallback
del self.PostRenderTasksCallback
## Called by Deadline to initialize the process.
def InitializeProcess( self ):
self.SingleFramesOnly = True
self.StdoutHandling = True
self.HideDosWindow = True
self.PluginType = PluginType.Simple
draftLocalPath = Path.Combine( self.GetSlaveDirectory(), "Draft" )
self.AddStdoutHandlerCallback( "Draft Tile Assembler Failed! see log for more details." ).HandleCallback += self.HandleStdoutError
self.AddStdoutHandlerCallback( "Assembling Progress: [0-9]+%" ).HandleCallback += self.HandleStdoutProgress
self.AddStdoutHandlerCallback( "Assembling image [0-9]+ of [0-9]+" ).HandleCallback += self.HandleStdoutFolderFile
self.AddStdoutHandlerCallback( "Assembling Folder" ).HandleCallback += self.HandleStdoutIsFolder
self.DraftAutoUpdate( draftLocalPath )
if SystemUtils.IsRunningOnWindows():
draftLibrary = Path.Combine( draftLocalPath, "Draft.pyd" )
else:
draftLibrary = Path.Combine( draftLocalPath, "Draft.so" )
if not os.path.isfile( draftLibrary ):
self.FailRender( "Could not find local Draft installation." )
else:
self.LogInfo( "Found Draft python module at: '%s'" % draftLibrary )
self.DraftDirectory = draftLocalPath
#preserve existing env vars by appending/prepending
newPythonPath = self.DraftDirectory
if Environment.GetEnvironmentVariable( "PYTHONPATH" ) != None:
newPythonPath = newPythonPath + Path.PathSeparator + Environment.GetEnvironmentVariable( "PYTHONPATH" )
newMagickPath = self.DraftDirectory
if Environment.GetEnvironmentVariable( "MAGICK_CONFIGURE_PATH" ) != None:
#give locally set MAGICK path priority over the Draft one
newMagickPath = Environment.GetEnvironmentVariable( "MAGICK_CONFIGURE_PATH" ) + Path.PathSeparator + newMagickPath
self.SetEnvironmentVariable( 'PYTHONPATH', newPythonPath )
self.SetEnvironmentVariable( 'MAGICK_CONFIGURE_PATH', newMagickPath )
if SystemUtils.IsRunningOnLinux():
newLDPath = Path.Combine(ClientUtils.GetBinDirectory(),"python","lib")+Path.PathSeparator+self.DraftDirectory
if Environment.GetEnvironmentVariable( "LD_LIBRARY_PATH" ) != None:
newLDPath = newLDPath + Path.PathSeparator + Environment.GetEnvironmentVariable( "LD_LIBRARY_PATH" )
self.SetEnvironmentVariable( 'LD_LIBRARY_PATH', newLDPath )
elif SystemUtils.IsRunningOnMac():
newDYLDPath = self.DraftDirectory
if Environment.GetEnvironmentVariable( "DYLD_LIBRARY_PATH" ) != None:
newDYLDPath = newDYLDPath + Path.PathSeparator + Environment.GetEnvironmentVariable( "DYLD_LIBRARY_PATH" )
self.SetEnvironmentVariable( 'DYLD_LIBRARY_PATH', newDYLDPath )
def DraftAutoUpdate( self, localPath ):
updateNeeded = True
draftPathComponents = "draft"
if SystemUtils.IsRunningOnMac():
draftPathComponents = os.path.join( draftPathComponents, "Mac" )
else:
if SystemUtils.IsRunningOnLinux():
draftPathComponents = os.path.join( draftPathComponents, "Linux" )
else:
draftPathComponents = os.path.join( draftPathComponents, "Windows" )
if SystemUtils.Is64Bit():
draftPathComponents = os.path.join( draftPathComponents, "64bit" )
else:
draftPathComponents = os.path.join( draftPathComponents, "32bit" )
localFile = os.path.join( localPath, "Version" )
repoFile = RepositoryUtils.GetRepositoryFilePath( os.path.join( draftPathComponents, "Version" ), False )
if not os.path.exists( repoFile ):
self.FailRender( "ERROR: Draft was not found in the Deadline Repository!" )
if ( os.path.exists( localPath ) and os.path.isfile( localFile ) and os.path.isfile( repoFile ) ):
if filecmp.cmp(localFile, repoFile):
updateNeeded = False
elif not os.path.exists( localPath ):
self.LogInfo( "Creating local Draft directory..." )
os.makedirs( localPath )
if ( updateNeeded ):
repoPath = RepositoryUtils.GetRepositoryPath( draftPathComponents, False )
self.LogInfo( "Draft upgrade detected, copying updated files..." )
for filePath in Directory.GetFiles( repoPath ):
fileName = Path.GetFileName( filePath )
self.LogInfo( "Copying '%s'..." % fileName )
File.Copy( filePath, Path.Combine(localPath, fileName), True )
self.LogInfo( "Draft update completed!" )
def RenderExecutable( self ):
#build up the path parts based on system type & bitness
if SystemUtils.IsRunningOnWindows():
pythonExe = "dpython.exe"
elif SystemUtils.IsRunningOnMac():
pythonExe = "dpython"
else:
pythonExe = "dpython"
pythonPath = Path.Combine( ClientUtils.GetBinDirectory(), pythonExe )
self.LogInfo( "Looking for bundled python at: '%s'" % pythonPath )
if not FileUtils.FileExists( pythonPath ):
self.FailRender( "Could not find bundled Python executable." )
self.PythonExe = pythonPath
return self.PythonExe
def StartupDirectory(self):
return self.DraftDirectory
def PreRenderTasks(self):
self.LogInfo( "Draft Tile Assembler job starting..." )
sceneFilename = ""
if not self.GetBooleanPluginInfoEntryWithDefault( "MultipleConfigFiles", False ):
sceneFilename = self.GetDataFilename()
else:
configFilenames = self.GetAuxiliaryFilenames()
sceneFilename = configFilenames[int(self.GetCurrentTaskId())]
tempSceneDirectory = self.CreateTempDirectory( "thread" + str(self.GetThreadNumber()) )
tempSceneFileName = Path.GetFileName( sceneFilename )
self.TempSceneFilename = Path.Combine( tempSceneDirectory, tempSceneFileName )
if SystemUtils.IsRunningOnWindows():
RepositoryUtils.CheckPathMappingInFileAndReplaceSeparator(sceneFilename, self.TempSceneFilename, "/", "\\")
else:
RepositoryUtils.CheckPathMappingInFileAndReplaceSeparator(sceneFilename, self.TempSceneFilename, "\\", "/")
os.chmod( self.TempSceneFilename, os.stat( self.TempSceneFilename ).st_mode )
def PostRenderTasks(self):
#check if we're running a post render script (ie, shotgun upload)
postRenderScript = self.GetPluginInfoEntryWithDefault("postRenderScript", None)
if ( postRenderScript ) :
ProcessUtils.SpawnProcess( self.PythonExe, postRenderScript )
self.LogInfo( "Draft Tile Assembler Job Completed" )
def HandleStdoutError(self):
self.FailRender( self.GetRegexMatch(0) )
def HandleStdoutProgress(self):
output = self.GetRegexMatch(0)
percentage = re.search('(\d+)%$', output).group(0)
percentage = int(percentage[:-1])*1.0
if self.isFolderAssembly:
output = "File "+str(self.currentFile)+" of "+str(self.maxFiles)+ ": "+output
percentage = percentage/self.maxFiles
additonalPercentage = ((self.currentFile-1.0)/self.maxFiles)*100
percentage = percentage+additonalPercentage
percentage = int(percentage+0.5)*1.0
self.SetProgress( percentage )
self.SetStatusMessage( output )
def HandleStdoutFolderFile(self):
output = self.GetRegexMatch(0)
match = re.search('(\d+) of (\d+)', output)
self.currentFile = float(match.group(1))
self.maxFiles = float(match.group(2))
def HandleStdoutIsFolder(self):
self.isFolderAssembly = True
def RenderArgument( self ):
scriptFile = Path.Combine( self.GetPluginDirectory(), "Assembler.py" )
configFile = self.TempSceneFilename
tempFolder = self.CreateTempDirectory("AssembledImage")
errorOnMissing = self.GetBooleanPluginInfoEntryWithDefault("ErrorOnMissing", True)
cleanupTiles = self.GetBooleanPluginInfoEntryWithDefault("CleanupTiles", False)
errorOnMissingBackground = self.GetBooleanPluginInfoEntryWithDefault("ErrorOnMissingBackground", True)
return '"' + scriptFile + '" "' + configFile + '" ' + str(errorOnMissing) + " " + str(cleanupTiles) + " " + str(errorOnMissingBackground) + ' "' + tempFolder + '"' | UTF-8 | Python | false | false | 10,594 | py | 356 | DraftTileAssembler.py | 281 | 0.631018 | 0.627997 | 0 | 232 | 44.668103 | 171 |
batalhadematos/addons-tko | 8,461,085,605,540 | d182832e132d4136ef13c35f6ce3df794b7c9102 | 78a389e6dd70a96f7c96295743f3ab5c17716f81 | /tko_discharge_notes/report/common_report_header.py | 09770d23c6e3481057978ac90fdd8ac976a35458 | [] | no_license | https://github.com/batalhadematos/addons-tko | e98a231b41bd5eaf40d047cc0237503fea6562d0 | 7772a9d5d0471490af78e04e7108624895670bbc | refs/heads/master | 2015-08-17T15:24:45.680622 | 2015-07-05T15:36:20 | 2015-07-05T15:36:20 | 27,509,195 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import pooler
from openerp.tools.translate import _
class common_report_header(object):
# def _sum_debit(self, period_id=False, journal_id=False):
# if journal_id and isinstance(journal_id, int):
# journal_id = [journal_id]
# if period_id and isinstance(period_id, int):
# period_id = [period_id]
# if not journal_id:
# journal_id = self.journal_ids
# if not period_id:
# period_id = self.period_ids
# if not (period_id and journal_id):
# return 0.0
# self.cr.execute('SELECT SUM(debit) FROM account_move_line l '
# 'WHERE period_id IN %s AND journal_id IN %s ' + self.query_get_clause + ' ',
# (tuple(period_id), tuple(journal_id)))
# return self.cr.fetchone()[0] or 0.0
#
# def _sum_credit(self, period_id=False, journal_id=False):
# if journal_id and isinstance(journal_id, int):
# journal_id = [journal_id]
# if period_id and isinstance(period_id, int):
# period_id = [period_id]
# if not journal_id:
# journal_id = self.journal_ids
# if not period_id:
# period_id = self.period_ids
# if not (period_id and journal_id):
# return 0.0
# self.cr.execute('SELECT SUM(credit) FROM account_move_line l '
# 'WHERE period_id IN %s AND journal_id IN %s '+ self.query_get_clause+'',
# (tuple(period_id), tuple(journal_id)))
# return self.cr.fetchone()[0] or 0.0
def _get_start_date(self, data):
if data.get('form', False) and data['form'].get('date_from', False):
return data['form']['date_from']
return ''
def _get_end_date(self, data):
if data.get('form', False) and data['form'].get('date_to', False):
return data['form']['date_to']
return ''
def _get_filter(self, data):
if data.get('form', False) and data['form'].get('filter', False):
if data['form']['filter'] == 'filter_date':
return self._translate('Date')
return self._translate('No Filters')
def _query_get(self, cr, uid, obj='l', context=None):
fiscalyear_obj = self.pool.get('account.fiscalyear')
fiscalperiod_obj = self.pool.get('account.period')
fiscalyear_ids = []
if context is None:
context = {}
company_clause = " "
if context.get('company_id', False):
company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False)
if not context.get('fiscalyear', False):
if context.get('all_fiscalyear', False):
#this option is needed by the aged balance report because otherwise, if we search only the draft ones, an open invoice of a closed fiscalyear won't be displayed
fiscalyear_ids = fiscalyear_obj.search(cr, uid, [])
else:
fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
else:
#for initial balance as well as for normal query, we check only the selected FY because the best practice is to generate the FY opening entries
fiscalyear_ids = [context['fiscalyear']]
fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
state = context.get('state', False)
where_sale_state = ''
where_sale_lines_by_date = ''
if context.get('date_from', False) and context.get('date_to', False):
where_sale_lines_by_date = " AND " +obj+".order_id IN (SELECT id FROM sale_order WHERE date_order >= '" +context['date_from']+"' AND date_order <= '"+context['date_to']+"')"
if state:
if state.lower() not in ['all']:
where_sale_state= " AND "+obj+".order_id IN (SELECT id FROM sale_order WHERE sale_order.state = '"+state+"') "
# if context.get('period_from', False) and context.get('period_to', False) and not context.get('periods', False):
# context['periods'] = fiscalperiod_obj.build_ctx_periods(cr, uid, context['period_from'], context['period_to'])
# if context.get('periods', False):
# ids = ','.join([str(x) for x in context['periods']])
# query = obj+".state <> 'draft' AND so.period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s) AND id IN (%s)) %s %s" % (fiscalyear_clause, ids, where_sale_state, where_sale_lines_by_date)
# else:
# query = obj+".state <> 'draft' AND so.period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s)) %s %s" % (fiscalyear_clause, where_sale_state, where_sale_lines_by_date)
query = "%s %s" % (where_sale_state, where_sale_lines_by_date)
query += company_clause
return query
# def _sum_debit_period(self, period_id, journal_id=None):
# journals = journal_id or self.journal_ids
# if not journals:
# return 0.0
# self.cr.execute('SELECT SUM(debit) FROM account_move_line l '
# 'WHERE period_id=%s AND journal_id IN %s '+ self.query_get_clause +'',
# (period_id, tuple(journals)))
#
# return self.cr.fetchone()[0] or 0.0
#
# def _sum_credit_period(self, period_id, journal_id=None):
# journals = journal_id or self.journal_ids
# if not journals:
# return 0.0
# self.cr.execute('SELECT SUM(credit) FROM account_move_line l '
# 'WHERE period_id=%s AND journal_id IN %s ' + self.query_get_clause +' ',
# (period_id, tuple(journals)))
# return self.cr.fetchone()[0] or 0.0
def _get_fiscalyear(self, data):
if data.get('form', False) and data['form'].get('fiscalyear_id', False):
return pooler.get_pool(self.cr.dbname).get('account.fiscalyear').browse(self.cr, self.uid, data['form']['fiscalyear_id']).name
return ''
def _get_company(self, data):
if data.get('form', False) and data['form'].get('chart_account_id', False):
return pooler.get_pool(self.cr.dbname).get('account.fiscalyear').browse(self.cr, self.uid, data['form']['fiscalyear_id']).company_id.name
return ''
def _get_currency(self, data):
if data.get('form', False) and data['form'].get('chart_account_id', False):
return pooler.get_pool(self.cr.dbname).get('account.fiscalyear').browse(self.cr, self.uid, data['form']['fiscalyear_id']).company_id.currency_id.symbol
return ''
| UTF-8 | Python | false | false | 7,578 | py | 149 | common_report_header.py | 50 | 0.581948 | 0.577857 | 0 | 148 | 50.195946 | 220 |
wm-public/sge | 11,776,800,365,823 | 677d115e8eb60b93bb1c762b756bcdab189bf215 | b307b5c5586d9b1a8b7e9d64024c078e2f185a3f | /personal_log/urls.py | 450a3a49144be7d364b15ce4efb2a46aeb01916e | [] | no_license | https://github.com/wm-public/sge | d415f12c48afc7f9cd63b3a0f8348d6959c97c2d | 34901fc03d27accd1c7bd92983248c7a64b05843 | refs/heads/master | 2018-10-14T01:21:24.117757 | 2018-10-03T16:18:57 | 2018-10-03T16:18:57 | 134,367,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.conf.urls import url
from personal_log import views
urlpatterns = [
# url(r'^update/(?P<person_id>\d+)/(?P<is_patient>\d+)/$', views.personal_log_update, name='personal_log_update'),
]
| UTF-8 | Python | false | false | 202 | py | 220 | urls.py | 135 | 0.683168 | 0.683168 | 0 | 6 | 32.666667 | 118 |
smetanadvorak/myo-python | 11,355,893,560,896 | b06e4c080a9ab4a1861b50cd649a910b166b2c25 | e0231fcdd20bbcb13668cbce226a63af360c5d1b | /myo/macaddr.py | 25b53cf1df490470304c14934fc78f0f44e3c264 | [
"MIT"
] | permissive | https://github.com/smetanadvorak/myo-python | ee7e90fa07a71481c41469356ecdef9895d887e7 | 35fd8fe3f577e8e4bd1bd58a75fa2f4d56969997 | refs/heads/master | 2022-06-08T19:08:25.243283 | 2020-05-04T15:16:39 | 2020-05-04T15:16:39 | 259,960,172 | 0 | 0 | MIT | true | 2020-04-29T15:09:53 | 2020-04-29T15:09:52 | 2020-04-26T15:41:45 | 2019-10-12T22:50:06 | 1,613 | 0 | 0 | 0 | null | false | false | # The MIT License (MIT)
#
# Copyright (c) 2015-2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import six
MAX_VALUE = (16 ** 12 - 1)
def encode(value):
"""
Encodes the number *value* to a MAC address ASCII string in binary form.
Raises a #ValueError if *value* is a negative number or exceeds the MAC
address range.
"""
if value > MAX_VALUE:
raise ValueError('value {!r} exceeds MAC address range'.format(value))
if value < 0:
raise ValueError('value must not be negative')
# todo: convert to the right byte order. the resulting
# mac address is reversed on my machine compared to the
# mac address displayed by the hello-myo SDK sample.
# See issue #7
string = ('%x' % value).rjust(12, '0')
assert len(string) == 12
result = ':'.join(''.join(pair) for pair in zip(*[iter(string)]*2))
return result.upper()
def decode(bstr):
"""
Decodes an ASCII encoded binary MAC address tring into a number.
"""
bstr = bstr.replace(b':', b'')
if len(bstr) != 12:
raise ValueError('not a valid MAC address: {!r}'.format(bstr))
try:
return int(bstr, 16)
except ValueError:
raise ValueError('not a valid MAC address: {!r}'.format(bstr))
class MacAddress(object):
"""
Represents a MAC address. Instances of this class are immutable.
"""
def __init__(self, value):
if isinstance(value, six.integer_types):
if value < 0 or value > MAX_VALUE:
raise ValueError('value {!r} out of MAC address range'.format(value))
elif isinstance(value, six.string_to_int):
if isinstance(value, six.text_type):
value = value.encode('ascii')
value = decode(value)
else:
msg = 'expected string, bytes or int for MacAddress, got {}'
return TypeError(msg.format(type(value).__name__))
self._value = value
self._string = None
def __str__(self):
if self._string is None:
self._string = encode(self._value)
return self._string
def __repr__(self):
return '<MAC {}>'.format(self)
@property
def value(self):
return self._value
| UTF-8 | Python | false | false | 3,097 | py | 13 | macaddr.py | 8 | 0.691314 | 0.682919 | 0 | 97 | 30.927835 | 78 |
tma5/FreeTakServer | 2,585,570,337,998 | b8a145901c3bb09f90e99ea14ff254b01df958ec | c54af0739246a1cda2b4642d70cd3b89dd6ad77c | /Old/CoTtest.py | c188c69a8afe5eb8979f1bc0cd69ffb9ae8dd3e3 | [
"MIT",
"EPL-1.0"
] | permissive | https://github.com/tma5/FreeTakServer | 043e2b2e9c361937edb3d12db5201328088df618 | 794eee7cc0086d5d54193b2033fab2396b90b0e2 | refs/heads/master | 2023-02-27T01:16:02.784697 | 2020-06-05T01:37:50 | 2020-06-05T01:37:50 | 269,503,190 | 0 | 0 | MIT | true | 2020-06-05T01:33:32 | 2020-06-05T01:33:32 | 2020-05-21T19:56:50 | 2020-05-16T19:45:07 | 9,053 | 0 | 0 | 0 | null | false | false | import datetime as dt
import uuid
import xml.etree.ElementTree as ET
import socket
import logging
logger = logging.getLogger("django")
ID = {
"pending": "p",
"unknown": "u",
"assumed-friend": "a",
"friend": "f",
"neutral": "n",
"suspect": "s",
"hostile": "h",
"joker": "j",
"faker": "f",
"none": "o",
"other": "x"
}
DIM = {
"space": "P",
"air": "A",
"land-unit": "G",
"land-equipment": "G",
"land-installation": "G",
"sea-surface": "S",
"sea-subsurface": "U",
"subsurface": "U",
"other": "X"
}
DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ"
class CursorOnTarget:
def atoms():
timer = dt.datetime
now = timer.utcnow()
zulu = now.strftime(DATETIME_FMT)
stale_part = now.minute + 1
if stale_part > 59:
stale_part = stale_part - 60
stale_now = now.replace(minute=stale_part)
stale = stale_now.strftime(DATETIME_FMT)
cot_xml ='''
<?xml version="1.0" standalone="yes"?>
<event
version="2.0"
uid="J-01334"
type="a-.-G-E-W-O"
time="{0}"
start="{0}"
stale="{1}"
how="m-i">
<detail></detail>
<point
lat="30.0090027"
lon="-85.9578735"
hae="-42.6"
ce="45.3"
le="99.5"/>
</event>
'''.format(zulu, stale)
f = open("/home/natha/TAK/xmlfile.xml", "a")
f.write(cot_xml)
f.close() | UTF-8 | Python | false | false | 1,353 | py | 47 | CoTtest.py | 40 | 0.529933 | 0.497413 | 0 | 68 | 18.911765 | 52 |
kkahloots/Rethinking_Data_Effeient_GANs | 13,082,470,426,417 | c611f1ee0be5f7d5e9097706be6b97e9b84514a4 | a1b7be1e987a7aaf6beb96da9c6b0f4d6140c3f2 | /augmentation/Cutout.py | cf4ae37da9c4717171890ca3db7185ae255c4463 | [] | no_license | https://github.com/kkahloots/Rethinking_Data_Effeient_GANs | c64c2aa9d7ff1eb619e92761e223021ea6bddaeb | 7265d7e5021d03e359ab50c9190ca416161ae9c5 | refs/heads/master | 2023-02-28T02:04:22.859682 | 2021-02-04T11:57:44 | 2021-02-04T11:57:44 | 320,330,900 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import tensorflow as tf
import tensorflow_addons as tfa
from augmentation.Coloring import adjust_color
import numpy as np
import cv2
def cutout(images, **kwargs):
images = images * kwargs['mask']
#dbatch = dilation2d(images)
#condition = tf.equal(images, 0)
#images = tf.where(condition, dbatch, images)
#images = tfa.image.equalize(images)
return inpaint(images, kwargs['mask'])
def patch(images, **kwargs):
case_true = tf.random.shuffle(images)
images = images * kwargs['mask']
condition = tf.equal(images, 0)
images = tf.where(condition, case_true, images)
images = tfa.image.equalize(images)
return adjust_color(tfa.image.equalize(images),5)
def inpaint(images, masks):
def _py_inpaint(images, masks):
imgs = []
radius = images.shape[1]//10
for i in range(len(images)):
msk = masks[i].numpy()
ix = np.where(msk == 0)
msk[ix] = 255
ix = np.where(msk == 1)
msk[ix] = 0
msk = cv2.cvtColor(cv2.cvtColor(msk.astype(np.uint8), cv2.IMREAD_COLOR), cv2.COLOR_BGR2GRAY)
imgs += [cv2.inpaint(cv2.cvtColor(
images[i].numpy().astype(np.uint8), cv2.IMREAD_COLOR), msk, radius, flags=cv2.INPAINT_TELEA)]
return np.array(imgs)
return tf.py_function(_py_inpaint, [images, masks], tf.float32)
def dilation2d(img4D):
b, h, w, c = img4D.get_shape().as_list()
kernel = tf.ones((h//5, h//5, c))
output4D = tf.nn.dilation2d(img4D, filters=kernel, strides=(1,1,1,1), dilations=(1,1,1,1),
data_format='NHWC', padding="SAME")
output4D = output4D - tf.ones_like(output4D)
return output4D
def rand_mask(batch_size, height, width, ratio=0.25):
cutout_size = tf.cast(tf.cast((width, height), tf.float32) * ratio + 0.5, tf.int32)
offset_x = tf.random.uniform([batch_size, 1, 1], maxval=width + (1 - cutout_size[0] % 2), dtype=tf.int32)
offset_y = tf.random.uniform([batch_size, 1, 1], maxval=height + (1 - cutout_size[1] % 2), dtype=tf.int32)
grid_batch, grid_x, grid_y = tf.meshgrid(tf.range(batch_size, dtype=tf.int32), tf.range(cutout_size[0], dtype=tf.int32), tf.range(cutout_size[1], dtype=tf.int32), indexing='ij')
cutout_grid = tf.stack([grid_batch, grid_x + offset_x - cutout_size[0] // 2, grid_y + offset_y - cutout_size[1] // 2], axis=-1)
mask_shape = tf.stack([batch_size, width, height])
cutout_grid = tf.maximum(cutout_grid, 0)
cutout_grid = tf.minimum(cutout_grid, tf.reshape(mask_shape - 1, [1, 1, 1, 3]))
mask = tf.maximum(1 - tf.scatter_nd(cutout_grid, tf.ones([batch_size, cutout_size[0], cutout_size[1]], dtype=tf.float32), mask_shape), 0)
return tf.expand_dims(mask, axis=3)
| UTF-8 | Python | false | false | 2,766 | py | 25 | Cutout.py | 13 | 0.62726 | 0.592552 | 0 | 68 | 39.676471 | 181 |
simasima121/punchstarter | 6,562,710,038,984 | 89eae557a3804716f97a765ff4c298e8ed64f486 | 68c1bfbd70a8e2ea24b1b8907aecf58727d4afe9 | /punchstarter/__init__.py | fa604d90369c53dc8315fe6a0c9d9c9f08afd9ba | [] | no_license | https://github.com/simasima121/punchstarter | 72916435dfaf68d31b363201e6793f69f3939dd3 | 23601d2abedfbf137c7e584a505360d3a5072a5c | refs/heads/master | 2021-01-10T03:16:39.306658 | 2016-03-16T13:01:15 | 2016-03-16T13:01:15 | 54,031,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from flask import Flask
from flask.ext.script import Manager
app = Flask(__name__)
manager = Manager(app)
@app.route("/")
def hello():
return "Hello World!" | UTF-8 | Python | false | false | 162 | py | 1 | __init__.py | 1 | 0.691358 | 0.691358 | 0 | 9 | 17.111111 | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.