text
stringlengths 8
6.05M
|
|---|
NM = input()
N, M = int(NM.split()[0]), int(NM.split()[1])
dms = set([])
bms = set([])
for _ in range(N):
dms.add(input())
for _ in range(M):
bms.add(input())
dbms = dms & bms
dbms = list(dbms)
print(len(dbms))
dbms.sort()
for i in dbms:
print(i)
# Done
|
import pygame
import setup
import constants as c
import time
class Coin(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.sprite_sheet = setup.picture['item_objects']
self.frame = []
self.set_frame()
self.frame_index = 0
#TODO 不知道是啥
self.animation_timer = 0
self.state = c.SPIN
self.image = self.frame[self.frame_index]
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y - 5
self.gravity = 1
self.v_y = -15
self.height = self.rect.bottom - 5
#TODO score group
def get_image(self, x, y, width, height):
image = pygame.Surface([width, height])
rect = image.get_rect()
image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))
image.set_colorkey(c.BLACK)
image = pygame.transform.scale(image,
(int(rect.width * c.SIZE_MULTIPLIER),
int(rect.height * c.SIZE_MULTIPLIER)))
return image
def set_frame(self):
self.frame.append(self.get_image(52, 113, 8, 14))
self.frame.append(self.get_image(4, 113, 8, 14))
self.frame.append(self.get_image(20, 113, 8, 14))
self.frame.append(self.get_image(36, 113, 8, 14))
def update(self):
#self.current_time = time.time()
if self.state == c.SPIN:
self.spinning_state()
def spinning_state(self):
self.image = self.frame[self.frame_index]
self.rect.y += self.v_y
self.v_y += self.gravity
#if (self.current_time - self.animation_timer) > 80:
if self.frame_index < 3:
self.frame_index += 1
else:
self.frame_index = 0
#self.animation_timer = self.current_time
if self.rect.bottom > self.height:
self.kill()
|
import asyncio
import mqttools
import logging
async def handle_messages(client):
while True:
topic, message = await client.messages.get()
print(f'Got {message} on {topic}.')
if topic is None:
print('Connection lost.')
break
async def reconnector():
client = mqttools.Client('localhost',
1883,
subscriptions=['foobar'],
connect_delays=[1, 2, 4, 8])
while True:
await client.start()
await handle_messages(client)
await client.stop()
logging.basicConfig(level=logging.INFO)
asyncio.run(reconnector())
|
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('publico.urls', namespace="publico")),
path('admin/', admin.site.urls),
path('usuario/', include('usuario.urls')),
path('venta/', include('venta.urls', namespace="app1")),
path('tinymce/', include('tinymce.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
import threading
import Globals
from Connect import *
class Motor(threading.Thread):
# Initialize thread and Motor instance attributes
def __init__(self):
threading.Thread.__init__(self)
self.killReceived = False
self.x = 0
self.y = 1
self.rightMotor = 0
self.leftMotor = 1
self.port = 0
self.serial = None
# Start thread
def run(self):
while not self.killReceived:
while not Globals.joyConnected:
continue
Connect.connectMotor(self)
while not self.killReceived:
if not self.updatePWM():
Connect.close(self.serial)
logging.info("Could not write data over serial")
break
def updatePWM(self):
Globals.lock.acquire()
writeWithSuccess = True
if self.x != Globals.coordinates['x'] or self.y != Globals.coordinates['y']:
self.x = Globals.coordinates['x']
self.y = Globals.coordinates['y']
#coordinates = Globals.coordinates
#self.transformXYtoM(coordinates)
print(str(self.x) + ',' + str(self.y))
writeWithSuccess = Connect.write(self.serial,[self.x,self.y])
else:
Globals.lock.wait()
logging.info("Coordinates' data not changed")
Globals.lock.release()
return writeWithSuccess
def transformXYtoM(self, coordinates):
self.rightMotor = coordinates['x']
self.leftMotor = coordinates['y']
|
# -*- coding: utf-8 -*-
import networkx as nx
import nx_multi_shp
import os
from osgeo import ogr
def convert_shp_to_graph(input_shp, directed, multigraph, parallel_edges_attribute):
"""Converts a shapefile to networkx graph object in accordance to the given parameters.
It can directed or undirected, simple graph or multigraph
Parameters
----------
input_shp: shapefile path
directed: 'true' or 'false'
If value is true – directed graph will be created.
If value is false - undirected graph will be created
multigraph: 'true' or 'false'
If value is true – multigraph will be created
If value is false – simple graph will be created
parallel_edges_attribute: string
Field of the shapefile which allows to distinguish parallel edges.
Note that it could be a field of different types, but all values of this attribute should be filled
Returns
-------
Graph
"""
if multigraph == 'true':
G = nx_multi_shp.read_shp(r'{0}'.format(input_shp), parallel_edges_attribute, simplify=True,
geom_attrs=True, strict=True)
else:
G = nx.read_shp(r'{0}'.format(input_shp))
if directed == 'true':
graph = G
else:
graph = G.to_undirected()
return graph
def export_path_to_shp(path_dict, multy, multy_attribute, output_workspace, G):
new_graph = nx.MultiGraph()
a = 0
for node in path_dict:
path_list = path_dict[node]
path_list.insert(0, node)
b = 0
for edge in G.edges(keys=True, data=True):
data = new_graph.get_edge_data(*edge)
Wkt = data['Wkt']
c = 0
for i in range(len(path_list) - 1):
identifier = str(a) + str(b) + str(c)
if tuple([tuple(path_list[i]), tuple(path_list[i + 1])]) == tuple([edge[0], edge[1]]):
new_graph.add_edge(edge[0], edge[1], identifier, Name=edge[2], ident=identifier, Wkt=Wkt)
elif tuple([tuple(path_list[i + 1]), tuple(path_list[i])]) == tuple([edge[0], edge[1]]):
new_graph.add_edge(edge[0], edge[1], identifier, Name=edge[2], ident=identifier, Wkt=Wkt)
c += 1
b += 1
a += 1
if multy == 'true':
nx_multi_shp.write_shp(new_graph, 'ident', output_workspace)
else:
nx.write_shp(new_graph, output_workspace)
def create_cpg(shapefile):
with open('{}.cpg'.format(shapefile), 'w') as cpg:
cpg.write('cp1251')
def process_layer(layer):
grouped_features = {}
for feature in layer:
feature_name = feature.GetField('NAME')
if feature_name in grouped_features:
grouped_features[feature_name] += [feature]
else:
grouped_features[feature_name] = [feature]
records = []
for feature_name in grouped_features:
record = {}
record['name'] = feature_name
record['geometry'] = merge_features_geometry(grouped_features[feature_name])
record['count'] = len(grouped_features[feature_name])
records.append(record)
return records
def simplify(features):
threshold = 10
for x in range(len(features) - 1):
if not features[x]:
continue
for y in range(x + 1, len(features)):
if not features[y]:
continue
coord_lst = features[x].GetGeometryRef().GetPoints() + features[y].GetGeometryRef().GetPoints()
points = []
for coords in coord_lst:
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(*coords)
points.append(point)
if (points[0].Distance(points[2]) < threshold and points[1].Distance(points[3]) < threshold) or (
points[1].Distance(points[2]) < threshold and points[0].Distance(points[3]) < threshold):
features[y] = None
features = list(filter(lambda a: a, features))
return features
def merge_features_geometry(features):
features = simplify(features)
multiline = ogr.Geometry(ogr.wkbMultiLineString)
for feature in features:
multiline.AddGeometry(feature.GetGeometryRef())
return multiline
year = 1993
path_to_model = r'D:\Projects\diploma\model'
path_f = os.path.join(path_to_model, '{}'.format(year))
path_e = os.path.join(path_to_model, '{}_e'.format(year))
file_path = os.path.join(path_e, 'edges')
G = convert_shp_to_graph(os.path.join(path_to_model, 'shapefiles',"_{}_lines.shp".format(year)), "false", "true", "Name")
# электросетевая центральность
G1 = nx.read_shp(os.path.join(path_to_model, 'shapefiles',"_{}_points.shp".format(year)))
G1 = G1.to_undirected()
dictionary_a = {}
nodes_a = G1.nodes
for node1 in nodes_a:
t1 = nx.get_node_attributes(G1, 'Point_Type')
dictionary_a[node1] = t1[node1]
nx.set_node_attributes(G, dictionary_a, 'type')
nodes_g = nx.nodes(G)
gen = set()
node_dict = nx.get_node_attributes(G, 'type')
for node in nodes_g:
if node in node_dict:
if node_dict[node] == 'ЭС':
print(node, ' is generation')
gen.add(node)
path = nx.multi_source_dijkstra_path(G, gen)
export_path_to_shp(path, "true", 'Name', path_e, G)
create_cpg(file_path)
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open('{}.shp'.format(file_path))
src_layer = dataSource.GetLayer()
records = process_layer(src_layer)
data_source = driver.CreateDataSource(os.path.join(path_e, 'el_centrality{}.shp'.format(year)))
dst_layer = data_source.CreateLayer(file_path, None, ogr.wkbMultiLineString, options=["ENCODING=CP1251"])
field_name = ogr.FieldDefn('name', ogr.OFTString)
field_name.SetWidth(80)
dst_layer.CreateField(field_name)
dst_layer.CreateField(ogr.FieldDefn('count', ogr.OFTInteger))
for record in records:
feature = ogr.Feature(dst_layer.GetLayerDefn())
for key in record.keys():
if key == 'geometry':
feature.SetGeometry(record[key])
else:
feature.SetField(key, record[key])
dst_layer.CreateFeature(feature)
# degree centrality
DC = nx.degree_centrality(G)
nx.set_node_attributes(G, DC, 'centr')
nodes = nx.nodes(G)
d_eff = {}
for node1 in nodes:
eff = []
for node2 in nodes:
if node1 != node2:
e = nx.efficiency(G, node1, node2)
eff.append(e)
ave = float(sum(eff) / len(eff))
d_eff[node1] = ave
nx.set_node_attributes(G, d_eff, 'Effic')
# nx.write_shp(G,r"D:\Projects\diploma\model\1993")
# local_edge_connectivity
le = {}
for n in nodes_g:
if n in node_dict:
l = []
for k in gen:
if k != n:
ec = nx.edge_connectivity(G, k, n)
l.append(ec)
ave1 = float(sum(l) / len(l))
le[n] = ave1
nx.set_node_attributes(G, le, 'connect')
nx_multi_shp.write_shp(G, 'Name', path_f)
# current_flow
# edges = nx.edges(G)
# edg_dict = nx.get_edge_attributes(G, 'Weight')
# for n2 in nodes_g:
# if n2 in node_dict:
# for m in gen:
# if m != n2:
# subs = nx.edge_current_flow_betweenness_centrality_subset(G,m,n2,'True','Weight')
|
# Generated by Django 2.2.6 on 2019-11-05 09:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('work', '0012_remove_shiftedqtyextra_site'),
]
operations = [
migrations.CreateModel(
name='SiteExtra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('hab_id', models.CharField(max_length=200, unique=True)),
('approve_id', models.CharField(max_length=200)),
('village', models.CharField(max_length=200)),
('census', models.CharField(max_length=200)),
('habitation', models.CharField(max_length=200)),
('division', models.CharField(max_length=200)),
('district', models.CharField(max_length=200)),
],
),
migrations.RemoveField(
model_name='progressqtyextra',
name='hab_id',
),
migrations.RemoveField(
model_name='shiftedqtyextra',
name='hab_id',
),
migrations.AddField(
model_name='progressqtyextra',
name='site',
field=models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, to='work.SiteExtra'),
preserve_default=False,
),
migrations.AddField(
model_name='shiftedqtyextra',
name='site',
field=models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, to='work.SiteExtra'),
preserve_default=False,
),
]
|
import time, pytest
import sys,os
sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib')))
from clsCommon import Common
import clsTestService
from localSettings import *
import localSettings
from utilityTestFunc import *
import enums
class Test:
#================================================================================================================================
# @Author: Michal Zomper
# Test Name : Categories - Edit metadata
# Test description:
# create new category
# Enter category as the category manager Click on 'Actions' --> 'Edit'
# Change the category's name / description / tags - The information saved and changed successfully
#================================================================================================================================
testNum = "711"
supported_platforms = clsTestService.updatePlatforms(testNum)
status = "Pass"
timeout_accured = "False"
driver = None
common = None
# Test variables
description = "Description"
NewDescription = "New Description"
tags = "Tags,"
NewTags = "New Tags,"
categoryName = None
newCategoryName = None
#run test as different instances on all the supported platforms
@pytest.fixture(scope='module',params=supported_platforms)
def driverFix(self,request):
return request.param
def test_01(self,driverFix,env):
#write to log we started the test
logStartTest(self,driverFix)
try:
########################### TEST SETUP ###########################
#capture test start time
self.startTime = time.time()
#initialize all the basic vars and start playing
self,self.driver = clsTestService.initializeAndLoginAsUser(self, driverFix)
self.common = Common(self.driver)
self.categoryName = clsTestService.addGuidToString("Categories - Edit metadata", self.testNum)
self.newCategoryName = clsTestService.addGuidToString("New Category Name", self.testNum)
##################### TEST STEPS - MAIN FLOW #####################
writeToLog("INFO","Step 1: Going to create new category")
self.common.apiClientSession.startCurrentApiClientSession()
parentId = self.common.apiClientSession.getParentId('galleries')
if self.common.apiClientSession.createCategory(parentId, localSettings.LOCAL_SETTINGS_LOGIN_USERNAME, self.categoryName, self.description, self.tags) == False:
self.status = "Fail"
writeToLog("INFO","Step 1: FAILED to create category")
return
writeToLog("INFO","Step 2: Going to clear cache")
if self.common.admin.clearCache() == False:
self.status = "Fail"
writeToLog("INFO","Step 2: FAILED to clear cache")
return
writeToLog("INFO","Step 3: Going navigate to home page")
if self.common.home.navigateToHomePage(forceNavigate=True) == False:
self.status = "Fail"
writeToLog("INFO","Step 3: FAILED navigate to home page")
return
writeToLog("INFO","Step 4: Going navigate to edit category page")
if self.common.category.navigateToEditCategoryPage(self.categoryName) == False:
self.status = "Fail"
writeToLog("INFO","Step 4: FAILED navigate to category edit page")
return
writeToLog("INFO","Step 5: Going to edit category metadata")
if self.common.category.editCategoryMatedate(self.newCategoryName, self.NewDescription, self.NewTags) == False:
self.status = "Fail"
writeToLog("INFO","Step 5: FAILED to change category metadata")
return
writeToLog("INFO","Step 6: Going navigate to category page")
if self.common.category.navigateToCategoryPageFronEditCategoryPage(self.newCategoryName) == False:
self.status = "Fail"
writeToLog("INFO","Step 6: FAILED navigate to category page")
return
writeToLog("INFO","Step 7: Going to verify metadata change in category page")
if self.common.category.varifyCategoryMatedate(self.newCategoryName, self.NewDescription, self.NewTags) == False:
self.status = "Fail"
writeToLog("INFO","Step 7: FAILED to change category metadata")
return
##################################################################
writeToLog("INFO","TEST PASSED: 'Categories - Edit metadata' was done successfully")
# if an exception happened we need to handle it and fail the test
except Exception as inst:
self.status = clsTestService.handleException(self,inst,self.startTime)
########################### TEST TEARDOWN ###########################
def teardown_method(self,method):
try:
self.common.handleTestFail(self.status)
writeToLog("INFO","**************** Starting: teardown_method ****************")
self.common.apiClientSession.deleteCategory(self.newCategoryName)
writeToLog("INFO","**************** Ended: teardown_method *******************")
except:
pass
clsTestService.basicTearDown(self)
#write to log we finished the test
logFinishedTest(self,self.startTime)
assert (self.status == "Pass")
pytest.main('test_' + testNum + '.py --tb=line')
|
# string1 = "hello"
# string2 = "o"
# #print(string1[1:] + string1[0])
# #print(string1[0])
# print(string2[1:])
# array1 = [5, 12, 4, 6, 7, 21, 34, 6, 7, 32, 4]
# biggest = array1[0]
# for i in array1:
# # print(i)
# if i > biggest:
# biggest = i
# print(biggest)
# racecar = "racecar"
# print(racecar[1:len(racecar)-1])
# print(racecar[1:-1])
print(21%2)
|
# -*- encoding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import numpy as np
import unittest
import poketto.metrics as metrics
class TestBinaryMetrics(unittest.TestCase):
def test_invalid_input(self):
self.assertRaises(ValueError, metrics.BinaryMetrics, None, [1])
self.assertRaises(ValueError, metrics.BinaryMetrics, [1], None)
self.assertRaises(ValueError, metrics.BinaryMetrics, [1, 0], [0.4, 0.3, 0.1])
self.assertRaises(ValueError, metrics.BinaryMetrics, [1, 0, 2], [0.4, 0.3, 0.1])
self.assertRaises(ValueError, metrics.BinaryMetrics, [1, 0, 1], [1.2, 0.3, 0.1])
def test_auc(self):
y = [0, 0, 1, 1]
pred = [0.1, 0.4, 0.35, 0.8]
metric = metrics.BinaryMetrics(y, pred)
self.assertAlmostEqual(metric.metrics["auc"], 0.75)
def test_average_precision(self):
y = [0, 0, 1, 1]
pred = [0.1, 0.4, 0.35, 0.8]
metric = metrics.BinaryMetrics(y, pred)
self.assertAlmostEqual(metric.metrics["average_precision"], 0.83333333)
def test_logloss(self):
y = [0, 1, 1, 0]
pred = [0.1, 0.9, 0.8, 0.35]
metric = metrics.BinaryMetrics(y, pred)
self.assertAlmostEqual(metric.metrics["logloss"], 0.21616187)
def test_mse(self):
pass
def test_ks(self):
y = np.random.randint(0, 2, 10000)
pred = np.random.rand(10000)
metric = metrics.BinaryMetrics(y, pred)
self.assertAlmostEqual(metric.metrics["ks"], np.max(metric.tpr - metric.fpr), places=3)
self.assertAlmostEqual(metric.metrics["opt_cut"],
metric.threshold[np.argmax(metric.tpr - metric.fpr)], places=3)
metric.plot()
if __name__ == "__main__":
unittest.main()
|
from django.conf.urls.defaults import *
import apiserver as api
import organization
class TOC(api.TOC):
class Meta:
route = ''
resources = [organization.resources.Organizations]
v1 = api.API('v1')
v1.register(TOC)
v1.register(organization.resources)
v1.register(api.explorer.Explorer)
urlpatterns = patterns('',
(r'^', include(v1.urlconf)),
)
|
import unittest
from moviesnotifier import (UrlLibHtmlRetriever)
class UrlLibHtmlRetrieverTest(unittest.TestCase):
def setUp(self):
self.retriever = UrlLibHtmlRetriever()
def test_retrieveHtml(self):
url = "http://example.com/"
html = self.retriever.get(url)
self.assertIn("<h1>Example Domain</h1>", html)
|
from entity.item import Item
from entity.product import Product
from typing import Optional
class Basket:
def __init__(self):
self._items = []
def add_item(self, item: Item) -> None:
exist_item = self.get_item_from_product(item.product)
# if exist_item:
# exist_item.add_quantity(item.quantity)
# return
#
# self._items.append(item)
exist_item.add_quantity(item.quantity) if exist_item else self._items.append(
item
)
def remove_product(self, product: Product) -> bool:
exist_item = self.get_item_from_product(product)
if exist_item:
self._items.remove(exist_item)
return True
return False
def get_quantity_for_product(self, product: Product) -> int:
exist_item = self.get_item_from_product(product)
# if exist_item:
# return exist_item.quantity
#
# return 0
return exist_item.quantity if exist_item else 0
def count(self) -> int:
return len(self._items)
def get_total(self) -> float:
return sum([item.total_price() for item in self._items])
def get_item_from_product(self, product: Product) -> Optional[Item]:
for item in self._items:
if item.product == product:
return item
return None
def display(self):
for item in self._items:
print(
item.product.sku,
item.product.manufacture.get_name(),
item.product.name,
item.product.price,
item.quantity,
)
|
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Post
from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib import messages
from django.contrib.auth.models import User
from Users.models import FollowList
def home(request):
context={'post':Post.objects.all(),'followlist':user.followings.all()}
return render(request,'Blog/home.html',context)
class PostListView(ListView):
model=Post
template_name='Blog/home.html' #<app>/<model>_<viewtype>.html
context_object_name='post'
ordering=['-time']
class PostDetailView(DetailView):
model=Post
class PostCreateView(LoginRequiredMixin, CreateView):
model=Post
fields=['title','content']
def form_valid(self, form):
form.instance.author=self.request.user
messages.success(self.request,'Congrats! Your Post has been Published :)')
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UpdateView):
model=Post
template_name="Blog/post_update.html"
fields=['title','content']
def form_valid(self, form):
if form.instance.author==self.request.user:
messages.success(self.request,'Congrats! Your Post has been Edited :)')
return super().form_valid(form)
else:
messages.error (self.request,'YOU CANNOT EDIT ANYONES POST EXCEPT YOUR OWN :(')
return redirect('post_detail', form.instance.id)
#NOTE::: I COULD HAVE USED AN ALTERNATIVE:
#IMPORT UserPassesTestMixin
#from django.contrib.auth.mixins, and use it as a parameter inside PostUpdateView class
# Then create a test for this parameter as follow:
#def test_func(self):
# post=self.get_object() (get_object is a method of the Update view )
# if self.request.user==post.author:
# return True
# else:
# return False
#as suggested in Corey Playlist
class PostDeleteView(LoginRequiredMixin,UserPassesTestMixin, DeleteView):
model=Post
success_url='/'
def test_func(self):
post=self.get_object()
if self.request.user==post.author:
return True
else:
return False
def about(request):
return render(request,"Blog/about.html")
|
import sys
from datetime import datetime
from multiprocessing import Pool, cpu_count
from pathlib import Path
from functools import reduce
from fbprophet import Prophet
import pandas as pd
from tqdm import tqdm
def split_series(df):
"""Splits DataFrame into one DataFrame for each time series."""
series = []
for i in range(1, df.shape[1]):
df_i = data.iloc[:, [0, i]]
df_i.columns = ['ds', 'y']
series.append((i, df_i))
return series
def run_prophet(pair):
"""Makes Prophet model on given time series and predicts next 56 sales."""
time = datetime.now()
i, df = pair
model = Prophet(daily_seasonality=False)
model.fit(df)
train_time = datetime.now() - time
time = datetime.now()
forecast = model.make_future_dataframe(periods=56, include_history=False)
forecast = model.predict(forecast)
test_time = datetime.now() - time
return i, forecast, train_time, test_time
def get_predictions(pairs, parallel):
"""Get all predictions and print test and train times."""
# get all predictions in sorted order
pairs.sort(key=lambda x: x[0])
preds = [pair[1][['yhat']] for pair in pairs]
preds = pd.concat(preds, axis=1)
# select validation and evaluation predictions from all predictions
validation = preds[:28].T
validation.index = range(validation.shape[0])
evaluation = preds[28:].T
evaluation.index = range(evaluation.shape[0])
# print parallel train and test times
train_time = reduce(lambda x, y: x + y, [pair[2] for pair in pairs])
test_time = reduce(lambda x, y: x + y, [pair[3] for pair in pairs])
print('Train time:', train_time / (train_time + test_time) * parallel)
print('Test time:', test_time / (train_time + test_time) * parallel)
return validation, evaluation
def submit(sales, validation, evaluation, submission_path):
"""Saves predictions to storage in one file."""
# columns used by Kaggle
columns = [f'F{i}' for i in range(1, 29)]
# make validation projections in Kaggle format
id_col = pd.DataFrame(sales.columns)
validation.columns = columns
validation = pd.concat((id_col, validation), axis=1)
# make evaluation projections in Kaggle format
eval_id_col = id_col.applymap(lambda x: x[:-10] + 'evaluation')
evaluation.columns = columns
evaluation = pd.concat((eval_id_col, evaluation), axis=1)
# concatenate all projections and save to storage
projections = pd.concat((validation, evaluation), axis=0)
projections.to_csv(submission_path, index=False)
if __name__ == '__main__':
time = datetime.now()
sys.stdout = open('out.txt', 'w')
num_days = 1000
path = Path(r'D:\Users\Niels-laptop\Documents\2019-2020\Machine Learning '
r'in Practice\Competition 2\project')
submission_path = 'submission_prophet.csv'
sales = pd.read_csv(path / 'sales_train_validation.csv')
sales = sales.sort_values(by=['store_id', 'item_id'])
sales = sales.set_index('id')
sales = sales.iloc[:10, -num_days - 28:-28]
sales = sales.T
cal = pd.read_csv(path / 'calendar.csv')[['date', 'd']]
data = sales.merge(cal, left_index=True, right_on='d')
data = data[['date'] + sales.columns.tolist()]
data = split_series(data)
p = Pool(cpu_count())
print('Preparation time:', datetime.now() - time)
time = datetime.now()
predictions = list(tqdm(p.imap(run_prophet, data), total=len(data)))
p.close()
p.join()
parallel = datetime.now() - time
time = datetime.now()
validation, evaluation = get_predictions(predictions, parallel)
submit(sales, validation, evaluation, submission_path)
print('Submission time:', datetime.now() - time)
sys.stdout.close()
|
from .block_loader import BlockLoader # noqa F401
from .investigator_loader import InvestigatorLoader # noqa F401
from .observation_loader import ObservationLoader # noqa F401
from .observing_window_loader import ObservingWindowLoader # noqa F401
from .proposal_loader import ProposalLoader # noqa F401
|
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'testParametrow.ui'
##
## Created by: Qt User Interface Compiler version 5.14.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import (QCoreApplication, QDate, QDateTime, QMetaObject,
QObject, QPoint, QRect, QSize, QTime, QUrl, Qt)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont,
QFontDatabase, QIcon, QKeySequence, QLinearGradient, QPalette, QPainter,
QPixmap, QRadialGradient)
from PySide2.QtWidgets import *
class Ui_FormTestParametrow(object):
def setupUi(self, FormTestParametrow):
if not FormTestParametrow.objectName():
FormTestParametrow.setObjectName(u"FormTestParametrow")
FormTestParametrow.resize(642, 549)
self.gridLayout = QGridLayout(FormTestParametrow)
self.gridLayout.setObjectName(u"gridLayout")
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setObjectName(u"verticalLayout")
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.label = QLabel(FormTestParametrow)
self.label.setObjectName(u"label")
self.horizontalLayout.addWidget(self.label)
self.comboBoxKlasyfikatory = QComboBox(FormTestParametrow)
self.comboBoxKlasyfikatory.setObjectName(u"comboBoxKlasyfikatory")
self.comboBoxKlasyfikatory.setMinimumSize(QSize(200, 0))
self.horizontalLayout.addWidget(self.comboBoxKlasyfikatory)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
self.btnTestuj = QPushButton(FormTestParametrow)
self.btnTestuj.setObjectName(u"btnTestuj")
self.horizontalLayout_2.addWidget(self.btnTestuj)
self.btnZapiszWyniki = QPushButton(FormTestParametrow)
self.btnZapiszWyniki.setObjectName(u"btnZapiszWyniki")
self.horizontalLayout_2.addWidget(self.btnZapiszWyniki)
self.btnPokazTabele = QPushButton(FormTestParametrow)
self.btnPokazTabele.setObjectName(u"btnPokazTabele")
self.horizontalLayout_2.addWidget(self.btnPokazTabele)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.horizontalLayout_13 = QHBoxLayout()
self.horizontalLayout_13.setObjectName(u"horizontalLayout_13")
self.checkBoxCriterion = QCheckBox(FormTestParametrow)
self.checkBoxCriterion.setObjectName(u"checkBoxCriterion")
self.horizontalLayout_13.addWidget(self.checkBoxCriterion)
self.line = QFrame(FormTestParametrow)
self.line.setObjectName(u"line")
self.line.setFrameShape(QFrame.VLine)
self.line.setFrameShadow(QFrame.Sunken)
self.horizontalLayout_13.addWidget(self.line)
self.label_12 = QLabel(FormTestParametrow)
self.label_12.setObjectName(u"label_12")
self.horizontalLayout_13.addWidget(self.label_12)
self.lineEditCriterion_2 = QLineEdit(FormTestParametrow)
self.lineEditCriterion_2.setObjectName(u"lineEditCriterion_2")
self.lineEditCriterion_2.setMinimumSize(QSize(400, 0))
self.horizontalLayout_13.addWidget(self.lineEditCriterion_2)
self.verticalLayout.addLayout(self.horizontalLayout_13)
self.horizontalLayout_9 = QHBoxLayout()
self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")
self.checkBoxMaxDepth = QCheckBox(FormTestParametrow)
self.checkBoxMaxDepth.setObjectName(u"checkBoxMaxDepth")
self.horizontalLayout_9.addWidget(self.checkBoxMaxDepth)
self.line_2 = QFrame(FormTestParametrow)
self.line_2.setObjectName(u"line_2")
self.line_2.setFrameShape(QFrame.VLine)
self.line_2.setFrameShadow(QFrame.Sunken)
self.horizontalLayout_9.addWidget(self.line_2)
self.label_8 = QLabel(FormTestParametrow)
self.label_8.setObjectName(u"label_8")
self.horizontalLayout_9.addWidget(self.label_8)
self.label_14 = QLabel(FormTestParametrow)
self.label_14.setObjectName(u"label_14")
self.horizontalLayout_9.addWidget(self.label_14)
self.spinBoxMaxDepthOd = QSpinBox(FormTestParametrow)
self.spinBoxMaxDepthOd.setObjectName(u"spinBoxMaxDepthOd")
self.horizontalLayout_9.addWidget(self.spinBoxMaxDepthOd)
self.label_15 = QLabel(FormTestParametrow)
self.label_15.setObjectName(u"label_15")
self.horizontalLayout_9.addWidget(self.label_15)
self.spinBoxMaxDepthDo = QSpinBox(FormTestParametrow)
self.spinBoxMaxDepthDo.setObjectName(u"spinBoxMaxDepthDo")
self.spinBoxMaxDepthDo.setMinimum(1)
self.spinBoxMaxDepthDo.setMaximum(999)
self.horizontalLayout_9.addWidget(self.spinBoxMaxDepthDo)
self.label_16 = QLabel(FormTestParametrow)
self.label_16.setObjectName(u"label_16")
self.horizontalLayout_9.addWidget(self.label_16)
self.spinBoxMaxDepthCo = QSpinBox(FormTestParametrow)
self.spinBoxMaxDepthCo.setObjectName(u"spinBoxMaxDepthCo")
self.spinBoxMaxDepthCo.setValue(1)
self.horizontalLayout_9.addWidget(self.spinBoxMaxDepthCo)
self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(self.horizontalSpacer_7)
self.verticalLayout.addLayout(self.horizontalLayout_9)
self.horizontalLayout_10 = QHBoxLayout()
self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
self.checkBoxRandomState = QCheckBox(FormTestParametrow)
self.checkBoxRandomState.setObjectName(u"checkBoxRandomState")
self.horizontalLayout_10.addWidget(self.checkBoxRandomState)
self.line_3 = QFrame(FormTestParametrow)
self.line_3.setObjectName(u"line_3")
self.line_3.setFrameShape(QFrame.VLine)
self.line_3.setFrameShadow(QFrame.Sunken)
self.horizontalLayout_10.addWidget(self.line_3)
self.label_11 = QLabel(FormTestParametrow)
self.label_11.setObjectName(u"label_11")
self.horizontalLayout_10.addWidget(self.label_11)
self.spinBoxRandomState_2 = QSpinBox(FormTestParametrow)
self.spinBoxRandomState_2.setObjectName(u"spinBoxRandomState_2")
self.horizontalLayout_10.addWidget(self.spinBoxRandomState_2)
self.horizontalSpacer_8 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(self.horizontalSpacer_8)
self.verticalLayout.addLayout(self.horizontalLayout_10)
self.horizontalLayout_11 = QHBoxLayout()
self.horizontalLayout_11.setObjectName(u"horizontalLayout_11")
self.checkBoxMinSamplesLeaf = QCheckBox(FormTestParametrow)
self.checkBoxMinSamplesLeaf.setObjectName(u"checkBoxMinSamplesLeaf")
self.horizontalLayout_11.addWidget(self.checkBoxMinSamplesLeaf)
self.line_4 = QFrame(FormTestParametrow)
self.line_4.setObjectName(u"line_4")
self.line_4.setFrameShape(QFrame.VLine)
self.line_4.setFrameShadow(QFrame.Sunken)
self.horizontalLayout_11.addWidget(self.line_4)
self.label_10 = QLabel(FormTestParametrow)
self.label_10.setObjectName(u"label_10")
self.horizontalLayout_11.addWidget(self.label_10)
self.label_18 = QLabel(FormTestParametrow)
self.label_18.setObjectName(u"label_18")
self.horizontalLayout_11.addWidget(self.label_18)
self.spinBoxMinSamplesLeafOd = QSpinBox(FormTestParametrow)
self.spinBoxMinSamplesLeafOd.setObjectName(u"spinBoxMinSamplesLeafOd")
self.horizontalLayout_11.addWidget(self.spinBoxMinSamplesLeafOd)
self.label_19 = QLabel(FormTestParametrow)
self.label_19.setObjectName(u"label_19")
self.horizontalLayout_11.addWidget(self.label_19)
self.spinBoxMinSamplesLeafDo = QSpinBox(FormTestParametrow)
self.spinBoxMinSamplesLeafDo.setObjectName(u"spinBoxMinSamplesLeafDo")
self.spinBoxMinSamplesLeafDo.setMinimum(1)
self.spinBoxMinSamplesLeafDo.setMaximum(999)
self.horizontalLayout_11.addWidget(self.spinBoxMinSamplesLeafDo)
self.label_20 = QLabel(FormTestParametrow)
self.label_20.setObjectName(u"label_20")
self.horizontalLayout_11.addWidget(self.label_20)
self.spinBoxMinSaplesLeafCo = QSpinBox(FormTestParametrow)
self.spinBoxMinSaplesLeafCo.setObjectName(u"spinBoxMinSaplesLeafCo")
self.spinBoxMinSaplesLeafCo.setValue(1)
self.horizontalLayout_11.addWidget(self.spinBoxMinSaplesLeafCo)
self.horizontalSpacer_9 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_11.addItem(self.horizontalSpacer_9)
self.verticalLayout.addLayout(self.horizontalLayout_11)
self.horizontalLayout_12 = QHBoxLayout()
self.horizontalLayout_12.setObjectName(u"horizontalLayout_12")
self.checkBoxMinSamplesSplit = QCheckBox(FormTestParametrow)
self.checkBoxMinSamplesSplit.setObjectName(u"checkBoxMinSamplesSplit")
self.horizontalLayout_12.addWidget(self.checkBoxMinSamplesSplit)
self.line_5 = QFrame(FormTestParametrow)
self.line_5.setObjectName(u"line_5")
self.line_5.setFrameShape(QFrame.VLine)
self.line_5.setFrameShadow(QFrame.Sunken)
self.horizontalLayout_12.addWidget(self.line_5)
self.label_9 = QLabel(FormTestParametrow)
self.label_9.setObjectName(u"label_9")
self.horizontalLayout_12.addWidget(self.label_9)
self.label_21 = QLabel(FormTestParametrow)
self.label_21.setObjectName(u"label_21")
self.horizontalLayout_12.addWidget(self.label_21)
self.spinBoxMinSamplesSplitOd = QSpinBox(FormTestParametrow)
self.spinBoxMinSamplesSplitOd.setObjectName(u"spinBoxMinSamplesSplitOd")
self.horizontalLayout_12.addWidget(self.spinBoxMinSamplesSplitOd)
self.label_22 = QLabel(FormTestParametrow)
self.label_22.setObjectName(u"label_22")
self.horizontalLayout_12.addWidget(self.label_22)
self.spinBoxMinSaplesSplitDo = QSpinBox(FormTestParametrow)
self.spinBoxMinSaplesSplitDo.setObjectName(u"spinBoxMinSaplesSplitDo")
self.spinBoxMinSaplesSplitDo.setMinimum(1)
self.spinBoxMinSaplesSplitDo.setMaximum(999)
self.horizontalLayout_12.addWidget(self.spinBoxMinSaplesSplitDo)
self.label_23 = QLabel(FormTestParametrow)
self.label_23.setObjectName(u"label_23")
self.horizontalLayout_12.addWidget(self.label_23)
self.spinBoxMinSamplesSplitCo = QSpinBox(FormTestParametrow)
self.spinBoxMinSamplesSplitCo.setObjectName(u"spinBoxMinSamplesSplitCo")
self.spinBoxMinSamplesSplitCo.setValue(1)
self.horizontalLayout_12.addWidget(self.spinBoxMinSamplesSplitCo)
self.horizontalSpacer_10 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(self.horizontalSpacer_10)
self.verticalLayout.addLayout(self.horizontalLayout_12)
self.horizontalLayout_14 = QHBoxLayout()
self.horizontalLayout_14.setObjectName(u"horizontalLayout_14")
self.checkBoxSpliter = QCheckBox(FormTestParametrow)
self.checkBoxSpliter.setObjectName(u"checkBoxSpliter")
self.horizontalLayout_14.addWidget(self.checkBoxSpliter)
self.line_6 = QFrame(FormTestParametrow)
self.line_6.setObjectName(u"line_6")
self.line_6.setFrameShape(QFrame.VLine)
self.line_6.setFrameShadow(QFrame.Sunken)
self.horizontalLayout_14.addWidget(self.line_6)
self.label_13 = QLabel(FormTestParametrow)
self.label_13.setObjectName(u"label_13")
self.horizontalLayout_14.addWidget(self.label_13)
self.lineEditSpliter_2 = QLineEdit(FormTestParametrow)
self.lineEditSpliter_2.setObjectName(u"lineEditSpliter_2")
self.horizontalLayout_14.addWidget(self.lineEditSpliter_2)
self.verticalLayout.addLayout(self.horizontalLayout_14)
self.txtWyniki = QTextEdit(FormTestParametrow)
self.txtWyniki.setObjectName(u"txtWyniki")
self.verticalLayout.addWidget(self.txtWyniki)
self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.retranslateUi(FormTestParametrow)
QMetaObject.connectSlotsByName(FormTestParametrow)
# setupUi
def retranslateUi(self, FormTestParametrow):
FormTestParametrow.setWindowTitle(QCoreApplication.translate("FormTestParametrow", u"Test parametr\u00f3w klasyfikatora", None))
self.label.setText(QCoreApplication.translate("FormTestParametrow", u"Kt\u00f3ry klasyfikator testowa\u0107:", None))
self.btnTestuj.setText(QCoreApplication.translate("FormTestParametrow", u"Testuj", None))
self.btnZapiszWyniki.setText(QCoreApplication.translate("FormTestParametrow", u"Zapisz wyniki", None))
self.btnPokazTabele.setText(QCoreApplication.translate("FormTestParametrow", u"Poka\u017c tabel\u0119 bazow\u0105", None))
self.checkBoxCriterion.setText(QCoreApplication.translate("FormTestParametrow", u"Dodaj do sprawdzenia", None))
self.label_12.setText(QCoreApplication.translate("FormTestParametrow", u"criterion:", None))
self.checkBoxMaxDepth.setText(QCoreApplication.translate("FormTestParametrow", u"Dodaj do sprawdzenia", None))
self.label_8.setText(QCoreApplication.translate("FormTestParametrow", u"max_depth:", None))
self.label_14.setText(QCoreApplication.translate("FormTestParametrow", u"od:", None))
self.label_15.setText(QCoreApplication.translate("FormTestParametrow", u"do:", None))
self.label_16.setText(QCoreApplication.translate("FormTestParametrow", u"co:", None))
self.checkBoxRandomState.setText(QCoreApplication.translate("FormTestParametrow", u"Dodaj do sprawdzenia", None))
self.label_11.setText(QCoreApplication.translate("FormTestParametrow", u"random_state:", None))
self.checkBoxMinSamplesLeaf.setText(QCoreApplication.translate("FormTestParametrow", u"Dodaj do sprawdzenia", None))
self.label_10.setText(QCoreApplication.translate("FormTestParametrow", u"min_samples_leaf:", None))
self.label_18.setText(QCoreApplication.translate("FormTestParametrow", u"od:", None))
self.label_19.setText(QCoreApplication.translate("FormTestParametrow", u"do:", None))
self.label_20.setText(QCoreApplication.translate("FormTestParametrow", u"co:", None))
self.checkBoxMinSamplesSplit.setText(QCoreApplication.translate("FormTestParametrow", u"Dodaj do sprawdzenia", None))
self.label_9.setText(QCoreApplication.translate("FormTestParametrow", u"min_samples_split:", None))
self.label_21.setText(QCoreApplication.translate("FormTestParametrow", u"od:", None))
self.label_22.setText(QCoreApplication.translate("FormTestParametrow", u"do:", None))
self.label_23.setText(QCoreApplication.translate("FormTestParametrow", u"co:", None))
self.checkBoxSpliter.setText(QCoreApplication.translate("FormTestParametrow", u"Dodaj do sprawdzenia", None))
self.label_13.setText(QCoreApplication.translate("FormTestParametrow", u"splitter:", None))
# retranslateUi
|
""" File: proj04_short.py
Author: Abraham Aruguete
Purpose: So this project contains three functions which will be called by Russ' testcases. I'm actually working on writing down a pre-plan for my code instead of just rushing in there coding this time! How pleasant. I think I'm maturing. """
def compare_front(linearType1, linearType2):
""" This function compares two linear types starting from index zero. """
assert type(linearType1) == type(linearType2)
i = 0
charsSame = 0
if (linearType1[0] != linearType2[0]):
return 0
if (linearType1 == linearType2):
return len(linearType1)
if not linearType1 or not linearType2:
return 0
while ((i < len(linearType1)) and (i < len(linearType2)) and (linearType1[i] == linearType2[i])):
if(linearType1[i] == linearType2[i]):
charsSame += 1
if(charsSame == len(linearType1)):
return len(linearType1)
if(charsSame == len(linearType2)):
return len(linearType2)
i += 1
return charsSame
def compare_back(linearType1, linearType2):
"""This function compares two linear types starting from the highest index of each."""
assert type(linearType1) == type(linearType2)
if (len(linearType1) <= len(linearType2)):
indexSmaller = len(linearType1) - 1
indexLarger = len(linearType2) - 1
if not linearType1 or not linearType2:
return 0
charsSame = 0
while indexSmaller >= 0 and (linearType1[indexSmaller] == linearType2[indexLarger]):
if(linearType1[indexSmaller] == linearType2[indexLarger]):
charsSame += 1
if(indexSmaller == len(linearType1)):
return len(smallerLinear)
indexSmaller -= 1
indexLarger -= 1
return charsSame
else:
indexSmaller = len(linearType2) - 1
indexLarger = len(linearType1) - 1
if not linearType1 or not linearType2:
return 0
charsSame = 0
while indexSmaller >= 0 and (linearType2[indexSmaller] == linearType1[indexLarger]):
if(linearType2[indexSmaller] == linearType1[indexLarger]):
charsSame += 1
if(indexSmaller == len(linearType2)):
return len(smallerLinear)
indexSmaller -= 1
indexLarger -= 1
return charsSame
def primary_stress(listOfStrings):
""" This function iterates through a list of phonemes and returns the index
of the phoneme which contains the primary stress. """
assert type(listOfStrings) == list
assert listOfStrings != []
for string in listOfStrings:
assert string != ""
flag = False
for index in range(len(listOfStrings)):
if len(listOfStrings[index]) > 1:
if "1" in listOfStrings[index]:
flag = True
searchIndex = index
break
if flag:
return searchIndex
else:
return None
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 7 01:35:39 2019
@author: Anubhav
"""
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
#Classification Algorithms
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.linear_model import LogisticRegression
from sklearn import metrics as m
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.model_selection import ShuffleSplit
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt
data = pd.read_csv("bank-additional-full.csv", delimiter=";",header='infer')
data.head()
data.corr()
data.dtypes
data_new = pd.get_dummies(data, columns=['job','marital',
'education','default',
'housing','loan',
'contact','month',
'poutcome'])
data_new.y.replace(('yes', 'no'), (1, 0), inplace=True)
data_new.dtypes
data_y = pd.DataFrame(data_new['y'])
data_X = data_new.drop(['y'], axis=1)
print(data_X.columns)
print(data_y.columns)
X_train, X_test, y_train, y_test = train_test_split(data_X, data_y, test_size=0.3, random_state=2, stratify=data_y)
print (X_train.shape)
print (X_test.shape)
print (y_train.shape)
print (y_test.shape)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
|
from string import maketrans
DNA = maketrans('ACGT', 'TGCA')
def DNA_strand(string):
""" dna_strand == PEP8 (forced naming by CodeWars) """
return string.translate(DNA)
|
#!/usr/bin/python3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
def sendMail():
msg = MIMEMultipart()
# General settings
msg['from'] = 'form@example.com'
msg['to'] = 'to@example.com'
msg['subject'] = 'your_subject'
message = 'your_messages'
# add in the message body
msg.attach(MIMEText(message, 'plain'))
# Create server
server = smtplib.SMTP('yourmailserver:port')
# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print("Successfully send mail to %s:" % (msg['to']))
def spam():
min = 1
max = int(input('How much messages you want send: '))
while max >= min:
sendMail()
min += 1
spam()
|
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name = 'books'
urlpatterns = [
# ex: /readospher/
path('', views.IndexView.as_view(), name='index'),
path('books/', views.BookSearchListView.as_view(), name='book-search-list'),
path('books/top', views.BookListView.as_view(), name='book-top-list'),
path('books/recent', views.BookRecentListView.as_view(), name='book-recent-list'),
path('books/<int:pk>/', views.BookDetailView.as_view(), name='book-detail'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
import random
import scrabble_points
from wordlist import get_wordlist
FREQUENCY = {
'A': 9,
'B': 2,
'C': 2,
'D': 4,
'E': 12,
'F': 2,
'G': 3,
'H': 2,
'I': 9,
'J': 1,
'K': 1,
'L': 4,
'M': 2,
'N': 6,
'O': 8,
'P': 2,
'Q': 1,
'R': 6,
'S': 4,
'T': 6,
'U': 4,
'V': 2,
'W': 2,
'X': 1,
'Y': 2,
'Z': 1,
'__': 2
}
POINTS = {
'A': 1,
'B': 3,
'C': 3,
'D': 2,
'E': 1,
'F': 4,
'G': 2,
'H': 4,
'I': 1,
'J': 8,
'K': 5,
'L': 1,
'M': 3,
'N': 1,
'O': 1,
'P': 3,
'Q': 10,
'R': 1,
'S': 1,
'T': 1,
'U': 1,
'V': 4,
'W': 4,
'X': 8,
'Y': 4,
'Z': 10,
}
DRAW = 'D'
WORD = 'W'
PRINT = 'P'
QUIT = 'Q'
ZERO = 0
SEVEN = 0
def create_new_bag(frequency):
new_bag = scrabble_points.bag_of_letters(frequency)
return new_bag
def draw_letters(new_bag):
letters_drawn = []
for l in range(7):
# choose 7 random letters from the bag
# and append them to a new list
l = random.choice(new_bag)
letters_drawn.append(l)
# remove the 7 random letters from the bag
new_bag.remove(l)
return letters_drawn
def draw(bag_of_letters):
picks = draw_letters(bag_of_letters)
print('You draw the following letters: ',picks)
return picks
def print_summary(words_played):
'''
Name: print_summary
Parameters: dict
Return: str, str
'''
tot = sum(words_played.values())
# format total points and words played
message = 'You have a total of',tot,'points\n'
words = "\n".join("{} -- {} points".format(w, p) for w, p in words_played.items())
return words, message
def wordgame():
# new bag of letters
new_bag = create_new_bag(FREQUENCY)
wordlist = get_wordlist()
words_played = {}
total_points = 0
while True:
# ask for user input
user_input = input('Pick one of the following:\n'
+ 'D -- Draw 7 letters from the bag \n'
+ 'W -- Make a word from the letters in play \n'
+ 'P -- Print all words played so far \n'
+ 'Q -- Quit \n'
+ 'Your choice: '
)
input_uppercase = user_input.upper()
if input_uppercase == DRAW:
# check if the bag is empty
if len(new_bag) > ZERO:
try:
# pick 7 new letters
letters_in_play = draw(new_bag)
# if the bag is empty, create an exception
except IndexError:
print('The bag is empty! Game over.')
break
elif input_uppercase == WORD:
# letters the users has
print(letters_in_play)
# ask user to create a word
word = input('Create a word with the letters available to you: ')
word_upper = word.upper()
# check if the word exists in the list and if letter is in the
# letters at play
if word_upper in wordlist and [l in word_upper for l in letters_in_play if l in word_upper]:
# calculate points for the round
total_points = scrabble_points.get_word_value(word_upper,POINTS)
words_played[word_upper] = total_points
# remove each letter used from the list of letters in play
for l in word_upper:
letters_in_play.remove(l)
else:
print('Sorry. The word you chose is not valid')
# if letters in play is empty, stop the game
if len(letters_in_play) == ZERO:
break
elif input_uppercase == PRINT:
tot = sum(words_played.values())
print('You have a total of',tot,'points\n')
print("\n".join("{} -- {} points".format(w, p) for w, p in words_played.items()))
elif input_uppercase == QUIT:
print('Bye bye!')
break
else:
print('Please, select a valid choice.')
print('Thank you for playing!')
wordgame()
|
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Generates a JSON schema file to be uploaded to the JSON schema store
(https://www.schemastore.org/json/). The schema file is used by IDEs (PyCharm, VSCode, etc) to
provide intellisense when editing Pants configuration files in TOML format. It can also be used to
validate your pants.toml configuration file programmatically.
Live run:
$ ./pants help-all > all-help.json
$ ./pants run build-support/bin/generate_json_schema.py -- --all-help-file=all-help.json
"""
import argparse
import itertools
import json
import re
from typing import Any, Dict, Iterable
from packaging.version import Version
from pants.version import VERSION
GENERATED_JSON_SCHEMA_FILENAME = f"pantsbuild-{VERSION}.json"
DOCS_URL = "https://www.pantsbuild.org"
VERSION_MAJOR_MINOR = f"{Version(VERSION).major}.{Version(VERSION).minor}"
PYTHON_TO_JSON_TYPE_MAPPING = {
"str": "string",
"bool": "boolean",
"list": "array",
"int": "number",
"float": "number",
"dict": "object",
}
# Certain default values will be expanded using local runtime environment which is undesirable.
# This list may need to be extended as more options with environment specific default values are added.
ENV_SPECIFIC_OPTION_DEFAULTS = {
"pants_config_files": ["<buildroot>/pants.toml"],
"pants_subprocessdir": "<buildroot>/.pids",
"pants_distdir": "<buildroot>/dist",
"pants_workdir": "<buildroot>/.pants.d",
"local_store_dir": "$XDG_CACHE_HOME/lmdb_store",
"named_caches_dir": "$XDG_CACHE_HOME/named_caches",
}
def simplify_option_description(description: str) -> str:
"""Take only a first sentence out of a multi-sentence description without a final full stop.
There is an assumption that there are no newlines.
"""
return re.split(r"(?<=[^A-Z].[.?]) +(?=[A-Z])", description)[0].rstrip(".")
def get_description(option: dict, section: str) -> str:
"""Get a shortened description with a URL to the online docs of the given option."""
option_help: str = option["help"].lstrip("\n").split("\n")[0]
option_name: str = option["config_key"]
simplified_option_help = simplify_option_description(option_help)
url = f"{DOCS_URL}/v{VERSION_MAJOR_MINOR}/docs/reference-{section.lower()}#{option_name}"
return f"{simplified_option_help}\n{url}"
def get_default(option: dict) -> Any:
"""Get default value for an option.
Ensure options that depend on any machine specific environment are properly handled. E.g.
`"default": "<buildroot>/.pants.d"` will be expanded to the `"default": "/home/your-user.name/code/pants/.pants.d"`
which is not what we want to have in a public schema.
"""
return ENV_SPECIFIC_OPTION_DEFAULTS.get(option["config_key"], option["default"])
def build_scope_properties(ruleset: dict, options: Iterable[dict], scope: str) -> dict:
"""Build properties object for a single scope.
There are custom types (e.g. `file_option` or `LogLevel`) for which one cannot safely infer a
type, so no type is added to the ruleset. If there are choices, there is no need to provide
"type" for the schema (assuming all choices share the same type). If an option value can be
loaded from a file, a union of `string` and option's `typ` is used. Otherwise, a provided `typ`
field is used.
"""
for option in options:
properties = ruleset[scope]["properties"]
properties[option["config_key"]] = {
"description": get_description(option, scope),
"default": get_default(option),
}
if option["choices"]:
# TODO(alte): find a safe way to sort choices
properties[option["config_key"]]["enum"] = option["choices"]
else:
typ = PYTHON_TO_JSON_TYPE_MAPPING.get(option["typ"])
# TODO(alte): do we want to maintain a mapping between special options?
# `process_total_child_memory_usage` ("typ": "memory_size") -> "int"
# `engine_visualize_to` ("typ": "dir_option") -> "str"
if typ:
# options may allow providing value inline or loading from a filepath string
if option.get("fromfile"):
properties[option["config_key"]]["oneOf"] = [{"type": typ}, {"type": "string"}]
else:
properties[option["config_key"]]["type"] = typ
# TODO(alte): see if one safely codify in the schema the fact that we support `.add` and `.remove`
# semantics on arrays; e.g. `extra_requirements.add` can either be an array or an object
# {add|remove: array}
return ruleset
def main() -> None:
args = get_args()
with open(args.all_help_file) as fh:
all_help = json.load(fh)["scope_to_help_info"]
# set GLOBAL scope that is declared under an empty string
all_help["GLOBAL"] = all_help[""]
del all_help[""]
# build ruleset for all scopes (where "scope" is a [section]
# in the pants.toml configuration file such as "pytest" or "mypy")
ruleset = {}
for scope, options in all_help.items():
ruleset[scope] = {
"description": all_help[scope]["description"],
"type": "object",
"properties": {},
}
ruleset = build_scope_properties(
ruleset=ruleset,
options=itertools.chain(options["basic"], options["advanced"]),
scope=scope,
)
schema: Dict[str, Any] = dict()
schema["$schema"] = "http://json-schema.org/draft-04/schema#"
schema["description"] = "Pants configuration file schema: https://www.pantsbuild.org/"
schema["properties"] = ruleset
# custom plugins may have own configuration sections
schema["additionalProperties"] = True
schema["type"] = "object"
with open(GENERATED_JSON_SCHEMA_FILENAME, "w") as fh:
fh.write(json.dumps(schema, indent=2, sort_keys=True))
def create_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Generates JSON schema file to be used in IDEs for Pants configuration files in TOML format."
)
parser.add_argument(
"--all-help-file",
help="Input file with the contents produced by the `./pants help-all` command.",
required=True,
)
return parser
def get_args():
return create_parser().parse_args()
if __name__ == "__main__":
main()
|
from django.contrib import admin
from .models import Board, User, SelectKnight, Election, Expedition, Game, GameHistory # 추가
from .models import Knight # 추가
# Register your models here.
class KnightAdmin(admin.ModelAdmin):
list_display = ('knightId', 'name', 'evlYn',)
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'joinYn', 'readyYn', 'assinKnightId','hosuYn',)
class GameHistoryAdmin(admin.ModelAdmin):
list_display = ('gameId', 'username','winYn','succYn', 'knightId',)
class GameAdmin(admin.ModelAdmin):
list_display = ('gameId', 'joinUserCnt', 'expeditionSeq', 'completeYn',)
class ExpeditionAdmin(admin.ModelAdmin):
list_display = ('gameId', 'expeditionSeq', 'expeditionUserCnt', 'succUserCnt', 'succYn', 'completeYn', 'usernamelist',)
admin.site.register(Knight,KnightAdmin) # 추가
admin.site.register(Expedition,ExpeditionAdmin) # 추가
admin.site.register(User,UserAdmin) # 추가
admin.site.register(GameHistory,GameHistoryAdmin) # 추가
admin.site.register(Game,GameAdmin) # 추가
admin.site.register(SelectKnight) # 추가
admin.site.register(Election) # 추가
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-30 11:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalogues', '0003_auto_20170830_1430'),
]
operations = [
migrations.AlterField(
model_name='form_four_news_portal',
name='document_file',
field=models.FileField(blank=True, upload_to='uploads/'),
),
migrations.AlterField(
model_name='form_three_news_portal',
name='document_file',
field=models.FileField(blank=True, upload_to='uploads/'),
),
migrations.AlterField(
model_name='form_two_news_portal',
name='document_file',
field=models.FileField(blank=True, upload_to='uploads/'),
),
]
|
from __future__ import unicode_literals
from django.db import models
import re, bcrypt
NAME_REGEX = re.compile(r'^[a-zA-Z\s]+$')
USERNAME_REGEX = re.compile(r'^[\w\s]+$')
SPACE_REGEX = re.compile('.*\s')
class UserManager(models.Manager):
def validate_reg(self, input):
errors = []
name = input['name']
username = input['username']
pw = input['pw']
pw_conf = input['pw_confirm']
if not name or name.isspace():
errors.append(("Please enter your name!","name"))
elif len(name) < 3 or not NAME_REGEX.match(name):
errors.append(("Name is invalid!","name"))
if not username or username.isspace():
errors.append(("Please enter your username!","username"))
elif len(username) < 3 or not USERNAME_REGEX.match(username):
errors.append(("Username is invalid!","username"))
elif self.filter(username__iexact=username).exists():
errors.append(("Username already exists!","register"))
if not pw or pw.isspace():
errors.append(("Please create a new password.","pw"))
elif SPACE_REGEX.match(pw) or len(pw) < 8:
errors.append(("Please create a new password as per the criteria.","pw"))
if not pw == pw_conf:
errors.append(("The passwords entered don't match.","confirm"))
if errors:
return (False, errors)
else:
hashed = bcrypt.hashpw(pw.encode(), bcrypt.gensalt())
user = self.create(name=name, username=username, pw_hash=hashed)
return (True, user)
def validate_log(self, input):
errors = []
user = User.objects.filter(username=input['username'])
if user.exists():
hashed_pw = user[0].pw_hash.encode()
input_pw = input['pw'].encode()
if bcrypt.checkpw(input_pw, hashed_pw):
return (True, user[0])
else:
errors.append(("Incorrect password!","login_pw"))
else:
errors.append(("Username doesn't exist!","login_user"))
return (False, errors)
class User(models.Model):
name = models.CharField(max_length=55)
username = models.CharField(max_length=55)
pw_hash = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
def __unicode__(self):
return self.name
|
from marshmallow import Schema, fields, validate
from settings.database import session
from utils.serializers import BaseSchema
# Create your serializers here.
class AuthenticationSchema(Schema):
username = fields.Str(
required=True,
allow_none=False,
validate=validate.Length(min=4)
)
password = fields.Str(
required=True,
allow_none=False,
validate=validate.Length(min=4)
)
class ToKenBlackListSchema(BaseSchema):
jti = fields.Str(required=True, allow_none=False)
token_type = fields.Str(required=True, allow_none=False,
validate=validate.Length(max=10))
user_identity = fields.Str(
required=True, allow_none=False, validate=validate.Length(max=50))
revoked = fields.Boolean(default=False, allow_none=False)
expires = fields.DateTime(dump_only=True)
|
import os,sys,time,traceback as tb,re,json
from pprint import pprint
data = ''.join(sys.stdin.xreadlines())
def get_tuple(cursor, name, tup, skip_ws=True):
if skip_ws: ws,cursor = get_ws(cursor)
ret = {}
cursor0 = ret['start'] = cursor
while data.startswith(tup, cursor):
cursor += 1
pass
ret['tok']=data[cursor0:cursor]
if not ret['tok']:
ret['err'] = 'not found'
return ret,cursor
def get_ws(cursor):
ret = {}
cursor0 = ret['start'] = cursor
while data.startswith(tuple(' \t\r\n\v'),cursor):
cursor += 1
pass
ret['ws']=data[cursor0:cursor]
return ret,cursor
def get_id(cursor, skip_ws=True):
return get_tuple(cursor, 'id',
tuple('abcdefghijklmnopqrstuvwxyz'+
'ABCDEFGHIJKLMNOPQRSTUVWXYX'+
'0123456789_'), skip_ws=skip_ws)
def get_int(cursor, skip_ws=True):
return get_tuple(cursor, 'int',
tuple('0123456789'))
def get_xstr(cursor, tok_str, skip_ws=True):
if skip_ws: x,cursor = get_ws(cursor)
ret = {}
cursor0 = ret['start'] = cursor
if data.startswith(tok_str, cursor):
cursor += len(tok_str)
pass
ret['str']=data[cursor0:cursor]
if not ret['str']:
ret['err'] = 'not found'
return ret,cursor
def get_str_url_encoded(cursor,skip_ws=True):
from urllib import unquote
if skip_ws: x,cursor = get_ws(cursor)
cursor0=cursor
if not data.startswith('"',cursor):
return dict(err='not found'), cursor
n = data.find('"',cursor+1)
if n == -1:
return ('unbound string',''),cursor
ret = {}
ret['start']=cursor0
ret['str'] = unquote(data[cursor+1:n])
return ret,n+1
get_str_url=get_str_url_encoded
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 20 19:00:59 2014
@author: jgr42_000
"""
from __future__ import division
import numpy as np
#import operator as op
import itertools
#from collections import OrderedDict
import copy
import os
import argparse
import cPickle
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import Normalize
#from sklearn.pipeline import Pipeline
from sklearn import preprocessing
from sklearn import cross_validation
from sklearn import svm
from sklearn import tree
from sklearn.linear_model import LinearRegression # Ridge
from sklearn import gaussian_process
from sklearn import neighbors
from sklearn.ensemble import GradientBoostingRegressor
from scipy.optimize import minimize
#from scipy.optimize import minimize
from scipy.optimize import basinhopping
#from scipy import optimize
def make_meta(data_dict, doe_set, data_opts, fit_opts):
obj_inp = fit_opts['obj_spec']
obj_data = data_dict[obj_inp].get_surro_data()
obj_err = np.square(data_dict[obj_inp].get_surro_err())
reac_co_data = data_dict['reac_coeff'].data_fit[:,1] # At some point, will want to make this for all bu steps | TAG: Improve
void_w_data = data_dict['void_worth'].data_fit[:,1]
max_cycle_data = data_dict['reac'].max_bu_data
X_t = doe_set['doe_scaled']
sur_type = fit_opts['sur_type']
theta_opt = fit_opts['theta_opt']
if theta_opt == 'custom':
theta_bounds = fit_opts['theta_bounds']
if fit_opts['num_theta'] == 'single':
num_feat = 1
elif fit_opts['num_theta'] == 'all':
num_feat = X_t.shape[-1]
else:
raise Exception('{} is not a supported option for num_theta!'.format(fit_opts['num_theta']))
theta_guess = [theta_bounds['guess']] * num_feat
theta_lowb = [theta_bounds['low']] * num_feat
theta_upb = [theta_bounds['up']] * num_feat
# select theta type for obj_val only for now
if sur_type == 'interp':
if theta_opt == 'default':
obj_val = gaussian_process.GaussianProcess()
elif theta_opt == 'custom':
obj_val = gaussian_process.GaussianProcess(theta0 = theta_guess, thetaL = theta_lowb,
thetaU = theta_upb)
else:
raise Exception('{} is not a valid theta_opt specification!'.format(theta_opt))
xval_obj_val = copy.deepcopy(obj_val)
elif sur_type == 'regress':
if theta_opt == 'default':
obj_val = gaussian_process.GaussianProcess(nugget = obj_err)
xval_obj_val = gaussian_process.GaussianProcess(nugget = np.mean(obj_err)) # Could make this np.max() to be conservative | TAG: CHANGE
elif theta_opt == 'custom':
obj_val = gaussian_process.GaussianProcess(nugget = obj_err, theta0=theta_guess,
thetaL = theta_lowb, thetaU = theta_upb)
xval_obj_val = gaussian_process.GaussianProcess(nugget = np.mean(obj_err), theta0=theta_guess,
thetaL = theta_lowb, thetaU = theta_upb)
else:
raise Exception('{} is not a valid theta_opt specification!'.format(theta_opt))
else:
raise Exception('{} is not a valid sur_type option!'.format(sur_type))
reac_co = gaussian_process.GaussianProcess()
void_w = gaussian_process.GaussianProcess()
max_cycle = gaussian_process.GaussianProcess()
#test = neighbors.KNeighborsRegressor()
#test = GradientBoostingRegressor()
# with open(data_opts['data_fname'], 'rb') as datf:
# run_data = cPickle.load(datf)
# scal = preprocessing.MinMaxScaler()
# X_t = scal.fit_transform(run_data['reac'].fit_dv_mtx)
#test = svm.SVR(C=1.0, epsilon=0.00)a
#test = Ridge()
#test = tree.DecisionTreeRegressor()
obj_val.fit(X_t, obj_data)
reac_co.fit(X_t, reac_co_data)
void_w.fit(X_t, void_w_data)
max_cycle.fit(X_t, max_cycle_data)
fit_dict = {'X_t':X_t,'obj_val':obj_val, 'reac_co':reac_co, 'void_w':void_w, \
'max_cycle':max_cycle, 'xval_obj_val':xval_obj_val}
# If using a regressing GPM, build a re-interpolator for use in search-and-infill
if sur_type == 'regress':
# Start by getting the rGPM data at each DOE location
igpm_obj_val_data = np.apply_along_axis(obj_val.predict, 1, X_t).sum(1)
# Now, use this as the data to fit with a new interpolating GPM (iGPM)
# that uses the same hyperparameters as the rGPM
igpm_obj_val = gaussian_process.GaussianProcess(theta0=obj_val.theta_)
igpm_obj_val.fit(X_t, igpm_obj_val_data)
fit_dict.update({'igpm_obj_val':igpm_obj_val})
with open(data_opts['fit_fname'], 'wb') as fitf:
cPickle.dump(fit_dict, fitf, 2)
return fit_dict
# NOTE: should plot with all values save the x-axis at 1, not 0
# x_plot = np.empty([1000,4])
# x_plot[:,0:3] = X_t[0,0:3]
# x_plot[:,3] = np.linspace(0.0,1.0,1000)
# y_pred, MSE = test.predict(x_plot, eval_MSE=True)
# sigma = np.sqrt(MSE)
# fig = plt.figure()
# plt.plot(X_t[0:3,3], run_data['reac'].data_fit[0:3], 'r.', markersize=10, label=u'Observations')
# plt.plot(x_plot[:,3], y_pred, 'b-', label=u'Prediction')
# plt.fill(np.concatenate([x_plot[:,3],x_plot[:,3][::-1]]), \
# np.concatenate([y_pred - 1.96 * sigma, \
# (y_pred + 1.96 * sigma)[::-1]]), \
# alpha=.5, fc='b', ec='None', label='95% confidence interval')
# plt.xlabel('Enrichment (fraction of max)')
# plt.ylabel('Reactivity [pcm]')
# plt.legend(loc='upper left')
# fig.savefig('reac_fit_err.png', dpi=600.0)
# x0 = np.ones(4)
# mybounds = [(0.0,1.0),(0.0,1.0),(0.0,1.0),(0.0,1.0)]
# def positive_pred(X):
# return -1.0 * test.predict(X)
## res = minimize(test.predict, x0, method='nelder-mead', options={'disp':True})
# res = minimize(positive_pred, x0, method ='L-BFGS-B', bounds = mybounds, jac = False, options={'disp':True})
# #test = Pipeline([('minmx', preprocessing.MinMaxScaler()),('svm_r', svm.SVR(C=1.0, epsilon=0.001))])
# #test = Pipeline([('minmx', preprocessing.MinMaxScaler()),('rdge', Ridge())])
# #test.fit(run_data['reac'].fit_dv_mtx, run_data['reac'].data_fit)
# print res.x
# pass
def eval_meta(data_dict, fit_dict, data_opts, fit_opts):
obj_inp = fit_opts['obj_spec']
obj_data = data_dict[obj_inp].get_surro_data()
obj_gpm = fit_dict['xval_obj_val'] #fit_dict['obj_val']
X_t = fit_dict['X_t']
k_num = fit_opts['num_k_folds']
# Modified to work with GPM regression by using an average 'nugget' instead of pointwise nugget
scores = cross_validation.cross_val_score(obj_gpm, X_t, obj_data, cv = k_num)
fit_dict.update({'scores':scores})
# Return coefficient of determination (R^2) value of the fit
# Best possible score = 1.0, lower values worse
with open(data_opts['fit_fname'], 'wb') as fitf:
cPickle.dump(fit_dict, fitf, 2)
return fit_dict
def make_plots(dv_dict, data_opts, plot_opts):
type_opt = plot_opts['type']
# Unpickle the data
with open(data_opts['data_fname'], 'rb') as datf:
run_data = cPickle.load(datf)
with open(data_opts['fit_fname'], 'rb') as datf:
fit_data = cPickle.load(datf)
plot_data = []
plot_data.append(run_data['reac'].data_shape[:,2,2,2,2,1])
plot_data.append(run_data['reac'].data_shape[2,:,2,2,2,1])
plot_data.append(run_data['reac'].data_shape[2,2,:,2,2,1])
plot_data.append(run_data['reac'].data_shape[2,2,2,:,2,1])
plot_axis_labels = []
plot_axis_labels.append('Core height (scaled)')
plot_axis_labels.append('Packing fraction (scaled)')
plot_axis_labels.append('Kernel radius (scaled)')
plot_axis_labels.append('Enrichment (scaled)')
if type_opt == '2d':
# plot all data
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(run_data['reac'].data)
ax.set_ylabel('reactivity [pcm]')
fig.savefig('reac.png')
# plot reac vs. dv data
fig = plt.figure()
# reac vs. kernel radius
ax = fig.add_subplot(2, 3, 1)
plt.xticks(rotation=45.0)
ax.plot(dv_dict['krad'], run_data['reac'].data_shape[2,2,:,2,2,0], '-bD')
ax.set_xlabel("kernel radius [cm]")
ax.set_ylabel('reactivity [pcm]')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
#ax.set_xticklabels(rotation=45.0)
# reac vs. enrichment
ax = fig.add_subplot(2, 3, 2)
plt.xticks(rotation=45.0)
ax.plot(dv_dict['enr'], run_data['reac'].data_shape[2,2,2,:,2,0], '-bD')
ax.set_xlabel("u-235 enrichment [a%]")
ax.set_ylabel('reactivity [pcm]')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. core height
ax = fig.add_subplot(2, 3, 3)
plt.xticks(rotation=45.0)
ax.plot(dv_dict['coreh'], run_data['reac'].data_shape[:,2,2,2,2,0], '-bD')
ax.set_xlabel("core active height [cm]")
ax.set_ylabel('reactivity [pcm]')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. pf
ax = fig.add_subplot(2, 3, 4)
plt.xticks(rotation=45.0)
ax.plot(dv_dict['pf'], run_data['reac'].data_shape[2,:,2,2,2,0], '-bD')
ax.set_xlabel("TRISO packing fraction")
ax.set_ylabel('reactivity [pcm]')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. cycle length
ax = fig.add_subplot(2, 3, 5)
plt.xticks(rotation=45.0)
ax.plot(dv_dict['bu'], run_data['reac'].data_shape[2,2,2,2,2,:], '-bD')
ax.set_xlabel("cycle length [EFPD]")
ax.set_ylabel('reactivity [pcm]')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. coolant density fraction
ax = fig.add_subplot(2, 3, 6)
plt.xticks(rotation=45.0)
ax.plot(dv_dict['cdens'], run_data['reac'].data_shape[2,2,2,2,:,0], '-bD')
ax.set_xlabel("coolant density fraction")
ax.set_ylabel('reactivity [pcm]')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
#fig.autofmt_xdate()
fig.subplots_adjust(hspace=0.5, wspace=0.5)
fig.set_size_inches(12.0, 7.0)
#fig.set_dpi(200.0)
fig.savefig('reac_all_dv.png', dpi=600.0)
#plt.plot(reac.data)
#plt.show()
#plt.savefig('reac.png')
elif type_opt=='3d':
# plot reac vs. dv data
fig = plt.figure()
# reac vs. core height and packing fraction
ax = fig.add_subplot(2, 3, 1, projection='3d')
X_ax, Y_ax = np.meshgrid(dv_dict['pf'], dv_dict['coreh'])
# norm_val = Normalize(vmin=np.min(run_data['reac'].data_shape[:,:,2,2,2,0]),
# vmax=np.max(run_data['reac'].data_shape[:,:,2,2,2,0]),
# clip=False)
plt.xticks(rotation=45.0)
plt.yticks(rotation=-45.0)
surf1 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[:,:,2,2,2,0], alpha=0.75,
rstride=1, cstride=1)
plt.xticks(dv_dict['pf'])
plt.yticks(dv_dict['coreh'])
plt.locator_params(axis='z',nbins=5)
# ax.zaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. core height and kernel radius
ax = fig.add_subplot(2, 3, 2, projection='3d')
X_ax, Y_ax = np.meshgrid(dv_dict['krad'], dv_dict['coreh'])
plt.xticks(rotation=45.0)
plt.yticks(rotation=-45.0)
surf2 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[:,2,:,2,2,0], alpha=0.75,
rstride=1, cstride=1)
plt.xticks(dv_dict['krad'])
plt.yticks(dv_dict['coreh'])
plt.locator_params(axis='z',nbins=5)
# ax.zaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. core height and enrichment
ax = fig.add_subplot(2, 3, 3, projection='3d')
X_ax, Y_ax = np.meshgrid(dv_dict['enr'], dv_dict['coreh'])
plt.xticks(rotation=45.0)
plt.yticks(rotation=-45.0)
surf3 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[:,2,2,:,2,0], alpha=0.75,
rstride=1, cstride=1)
plt.xticks(dv_dict['enr'])
plt.yticks(dv_dict['coreh'])
plt.locator_params(axis='z',nbins=5)
# ax.zaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs.packing fraction and kernel radius
ax = fig.add_subplot(2, 3, 4, projection='3d')
X_ax, Y_ax = np.meshgrid(dv_dict['krad'], dv_dict['pf'])
plt.xticks(rotation=45.0)
plt.yticks(rotation=-45.0)
surf4 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[2,:,:,2,2,0], alpha=0.75,
rstride=1, cstride=1)
plt.xticks(dv_dict['krad'])
plt.yticks(dv_dict['pf'])
plt.locator_params(axis='z',nbins=5)
# ax.zaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs.packing fraction and enrichment
ax = fig.add_subplot(2, 3, 5, projection='3d')
X_ax, Y_ax = np.meshgrid(dv_dict['enr'], dv_dict['pf'])
plt.xticks(rotation=45.0)
plt.yticks(rotation=-45.0)
surf5 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[2,:,2,:,2,0], alpha=0.75,
rstride=1, cstride=1)
plt.xticks(dv_dict['enr'])
plt.yticks(dv_dict['pf'])
plt.locator_params(axis='z',nbins=5)
# ax.zaxis.get_major_formatter().set_powerlimits((0,1))
# reac vs. kernel radius and enrichment
ax = fig.add_subplot(2, 3, 6, projection='3d')
X_ax, Y_ax = np.meshgrid(dv_dict['enr'], dv_dict['krad'])
plt.xticks(rotation=45.0)
plt.yticks(rotation=-45.0)
surf6 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[2,2,:,:,2,0], alpha=0.75,
rstride=1, cstride=1)
plt.xticks(dv_dict['enr'])
plt.yticks(dv_dict['krad'])
plt.locator_params(axis='z',nbins=5)
# ax.zaxis.get_major_formatter().set_powerlimits((0,1))
# Final plot options
fig.subplots_adjust(hspace=0.25, wspace=0.15)
fig.set_size_inches(12.0, 7.0)
fig.savefig('reac_all_dv_3d.png', dpi=600.0)
# make the itertool
# dv_s = itertools.combinations(dv_dict.keys(), 2)
# fig = plt.figure()
# for dv_idx,dv_set in enumerate(dv_s):
# ax = fig.add_subplot(2, 3, dv_idx, projection='3d')
# X_ax, Y_ax = np.meshgrid(dv_dict[dv_set[1]], dv_dict[dv_set[0]])
# # norm_val = Normalize(vmin=np.min(run_data['reac'].data_shape[:,:,2,2,2,0]),
# # vmax=np.max(run_data['reac'].data_shape[:,:,2,2,2,0]),
# # clip=False)
# plt.xticks(rotation=45.0)
# plt.yticks(rotation=-45.0)
# surf1 = ax.plot_surface(X_ax, Y_ax, run_data['reac'].data_shape[:,:,2,2,2,0], alpha=0.75,
# rstride=1, cstride=1)
# plt.xticks(dv_dict['pf'])
# plt.yticks(dv_dict['coreh'])
# plt.locator_params(axis='z',nbins=5)
elif type_opt == '2d_gpm':
# Plot obj. fun vs. each dv
for dv_idx in range(4): # CHANGE TAG: Will need to modify if variable number of dv's
dv_set = range(4) # CHANGE TAG: Will need to modify if variable number of dv's
dv_set.pop(dv_idx)
# First, set up matrix for plotting prediction
x_plot = np.empty([1000,4])
for idx in dv_set:
x_plot[:,idx] = plot_opts['gpm_opt']
x_plot[:,dv_idx] = np.linspace(0.0,1.0,1000)
y_pred, MSE = fit_data['obj_val'].predict(x_plot, eval_MSE=True)
sigma = np.sqrt(MSE)
# Second, prepare observed high-fidelity data for co-plotting
# Need to get the x-values of each dv fit_transformed
# such that they will match those of the prediction
scal = preprocessing.MinMaxScaler()
x_obs = scal.fit_transform(dv_dict.values()[dv_idx])
y_obs = plot_data[dv_idx]
# Now make the plot
fig = plt.figure()
ax = fig.add_subplot(111)
# Plot observations
ax.plot(x_obs, y_obs, 'r.', markersize=20, label=u'Observations')
ax.plot(x_plot[:,dv_idx], y_pred, 'b-', label=u'Prediction')
ax.fill(np.concatenate([x_plot[:,dv_idx],x_plot[:,dv_idx][::-1]]), \
np.concatenate([y_pred - 1.96 * sigma, \
(y_pred + 1.96 * sigma)[::-1]]), \
alpha=.5, fc='b', ec='None', label='95% confidence interval')
ax.yaxis.get_major_formatter().set_powerlimits((0,1))
fig.set_size_inches(10.0, 7.0)
ax.legend(loc='upper left', prop={'size':15})
ax.set_xlabel(plot_axis_labels[dv_idx], fontsize=20)
ax.set_ylabel('Reactivity [pcm]', fontsize=20)
ax.tick_params(axis='both', which='major', labelsize=20)
fig.subplots_adjust(hspace=0.25, wspace=0.15)
fig.savefig('gpm_test_dv_{0}.png'.format(dv_dict.keys()[dv_idx]), dpi=600.0)
# # vs. kernel radius
# # First, set up matrix for plotting prediction
# x_plot = np.empty([1000,4])
# # Kernel radius is the third of four dv's, so fill other columns with the
# for idx in [0,1,3]:
# x_plot[:,idx] = plot_opts['gpm_opt']
# x_plot[:,2] = np.linspace(0.0,1.0,1000)
# y_pred, MSE = fit_data['obj_val'].predict(x_plot, eval_MSE=True)
# sigma = np.sqrt(MSE)
# fig = plt.figure()
# ax = fig.add_subplot(2,3,2)
# ax.plot(fit_data['X_t'][0:3,3], run_data['reac'].data_fit[0:3], 'r.', markersize=10, label=u'Observations')
# ax.plot(x_plot[:,3], y_pred, 'b-', label=u'Prediction')
# ax.fill(np.concatenate([x_plot[:,3],x_plot[:,3][::-1]]), \
# np.concatenate([y_pred - 1.96 * sigma, \
# (y_pred + 1.96 * sigma)[::-1]]), \
# alpha=.5, fc='b', ec='None', label='95% confidence interval')
# ax.set_xlabel('Kernel radius (fraction of max)')
# ax.set_ylabel('Reactivity [pcm]')
# # vs. enrichment
# x_plot = np.empty([1000,4])
# x_plot[:,0:3] = fit_data['X_t'][0,0:3]
# x_plot[:,3] = np.linspace(0.0,1.0,1000)
# y_pred, MSE = fit_data['obj_val'].predict(x_plot, eval_MSE=True)
# sigma = np.sqrt(MSE)
# fig = plt.figure()
# ax = fig.add_subplot(2,3,2)
# ax.plot(fit_data['X_t'][0:3,3], run_data['reac'].data_fit[0:3], 'r.', markersize=10, label=u'Observations')
# ax.plot(x_plot[:,3], y_pred, 'b-', label=u'Prediction')
# ax.fill(np.concatenate([x_plot[:,3],x_plot[:,3][::-1]]), \
# np.concatenate([y_pred - 1.96 * sigma, \
# (y_pred + 1.96 * sigma)[::-1]]), \
# alpha=.5, fc='b', ec='None', label='95% confidence interval')
# ax.set_xlabel('Enrichment (fraction of max)')
# ax.set_ylabel('Reactivity [pcm]')
# #ax.legend(loc='upper left')
# fig.subplots_adjust(hspace=0.25, wspace=0.15)
# fig.set_size_inches(12.0, 7.0)
# #fig.savefig('reac_all_dv_3d.png', dpi=600.0)
else:
raise Exception(" Plot type selection does not exist; please select either '2d' or '3d' ")
|
def dijsktra_sparso(nodo, grafo):
from heapq import heappop, heappush
from math import inf
distanze = [inf for _ in grafo]
distanze[nodo] = 0
visitati = {nodo}
# Inizializzo heap.
heap = []
for adiacente, costo in grafo[nodo]:
distanze[adiacente] = costo
heappush(heap, (costo, adiacente)) # così ordina per costo
while heap:
costo, nodo = heappop(heap)
# Devo controllare che la coppia non sia vecchia.
if nodo not in visitati:
visitati.add(nodo)
for adiacente, costo in grafo[nodo]:
if adiacente not in visitati:
if distanze[adiacente] > distanze[nodo] + costo:
distanze[adiacente] = distanze[nodo] + costo
heappush(heap, (distanze[adiacente], adiacente))
return distanze
|
import sys, os
import Sorting_Algorithm
#If decide to start without input array
array = [10, -9, 8, -7, 6, -5, 4, -3, 2, -1, 0]
# Main definition - constants
menu_actions = {}
# Main menu
def main_menu():
os.system('CLS')
print("Welcome,\n")
print("Please choose the menu you want to start:")
print("1. Input Array")
print("2. Bubble Sort")
print("3. Insertion Sort")
print("4. Selection Sort")
print("\n0. Quit")
choice = input(" >> ")
exec_menu(choice)
return
# Execute menu
def exec_menu(choice):
os.system('CLS')
ch = choice.lower()
if ch == '':
menu_actions['main_menu']()
else:
try:
menu_actions[ch]()
except KeyError:
print("Invalid selection, please try again.\n")
menu_actions['main_menu']()
return
# Menu 1, input array
def menu1():
print("Enter elements to sort")
global array
array = list(map(int, input(">>").split()))
print("2. Bubble Sort")
print("3. Insertion Sort")
print("4. Selection Sort")
print("9. Back")
print("0. Quit")
choice = input(" >> ")
exec_menu(choice)
return
# Menu 2, Bubble sort
def menu2():
Sorting_Algorithm.bubble_sort(array)
print("9. Back")
print("0. Quit")
choice = input(" >> ")
exec_menu(choice)
return
# Menu 3, Insertion Sort
def menu3():
Sorting_Algorithm.insertion_sort(array)
print("9. Back")
print("0. Quit")
choice = input(" >> ")
exec_menu(choice)
return
# Menu 4, Selection Sort
def menu4():
Sorting_Algorithm.selection_sort(array)
print("9. Back")
print("0. Quit")
choice = input(" >> ")
exec_menu(choice)
return
# Back to main menu
def back():
menu_actions['main_menu']()
# Exit program
def exit():
sys.exit()
# =======================
# MENUS DEFINITIONS
# =======================
# Menu definition
menu_actions = {
'main_menu': main_menu,
'1': menu1,
'2': menu2,
'3': menu3,
'4': menu4,
'9': back,
'0': exit,
}
|
"""
Week 1, Day 2: Jewels And Stones
You're given strings J representing the types of stones that are jewels, and S representing the stones you have.
Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive,
so "a" is considered a different type of stone from "A".
N O T E :
- S and J will consist of letters and have length at most 50.
- The characters in J are distinct.
- Hint: For each stone, check if it is a jewel.
E X A M P L E S
Input: J = "aA", S = "aAAbbbb"
Output: 3
Input: J = "z", S = "ZZ"
Output: 0
"""
from collections import Counter, defaultdict
def numJewelsInStones(J: str, S: str) -> int:
return sum(value for key, value in Counter(S).items() if key in J)
def numJewelsInStones_v2(J: str, S: str) -> int:
jewels, stones, counts = set(J), list(S), 0
for s in stones:
if s in jewels:
counts += 1
return counts
def numJewelsInStones_v3(J: str, S: str) -> int:
return len([s for s in list(S) if s in set(J)])
def numJewelsInStones_v4(J: str, S: str) -> int:
"""This seams to be the fastest solution. At least from point of view of the LeetCode solution runner."""
counts = defaultdict(int)
for j in J:
counts[j] += S.count(j)
return sum(counts.values())
if __name__ == '__main__':
assert numJewelsInStones_v4('aA', 'aAAbbbb') == 3
assert numJewelsInStones_v4('z', 'ZZ') == 0
# last line of code
|
import pygame
from pygame import *
from pygame import display
from pygame import movie
import sys
import time
from random import *
#Colors
Aqua = (0, 255, 255)
Black = (0, 0, 0)
Blue = (0, 0, 255)
CornflowerBlue = (100, 149, 237)
Fuchsia = (255, 0, 255)
Gray = (128, 128, 128)
Green = (0, 128, 0)
Lime = (0, 255, 0)
Maroon = (128, 0, 0)
NavyBlue = (0, 0, 128)
Olive = (128, 128, 0)
Purple = (128, 0, 128)
Red = (255, 0, 0)
Silver = (192, 192, 192)
Teal = (0, 128, 128)
White = (255, 255, 255)
Yellow = (255, 255, 0)
screen_width = 800
screen_height = 600
#global lives
#lives = 10
speed = [1,1]
gravity = 0.1
WIN_WIDTH = 1100
WIN_HEIGHT = 600
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)
global HORIZ_MOV_INCR
HORIZ_MOV_INCR = 10
CAMERA_SLACK = 30
class Player(pygame.sprite.Sprite): #class player which is a sprite
penguin = pygame.sprite.Group()
def __init__(self,x, y):
#super(Player,self).__init__(*groups)
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.image = pygame.image.load('penguin.png') #load image into the player
self.rect = pygame.rect.Rect((self.x,self.y), self.image.get_size()) #obtain a rectangle around it
self.resting = False #flag stored to know when the character is resting
self.dy = 0
self.lives = 10
self.alive = True
self.Reached_Goal = False
def update(self, dt, game, screen):
self.isAlive()
self.checkGoal()
self.enemeyCollision()
self.icicleCollision()
self.gameOver()
last = self.rect.copy()
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
self.rect.y -= 500 * dt
if key[pygame.K_LEFT]:
self.rect.x -= 300 * dt
if key[pygame.K_RIGHT]:
self.rect.x += 300 * dt
if key[pygame.K_DOWN]:
self.rect.y += 300 * dt
if self.resting and key[pygame.K_SPACE]:
self.dy = -300
self.resting = False
self.dy = min(400, self.dy + 40)
self.rect.y += self.dy * dt
new = self.rect
for cell in pygame.sprite.spritecollide(self, terrain.All_Terrain ,False):
cell = cell.rect
if last.right <= cell.left and new.right > cell.left:
new.right = cell.left
if last.left >= cell.right and new.left < cell.right:
new.left = cell.right
if last.bottom <= cell.top and new.bottom > cell.top:
self.resting = True
new.bottom = cell.top
self.dy = 0
if last.top >= cell.bottom and new.top < cell.bottom:
new.top = cell.bottom
self.dy = 0
def drawLivesCounter(self):
font = pygame.font.Font(None, 36)
text = font.render(str(self.lives), 1, (10,10,10))
textpos = text.get_rect()
textpos.centerx = 100
textpos.centery = 100
screen.blit(text,textpos)
def checkGoal(self):
if pygame.sprite.spritecollide(self, terrain.Goal, False):
self.goalSound()
self.Reached_Goal = True
#def playMusic(self):
# file = 'snow.mp3'
# pygame.mixer.init()
# pygame.mixer.music.load(file)
# pygame.mixer.music.play(-1)
def snowSound(self):
#file = snow_effect.wav
sound = pygame.mixer.Sound('snow_effect.wav')
#pygame.mixer.music.load(file)
#pygame.mixer.music.play()
pygame.mixer.Sound.play(sound)
def goalSound(self):
sound = pygame.mixer.Sound('goal.wav')
pygame.mixer.Sound.play(sound)
def enemeyCollision(self):
if pygame.sprite.spritecollide(self, enemey.Enemies, False):
self.snowSound()
self.lives -= 1
#self.rect = pygame.rect.Rect((self.x,self.y), self.image.get_size())
#self.playMusic()
def icicleCollision(self):
if pygame.sprite.spritecollide(self, Icicles.Ice,False):
self.snowSound()
self.lives -= 1
#self.rect = pygame.rect.Rect((self.x,self.y), self.image.get_size())
#self.playMusic()
def isAlive(self):
if self.rect.left < 0 or self.rect.right > WIN_WIDTH or self.rect.top < 0 or self.rect.bottom >WIN_HEIGHT:
self.snowSound()
self.lives -= 1
#self.rect = pygame.rect.Rect((self.x,self.y), self.image.get_size())
#self.playMusic()
def gameOver(self):
if self.lives <= 0:
self.alive = False
class terrain(pygame.sprite.Sprite):
All_Terrain = pygame.sprite.Group()
Goal = pygame.sprite.Group()
Snow = pygame.sprite.Group()
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
#self.image = pygame.image.load('floor_large.png')
self.image = image
self.rect = pygame.rect.Rect((x,y), self.image.get_size())
class enemey(pygame.sprite.Sprite):
Enemies = pygame.sprite.Group()
def __init__(self, image, x, y, direction, dx, platform_width):
pygame.sprite.Sprite.__init__(self)
self.image = image
#self.x = x
#self.rect.centery = y
#platform_width =
#self.direction = "right"
self.direction = direction
self.dx = dx
self.platform_width = platform_width
self.rect = pygame.rect.Rect((x,y), self.image.get_size())
self.last = self.rect.copy()
#self.rect.x = x
#def update(self, dt, game, screen, platform_width, direction, dx):
def update(self, dt, game, screen):
if self.direction == "right":
self.rect.x += self.dx * dt
if self.rect.x >= self.last.x + self.platform_width /2:
self.direction = "left"
if self.direction == "left":
self.rect.x -= self.dx * dt
if self.rect.x <= self.last.x - self.platform_width / 2:
self.direction = "right"
#if self.rect.x == self.last.x:
#self.direction = right
# self.rect.x += dx * dt
#if self.rect.x == self.last.x - platform_width / 2:
#self.direction = right
# self.rect.x -= dx * dt
#if self.rect.x == self.last.x + platform_width / 2:
#self.drection = left
# self.rect.x += dx * dt
#self.rect.x -= randint(-50,50) * dt
class FallingSnow(pygame.sprite.Sprite):
Snowy = pygame.sprite.Group()
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = pygame.rect.Rect((x,y), self.image.get_size())
self.rect.y = y
def update(self, dt, game, screen):
self.rect.y += 100 * dt
class cloud(pygame.sprite.Sprite):
Clouds = pygame.sprite.Group()
def __init__(self, image, x, y, direction, dx, screen_width):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.direction = direction
self.dx = dx
self.screen_width = screen_width
self.rect = pygame.rect.Rect((x,y), self.image.get_size())
self.last = self.rect.copy()
def update(self, dt, game, screen):
if self.direction == "right":
self.rect.x += self.dx * dt
if self.rect.x >= self.last.x + self.screen_width / 2.5:
self.direction = "left"
if self.direction == "left":
self.rect.x -= self.dx * dt
if self.rect.x <= self.last.x - self.screen_width / 2.5:
self.direction = "right"
class Icicles(pygame.sprite.Sprite):
Ice = pygame.sprite.Group()
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = pygame.rect.Rect((x,y), self.image.get_size())
def update(self, dt, game, screen):
self.rect.y += 100 * dt
main_penguin = pygame.image.load('penguin.png')
snowman = pygame.image.load('snowman.png')
large_floor = pygame.image.load('floor_large.png')
snow = pygame.image.load('tile.png')
goal = pygame.image.load('goal.png')
small_floor = pygame.image.load('floor_small.png')
snow1 = pygame.image.load('snow1.png')
cloud_image = pygame.image.load('cloud.png')
icicle_image = pygame.image.load('icicle.png')
text_1 = pygame.image.load('Text_1.png')
text_2 = pygame.image.load('Text_2.png')
text_3 = pygame.image.load('text_3.png')
text_4 = pygame.image.load('text_4.png')
background_1 = pygame.image.load('Background_1.png')
background_2 = pygame.image.load('Background_2.jpg')
background_3 = pygame.image.load('Background_3.png')
background_4 = pygame.image.load('Background_4.jpg')
main_title = pygame.image.load('main_title.png')
text_bubble1 = pygame.image.load('text_bubble1.png')
text_bubble2 = pygame.image.load('text_bubble2.png')
text_bubble3 = pygame.image.load('text_bubble3.png')
text_instructions = pygame.image.load('Instruction_Text.png')
text_bubble4 = pygame.image.load('text_bubble4.png')
left_arrow = pygame.image.load('left_arrow.png')
right_arrow = pygame.image.load('right_arrow.png')
escape_button = pygame.image.load('escape_button.png')
#def drawTerrain(self)
#class enemy(pygame.sprite.Sprite):
#class ScrolledGroup(pygame.sprite.Group):
# def draw(self,surface):
# for sprite in self.sprites():
# surface.blit(sprite.image, (sprite.rect.x - self.camera_x, sprite.rect.y))
#all_fonts = pygame.font.get_fonts()
#class levels(object):
# def __init__(self, background, sprites):
######### LEVELS #########
# = [[small_floors], [large_floors], [goal], [enemies], [clouds]]
Level_1 = [[terrain(small_floor, 550,350), terrain(small_floor, 350, 300), terrain(small_floor, 600, 200)], [terrain(large_floor, 30, 300), terrain(large_floor, 900, 300)], [terrain(goal, 950, 215)], [enemey(snowman, 1700, 300, "right", 50, 125)], [cloud(cloud_image, 2000, 20, "right", 10, 10)], [Player(30,200)]]
Level_2 = [[terrain(small_floor, 1000, 237), terrain(small_floor, 900,300), terrain(small_floor, 500, 500)],[terrain(large_floor,30,150), terrain(large_floor,300,300), terrain(large_floor, 700, 400)],[terrain(goal,1000,150)],[ enemey(snowman, 800, 340, "right", 50, 125),enemey(snowman, 400,240, "right", 50, 125) ], [cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH)], [Player(30,30)] ]
Level_3 = [[terrain(small_floor, 500, 500)], [terrain(large_floor, 30, 150), terrain(large_floor, 800, 300)], [terrain(goal, 900, 215)], [enemey(snowman, 1500,240, "right", 50, 125)] , [cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH)], [Player(30,30)]]
Level_4 = [[terrain(small_floor, 525 , 500)],[terrain(large_floor,475,200)],[terrain(goal,525,420)],[ enemey(snowman, 1700, 340, "right", 50, 125)], [cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH), cloud(cloud_image, HALF_WIDTH + 200, 150, "right", 100, WIN_WIDTH)], [Player(550,100)] ]
Level_5 = [[terrain(small_floor, 200, 500), terrain(small_floor, 775,425), terrain(small_floor, 950, 500)],[terrain(large_floor,0,250), terrain(large_floor,240,225), terrain(large_floor, 480 , 200), terrain(large_floor,720,180)],[terrain(goal,200,415)],[ enemey(snowman, 2000, 340, "right", 50, 125)], [cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH), cloud(cloud_image, HALF_WIDTH + 50 , 50, "left", 100, WIN_WIDTH)], [Player(30,30)] ]
Level_6 = [[terrain(small_floor, 50, 200), terrain(small_floor, 150,200), terrain(small_floor, 300, 200), terrain(small_floor,500, 200)],[terrain(large_floor,800,200)],[terrain(goal,900,115)],[ enemey(snowman, 1700, 340, "right", 50, 125)], [cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH)], [Player(50,100)] ]
Level_7 = [[terrain(small_floor, 500, 500)],[terrain(large_floor,400,150)],[terrain(goal,500,70)],[ enemey(snowman, 1700, 340, "right", 50, 125)], [cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH)], [Player(500, 425)] ]
Level_8 = [[terrain(small_floor, 500, 300)], [terrain(large_floor, 30, 500), terrain(large_floor, 100, 200), terrain(large_floor,600, 400 ), terrain(large_floor, 800, 125)], [terrain(goal, 850, 40)], [enemey(snowman, 200, 145, "right", 50, 125), enemey(snowman,650, 345, "left", 50, 125)], [cloud(cloud_image, HALF_WIDTH, 50, "left", 100, WIN_WIDTH)], [Player(50,400)]]
Level_9 = [[terrain(small_floor, 125,500)], [terrain(large_floor, 30, 245), terrain(large_floor, 350, 100), terrain(large_floor, 350, 350), terrain(large_floor, 700,245), terrain(large_floor,350, 530)], [terrain(goal, 400, 445)], [enemey(snowman, 470, 293, "right", 50, 125),enemey(snowman, 130, 190 , "left", 50,125), enemey(snowman,430,477, "right", 50,125), enemey(snowman,755, 190, "left", 50,125)], [cloud(cloud_image, HALF_WIDTH, 20, "right", 100, WIN_WIDTH)], [Player(400,5)]]
Level_10 = [[terrain(small_floor, 20,550), terrain(small_floor, 100, 100), terrain(small_floor, 250, 450), terrain(small_floor, 600, 200), terrain(small_floor, 800, 400), terrain(small_floor, 850, 150)], [terrain(large_floor, 30, 250), terrain(large_floor, 900, 525), terrain(large_floor, 450, 400)], [terrain(goal, 850, 70)], [enemey(snowman, 115 , 197, "right", 50, 175), enemey(snowman, 530, 345, "left", 50, 125), enemey(snowman, 960, 475, "left", 50, 125)], [cloud(cloud_image, HALF_WIDTH, 20, "right", 100, WIN_WIDTH), cloud(cloud_image, HALF_WIDTH - 80, 10, "left", 100, WIN_WIDTH), cloud(cloud_image, HALF_WIDTH + 50, 40, "left", 100, WIN_WIDTH)], [Player(20,475)]]
class Game(object):
#def __init__(self):
# self.lives = 10
#def FallingSnow(self):
#snow = []
# while True:
# terrain.Snow.add(terrain(snow,randint(0,WIN_WIDTH),50))
# time.sleep(1)
#def drawPauseScreen(self):
def drawEndGame(self,screen):
screen.blit(background_3, (0,0))
#pygame.display.flip()
def drawMainScreen(self,screen):
#main_background = pygame.image.load()
screen.blit(background_2, (0,0))
screen.blit(text_2, (HALF_WIDTH / 2.3, HALF_HEIGHT / 0.75))
screen.blit(main_title, (HALF_WIDTH / 1.7, HALF_HEIGHT / 4))
#font = pygame.font.Font(Comic Sans MS,50)
#text = font.render("Press Enter To Start", 1, Blue)
#textpos = text.get_rect()
#textpos.centerx = HALF_WIDTH
#textpos.centery = HALF_HEIGHT
#screen.blit(text, textpos)
pygame.display.flip()
def drawHelpScreen_1(self,screen):
screen.blit(background_3, (0,0))
screen.blit(text_bubble1, (500, 50))
screen.blit(text_3, (15, 110))
screen.blit(right_arrow, (950, 500))
screen.blit(escape_button, (850, 500))
pygame.display.flip()
def drawHelpScreen_2(self,screen):
screen.blit(self.background, (0,0))
screen.blit(text_instructions, (50, 50))
screen.blit(main_penguin, (275,240))
screen.blit(snowman, (875, 268))
screen.blit(cloud_image, (50, 100))
screen.blit(right_arrow, (950, 500))
screen.blit(left_arrow, (850, 500))
pygame.display.flip()
def drawHelpScreen_3(self,screen):
screen.blit(background_3, (0,0))
screen.blit(text_bubble2, (-100, 20))
screen.blit(right_arrow, (950, 500))
screen.blit(left_arrow, (850, 500))
pygame.display.flip()
def drawHelpScreen_4(self,screen):
screen.blit(background_4, (0,0))
screen.blit(text_bubble4, (200,50))
screen.blit(left_arrow, (850, 500))
screen.blit(escape_button, (950, 500))
pygame.display.flip()
def drawClickCounter(self,screen):
font = pygame.font.Font(None,36)
text = font.render("Moves:" + str(self.clicks), 1, (10,10,10))
textpos = text.get_rect()
textpos.centerx = 220
textpos.centery = 50
screen.blit(text, textpos)
def drawLifeBox(self,screen):
font = pygame.font.Font(None,36)
text = font.render("Lives:" + str(self.level[5][0].lives) , 1, (10,10,10))
textpos = text.get_rect()
textpos.centerx = 100
textpos.centery = 50
screen.blit(text, textpos)
def drawLevelWon(self,screen):
font = pygame.font.Font(None,36)
text = font.render("Level Complete", 1, (10,10,10))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
textpos.centery = screen.get_rect().centery
screen.blit(text, textpos)
def drawGameOver(self,screen):
#self.redrawAll()
font = pygame.font.Font(None, 36)
text = font.render("Game Over", 1, (10,10,10))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
textpos.centery = screen.get_rect().centery
screen.blit(text, textpos)
pygame.display.flip()
def initIcicles(self):
Icicles.Ice.add(Icicles(icicle_image, randint(200,1100), 50))
def initFallingSnow(self):
#time.sleep(10)
FallingSnow.Snowy.add(FallingSnow(snow1,randint(0,1000),0))
def initClouds(self, level):
for x in level[4]:
cloud.Clouds.add(x)
def initPlayer(self, level):
for x in level[5]:
Player.penguin.add(x)
#cloud.Clouds.add(cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH))
def initEnemies(self, level):
#if level[3] != "None":
for x in level[3]:
enemey.Enemies.add(x)
#enemey.Enemies.add(enemey(snowman, 800, 340, "right", 50, 125))
#enemey.Enemies.add(enemey(snowman, 400,240, "right", 50, 125))
#self.rect.x+= x_speed
#enemey.update()
def initGoal(self, level):
#for x in range(100):
for x in level[2]:
terrain.Goal.add(x)
def initSnow(self):
self.snows = []
print self.snows
for x in self.snows:
terrain.All_Terrain.add(x)
def initFloor(self, level):
#self.image = pygame.image.load('floor_large.png')
#small_floors = [terrain(small_floor, 1000, 237), terrain(small_floor, 900,300), terrain(small_floor, 500, 500)]
#large_floors = [terrain(large_floor,30,150), terrain(large_floor,300,300), terrain(large_floor, 700, 400)]
for x in level[1]:
terrain.All_Terrain.add(x)
for y in level[0]:
terrain.All_Terrain.add(y)
# floor = pygame.sprite.Sprite(self.floors)
# ice = pygame.image.load('floor_large.png')
# floor.image = ice
# floor.rect = pygame.rect.Rect((200,500), floor.image.get_size())
# self.sprites.add(self.floors)
def main(self,screen):
global cameraX, cameraY
self.MenuScreen = True
self.HelpScreen_1 = False
self.HelpScreen_2 = False
self.HelpScreen_3 = False
self.HelpScreen_4 = False
#self.HelpScreen_2 = False
self.Level_1 = True
self.Level_2 = False
self.Level_3 = False
self.Level_4 = False
self.Level_5 = False
self.Level_6 = False
self.Level_7 = False
self.Level_8 = False
self.Level_9 = False
self.Level_10 = False
self.End_game = False
self.repeat = False
#self.lives = 10
self.world_shift_x = 0
self.left_viewbox = WIN_WIDTH/2 - WIN_WIDTH/8
self.right_viewbox = WIN_WIDTH/2 + WIN_WIDTH/10
self.objects = pygame.sprite.Group()
self.GameOver = False
self.clicks = 10
self.clock = pygame.time.Clock()
self.background = pygame.image.load('snow.png')
pygame.display.set_caption("Penguin")
#self.tile = pygame.image.load('tile.png')
#self.sprites = pygame.sprite.Group()
#self.camera = Camera(complex_camera, HALF_WIDTH, HALF_HEIGHT)
#self.player = Player(self.objects)
#self.cloud = cloud(self.objects)
#self.x = self.cloud.rect.x
#self.camera = Camera(screen, self.player.rect,WIN_WIDTH, WIN_HEIGHT)
#sprites = ScrolledGroup()
#sprites.camera_x = 0
#self.floors = pygame.sprite.Group()
#self.FallingSnow()
#self.initIcicles()
#self.initFallingSnow()
#self.initEnemies()
#self.initClouds()
#self.initSnow()
#self.initFloor()
#self.initGoal()
self.run()
######### creating level 1
#def get
def click_sound(self):
#file = snow_effect.wav
sound = pygame.mixer.Sound('click.wav')
#pygame.mixer.music.load(file)
#pygame.mixer.music.play()
pygame.mixer.Sound.play(sound)
def run(self):
#self.player = Player(self.objects)
self.initLevel(Level_1)
#if not self.Level_1:
# self.initLevel(Level_2)
#else:
# self.initLevel(Level_1)
while True:
self.dt = self.clock.tick(60)
print self.MenuScreen
if not self.MenuScreen:
if not self.HelpScreen_1:
if not self.HelpScreen_2:
if not self.HelpScreen_3:
if not self.HelpScreen_4:
if not self.End_game:
if self.level[5][0].alive:
for event in pygame.event.get():
if self.level[5][0].Reached_Goal == True:
if not self.Level_10:
if not self.Level_9:
if not self.Level_8:
if not self.Level_7:
if not self.Level_6:
if not self.Level_5:
if not self.Level_4:
if not self.Level_3:
if not self.Level_2:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_1)
self.initLevel(Level_2)
self.Level_1 = False
self.Level_2 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_2)
self.initLevel(Level_3)
self.Level_2 = False
self.Level_3 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_3)
self.initLevel(Level_4)
self.Level_3 = False
self.Level_4 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_4)
self.initLevel(Level_5)
self.Level_4 = False
self.Level_5 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_5)
self.initLevel(Level_6)
self.Level_5 = False
self.Level_6 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_6)
self.initLevel(Level_7)
self.Level_6 = False
self.Level_7 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_7)
self.initLevel(Level_8)
self.Level_7 = False
self.Level_8 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_8)
self.initLevel(Level_9)
self.Level_8 = False
self.Level_9 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
self.clearLevel(Level_9)
self.initLevel(Level_10)
self.Level_9 = False
self.Level_10 = True
self.level[5][0].Reached_Goal = False
else:
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
pygame.mixer.quit()
self.clearLevel(Level_10)
self.drawEndGame(screen)
self.Level_10 = False
self.End_game = True
self.level[5][0].Reached_Goal = False
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_q:
self.main(screen)
#break
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.MOUSEMOTION:
self.x, self.y = event.pos
print (self.x,self.y)
if self.clicks > 0:
if event.type ==pygame.MOUSEBUTTONDOWN and event.button == 1:
#self.snows.append(terrain(snow,self.x,self.y))
self.click_sound()
self.clicks -= 1
terrain.All_Terrain.add(terrain(snow,self.x,self.y))
#if not self.MenuScreen:
self.redrawAll()
else:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_q:
self.main(screen)
self.drawGameOver(screen)
# if self.dt % 10 == 0:
# self.initIcicles()
if self.dt % 5 == 0:
self.initFallingSnow()
else:
for event in pygame.event.get():
if (event.type == pygame.KEYDOWN) and event.key == pygame.K_n:
#self.clearLevel(Level_10)
#self.drawMainScreen(screen)
#self.Level_10 = False
#pygame.mixer.quit()
#screen = pygame.display.set_mode((WIN_WIDTH,WIN_HEIGHT))
#pygame.display.init()
#pygame.movie.Movie('penguin_dance.mpg')
#pygame.movie.Movie.set_display(screen)
#pygame.movie.Movie.play()
pygame.display.init()
movie = pygame.movie.Movie('penguin_dance.mpg')
screen1 = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
#screen1 = pygame.display.set_mode(movie.get_size())
movie_screen = pygame.Surface(movie.get_size()).convert()
movie.set_display(screen1)
movie.play()
#playing = True
#while playing:
screen1.blit(movie_screen, (0,0))
pygame.display.update()
#pygame.display.update()
#self.clock.tick(60)
#self.movie = pygame.movie.Movie('penguin_dance.mpg')
#self.resolution = self.movie.get_size()
#self.movie_length = self.movie.get_length()
#self.image_surface = pygame.Surface(self.resolution)
#self.image_surface.fill([0,0,0])
#self.movie.set_display(screen)
#self.movie.play()
#m.play()
#pygame.display.init()
#movie = pygame.movie.Movie('penguin_dance.mpg')
#w,h = movie.get_size()
#display = pygame.display.set_mode((w,h))
#movie.set_display(display)
#movie.play()
#pygame.movie.init()
#mygame.movie.Movie.load('penguin_dance.mpg')
#pygame.movie.Movie.play(1)
#pygame.movie.Movie('penguin_dance.mpg')
#ygame.movie.Movie.play()
#movie_screen = pygame.Surface(movie.get_size()).convert()
#playing = True
#while playing:
#screen.blit(movie_screen, (0,0))
#pygame.display.update()
#self.clock.tick(60)
#sys.exit(0)
#self.End_game = False
#self.MenuScreen = True
#self.repeat = True
#self.level[5][0].Reached_Goal = False
else:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
self.HelpScreen_4 = False
self.HelpScreen_3 = False
self.HelpScreen_2 = False
self.HelpScreen_1 = False
self.MenuScreen = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
self.HelpScreen_4 = False
self.HelpScreen_3 = True
self.drawHelpScreen_4(screen)
else:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
self.HelpScreen_3 = False
self.HelpScreen_2 = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
self.HelpScreen_3 = False
self.HelpScreen_4 = True
self.drawHelpScreen_3(screen)
else:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
self.HelpScreen_2 = False
self.HelpScreen_1 = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
self.HelpScreen_2 = False
self.HelpScreen_3 = True
self.drawHelpScreen_2(screen)
else:
#self.drawHelpScreen_1(screen)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
self.HelpScreen_1 = False
self.MenuScreen = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
self.HelpScreen_1 = False
self.HelpScreen_2 = True
self.drawHelpScreen_1(screen)
else:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
self.MenuScreen = False
#self.Level_1 = True
#self.clearLevel(Level_1)
#self.initLevel(Level_1)
#if self.repeat == True:
# self.main(screen)
#self.clearLevel(Level_1)
#self.initLevel(Level_1)
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit(0)
if event.type == pygame.QUIT:
sys.exit(0)
if event.type == pygame.KEYDOWN and event.key == pygame.K_h:
self.HelpScreen_1 = True
self.MenuScreen = False
self.drawMainScreen(screen)
#self.redrawAll()
#self.drawGameOver()
#self.redrawAll()
#self.run_viewbox()
#self.camera.update(self.player)
#enemey.update()
#self.initSnow()
#screen.blit(self.tile, (self.x,self.y))
#pygame.display.flip()
#print self.player.alive
#if self.player.alive == False:
#sys.exit(0)
#Player.drawLivesCounter()
#print Player.lives
#self.redrawAll()
#for e in self.objects:
# screen.blit(e.image, self.camera.apply(e))
#if Player.alive == True:
#print self.GameOver
#if not self.GameOver:
# self.redrawAll()
def initLevel(self, level):
#self.objects.remove()
#self.initIcicles()
#self.initFallingSnow()
self.level = level
self.initClouds(level)
self.initSnow()
self.initEnemies(level)
self.initFloor(level)
self.initGoal(level)
self.initPlayer(level)
#self.player = Player(self.objects)
def clearLevel(self,level):
#self.objects.remove(terrain.All_Terrain)
#self.objects.remove(terrain.Goal)
#self.objects.remove(terrain.Snow)
#self.objects.remove(FallingSnow.Snowy)
#Icicles.Ice.remove(
#cloud.Clouds.remove(cloud(cloud_image, HALF_WIDTH , 50, "right", 100, WIN_WIDTH))
enemey.Enemies.remove(level[3])
terrain.All_Terrain.empty()
terrain.All_Terrain.remove(level[0])
terrain.All_Terrain.remove(level[1])
terrain.Goal.remove(level[2])
cloud.Clouds.remove(level[4])
Player.penguin.remove(level[5])
#self.objects.remove(self.player)
def drawLevel(self,level):
#self.objects.add(terrain.All_Terrain)
#self.objects.add(terrain.Goal)
#terrain.Goal.draw(screen)
#self.objects.add(terrain.Snow)
#self.objects.add(FallingSnow.Snowy)
FallingSnow.Snowy.draw(screen)
terrain.All_Terrain.draw(screen)
terrain.Goal.draw(screen)
#self.objects.draw(screen)
cloud.Clouds.draw(screen)
enemey.Enemies.draw(screen)
Icicles.Ice.draw(screen)
#self.objects.draw(screen)
Player.penguin.draw(screen)
# = [[small_floors], [large_floors], [goal], [enemies]]
#def pickLevel(self):
def redrawAll(self):
# if self.player.Reached_Goal:
# if not self.Level_2:
# self.drawLevelWon(screen)
#self.player.Reached_Goal = False
#for event in pygame.event.get():
#if event.type == pygame.KEYDOWN and event.key == pygame.K_n:
#print "hi"
#self.player.Reached_Goal = False
# self.Level_1 = False
# self.Level_2 = True
# self.clearLevel(Level_1)
# self.initLevel(Level_2)
# else:
# if not self.Level_1:
# self.drawLevel(Level_2)
# else:
# self.drawLevel(Level_1)
#self.initIcicles()
#self.initFallingSnow()
#self.initEnemies(level)
#self.initClouds()
#self.initSnow()
#self.initFloor(level)
#self.initGoal(level)
if self.Level_3:
if self.dt % 10 == 0:
self.initIcicles()
self.objects.update(self.dt / 1000., self, screen)
#self.objects.add(terrain.All_Terrain)
#self.objects.add(terrain.Goal)
#self.objects.add(terrain.Snow)
#self.objects.add(enemey.Enemies)
#self.objects.add(FallingSnow.Snowy)
#enemey.Enemies.draw(screen)
#self.camera.update(self.player)
#FallingSnow.Snowy.update(self.dt / 1000., self, screen)
#if not self.MenuScreen:
screen.blit(self.background, (0,0))
self.drawLifeBox(screen)
self.drawClickCounter(screen)
Icicles.Ice.update(self.dt / 1000., self, screen)
FallingSnow.Snowy.update(self.dt / 1000., self, screen)
Player.penguin.update(self.dt / 1000., self, screen)
#Icicles.Ice.draw(screen)
#Camera.draw_sprites(screen, self.objects)
#Camera.update()
#self.camera.update(self.player)
#self.objects.draw(screen)
cloud.Clouds.update(self.dt / 1000., self, screen)
#cloud.Clouds.draw(screen)
enemey.Enemies.update(self.dt / 1000., self, screen)
if self.Level_1:
self.drawLevel(Level_1)
if self.Level_2:
self.drawLevel(Level_2)
if self.Level_3:
self.drawLevel(Level_3)
if self.Level_4:
self.drawLevel(Level_4)
if self.Level_5:
self.drawLevel(Level_5)
if self.Level_6:
self.drawLevel(Level_6)
if self.Level_7:
self.drawLevel(Level_7)
if self.Level_8:
self.drawLevel(Level_8)
if self.Level_9:
self.drawLevel(Level_9)
if self.Level_10:
self.drawLevel(Level_10)
if self.End_game:
self.drawEndGame(screen)
if self.level[5][0].Reached_Goal:
self.drawLevelWon(screen)
#enemey.Enemies.draw(screen)
#if self.player.Reached_Goal:
# if not self.Level_2:
# self.drawLevelWon(screen)
#self.player.Reached_Goal = False
#for event in pygame.event.get():
#if event.type == pygame.KEYDOWN and event.key == pygame.K_n:
#print "hi"
#self.player.Reached_Goal = False
# self.Level_1 = False
# self.Level_2 = True
# self.clearLevel(Level_1)
# self.initLevel(Level_2)
# else:
#self.initLevel(Level_2)
#self.redrawAll()
#terrain.All_Terrain.draw(screen)
#terrain.Goal.draw(screen)
#self.sprites.draw(screen)
pygame.display.flip()
# def drawLine(self):
if __name__ == '__main__':
file = 'snow.mp3'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play(-1)
screen = pygame.display.set_mode((WIN_WIDTH,WIN_HEIGHT))
Game().main(screen)
|
a,b=map(int,input().split(" "))
l=list(map(int,input().split(" ")))
r=[[abs(i-b),i]for i in l]
r=sorted(r)
r=r[1:]
r=[i[1] for i in r[ :3]]
print(*r)
|
import os
import re
import sys
import _pickle as cPickle
from sklearn.metrics.pairwise import linear_kernel
from collections import OrderedDict
from module import ProcessQuery as pq
domain=sys.argv[1]
userUtterance=sys.argv[2]
scriptDir=os.path.dirname(__file__)
picklePath=os.path.join(scriptDir,'model',domain+'_')
utter=re.sub(r'[^a-zA-Z ]','',userUtterance)
combinations=pq.genUtterances(utter)
jResult=pq.processUtterance(combinations)
print(str(jResult).replace("'",'"'),end="")
|
# coding:utf-8
from __future__ import absolute_import, unicode_literals
__author__ = "golden"
__date__ = '2018/7/20'
from jspider.web.app import app_creator
from jspider.utils.config import Config
from jspider.manager.spider import SpiderManager
if __name__ == '__main__':
config = Config()
config.from_pyfile('config.py')
app = app_creator(config)
app.manager = SpiderManager()
app.run(debug=True, host='0.0.0.0', port=8081)
|
import boto3
import logging
import botostubs
from botocore.exceptions import ClientError
boto_session = boto3.Session(profile_name='personal')
ec2: botostubs.EC2 = boto_session.client('ec2', region_name='ap-south-1')
|
import codecs
import json
file_cidades = codecs.open('cidades.json', encoding='utf-8')
cidades_texto = file_cidades.read()
cidades_json = json.loads(cidades_texto)
for cidade in cidades_json:
print(cidade)
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 14:58:16 2020
@author: logam
"""
import matplotlib.pyplot as plt
import numpy as np
import cv2
img = cv2.imread('test3.jpg')
plt.figure(dpi=300)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(img)
hist, bins = np.histogram(img.flatten(), 256,[0,256])
equ = cv2.equalizeHist(img)
plt.hist(img.flatten(),256,[0,256], color="r")
#pls.imshow()
plt.subplot(121),plt.hist(img.flatten(),256,[0,256], color="r"),plt.title('Histogramm')
plt.subplot(122),plt.imshow(img, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
|
origin = open('idf_sample/simple.idf', 'r')
new = open('idf_sample/simple.idf.tmp', 'w')
for line in origin:
new.write(line.replace('@@Height@@', '1000'))
origin.close()
new.close()
|
import os
from unittest import TestCase, mock
from src import env
MONGODB_CONNECTION_STRING = 'a mongodb connection string'
class TestEnv(TestCase):
def setUp(self):
self.addCleanup(mock.patch.stopall)
mock_env = {
'MONGODB_CONNECTION_STRING': MONGODB_CONNECTION_STRING
}
self.mock_env_patch = mock.patch.dict(os.environ, mock_env)
self.mock_env_patch.start()
def tearDown(self):
self.mock_env_patch.stop()
def test_get_mongodb_connection_string(self):
self.assertEqual(MONGODB_CONNECTION_STRING, env.get_mongodb_connection_string())
|
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from os import environ
import json
import datetime
import requests
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
CORS(app)
class UserChatID(db.Model):
__tablename__ = 'UserChatID'
# NEED TO ADD IN DB.ForeignKey('databasename.columnname')
TelegramHandle = db.Column(db.String(100), primary_key= True)
ChatID = db.Column(db.Integer, nullable= False)
def __init__(self, TelegramHandle, ChatID):
self.TelegramHandle = TelegramHandle
self.ChatID = ChatID
def json(self):
return {
"TelegramHandle" : self.TelegramHandle,
"ChatID" : self.ChatID
}
@app.route("/telegramNotification/<string:TelegramHandle>/<string:errorMsg>")
@app.route("/telegramNotification/<string:TelegramHandle>/<string:appointmentDate>/<string:appointmentTime>/<string:clinicName>")
def sendTelegramNoti(TelegramHandle, appointmentDate=None, appointmentTime=None, clinicName=None, errorMsg=None):
getChatID = "http://localhost:5566/telegramNotification/getChatID/" + TelegramHandle
sendToChat = "http://<dockerIPAddress>:4646/telegram/sendMessage/"
result = requests.get(getChatID).json()
chatID = str(result['message'])
if (errorMsg != None):
sendToChat += chatID + "/" + errorMsg
else:
sendToChat += chatID + "/" + str(appointmentDate) + "/" + str(appointmentTime) + "/" + str(clinicName)
sendResult = requests.get(sendToChat).json()
return sendResult
@app.route("/telegramNotification/getChatID/<string:TelegramHandle>")
def getChatID(TelegramHandle):
chatID = UserChatID.query.filter_by(TelegramHandle = TelegramHandle).first()
result = "Not Found"
if chatID:
result = chatID.json()['ChatID']
return jsonify({"status": True, "message": result})
else:
return jsonify({"status": False, "message": result})
@app.route("/telegramNotification/addChatID/<string:TelegramHandle>/<int:ChatID>")
def addChatID(TelegramHandle, ChatID):
getChatIDLink = "http://localhost:5566/telegramNotification/getChatID/" + TelegramHandle
search = requests.get(getChatIDLink).json()
# return search.json()
if search['status'] == False:
chatIDObj = UserChatID(TelegramHandle, ChatID)
try:
db.session.add(chatIDObj)
db.session.commit()
return jsonify({"status": True, "message": "ChatID is added into the database"})
except:
return jsonify({"status": False, "message": "An error occurred creating chatID."})
else:
return jsonify({"status": False, "message": "ChatID has been created"})
@app.route("/telegramNotification/update")
def updateNotification():
getUpdatesLink = "http://<dockerIPAddress>:4646/telegram/getUpdates"
result = requests.get(getUpdatesLink).json()
temp = 0
if (result["status"] == True):
data = result["message"]
for object in data:
# if chatID is NOT in the database then add the teleHandle and ChatID into the database
print ("here")
teleHandle = object['message']['from']['username']
chatID = object['message']['chat']['id']
temp = object['update_id']
getChatIDLink = "http://localhost:5566/telegramNotification/getChatID/" + teleHandle
found = requests.get(getChatIDLink).json()
if found['status'] == False:
addChatIDLink = "http://localhost:5566/telegramNotification/addChatID/" + teleHandle + "/" + str(chatID)
addStatus = requests.get(addChatIDLink)
temp+=1
resetLink = getUpdatesLink + "/" + str(temp)
try:
reset = requests.get(resetLink)
reply = reset.json()
return jsonify({"message" : reply}),200
except requests.exceptions.RequestException as e:
print(e)
return jsonify({"message":e}), 400
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5566, debug=True)
|
import os
import sys
import shutil
def find_family_index(alignments_info_file, alignment_name):
lines = open(alignments_info_file).readlines()[1:]
for i in range(0, len(lines)):
if "/" + alignment_name in lines[i] or lines[i].startswith(alignment_name):
return i
return -1
def extract_line(input_file, index, output_file):
lines = open(input_file).readlines()
with open(output_file, "w") as writer:
current_index = 0
for line in lines:
if (">" in line):
continue
else:
if (current_index == index):
writer.write(line)
return
else:
current_index += 1
def extract_gene_family(input_dataset_dir, alignment_name, output):
species_tree = os.path.join(input_dataset_dir, "speciesTree.newick")
true_trees = os.path.join(input_dataset_dir, "trueGeneTrees.newick")
raxml_trees = os.path.join(input_dataset_dir, "geneTrees.newick")
treerecs_trees = os.path.join(input_dataset_dir, "treerecs_output.newick.best")
alignments_info_file = os.path.join(input_dataset_dir, "alignment.txt")
msa_file = os.path.join(input_dataset_dir, "alignments", alignment_name)
output_species_tree = os.path.join(output, "speciesTree.newick")
output_true_tree = os.path.join(output, "trueGeneTree.newick")
output_raxml_tree = os.path.join(output, "raxmlGeneTree.newick")
output_treerecs_tree = os.path.join(output, "treerecsGeneTree.newick")
output_msa = os.path.join(output, "alignment.msa")
os.makedirs(output)
shutil.copyfile(species_tree, output_species_tree)
shutil.copyfile(msa_file, output_msa)
family_index = find_family_index(alignments_info_file, alignment_name)
print(family_index)
if (family_index == -1):
print(alignment_name)
extract_line(true_trees, family_index, output_true_tree)
extract_line(raxml_trees, family_index, output_raxml_tree)
extract_line(treerecs_trees, family_index, output_treerecs_tree)
if __name__ == '__main__':
if (len(sys.argv) != 4):
print("Syntax : input_dataset_dir alignment_name output_dir")
sys.exit(1)
input_dataset_dir = sys.argv[1]
alignment_name = sys.argv[2]
output = sys.argv[3]
extract_gene_family(input_dataset_dir, alignment_name, output)
|
import os, sys
import argparse
import subprocess
# return output from bash pipe cmd as decoded string
def run_cmd(cmd):
bash_cmd = cmd
process = subprocess.Popen(bash_cmd.split(), stdout=subprocess.PIPE)
output = process.stdout.read()
return output.decode('utf-8')
# return branches list
def get_branches():
unwanted_branches = ['master', 'HEAD', '>']
decoded_string = run_cmd("git branch -r --sort=committerdate")
branches = decoded_string.split()
clean_branch_list = []
branch_list = [branch for branch in branches if not any(unwanted_branch in branch for unwanted_branch in unwanted_branches)]
for branch in branch_list:
string = branch.split("/")
clean_branch_list.append(string[1])
return clean_branch_list
def get_tags():
decoded_string = run_cmd("git tag")
tags = decoded_string.split()
return tags
def get_git_username():
decoded_string = run_cmd("git config user.name")
return decoded_string.rstrip("\n\r")
def get_repo_name():
decoded_string = run_cmd("git rev-parse --show-toplevel")
split_string = decoded_string.split("/")
return split_string[-1].rstrip("\n\r")
def main():
parser = argparse.ArgumentParser(
description='Generate branches or tags markdown output',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''Example of use:
Default usage returns all branches and tags markdown in chronological order:
gtrix
Optional arguments:
gtrix -u "username"
gtrix -t''')
parser.add_argument('-u', '--user', help='set user[Optional]')
parser.add_argument("-t", '--tags', dest='tags', action='store_true', help='get tags only')
parser.set_defaults(tags=False)
args = parser.parse_args()
# check if .git directory exists
# exit if it doesn't exists
if ".git" not in os.listdir():
print("Not a git directory! Ensure you are inside a git repository")
sys.exit()
branches = get_branches()
tags = get_tags()
repo = get_repo_name()
if args.user:
username = args.user
else:
username = get_git_username()
# - [Board-Setup-2](https://github.com/kodaman2/TTT-Book/tree/Board-Setup-2)
if not args.tags:
for branch in branches:
print("- [%s](https://github.com/%s/%s/tree/%s)\n" % (branch, username, repo, branch))
if args.tags:
for tag in tags:
print("- [%s](https://github.com/%s/%s/tree/%s)\n" % (tag, username, repo, tag))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @copyright 2016 TUNE, Inc. (http://www.tune.com)
# @version $Date: 2016-07-07 12:45:28 PDT $
import sys
from pprintpp import pprint
import pytz
from pytz_convert import (
convert_tz_abbrev_to_tz_offset,
convert_tz_abbrev_to_tz_seconds,
convert_tz_name_to_now_tz_abbrev,
convert_tz_name_to_date_tz_abbrev,
convert_tz_name_to_now_tz_offset,
convert_tz_offset_and_date_to_tz_name,
convert_tz_offset_to_tz_hours,
convert_tz_offset_to_tz_minutes,
convert_tz_hours_to_tz_offset,
parse_gmt_offset_timezone
)
def main():
tz_name = "US/Central"
tz_abbrev = "PST"
tz_offset = convert_tz_abbrev_to_tz_offset(tz_abbrev)
pprint(tz_offset)
tz_offset = convert_tz_name_to_now_tz_offset(tz_name)
pprint(tz_offset)
tz_abbrev = convert_tz_name_to_now_tz_abbrev(tz_name)
pprint(tz_abbrev)
tz_hours = convert_tz_offset_to_tz_hours(tz_offset)
pprint(tz_hours)
tz_minutes = convert_tz_offset_to_tz_minutes(tz_offset)
pprint(tz_minutes)
tz_offset = convert_tz_hours_to_tz_offset(tz_hours)
pprint(tz_offset)
tz_seconds = convert_tz_abbrev_to_tz_seconds('PST')
pprint(tz_seconds)
tz_abbrev = convert_tz_name_to_now_tz_abbrev(tz_name)
pprint(tz_abbrev)
tz_abbrev = convert_tz_name_to_date_tz_abbrev(tz_name, str_date='2016-03-01')
pprint(tz_abbrev)
tz_abbrev = convert_tz_name_to_date_tz_abbrev(tz_name, str_date='2016-03-30')
pprint(tz_abbrev)
google_adwords_tz_name, tz_offset = parse_gmt_offset_timezone(
tz_gmt_offset_name='(GMT-08:00) Pacific Time'
)
print("{}, {}".format(google_adwords_tz_name, tz_offset))
tz_names = convert_tz_offset_and_date_to_tz_name(
tz_offset=tz_offset,
str_date='2016-03-01'
)
print("{}, {}".format(tz_names, tz_offset))
tz_names = convert_tz_offset_and_date_to_tz_name(
tz_offset=tz_offset,
str_date='2016-03-30'
)
print("{}, {}".format(tz_names, tz_offset))
pprint(pytz.country_timezones['IN'])
for tz_offset_num in range(-11, 13):
if tz_offset_num >= 0:
tz_offset = "+{:02d}00".format(tz_offset_num)
else:
tz_offset = "-{:02d}00".format(abs(tz_offset_num))
tz_names = convert_tz_offset_and_date_to_tz_name(
tz_offset=tz_offset,
str_date='2016-03-01'
)
print("{}, {}".format(
tz_offset,
tz_names
))
if __name__ == '__main__':
sys.exit(main())
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 21:32:15 2019
@author: HP
"""
T=int(input())
while(T):
N=int(input())
A=input()
sum=0
for i in range(N):
if int(A[i])==1:
k=0
for j in range(i,N):
if int(A[j])==1:
k=k+1
sum=sum+k
print(sum)
T=T-1
|
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class MyTopo( Topo ):
"Simple topology example."
def __init__( self ):
"Create custom topo."
# Initialize topology
Topo.__init__( self )
# Add hosts and switches
s1 = self.addSwitch('s1')
s2 = self.addSwitch('s2')
s3 = self.addSwitch('s3')
s4 = self.addSwitch('s4')
s5 = self.addSwitch('s5')
s6 = self.addSwitch('s6')
s7 = self.addSwitch('s7')
s8 = self.addSwitch('s8')
s9 = self.addSwitch('s9')
s10 = self.addSwitch('s10')
s11 = self.addSwitch('s11')
s12 = self.addSwitch('s12')
h1 = self.addHost('h1')
h2 = self.addHost('h2')
h3 = self.addHost('h3')
h4 = self.addHost('h4')
h5 = self.addHost('h5')
h6 = self.addHost('h6')
h7 = self.addHost('h7')
h8 = self.addHost('h8')
h9 = self.addHost('h9')
h10 = self.addHost('h10')
h11 = self.addHost('h11')
h12 = self.addHost('h12')
# Add links
self.addLink(s1, s2)
self.addLink(s2, s5)
self.addLink(s2, s6)
self.addLink(s2, s12)
self.addLink(s9, s12)
self.addLink(s9, s3)
self.addLink(s3, s6)
self.addLink(s6, s7)
self.addLink(s7, s4)
self.addLink(s4, s11)
self.addLink(s11, s10)
self.addLink(s10, s8)
self.addLink(s8, s5)
self.addLink(s7, s5)
self.addLink(s4, s10)
self.addLink(h1, s1)
self.addLink(h2, s2)
self.addLink(h3, s3)
self.addLink(h4, s4)
self.addLink(h5, s5)
self.addLink(h6, s6)
self.addLink(h7, s7)
self.addLink(h8, s8)
self.addLink(h9, s9)
self.addLink(h10, s10)
self.addLink(h11, s11)
self.addLink(h12, s12)
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
import factory
from colossus.apps.templates.models import EmailTemplate
class EmailTemplateFactory(factory.DjangoModelFactory):
name = factory.Sequence(lambda n: f'campaign_{n}')
class Meta:
model = EmailTemplate
|
#!/usr/bin/env python3
#########################################
### CUAUV Hydrophones sample generator (modeled after code written by Patrick Dear
# @ author Patrick Dear (translated to Python3 from Matlab by Noah Levy)
#########################################
#Multipathing channel model taken from here: Underwater Acoustic Communications: Design Considerations on the Phyisical Layer
import numpy as np
import numpy.random
import scipy
import scipy.io
SAMPLE_FREQ = 400e3
ELEM_SPACING = 0.015 #element spacing in meters
SPEED_SOUND = 1497
PING_FREQ = 37500
PING_LENGTH = 0.0095 #In seconds (9ms)
PINGER_RING_UP_TAU = 0.0010 #In seconds (1ms tau)
INTER_PING_TIME = 1.5 #In seconds (1.5s)
PING_PERIOD = PING_LENGTH+INTER_PING_TIME
PING_AZIMUTH_ANGLE = np.radians(165) #NOTE: This is the azimuthal angle in spherical cooridinates (phi in physics)
PING_POLAR_ANGLE = np.radians(110) #This is the polar angle in spherical coords (theta in physics)
NOISE_POWER = 0.05
NUMBER_OF_MULTIPATHS = 10
MAXIMUM_MULTIPATH_DISTANCE = 12 #In meters
MAX_MULTIPATH_GAIN = .3
DATA_LEN = 5 #In seconds
lambda_sound = SPEED_SOUND/PING_FREQ #Phase velocity in H20 divided by ping frequency is wavelength (roughly 4 cm)
omega = 2*scipy.pi*PING_FREQ #Angular frequency
k_hat = np.asarray([np.sin(PING_POLAR_ANGLE)*np.cos(PING_AZIMUTH_ANGLE), np.sin(PING_POLAR_ANGLE)*np.sin(PING_AZIMUTH_ANGLE), np.cos(PING_POLAR_ANGLE)]) #Normalized wavevector, khat
ping_start_delay = np.random.random() #Delay start of first ping by 0-1 sec
ping_interval_uncertainty_time = .1 #Interval between pings can vary by as much as .1 second
delta_phase_x = k_hat[0]*ELEM_SPACING/SPEED_SOUND*omega
delta_phase_y = k_hat[1]*ELEM_SPACING/SPEED_SOUND*omega
phase_ref = 2*scipy.pi*np.random.random()
phase_1_0 = phase_ref + delta_phase_x;
phase_0_1 = phase_ref + delta_phase_y;
time = np.arange(0,DATA_LEN,1/SAMPLE_FREQ)
envelope = np.zeros(ping_start_delay*SAMPLE_FREQ)
while len(envelope) < len(time):
on_period = (1-np.exp(-1*np.linspace(0,PING_LENGTH,PING_LENGTH*SAMPLE_FREQ)/PINGER_RING_UP_TAU)) #*np.ones(PING_LENGTH*SAMPLE_FREQ)
off_period = np.zeros(SAMPLE_FREQ*(INTER_PING_TIME+ping_interval_uncertainty_time*(np.random.random() - .5)))
#print(envelope.shape)
#print(on_period.shape)
#print(off_period.shape)
envelope = np.concatenate((envelope,on_period,off_period),axis=0) #Generate an envelope a fixed size ON period, plus a variable sized inter ping time (because the pinger does not seem to have a totally deterministic duty cycle))
print(envelope.shape)
envelope = envelope[0:len(time)].flatten()
source_0_0 = np.cos(omega*time - phase_ref)*envelope
source_0_0 += NOISE_POWER*(np.random.randn(len(time)))
source_0_1 = np.cos(omega*time - phase_0_1)*envelope
source_0_1 += NOISE_POWER*(np.random.randn(len(time)))
source_1_0 = np.cos(omega*time - phase_1_0)*envelope
source_1_0 += NOISE_POWER*(np.random.randn(len(time)))
###########################################
##LAME ATTEMPT AT MODELING MULTIPATHING
#######################################
multipath_distances = MAXIMUM_MULTIPATH_DISTANCE*np.random.random(NUMBER_OF_MULTIPATHS) #random
multipath_delays_in_seconds = multipath_distances/SPEED_SOUND
multipath_delays_in_ticks = multipath_delays_in_seconds*SAMPLE_FREQ
multipath_gains = np.random.random(multipath_delays_in_ticks.shape)*MAX_MULTIPATH_GAIN
channel_vector = np.zeros(np.max(multipath_delays_in_ticks) + 1)
channel_vector[0] = 1 #Line of sight path
for idx,x in enumerate(multipath_delays_in_ticks):
channel_vector[x] = multipath_gains[idx]
print(channel_vector)
source_0_0 = np.convolve(source_0_0,channel_vector)
source_0_1 = np.convolve(source_0_1,channel_vector)
source_1_0 = np.convolve(source_1_0,channel_vector)
gain_0_0 = 250 + np.random.randint(-50,50)
gain_0_1 = 250 + np.random.randint(-50,50)
gain_1_0 = 250 + np.random.randint(-50,50)
sample_0_0 = 2048+np.floor(source_0_0*gain_0_0)
sample_0_1 = 2048+np.floor(source_0_1*gain_0_1)
sample_1_0 = 2048+np.floor(source_1_0*gain_1_0)
d = dict()
d['sample_0_0'] = sample_0_0.flatten()
d['sample_0_1'] = sample_0_1.flatten()
d['sample_1_0'] = sample_1_0.flatten()
scipy.io.savemat('test',d,do_compression=True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/20 15:05
# @Author : Jason
# @Site :
# @File : keras_test.py
# @Software: PyCharm
from keras.models import Sequential
from keras.layers.core import Dense ,Dropout,Activation
from keras.optimizers import SGD
model = Sequential() #模型初始化
model.add(Dense(20,64)) #添加输入层
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64,64))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64,1))
model.add(Activation('sigmoid'))
sgd = SGD(lr=0.1,decay=1e-6,momentum=0.9,nesterov=True)
model.compile(loss='mean_squared_error',optimizer=sgd)
model.fit(X_train,y_train,nb_epoch=20,batch_size=16)
score = model.evaluate(X_test,y_test,batch_size=16)
|
# Generated by Django 2.2 on 2019-04-12 19:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('yohbiteapp', '0010_auto_20190412_0953'),
]
operations = [
migrations.AddField(
model_name='restaurant',
name='district',
field=models.ForeignKey(default=3, on_delete=django.db.models.deletion.CASCADE, to='yohbiteapp.District'),
),
migrations.AddField(
model_name='restaurant',
name='location',
field=models.ForeignKey(default=11, on_delete=django.db.models.deletion.CASCADE, to='yohbiteapp.Location'),
),
]
|
import datetime
import unittest
from collections import OrderedDict
from unittest.main import main
from wta.app import MatchScrapper
def init_scrapper(build=False):
instance = MatchScrapper(filename='test_page.html')
if build:
instance.build('player-matches__tournament')
return instance
class TestEmptyScrap(unittest.TestCase):
def setUp(self):
self.scrapper = init_scrapper()
def test_is_list(self):
self.assertIsInstance(self.scrapper.tournaments, list)
def test_deep_clean(self):
s = '\n Eugenie Bouchard'
self.assertEqual(self.scrapper._deep_clean(s), ['Eugenie', 'Bouchard'])
def test_date_parsing(self):
d = '20-Oct 26, 2020'
result = self.scrapper._parse_date(d)
self.assertIsInstance(result, datetime.date)
self.assertEqual(result.year, 2020)
def test_normalizing(self):
s = ' EUGENIE bouchard '
self.assertEqual(self.scrapper._normalize(s), 'Eugenie Bouchard')
self.assertEqual(self.scrapper._normalize(s, as_title=True), 'Eugenie Bouchard')
class Constructors(unittest.TestCase):
def setUp(self):
self.scrapper = init_scrapper()
def test_parse_tournament_header(self):
divs = self.scrapper.soup.find_all('div')
for div in divs:
if div.has_attr('class'):
class_attrs = div.attrs['class']
if 'player-matches__tournament' in class_attrs:
headers = div.find('div', 'player-matches__tournament-header')
result = self.scrapper._parse_tournament_header(headers)
self.assertIsInstance(result, OrderedDict)
def test_construct_tournament_header(self):
name, _ = self.scrapper._construct_tournament_header([])
self.assertIsNone(name)
def test_construct_tournament_header_2(self):
name, values = self.scrapper._construct_tournament_header([1, [2, 'Paris, France'], 4, 5, 6])
self.assertIsInstance(values, dict)
self.assertEqual(name, 'Paris')
self.assertEqual(values['country'], 'France')
if __name__ == "__main__":
unittest.main()
|
class Solution:
# @param A : list of integers
# @return an integer
import sys
def findMinXor(self, A):
mini = int(sys.float_info.max)
n = len(A)
for i in range(0,n-1):
res = A[i] ^ A[i+1]
mini = min(mini,res)
return mini
|
from router_solver import *
import game_engine.constants
from game_engine.constants import *
import game_engine.spritesheet
from game_engine.spritesheet import *
# Clase usada para rockas y moscas
class Item(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, type):
super().__init__()
self.x = x
self.y = y
self.type = type
self.width = width
self.height = height
self.eaten = False
self.board_x = self.x // Constants.ITEM_WIDTH
self.board_y = self.y // Constants.ITEM_HEIGHT
self.image = None
self.rect = None
def update(self):
pass
# Obtiene el sprite del item
def construct_animation(self):
if self.type == "Rock":
sprite_sheet = SpriteSheet(Constants.ROCK_IMAGE)
elif self.type == "Fly":
sprite_sheet = SpriteSheet(Constants.FLY_IMAGE)
self.image = sprite_sheet.get_image(
1, 0, Constants.ITEM_WIDTH - 1, Constants.ITEM_HEIGHT - 1
)
self.rect = self.image.get_rect()
|
#import
import pygame
import sys
import time
import math
import random
import shelve
from random import randrange
#Constants
white = (255,255,255)
lightgreen = (168,192,50)
green = (97,178,56)
darkgreen = (52,151,78)
blue= (70,126,145)
lblue = (153,217,234)
yellow = (242,250,87)
score_=0
distance = 0
lef_angle=0
right_angle=0
a=0
b=0
dir_cat =0
dir_gaz =0
dir_c = 0
dir_g = 0
dir_g0 = 0
start = True
pressed_up = False
pressed_left = False
pressed_right = False
intro = True
pos_cat = [0,0]
pos_gaz= [101,92]
pygame.init()
screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Hunt-Me")
icon = pygame.image.load("icon.gif")
pygame.display.set_icon(icon)
clock = pygame.time.Clock()
myFont = pygame.font.SysFont("Agency FB", 48)
hereFont = pygame.font.SysFont("Agency FB", 40)
scoreFont = pygame.font.SysFont("Agency FB",48)
menuFont = pygame.font.SysFont("Agency FB",62)
winFont = pygame.font.SysFont("Agency FB",100)
where = hereFont.render("here !",1,lightgreen)
N = myFont.render("North ",1,white)
NE = myFont.render("NorthEast ",1,white)
NW = myFont.render("NorthWest ",1,white)
S = myFont.render("South ",1,white)
SE = myFont.render("SouthEast",1,white)
SW = myFont.render("SouthWest",1,white)
E = myFont.render("East",1,white)
W = myFont.render("West",1,white)
play = menuFont.render("HunT",4,lightgreen)
more = menuFont.render("? help",4,blue)
sound = pygame.mixer.Sound("cricket.ogg")
run_sound = pygame.mixer.Sound("run.ogg")
back = pygame.image.load("back.png")
game_logo = pygame.image.load("deer.png")
logo = pygame.image.load("logo.png")
################ methods ###############
### Main Menu
def game_intro():
global intro, score_
score = scoreFont.render(str(score_),1,white)
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(white)
screen.blit(play,(720,650))
screen.blit(more,(410,650))
screen.blit(game_logo,(400,0))
pygame.draw.rect(screen, lblue, (560,510,80,80), 0)
screen.blit(score,(590,520))
screen.blit(logo,(10,730))
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
### Donate button
if 710 + 85 > mouse[0] > 710 and 645 + 70 > mouse[1] > 645 :
if click[0] == 1:
intro = False
random_dist()
if 400+85 > mouse[0] > 400 and 645 + 70 > mouse[1] > 645 :
if click[0] == 1:
helper()
pygame.display.update()
#Compass
def compass():
if dir_c == 0 or dir_c == 360:
screen.blit(N,(560,10))
elif dir_c == 45 :
screen.blit(NE,(560,10))
elif dir_c == 90 :
screen.blit(E,(560,10))
elif dir_c == 135 :
screen.blit(SE,(560,10))
elif dir_c == 180 :
screen.blit(S,(560,10))
elif dir_c == 225 :
screen.blit(SW,(560,10))
elif dir_c == 270 :
screen.blit(W,(560,10))
elif dir_c == 315 :
screen.blit(NW,(560,10))
#random distance
def random_dist():
global pos_gaz
pos_gaz[0] = random.randint(120,200)
pos_gaz[1] = random.randint(120,200)
#distance
def dist():
global distance
global dir_cat
global dir_gaz
dir_cat = math.ceil(math.cos(pos_cat[1]))
dir_gaz = math.ceil(math.cos(pos_gaz[1]))
distance = math.ceil(math.sqrt((pow((pos_gaz[0]-pos_cat[0]),2)) + (pow((pos_gaz[1] - pos_cat[1]),2))))
#update position_cat
def run_cat():
global dir_c , pressed_up
if pressed_up:
pos_cat[0] += 3 * math.cos(dir_c)
pos_cat[1] += 3 * math.sin(dir_c)
if pressed_left:
if dir_c > 44:
dir_c -= 45
else:
dir_c = 360
if pressed_right:
if dir_c < 316:
dir_c += 45
else:
dir_c = 0
#HELP
def help_me():
global dir_g0,dir_g
dir_g = pos_gaz[1]
while dir_g > 360:
dir_g = dir_g - 360
if dir_c < dir_g:
screen.blit(where,(980,250))
else:
screen.blit(where,(220,250))
#Key Events
def update_pos_cat():
global pressed_up
global pressed_left
global pressed_right
global pressed_down
keys=pygame.key.get_pressed()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
pressed_up = True
if event.key == pygame.K_LEFT:
pressed_left = True
if event.key == pygame.K_RIGHT:
pressed_right = True
if event.key == pygame.K_DOWN:
pressed_down = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
pressed_up = False
if event.key == pygame.K_LEFT:
pressed_left = False
if event.key == pygame.K_RIGHT:
pressed_right = False
if event.key == pygame.K_DOWN:
pressed_down = False
#update position_gaz first time
def update_pos_gaz_r1():
global left_angle
global right_angle
if pos_cat[0] < pos_gaz[0] and pos_cat[1] < pos_gaz[1]:
left_angle = 0
right_angle = 90
if pos_cat[0] < pos_gaz[0] and pos_cat[1] > pos_gaz[1]:
left_angle = 90
right_angle = 180
if pos_cat[0] > pos_gaz[0] and pos_cat[1] < pos_gaz[1]:
left_angle = 270
right_angle = 360
if pos_cat[0] > pos_gaz[0] and pos_cat[1] > pos_gaz[1]:
left_angle = 180
right_angle = 270
#update positoin of gaz second time
def update_pos_gaz_r2():
global left_angle
global right_angle
if pos_cat[0] < pos_gaz[0] and pos_cat[1] < pos_gaz[1]:
left_angle = -90
right_angle = 180
if pos_cat[0] < pos_gaz[0] and pos_cat[1] > pos_gaz[1]:
left_angle = -180
right_angle = 90
if pos_cat[0] > pos_gaz[0] and pos_cat[1] < pos_gaz[1]:
left_angle = 0
right_angle = 270
if pos_cat[0] > pos_gaz[0] and pos_cat[1] > pos_gaz[1]:
left_angle = -270
right_angle = 0
#set random angle
def random_angle():
global a
global b
angle = random.randint(left_angle,right_angle)
print(angle)
a = math.sin(angle)
b = math.cos(angle)
#gaz run
def run_gaz():
pos_gaz[0] += 2*a
pos_gaz[1] += 2*b
time.sleep(0.100)
####### Game Loop #########
while True :
game_intro()
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
screen.blit(back,(0,0))
dist()
update_pos_cat()
run_cat()
if distance <10:
win1 = winFont.render("Great !! ",1,yellow)
win2 = winFont.render("You won't sleep hungry tonight",1,yellow)
screen.blit(win1,(380,180))
score_ += 1
intro = True
if distance < 101 and distance >98:
update_pos_gaz_r1()
random_angle()
distance += 3
if distance < 101:
if distance < 43 and distance > 40:
update_pos_gaz_r2()
random_angle()
distance +=2
elif distance < 40:
run_gaz()
white = lightgreen
else:
white =(255,255,255)
if pressed_up :
run_gaz()
mts = scoreFont.render("mts",1,white)
distDisplay = scoreFont.render(str(distance), 1, white)
compassDisplay = myFont.render(str(dir_c), 1, white)
compass()
screen.blit(distDisplay,(580,730))
screen.blit(mts,(655,730))
help_me()
if pressed_up:
run_sound.play()
pygame.key.get_repeat()
pygame.display.flip()
|
#!/usr/bin/python3
s = 'Hello, Runoob'
print(str(s))
print(repr(s))
print(str(1/7))
x = 10 * 3.25
y = 200 * 200
s = 'x的值为: ' + repr(s) + ', y的值为: ' + repr(y) + '...'
print(s)
# repr() 可以转义字符串中的特殊字符
hello = 'hello, runoob\n'
hellos = repr(hello)
print(hellos)
# repr() 函数的参数可以是python的任何对象
print(repr((x, y, ('Google', 'Runoob'))))
|
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.decorators.csrf import csrf_exempt
from rest_auth.registration.views import VerifyEmailView
from django.views.generic import TemplateView
from django.conf import settings
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'auth/', include('rest_framework_social_oauth2.urls')),
path(r'accounts/', include('authentication.urls')),
path(r'', include('devices.urls')),
path(r'', include('rest_framework.urls')),
path(r'', include('shop.urls')),
path(r'', include('users.urls')),
path(r'', TemplateView.as_view(template_name = 'index.html'))
]
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
|
import pyaudio
import wave
from scipy.fftpack import fft, ifft
import numpy as np
import matplotlib.pyplot as plt
import cv2
from scipy import signal
from swan import pycwt
CHUNK = 1024
FORMAT = pyaudio.paInt16 # int16型
CHANNELS = 1 # 1;monoral 2;ステレオ-
RATE = 22100 # 22.1kHz 44.1kHz
RECORD_SECONDS = 5 # 5秒録音
WAVE_OUTPUT_FILENAME = "output2.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
s=1
# figureの初期化
fig = plt.figure(figsize=(12, 10))
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
ax2.axis([0, 5, 200,20000])
ax2.set_yscale('log')
while True:
fig.delaxes(ax1)
fig.delaxes(ax3)
ax1 = fig.add_subplot(311)
ax3 = fig.add_subplot(313)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
wavfile = WAVE_OUTPUT_FILENAME
wr = wave.open(wavfile, "rb")
ch = CHANNELS #wr.getnchannels()
width = p.get_sample_size(FORMAT) #wr.getsampwidth()
fr = RATE #wr.getframerate()
fn = wr.getnframes()
fs = fn / fr
origin = wr.readframes(wr.getnframes())
data = origin[:fn]
wr.close()
sig = np.frombuffer(data, dtype="int16") /32768.0
t = np.linspace(0,fs, fn/2, endpoint=False)
ax1.axis([0, 5, -0.0075,0.0075])
ax1.plot(t, sig)
nperseg = 256
f, t, Zxx = signal.stft(sig, fs=fs*fn/50, nperseg=nperseg)
ax2.pcolormesh(t, 5*f, np.abs(Zxx), cmap='hsv')
freq =fft(sig,int(fn/2))
Pyy = np.sqrt(freq*freq.conj())*2/fn
f = np.arange(int(fn/2))
ax3.axis([200, 20000, 0,0.000075])
ax3.set_xscale('log')
ax3.plot(f,Pyy)
plt.pause(1)
plt.savefig('figure'+str(s)+'.png')
s += 1
|
#!/usr/bin/python
import sys
import lfc
import commands
import os
#
# test entry
#
directory = "/grid/dteam/my_test_dir/"
name = "/grid/dteam/my_test_dir/my.test"
replica1 = "sfn://my_se.in2p3.fr/hpss/in2p3.fr/group/sophie/tests_python/dir/my.test"
replica2 = "srm://my_other_se.cern.ch/castor/cern.ch/grid/sophie/tests_python/dir/my.test"
replica3 = "sfn://my_se.in2p3.fr/hpss/in2p3.fr/group/sophie/tests_python/dir/my.test2"
status = '-'
f_type = 'D'
#
# delete test entry, if exists
#
stat1 = lfc.lfc_filestatg()
if (lfc.lfc_statg(name,"",stat1)) == 0:
if (lfc.lfc_delreplica(stat1.guid, None, replica1)) != 0:
err_num = lfc.cvar.serrno
err_string = lfc.sstrerror(err_num)
print "error"+ str(err_num) + " (" + err_string + ")"
lfc.lfc_delreplica(stat1.guid, None, replica2)
lfc.lfc_delreplica(stat1.guid, None, replica3)
lfc.lfc_unlink(name)
lfc.lfc_rmdir(directory)
#
# create entry in LFC for following tests
#
guid = commands.getoutput('uuidgen').split('\n')[0]
print guid
lfc.lfc_mkdir(directory, 0755)
if (lfc.lfc_creatg(name, guid, 0644)) != 0:
err_num = lfc.cvar.serrno
err_string = lfc.sstrerror(err_num)
print "Error when creating " + name + ": Error " + str(err_num) + " (" + err_string + ")"
#
# stat this entry in the LFC and print the GUID
#
stat3 = lfc.lfc_filestatg()
if (lfc.lfc_statg(name,"",stat3)) == 0:
guid = stat3.guid
print "[OK] The GUID for " + name + " is " + guid
else:
err_num = lfc.cvar.serrno
err_string = lfc.sstrerror(err_num)
print "[ERROR] There was an error while looking for " + name + ": Error " + str(err_num) + " (" + err_string + ")"
#
# add replicas
#
lfc.lfc_addreplica(guid, None, os.getenv("LFC_HOST"), replica1, status, f_type, "", "")
lfc.lfc_addreplica(guid, None, os.getenv("LFC_HOST"), replica2, status, f_type, "", "")
lfc.lfc_addreplica(guid, None, os.getenv("LFC_HOST"), replica3, status, f_type, "", "")
#
# list replicas, starting from the GUID
#
listp = lfc.lfc_list()
flag = lfc.CNS_LIST_BEGIN
print "Listing replicas for GUID " + guid
num_replicas=0
while(1):
res = lfc.lfc_listreplica("",guid,flag,listp)
flag = lfc.CNS_LIST_CONTINUE
if res == None:
break
else:
rep_name = res.sfn
print "Replica: " + rep_name
num_replicas = num_replicas + 1
lfc.lfc_listreplica("",guid,lfc.CNS_LIST_END,listp)
print "Found " + str(num_replicas) + " replica(s)"
#
# using the lfc_getreplica method
#
result, list = lfc.lfc_getreplica(name, "", "")
print "result = " + str(result)
print "len(list) = " + str(len(list)) + " replicas found"
if (result == 0):
for i in list:
print i.host
print i.sfn
#
# using lfc_readdirxr method
#
dir = lfc.lfc_opendirg(directory,"")
while 1:
read_pt = lfc.lfc_readdirxr(dir,"")
if (read_pt == None) or (read_pt == 0):
break
entry,list=read_pt
print entry.d_name
try:
for i in range(len(list)):
print " ==> %s" % list[i].sfn
except TypeError, x:
print " ==> None"
lfc.lfc_closedir(dir)
#
# delete test entry
#
stat4 = lfc.lfc_filestatg()
if (lfc.lfc_statg(name,"",stat4)) == 0:
lfc.lfc_delreplica(stat4.guid, None, replica1)
lfc.lfc_delreplica(stat4.guid, None, replica2)
lfc.lfc_delreplica(stat4.guid, None, replica3)
lfc.lfc_unlink(name)
lfc.lfc_rmdir(directory)
|
while True:
n=input
if n%2==0:
print'Congrats u entered an even no'
break;
else:
continue
|
import cv2
cap = cv2.VideoCapture('video.mp4') #videos are read by frames we can give 0,1 to on front cam
while(True):
#capture frame by frame
ret, frame = cap.read()
#Display the resulting frame
cv2.imshow('frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'): #25 normal speed, extra code to get video close atomatically when i press 'q'
break
cap.release()
cv2.destroyAllWindows() #to destroy all background data
|
from apps import App, Response, TemplateResponse, JSONResponse
from wsgiref.simple_server import make_server
app = App()
@app.route('^/$', 'GET')
def hello(request):
return Response('Hello World')
@app.route('^/user/$', 'POST')
def create_user(request):
return Response('User created', status=201)
@app.route('^/user/(?P<name>\w+)/$', 'GET')
def user_detail(request, name):
return Response('Hello {name}'.format(name=name))
@app.route('^/user/(?P<name>\w+)/follow/$', 'POST')
def create_user(name):
return JSONResponse({'message': 'User Created.'}, status=201)
@app.route('^/user/$', 'GET')
def users(request):
users_list = ['user%s' % i for i in range(10)]
return TemplateResponse('users.html', titile='User List', users=users_list)
if __name__ == '__main__':
httpd = make_server('', 8000, app)
httpd.serve_forever()
|
"""
This file is used in get_video.py
The main function extracts a frame from a ts video
"""
import glob
import cv2
def extract_frame_from_video_url(video_link):
frame_is_read, frame = cv2.VideoCapture(video_link).read()
if frame_is_read:
return frame_is_read, frame
else:
print("Could not read the frame." + count)
|
#!/usr/bin/env python3
import rospy
import math
import time
import py_trees
import py_trees.console as console
from std_msgs.msg import String
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from tf import transformations
from sensor_msgs.msg import LaserScan
# Global pose variables
global curr_x, curr_y, curr_z
# Initialize flag variables
getClose = True
isAligned = False
nearDoor = False
notInFront = True
# Laser callback
def get_regions(data):
# print(data.ranges.index(min(min(data.ranges[90:300]), min(data.ranges[360:450]), min(data.ranges[510:570]), min(data.ranges[630:635]))))
global getClose, isAligned
# If both isn't close to the bathroom yet, get close
if getClose:
get_close(data)
# If bot isn't aligned with the wall, align
elif not isAligned:
align_wall(data)
# If bot is at the edge of the door
elif not nearDoor:
follow_wall(data)
elif notInFront:
get_in_front(data)
# Pose callback
def get_pose(data):
global curr_x, curr_y, curr_z
curr_x = data.pose.pose.position.x
curr_y = data.pose.pose.position.y
quaternion = (data.pose.pose.orientation.x, data.pose.pose.orientation.y, data.pose.pose.orientation.z, data.pose.pose.orientation.w)
euler = transformations.euler_from_quaternion(quaternion)
curr_z = euler[2]
# Get distance between 2 points
def get_dist(x1,y1,x2,y2):
return(math.sqrt((x1-x2) ** 2 + (y1-y2) ** 2))
def get_in_front(laser_data):
global notInFront
# Velocity publisher
pub = rospy.Publisher('/cmd_vel',Twist,queue_size=10)
# Enter status publisher
finish_pub = rospy.Publisher('/enter_done', String, queue_size=10)
vel = Twist()
# Turn to align
vel.linear.x = 0
vel.linear.y = 0
vel.angular.z = -.1
pub.publish(vel)
rospy.sleep(1)
vel.angular.z = 0
pub.publish(vel)
# Move right
vel.linear.x = 0
vel.linear.y = -0.2
vel.angular.z = 0
pub.publish(vel)
rospy.sleep(1.75)
# Move front
vel.linear.x = .2
vel.linear.y = 0
vel.angular.z = 0
pub.publish(vel)
rospy.sleep(2.2)
# Stop (Bathroom Entered)
vel.linear.x = 0
vel.linear.y = 0
vel.angular.z = 0
pub.publish(vel)
finish_pub.publish("Done")
notInFront = False
def follow_wall(laser_data):
global nearDoor
# Velocity publisher
pub = rospy.Publisher('/cmd_vel',Twist,queue_size=10)
vel = Twist()
linear_x = 0
linear_y = 0
angular_z = 0
# Check which side the bot is facing relative to the wall
if laser_data.ranges[180] > 2.5 and laser_data.ranges[180] < 5 and laser_data.ranges[90] < 3:
nearDoor = True
linear_x = 0
linear_y = 0
elif laser_data.ranges[180] < 10:
min_laser_dist = min(laser_data.ranges[170:270])
min_index = laser_data.ranges.index(min_laser_dist)
rot_angle = (min_index - 180)/2
angular_z = rot_angle*.01
linear_y = -.2
linear_x = (laser_data.ranges[180] - .6)*.1
# elif laser_data.ranges[270] < 1.1 or laser_data.ranges[270]==float('inf'):
else:
linear_x = 0
linear_y = -.2
angular_z = 0.5
# Set and publish velocity
vel.linear.x = linear_x
vel.linear.y = linear_y
vel.angular.z = angular_z
pub.publish(vel)
# Align bot with wall after getting close
def align_wall(laser_data):
global isAligned
# Velocity publisher
pub = rospy.Publisher('/cmd_vel',Twist,queue_size=10)\
vel = Twist()
linear_x = 0
linear_y = 0
angular_z = 0
min_laser_dist = min(laser_data.ranges[180], laser_data.ranges[360], laser_data.ranges[540], laser_data.ranges[0])
min_index = laser_data.ranges.index(min_laser_dist)
# If bot is aligned, set flag
if (laser_data.ranges[90] < 1.3 and laser_data.ranges[270] < 1.3) or (laser_data.ranges[90] < 1.3 and laser_data.ranges[270] < 1.3) or (laser_data.ranges[90] < 1.3 and laser_data.ranges[90] > 1.2 and laser_data.ranges[270] == float('inf')) or (laser_data.ranges[90] ==float('inf') and laser_data.ranges[270] < 1.25 and laser_data.ranges[270] > 1.2):
print('done')
angular_z = 0
isAligned = True
# Determine the direction in which the bot must turn...required only for corner cases
elif not isAligned and laser_data.ranges[90] < 1.3 and laser_data.ranges[270] == float('inf'):
print('right')
angular_z = -.2
elif not isAligned and laser_data.ranges[270] > 1.3 and laser_data.ranges[90] == float('inf'):
print('right')
angular_z = -.2
elif not isAligned and laser_data.ranges[90] > 1.3 and laser_data.ranges[270] == float('inf'):
print('left')
angular_z = .2
elif not isAligned and laser_data.ranges[270] < 1.3 and laser_data.ranges[90] == float('inf'):
print('left')
angular_z = .2
# Set and publish velocity
vel.linear.x = linear_x
vel.linear.y = linear_y
vel.angular.z = angular_z
pub.publish(vel)
# Get close to the wall
def get_close(laser_data):
global curr_x, curr_y, curr_z
global getClose
pub = rospy.Publisher('/cmd_vel',Twist,queue_size=10)\
vel = Twist()
linear_x = 0
linear_y = 0
angular_z = 0
min_laser_dist = min(laser_data.ranges[90:270])
min_index = laser_data.ranges.index(min_laser_dist)
rot_angle = (min_index - 180)/2
angular_z = rot_angle*.01
if abs(rot_angle)<10:
linear_x = min((min_laser_dist - .5)*.7,.5)
else:
linear_x = 0
if abs(linear_x) < .05 and abs(angular_z) <.01:
getClose = False
vel.linear.x = linear_x
vel.linear.y = linear_y
vel.angular.z = angular_z
pub.publish(vel)
if __name__ == "__main__":
rospy.init_node('find_door')
rospy.Subscriber('/scan',LaserScan,get_regions, queue_size=10)
rospy.Subscriber('/odom',Odometry,get_pose,queue_size=10)
rospy.spin()
|
# -*- coding: utf-8 -*-
import unittest
import sys
sys.path.append('../../../python')
from testecono.sileg.testsileg import TestSileg
def suite():
"""
Gather all the tests from this module in a test suite.
"""
test_suite = unittest.TestSuite()
test_suite.addTest(TestSileg('test_create_database'))
return test_suite
mySuit=suite()
runner=unittest.TextTestRunner()
runner.run(mySuit)
|
import sys
import csv
import json
import optparse
import collections
parser = optparse.OptionParser()
parser.add_option(
'-i', '--input', dest='input_file',
help='input file name',
default='globe/data/locations.tsv',
)
parser.add_option(
'-c', '--coalesce_time_interval', type='int', dest='coalesce_time_interval',
help='Interval (seconds) to coalesce points into. Expected input to be time sorted',
default=60*5,
)
parser.add_option(
'-t', '--minimum_count_threshold', type='int', dest='minimum_count_threshold',
help='Removes points with magnitudes below threshold. Makes rendering performance better',
default=1,
)
(options, args) = parser.parse_args()
time_cursor = 0
coalesced_points = collections.defaultdict(int)
reader = csv.reader(open(options.input_file, 'r'), delimiter='\t')
first_element = True
print('[')
for row in reader:
time = int(row[0])
latitude = float(row[1])
longitude = float(row[2])
coalesced_points[str(latitude) + ',' + str(longitude)] += 1
if time > time_cursor + options.coalesce_time_interval:
if len(coalesced_points) > 0:
output_points = []
for location, count in coalesced_points.items():
if count >= options.minimum_count_threshold:
[latitude, longitude] = location.split(',')
output_points.append(float(latitude))
output_points.append(float(longitude))
output_points.append(count)
if not first_element:
print(','),
print([time, output_points])
first_element = False
time_cursor = time
coalesced_points = collections.defaultdict(int)
print(']')
|
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
def input():
return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
ns = []
while len(ns) < rantime:
n = random.randint(ran1, ran2)
if not n in ns:
ns.append(n)
return sorted(ns)
def rand_query(ran1, ran2, rantime):
r_query = []
while len(r_query) < rantime:
n_q = rand_ints_nodup(ran1, ran2, 2)
if not n_q in r_query:
r_query.append(n_q)
return sorted(r_query)
from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right
import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7
#############
# Main Code #
#############
N, Q = getNM()
sec = [getList() for i in range(N)]
section = []
for i in range(N):
s, t, x = sec[i]
section.append([s - x, t - x])
query = getArray(Q)
# 各queryがどのsectionの開区間[s, t)内にあるか
def event_sort(section, query):
s_n = len(section)
q_n = len(query)
task = []
for i in range(s_n):
s, t = section[i]
task.append((s, 0, i))
task.append((t, 1, i))
for i in range(q_n):
task.append((query[i], 2, i))
task.sort()
se = set()
### この問題専用 ###
res = [-1] * q_n # 答え
ignore = [-1] * s_n # まだ区間が生きているか
se_hp = [] # ignoreを元にまだ生きている区間の中でのxの最小値を求める
heapify(se_hp)
##################
for a, b, c in task:
if b == 1:
se.remove(c)
ignore[c] = 1 # これは無視していい
elif b == 0:
se.add(c)
heappush(se_hp, (sec[c][2], c)) # xの値をsecから引っ張る
else:
# 小さい順から抜け殻を捨てて回る
while se_hp and ignore[se_hp[0][1]] == 1:
heappop(se_hp)
if se_hp:
res[c] = se_hp[0][0]
else:
res[c] = -1
return res
for i in event_sort(section, query):
print(i)
section = [
[-3, 3],
[-1, 1],
[5, 7],
[1, 2],
]
query = [0, 1, 2, 3]
def event_sort(section, query):
s = len(section)
q = len(query)
# イベント生成
task = []
for i in range(s):
s, t = section[i]
task.append((s, 0, i))
task.append((t, 1, i))
for i in range(q):
task.append((query[i], 2, i))
task.sort()
# 引っかかってる場所の管理
se = set()
res = []
for a, b, c in task:
# ゴールが来ると削除
if b == 1:
se.remove(c)
# スタートが来ると追加
elif b == 0:
se.add(c)
# queについてなら
else:
res.append(deepcopy(se))
return res
# query内の点iがどのsection内の点j内にあるか
# [{0, 1}, {0, 3}, {0}, set()]
print(event_sort(section, query))
|
#!/usr/bin/env python
import logging, os, sys, unittest
import Test_pycosat, Test_sniper_logic, Test_z3
#####################
# UNITTEST DRIVER #
#####################
def unittest_driver() :
print
print "***********************************"
print "* RUNNING TEST SUITE FOR SNIPER *"
print "***********************************"
print
# make absolutely sure no leftover IR files exist.
if os.path.exists( "./IR*.db*" ) :
os.system( "rm ./IR*.db*" )
logging.info( " UNIT TEST DRIVER : deleted all rogue IR*.db* files." )
# run Test_pycosat tests
suite = unittest.TestLoader().loadTestsFromTestCase( Test_pycosat.Test_pycosat )
unittest.TextTestRunner( verbosity=2, buffer=True ).run( suite )
# run Test_z3 tests
suite = unittest.TestLoader().loadTestsFromTestCase( Test_z3.Test_z3 )
unittest.TextTestRunner( verbosity=2, buffer=True ).run( suite )
# run Test_sniper_logic tests
suite = unittest.TestLoader().loadTestsFromTestCase( Test_sniper_logic.Test_sniper_logic )
unittest.TextTestRunner( verbosity=2, buffer=True ).run( suite )
#########################
# THREAD OF EXECUTION #
#########################
if __name__ == "__main__" :
logging.basicConfig( format='%(levelname)s:%(message)s', level=logging.INFO )
unittest_driver()
# make absolutely sure no leftover IR files exist.
if os.path.exists( "./IR*.db*" ) :
os.system( "rm ./IR*.db*" )
logging.info( " UNIT TEST DRIVER : deleted all rogue IR*.db* files." )
#########
# EOF #
#########
|
from django import forms
from posts.models import Post, PostAttachment
from posts.utility import POST_FILTER_CHOICES, POST_TEXT_PLACEHOLDER, MAX_FILES_COUNT, MAX_FILES_COUNT_ERROR
class PostCreateForm(forms.Form):
post_text = forms.CharField(widget=forms.Textarea(
attrs={
'class': 'form-control',
'placeholder': POST_TEXT_PLACEHOLDER,
'id': 'post-text'
}
))
post_attachments = forms.ImageField(required=False, widget=forms.ClearableFileInput(
attrs={
'class': 'form-control',
'id': 'post_atts',
'multiple': True,
}
))
def clean(self):
cleaned_data = self.cleaned_data
#cc_myself = cleaned_data.get("post_text")
post_attachments = self.files.getlist("post_attachments")
if len(post_attachments) > MAX_FILES_COUNT:
msg = MAX_FILES_COUNT_ERROR.format(MAX_FILES_COUNT)
self._errors["post_attachments"] = self.error_class([msg])
return cleaned_data
class PostFilterForm(forms.Form):
post_filter_choice = forms.ChoiceField(
choices=POST_FILTER_CHOICES,
widget=forms.Select(
attrs={
'class': 'form-control form-control-sm'
}
))
|
# -*- coding: utf-8 -*-
"""
@author: Stephanie McCumsey
CIS 472 WINTER 2015
Naive Bayes
./nb <train> <test> <beta> <model>
the input I use to test : "run nb.py spambase-train.csv spambase-test.csv 1 nb.model"
"""
from __future__ import division
import sys
import pandas as pd
import numpy as np
import pdb
import math
def naiveBayes(trainingData, maxIter, beta):
'''
build the logisticTrain from training data
activation value determines if logisticTrain should update weights or not
'''
beta = float(beta)
base = 0
numCols = len(trainingData.columns[:-1].values)
weights = numCols * [0]
attrCountX1Y0 = numCols * [beta-1]
attrCountX1Y1 = numCols * [beta-1]
attrCountX0Y0 = numCols * [beta-1]
attrCountX0Y1 = numCols * [beta-1]
trainingData = trainingData.as_matrix()
py1 = 0
pdb.set_trace()
for i, row in enumerate(trainingData): #compute probabilities for all examples
label = row[-1]
if label == 1:
py1 += 1
for j in range(0, numCols):
if label == 1 and trainingData[i,j] == 1:
attrCountX1Y1[j] +=1
if label == 0 and trainingData[i,j] == 1:
attrCountX1Y0[j] +=1
if label == 1 and trainingData[i,j] == 0:
attrCountX0Y1[j] +=1
if label == 0 and trainingData[i,j] == 0:
attrCountX0Y0[j] +=1
py0 = trainingData.shape[0]-py1
# pdb.set_trace()
py0 = float(py0)
py1 = float(py1)
attrCountX0Y0 = np.divide(attrCountX0Y0, py0)
attrCountX0Y1 = np.divide(attrCountX0Y1, py1)
attrCountX1Y0 = np.divide(attrCountX1Y0, py0)
attrCountX1Y1 = np.divide(attrCountX1Y1, py1)
for i in range(0, numCols):
x1 = attrCountX1Y1[i]/attrCountX1Y0[i]
x0 = attrCountX0Y1[i]/attrCountX0Y0[i]
# pdb.set_trace()
weights[i] = math.log(x1) - math.log(x0)
# print weights[i]
base += math.log(attrCountX0Y1[i]/attrCountX0Y0[i])
# print base
# pdb.set_trace()
base += np.log(py1/py0)
return weights, base
def nbTest(w, b, data):
'''make prediction from learned perceptron
input: weightVector, base, test example
output: accuracy
'''
count = 0
for row in data:
p = 0
example = row[:-1]
for j, val in enumerate(example):
if val == 1:
p += w[j]
p += b
print p
accuracy = count/len(data) * 100
return accuracy
def writeFile(file, w, b, attributes):
''' write base and weights to the input.model file'''
file.write(str(b) + "\n")
for idx, w_i in enumerate(w):
file.write(attributes[idx] + " " + str(w_i) + "\n")
pass
def read_csv(CSVfile):
'''read input .cvs file with pandas'''
dataTable = pd.read_csv((CSVfile))
return dataTable
def main (trainCSV, testCSV, beta, modelFile):
trainingData = read_csv(trainCSV) #get feature vectors
testData = read_csv(testCSV)
attributes = trainingData.columns[:-1].values
maxIter = 100
w, b = naiveBayes(trainingData, maxIter, beta)
# print w, b
trainingData2 = trainingData.as_matrix()
testData = testData.as_matrix()
trainAccuracy = nbTest(w, b, trainingData2)
testAccuracy = nbTest(w, b, testData)
print "THESE RESULTS MAKE NO SENSE! UNABLE TO FIX as of turnin time"
# print "training accuracy :", trainAccuracy, "%"
# print "test accuracy :", testAccuracy, "%"
with open(modelFile, 'w+') as file :
writeFile(file, w, b, attributes)
return
if __name__ == "__main__":
args = sys.argv[1:]
main ( *args )
|
# 224. Basic Calculator
class Solution:
def calculate(self, s: 'str') -> 'int':
inBrac = []
BracCount = 0
res = 0
left = []
ops_sign = 1
count , length = 0, len(s)
for term in s:
count += 1
if term == '':
continue
if term == '(':
if BracCount == 0:
BracCount += 1
continue
else:
BracCount += 1
if BracCount > 0:
inBrac.append(term)
if term == ')':
BracCount -= 1
if BracCount == 0:
inBrac.pop()
res += self.calculate(inBrac) * ops_sign
inBrac = []
else:
continue
else:
if term == '+':
if len(left)>0:
res += ops_sign*(int(''.join(left)))
left = []
ops_sign = 1
elif term == '-':
if len(left)>0:
res += ops_sign*(int(''.join(left)))
left = []
ops_sign = -1
elif term.isdigit():
left.append(term)
if count == length:
if len(left)>0:
res += ops_sign*(int(''.join(left)))
left = []
return res
|
import codecs
import geeknoteConvertorLib
import unittest
from orgAnalyzer import OrgTable
from enmlOutput import OrgTableHTMLWriter
import utils
class TestGeeknoteConvertor(unittest.TestCase):
def test_replaceChar(self):
source = "* this is a bulletpoint"
target = "# this is a bulletpoint"
result = geeknoteConvertorLib.replaceChar(source, "*", "#")
self.assertEqual(target, result)
def test_replaceCharMutliple(self):
source = "** this is a bulletpoint"
target = "## this is a bulletpoint"
result = geeknoteConvertorLib.replaceChar(source, "*", "#")
self.assertEqual(target, result)
def test_escapeChars(self):
source = " # just something _ I'm writing"
target = " \# just something \_ I'm writing"
result = geeknoteConvertorLib.escapeChars(source, ["#", "_"])
self.assertEqual(target, result)
def test_escapeCharsMutliple(self):
source = " # just something __ I'm writing"
target = " \# just something \_\_ I'm writing"
result = geeknoteConvertorLib.escapeChars(source, ["#", "_"])
self.assertEqual(target, result)
def test_escapeCharsFile(self):
source = ["# test", "_ test"]
target = ["\\# test", "\\_ test"]
result = geeknoteConvertorLib.escapeCharsFile(source, ["#", "_"])
self.assertEqual(target, result)
def test_replaceCharFile(self):
source = ["# test", "_ test"]
target = ["* test", "_ test"]
result = geeknoteConvertorLib.replaceCharFile(source, "#", "*")
self.assertEqual(target, result)
def test_replaceEscapedChar(self):
source = "\\* this is a bulletpoint"
target = "* this is a bulletpoint"
result = geeknoteConvertorLib.replaceChar(source, "\\*", "*")
self.assertEqual(target, result)
def test_unsecapeChar(self):
source = "\* this is a bulletpoint"
target = "* this is a bulletpoint"
result = geeknoteConvertorLib.unescapeChars(source, ["\*", "*"])
self.assertEqual(target, result)
def testRemoveEmptyLines(self):
source = ["\n",""," ","\n", " ", "First Line", ""]
target = ["First Line", ""]
result = geeknoteConvertorLib.removeEmptyLines(source)
self.assertEqual(result, target)
def testOnlyEmptyLines(self):
source = ["\n",""," ","\n", " ", " \n", ""]
target = []
result = geeknoteConvertorLib.removeEmptyLines(source)
self.assertEqual(result, target)
def testWriteHtmlTable(self):
vTable = [["h"+str(i) for i in range(4)], ["c1"+str(i) for i in range(4)], ["c2"+str(i) for i in range(4)]]
vOrgTable = OrgTable.constructFromTable(vTable)
vHTMLWriter = OrgTableHTMLWriter(vOrgTable)
vResult = vHTMLWriter.parseHTML()
vTarget = ["<TABLE>"
,"<TR><TH>h0</TH><TH>h1</TH><TH>h2</TH><TH>h3</TH></TR>"
,"<TR><TD>c10</TD><TD>c11</TD><TD>c12</TD><TD>c13</TD></TR>"
,"<TR><TD>c20</TD><TD>c21</TD><TD>c22</TD><TD>c23</TD></TR>"
,"</TABLE>"]
self.assertEqual(vResult, vTarget)
def testIsOrgModeFile(self):
vSource = ["# -*-Org-*-", "First line"]
vResult = geeknoteConvertorLib.isOrgModeFile(vSource)
self.assertTrue(vResult)
def testIsOrgModeFileNot(self):
vSource = ["# Nothing", "First line"]
vResult = geeknoteConvertorLib.isOrgModeFile(vSource)
self.assertFalse(vResult)
def testFullConversionToGeeknote(self):
vSourceFile = codecs.open(filename="./tests/resources/test.org", mode="r", encoding="utf-8")
vDestinationFile = codecs.open(filename="./tests/resources/test.evernote.out", mode="w+", encoding="utf-8")
try:
geeknoteConvertorLib.org2ever(vSourceFile, vDestinationFile)
finally:
vSourceFile.close()
vDestinationFile.close()
vResultFile = codecs.open(filename="./tests/resources/test.evernote.out", mode="r", encoding="utf-8")
vTargetFile = codecs.open(filename="./tests/resources/test.evernote.target", mode="r", encoding="utf-8")
try:
vResult = utils.cacheFile(vResultFile)
vTarget = utils.cacheFile(vTargetFile)
self.assertEqual(vResult, vTarget)
except Exception as e:
self.assertTrue(False, "Exception happened while comparing files: "+str(e))
finally:
vResultFile.close()
vTargetFile.close()
def testFullConversionToOrgMode(self):
vSourceFile = codecs.open(filename="./tests/resources/test.evernote", mode="r", encoding="utf-8")
vDestinationFile = codecs.open(filename="./tests/resources/test.org.out", mode="w+", encoding="utf-8")
try:
geeknoteConvertorLib.ever2org(vSourceFile, vDestinationFile)
finally:
vSourceFile.close()
vDestinationFile.close()
vResultFile = codecs.open(filename="./tests/resources/test.org.out", mode="r", encoding="utf-8")
vTargetFile = codecs.open(filename="./tests/resources/test.org.target", mode="r", encoding="utf-8")
try:
vResult = utils.cacheFile(vResultFile)
vTarget = utils.cacheFile(vTargetFile)
self.assertEqual(vResult, vTarget)
except Exception as e:
self.assertTrue(False, "Exception happened while comparing files: "+str(e))
finally:
vResultFile.close()
vTargetFile.close()
|
"""
Created by Alex Wang on 2019-09-09
"""
import numpy as np
import sklearn
from sklearn.metrics import average_precision_score, precision_recall_curve
from eval_util import EvaluationMetrics
def cal_accuracy(predict_all, tags_all):
predict_all = np.concatenate(predict_all, axis=0)
tags_all = np.concatenate(tags_all, axis=0)
predict_argmax = np.argmax(predict_all, axis=1)
equal_arr = np.equal(tags_all, predict_argmax)
acc_num = sum([1 for item in equal_arr if item == True])
accuracy = acc_num * 1. / len(equal_arr)
return tags_all, predict_argmax, accuracy
def cal_weight_acc_and_recall(predict_all, tags_all, label_weight_map):
label_weight_map[0] = 0
predict_all = np.concatenate(predict_all, axis=0)
tags_all = np.concatenate(tags_all, axis=0)
predict_argmax = np.argmax(predict_all, axis=1)
equal_arr = np.equal(tags_all, predict_argmax)
acc_sum = sum([label_weight_map[predict_argmax[i]] for i in range(len(equal_arr)) if equal_arr[i] == True])
total_acc_sum = sum([label_weight_map[predict_argmax[i]] for i in range(len(equal_arr))])
recal_sum = sum([label_weight_map[tags_all[i]] for i in range(len(equal_arr)) if equal_arr[i] == True])
total_recall_sum = sum([label_weight_map[tags_all[i]] for i in range(len(equal_arr))])
true_num = sum([1 for item in equal_arr if item == True])
print('length of equal_arr:{}, true_num:{}, acc_sum:{:.4f}, total_acc_sum:{:.4f},'
' recal_sum:{:.4f}, total_recall_sum:{:.4f}'.
format(len(equal_arr), true_num, acc_sum, total_acc_sum, recal_sum, total_recall_sum))
if total_acc_sum == 0 or total_recall_sum == 0:
return 0, 0
return acc_sum * 1. / total_acc_sum, recal_sum * 1. / total_recall_sum
def cal_accuracy_weight(predict_all, tags_all, sample_weight_map):
predict_all = np.concatenate(predict_all, axis=0)
tags_all = np.concatenate(tags_all, axis=0)
predict_argmax = np.argmax(predict_all, axis=1)
equal_arr = np.equal(tags_all, predict_argmax)
acc_num = sum([1 for item in equal_arr if item == True])
accuracy = acc_num * 1. / len(equal_arr)
weight_devider = sum([max(sample_weight_map[predict_argmax[i]], sample_weight_map[tags_all[i]])
for i in range(len(tags_all))])
weight_correct = sum([sample_weight_map[predict_argmax[i]] for i in range(len(predict_argmax)) if
predict_argmax[i] == tags_all[i]])
return tags_all, predict_argmax, accuracy, weight_correct * 1. / weight_devider
def one_hot_encode(x, n_classes):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
return np.eye(n_classes)[x]
def top_n_accuracy(preds, truths, k):
"""
:param preds: n * num_class
:param truths: n * 1
:param k:
:return:
"""
best_n = np.argsort(preds, axis=1)[:, -k:]
# ts = np.argmax(truths, axis=1)
successes = 0
for i in range(truths.shape[0]):
if truths[i] in best_n[i, :]:
successes += 1
return float(successes) / truths.shape[0]
def test_map():
print(sklearn.__version__)
y_true = np.array([[1, 0, 1], [0, 1, 1]])
y_scores = np.array([[0.9, 0.2, 0.6], [0.8, 0.4, 0.7]])
print(average_precision_score(y_true, y_scores)) # 1.0
y_true = np.array([[1, 0, 1], [0, 0, 1]])
y_scores = np.array([[0.9, 0.2, 0.6], [0.8, 0.4, 0.7]])
print(average_precision_score(y_true, y_scores)) # nan
y_true_1 = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])
y_scores_1 = np.array([[0.008933052, 0.008828126, 0.008171955, 0.008292454, 0.008541321, 0.008941861, 0.008382217,
0.0093171345, 0.00887154, 0.00924207, 0.008431922, 0.010134701, 0.009067293, 0.008715886,
0.009046094, 0.008905834, 0.009304215, 0.0084734885, 0.009113058, 0.008725466, 0.00891771,
0.009029874, 0.009075413, 0.008714477, 0.008642749, 0.009606169, 0.009153075, 0.008541235,
0.008757088, 0.008895436, 0.008685254, 0.009073456, 0.009021303, 0.0091500655, 0.008602242,
0.008729225, 0.008651532, 0.00889056, 0.008539058, 0.008853196, 0.008528904, 0.009081975,
0.008880149, 0.009011798, 0.008814402, 0.008310771, 0.0086474195, 0.0088569755, 0.008831825,
0.008448529, 0.009218237, 0.008776604, 0.008426106, 0.009735886, 0.008201035, 0.0084616,
0.009321873, 0.008009138, 0.008612209, 0.008708076, 0.009205309, 0.009468417, 0.008822096,
0.009634672, 0.009128048, 0.009276119, 0.008234107, 0.008126152, 0.008283921, 0.008857169,
0.00962041, 0.009142644, 0.008910086, 0.008707047, 0.009858493, 0.008486905, 0.008855863,
0.0085881585, 0.009101725, 0.008991773, 0.008670437, 0.009238689, 0.008999442, 0.0087768845,
0.008720844, 0.008967684, 0.008977434, 0.008293324, 0.009205814, 0.00939858, 0.008000079,
0.009096718, 0.009747102, 0.008235297, 0.008520133, 0.008829131, 0.008627394, 0.008885311,
0.008586436, 0.008513904, 0.009096116, 0.00846825, 0.008941086, 0.009500336, 0.008395509,
0.0090844305, 0.008948396, 0.009351325, 0.008645779, 0.008186368, 0.009221275, 0.0087996945,
0.007919371],
[0.008863348, 0.008990947, 0.008665387, 0.008738659, 0.008795575, 0.0088580595, 0.008690404,
0.00893555, 0.008795486, 0.009135452, 0.00867635, 0.009216128, 0.008762823, 0.008837637,
0.008773661, 0.008889659, 0.00897715, 0.008758745, 0.008812604, 0.008703191, 0.009076109,
0.009168529, 0.008894875, 0.008803903, 0.008823888, 0.0090954555, 0.008903092, 0.008849877,
0.008811562, 0.008768541, 0.008788469, 0.008823974, 0.008926489, 0.009004612, 0.008925563,
0.008869472, 0.008670877, 0.0089344, 0.008665922, 0.008771081, 0.008865634, 0.008838625,
0.008891488, 0.008868792, 0.008716473, 0.008714524, 0.008965747, 0.008925145, 0.008503174,
0.008657943, 0.008897216, 0.008951141, 0.008816177, 0.009063996, 0.0084034335, 0.0088644065,
0.008865652, 0.008744331, 0.008692555, 0.0088317795, 0.0089199385, 0.008973046, 0.008862132,
0.00932832, 0.00900139, 0.008982577, 0.008714671, 0.00865364, 0.008616712, 0.008831579,
0.008901949, 0.009169578, 0.009096002, 0.00880188, 0.009072054, 0.008692439, 0.0089836605,
0.008842373, 0.008753372, 0.008847853, 0.008797723, 0.009024471, 0.008734624, 0.008726025,
0.008803052, 0.008897076, 0.009003864, 0.008712522, 0.008844816, 0.008648713, 0.008749454,
0.008825217, 0.009085626, 0.00866521, 0.00862834, 0.008855059, 0.008822056, 0.008927014,
0.0090179695, 0.008871902, 0.008933072, 0.008876315, 0.0090619, 0.008783536, 0.008819637,
0.008912323, 0.008794113, 0.00904266, 0.0086641675, 0.008623698, 0.008907507, 0.008743409,
0.008620076]])
print(top_n_accuracy(y_scores_1, y_true_1, 3))
# print(average_precision_score(y_true_1, y_scores_1))
eval_metrics = EvaluationMetrics(113, 113)
eval_metrics.accumulate(y_scores_1, y_true_1, [0, 0])
print(eval_metrics.get())
eval_metrics = EvaluationMetrics(113, 20)
eval_metrics.accumulate(y_scores_1, y_true_1, [0, 0])
print(eval_metrics.get())
def load_id_name_map(file_path, level_num=2):
previous_id = -1
id_name_map = {}
for i in range(level_num):
id_name_map[i] = {}
current_level = 0
for line in open(file_path, 'r'):
if line.strip() == '':
continue
elems = line.strip().split("\t")
if len(elems) < 2:
print('load_id_name_map error:{}'.format(line))
id, name = elems
id = int(id)
if id < previous_id:
current_level += 1
id_name_map[current_level][id] = name
previous_id = id
return id_name_map
if __name__ == '__main__':
test_map()
print(one_hot_encode([1, 3, 4, 6, 9, 14, 1], 20))
id_name_map = load_id_name_map('../new_struct/train_data_format/video_label_id_name_map_20200609.txt', level_num=3)
for i in range(2):
id_name_map_tmp = id_name_map[i]
print('level {}'.format(i))
for j in range(len(id_name_map_tmp)):
print('{}\t{}'.format(j, id_name_map_tmp[j]))
|
# -*- python -*-
# Optional Assignment: Underscore
# Your own custom Python Module!
# Did you know that you can actually create your own custom python module similar
# to the Underscore library in JavaScript? That may be hard to believe, as the things
# you've learned might seem simple (again, we try to make it look simple...,
# but in truth, you know how to create significant Python modules of your own.
# To create a custom Python module, you will simply add methods to a Python class!
# You will create the following methods from the underscore library as methods of the "_" object.
# Pay attention to what you have to change, in terms of parameters for each method as well as implementation.
# class Underscore(object):
# def map(self):
# # your code here
# def reduce(self):
# # your code here
# def find(self):
# # your code here
# def filter(self):
# # your code
# def reject(self):
# # your code
# you just created a library with 5 methods!
# let's create an instance of our class
# _ = Underscore() # yes we are setting our instance to a variable that is an underscore
# evens = _.filter([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0)
# print evens #=> [2, 4, 6]
# In the code above, you just created your own custom Python module/library that others
# can use! How can others use the methods in your library? By calling the properties
# stored in the class you defined (e.g. _.map(), _. reduce(), _.find(), etc).
# Your assignment is to implement the 5 methods above using delegating callbacks.
# You will have to modify the 5 methods to take in an array and a callback. Use what
# you learned in the previous chapter about callbacks to complete the assignment.
# One important concept that we want you to learn through this assignment is how
# to pass data to and from callbacks. You pass data to a callback with a parameter
# and you pass data from the callback back to the parent function with a return.
# While you are going through this assignment pay close attention to this relationship.
# To understand what each method does, please refer to the underscore library.
# Note that your method does not have to be as robust as underscore's; you just
# need to get the base functionality working. Therefore for most methods you will
# only have the list and a lambda as parameters, and for the lambda you will pass
# in each element and potentially a "memo" also known as a "collector".
# Note that some of these functions already exist in Python. We want you to explore
# how you might implement these yourself. Be aware that these tools exist to help
# work in a design idiom known as "functional programming". It's not something that
# we cover here, but is a topic you may want to explore on your own.
# It is mainly used in data science in recent years.
from Underscore import *
_ = Underscore()
multBy2 = _.map([1, 2, 3, 4, 5, 6], lambda x: x * 2)
print "multBy2:", multBy2 #=> [2, 4, 6, 8, 10, 12]
foldl1 = _.reduce([1, 2, 3, 4, 5, 6], lambda i, x: i + x)
print "foldl1:", foldl1 #=> 21
foldl2 = _.reduce([1, 2, 3, 4, 5, 6], lambda i, x: i + x, 13)
print "foldl2:", foldl2 #=> 34
firstEven = _.find([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0)
print "firstEven:", firstEven #=> 2
firstMod3 = _.find([1, 2, 3, 4, 5, 6], lambda x: x % 3 == 0)
print "firstMod3:", firstMod3 #=> 3
evens = _.filter([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0)
print "evens:", evens #=> [2, 4, 6]
odds = _.reject([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0)
print "odds:", odds #=> [1, 3, 5]
|
from helpers import SetUp
#self.MEM = memory.Memory(self.R, self.postMemBuff, self.preMemBuff, opcodeStr, arg1, arg2,
# arg3, dataval, address, self.numInstructions, self.cache, self.cycleList)
class Memory:
def __init__(self, R, postMemBuff, preMemBuff, opcodeStr, arg1, arg2, arg3,
dataval, address, numInstructions, cache, cycleList):
self.R = R
self.postMemBuff = postMemBuff
self.preMemBuff = preMemBuff
self.opcodeStr = opcodeStr
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
self.dataval = dataval
self.address = address
self.numInstructions = numInstructions
self.cache = cache
self.cycleList = cycleList
def run(self):
"""
mem unit handles LDUR and STUR operations. Calculate the memory addresses in this unit
STUR instructions never goes into the post-mem buffer. it just disappears
:return:
"""
# def checkCache(self, dataIndex, instructionIndex, isWriteToMem, dataToWrite):
i = self.preMemBuff[0]
#testing
self.postMemBuff = [-1, -1]
#from fetch
#if self.cache.checkCache(-1, i, 0, 0):
#some operation needed to check if there is any operations using needed register still in pipeline
if self.opcodeStr[i] == "STUR":
#if self.cache.checkCache(i, i, 1, self.R[self.arg1[i]]):
if (self.R[self.arg2[i]] + self.arg3[i] * 4) > self.address[-1]:
numAppend = ((self.R[self.arg2[i]] + self.arg3[i] * 4) - self.address[-1]) // 4
for z in range(numAppend):
self.address.append(self.address[-1] + 4)
self.dataval.append(0)
self.dataval[-1] = self.R[self.arg1[i]]
while (len(self.dataval) % 8 != 0):
self.address.append(self.address[-1] + 4)
self.dataval.append(0)
#added
elif (self.R[self.arg2[i]] + self.arg3[i] * 4 ) <= self.address[-1]:
for n in range(len(self.address)):
if self.R[self.arg2[i]] + (self.arg3[i] * 4 ) == self.address[n]:
self.dataval[n - self.numInstructions] = self.R[self.arg1[i]]
"""
elif (armState.R[self.arg2[i]] + self.arg3[i] * 4) <= self.address[-1]:
for n in range(len(self.address)):
if armState.R[self.arg2[i]] + (self.arg3[i] * 4) == self.address[n]:
self.dataval[n - self.numInstructs] = armState.R[self.arg1[i]]
"""
if self.cache.checkCache(i,i, 1, self.R[self.arg1[i]]):
#[readyToCycle, checkCacheNumSTUR] = (i, i, 1, self.R[self.arg1[i]])
#print(f"checkCacheNumSTUR : {checkCacheNumSTUR}")
#if readyToCycle:
self.preMemBuff[0] = self.preMemBuff[1]
self.preMemBuff[1] = -1
#LDUR sends data and address to post-mem buffer
if self.opcodeStr[i] == "LDUR": #LDUR Rd, [Rn #offset] #rd =arg1=destreg, rn = arg2=src1, arg3 = offset
for n in range(len(self.address)):
if self.R[self.arg2[i]] + (self.arg3[i] * 4) == self.address[n]:
dataIndex = (self.address[n] - (96 + (self.numInstructions * 4) )) // 4
self.postMemBuff = [self.dataval[n - self.numInstructions], i]
#testing...
#if self.cache.checkCache(i,i, 1, self.R[self.arg1[i]]):
if self.cache.checkCache(dataIndex, i, 0, self.R[self.arg1[i]]):
self.preMemBuff[0] = self.preMemBuff[1]
self.preMemBuff[1] = -1
#elif self.opcode[i] == 1986: #LDUR
# for n in range(len(self.address)):
# if armState.R[self.arg2[i]] + (self.arg3[i] * 4) == self.address[n]:
# # print("inlist")
# armState.R[self.arg1[i]] = self.dataval[n - self.numInstructs]
#elif self.opcodeStr[i] == "AND": #AND RD = Rm & Rn #rd=arg3=destreg, rm=arg2=src2, rn=arg1=src1
#self.postALUBuff = [self.R[self.arg1[i]] & self.R[self.arg2[i]], i]
return [self.preMemBuff, self.postMemBuff]
#how STUR is calculated in simulator.py (for reference)
"""
if (armState.R[self.arg2[i]] + (self.arg3[i]) * 4) > self.address[-1]:
numAppend = ((armState.R[self.arg2[i]] + self.arg3[i] * 4) - self.address[-1]) // 4
# print(armState.R[self.arg2[i]] + (self.arg3[i]*4))
# print(self.address[-1])
# print(numAppend)
for z in range(numAppend):
self.address.append(self.address[-1] + 4)
self.dataval.append(0)
self.dataval[-1] = armState.R[self.arg1[i]]
while (len(self.dataval) % 8 != 0):
self.address.append(self.address[-1] + 4)
self.dataval.append(0)
elif (armState.R[self.arg2[i]] + self.arg3[i] * 4) <= self.address[-1]:
for n in range(len(self.address)):
if armState.R[self.arg2[i]] + (self.arg3[i] * 4) == self.address[n]:
self.dataval[n - self.numInstructs] = armState.R[self.arg1[i]]
"""
|
import Plugin
class LogPlugin(Plugin.Plugin):
registeredCommands=""
priority=5
def init(self):
self.file=open('logs/backend.log','a')
def shutdown(self):
self.file.close()
def recvCommand(self, conElement):
self.file.write("{0}\n".format(str(conElement)))
self.file.flush()
return 'continue'
|
#!/usr/bin/env python3
from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D
from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
import xml.etree.ElementTree as ET
import threading
import time
from sys import stderr
tank_block = MoveTank(OUTPUT_B, OUTPUT_C)
largeMotor_Left= LargeMotor(OUTPUT_B)
largeMotor_Right= LargeMotor(OUTPUT_C)
#_________________________________________________________________________________________________________________________________
def Tank_seconds(stop, left_speed, right_speed, seconds):
# turn the motors on for a number of seconds
print("In tank_seconds", file=stderr)
start_time = time.time()
tank_block.on(right_speed=right_speed, left_speed=left_speed)
while time.time() < start_time + seconds:
if stop():
break
tank_block.off()
print('Leaving Tank_seconds', file=stderr)
#stopProcessing=False
#Tank_seconds(lambda:stopProcessing, left_speed=30, right_speed=30, rotations=5)
|
import colorsys
import random
import numpy as np
from skimage.measure import label, regionprops, find_contours
from matplotlib.patches import Polygon
from matplotlib import patches, lines
import matplotlib.pyplot as plt
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
def random_colors(N, bright=True):
"""
Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB.
"""
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
random.shuffle(colors)
return colors
def apply_mask(image, mask, color, alpha=0.5):
"""Apply the given mask to the image.
"""
for c in range(3):
image[:, :, c] = np.where(mask == 1,
image[:, :, c] *
(1 - alpha) + alpha * color[c] * 255,
image[:, :, c])
return image
def display_instances(image, boxes, masks, class_ids, class_names,
scores=None, title="",
figsize=(16, 16), ax=None,
show_mask=True, show_bbox=True,
colors=None, captions=None, filename=None):
"""
boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
masks: [height, width, num_instances]
class_ids: [num_instances]
class_names: list of class names of the dataset
scores: (optional) confidence scores for each box
title: (optional) Figure title
show_mask, show_bbox: To show masks and bounding boxes or not
figsize: (optional) the size of the image
colors: (optional) An array or colors to use with each object
captions: (optional) A list of strings to use as captions for each object
"""
# Number of instances
N = boxes.shape[0]
if not N:
print("\n*** No instances to display *** \n")
else:
assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]
# If no axis is passed, create one and automatically call show()
auto_show = False
if not ax:
fig, ax = plt.subplots(1, figsize=figsize)
auto_show = True
fig.tight_layout()
# Generate random colors
colors = colors or random_colors(N)
# Show area outside image boundaries.
height, width = image.shape[:2]
ax.set_ylim(height + 10, -10)
ax.set_xlim(-10, width + 10)
ax.axis('off')
ax.set_title(title)
masked_image = image.astype(np.uint32).copy()
for i in range(N):
color = colors[i]
# Bounding box
if not np.any(boxes[i]):
# Skip this instance. Has no bbox. Likely lost in image cropping.
continue
x1, y1, x2, y2 = boxes[i]
if show_bbox:
p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,
alpha=0.7, linestyle="dashed",
edgecolor=color, facecolor='none')
ax.add_patch(p)
# Label
if not captions:
class_id = class_ids[i]
score = scores[i] if scores is not None else None
label = class_names[class_id]
caption = "{} {:.3f}".format(label, score) if score else label
else:
caption = captions[i]
ax.text(x1, y1 + 8, caption,
color='green', size=15, backgroundcolor="none")
# Mask
mask = masks[:, :, i]
if show_mask:
masked_image = apply_mask(masked_image, mask, color)
# Mask Polygon
# Pad to ensure proper polygons for masks that touch image edges.
padded_mask = np.zeros(
(mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = mask
contours = find_contours(padded_mask, 0.5)
for verts in contours:
# Subtract the padding and flip (y, x) to (x, y)
verts = np.fliplr(verts) - 1
p = Polygon(verts, facecolor="none", edgecolor=color)
ax.add_patch(p)
ax.imshow(masked_image.astype(np.uint8))
if filename :
plt.savefig(filename, bbox_inches='tight', pad_inches=0)
plt.close()
else :
fig.canvas.draw()
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
return data
def rleToMask(rleString,height,width):
rows,cols = height,width
rleNumbers = [int(numstring) for numstring in rleString.split(' ')]
rlePairs = np.array(rleNumbers).reshape(-1,2)
img = np.zeros(rows*cols,dtype=np.uint8)
for index,length in rlePairs:
index -= 1
img[index:index+length] = 1
img = img.reshape(cols,rows)
img = img.T
return img
def makeBBox(mask) :
lbl_0 = label(mask)
props = regionprops(lbl_0)
height, width = mask.shape
y1, x1, y2, x2 = height, width, 0, 0
for prop in props :
minr, minc, maxr, maxc = prop.bbox
y1 = min(y1, minr)
x1 = min(x1, minc)
y2 = max(y2, maxr)
x2 = max(x2, maxc)
bbox = np.array([y1, x1, y2, x2])
return bbox
def viz_coco_example(img, imginfo, annotations, classnames) :
height, width = imginfo['height'], imginfo['width']
assert(img.shape[0] == height)
assert(img.shape[1] == width)
masks = SegmentationMask([ann['segmentation'] for ann in annotations], size=(width, height), mode='poly')
bboxes = []
classids = []
for ann in annotations :
x, y, width, height = ann['bbox']
x1, y1, x2, y2 = x, y, x+width, y+height
bboxes.append([y1, x1, y2, x2])
classids.append(ann['category_id']-1) # category_ids are 1-indexed in COCO datasets
classids = np.array(list(map(int, classids)))
bboxes = np.stack(bboxes, axis=0)
masks = masks.get_mask_tensor().numpy()
if masks.ndim == 2 :
masks = masks[np.newaxis, :, :]
masks = np.transpose(masks, (1, 2, 0))
display_instances(img, boxes=bboxes, masks=masks, class_ids=classids, class_names=classnames)
|
from torch.utils.data import Dataset
from torchvision import transforms
from skimage import io
import os
import json
import numpy as np
import torch
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
class CLEVR3(Dataset):
def __init__(self, root, mode):
# path = os.path.join(root, mode)
self.root = root
assert os.path.exists(root), 'Path {} does not exist'.format(root)
self.img_paths = []
for file in os.scandir(os.path.join(root, 'images')):
img_path = file.path
self.img_paths.append(img_path)
self.img_paths.sort()
self.masks = []
scene_path = os.path.join(root, 'scenes.json')
with open(scene_path,'r') as r:
scene_data = json.load(r)['scenes']
pointer = 0
for k,scene in enumerate(scene_data):
if pointer<len(self.img_paths) and scene['image_filename'] == os.path.split(self.img_paths[pointer])[-1]:
pointer += 1
self.masks.append(annotate_masks(scene))
def __getitem__(self, index):
img_path = self.img_paths[index]
img = io.imread(img_path)[:, :, :3]
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((128,128)),
transforms.ToTensor(),
])
img = transform(img)
mask_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((128,128), interpolation=Image.NEAREST),
])
mask = self.masks[index]
mask = [np.array(mask_transform(x[:, :, None].astype(np.uint8))) for x in mask]
mask = np.stack(mask, axis=0)
mask = torch.from_numpy(mask.astype(np.float)).float()
return img, mask
def __len__(self):
return len(self.img_paths)
import jaclearn.vision.coco.mask_utils as mask_utils
def _is_object_annotation_available(scene):
if len(scene['objects']) > 0 and 'mask' in scene['objects'][0]:
return True
return False
def _get_object_masks(scene):
"""Backward compatibility: in self-generated clevr scenes, the groundtruth masks are provided;
while in the clevr test data, we use Mask R-CNN to detect all the masks, and stored in `objects_detection`."""
if 'objects_detection' not in scene:
return scene['objects']
if _is_object_annotation_available(scene):
return scene['objects']
return scene['objects_detection']
def annotate_masks(scene):
if 'objects' not in scene and 'objects_detection' not in scene:
return list()
masks = [mask_utils.decode(i['mask']).astype('float32') for i in _get_object_masks(scene)]
return masks
|
from django.apps import AppConfig
class UnchockapiConfig(AppConfig):
name = 'unchockapi'
|
#------------------------------------------------------------------------------
# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)
#
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at:
#
# http://joinup.ec.europa.eu/system/files/EN/EUPL%20v.1.1%20-%20Licence.pdf
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
#------------------------------------------------------------------------------
import unittest
from wnodes.utils import utils
class UtilsTestCase(unittest.TestCase):
def test_guid(self):
'''test_guid'''
v = '%s' % (utils.guid())
self.assertEqual(type(v), str)
self.assertEqual(len(v),36)
def main():
suite = unittest.TestLoader().loadTestsFromTestCase(UtilsTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
main()
|
# Generated by Django 3.2 on 2021-07-12 17:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('film', '0018_auto_20210712_2012'),
]
operations = [
migrations.RemoveField(
model_name='film',
name='actor',
),
migrations.RemoveField(
model_name='film',
name='interact',
),
migrations.RemoveField(
model_name='film',
name='review',
),
migrations.RemoveField(
model_name='film',
name='search',
),
]
|
#!/usr/bin/env python
from __future__ import print_function
import json
import logging
import os
import shutil
import subprocess
import sys
import time
from shlex import split
def configure_logging():
logging.basicConfig(level=logging.DEBUG)
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logger_instance = logging.getLogger("general")
stderr = logging.StreamHandler(sys.stderr)
stderr.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
stderr.setLevel(logging.DEBUG)
logger_instance.addHandler(stderr)
return logger_instance
log = configure_logging()
class ShellCommand(object):
def __init__(self, command):
self.commands = command.split(" ")
def concatenate(self, other_command):
self.commands.append("&&")
self.commands.extend(other_command.build_list())
return self
def add_option(self, option, value=None, assignment_character=" "):
if value is None:
self.commands.append(option)
else:
if assignment_character == " ":
self.commands.append(option)
self.commands.append(value)
else:
self.commands.append(option + assignment_character + value)
return self
def add_arg(self, value):
self.commands.append(value)
return self
def build_list(self):
return self.commands
def build_string(self):
return " ".join(self.commands)
def get_tag(params):
if "tag_file" in params:
with open(params["tag_file"], "r") as fh:
return fh.read().strip()
return "latest"
def get_destination(params):
tag = get_tag(params)
return params["registry"] + "/" + params["image_name"] + ":" + tag
def get_dockerfile(params):
if "dockerfile" in params:
return params["dockerfile"]
return "Dockerfile"
def get_context(params):
if "build_context" in params:
return "/tmp/build/put/" + params["build_context"]
return None
def set_argument(argument_store, argument_name, value):
if value is not None:
argument_store[argument_name] = value
def build_kaniko_command(payload):
argument_store = {}
params = payload["params"]
set_argument(argument_store, "--context", get_context(params))
set_argument(argument_store, "--destination", get_destination(params))
set_argument(argument_store, "--dockerfile", get_dockerfile(params))
command = ShellCommand("executor")
for argument_key in argument_store:
command.add_option(argument_key, argument_store[argument_key], "=")
return command
def do_docker_auth(source, kaniko_home_folder):
kaniko_docker_folder = kaniko_home_folder + ".docker/"
if "docker_config_file" in source:
if not os.path.exists(kaniko_docker_folder):
os.makedirs(kaniko_docker_folder)
shutil.copyfile(source["docker_config_file"], kaniko_docker_folder + "config.json")
def execute_kaniko_command(payload, kaniko_build_command):
command_run_logs = ''
# Run command
proc = subprocess.Popen(split(kaniko_build_command), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
byte = proc.stdout.read(1)
if byte:
sys.stderr.buffer.write(byte)
sys.stderr.flush()
command_run_logs += str(byte, 'utf-8')
else:
break
# Wait for command to exit
while proc.poll() is None:
# Process hasn't exited yet, let's wait some
time.sleep(0.5)
last_line = command_run_logs.strip().split("\n")[-1]
log.info("Proc exited with code: " + str(proc.returncode))
if proc.returncode == 0:
sha = last_line.split(" ")[4]
concourse_output = {
"version": {"ref": sha},
"metadata": [
{"name": "image_name", "value": payload["params"]["image_name"]},
{"name": "registry", "value": payload["params"]["registry"]},
{"name": "tag", "value": get_tag(payload["params"])},
]
}
log.info(json.dumps(concourse_output))
print(json.dumps(concourse_output))
def run(payload, args):
if payload["source"] is None:
payload["source"] = {}
with open("payload.json", "w") as fh:
fh.write(json.dumps(payload))
log.info("Payload: " + str(payload))
kaniko_home_folder = "/kankiko/"
if not len(args) == 0 and args[0] == "test":
kaniko_home_folder = os.getcwd() + "/test/kaniko/"
do_docker_auth(payload["source"], kaniko_home_folder)
kaniko_command = build_kaniko_command(payload)
kaniko_command_string = kaniko_command.build_string()
log.info("Command: " + kaniko_command_string)
if len(args) == 0 or args[0] != "test":
execute_kaniko_command(payload, kaniko_command_string)
run(json.loads(sys.stdin.read()), sys.argv[1:])
|
from rubicon_ml.exceptions import RubiconException
from rubicon_ml.sklearn.estimator_logger import EstimatorLogger
from rubicon_ml.sklearn.utils import log_parameter_with_warning
class FilterEstimatorLogger(EstimatorLogger):
"""The filter logger for sklearn estimators. Use this
logger to either select or ignore specific parameters
for logging.
Parameters
----------
estimator : a sklearn estimator, optional
The estimator
experiment : rubicon.client.Experiment, optional
The experiment to log the parameters and metrics to.
step_name : str, optional
The name of the pipeline step.
select : list, optional
The list of parameters on this estimator that you'd like
to log. All other parameters will be ignored.
ignore : list, optional
The list of parameters on this estimator that you'd like
to ignore by not logging. The other parameters will be logged.
ignore_all : bool, optional
Ignore all parameters if true.
"""
def __init__(
self,
estimator=None,
experiment=None,
step_name=None,
select=[],
ignore=[],
ignore_all=False,
):
if ignore and select:
raise RubiconException("provide either `select` OR `ignore`, not both")
self.ignore = ignore
self.ignore_all = ignore_all
self.select = select
super().__init__(estimator=estimator, experiment=experiment, step_name=step_name)
def log_parameters(self):
if self.ignore_all:
return
for name, value in self.estimator.get_params().items():
if (self.ignore and name not in self.ignore) or (self.select and name in self.select):
log_parameter_with_warning(self.experiment, f"{self.step_name}__{name}", value)
|
from concurrent import futures
from concurrent.futures import ProcessPoolExecutor
import os
import sys
import threading
import time
from . import slurm
from .remote import INFILE_FMT, OUTFILE_FMT
from .util import random_string, local_filename, call
from . import pickling
import logging
import importlib
import re
import signal
class RemoteException(Exception):
def __init__(self, error, job_id):
self.error = error
self.job_id = job_id
def __str__(self):
return str(self.job_id) + "\n" + self.error.strip()
SLURM_STATES = {
"Failure": [
"CANCELLED",
"BOOT_FAIL",
"DEADLINE",
"FAILED",
"NODE_FAIL",
"OUT_OF_MEMORY",
"PREEMPTED",
"STOPPED",
"TIMEOUT"
],
"Success": [
"COMPLETED"
],
"Ignore": [
"RUNNING",
"CONFIGURING",
"COMPLETING",
"PENDING",
"RESV_DEL_HOLD",
"REQUEUE_FED",
"REQUEUE_HOLD",
"REQUEUED",
"RESIZING"
],
"Unclear": [
"SUSPENDED",
"REVOKED",
"SIGNALING",
"SPECIAL_EXIT",
"STAGE_OUT"
]
}
class FileWaitThread(threading.Thread):
"""A thread that polls the filesystem waiting for a list of files to
be created. When a specified file is created, it invokes a callback.
"""
def __init__(self, callback, interval=1):
"""The callable ``callback`` will be invoked with value
associated with the filename of each file that is created.
``interval`` specifies the polling rate.
"""
threading.Thread.__init__(self)
self.callback = callback
self.interval = interval
self.waiting = {}
self.lock = threading.Lock()
self.shutdown = False
def stop(self):
"""Stop the thread soon."""
with self.lock:
self.shutdown = True
def waitFor(self, filename, value):
"""Adds a new filename (and its associated callback value) to
the set of files being waited upon.
"""
with self.lock:
self.waiting[filename] = value
def run(self):
def handle_completed_job(job_id, filename, failed_early):
self.callback(job_id, failed_early)
del self.waiting[filename]
while True:
with self.lock:
if self.shutdown:
return
# Poll for each file.
for filename in list(self.waiting):
job_id = self.waiting[filename]
if os.path.exists(filename):
# Check for output file as a fast indicator for job completion
handle_completed_job(job_id, filename, False)
else:
# If the output file was not found, we determine the job status so that
# we can recognize jobs which failed hard (in this case, they don't produce output files)
stdout, _, exit_code = call("scontrol show job {}".format(job_id))
# We have to re-check for the output file since this could be created in the mean time
if os.path.exists(filename):
handle_completed_job(job_id, filename, False)
else:
if exit_code != 0:
logging.error(
"Couldn't call scontrol to determine job's status. {}. Continuing to poll for output file. This could be an indicator for a failed job which was already cleaned up from the slurm db. If this is the case, the process will hang forever."
)
else:
job_state_search = re.search('JobState=([a-zA-Z_]*)', str(stdout))
if job_state_search:
job_state = job_state_search.group(1)
if job_state in SLURM_STATES["Failure"]:
handle_completed_job(job_id, filename, True)
elif job_state in SLURM_STATES["Ignore"]:
# This job state can be ignored
pass
elif job_state in SLURM_STATES["Unclear"]:
logging.warn("The job state for {} is {}. It's unclear whether the job will recover. Will wait further".format(job_id, job_state))
elif job_state in SLURM_STATES["Success"]:
logging.error(
"Job state is completed, but {} couldn't be found.".format(
filename
)
)
handle_completed_job(job_id, filename, True)
time.sleep(self.interval)
class SlurmExecutor(futures.Executor):
"""Futures executor for executing jobs on a Slurm cluster."""
def __init__(
self,
debug=False,
keep_logs=False,
job_resources=None,
job_name=None,
additional_setup_lines=[],
**kwargs
):
os.makedirs(local_filename(), exist_ok=True)
self.debug = debug
self.job_resources = job_resources
self.additional_setup_lines = additional_setup_lines
self.job_name = job_name
self.was_requested_to_shutdown = False
# `jobs` maps from job id to future and workerid
# In case, job arrays are used: job id and workerid are in the format of
# `job_id-job_index` and `workerid-job_index`.
self.jobs = {}
self.job_outfiles = {}
self.jobs_lock = threading.Lock()
self.jobs_empty_cond = threading.Condition(self.jobs_lock)
self.keep_logs = keep_logs
self.wait_thread = FileWaitThread(self._completion)
self.wait_thread.start()
signal.signal(signal.SIGINT, self.handle_kill)
signal.signal(signal.SIGTERM, self.handle_kill)
self.meta_data = {}
if "logging_config" in kwargs:
self.meta_data["logging_config"] = kwargs["logging_config"]
def handle_kill(self,signum, frame):
self.wait_thread.stop()
job_ids = ",".join(str(id) for id in self.jobs.keys())
print("A termination signal was registered. The following jobs on slurm are still running:\n{}".format(job_ids))
sys.exit(130)
def _start(self, workerid, job_count=None, job_name=None):
"""Start a job with the given worker ID and return an ID
identifying the new job. The job should run ``python -m
cfut.remote <workerid>.
"""
return slurm.submit(
"{} -m cluster_tools.remote {}".format(sys.executable, workerid),
job_resources=self.job_resources,
job_name=self.job_name if self.job_name is not None else job_name,
additional_setup_lines=self.additional_setup_lines,
job_count=job_count,
)
def _cleanup(self, jobid):
"""Given a job ID as returned by _start, perform any necessary
cleanup after the job has finished.
"""
if self.keep_logs:
return
outf = slurm.OUTFILE_FMT.format(str(jobid))
try:
os.unlink(outf)
except OSError:
pass
def _completion(self, jobid, failed_early):
"""Called whenever a job finishes."""
with self.jobs_lock:
fut, workerid = self.jobs.pop(jobid)
if not self.jobs:
self.jobs_empty_cond.notify_all()
if self.debug:
print("job completed: {}".format(jobid), file=sys.stderr)
if failed_early:
# If the code which should be executed on a node wasn't even
# started (e.g., because python isn't installed or the cluster_tools
# couldn't be found), no output was written to disk. We only noticed
# this circumstance because the whole slurm job was marked as failed.
# Therefore, we don't try to deserialize pickling output.
success = False
result = "Job submission/execution failed. Please look into the log file at {}".format(
slurm.OUTFILE_FMT.format(jobid)
)
else:
with open(OUTFILE_FMT % workerid, "rb") as f:
outdata = f.read()
success, result = pickling.loads(outdata)
if success:
fut.set_result(result)
else:
fut.set_exception(RemoteException(result, jobid))
# Clean up communication files.
if os.path.exists(INFILE_FMT % workerid):
os.unlink(INFILE_FMT % workerid)
if os.path.exists(OUTFILE_FMT % workerid):
os.unlink(OUTFILE_FMT % workerid)
self._cleanup(jobid)
def ensure_not_shutdown(self):
if self.was_requested_to_shutdown:
raise RuntimeError(
"submit() was invoked on a SlurmExecutor instance even though shutdown() was executed for that instance."
)
def submit(self, fun, *args, **kwargs):
"""Submit a job to the pool."""
fut = futures.Future()
self.ensure_not_shutdown()
# Start the job.
workerid = random_string()
funcser = pickling.dumps((fun, args, kwargs, self.meta_data), True)
with open(INFILE_FMT % workerid, "wb") as f:
f.write(funcser)
job_name = fun.__name__
jobid = self._start(workerid, job_name=job_name)
if self.debug:
print("job submitted: %i" % jobid, file=sys.stderr)
# Thread will wait for it to finish.
self.wait_thread.waitFor(OUTFILE_FMT % workerid, jobid)
with self.jobs_lock:
self.jobs[jobid] = (fut, workerid)
fut.slurm_jobid = jobid
return fut
def map_to_futures(self, fun, allArgs):
self.ensure_not_shutdown()
allArgs = list(allArgs)
futs = []
workerid = random_string()
get_workerid_with_index = lambda index: workerid + "_" + str(index)
# Submit jobs eagerly
for index, arg in enumerate(allArgs):
fut = futures.Future()
# Start the job.
funcser = pickling.dumps((fun, [arg], {}, self.meta_data), True)
infile_name = INFILE_FMT % get_workerid_with_index(index)
with open(infile_name, "wb") as f:
f.write(funcser)
futs.append(fut)
job_count = len(allArgs)
job_name = fun.__name__
jobid = self._start(workerid, job_count, job_name)
get_jobid_with_index = lambda index: str(jobid) + "_" + str(index)
if self.debug:
print(
"main job submitted: %i. consists of %i subjobs." % (jobid, job_count),
file=sys.stderr,
)
with self.jobs_lock:
for index, fut in enumerate(futs):
jobid_with_index = get_jobid_with_index(index)
# Thread will wait for it to finish.
workerid_with_index = get_workerid_with_index(index)
self.wait_thread.waitFor(
OUTFILE_FMT % workerid_with_index, jobid_with_index
)
fut.slurm_jobid = jobid
fut.slurm_jobindex = index
self.jobs[jobid_with_index] = (fut, workerid_with_index)
return futs
def shutdown(self, wait=True):
"""Close the pool."""
self.was_requested_to_shutdown = True
if wait:
with self.jobs_lock:
if self.jobs:
self.jobs_empty_cond.wait()
self.wait_thread.stop()
self.wait_thread.join()
def map(self, func, args, timeout=None, chunksize=None):
if chunksize is not None:
logging.warning(
"The provided chunksize parameter is ignored by SlurmExecutor."
)
start_time = time.time()
futs = self.map_to_futures(func, args)
results = []
# Return a separate generator as iterator to avoid that the
# map() method itself becomes a generator.
# If map() was a generator, the submit() calls would be invoked
# lazily which can lead to a shutdown of the executor before
# the submit calls are performed.
def result_generator():
for fut in futs:
passed_time = time.time() - start_time
remaining_timeout = (
None if timeout is None else timeout - passed_time
)
yield fut.result(remaining_timeout)
return result_generator()
def map_unordered(self, func, args):
futs = self.map_to_futures(func, args)
# Return a separate generator to avoid that map_unordered
# is executed lazily.
def result_generator():
for fut in futures.as_completed(futs):
yield fut.result()
return result_generator()
def get_existent_kwargs_subset(whitelist, kwargs):
new_kwargs = {}
for arg_name in whitelist:
if arg_name in kwargs:
new_kwargs[arg_name] = kwargs[arg_name]
return new_kwargs
PROCESS_POOL_KWARGS_WHITELIST = ["max_workers", "mp_context", "initializer", "initargs"]
class WrappedProcessPoolExecutor(ProcessPoolExecutor):
def __init__(self, **kwargs):
new_kwargs = get_existent_kwargs_subset(PROCESS_POOL_KWARGS_WHITELIST, kwargs)
ProcessPoolExecutor.__init__(self, **new_kwargs)
def map_unordered(self, func, args):
futs = self.map_to_futures(func, args)
# Return a separate generator to avoid that map_unordered
# is executed lazily (otherwise, jobs would be submitted
# lazily, as well).
def result_generator():
for fut in futures.as_completed(futs):
yield fut.result()
return result_generator()
def map_to_futures(self, func, args):
futs = [self.submit(func, arg) for arg in args]
return futs
class SequentialExecutor(WrappedProcessPoolExecutor):
def __init__(self, **kwargs):
kwargs["max_workers"] = 1
WrappedProcessPoolExecutor.__init__(self, **kwargs)
def pickle_identity(obj):
return pickling.loads(pickling.dumps(obj, True))
def pickle_identity_executor(func, *args, **kwargs):
result = func(*args, **kwargs)
return pickle_identity(result)
class PickleExecutor(WrappedProcessPoolExecutor):
def submit(self, _func, *_args, **_kwargs):
(func, args, kwargs) = pickle_identity((_func, _args, _kwargs))
return super().submit(pickle_identity_executor, func, *args, **kwargs)
def get_executor(environment, **kwargs):
if environment == "slurm":
return SlurmExecutor(**kwargs)
elif environment == "multiprocessing":
return WrappedProcessPoolExecutor(**kwargs)
elif environment == "sequential":
return SequentialExecutor(**kwargs)
elif environment == "test_pickling":
return PickleExecutor(**kwargs)
raise Exception("Unknown executor: {}".format(environment))
|
# -*- coding: utf-8 -*-
# 卷积神经网络训练mnist
# 训练20000次后,再进行测试,测试精度可以达到99%。
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32,[None,784])
y_actual = tf.placeholder(tf.float32,shape=[None,10])
# 定义四个函数,分别用于初始化权值W,初始化偏置项b, 构建卷积层和构建池化层。
# 初始化权值W
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
# 初始化偏置项b
def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial)
# 构建卷积层
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') #strides卷积模板移动的步长,padding 边界处理方式
# 构建池化层
def max_pool(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
# 接下来构建网络。整个网络由两个卷积层(包含激活层和池化层),一个全连接层,一个dropout层和一个softmax层组成。
# 构建网络
x_image = tf.reshape(x,[-1,28,28,1]) #转换输入数据shape,以便于用于网络中
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1) #第一个卷积层
h_pool1 = max_pool(h_conv1) #第一个池化层
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2) #第二个卷积层
h_pool2 = max_pool(h_conv2) #第二个池化层
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64]) #reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1) #第一个全连接层
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob) #dropout层
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
y_predict = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2) #softmax层
# 训练模型
cross_entropy = -tf.reduce_sum(y_actual * tf.log(y_predict)) #求交叉熵
# train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) #用梯度下降法使得残差最小
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) # 梯度下降法
correct_prediction = tf.equal(tf.argmax(y_predict,1),tf.argmax(y_actual,1)) #在测试阶段,测试准确度计算
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float")) #多个批次的准确度均值
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
for i in range(20000): #训练阶段,迭代1000次
batch = mnist.train.next_batch(50) #每批次50行数据
if (i%100==0): #每训练100次,执行一次
train_acc = accuracy.eval(feed_dict={x:batch[0],y_actual:batch[1],keep_prob:1.0})
print 'step %d, training accuracy %g' %(i,train_acc)
train_step.run(feed_dict = {x: batch[0], y_actual: batch[1], keep_prob: 0.5})
test_acc = accuracy.eval(feed_dict={x:mnist.test.images,y_actual:mnist.test.labels,keep_prob:1.0})
print "test accuracy %g" %test_acc
#
# cross_entropy = -tf.reduce_sum(y_actual * tf.log(y_predict)) # 交叉熵
# train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) # 梯度下降法
# correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1))
# accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # 精确度计算
# sess = tf.InteractiveSession()
# sess.run(tf.initialize_all_variables())
# for i in range(20000):
# batch = mnist.train.next_batch(50)
# if i % 100 == 0: # 训练100次,验证一次
# train_acc = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 1.0})
# print('step', i, 'training accuracy', train_acc)
# train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
#
# test_acc = accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
# print("test accuracy", test_acc)
|
# Generated by Django 3.1.7 on 2021-04-17 11:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20210416_0251'),
]
operations = [
migrations.AddField(
model_name='room',
name='current_song',
field=models.CharField(max_length=50, null=True),
),
]
|
#
from evennia import create_object
from typeclasses import rooms, exits, characters
from features import radio_objects
from evennia.utils import search
radio = create_object(radio_objects.RadioObj, key="Radio", location=caller.location)
radio.db.radio_switch = True
channel = search.search_channel("Public")[0]
channel.connect(radio)
|
#!/usr/bin/env python3
from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D
from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
from ev3dev2.button import Button
import xml.etree.ElementTree as ET
import threading
import time
from sys import stderr
import os
#from LookingBlackLine_stopBlack import LookingBlackLine_stopBlack
from FollowBlackLine_rotations import FollowBlackLine_rotations
from LookingBlackLine_rotations import LookingBlackLine_rotations
from Delay_seconds import Delay_seconds
'''
from onForRotations import onForRotations
from tank_rotations import tank_rotations
from Degrees_aim import turn_to_degrees
from reset_gyro import reset_gyro
'''
'''
colourAttachment = ColorSensor(INPUT_4)
colourLeft = ColorSensor(INPUT_3) # bcs apparently they have to be backwards...
colourRight = ColorSensor(INPUT_2)
gyro = GyroSensor(INPUT_1)
steering_drive = MoveSteering(OUTPUT_B, OUTPUT_C)
tank_block = MoveTank(OUTPUT_B, OUTPUT_C)
largeMotor_Left= LargeMotor(OUTPUT_B)
largeMotor_Right= LargeMotor(OUTPUT_C)
# mediumMotor_Left ]\
# = MediumMotor(OUTPUT_A)
mediumMotor = MediumMotor(OUTPUT_D)
'''
'''
x=0
stopProcessing=False
while True:
print(x, file= stderr)
print(colourAttachment.raw, file=stderr)
x = x + 1
Delay_seconds(lambda:stopProcessing, 5)
'''
colourAttachment = ColorSensor(INPUT_4)
def colourAttachment_values():
button = Button()
stop = False
os.system('setfont Lat15-TerminusBold14')
# os.system('setfont Lat15-TerminusBold32x16') # Try this larger font
print('insert black', file=stderr)
print('insert black')
button.wait_for_pressed(['enter'])
black = colourAttachment.raw
print('insert green', file=stderr)
print('insert green')
Delay_seconds(lambda:stop, 2)
green = colourAttachment.raw
print('insert red', file=stderr)
print('insert red')
Delay_seconds(lambda:stop, 2)
red = colourAttachment.raw
print('insert yellow', file=stderr)
print('insert yellow')
Delay_seconds(lambda:stop, 2)
yellow = colourAttachment.raw
print('insert white', file=stderr)
print('insert white')
Delay_seconds(lambda:stop, 2)
white = colourAttachment.raw
attachment_values = [black, green, red, yellow, white]
print(black[0], file=stderr)
return attachment_values
attachment_values = colourAttachment_values()
print('attachment_values: {}'.format(attachment_values))
'''
Sensor 1 = {nothing:(63, 66, 152)
black:(31, 39, 78)
red:(208, 54, 63)
yellow:(307, 250, 105)
white:(327, 401, 499)
brown:(73, 56, 72)}
Sensor 2 = {nothing:(43, 44, 41)
black:(22, 29, 24)
red:(171, 36, 22)
yellow:(264, 169, 44)
white:(277, 273, 218)
brown:(57, 35, 24)}
'''
#LookingBlackLine_rotations(speed= 18, rotations = 5, colourSensor= "RIGHT", Turning = .15,lineSide = "LEFT", stop = False )
#FollowBlackLine_rotations(speed= 10, rotations = 5, colourSensor= "RIGHT", lineSide = "LEFT", stop = False )
#RIGHT = 4423q
#turn_to_degrees(lambda:stopProcessing, speed=20, degrees=90) # speeds over 5 are inaccurate but still get more or less right (to be fair, they are inaccurate by the same amount each time...)
#Delay_seconds(lambda:stopProcessing, 2)8
#turn_to_degrees(lambda:stopProcessing, speed=5, degrees=90) # second time at slow speed for accuracy
#tank_rotations(lambda:stopProcessing, left_speed=30, right_speed=20, rotations=0.6 )
#onForRotations(lambda:stopProcessing, motor=mediumMotor, speed=-30, rotations=-0.2, gearRatio=1.4)
|
from direct.showbase.ShowBase import ShowBase
from panda3d.core import WindowProperties
from direct.gui.OnscreenText import OnscreenText
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGui import *
import ctypes
class UserInterface:
def __init__(self, fullscreen : bool = False):
self.interface01 = [] # loading animation
self.interface02 = [] # displaying preloaded data
self.fullscreen = fullscreen
self.using_captions = False
self.Indicators = []
return None
def create(self):
# do stuff
return None
def show(self,element):
# do stuff
return None
def hide(self,element):
# do stuff
return None
def toggleFullScreen(self):
self.fullscreen = not self.fullscreen
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
self.window_properties = WindowProperties()
if self.fullscreen:
self.window_properties.setFullscreen(1)
self.window_properties.setSize(screensize)
else:
self.window_properties.setFullscreen(0)
base.win.requestProperties(self.window_properties)
def toggleIndicators(self):
self.using_captions = not self.using_captions
if self.using_captions:
if not len(self.Indicators):# never created before
for x in range(4):
node = TextNode('text%s' % str(x))
node.setText('') # default
textNdp = render.attachNewNode(node)
self.Indicators.append(textNdp)
else:
for x in self.Indicators:
x.show()
ShowBase.task_mgr.add(self.updateIndicators,'captionUpdatingTask')
else:
for x in self.Indicators:
x.hide()
def updateIndicators(self, task, data):
if self.using_captions:
return task.cont
else:
return task.done
|
# Tamanho de strings.
# Faça um programa que leia 2 strings e informe o
# conteúdo delas seguido do seu comprimento.
# Informe também se as duas strings possuem o mesmo
# comprimento e são iguais ou diferentes no conteúdo.
if __name__ == '__main__':
mensagem_1 = input('Digite uma frase: ').strip()
mensagem_2 = input('Digite outra frase: ').strip()
comprimento_mensagem_1 = len(mensagem_1)
comprimento_mensagem_2 = len(mensagem_2)
print('{}: {} caracteres'.format(mensagem_1, comprimento_mensagem_1))
print('{}: {} caracteres'.format(mensagem_2, comprimento_mensagem_2))
possuem_o_mesmo_comprimento = comprimento_mensagem_1 == comprimento_mensagem_2
if possuem_o_mesmo_comprimento:
print('As duas mensagens possuem o mesmo comprimento!')
else:
print('As duas mensagens NÃO possuem o mesmo comprimento!')
if possuem_o_mesmo_comprimento and mensagem_1 == mensagem_2:
print('As duas mensagens são iguais!')
else:
print('As duas mensagens são diferentes!')
|
#!/usr/bin/python3
# -*- coding: UTF-8 -*-#
import cgitb
import cgi; cgitb.enable() # opcional para debug
import logging
import inject
import re
import psycopg2
import codecs
import sys
sys.path.insert(0, '../../python')
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
logging.basicConfig(level=logging.DEBUG)
args = cgi.FieldStorage()
if "i" not in args:
print("Status: 403 Forbidden\r\n\r\n")
print("no argumentos")
sys.exit(1)
fid = args.getvalue("i")
#if not re.search('/([a-zA-Z]+\-*)+/', fid):
# print("Status: 403 Forbidden\r\n\r\n")
# print("no valor {}".format(fid))
# sys.exit(1)
from model.systems.files.files import Files
from model.config import Config
config = Config('server-config.cfg')
def _getDatabase(config):
host = config.configs['database_host']
dbname = config.configs['database_database']
user = config.configs['database_user']
passw = config.configs['database_password']
return psycopg2.connect(host=host, dbname=dbname, user=user, password=passw)
con = _getDatabase(config)
try:
if fid == 'e':
print("Content-Type: {}; charset=utf-8".format('text/csv'))
print("Content-Disposition: attachment; filename=\"ingeso-errores.csv\"")
print()
cur = con.cursor()
cur.execute('select error, names, dni, email, comment, created from ingreso.errors')
for c in cur:
errors = ''
for a in c:
errors = errors + str(a).replace("\"", '').replace(';', ',') + ';'
print(errors)
elif fid == 'p':
print("Content-Type: {}; charset=utf-8".format('text/csv'))
print("Content-Disposition: attachment; filename=\"ingeso.csv\"")
print()
cur = con.cursor()
cur.execute('select name, lastname, dni, u.created, email from profile.users u left join profile.mails m on (u.id = m.user_id and m.confirmed)')
for c in cur:
errors = ''
for a in c:
errors = errors + (str(a).replace("\"", '').replace(';', ',') if a is not None else ' ') + ';'
print(errors)
else:
print("Status: 403 Forbidden\r\n\r\n")
print()
finally:
con.close()
|
import numpy as np
import math
import matplotlib.pyplot as plt
def main():
# We format the data matrix so that each row is the feature for one sample.
# The number of rows is the number of data samples.
# The number of columns is the dimension of one data sample.
X = np.load('q1x.npy')
N = X.shape[0]
Y = np.load('q1y.npy')
# To consider intercept term, we append a column vector with all entries=1.
# Then the coefficient correpsonding to this column is an intercept term.
X = np.concatenate((np.ones((N, 1)), X), axis=1)
if __name__ == "__main__":
main()
|
def iTR(num):
#dr={0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX',10:'X',40:'XL',50:'L',90:'XC',100:'C',400:'CD',500:'D',900:'CM',1000:'M'}
dr={0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX'}
q=num//1000#千位
b=(num-1000*q)//100#百位
s=(num-1000*q-100*b)//10#十位
g=num-1000*q-100*b-10*s#个位
#qr=q*dr[1000]#罗马千位
qr=q*'M'
if b==9:#罗马百位
#br=dr[900]
br='CM'
elif 4<b<9:
#br=dr[500]+(b-5)*dr[100]
br='D'+(b-5)*'C'
elif b==4:
#br=dr[400]
br='CD'
elif b<4:
#br=b*dr[100]
br=b*'C'
if s==9:#罗马十位
#sr=dr[90]
sr='XC'
elif 4<s<9:
#sr=dr[50]+(s-5)*dr[10]
sr='L'+(s-5)*'X'
elif s==4:
#sr=dr[40]
sr='XL'
elif s<4:
#sr=s*dr[10]
sr=s*'X'
gr=dr[g]#罗马个位
res=qr+br+sr+gr
return res
num=1994
print(iTR(num))
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Natoms = 1500
RF = [5,10,25,50,100,150,200,250,300,400,500,600]
#path = r"C:\\Users\\Daniel White\\RF_data500000.csv" # 5 0's
def Data(a):
'''[0] is data, [1] is RF value'''
df = pd.read_excel('RF_data{}00000.xlsx'.format(a))
return df,df.columns[1]
HallD,BallD = [],[]
for i in range(len(RF)):
B = []
H = []
for index,row in Data(RF[i])[0].iterrows():
B.append(row[0])
H.append(row[1])
BallD.append(B)
HallD.append(H)
plt.title('Density Distribution of Increasing RF\nw/ 150 Atoms, 150MHz AOM, Beta 1, Intens = 170 (4mW/cm2)',size=19)
plt.xlabel('Distance from source / m',size=17)
plt.ylabel('Particle Density',size=17)
# # # # # # # # # # ##
''' F W H M ''' # ##
FWHMs = []
for i in range(len(RF)):
HallD_ = HallD[i]
BallD_ = BallD[i]
Hpeak = [max(HallD_), int(round( np.median(np.where(HallD_==max(HallD_))) ))]
Lmin = max(np.where(HallD_[:Hpeak[1]] == min(HallD_[:Hpeak[1]] ) )[0])
Lmax = max(np.where(HallD_[Hpeak[1]:] == min(HallD_[Hpeak[1]:] ) )[0])
#print('Index Distance from center to edge R L= ', BallD[Hpeak[1]]-BallD[Lmin], BallD[Lmax]-BallD[Hpeak[1]])
#vLmin,vLmax = BinFactor* IS IT POSSIBLE TO CONVERT INTO ORGINAL VELOCITY = not needed right now
FWi = Lmax-Lmin
Bot = max(HallD_[Lmax],HallD_[Lmin])
HM = Bot + (Hpeak[0]+Bot)/2
lHM = np.abs(HallD_[:Hpeak[1]]-HM).argmin()
rHM = np.abs(HallD_[Hpeak[1]:]-HM).argmin()+Hpeak[1]
#print(lHM,rHM)
Skew = -1*(BallD_[Hpeak[1]]-BallD_[lHM]-BallD_[rHM]+BallD_[Hpeak[1]])
#print('Skew =',Skew,' +=MB')
FWHM = BallD_[rHM]-BallD_[lHM]
FWHMs.append(FWHM)
#print(FWHMs)
col_ = ( float(0.3), float((0/(len(RF)+1)+0.0001)**2), 1-float((0/(len(RF)+5)+0.0001)**0.7))
plt.fill_between(BallD[0], HallD[0],color=col_,alpha=0.2)
plt.plot(BallD[0], HallD[0],c=col_,linewidth=3,label='0.5MHz {}cm = FWHM'.format(round(FWHMs[0]*100,4)))
for i in range(1,len(RF)):
col = ( float(0.3), float((i/(len(RF)+1)+0.0001)**2), 1-float((i/(len(RF)+5)+0.0001)**0.7))
plt.plot(BallD[i], HallD[i],c=col,linewidth=5,label=str(RF[i]/10)+'MHz {}cm'.format(round(FWHMs[i]*100,4)))
plt.fill_between(BallD[i], HallD[i],color=col,alpha=0.2)
plt.legend(fontsize=25)
plt.show()
# FWHM is a bit broken, need way more bins
'''
3 D A t t e m p t
# # # # # # #
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_suBallD(1,1,1,projection='3d')
'''
#ax.plot_wireframe(BallD,HallD,RF)
|
from pathlib import Path
from typing import Any, Callable, Optional, Tuple
import PIL.Image
from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg
from .vision import VisionDataset
class Flowers102(VisionDataset):
"""`Oxford 102 Flower <https://www.robots.ox.ac.uk/~vgg/data/flowers/102/>`_ Dataset.
.. warning::
This class needs `scipy <https://docs.scipy.org/doc/>`_ to load target files from `.mat` format.
Oxford 102 Flower is an image classification dataset consisting of 102 flower categories. The
flowers were chosen to be flowers commonly occurring in the United Kingdom. Each class consists of
between 40 and 258 images.
The images have large scale, pose and light variations. In addition, there are categories that
have large variations within the category, and several very similar categories.
Args:
root (string): Root directory of the dataset.
split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``.
transform (callable, optional): A function/transform that takes in an PIL image and returns a
transformed version. E.g, ``transforms.RandomCrop``.
target_transform (callable, optional): A function/transform that takes in the target and transforms it.
download (bool, optional): If true, downloads the dataset from the internet and
puts it in root directory. If dataset is already downloaded, it is not
downloaded again.
"""
_download_url_prefix = "https://www.robots.ox.ac.uk/~vgg/data/flowers/102/"
_file_dict = { # filename, md5
"image": ("102flowers.tgz", "52808999861908f626f3c1f4e79d11fa"),
"label": ("imagelabels.mat", "e0620be6f572b9609742df49c70aed4d"),
"setid": ("setid.mat", "a5357ecc9cb78c4bef273ce3793fc85c"),
}
_splits_map = {"train": "trnid", "val": "valid", "test": "tstid"}
def __init__(
self,
root: str,
split: str = "train",
transform: Optional[Callable] = None,
target_transform: Optional[Callable] = None,
download: bool = False,
) -> None:
super().__init__(root, transform=transform, target_transform=target_transform)
self._split = verify_str_arg(split, "split", ("train", "val", "test"))
self._base_folder = Path(self.root) / "flowers-102"
self._images_folder = self._base_folder / "jpg"
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
from scipy.io import loadmat
set_ids = loadmat(self._base_folder / self._file_dict["setid"][0], squeeze_me=True)
image_ids = set_ids[self._splits_map[self._split]].tolist()
labels = loadmat(self._base_folder / self._file_dict["label"][0], squeeze_me=True)
image_id_to_label = dict(enumerate((labels["labels"] - 1).tolist(), 1))
self._labels = []
self._image_files = []
for image_id in image_ids:
self._labels.append(image_id_to_label[image_id])
self._image_files.append(self._images_folder / f"image_{image_id:05d}.jpg")
def __len__(self) -> int:
return len(self._image_files)
def __getitem__(self, idx: int) -> Tuple[Any, Any]:
image_file, label = self._image_files[idx], self._labels[idx]
image = PIL.Image.open(image_file).convert("RGB")
if self.transform:
image = self.transform(image)
if self.target_transform:
label = self.target_transform(label)
return image, label
def extra_repr(self) -> str:
return f"split={self._split}"
def _check_integrity(self):
if not (self._images_folder.exists() and self._images_folder.is_dir()):
return False
for id in ["label", "setid"]:
filename, md5 = self._file_dict[id]
if not check_integrity(str(self._base_folder / filename), md5):
return False
return True
def download(self):
if self._check_integrity():
return
download_and_extract_archive(
f"{self._download_url_prefix}{self._file_dict['image'][0]}",
str(self._base_folder),
md5=self._file_dict["image"][1],
)
for id in ["label", "setid"]:
filename, md5 = self._file_dict[id]
download_url(self._download_url_prefix + filename, str(self._base_folder), md5=md5)
|
################ ИМПОРТ МОДУЛЕЙ ################
import pygame
from pygame.locals import *
from pygame.math import Vector2
from math import sqrt, atan2, cos, sin
from data import *
from camera import *
################ НАСТРОЙКИ ОКНА ################
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(CAPTION)
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
################ ПОВЕРХНОСТЬ ОТРИСОВКИ ################
display = pygame.Surface((SURFACE_WIDTH, SURFACE_HEIGHT))
################ ГРУППЫ СПРАЙТОВ ################
all_sprites = pygame.sprite.Group()
map_sprites = pygame.sprite.Group()
player_sprite = pygame.sprite.Group()
bullet_group = pygame.sprite.Group()
################ ТЕСТ НА КОЛЛИЗИЮ ################
def collision_test(rect, tiles_list):
"""Вторым значением фунция принимает список pygame.Rect объектов,
так как вся карта создается в одном классе => храниться как единый объект"""
hit_list = []
for tile in tiles_list:
if rect.colliderect(tile):
hit_list.append(tile)
return hit_list
################ КАРТА УРОВНЯ ################
tile_rects = []
class Map(pygame.sprite.Sprite):
def __init__(self, map_folder_name):
super().__init__(map_sprites)
self.background_image = pygame.image.load(f'{map_folder_name}/background2.jpg').convert()
self.background_image = pygame.transform.scale(self.background_image, (SURFACE_WIDTH, SURFACE_HEIGHT))
self.grass_img = pygame.image.load(f'{map_folder_name}/Tiles/grass.png').convert()
self.earth_img = pygame.image.load(f'{map_folder_name}/Tiles/earth.png').convert()
with open(f'{map_folder_name}/map.txt') as file:
self.map_data = [[int(i) for i in row] for row in file.read().split('\n')]
def update(self):
display.blit(self.background_image, (0, 0))
for y, row in enumerate(self.map_data):
for x, tile in enumerate(row):
if tile:
self.tile_x = x * TILE_SIDE
self.tile_y = y * TILE_SIDE
if tile == 1:
self.tile_image = self.earth_img
elif tile == 2:
self.tile_image = self.grass_img
display.blit(self.tile_image, (self.tile_x - camera.offset.x, self.tile_y - camera.offset.y))
tile_rects.append(pygame.Rect(self.tile_x, self.tile_y, TILE_SIDE, TILE_SIDE))
################ ПЕРСОНАЖ ################
class Player(pygame.sprite.Sprite):
def __init__(self, player_image_name):
super().__init__(player_sprite)
self.image = pygame.image.load(player_image_name) # Спрайт
self.rect = self.image.get_rect() # Rect персонажа
# Начальные координаты
self.rect.y = 3 * (SURFACE_HEIGHT / HEIGHT) * TILE_SIDE
self.rect.x = 5 * (SURFACE_HEIGHT / HEIGHT) * TILE_SIDE
# Размер персонажа
self.width, self.height = self.rect.size
self.orientation = 'right'
# Параметры движения по оси Ox
self.moving_right, self.moving_left = False, False
self.speed = 2
# Параметры прыжка (различные коэффициенты для более гибкой настройки высоты прыжка и тп)
self.is_jump = False
self.jump_force = 40
self.jump_count = 0
self.jump_coef = 0.2
self.gravity = 1
self.acceleration = 0.1
# Перемещение перосонажа по обоим осям + коллизия с картой
def player_move(self, tiles):
self.rect.x += self.movement[0]
hit_list = collision_test(self.rect, tiles)
for tile in hit_list:
if self.movement[0] > 0:
self.rect.right = tile.left
self.collisions_types['right'] = True
elif self.movement[0] < 0:
self.rect.left = tile.right
self.collisions_types['left'] = True
self.rect.y += self.movement[1]
hit_list = collision_test(self.rect, tiles)
for tile in hit_list:
if self.movement[1] > 0:
self.rect.bottom = tile.top
self.is_jump = False
self.collisions_types['bottom'] = True
elif self.movement[1] < 0:
self.rect.top = tile.bottom
self.is_jump = False
self.collisions_types['top'] = True
# Прыдок
def jump(self):
if self.is_jump:
if self.jump_count >= 0:
self.movement[1] -= self.jump_count * self.jump_coef
self.jump_count -= 1
else:
self.is_jump = False
# Отрисовываем персонажа
def blit_player(self):
x, y = self.rect.x - camera.offset.x, self.rect.y - camera.offset.y
if self.orientation == 'right':
display.blit(self.image, (x, y))
elif self.orientation == 'left':
display.blit(pygame.transform.flip(self.image, True, False), (x, y))
# Цикл персонажа
def update(self):
self.movement = [0, 0] # Скорость перемещения перосонажа по обоим осям
self.collisions_types = {'top': False, 'bottom': False, 'left': False, 'right': False}
# Перемещение влево/право
if self.moving_right:
self.movement[0] += self.speed
if self.moving_left:
self.movement[0] -= self.speed
# Гравитация
self.movement[1] += self.gravity
self.gravity += self.acceleration
# Устанавливаем максимальное значение гравитации
if self.movement[1] > 3:
self.movement[1] = 3
self.jump()
self.player_move(tile_rects)
self.blit_player()
################ ПРИЦЕЛ ################
class Cursor(pygame.sprite.Sprite):
def __init__(self, scope_image_name):
super().__init__(player_sprite)
self.image = pygame.image.load(scope_image_name)
self.rect = self.image.get_rect()
def update(self):
mouse_position = pygame.mouse.get_pos()
self.rect.centerx = mouse_position[0] * (SURFACE_WIDTH / WIDTH)
self.rect.centery = mouse_position[1] * (SURFACE_HEIGHT / HEIGHT)
display.blit(self.image, self.rect)
################ ПУЛЯ ################
class Bullet(pygame.sprite.Sprite):
def __init__(self, bullet_image_name, start_position, finish_position, speed):
super().__init__(bullet_group)
self.image = pygame.image.load(bullet_image_name)
self.x, self.y = start_position
self.start_position = (
start_position[0] - camera.offset.x,
start_position[1] - camera.offset.y,
)
self.finish_position = finish_position
self.speed = speed
self.dx = self.finish_position[0] - self.start_position[0]
self.dy = self.finish_position[1] - self.start_position[1]
self.angle = atan2(self.dy, self.dx)
def destroy(self):
self.rect_to_collide = pygame.Rect(
self.x, self.y, self.image.get_width(), self.image.get_height()
)
if collision_test(self.rect_to_collide, tile_rects):
self.kill()
x = self.x - camera.offset.x
y = self.y - camera.offset.y
if (x < 0 or x > SURFACE_WIDTH) or (y < 0 or y > SURFACE_HEIGHT):
self.kill()
def update(self):
self.x += self.speed * cos(self.angle)
self.y += self.speed * sin(self.angle)
self.destroy()
display.blit(self.image, (self.x - camera.offset.x, self.y - camera.offset.y))
################ КАРТА ########ы########
Map(map_folder_name='Assets/Maps/Map1')
################ ПЕРСОНАЖ ################
player = Player(player_image_name='Assets/player.png') # Персонаж
cursor = Cursor(scope_image_name='Assets/scope.png')
################ КАМЕРА ################
camera = Camera(player=player, width=SURFACE_WIDTH, height=SURFACE_HEIGHT)
follow = Follow(camera, player, smooth=25)
border = Border(camera, player)
auto = Auto(camera, player, speed=1)
camera.setmethod(follow)
################ ИГРОВОЙ ЦИКЛ ################
run = True
while run:
tile_rects = []
map_sprites.update()
################ ИГРОВЫЕ СОБЫТИЯ ################
for event in pygame.event.get():
if event.type == QUIT:
run = False
################ СОБЫТИЯ КЛАВИАТУРЫ ################
if event.type == pygame.KEYDOWN:
if event.key == K_d:
player.moving_right = True
player.orientation = "right"
if event.key == K_a:
player.moving_left = True
player.orientation = "left"
if event.key == K_SPACE:
if player.collisions_types["bottom"] or \
player.collisions_types["left"] or \
player.collisions_types["right"]:
player.is_jump = True
player.jump_count = player.jump_force
if event.type == pygame.KEYUP:
if event.key == K_d:
player.moving_right = False
if event.key == K_a:
player.moving_left = False
################ СОБЫТИЯ МЫШИ ################
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
Bullet(
bullet_image_name="Assets/bullet.png",
start_position=player.rect.center,
finish_position=cursor.rect.center,
speed=4,
)
################ ОБНОВЛЕНИЕ/АНИМАЦИЯ СПРАЙТОВ ################
all_sprites.update()
player_sprite.update()
bullet_group.update()
camera.scroll()
# Растягиваем display на весь screen
surface = pygame.transform.scale(display, WINDOW_SIZE) # WINDOW_SIZE
screen.blit(surface, (0, 0))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
|
import heapq
def sortAkSorted(iterable, k):
largest = []
sortedArray = []
for value in iterable:
heapq.heappush(largest, value)
if len(largest) > k:
sortedArray.append(heapq.heappop(largest))
if (len(largest) < k):
return None
for elm in largest:
sortedArray.append(elm)
return sortedArray
print(sortAkSorted([8, 5, 3, 2, 8, 10, 9], 3))
|
import numpy as np
def gradient_descent(grad_f,x_init,learning_rate):
grad_is_zero_flag = 1
counter = 0
while grad_is_zero_flag >= 1:
grad_is_zero_flag = 0
grad_value = grad_f(x_init)
for sub_value in grad_value:
if sub_value >= 0.0001:
grad_is_zero_flag += 1
if grad_is_zero_flag >= 1:
x_init = x_init - learning_rate*(grad_value)
counter += 1
return x_init
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.