text
string
size
int64
token_count
int64
from abc import ABC class Refferal_API(ABC): def __init__(self): # TODO pass def NewVacancy(): # TODO pass def NewApplication(): # TODO pass def NotifyReferrer(): # TODO pass def NotifyApplicant(): # TODO pass
324
98
# Generated by Django 3.2.8 on 2021-11-10 05:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms_voting', '0011_auto_20211110_0502'), ] operations = [ migrations.RemoveField( model_name='bulletin', name='result', ), migrations.AlterField( model_name='poll', name='remote_participants', field=models.TextField(default=''), ), ]
502
172
import os from config import config def getpath(path): base_path = os.path.join(config.upload_path, 'app', 'static', 'upload') UPLOAD_LICENCE_FOLDER = os.path.join(base_path, 'licence') UPLOAD_COVER_FOLDER = os.path.join(base_path, 'cover') UPLOAD_PIECE_FOLDER = os.path.join(base_path, 'pieceimg') UPLOAD_LIGHT_FOLDER = os.path.join(base_path, 'light') if path == "licence": return UPLOAD_LICENCE_FOLDER elif path == "cover": return UPLOAD_COVER_FOLDER elif path == "pieceimg": return UPLOAD_PIECE_FOLDER elif path == "light": return UPLOAD_LIGHT_FOLDER return path
670
244
from click.exceptions import FileError from scipy.optimize import curve_fit import matplotlib.pyplot as plt from . import util import numpy as np import click import sys import csv import os def pt1(t, K, T): """ time-domain solution/formula for a first-order/pt1 system Args: t (float): time K (float): gain T (float): time-constant Returns: float: f(t) """ return K * (1 - np.exp(-t/T)) def pt2(t, K, T): """ time-domain solution/formula for a second-order/pt2 system with critical damping, d = 1, T = T1 = T2 Args: t (float): time K (float): gain T (float): time-constant Returns: float: f(t) """ return K * (1 - np.exp(-t/T) - ((t/T) * np.exp(-t/T))) def pt1gen(t_arr, K, T, y0 = 0): """ generate y(t) of PT1 for t in t_arr Args: t_arr (list(float)): time array K (float): gain T (float): time-constant Returns: list(float): y(t) for t in t_arr """ return [pt1(t, K, T) + y0 for t in t_arr] def pt2gen(t_arr, K, T, y0 = 0): """ generate y(t) of PT2 for t in t_arr Args: t_arr (list(float)): time array K (float): gain T (float): time-constant Returns: list(float): y(t) for t in t_arr """ return [pt2(t, K, T) + y0 for t in t_arr] def pt1fit(t, y, Kg=1, Tg=1): """ curve_fit of pt1(-like) data Args: t (list(float)): time y (list(float)): output Kg (float, optional): initial guess for gain. Defaults to 1. Tg (float, optional): initial guess for time-constant. Defaults to 1. Returns: tuple(float,float): best fit -> K_opt, T_opt """ if not len(t) == len(y): return None # delete offset and normalize t = [n - t[0] for n in t] y = [n - y[0] for n in y] t_norm = [n / max(t) for n in t] y_norm = [n / max(y) for n in y] (popt,_) = curve_fit(pt1, t_norm, y_norm, p0=[Kg, Tg], absolute_sigma=True) K_opt = max(y) * popt[0] T_opt = max(t) * popt[1] return (K_opt, T_opt) def pt2fit(t, y, Kg=1, Tg=1): """ curve_fit of pt2(-like) data Args: t (list(float)): time y (list(float)): output Kg (float, optional): initial guess for gain. Defaults to 1. Tg (float, optional): initial guess for time-constant. Defaults to 1. Returns: tuple(float,float): best fit -> K_opt, T_opt """ if not len(t) == len(y): return None # delete offset and normalize t = [n - t[0] for n in t] y = [n - t[0] for n in y] t_norm = [n / max(t) for n in t] y_norm = [n / max(y) for n in y] (popt,_) = curve_fit(pt2, t_norm, y_norm, p0=[Kg, Tg], absolute_sigma=True) K_opt = max(y) * popt[0] T_opt = max(t) * popt[1] return (K_opt, T_opt) @click.option("--datapath", "-d", help="Path to csv file with target data", type=click.Path(exists=True)) @click.option("--eventspath", "-e", help="Path to csv file with event data", type=click.Path()) @click.option("--outdir", "-o", help="Directory to store output artifacts", type=click.Path(exists=True)) @click.option("--columns", "-c", help="Name of the columns", type=str, multiple=True) @click.option("--type", "-t", help="PTn type: PT1, PT2", type=str, multiple=True) @click.option("--show", "-s", help="Show plots", is_flag=True) @click.command() def do_fit(datapath, eventspath, outdir, columns, show): data = [] delimiter = util.get_delimiter(datapath) with open(datapath, 'r') as data_file: reader = csv.DictReader(data_file, delimiter=delimiter) for entry in reader: data.append(entry) events = [] delimiter = util.get_delimiter(eventspath) with open(eventspath, 'r') as events_file: reader = csv.DictReader(events_file, delimiter=delimiter) for entry in reader: events.append(entry) data_per_event = {} time_slots = [] for key in list(events[0].keys()): if key == "<event-name>": continue from_index = int(events[0][key]) to_index = int(events[1][key]) time_slots.append(range(from_index, to_index)) data_per_event[key] = data[from_index:to_index] for col in columns: ptn_param = [] plt.figure() plt.plot(util.column(data, col), label="all") for index, key in enumerate(list(data_per_event.keys())): if type == "PT1": ptn_param.append(pt1fit(time_slots[index], util.column(data_per_event[key], col))) elif type == "PT2": ptn_param.append(pt2fit(time_slots[index], util.column(data_per_event[key], col))) print(key, end=": (K_opt, T_opt)=") print(ptn_param[index]) plt.plot(time_slots[index], util.column(data_per_event[key], col), label=f"{key} : {time_slots[index]}") plt.legend() plt.grid('both') plt.savefig(f"{outdir}/timeslots_{col}.png") for index, key in enumerate(list(data_per_event.keys())): plt.figure() col_data = np.array(util.column(data_per_event[key], col)) col_data -= col_data[0] plt.plot(col_data, label=f"{key}") t_arr = range(len(time_slots[index])) K_opt = ptn_param[index][0] T_opt = ptn_param[index][1] if type == "PT1": plt.plot(pt1gen(t_arr, K_opt, T_opt), "--", label=f"{key} --fit") elif type == "PT2": plt.plot(pt2gen(t_arr, K_opt, T_opt), "--", label=f"{key} --fit") plt.title(f"K_opt: {K_opt}\nT_opt: {T_opt}") plt.legend() plt.grid('both') plt.savefig(f"{outdir}/{col}_{key}_fit.png") if show: plt.show() def main(): if len(sys.argv) == 1: do_fit.main(["--help"]) else: do_fit.main() if __name__ == "__main__": main()
5,551
2,195
'''What is premium?''' from discord.ext import commands from packages.utils import Embed, ImproperType class Command(commands.Cog): def __init__(self, client): self.client= client @commands.command() async def premium(self, ctx): #return await ctx.send('This command is currently under maintenance. The developers will try to get it up again as soon as possible. In the meantime feel free to use `n.help` to get the other commands. Thank you for your understanding!') if await ImproperType.check(ctx): return embed=Embed('Premium', 'Premium is a one time purchase for your Discord server. \n It will make your server appearance a lot better. \n There are lots of benefits you will get for being a premium server. \n \n Your benefits are: \n :small_blue_diamond: **LIFETIME** server access to **all** features of this bot. \n :small_blue_diamond: You don\'t have to do anything, the bot will create speed, gold member, accuracy and race roles for your server. \n :small_blue_diamond: Role registering / updating system through the command `n.update`. \n :small_blue_diamond: Nickname updating system through the command `n.update`. \n :small_blue_diamond: The feeling that you helped the developers a lot through your purchasement. \n :small_blue_diamond: More things coming soon:tm:, so stay tuned. \n \n :small_orange_diamond: In order to receive these Premium features, check your class down below. Then send `10M` to [this](https://nitrotype.com/racer/hypertyper55) account and DM <@505338178287173642> on discord.', 'diamond_shape_with_a_dot_inside') #\n\n **__List of Premium 💠 Server Prizes__** (since December 20th 2020)\n\n:small_orange_diamond: ***Class I:*** Human Members: __<50__, Age: __>3 months__: `5M`.\n\n:small_orange_diamond: ***Class II:*** Human members: __50-99__, Age: __>3 months__: `10M`.\n\n:small_orange_diamond: ***Class III:*** Human members: 100-150, Age: __>3 months__: `15M`. \n\n:small_orange_diamond: ***Class IV:*** Human members: __150-199__, Age __>3 months__: `20M`. \n\n:small_orange_diamond: ***Class V: ***Human members: __200+__, Age: __>3 months__: `25M`. \n\n:small_orange_diamond: ***Class VI: ***Human members: __ANY__, Age: __<3 months__: `20M`.') embed.footer(f'{ctx.author} • Become a premium 💠 member today! 💗') embed.thumbnail('https://media.discordapp.net/attachments/719414661686099993/754971786231283712/season-callout-badge.png') await embed.send(ctx) try: await ctx.message.delete() except: pass def setup(client): client.add_cog(Command(client))
2,632
921
from cmd import Cmd import sys from select import poll, POLLIN import string from subprocess import call from wireless_emulator import * from wireless_emulator.clean import cleanup class CLI(Cmd): prompt = 'WirelessTransportEmulator>' identchars = string.ascii_letters + string.digits + '_' + '-' def __init__(self, emulator, stdin=sys.stdin): self.emulator = emulator self.inPoller = poll() self.inPoller.register(stdin) Cmd.__init__(self) print( '*** Starting CLI:\n' ) self.run() def run(self): while True: try: # Make sure no nodes are still waiting self.cmdloop() break except KeyboardInterrupt: # Output a message - unless it's also interrupted # pylint: disable=broad-except try: print( '\nKeyboard interrupt. Use quit or exit to shotdown the emulator.\n' ) except Exception: pass def default(self, line): """Called on an input line when the command prefix is not recognized. Overridden to run shell commands when a node is the first CLI argument. Past the first CLI argument, node names are automatically replaced with corresponding IP addrs.""" first, args, line = self.parseline(line) node = self.emulator.getNeByName(first) if node is not None: rest = args.split(' ') node.executeCommand(args) else: print('Node %s not found' % first) def emptyline( self ): "Don't repeat last command when you hit return." pass def do_exit(self, _line): "Exit" cleanup(self.emulator.configFileName) return 'exited by user command' def do_quit(self, line): "Exit" return self.do_exit(line) def do_print_nodes(self, _line): "Prints the names of all the Network Elements emulated" print('Available NEs are:') for neObj in self.emulator.networkElementList: print('%s' % neObj.uuid) def do_print_node_info(self, line): "Prints the information of the specified Network Element" args = line.split() if len(args) != 1: print('ERROR: usage: print_node_info <NE_UUID>') return node = self.emulator.getNeByName(args[0]) if node is not None: print('#########################################') print('#### Network Element UUID: \'%s\'' % node.uuid) print('#### Network Element management IP: %s' % node.managementIPAddressString) print('########### Interfaces: ###########') for intf in node.interfaceList: print('Interface: UUID=\'%s\' having IP=%s and Linux Interface Name=\'%s\'' % (intf.uuid, intf.IP, intf.interfaceName)) print('#########################################') else: print('Node %s not found' % args[0]) def do_dump_nodes(self, _line): "Dumps the information about all of the available Network Elements" for node in self.emulator.networkElementList: print('#########################################') print('#### Network Element UUID: \'%s\'' % node.uuid) print('#### Network Element management IP: %s' % node.managementIPAddressString) print('########### Interfaces: ###########') for intf in node.interfaceList: print('Interface: UUID=\'%s\' having IP=%s and Linux Interface Name=\'%s\'' % (intf.uuid, intf.IP, intf.interfaceName)) print('#########################################') def do_dump_links(self, _line): "Dumps the links available in the network" for topo in self.emulator.topologies: print('#################### %s #####################' % topo.topologyLayer) for link in topo.linkList: print('## Link=%d ## \'%s\': \'%s\' <-------> \'%s\':\'%s\'' % (link.linkId, link.interfacesObj[0].getNeName(), link.interfacesObj[0].getInterfaceUuid(), link.interfacesObj[0].getInterfaceUuid(), link.interfacesObj[1].getNeName())) print('#########################################')
4,435
1,195
from django.db import models # Create your models here. class HelthDepartment(models.Model): name = models.CharField(max_length=100) availability = models.DateTimeField() def __str__(self): return self.name #helth_department = ((0,"daily task"),(1,"work jobs"),(2,"house needs")) class Patient(models.Model): name = models.CharField(max_length=100) contact = models.CharField(max_length=100) email = models.EmailField() booking_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) appointment_date = models.DateTimeField(null=True , blank=True) #appointment_time = models.TimeField(null=True , blank=True) helth_department = models.ForeignKey(HelthDepartment,on_delete=models.CASCADE,null=True) history = models.TextField() #patient_contact = models.PhoneField() #helth_department = models.PositiveSmallIntegerField(choices=helth_department,default=0) def __str__(self): return self.name class Meta: ordering = ["-booking_date"]
1,036
337
# Generated by Django 3.0.3 on 2021-12-22 00:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vid', '0002_allnty'), ] operations = [ migrations.CreateModel( name='CountyMetrics', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField()), ('county', models.CharField(max_length=128)), ('state', models.CharField(max_length=128)), ('fips', models.CharField(max_length=128, null=True)), ('cases', models.IntegerField(null=True)), ('deaths', models.IntegerField(null=True)), ('population', models.IntegerField()), ('testPositivityRatio', models.FloatField(null=True)), ('infectionRate', models.FloatField(null=True)), ], options={ 'unique_together': {('date', 'fips')}, }, ), migrations.RenameModel( old_name='AllNTY', new_name='EntireUS', ), migrations.DeleteModel( name='CasesDeathsNTY', ), migrations.DeleteModel( name='MetricsActNow', ), migrations.DeleteModel( name='PennCases', ), migrations.DeleteModel( name='PennDeaths', ), migrations.DeleteModel( name='PennHospitals', ), migrations.DeleteModel( name='Places', ), ]
1,647
470
import math s = 0.0 k = 1 n = int(input()) for i in range(n+1): k*=max(1,i) s += 1/k print(s)
101
56
from unittest import TestCase from ..Model import Model from ..Simulation import Simulation from os.path import dirname, join import numpy as np import math class TestToy3(TestCase): def test_toy3(self): model = Model(join(dirname(__file__), "../../notebooks/model_files/toy3.bnet")) simulation = Simulation(model, ['A','B'], [0, 0]) result = simulation.get_last_states_probtraj() self.assertAlmostEqual(result.iloc[0, :].sum(), 1.0) self.assertAlmostEqual(result.loc[0, '<nil>'], 0.25) self.assertAlmostEqual(result.loc[0, 'A'], 0.25) self.assertAlmostEqual(result.loc[0, 'A'], 0.25) self.assertAlmostEqual(result.loc[0, 'A -- B'], 0.25)
745
261
class KeyBinderDummy(object): """Class used to allow keybindings to be caught and to be actioned.""" def __init__(self): self.bindings = [] self.saved_obj = None def bind(self, action, dispatcher, dispatcher_params): """ Bind a key press """ self.bindings.append({ 'action': action, 'dispatcher': dispatcher, 'dispatcher_params': dispatcher_params, }) def action_key(self, action): """ Actions a key press by calling the relavent dispatcher """ key_found = [x for x in self.bindings if x['action'] == action] assert len(key_found) == 1 func = key_found[0]['dispatcher'] func(key_found[0]['dispatcher_params'])
755
226
""" 题目:礼物的最大价值 在一个mxn的期盼的每一格都放有一个礼物 每个礼物有一定的价值(价值大于0) 你可以从棋盘的左上角开始拿格子里的礼物 并每次向右或者向下移动一格 直到达到棋盘的右下角 给定一个棋盘及其上面的礼物 请计算你最多能拿到多少价值的礼物 思路:动态规划 动态规划方程 dp[i][j]=max(dp[i-1][j],dp[i][j-1])+arr[i][j] """ class Solution: def GetGiftMaxValue(self, arr): if arr is None or len(arr) == 0: return 0 rows, cols = len(arr), len(arr[0]) results = [[0 for _ in range(cols)] for _ in range(rows)] for i in range(rows): for j in range(cols): try: results[i][j] = max(results[i - 1][j], results[i][j - 1]) + arr[i][j] except: try: results[i][j] = results[i - 1][j] + arr[i][j] except: try: results[i][j] = results[i][j - 1] + arr[i][j] except: pass return results[rows - 1][cols - 1] s = Solution() print(s.GetGiftMaxValue([[1, 10, 3, 8], [12, 2, 9, 6], [5, 7, 4, 11], [3, 7, 16, 5]])) print(s.GetGiftMaxValue(None)) print(s.GetGiftMaxValue([[1, 4, 2]])) print(s.GetGiftMaxValue([[1], [4], [2]]))
1,179
581
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : doubanRequest.py # @Author: G # @Date : 2018/8/5 import requests url = 'https://movie.douban.com' doubanText = requests.get(url).text print(doubanText)
218
100
import json import unittest from flask_caching import Cache from app import app, db from apps.shop.models import ( ShopItems, ShopCategories, ShopItemsCategoriesMapping, ShopItemLogos, ShopItemsURLMapping ) from apps.users.models import Users, UsersAccessTokens, UsersAccessLevels, UsersAccessMapping from apps.utils.time import get_datetime, get_datetime_one_hour_ahead class TestShopViews(unittest.TestCase): def setUp(self): # Clear redis cache completely cache = Cache() cache.init_app(app, config={"CACHE_TYPE": "RedisCache"}) with app.app_context(): cache.clear() self.app = app.test_client() # Add some categories cat1 = ShopCategories( Category="Units", SubCategory="Tests" ) cat2 = ShopCategories( Category="UnitTests", SubCategory="TestsUnits" ) db.session.add(cat1) db.session.add(cat2) db.session.commit() self.valid_cats = [cat1.ShopCategoryID, cat2.ShopCategoryID] # And some 3rd party logos logo1 = ShopItemLogos( Image="unittest-spotify.jpg", Created=get_datetime() ) logo2 = ShopItemLogos( Image="unittest-bandcamp.jpg", Created=get_datetime() ) logo3 = ShopItemLogos( Image="unittest-amazon.jpg", Created=get_datetime() ) logo4 = ShopItemLogos( Image="unittest-deezer.jpg", Created=get_datetime() ) db.session.add(logo1) db.session.add(logo2) db.session.add(logo3) db.session.add(logo4) db.session.commit() self.valid_logo_ids = [ logo1.ShopItemLogoID, logo2.ShopItemLogoID, logo3.ShopItemLogoID, logo4.ShopItemLogoID, ] # Add three shop items and related data item1 = ShopItems( Title="UnitTest ShopItem 1", Description="UnitTest This is item 1", Price=15.99, Currency="EUR", Image="unittest-shopitem1.jpg", Created=get_datetime() ) db.session.add(item1) db.session.commit() self.valid_items = [item1.ShopItemID] item1_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[0], ShopCategoryID=self.valid_cats[0] ) item1_cat2 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[0], ShopCategoryID=self.valid_cats[1] ) db.session.add(item1_cat1) db.session.add(item1_cat2) db.session.commit() item1_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[0], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item1_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[0], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item1_url1) db.session.add(item1_url2) db.session.commit() # Item 2 item2 = ShopItems( Title="UnitTest ShopItem 2", Description="UnitTest This is item 2", Price=8.49, Currency="EUR", Image="unittest-shopitem2.jpg", Created=get_datetime() ) db.session.add(item2) db.session.commit() self.valid_items.append(item2.ShopItemID) item2_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[1], ShopCategoryID=self.valid_cats[0] ) db.session.add(item2_cat1) db.session.commit() item2_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[1], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item2_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[1], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item2_url1) db.session.add(item2_url2) db.session.commit() # Item 3 item3 = ShopItems( Title="UnitTest ShopItem 3", Description="UnitTest This is item 3", Price=12, Currency="EUR", Image="unittest-shopitem3.jpg", Created=get_datetime() ) db.session.add(item3) db.session.commit() self.valid_items.append(item3.ShopItemID) item3_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[2], ShopCategoryID=self.valid_cats[0] ) item3_cat2 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[2], ShopCategoryID=self.valid_cats[1] ) db.session.add(item3_cat1) db.session.add(item3_cat2) db.session.commit() item3_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[2], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item3_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[2], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item3_url1) db.session.add(item3_url2) db.session.commit() # We also need a valid admin user for the add release endpoint test. user = Users( Name="UnitTest Admin", Username="unittest", Password="password" ) db.session.add(user) db.session.commit() # This is non-standard, but is fine for testing. self.access_token = "unittest-access-token" user_token = UsersAccessTokens( UserID=user.UserID, AccessToken=self.access_token, ExpirationDate=get_datetime_one_hour_ahead() ) db.session.add(user_token) db.session.commit() # Define level for admin if not UsersAccessLevels.query.filter_by(LevelName="Admin").first(): access_level = UsersAccessLevels( UsersAccessLevelID=4, LevelName="Admin" ) db.session.add(access_level) db.session.commit() grant_admin = UsersAccessMapping( UserID=user.UserID, UsersAccessLevelID=4 ) db.session.add(grant_admin) db.session.commit() self.user_id = user.UserID def tearDown(self): for cat in ShopCategories.query.filter(ShopCategories.Category.like("Unit%")).all(): db.session.delete(cat) for logo in ShopItemLogos.query.filter(ShopItemLogos.Image.like("unittest%")).all(): db.session.delete(logo) for item in ShopItems.query.filter(ShopItems.Title.like("UnitTest%")).all(): db.session.delete(item) db.session.commit() user = Users.query.filter_by(UserID=self.user_id).first() db.session.delete(user) db.session.commit() def test_getting_all_shopitems(self): """This should return all the shopitems along with their associated data, in ascending order, ID=1 first.""" response = self.app.get("/api/1.0/shopitems/") data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertEqual(3, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 1", data["shopItems"][0]["title"]) self.assertEqual("UnitTest This is item 1", data["shopItems"][0]["description"]) self.assertEqual(15.99, data["shopItems"][0]["price"]) self.assertEqual("EUR", data["shopItems"][0]["currency"]) self.assertEqual("unittest-shopitem1.jpg", data["shopItems"][0]["image"]) self.assertNotEqual("", data["shopItems"][0]["createdAt"]) self.assertTrue("updatedAt" in data["shopItems"][0]) self.assertEqual( [self.valid_cats[0], self.valid_cats[1]], data["shopItems"][0]["categories"] ) self.assertEqual(2, len(data["shopItems"][0]["urls"])) self.assertEqual("Spotify", data["shopItems"][0]["urls"][0]["urlTitle"]) self.assertEqual( "http://www.example.com/spotify", data["shopItems"][0]["urls"][0]["url"] ) self.assertEqual(self.valid_logo_ids[0], data["shopItems"][0]["urls"][0]["logoID"]) def test_getting_specific_shopitem(self): """Should return the data of the specified shopitem.""" response = self.app.get("/api/1.0/shopitems/{}".format(self.valid_items[2])) data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertEqual(1, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 3", data["shopItems"][0]["title"]) self.assertEqual("UnitTest This is item 3", data["shopItems"][0]["description"]) self.assertEqual(12, data["shopItems"][0]["price"]) self.assertEqual("EUR", data["shopItems"][0]["currency"]) self.assertEqual("unittest-shopitem3.jpg", data["shopItems"][0]["image"]) self.assertNotEqual("", data["shopItems"][0]["createdAt"]) self.assertTrue("updatedAt" in data["shopItems"][0]) self.assertEqual( [self.valid_cats[0], self.valid_cats[1]], data["shopItems"][0]["categories"] ) self.assertEqual(2, len(data["shopItems"][0]["urls"])) self.assertEqual("Spotify", data["shopItems"][0]["urls"][0]["urlTitle"]) self.assertEqual( "http://www.example.com/spotify", data["shopItems"][0]["urls"][0]["url"] ) self.assertEqual(self.valid_logo_ids[0], data["shopItems"][0]["urls"][0]["logoID"]) self.assertEqual("BandCamp", data["shopItems"][0]["urls"][1]["urlTitle"]) self.assertEqual( "http://www.example.com/bandcamp", data["shopItems"][0]["urls"][1]["url"] ) self.assertEqual(self.valid_logo_ids[1], data["shopItems"][0]["urls"][1]["logoID"]) def test_getting_shopitems_by_category(self): """Should return all items that match the subcategory.""" response = self.app.get("/api/1.0/shopitems/category/{}/".format(self.valid_cats[1])) data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertNotEqual(None, data) self.assertEqual(2, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 1", data["shopItems"][0]["title"]) self.assertEqual("UnitTest ShopItem 3", data["shopItems"][1]["title"]) def test_adding_shopitem(self): """Should add the new item and its related data (categories and urls). For URLs, there is no valid case to reference any existing URLs in the database, so they will be added every time. However, we can reuse a logo (eg. Spotify), so basically you can pick a logo in the UI and then the POST data will have an ID.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[ self.valid_cats[0], {"category": "UnitTests", "subcategory": "UnitTest New Subcategory"} ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] }, { "title": "Amazon", "url": "http://www.example.com/amazon/123", "logoID": self.valid_logo_ids[2] }, ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=item.ShopItemID).all() new_cat = ShopCategories.query.filter_by( SubCategory="UnitTest New Subcategory").first() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertNotEqual(None, item) self.assertNotEqual(None, cats) self.assertNotEqual(None, urls) self.assertEqual("UnitTest Post", item.Title) self.assertEqual("UnitTest Description", item.Description) self.assertEqual(14.95, float(item.Price)) self.assertEqual("EUR", item.Currency) self.assertEqual("unittest-post.jpg", item.Image) self.assertEqual(2, len(cats)) self.assertEqual("UnitTests", new_cat.Category) self.assertEqual("UnitTest New Subcategory", new_cat.SubCategory) self.assertEqual(2, len(urls)) # These appear in insert order. Sorting by title would be a lot of work for little benefit self.assertEqual("Spotify", urls[0].URLTitle) self.assertEqual("http://www.example.com/spotify/1", urls[0].URL) self.assertEqual("Amazon", urls[1].URLTitle) self.assertEqual("http://www.example.com/amazon/123", urls[1].URL) def test_updating_shop_item(self): """Should replace all existing values with the new updated values.""" response = self.app.put( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( dict( title="UnitTest Updated Title", description="UnitTest Updated Description", price=11.95, currency="EUR", image="unittest-update.jpg", categories=[ self.valid_cats[0], self.valid_cats[1], {"category": "UnitTests", "subcategory": "UnitTest New Subcategory"} ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/2", "logoID": self.valid_logo_ids[0] }, { "title": "Amazon MP3", "url": "http://www.example.com/amazon/124", "logoID": self.valid_logo_ids[2] }, { "title": "BandCamp", "url": "http://www.example.com/bandcamp/987", "logoID": self.valid_logo_ids[2] }, ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(200, response.status_code) self.assertEqual("", response.data.decode()) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() new_cat = ShopCategories.query.filter_by( SubCategory="UnitTest New Subcategory").first() self.assertNotEqual(None, item) self.assertNotEqual(None, cats) self.assertNotEqual(None, urls) self.assertEqual("UnitTest Updated Title", item.Title) self.assertEqual("UnitTest Updated Description", item.Description) self.assertEqual(11.95, float(item.Price)) self.assertEqual("EUR", item.Currency) self.assertEqual("unittest-update.jpg", item.Image) self.assertNotEqual("", item.Updated) self.assertEqual(3, len(cats)) self.assertEqual("UnitTests", new_cat.Category) self.assertEqual("UnitTest New Subcategory", new_cat.SubCategory) self.assertEqual(3, len(urls)) # These appear in insert order. Sorting by title would be a lot of work for little benefit self.assertEqual("Spotify", urls[0].URLTitle) self.assertEqual("http://www.example.com/spotify/2", urls[0].URL) self.assertEqual("Amazon MP3", urls[1].URLTitle) self.assertEqual("http://www.example.com/amazon/124", urls[1].URL) self.assertEqual("BandCamp", urls[2].URLTitle) self.assertEqual("http://www.example.com/bandcamp/987", urls[2].URL) def test_patching_shopitem_add(self): """Patch a ShopItems entry with "add" operation.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "add", "path": "/title", "value": "UnitTest Patched Title" }), dict({ "op": "add", "path": "/categories", "value": [self.valid_cats[1]] }), dict({ "op": "add", "path": "/urls", "value": [ { "title": "Deezer", "url": "deezer.com", "logoID": self.valid_logo_ids[3] } ] }), ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest Patched Title", item.Title) self.assertEqual(2, len(cats)) self.assertEqual(3, len(urls)) self.assertEqual("Deezer", urls[2].URLTitle) self.assertEqual("deezer.com", urls[2].URL) def test_patching_shopitem_copy(self): """Patch a ShopItems entry with "copy" operation. There is no possible copy operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/title", "path": "/description" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest ShopItem 2", item.Description) def test_patching_shopitem_move(self): """Patch a ShopItems entry with "move" operation. Move will by definition empty the source resource and populate the target resource with the value from source. However, this does not currently work yet due to SQLAlchemy and JSONPatch incompatibility. Just the value is replaced. The correct behaviour will be implemented later on.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "move", "from": "/description", "path": "/image" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest This is item 2", item.Image) def test_patching_shopitem_remove(self): """Patch a ShopItems entry with "remove" operation. This does not work for the base object due to SQLAlchemy JSONPatch incompatibility. But it does work for the joined tables URLs and categories.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "remove", "path": "/title" }), dict({ "op": "remove", "path": "/categories" }), dict({ "op": "remove", "path": "/urls" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual([], cats) self.assertEqual([], urls) def test_patching_shopitem_replace(self): """Patch a ShopItems entry with "replace" operation.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "replace", "path": "/title", "value": "UnitTest Patched Title" }), dict({ "op": "replace", "path": "/categories", "value": [self.valid_cats[1]] }), dict({ "op": "replace", "path": "/urls", "value": [ { "title": "Deezer", "url": "deezer.com", "logoID": self.valid_logo_ids[3] } ] }), ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest Patched Title", item.Title) self.assertEqual(1, len(cats)) self.assertEqual(1, len(urls)) self.assertEqual("Deezer", urls[0].URLTitle) self.assertEqual("deezer.com", urls[0].URL) def test_deleting_shop_item(self): """Should delete the specified shop item and it's mappings.""" response = self.app.delete( "/api/1.0/shopitems/{}".format(self.valid_items[2]), headers={ 'User': self.user_id, 'Authorization': self.access_token } ) cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[2]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[2]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual([], cats) self.assertEqual([], urls) def test_invalid_category_id(self): """When an invalid category ID is given, it should be skipped.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[0], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] } ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertEqual([], cats) def test_existing_string_category(self): """Should use the existing category and not create a new entry to ShopCategories.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[ { "category": "UnitTests", "subcategory": "TestsUnits" } ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] } ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() category_entries = ShopCategories.query.filter_by(Category="UnitTests").all() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertEqual(1, len(cats)) # Should only have one entry for the given values. self.assertEqual(1, len(category_entries)) def test_patching_categories(self): """Patch ShopItems categories with "copy" and "move" operations. There is no possible operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/categories", "path": "/categories" }), dict({ "op": "move", "from": "/categories", "path": "/categories" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) def test_patching_urls(self): """Patch ShopItems urls with "copy" and "move" operations. There is no possible operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/urls", "path": "/urls" }), dict({ "op": "move", "from": "/urls", "path": "/urls" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode())
31,876
9,353
# The MIT License (MIT) # Copyright (c) 2017 Massachusetts Institute of Technology # # Author: Cody Rude # This software has been created in projects supported by the US National # Science Foundation and NASA (PI: Pankratius) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import re from collections import OrderedDict def read_uavsar_metadata(in_file): ''' Parse UAVSAR metadata @param in_file: String of Metadata filename or file object (file should end in .ann) @return OrderedDict of metadata ''' if isinstance(in_file, str): with open(in_file, 'r') as info_file: data_info = info_file.readlines() else: data_info = [line.decode() for line in in_file.readlines()] data_info = [line.strip() for line in data_info] # Function to convert string to a number def str_to_number(in_string): try: return int(in_string) except: return float(in_string) data_name = data_info[0][31:] meta_data_dict = OrderedDict() for line in data_info: # Only work on lines that aren't commented out if re.match('^[^;]',line) != None: # Get the data type ('&' is text) data_type = re.search('\s+\((.*)\)\s+=', line).group(1) # Remove data type from line tmp = re.sub('\s+\(.*\)\s+=', ' =', line) # Split line into key,value split_list = tmp.split('=',maxsplit=1) # remove any trailing comments and strip whitespace split_list[1] = re.search('[^;]*',split_list[1]).group().strip() split_list[0] = split_list[0].strip() #If data type is not a string, parse it as a float or int if data_type != '&': # Check if value is N/A if split_list[1] == 'N/A': split_list[1] = float('nan') # Check for Raskew Doppler Near Mid Far as this # entry should be three seperate entries elif split_list[0] == 'Reskew Doppler Near Mid Far': split_list[0] = 'Reskew Doppler Near' second_split = split_list[1].split() split_list[1] = str_to_number(second_split[0]) meta_data_dict['Reskew Doppler Mid'] = str_to_number(second_split[1]) meta_data_dict['Reskew Doppler Far'] = str_to_number(second_split[2]) # Parse value to an int or float else: split_list[1] = str_to_number(split_list[1]) # Add key, value pair to dictionary meta_data_dict[split_list[0]] = split_list[1] return meta_data_dict
3,728
1,153
import json from urllib.parse import urlencode from flask import Response from werkzeug.http import HTTP_STATUS_CODES class ApiResponse(Response): default_status = 200 default_mimetype = 'application/json' def __init__(self, data=None, status=None, **kwargs): if data is None: if kwargs.get('response') is None: status = 204 else: if hasattr(data, 'to_dict'): data = data.to_dict() kwargs['response'] = json.dumps(data) if status is not None: kwargs['status'] = status super(Response, self).__init__(**kwargs) class ApiRedirect(ApiResponse): default_status = 302 def __init__(self, url, query=None, *args, **kwargs): super(ApiResponse, self).__init__(None, *args, **kwargs) if not (300 < self.status_code and self.status_code < 400): raise ValueError('Invalid Status Code, Redirects should be equal to or between 300 and 399') if query: if '?' in url: url += '&' + urlencode(query) else: url += '?' + urlencode(query) self.headers.add('location', url) class ApiError(Exception): code = 0 message = None status = 400 def __init__(self, message=None, status=None, *args, **kwargs): super(Exception, self).__init__() if status is not None: self.status = status if message is not None: self.message = message elif self.message is None: self.message = HTTP_STATUS_CODES.get(self.status, 'Unknown Error') if kwargs.get('code') is not None: self.code = kwargs.get('code') kwargs['data'] = kwargs.pop('metadata', None) or {} kwargs['data'].update({'code': self.code, 'message': self.message, 'status': self.status}) kwargs['status'] = self.status self.response = ApiResponse(**kwargs)
1,964
588
import argparse import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from dgl.nn.pytorch import GraphConv import dgl.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel import os import sys import samgraph.torch as sam import datetime from common_config import * class GCN(nn.Module): def __init__(self, in_feats, n_hidden, n_classes, n_layers, activation, dropout): super(GCN, self).__init__() self.layers = nn.ModuleList() # input layer self.layers.append( GraphConv(in_feats, n_hidden, activation=activation, allow_zero_in_degree=True)) # hidden layers for _ in range(n_layers - 2): self.layers.append( GraphConv(n_hidden, n_hidden, activation=activation, allow_zero_in_degree=True)) # output layer self.layers.append( GraphConv(n_hidden, n_classes, allow_zero_in_degree=True)) self.dropout = nn.Dropout(p=dropout) def forward(self, blocks, features): h = features for i, layer in enumerate(self.layers): if i != 0: h = self.dropout(h) h = layer(blocks[i], h) return h def parse_args(default_run_config): argparser = argparse.ArgumentParser("GCN Training") add_common_arguments(argparser, default_run_config) argparser.add_argument('--fanout', nargs='+', type=int, default=default_run_config['fanout']) argparser.add_argument('--lr', type=float, default=default_run_config['lr']) argparser.add_argument('--dropout', type=float, default=default_run_config['dropout']) argparser.add_argument('--weight-decay', type=float, default=default_run_config['weight_decay']) return vars(argparser.parse_args()) def get_run_config(): run_config = {} run_config.update(get_default_common_config(run_mode=RunMode.FGNN)) run_config['sample_type'] = 'khop2' run_config['fanout'] = [5, 10, 15] run_config['lr'] = 0.003 run_config['dropout'] = 0.5 run_config['weight_decay'] = 0.0005 run_config.update(parse_args(run_config)) process_common_config(run_config) assert(run_config['arch'] == 'arch5') assert(run_config['sample_type'] != 'random_walk') run_config['num_fanout'] = run_config['num_layer'] = len( run_config['fanout']) print_run_config(run_config) return run_config def run_init(run_config): sam.config(run_config) sam.data_init() if run_config['validate_configs']: sys.exit() def run_sample(worker_id, run_config): num_worker = run_config['num_sample_worker'] global_barrier = run_config['global_barrier'] ctx = run_config['sample_workers'][worker_id] print('[Sample Worker {:d}/{:d}] Started with PID {:d}({:s})'.format( worker_id, num_worker, os.getpid(), torch.cuda.get_device_name(ctx))) sam.sample_init(worker_id, ctx) sam.notify_sampler_ready(global_barrier) num_epoch = sam.num_epoch() num_step = sam.steps_per_epoch() if (worker_id == (num_worker - 1)): num_step = int(num_step - int(num_step / num_worker) * worker_id) else: num_step = int(num_step / num_worker) epoch_sample_total_times_python = [] epoch_pipeline_sample_total_times_python = [] epoch_sample_total_times_profiler = [] epoch_sample_times = [] epoch_get_cache_miss_index_times = [] epoch_enqueue_samples_times = [] print('[Sample Worker {:d}] run sample for {:d} epochs with {:d} steps'.format( worker_id, num_epoch, num_step)) # run start barrier global_barrier.wait() for epoch in range(num_epoch): if run_config['pipeline']: # epoch start barrier 1 global_barrier.wait() tic = time.time() for step in range(num_step): sam.sample_once() # sam.report_step(epoch, step) toc0 = time.time() if not run_config['pipeline']: # epoch start barrier 2 global_barrier.wait() # epoch end barrier global_barrier.wait() toc1 = time.time() epoch_sample_total_times_python.append(toc0 - tic) epoch_pipeline_sample_total_times_python.append(toc1 - tic) epoch_sample_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochSampleTime)) epoch_get_cache_miss_index_times.append( sam.get_log_epoch_value( epoch, sam.KLogEpochSampleGetCacheMissIndexTime) ) epoch_enqueue_samples_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochSampleSendTime) ) epoch_sample_total_times_profiler.append( sam.get_log_epoch_value(epoch, sam.kLogEpochSampleTotalTime) ) if worker_id == 0: sam.report_step_average(epoch - 1, step - 1) print('[Sample Worker {:d}] Avg Sample Total Time {:.4f} | Sampler Total Time(Profiler) {:.4f}'.format( worker_id, np.mean(epoch_sample_total_times_python[1:]), np.mean(epoch_sample_total_times_profiler[1:]))) # run end barrier global_barrier.wait() if worker_id == 0: sam.report_init() if worker_id == 0: test_result = [] test_result.append(('sample_time', np.mean(epoch_sample_times[1:]))) test_result.append(('get_cache_miss_index_time', np.mean( epoch_get_cache_miss_index_times[1:]))) test_result.append( ('enqueue_samples_time', np.mean(epoch_enqueue_samples_times[1:]))) test_result.append(('epoch_time:sample_total', np.mean( epoch_sample_total_times_python[1:]))) if run_config['pipeline']: test_result.append( ('pipeline_sample_epoch_time', np.mean(epoch_pipeline_sample_total_times_python[1:]))) test_result.append(('init:presample', sam.get_log_init_value(sam.kLogInitL2Presample))) test_result.append(('init:load_dataset:mmap', sam.get_log_init_value(sam.kLogInitL3LoadDatasetMMap))) test_result.append(('init:load_dataset:copy:sampler', sam.get_log_init_value(sam.kLogInitL3LoadDatasetCopy))) test_result.append(('init:dist_queue:alloc+push', sam.get_log_init_value(sam.kLogInitL3DistQueueAlloc)+sam.get_log_init_value(sam.kLogInitL3DistQueuePush))) test_result.append(('init:dist_queue:pin:sampler', sam.get_log_init_value(sam.kLogInitL3DistQueuePin))) test_result.append(('init:internal:sampler', sam.get_log_init_value(sam.kLogInitL2InternalState))) test_result.append(('init:cache:sampler', sam.get_log_init_value(sam.kLogInitL2BuildCache))) for k, v in test_result: print('test_result:{:}={:.2f}'.format(k, v)) global_barrier.wait() # barrier for pretty print # trainer print result sam.shutdown() def run_train(worker_id, run_config): ctx = run_config['train_workers'][worker_id] num_worker = run_config['num_train_worker'] global_barrier = run_config['global_barrier'] train_device = torch.device(ctx) print('[Train Worker {:d}/{:d}] Started with PID {:d}({:s})'.format( worker_id, num_worker, os.getpid(), torch.cuda.get_device_name(ctx))) # let the trainer initialization after sampler # sampler should presample before trainer initialization sam.wait_for_sampler_ready(global_barrier) sam.train_init(worker_id, ctx) if num_worker > 1: dist_init_method = 'tcp://{master_ip}:{master_port}'.format( master_ip='127.0.0.1', master_port='12345') world_size = num_worker torch.distributed.init_process_group(backend="nccl", init_method=dist_init_method, world_size=world_size, rank=worker_id, timeout=datetime.timedelta(seconds=get_default_timeout())) in_feat = sam.feat_dim() num_class = sam.num_class() num_layer = run_config['num_layer'] model = GCN(in_feat, run_config['num_hidden'], num_class, num_layer, F.relu, run_config['dropout']) model = model.to(train_device) if num_worker > 1: model = DistributedDataParallel( model, device_ids=[train_device], output_device=train_device) loss_fcn = nn.CrossEntropyLoss() loss_fcn = loss_fcn.to(train_device) optimizer = optim.Adam( model.parameters(), lr=run_config['lr'], weight_decay=run_config['weight_decay']) num_epoch = sam.num_epoch() num_step = sam.steps_per_epoch() model.train() epoch_copy_times = [] epoch_convert_times = [] epoch_train_times = [] epoch_total_times_python = [] epoch_train_total_times_profiler = [] epoch_pipeline_train_total_times_python = [] epoch_cache_hit_rates = [] epoch_miss_nbytes = [] epoch_feat_nbytes = [] copy_times = [] convert_times = [] train_times = [] total_times = [] align_up_step = int( int((num_step + num_worker - 1) / num_worker) * num_worker) # run start barrier global_barrier.wait() print('[Train Worker {:d}] run train for {:d} epochs with {:d} steps'.format( worker_id, num_epoch, num_step)) run_start = time.time() for epoch in range(num_epoch): # epoch start barrier global_barrier.wait() tic = time.time() if run_config['pipeline'] or run_config['single_gpu']: need_steps = int(num_step / num_worker) if worker_id < num_step % num_worker: need_steps += 1 sam.extract_start(need_steps) for step in range(worker_id, align_up_step, num_worker): if step < num_step: t0 = time.time() if (not run_config['pipeline']) and (not run_config['single_gpu']): sam.sample_once() batch_key = sam.get_next_batch() t1 = time.time() blocks, batch_input, batch_label = sam.get_dgl_blocks( batch_key, num_layer) t2 = time.time() else: t0 = t1 = t2 = time.time() # Compute loss and prediction batch_pred = model(blocks, batch_input) loss = loss_fcn(batch_pred, batch_label) optimizer.zero_grad() loss.backward() optimizer.step() # wait for the train finish then we can free the data safely event_sync() if (step + num_worker < num_step): batch_input = None batch_label = None blocks = None t3 = time.time() copy_time = sam.get_log_step_value(epoch, step, sam.kLogL1CopyTime) convert_time = t2 - t1 train_time = t3 - t2 total_time = t3 - t1 sam.log_step(epoch, step, sam.kLogL1TrainTime, train_time) sam.log_step(epoch, step, sam.kLogL1ConvertTime, convert_time) sam.log_epoch_add(epoch, sam.kLogEpochConvertTime, convert_time) sam.log_epoch_add(epoch, sam.kLogEpochTrainTime, train_time) sam.log_epoch_add(epoch, sam.kLogEpochTotalTime, total_time) copy_times.append(copy_time) convert_times.append(convert_time) train_times.append(train_time) total_times.append(total_time) # sam.report_step_average(epoch, step) # sync the train workers if num_worker > 1: torch.distributed.barrier() toc = time.time() epoch_total_times_python.append(toc - tic) # epoch end barrier global_barrier.wait() feat_nbytes = sam.get_log_epoch_value( epoch, sam.kLogEpochFeatureBytes) miss_nbytes = sam.get_log_epoch_value( epoch, sam.kLogEpochMissBytes) epoch_miss_nbytes.append(miss_nbytes) epoch_feat_nbytes.append(feat_nbytes) epoch_cache_hit_rates.append( (feat_nbytes - miss_nbytes) / feat_nbytes) epoch_copy_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochCopyTime)) epoch_convert_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochConvertTime)) epoch_train_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochTrainTime)) epoch_train_total_times_profiler.append( sam.get_log_epoch_value(epoch, sam.kLogEpochTotalTime)) if worker_id == 0: print('Epoch {:05d} | Epoch Time {:.4f} | Total Train Time(Profiler) {:.4f} | Copy Time {:.4f}'.format( epoch, epoch_total_times_python[-1], epoch_train_total_times_profiler[-1], epoch_copy_times[-1])) # sync the train workers if num_worker > 1: torch.distributed.barrier() print('[Train Worker {:d}] Avg Epoch Time {:.4f} | Train Total Time(Profiler) {:.4f} | Copy Time {:.4f}'.format( worker_id, np.mean(epoch_total_times_python[1:]), np.mean(epoch_train_total_times_profiler[1:]), np.mean(epoch_copy_times[1:]))) # run end barrier global_barrier.wait() run_end = time.time() # sampler print init and result global_barrier.wait() # barrier for pretty print if worker_id == 0: sam.report_step_average(epoch - 1, step - 1) sam.report_init() test_result = [] test_result.append(('epoch_time:copy_time', np.mean(epoch_copy_times[1:]))) test_result.append(('convert_time', np.mean(epoch_convert_times[1:]))) test_result.append(('train_time', np.mean(epoch_train_times[1:]))) test_result.append(('epoch_time:train_total', np.mean( epoch_train_total_times_profiler[1:]))) test_result.append( ('cache_percentage', run_config['cache_percentage'])) test_result.append(('cache_hit_rate', np.mean( epoch_cache_hit_rates[1:]))) test_result.append(('epoch_feat_nbytes', np.mean(epoch_feat_nbytes[1:]))) test_result.append(('batch_feat_nbytes', np.mean(epoch_feat_nbytes[1:])/(align_up_step/num_worker))) test_result.append(('epoch_miss_nbytes', np.mean(epoch_miss_nbytes[1:]))) test_result.append(('batch_miss_nbytes', np.mean(epoch_miss_nbytes[1:])/(align_up_step/num_worker))) test_result.append(('batch_copy_time', np.mean(epoch_copy_times[1:])/(align_up_step/num_worker))) test_result.append(('batch_train_time', np.mean(epoch_train_total_times_profiler[1:])/(align_up_step/num_worker))) if run_config['pipeline']: test_result.append( ('pipeline_train_epoch_time', np.mean(epoch_total_times_python[1:]))) test_result.append(('run_time', run_end - run_start)) test_result.append(('init:load_dataset:copy:trainer', sam.get_log_init_value(sam.kLogInitL3LoadDatasetCopy))) test_result.append(('init:dist_queue:pin:trainer', sam.get_log_init_value(sam.kLogInitL3DistQueuePin))) test_result.append(('init:internal:trainer', sam.get_log_init_value(sam.kLogInitL2InternalState))) test_result.append(('init:cache:trainer', sam.get_log_init_value(sam.kLogInitL2BuildCache))) for k, v in test_result: print('test_result:{:}={:.4f}'.format(k, v)) # sam.dump_trace() sam.shutdown() if __name__ == '__main__': run_config = get_run_config() run_init(run_config) num_sample_worker = run_config['num_sample_worker'] num_train_worker = run_config['num_train_worker'] # global barrier is used to sync all the sample workers and train workers run_config['global_barrier'] = mp.Barrier( num_sample_worker + num_train_worker, timeout=get_default_timeout()) workers = [] # sample processes for worker_id in range(num_sample_worker): p = mp.Process(target=run_sample, args=(worker_id, run_config)) p.start() workers.append(p) # train processes for worker_id in range(num_train_worker): p = mp.Process(target=run_train, args=(worker_id, run_config)) p.start() workers.append(p) ret = sam.wait_one_child() if ret != 0: for p in workers: p.kill() for p in workers: p.join() if ret != 0: sys.exit(1)
16,675
5,644
import serial # Using SERIAL module to connect to comm ports via ARDUINO Arduino_Serial = serial.Serial('/dev/ttyACM0',9600) # Connecting via ttyACM0 port (LINUX) print (Arduino_Serial.readline()) # Status print ("Please enter --------> 1 <------- to TURN ON THE LED and ---------> 0 <-------- to TURN OFF THE LED") while (True): # InFinite LOOP input_data = input() print ( "USER Entered... ", input_data ) if (input_data == '405'): # Exit Condition Arduino_Serial.write( '405'.encode() ) print ("--- Thank You ---") print ("--- ! BYE ! ---") break; elif (input_data == '1'): # Condition ONE Arduino_Serial.write( '1'.encode() ) # For Python 3 and above --> use "encode" to convert raw input into bytes! print ("--- LED IS ON NOW ---") print ("PRESS 405 to exit!!") elif (input_data == '0'): # Condition TWO Arduino_Serial.write( '0'.encode() ) # For Python 3 and above --> use "encode" to convert raw input into bytes! print ("--- LED IS OFF NOW ---") print ("PRESS 405 to exit!!") else: print(" Invalid Input! Sorry! ") ''' CODED BY TSG405 '''
1,445
416
import os import pathlib import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd from collections import OrderedDict class Logger: def __init__(self, save_dir, prefix=''): #names = ['epoch', # 'loss', 'loss_max', 'loss_median', 'loss_min', 'active_loss', # 'feat_2-norm_max', 'feat_2-norm_median', 'feat_2-norm_min'] self.log = OrderedDict([('epoch', [])]) self.save_dir = os.path.join(save_dir) pathlib.Path(save_dir).mkdir(parents=True, exist_ok=True) self.prefix = prefix def logg(self, d): for k in d: if k not in self.log: self.log[k] = [] self.log[k].append(d[k]) def append_epoch(self, e): self.log['epoch'].append(e) def append_loss(self, b_loss): names = ['loss', 'loss_max', 'loss_median', 'loss_min', 'active_loss'] for n in names: if n not in self.log: self.log[n] = [] self.log['loss'].append(b_loss.mean()) self.log['loss_max'].append(b_loss.max()) self.log['loss_median'].append(np.median(b_loss)) self.log['loss_min'].append(b_loss.min()) self.log['active_loss'].append((b_loss > 1e-3).mean()) def append_feat(self, b_feat): names = ['feat_2-norm_max', 'feat_2-norm_median', 'feat_2-norm_min'] for n in names: if n not in self.log: self.log[n] = [] norm = np.linalg.norm(b_feat, axis=1) self.log['feat_2-norm_max'].append(norm.max()) self.log['feat_2-norm_median'].append(np.median(norm)) self.log['feat_2-norm_min'].append(norm.min()) def write_log(self): dataframe = pd.DataFrame(self.log) dataframe.to_csv(os.path.join(self.save_dir, '%slog.csv' % self.prefix), index=False) def plot(self): epoch = np.array(self.log['epoch']) plt.figure() labels = ['loss_max', 'loss_median', 'loss_min'] for i, l in enumerate(labels): data = np.array(self.log[l]) plt.semilogy(epoch, data, label=l, color=cm.Blues(0.25+float(i)*0.25)) data = np.array(self.log['loss']) plt.semilogy(epoch, data, label='loss', color='r') plt.legend() plt.xlabel('epoch') plt.ylabel('loss') plt.title('loss vs. epoch') plt.savefig(os.path.join(self.save_dir, '%sloss.png' % self.prefix)) plt.close() plt.figure() data = np.array(self.log['active_loss']) plt.plot(epoch, data, label='active_loss') plt.legend() plt.xlabel('epoch') plt.ylabel('% of active loss') plt.title('% of active loss vs. epoch') plt.savefig(os.path.join(self.save_dir, '%sactive_loss.png' % self.prefix)) plt.close() plt.figure() labels = ['feat_2-norm_max', 'feat_2-norm_median', 'feat_2-norm_min'] for i, l in enumerate(labels): data = np.array(self.log[l]) plt.plot(epoch, data, label=l, color=cm.Blues(0.25+float(i)*0.25)) plt.legend() plt.xlabel('epoch') plt.ylabel('2-norm of feature') plt.title('2-norm of feature vs. epoch') plt.savefig(os.path.join(self.save_dir, '%sfeature_norm.png' % self.prefix)) plt.close()
3,453
1,217
# AFM font ZapfDingbats (path: /usr/share/fonts/afms/adobe/pzdr.afm). # Derived from Ghostscript distribution. # Go to www.cs.wisc.edu/~ghost to get the Ghostcript source code. import dir dir.afm["ZapfDingbats"] = (500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, 500, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918, )
1,493
1,363
import bs import random import math class RunaroundGame(bs.CoopGameActivity): tips = [ 'Jump just as you\'re throwing to get bombs up to the highest levels.', 'No, you can\'t get up on the ledge. You have to throw bombs.', 'Whip back and forth to get more distance on your throws..'] @classmethod def getName(cls): return 'Runaround' @classmethod def getDescription(cls, sessionType): return "Prevent enemies from reaching the exit." def __init__(self, settings={}): settings['map'] = 'Tower D' bs.CoopGameActivity.__init__(self, settings) try: self._preset = self.settings['preset'] except Exception: self._preset = 'pro' self._playerDeathSound = bs.getSound('playerDeath') self._newWaveSound = bs.getSound('scoreHit01') self._winSound = bs.getSound("score") self._cashRegisterSound = bs.getSound('cashRegister') self._badGuyScoreSound = bs.getSound("shieldDown") self._heartTex = bs.getTexture('heart') self._heartModelOpaque = bs.getModel('heartOpaque') self._heartModelTransparent = bs.getModel('heartTransparent') self._aPlayerHasBeenKilled = False self._spawnCenter = self._mapType.defs.points['spawn1'][0:3] self._tntSpawnPosition = self._mapType.defs.points['tntLoc'][0:3] self._powerupCenter = self._mapType.defs.boxes['powerupRegion'][0:3] self._powerupSpread = ( self._mapType.defs.boxes['powerupRegion'][6]*0.5, self._mapType.defs.boxes['powerupRegion'][8]*0.5) self._scoreRegionMaterial = bs.Material() self._scoreRegionMaterial.addActions( conditions=("theyHaveMaterial", bs.getSharedObject('playerMaterial')), actions=(("modifyPartCollision", "collide", True), ("modifyPartCollision", "physical", False), ("call", "atConnect", self._handleReachedEnd))) self._lastWaveEndTime = bs.getGameTime() self._playerHasPickedUpPowerup = False def onTransitionIn(self): bs.CoopGameActivity.onTransitionIn(self, music='Marching') self._scoreBoard = bs.ScoreBoard( label=bs.Lstr(resource='scoreText'), scoreSplit=0.5) self._gameOver = False self._wave = 0 self._canEndWave = True # we use this in place of a regular int to make it harder to hack scores self._score = bs.SecureInt(0) self._timeBonus = 0 self._scoreRegion = bs.NodeActor( bs.newNode( 'region', attrs={'position': self.getMap().defs.boxes['scoreRegion'] [0: 3], 'scale': self.getMap().defs.boxes['scoreRegion'] [6: 9], 'type': 'box', 'materials': [self._scoreRegionMaterial]})) def onBegin(self): bs.CoopGameActivity.onBegin(self) self._dingSound = bs.getSound('dingSmall') self._dingSoundHigh = bs.getSound('dingSmallHigh') playerCount = len(self.players) hard = False if self._preset in ['proEasy', 'uberEasy'] else True if self._preset in ['pro', 'proEasy', 'tournament']: self._excludePowerups = ['curse'] self._haveTnt = True self._waves = [ {'entries': [ {'type': bs.BomberBot, 'path': 3 if hard else 2}, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2} if playerCount > 1 \ else None, {'type': bs.BomberBot, 'path': 1} if hard else None, {'type': bs.BomberBot, 'path': 1} if playerCount > 2 \ else None, {'type': bs.BomberBot, 'path': 1} if playerCount > 3 \ else None, ]}, {'entries': [ {'type': bs.BomberBot, 'path': 1} if hard else None, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 2} if playerCount > 3 \ else None, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3} if hard else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 1 \ else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 2 \ else None, ]}, {'entries': [ {'type': bs.NinjaBot, 'path': 2} if hard else None, {'type': bs.NinjaBot, 'path': 2} if playerCount > 2 \ else None, {'type': bs.ChickBot, 'path': 2}, {'type': bs.ChickBot, 'path': 2} if playerCount > 1 \ else None, {'type': 'spacing', 'duration': 3000}, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 3} if hard else None, {'type': bs.BomberBot, 'path': 3}, {'type': bs.BomberBot, 'path': 3}, {'type': bs.BomberBot, 'path': 3} if playerCount > 3 \ else None, ]}, {'entries': [ {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': 'spacing', 'duration': 1000} if hard else None, {'type': bs.ChickBot, 'path': 2}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 3}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': 'spacing', 'duration': 1000} if hard else None, {'type': bs.ChickBot, 'path': 2}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 3}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 1} if (playerCount > 1 \ and hard) else None, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 2} if playerCount > 2 \ else None, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 3} if playerCount > 3 \ else None, {'type': 'spacing', 'duration': 1000}, ]}, {'entries': [ {'type': bs.NinjaBotProShielded if hard else bs.NinjaBot, 'path': 1}, {'type': bs.ToughGuyBot, 'path': 2} if hard else None, {'type': bs.ToughGuyBot, 'path': 2}, {'type': bs.ToughGuyBot, 'path': 2}, {'type': bs.ToughGuyBot, 'path': 3} if hard else None, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 1 \ else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 2 \ else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 3 \ else None, ]}, {'entries': [ {'type': bs.BomberBotProShielded, 'path': 3}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 1} if hard \ else None, {'type': 'spacing', 'duration': 1000} if hard else None, {'type': bs.BomberBotProShielded, 'path': 3}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 1} if hard \ else None, {'type': 'spacing', 'duration': 1500} if hard else None, {'type': bs.BomberBotProShielded, 'path': 3} \ if playerCount > 1 else None, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 2} \ if playerCount > 2 else None, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 1} \ if playerCount > 3 else None, ]}, ] elif self._preset in ['uberEasy', 'uber', 'tournamentUber']: self._excludePowerups = [] self._haveTnt = True self._waves = [ {'entries': [ {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': bs.ChickBot, 'path': 2}, {'type': bs.ChickBot, 'path': 2}, {'type': bs.ChickBot, 'path': 3}, {'type': bs.ToughGuyBotPro if hard else bs.ToughGuyBot, 'point': 'BottomLeft'}, {'type': bs.ToughGuyBotPro, 'point': 'BottomRight'} \ if playerCount > 2 else None, ]}, {'entries': [ {'type': bs.NinjaBot, 'path': 2}, {'type': bs.NinjaBot, 'path': 3}, {'type': bs.NinjaBot, 'path': 1} if hard else None, {'type': bs.NinjaBot, 'path': 2}, {'type': bs.NinjaBot, 'path': 3}, {'type': bs.NinjaBot, 'path': 1} if playerCount > 2 \ else None, ]}, {'entries': [ {'type': bs.BomberBotProShielded, 'path': 1} if hard \ else None, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 3}, {'type': bs.BomberBotProShielded, 'path': 3}, {'type': bs.NinjaBot, 'point': 'BottomRight'}, {'type': bs.NinjaBot, 'point': 'BottomLeft'} \ if playerCount > 2 else None, ]}, {'entries': [ {'type': bs.ChickBotPro, 'path': 1} if hard else None, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2} \ if playerCount > 1 else None, {'type': bs.ChickBotPro, 'path': 1 if hard else 2} \ if playerCount > 3 else None, ]}, {'entries': [ {'type': bs.ChickBotProShielded if hard else bs.ChickBotPro, 'point': 'BottomLeft'}, {'type': bs.ChickBotProShielded, 'point': 'BottomRight'} \ if hard else None, {'type': bs.ChickBotProShielded, 'point': 'BottomRight'} \ if playerCount > 2 else None, {'type': bs.BomberBot, 'path': 3}, {'type': bs.BomberBot, 'path': 3}, {'type': 'spacing', 'duration': 5000}, {'type': bs.ToughGuyBot, 'path': 2}, {'type': bs.ToughGuyBot, 'path': 2}, {'type': 'spacing', 'duration': 5000}, {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': bs.ChickBot, 'path': 1} if hard else None, ]}, {'entries': [ {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2} if hard \ else None, {'type': bs.MelBot, 'point': 'BottomRight'}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.MelBot, 'point': 'BottomRight'} \ if playerCount > 2 else None, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.PirateBot, 'point': 'BottomLeft'}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2} \ if playerCount > 1 else None, {'type': 'spacing', 'duration': 5000}, {'type': bs.MelBot, 'point': 'BottomLeft'}, {'type': 'spacing', 'duration': 2000}, {'type': bs.PirateBot, 'point': 'BottomRight'}, ]}, ] elif self._preset in ['endless', 'endlessTournament']: self._excludePowerups = [] self._haveTnt = True # spit out a few powerups and start dropping more shortly self._dropPowerups(standardPoints=True) bs.gameTimer(4000, self._startPowerupDrops) self.setupLowLifeWarningSound() self._updateScores() self._bots = bs.BotSet() # our TNT spawner (if applicable) if self._haveTnt: self._tntSpawner = bs.TNTSpawner(position=self._tntSpawnPosition) # make sure to stay out of the way of menu/party buttons in the corner interfaceType = bs.getEnvironment()['interfaceType'] lOffs = (-80 if interfaceType == 'small' else -40 if interfaceType == 'medium' else 0) self._livesBG = bs.NodeActor( bs.newNode( 'image', attrs={'texture': self._heartTex, 'modelOpaque': self._heartModelOpaque, 'modelTransparent': self._heartModelTransparent, 'attach': 'topRight', 'scale': (90, 90), 'position': (-110 + lOffs, -50), 'color': (1, 0.2, 0.2)})) vr = bs.getEnvironment()['vrMode'] self._startLives = 10 self._lives = self._startLives self._livesText = bs.NodeActor( bs.newNode( 'text', attrs={'vAttach': 'top', 'hAttach': 'right', 'hAlign': 'center', 'color': (1, 1, 1, 1) if vr else(0.8, 0.8, 0.8, 1.0), 'flatness': 1.0 if vr else 0.5, 'shadow': 1.0 if vr else 0.5, 'vrDepth': 10, 'position': (-113 + lOffs, -69), 'scale': 1.3, 'text': str(self._lives)})) bs.gameTimer(2000, self._startUpdatingWaves) def _handleReachedEnd(self): n = bs.getCollisionInfo("opposingNode") spaz = n.getDelegate() if not spaz.isAlive(): return # ignore bodies flying in.. self._flawless = False p = spaz.node.position bs.playSound(self._badGuyScoreSound, position=p) light = bs.newNode('light', attrs={'position': p, 'radius': 0.5, 'color': (1, 0, 0)}) bs.animate(light, 'intensity', {0: 0, 100: 1, 500: 0}, loop=False) bs.gameTimer(1000, light.delete) spaz.handleMessage(bs.DieMessage(immediate=True, how='goal')) if self._lives > 0: self._lives -= 1 if self._lives == 0: self._bots.stopMoving() self.continueOrEndGame() self._livesText.node.text = str(self._lives) t = 0 def _safeSetAttr(node, attr, value): if node.exists(): setattr(node, attr, value) for i in range(4): bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesText.node, 'color', (1, 0, 0, 1.0))) bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesBG.node, 'opacity', 0.5)) t += 125 bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesText.node, 'color', (1.0, 1.0, 0.0, 1.0))) bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesBG.node, 'opacity', 1.0)) t += 125 bs.gameTimer( t, bs.Call( _safeSetAttr, self._livesText.node, 'color', (0.8, 0.8, 0.8, 1.0))) def onContinue(self): self._lives = 3 self._livesText.node.text = str(self._lives) self._bots.startMoving() def spawnPlayer(self, player): pos = ( self._spawnCenter[0] + random.uniform(-1.5, 1.5), self._spawnCenter[1], self._spawnCenter[2] + random.uniform(-1.5, 1.5)) s = self.spawnPlayerSpaz(player, position=pos) if self._preset in ['proEasy', 'uberEasy']: s._impactScale = 0.25 # add the material that causes us to hit the player-wall s.pickUpPowerupCallback = self._onPlayerPickedUpPowerup def _onPlayerPickedUpPowerup(self, player): self._playerHasPickedUpPowerup = True def _dropPowerup(self, index, powerupType=None): if powerupType is None: powerupType = bs.Powerup.getFactory().getRandomPowerupType( excludeTypes=self._excludePowerups) bs.Powerup( position=self.getMap().powerupSpawnPoints[index], powerupType=powerupType).autoRetain() def _startPowerupDrops(self): bs.gameTimer(3000, self._dropPowerups, repeat=True) def _dropPowerups(self, standardPoints=False, forceFirst=None): """ Generic powerup drop """ # if its been a minute since our last wave finished emerging, stop # giving out land-mine powerups. (prevents players from waiting # around for them on purpose and filling the map up) if bs.getGameTime() - self._lastWaveEndTime > 60000: extraExcludes = ['landMines'] else: extraExcludes = [] if standardPoints: pts = self.getMap().powerupSpawnPoints for i, pt in enumerate(pts): bs.gameTimer(1000+i*500, bs.Call( self._dropPowerup, i, forceFirst if i == 0 else None)) else: pt = (self._powerupCenter[0] +random.uniform(-1.0*self._powerupSpread[0], 1.0*self._powerupSpread[0]), self._powerupCenter[1], self._powerupCenter[2]+random.uniform(-self._powerupSpread[1], self._powerupSpread[1])) # drop one random one somewhere.. bs.Powerup(position=pt, powerupType=bs.Powerup.getFactory().getRandomPowerupType( excludeTypes=self._excludePowerups+extraExcludes) ).autoRetain() def endGame(self): # FIXME FIXME FIXME - if we don't start our bots moving again we get # stuck this is because the bot-set never prunes itself while movement # is off and onFinalize never gets called for some bots because # _pruneDeadObjects() saw them as dead and pulled them off the # weak-ref lists. this is an architectural issue; can hopefully fix # this by having _actorWeakRefs not look at exists() self._bots.startMoving() bs.gameTimer(1, bs.Call(self.doEnd, 'defeat')) bs.playMusic(None) bs.playSound(self._playerDeathSound) def doEnd(self, outcome): if outcome == 'defeat': delay = 2000 self.fadeToRed() else: delay = 0 if self._wave >= 2: score = self._score.get() failMessage = None else: score = None failMessage = 'Reach wave 2 to rank.' self.end( delay=delay, results={'outcome': outcome, 'score': score, 'failMessage': failMessage, 'playerInfo': self.initialPlayerInfo}) def _onGotScoresToBeat(self, scores): self._showStandardScoresToBeatUI(scores) def _updateWaves(self): # if we have no living bots, go to the next wave if (self._canEndWave and not self._bots.haveLivingBots() and not self._gameOver and self._lives > 0): self._canEndWave = False self._timeBonusTimer = None self._timeBonusText = None if self._preset in ['endless', 'endlessTournament']: won = False else: won = (self._wave == len(self._waves)) # reward time bonus baseDelay = 4000 if won else 0 if self._timeBonus > 0: bs.gameTimer(0, bs.Call(bs.playSound, self._cashRegisterSound)) bs.gameTimer(baseDelay, bs.Call( self._awardTimeBonus, self._timeBonus)) baseDelay += 1000 # reward flawless bonus if self._wave > 0 and self._flawless: bs.gameTimer(baseDelay, self._awardFlawlessBonus) baseDelay += 1000 self._flawless = True # reset if won: # completion achievements if self._preset in ['pro', 'proEasy']: self._awardAchievement('Pro Runaround Victory', sound=False) if self._lives == self._startLives: self._awardAchievement('The Wall', sound=False) if not self._playerHasPickedUpPowerup: self._awardAchievement('Precision Bombing', sound=False) elif self._preset in ['uber', 'uberEasy']: self._awardAchievement( 'Uber Runaround Victory', sound=False) if self._lives == self._startLives: self._awardAchievement('The Great Wall', sound=False) if not self._aPlayerHasBeenKilled: self._awardAchievement('Stayin\' Alive', sound=False) # give remaining players some points and have them celebrate self.showZoomMessage( bs.Lstr(resource='victoryText'), scale=1.0, duration=4000) self.celebrate(10000) bs.gameTimer(baseDelay, self._awardLivesBonus) baseDelay += 1000 bs.gameTimer(baseDelay, self._awardCompletionBonus) baseDelay += 850 bs.playSound(self._winSound) self.cameraFlash() bs.playMusic('Victory') self._gameOver = True bs.gameTimer(baseDelay, bs.Call(self.doEnd, 'victory')) return self._wave += 1 # short celebration after waves if self._wave > 1: self.celebrate(500) bs.gameTimer(baseDelay, self._startNextWave) def _awardCompletionBonus(self): bonus = 200 bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(bonus)), ('${B}', bs.Lstr(resource='completionBonusText'))]), color=(0.7, 0.7, 1.0, 1), scale=1.6, position=(0, 1.5, -1)).autoRetain() self._score.add(bonus) self._updateScores() def _awardLivesBonus(self,): bonus = self._lives * 30 bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(bonus)), ('${B}', bs.Lstr(resource='livesBonusText'))]), color=(0.7, 1.0, 0.3, 1), scale=1.3, position=(0, 1, -1)).autoRetain() self._score.add(bonus) self._updateScores() def _awardTimeBonus(self, bonus): bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(bonus)), ('${B}', bs.Lstr(resource='timeBonusText'))]), color=(1, 1, 0.5, 1), scale=1.0, position=(0, 3, -1)).autoRetain() self._score.add(self._timeBonus) self._updateScores() def _awardFlawlessBonus(self): bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(self._flawlessBonus)), ('${B}', bs.Lstr(resource='perfectWaveText'))]), color=(1, 1, 0.2, 1), scale=1.2, position=(0, 2, -1)).autoRetain() self._score.add(self._flawlessBonus) self._updateScores() def _startTimeBonusTimer(self): self._timeBonusTimer = bs.Timer( 1000, self._updateTimeBonus, repeat=True) def _startNextWave(self): self.showZoomMessage( bs.Lstr( value='${A} ${B}', subs=[('${A}', bs.Lstr(resource='waveText')), ('${B}', str(self._wave))]), scale=1.0, duration=1000, trail=True) bs.gameTimer(400, bs.Call(bs.playSound, self._newWaveSound)) t = 0 baseDelay = 500 botAngle = random.random()*360.0 spawnTime = 100 botTypes = [] if self._preset in ['endless', 'endlessTournament']: level = self._wave targetPoints = (level+1) * 8.0 groupCount = random.randint(1, 3) entries = [] spazTypes = [] if level < 6: spazTypes += [[bs.BomberBot, 5.0]] if level < 10: spazTypes += [[bs.ToughGuyBot, 5.0]] if level < 15: spazTypes += [[bs.ChickBot, 6.0]] if level > 5: spazTypes += [[bs.ChickBotPro, 7.5]]*(1+(level-5)/7) if level > 2: spazTypes += [[bs.BomberBotProShielded, 8.0]]*(1+(level-2)/6) if level > 6: spazTypes += [[bs.ChickBotProShielded, 12.0]]*(1+(level-6)/5) if level > 1: spazTypes += [[bs.NinjaBot, 10.0]]*(1+(level-1)/4) if level > 7: spazTypes += [[bs.NinjaBotProShielded, 15.0]]*(1+(level-7)/3) # bot type, their effect on target points defenderTypes = [[bs.BomberBot, 0.9], [bs.ToughGuyBot, 0.9], [bs.ChickBot, 0.85]] if level > 2: defenderTypes += [[bs.NinjaBot, 0.75]] if level > 4: defenderTypes += [[bs.MelBot, 0.7]]*(1+(level-5)/6) if level > 6: defenderTypes += [[bs.PirateBot, 0.7]]*(1+(level-5)/5) if level > 8: defenderTypes += [[bs.ToughGuyBotProShielded, 0.65]]*(1+(level-5)/4) if level > 10: defenderTypes += [[bs.ChickBotProShielded, 0.6]]*(1+(level-6)/3) for group in range(groupCount): thisTargetPoints = targetPoints/groupCount # adding spacing makes things slightly harder r = random.random() if r < 0.07: spacing = 1500 thisTargetPoints *= 0.85 elif r < 0.15: spacing = 1000 thisTargetPoints *= 0.9 else: spacing = 0 path = random.randint(1, 3) # dont allow hard paths on early levels if level < 3: if path == 1: path = 3 # easy path if path == 3: pass # harder path elif path == 2: thisTargetPoints *= 0.8 # even harder path elif path == 1: thisTargetPoints *= 0.7 # looping forward elif path == 4: thisTargetPoints *= 0.7 # looping backward elif path == 5: thisTargetPoints *= 0.7 # random elif path == 6: thisTargetPoints *= 0.7 def _addDefender(defenderType, point): # entries.append() return thisTargetPoints * defenderType[1], { 'type': defenderType[0], 'point': point} # add defenders defenderType1 = defenderTypes[random.randrange( len(defenderTypes))] defenderType2 = defenderTypes[random.randrange( len(defenderTypes))] defender1 = defender2 = None if ((group == 0) or (group == 1 and level > 3) or (group == 2 and level > 5)): if random.random() < min(0.75, (level-1)*0.11): thisTargetPoints, defender1 = _addDefender( defenderType1, 'BottomLeft') if random.random() < min(0.75, (level-1)*0.04): thisTargetPoints, defender2 = _addDefender( defenderType2, 'BottomRight') spazType = spazTypes[random.randrange(len(spazTypes))] memberCount = max(1, int(round(thisTargetPoints/spazType[1]))) for i, member in enumerate(range(memberCount)): if path == 4: thisPath = i % 3 # looping forward elif path == 5: thisPath = 3-(i % 3) # looping backward elif path == 6: thisPath = random.randint(1, 3) # random else: thisPath = path entries.append({'type': spazType[0], 'path': thisPath}) if spacing != 0: entries.append({'type': 'spacing', 'duration': spacing}) if defender1 is not None: entries.append(defender1) if defender2 is not None: entries.append(defender2) # some spacing between groups r = random.random() if r < 0.1: spacing = 5000 elif r < 0.5: spacing = 1000 else: spacing = 1 entries.append({'type': 'spacing', 'duration': spacing}) wave = {'entries': entries} else: wave = self._waves[self._wave-1] try: botAngle = wave['baseAngle'] except Exception: botAngle = 0 botTypes += wave['entries'] self._timeBonusMult = 1.0 thisFlawlessBonus = 0 nonRunnerSpawnTime = 1000 for info in botTypes: if info is None: continue botType = info['type'] if botType is not None: if botType == 'nonRunnerDelay': nonRunnerSpawnTime += info['duration'] continue if botType == 'spacing': t += info['duration'] continue else: try: path = info['path'] except Exception: path = random.randint(1, 3) self._timeBonusMult += botType.pointsMult * 0.02 thisFlawlessBonus += botType.pointsMult * 5 # if its got a position, use that try: point = info['point'] except Exception: point = 'Start' # space our our slower bots delay = baseDelay delay /= self._getBotSpeed(botType) t += int(delay*0.5) bs.gameTimer( t, bs.Call( self.addBotAtPoint, point, {'type': botType, 'path': path}, 100 if point == 'Start' else nonRunnerSpawnTime)) t += int(delay*0.5) # we can end the wave after all the spawning happens bs.gameTimer(t-int(delay*0.5)+nonRunnerSpawnTime+10, self._setCanEndWave) # reset our time bonus # in this game we use a constant time bonus so it erodes away in # roughly the same time (since the time limit a wave can take is # relatively constant) ..we then post-multiply a modifier to adjust # points self._timeBonus = 150 self._flawlessBonus = thisFlawlessBonus self._timeBonusText = bs.NodeActor( bs.newNode( 'text', attrs={'vAttach': 'top', 'hAttach': 'center', 'hAlign': 'center', 'color': (1, 1, 0.0, 1), 'shadow': 1.0, 'vrDepth': -30, 'flatness': 1.0, 'position': (0, -60), 'scale': 0.8, 'text': bs.Lstr( value='${A}: ${B}', subs=[('${A}', bs.Lstr( resource='timeBonusText')), ('${B}', str( int( self._timeBonus * self._timeBonusMult)))])})) bs.gameTimer(t, self._startTimeBonusTimer) # keep track of when this wave finishes emerging - we wanna # stop dropping land-mines powerups at some point # (otherwise a crafty player could fill the whole map with them) self._lastWaveEndTime = bs.getGameTime()+t self._waveText = bs.NodeActor( bs.newNode( 'text', attrs={'vAttach': 'top', 'hAttach': 'center', 'hAlign': 'center', 'vrDepth': -10, 'color': (1, 1, 1, 1), 'shadow': 1.0, 'flatness': 1.0, 'position': (0, -40), 'scale': 1.3, 'text': bs.Lstr( value='${A} ${B}', subs=[('${A}', bs.Lstr(resource='waveText')), ('${B}', str(self._wave) + ('' if self._preset in ['endless', 'endlessTournament'] else('/' + str(len(self._waves)))))])})) def _onBotSpawn(self, path, spaz): # add our custom update callback and set some info for this bot.. spazType = type(spaz) spaz.updateCallback = self._updateBot spaz.rWalkRow = path spaz.rWalkSpeed = self._getBotSpeed(spazType) def addBotAtPoint(self, point, spazInfo, spawnTime=100): # dont add if the game has ended if self._gameOver: return pt = self.getMap().defs.points['botSpawn'+point][:3] self._bots.spawnBot( spazInfo['type'], pos=pt, spawnTime=spawnTime, onSpawnCall=bs.Call( self._onBotSpawn, spazInfo['path'])) def _updateTimeBonus(self): self._timeBonus = int(self._timeBonus * 0.91) if self._timeBonus > 0 and self._timeBonusText is not None: self._timeBonusText.node.text = bs.Lstr( value='${A}: ${B}', subs=[('${A}', bs.Lstr(resource='timeBonusText')), ('${B}', str( int(self._timeBonus * self._timeBonusMult)))]) else: self._timeBonusText = None def _startUpdatingWaves(self): self._waveUpdateTimer = bs.Timer(2000, self._updateWaves, repeat=True) def _updateScores(self): score = self._score.get() if self._preset == 'endless': if score >= 500: self._awardAchievement('Runaround Master') if score >= 1000: self._awardAchievement('Runaround Wizard') if score >= 2000: self._awardAchievement('Runaround God') self._scoreBoard.setTeamValue(self.teams[0], score, maxScore=None) def _updateBot(self, bot): speed = bot.rWalkSpeed t = bot.node.position boxes = self.getMap().defs.boxes # bots in row 1 attempt the high road.. if bot.rWalkRow == 1: if bs.isPointInBox(t, boxes['b4']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True # row 1 and 2 bots attempt the middle road.. if bot.rWalkRow in [1, 2]: if bs.isPointInBox(t, boxes['b1']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True # *all* bots settle for the third row if bs.isPointInBox(t, boxes['b7']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b2']): bot.node.moveUpDown = -speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b3']): bot.node.moveUpDown = -speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b5']): bot.node.moveUpDown = -speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b6']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif (bs.isPointInBox(t, boxes['b8']) and not bs.isPointInBox(t, boxes['b9'])) or t == (0.0, 0.0, 0.0): # default to walking right if we're still in the walking area bot.node.moveLeftRight = speed bot.node.moveUpDown = 0 bot.node.run = 0.0 return True # revert to normal bot behavior otherwise.. return False def handleMessage(self, m): if isinstance(m, bs.PlayerScoredMessage): self._score.add(m.score) self._updateScores() # respawn dead players elif isinstance(m, bs.PlayerSpazDeathMessage): self._aPlayerHasBeenKilled = True player = m.spaz.getPlayer() if player is None: bs.printError('FIXME: getPlayer() should no' ' longer ever be returning None') return if not player.exists(): return self.scoreSet.playerLostSpaz(player) # respawn them shortly respawnTime = 2000+len(self.initialPlayerInfo)*1000 player.gameData['respawnTimer'] = bs.Timer( respawnTime, bs.Call(self.spawnPlayerIfExists, player)) player.gameData['respawnIcon'] = bs.RespawnIcon(player, respawnTime) elif isinstance(m, bs.SpazBotDeathMessage): if m.how == 'goal': return pts, importance = m.badGuy.getDeathPoints(m.how) if m.killerPlayer is not None: try: target = m.badGuy.node.position except Exception: target = None try: if m.killerPlayer is not None and m.killerPlayer.exists(): self.scoreSet.playerScored( m.killerPlayer, pts, target=target, kill=True, screenMessage=False, importance=importance) bs.playSound( self._dingSound if importance == 1 else self._dingSoundHigh, volume=0.6) except Exception as e: print 'EXC in Runaround handling SpazBotDeathMessage:', e # normally we pull scores from the score-set, but if there's no # player lets be explicit.. else: self._score.add(pts) self._updateScores() else: self.__superHandleMessage(m) def __superHandleMessage(self, m): super(RunaroundGame, self).handleMessage(m) def _getBotSpeed(self, botType): if botType == bs.BomberBot: return 0.48 elif botType == bs.BomberBotPro: return 0.48 elif botType == bs.BomberBotProShielded: return 0.48 elif botType == bs.ToughGuyBot: return 0.57 elif botType == bs.ToughGuyBotPro: return 0.57 elif botType == bs.ToughGuyBotProShielded: return 0.57 elif botType == bs.ChickBot: return 0.73 elif botType == bs.ChickBotPro: return 0.78 elif botType == bs.ChickBotProShielded: return 0.78 elif botType == bs.NinjaBot: return 1.0 elif botType == bs.NinjaBotProShielded: return 1.0 elif botType == bs.PirateBot: return 1.0 elif botType == bs.MelBot: return 0.5 else: raise Exception('Invalid bot type to _getBotSpeed(): '+str(botType)) def _setCanEndWave(self): self._canEndWave = True
43,185
13,216
#!/usr/bin/python3 from plano import * ENV["BACKEND_SERVICE_HOST"] = "localhost" ENV["BACKEND_SERVICE_PORT"] = backend_port = str(get_random_port()) ENV["FRONTEND_SERVICE_PORT"] = frontend_port = str(get_random_port()) backend_url = f"http://localhost:{backend_port}/api/hello" frontend_url = f"http://localhost:{frontend_port}/" with start("python3 backend/app.py") as backend: with start("python3 frontend/app.py") as frontend: sleep(0.5) print(http_get(backend_url)) print(http_get(backend_url)) print(http_get(backend_url)) print(http_get(frontend_url)) print(http_get(frontend_url)) print(http_get(frontend_url)) print("SUCCESS")
710
250
"""Python C API alternative to `fractions` module.""" __version__ = '1.4.0' try: from _cfractions import Fraction except ImportError: import numbers as _numbers from fractions import Fraction as _Fraction from typing import (Any as _Any, Dict as _Dict, Optional as _Optional, Tuple as _Tuple, TypeVar as _TypeVar, Union as _Union, overload as _overload) _Number = _TypeVar('_Number', bound=_numbers.Number) class Fraction(_Fraction): def limit_denominator(self, max_denominator: int = 10 ** 6 ) -> 'Fraction': result = super().limit_denominator(max_denominator) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def as_integer_ratio(self) -> _Tuple[int, int]: return self.numerator, self.denominator def __new__(cls, numerator: _Union[int, float] = 0, denominator: _Optional[int] = None, **kwargs) -> 'Fraction': if denominator is not None: if not isinstance(denominator, int): raise TypeError('Denominator should be an integer.') if not isinstance(numerator, int): raise TypeError('Numerator should be an integer ' 'when denominator is specified.') return super().__new__(cls, numerator, denominator, **kwargs) def __abs__(self) -> 'Fraction': result = super().__abs__() return Fraction(result.numerator, result.denominator) @_overload def __add__(self, other: _numbers.Rational) -> 'Fraction': """Returns sum of the fraction with given rational number.""" @_overload def __add__(self, other: _Number) -> _Number: """Returns sum of the fraction with given number.""" def __add__(self, other): result = super().__add__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __copy__(self) -> 'Fraction': cls = type(self) return (self if cls is Fraction else cls(self._numerator, self._denominator)) def __deepcopy__(self, memo: _Optional[_Dict[int, _Any]] = None ) -> 'Fraction': return self.__copy__() def __divmod__(self, other: _Number ) -> _Tuple[_Number, _Union['Fraction', _Number]]: result = (divmod(float(self), other) if isinstance(other, float) else super().__divmod__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return ((result[0], Fraction(result[1].numerator, result[1].denominator) if isinstance(result[1], _numbers.Rational) else result[1]) if isinstance(result, tuple) else result) @_overload def __floordiv__(self, other: _numbers.Rational) -> 'Fraction': """ Returns quotient of division of the fraction by given rational number. """ @_overload def __floordiv__(self, other: _Number) -> _Number: """Returns quotient of division of the fraction by given number.""" def __floordiv__(self, other): result = (float(self) // other if isinstance(other, float) else super().__floordiv__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __mod__(self, other: _numbers.Rational) -> 'Fraction': """ Returns remainder of division of the fraction by given rational number. """ @_overload def __mod__(self, other: _Number) -> _Number: """ Returns remainder of division of the fraction by given number. """ def __mod__(self, other): result = (float(self) % other if isinstance(other, float) else super().__mod__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __mul__(self, other: _numbers.Rational) -> 'Fraction': """Returns product of the fraction with given rational number.""" @_overload def __mul__(self, other: _Number) -> _Number: """Returns product of the fraction with given number.""" def __mul__(self, other): result = super().__mul__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __neg__(self) -> 'Fraction': result = super().__neg__() return Fraction(result.numerator, result.denominator) def __pos__(self) -> 'Fraction': result = super().__pos__() return Fraction(result.numerator, result.denominator) def __pow__(self, exponent: _numbers.Complex, modulo: _Optional[_numbers.Complex] = None ) -> _numbers.Complex: result = super().__pow__(_Fraction(exponent.numerator, exponent.denominator) if isinstance(exponent, _numbers.Rational) else exponent) if isinstance(result, _numbers.Complex) and modulo is not None: result %= (_Fraction(modulo) if isinstance(modulo, _numbers.Rational) else modulo) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __radd__(self, other: _numbers.Rational) -> 'Fraction': """Returns sum of given rational number with the fraction.""" @_overload def __radd__(self, other: _Number) -> _Number: """Returns sum of given number with the fraction.""" def __radd__(self, other): result = super().__radd__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __rdivmod__(self, other: _Number ) -> _Tuple[_Number, _Union['Fraction', _Number]]: result = (divmod(other, float(self)) if isinstance(other, float) else super().__rdivmod__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return ((result[0], Fraction(result[1].numerator, result[1].denominator) if isinstance(result[1], _numbers.Rational) else result[1]) if isinstance(result, tuple) else result) @_overload def __rfloordiv__(self, other: _numbers.Rational) -> 'Fraction': """ Returns quotient of division of given rational number by the fraction. """ @_overload def __rfloordiv__(self, other: _Number) -> _Number: """Returns quotient of division of given number by the fraction.""" def __rfloordiv__(self, other): result = (other // float(self) if isinstance(other, float) else super().__rfloordiv__(Fraction(other) if isinstance(other, _numbers.Rational) else other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rmod__(self, other: _numbers.Rational) -> 'Fraction': """ Returns remainder of division of given rational number by the fraction. """ @_overload def __rmod__(self, other: _Number) -> _Number: """ Returns remainder of division of given number by the fraction. """ def __rmod__(self, other): result = (other % float(self) if isinstance(other, float) else super().__rmod__(other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rmul__(self, other: _numbers.Rational) -> 'Fraction': """Returns product of given rational number with the fraction.""" @_overload def __rmul__(self, other: _Number) -> _Number: """Returns product of given number with the fraction.""" def __rmul__(self, other): result = super().__rmul__(other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __round__(self, precision: _Optional[int] = None ) -> _Union[int, 'Fraction']: result = super().__round__(precision) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __rpow__(self, base: _numbers.Complex, modulo: _Optional[_numbers.Complex] = None ) -> _numbers.Complex: result = (_Fraction(base.numerator, base.denominator).__pow__(self) if isinstance(base, _numbers.Rational) else super().__rpow__(base)) if isinstance(result, _numbers.Complex) and modulo is not None: result %= modulo return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rsub__(self, other: _numbers.Rational) -> 'Fraction': """ Returns difference of given rational number with the fraction. """ @_overload def __rsub__(self, other: _Number) -> _Number: """Returns difference of given number with the fraction.""" def __rsub__(self, other): result = super().__rsub__(other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rtruediv__(self, other: _numbers.Rational) -> 'Fraction': """Returns division of given rational number by the fraction.""" @_overload def __rtruediv__(self, other: _Number) -> _Number: """Returns division of given number by the fraction.""" def __rtruediv__(self, other): result = super().__rtruediv__(other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __sub__(self, other: _numbers.Rational) -> 'Fraction': """ Returns difference of the fraction with given rational number. """ @_overload def __sub__(self, other: _Number) -> _Number: """Returns difference of the fraction with given number.""" def __sub__(self, other): result = super().__sub__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __truediv__(self, other: _numbers.Rational) -> 'Fraction': """Returns division of the fraction by given rational number.""" @_overload def __truediv__(self, other: _Number) -> _Number: """Returns division of the fraction by given number.""" def __truediv__(self, other): result = super().__truediv__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result)
14,492
3,565
import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import LabelBinarizer from sklearn.linear_model.logistic import LogisticRegression from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import classification_report from os.path import dirname, abspath, join PROJECT_ROOT = dirname(dirname(dirname(abspath(__file__)))) INPUT_ROOT = join(PROJECT_ROOT, 'input') SMS_FILE = join(INPUT_ROOT, 'sms', 'SMSSpamCollection') df = pd.read_csv(SMS_FILE, delimiter='\t', header=None) x = df[1].values y = df[0].values x_train_raw, x_test_raw, y_train, y_test = train_test_split(x,y) vectorizer = TfidfVectorizer() x_train = vectorizer.fit_transform(x_train_raw) x_test = vectorizer.transform(x_test_raw) lb = LabelBinarizer() y_train_binarized = lb.fit_transform(y_train) y_test_binarized = lb.transform(y_test) classifier = LogisticRegression() classifier.fit(x_train, y_train_binarized) predictions = classifier.predict(x_test) precisions = cross_val_score(classifier, x_train, y_train_binarized, cv=5, scoring='precision') print('Precisions from cross_val_score', precisions) report = classification_report(y_test_binarized, predictions,\ target_names=['ham', 'spam'], labels=lb.transform(['ham','spam']).reshape(-1)) print('Report from classification_report\n', report)
1,401
494
import numpy as np from lane_pixel_finder import find_lane_pixels ''' Calculates the curvature of polynomial functions in meters. ''' # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension def measure_curvature_real_with_pixels(img_shape, x, y): # Generate x and y values for plotting ploty = np.linspace(0, img_shape[0]-1, img_shape[0]) # Fit a second order polynomial to each using `np.polyfit` fit_cr = np.polyfit(y*ym_per_pix, x*xm_per_pix, 2) # Define y-value where we want radius of curvature # We'll choose the maximum y-value, corresponding to the bottom of the image y_eval = np.max(ploty) ##### calculation of R_curve (radius of curvature) ##### curverad = ((1 + (2*fit_cr[0]*y_eval*ym_per_pix + fit_cr[1])**2)**1.5) / np.absolute(2*fit_cr[0]) return curverad, fit_cr def measure_offset_real(img_shape, left_fit, right_fit): y = ym_per_pix * img_shape[0] l_fitValue = left_fit[0]* y**2 + left_fit[1]*y + left_fit[2] r_fit_Value = right_fit[0]*y**2 + right_fit[1]*y + right_fit[2] lane_center_pos = (l_fitValue + r_fit_Value) /2 return lane_center_pos - img_shape[1] / 2 * xm_per_pix
1,289
504
#----------------------------------------------------------------------------- # Name: Catching Exceptions (try-except.py) # Purpose: To provide example of a simple input loop using try-catch # # Author: Mr. Brooks # Created: 01-Oct-2020 # Updated: 01-March-2021 #----------------------------------------------------------------------------- while True: #Start an infinite loop value = input('Enter a number between -100 and 100: ') #Get a value from the user try: value = int(value) #Convert the value to an int except Exception as err: print(f'Something went wrong: {err}') #You should probably add a nicer error message else: #No exception was thrown, so break out of the infinite loop break print (value)
816
219
# coding: utf-8 r"""Tabby rear suspension assembly""" from car_assemblies import make_rear_suspension_assembly from osvcad.view import view_assembly, view_assembly_graph assembly = make_rear_suspension_assembly() if __name__ == "__main__": view_assembly(assembly) view_assembly_graph(assembly)
306
104
############################ # This example shows how to run pygosolnp with Truncated Normal distribution using Numpy and Scipy ############################ from typing import List, Optional # Numpy random has the PCG64 generator which according to some research is better than Mersenne Twister from numpy.random import Generator, PCG64 # Note that this script depends on scipy, which is not a requirement for pygosolnp from scipy.stats import truncnorm import pygosolnp # The Sampling class is an abstract class that can be inherited and customized as you please class TruncatedNormalSampling(pygosolnp.sampling.Sampling): def __init__(self, parameter_lower_bounds: List[float], parameter_upper_bounds: List[float], seed: Optional[int]): self.__generator = Generator(PCG64(seed)) self.__parameter_lower_bounds = parameter_lower_bounds self.__parameter_upper_bounds = parameter_upper_bounds def generate_sample(self, sample_size: int) -> List[float]: # This function returns random starting values for one sample return truncnorm.rvs(a=self.__parameter_lower_bounds, b=self.__parameter_upper_bounds, size=sample_size, random_state=self.__generator) # The Permutation Function has unique solution f(x) = 0 when x_i = i def permutation_function(data): n = 4 b = 0.5 result1 = 0 for index1 in range(1, n + 1): result2 = 0 for index2 in range(1, n + 1): result2 += ((pow(index2, index1) + b) * (pow(data[index2 - 1] / index2, index1) - 1)) result1 += pow(result2, 2) return result1 parameter_lower_bounds = [-4.0] * 4 parameter_upper_bounds = [4.0] * 4 if __name__ == '__main__': # Instantiate sampling object sampling = TruncatedNormalSampling( parameter_lower_bounds=parameter_lower_bounds, parameter_upper_bounds=parameter_upper_bounds, seed=99) # Note that the seed variable to pygosolnp.solve is ignored due to the custom sampling results = pygosolnp.solve( obj_func=permutation_function, par_lower_limit=parameter_lower_bounds, par_upper_limit=parameter_upper_bounds, number_of_restarts=6, number_of_simulations=20000, pysolnp_max_major_iter=25, pysolnp_tolerance=1E-9, start_guess_sampling=sampling) print(results.best_solution) # Best solution: [2.651591117309446, 1.7843343303461394, 3.8557508243271172, 2.601788248290573] # Objective function value: 101.48726054338877 # Not very good, the truncated normal function has generated samples that are mostly close to 0 # This is not very good for the permutation function
2,791
886
from .utils import GenomeFile, split_locus_tag class CustomAnnotationFile(GenomeFile): def __init__(self, file: str, original_path: str = None, custom_annotation_type: str = None): if custom_annotation_type: self.custom_annotation_type = custom_annotation_type else: self.custom_annotation_type = file.rsplit('.', 1)[-1] super().__init__(file=file, original_path=original_path) def rename(self, out: str, new_locus_tag_prefix: str, old_locus_tag_prefix: str = None, validate: bool = False) -> None: old_locus_tag_prefix = self._pre_rename_check(out, new_locus_tag_prefix, old_locus_tag_prefix) with open(self.path) as in_f: content = in_f.readlines() def rename_line(line: str): assert line.startswith(old_locus_tag_prefix), f'custom_annotations_file line does not contain old_locus_tag_prefix!' \ f'{old_locus_tag_prefix=}, {line=}, {self.path=}' return line.replace(old_locus_tag_prefix, new_locus_tag_prefix, 1) content = [rename_line(line) for line in content] with open(out, 'w') as out_f: out_f.writelines(content) self.path = out if validate: self.validate_locus_tags(locus_tag_prefix=new_locus_tag_prefix) def detect_locus_tag_prefix(self) -> str: with open(self.path) as f: line = f.readline() locus_tag = line.split('\t', 1)[0] locus_tag_prefix, gene_id = split_locus_tag(locus_tag) assert gene_id.isdigit(), f'locus_tag in {self.path=} is malformed. expected: {locus_tag_prefix}_[0-9]+ reality: {locus_tag}' return locus_tag_prefix def validate_locus_tags(self, locus_tag_prefix: str = None): if locus_tag_prefix is None: locus_tag_prefix = self.detect_locus_tag_prefix() with open(self.path) as f: for line in f: locus_tag = line.split('\t')[0] real_locus_tag_prefix, gene_id = split_locus_tag(locus_tag) assert real_locus_tag_prefix == locus_tag_prefix, \ f'locus_tag_prefix in {self.path=} does not match. expected: {locus_tag_prefix} reality: {real_locus_tag_prefix}' assert gene_id.isdigit(), f'locus_tag in {self.path=} is malformed. expected: {locus_tag_prefix}_[0-9]+ reality: {locus_tag}' def rename_custom_annotations(file: str, out: str, new_locus_tag_prefix: str, old_locus_tag_prefix: str = None, validate: bool = False): """ Change the locus tags in a custom annotations file :param file: input file :param out: output file :param new_locus_tag_prefix: desired locus tag :param old_locus_tag_prefix: locus tag to replace :param validate: if true, perform sanity check """ CustomAnnotationFile( file=file ).rename( out=out, new_locus_tag_prefix=new_locus_tag_prefix, old_locus_tag_prefix=old_locus_tag_prefix, validate=validate ) def main(): import fire fire.Fire(rename_custom_annotations) if __name__ == '__main__': main()
3,197
1,052
import argparse, joblib, csv, sys, os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import pandas as pd from mpl_toolkits.mplot3d import Axes3D from yellowbrick.text import TSNEVisualizer from sklearn.cluster import KMeans from sklearn.svm import SVC, LinearSVC from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix, f1_score from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, learning_curve from sklearn.feature_extraction.text import TfidfVectorizer ''' SVM classifier ''' # GLOBALS # Paths dir_path = os.path.dirname(os.path.realpath(__file__)) data_path = dir_path + '/TrainingData/training_data_all.csv' test_data_path = dir_path + '/TrainingData/HypothesisData.csv' model_path = dir_path + '/Model/svm_pipeline.joblib' stop_words_path = dir_path + '/TrainingData/stop_words_da.txt' # Rest # Train our SVM model def train_model(X, y, auto_split=False): # Create data processing and classifier pipeline svm_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(ngram_range=(1,10), analyzer='char_wb', stop_words=load_stop_words(), use_idf=False, smooth_idf=True, sublinear_tf=False )), ('svm', LinearSVC(C=3)) ]) # Parameters for Grid Search. This is used for finding the best values for processing and classifying parameters = {#'tfidf__stop_words':(load_stop_words(), None), # 'tfidf__smooth_idf':(True, False), # 'tfidf__sublinear_tf':(True, False), } out = open('svm_f1score.txt', 'w+') X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) skf = StratifiedKFold(4, True) if auto_split is True: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) clf = GridSearchCV(svm_pipeline, parameters, cv=skf.split(X_train, y_train), verbose=2, return_train_score=True, n_jobs=-1) clf.fit(X_train, y_train) clf = clf.best_estimator_ cm = confusion_matrix(y_test, clf.predict(X_test)) plt.figure() plot_confusion_matrix(cm) y_pred = clf.predict(X_test) f_score = f1_score(y_true=y_test, y_pred=y_pred, average='weighted') score = clf.score(X_test, y_test) out.write('{}, {}\n'.format(score, f_score)) else: clf = GridSearchCV(svm_pipeline, parameters, cv=skf.split(X, y), verbose=2, return_train_score=True, n_jobs=-1) X_test, y_test = load_test_dataset(squish_classes=True) clf.fit(X, y) clf = clf.best_estimator_ cm = confusion_matrix(y_test, clf.predict(X_test)) plot_confusion_matrix(cm) svm_score = clf.score(X_test, y_test) y_pred = clf.predict(X_test) f_score = f1_score(y_true=y_test, y_pred=y_pred, average='weighted') out.write('{}, {}\n'.format(svm_score, f_score)) print(cm) print('SVM Accuracy: {}'.format(round(svm_score*100, 4))) print('SVM F1 Score: {}'.format(round(f_score*100, 4))) joblib.dump(clf, model_path) return clf def load_dataset(encoding='utf8', squish_classes=True): ''' Loads training data and splits it into test and train sets Parameters ----------- encoding: The encoding of the file loaded. Default is UTF-8 Returns ------- X: The sentences, y: The labels ''' csv_reader = csv.reader(open(data_path, encoding=encoding)) X, y = [], [] # Saving comments and likes in seperate lists for row in csv_reader: X.append(row[1]) if squish_classes: if int(row[0]) < 0: y.append(-1) elif int(row[0]) > 0: y.append(1) else: y.append(0) else: y.append(row[0]) y = np.asarray(y) X = np.asarray(X) return X, y def load_test_dataset(encoding='utf-8-sig', squish_classes=True): ''' Loads training data and splits it into test and train sets Parameters ----------- encoding: The encoding of the file loaded. Default is UTF-8 Returns ------- X: The sentences, y: The labels ''' csv_reader = csv.reader(open(test_data_path, encoding=encoding)) X, y = [], [] # Saving comments and likes in seperate lists for row in csv_reader: X.append(row[1]) if squish_classes: if int(row[0]) < 0: y.append(-1) elif int(row[0]) > 0: y.append(1) else: y.append(0) else: y.append(row[0]) y = np.asarray(y) X = np.asarray(X) return X, y # Get list of stop words def load_stop_words(): stop_words = [] stop_words_list = open(stop_words_path, 'r') for word in stop_words_list.readlines(): stop_words.append(word.replace('\n', '')) return stop_words # <----------------------> # <- PLOTTING FUNCTIONS -> # <----------------------> def plot_data_2d(X_transformed, y): # PCA data2D = PCA(n_components=3).fit_transform(X_transformed.todense()) # Plot the datapoints with different colors depending on label for i in range(0, len(data2D)): if int(y[i]) < 0: plt.plot(data2D[i, 0], data2D[i, 1], "yo") elif int(y[i]) == 0: plt.plot(data2D[i, 0], data2D[i, 1], "bo") else: plt.plot(data2D[i, 0], data2D[i, 1], "co") # Labels for the plot negative_plt = mpatches.Patch(color='yellow', label='Negative') neutral_plt = mpatches.Patch(color='blue', label='Neutral') positive_plt = mpatches.Patch(color='cyan', label='Positive') plt.legend(handles=[positive_plt, neutral_plt, negative_plt]) plt.show() def plot_data_3d(X_transformed, y): ''' Loads training data and splits it into test and train sets Parameters ----------- X_transformed: The corpus transformed to a feature space, y: The labels ''' fig = plt.figure() ax = fig.add_subplot(111, projection='3d') data3d = PCA(n_components=3).fit_transform(X_transformed.todense()) # data3d = TSNE(n_components=3).fit_transform(X_transformed.todense()) # neg_xs, neg_ys, neg_zs = [], [], [] neu_xs, neu_ys, neu_zs = [], [], [] pos_xs, pos_ys, pos_zs = [], [], [] for i in range(0, len(y)): if y[i] < 0: neg_xs.append(data3d[i, 0]) neg_ys.append(data3d[i, 1]) neg_zs.append(data3d[i, 2]) if y[i] == 0: neu_xs.append(data3d[i, 0]) neu_ys.append(data3d[i, 1]) neu_zs.append(data3d[i, 2]) else: pos_xs.append(data3d[i, 0]) pos_ys.append(data3d[i, 1]) pos_zs.append(data3d[i, 2]) ax.scatter(neg_xs, neg_ys, neg_zs, c='b') ax.scatter(neu_xs, neu_ys, neu_zs, c='r') ax.scatter(pos_xs, pos_ys, pos_zs, c='g') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') def plot_confusion_matrix(cm, title='SVM Confusion matrix', cmap=plt.get_cmap('Blues')): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(3) plt.xticks(tick_marks, [-1, 0, 1], rotation=45) plt.yticks(tick_marks, [-1, 0, 1]) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() # From https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=None, train_sizes=np.linspace(.1, 1.0, 10)): """ Generate a simple plot of the test and training learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. title : string Title for the chart. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues plotted. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`StratifiedKFold` used. If the estimator is not a classifier or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validators that can be used here. n_jobs : int or None, optional (default=None) Number of jobs to run in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. train_sizes : array-like, shape (n_ticks,), dtype float or int Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class. (default: np.linspace(0.1, 1.0, 5)) """ plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=8, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.legend(loc="best") return plt # <----------------------> # <- SCRIPT STARTS HERE -> # <----------------------> # Train model first time X, y = load_dataset(squish_classes=True) pipeline = train_model(X, y, auto_split=False) X_transformed = pipeline.named_steps['tfidf'].transform(X) # tsne = TSNEVisualizer() # tsne.fit(X_transformed, y) # tsne.poof()
11,757
4,051
from yaml.composer import Composer as YamlComposer, ComposerError class Composer(YamlComposer): def compose_document(self): # Drop the DOCUMENT-START event. self.get_event() # UNITY: used to store data after the anchor self.extra_anchor_data = {} # Compose the root node. node = self.compose_node(None, None) # Drop the DOCUMENT-END event. self.get_event() # UNITY: prevent reset anchors after document end so we can access them on constructors # self.anchors = {} return node def get_anchor_from_node(self, node): for k, v in self.anchors.items(): if node == v: return k raise ComposerError("Expected anchor to be present for node") def get_extra_anchor_data_from_node(self, anchor): if anchor in self.extra_anchor_data: return self.extra_anchor_data[anchor] return ''
951
278
import platform from setuptools import Extension import numpy from Cython.Build import cythonize compile_args = [] link_args = [] pf = platform.system() if pf == "Windows": # for MSVC compile_args = ["/std:c++14", "/DNOMINMAX", "/O2", "/openmp"] elif pf == "Darwin": # for clang compile_args = ["-std=c++14", "-O2", "-march=native", "-Xpreprocessor", "-fopenmp"] link_args = ["-lomp"] elif pf == "Linux": # for gcc compile_args = ["-std=c++14", "-Ofast", "-march=native", "-fopenmp"] link_args = ["-fopenmp"] ext_modules = [ Extension( name="ubo2014_cy", sources=["btf_extractor/ubo2014.pyx"], include_dirs=[numpy.get_include(), "btf_extractor/c_ext"], define_macros=[("BTF_IMPLEMENTATION", "1"), ("NPY_NO_DEPRECATED_API", "1")], extra_compile_args=compile_args, extra_link_args=link_args, language="c++", ) ] def build(setup_kwargs): """ This function is mandatory in order to build the extensions. """ setup_kwargs.update( {"ext_modules": cythonize(ext_modules)} ) return setup_kwargs if __name__ == "__main__": build({})
1,164
432
import logging from django.views import View from .models import Users, Tokens from libs.response_extra import response_failure, response_success, user_does_not_exists, view_exception from libs.tool_decorator import cvb_params from .decorator import cvb_token_check log = logging.getLogger(__name__) class LoginView(View): @cvb_params(POST_BODY=["account", "password"]) def post(self, request, body_params): try: request_body = request.headers recv_token = request_body["Token"] login_type = request_body["platform"] if "platform" in request_body else 1 # 1是网页端 account = body_params['account'] password = body_params['password'] if recv_token == "none": # 不存在token才登录,“none”是前端兼容IE浏览器 user_m = Users.objects.filter(account=account).first() if user_m: if user_m.permission: # 验证是否允许登录 if user_m.authentication(password): # 验证密码 token = Tokens.objects.token_create(user_m.id, login_type) data = { "account": account, "userType": user_m.user_type, "name": user_m.name, "portrait": user_m.portrait, "token": token } return response_success(msg="登录成功", code=0, data=data) return response_failure(msg='密码错误,请重新输入', code=6) return response_failure(msg='用户被禁止登录', code=7) return response_failure(msg="账号不存在", code=5) return response_failure(msg="携带token登录", code=4) except BaseException as err: log.error(f"登录接口异常 {err}") class LogoutView(View): @cvb_token_check def get(self, request, user_id): request_body = request.headers recv_token = request_body["Token"] token_m = Tokens.objects.filter(user_id=user_id, token=recv_token).first() if token_m: token_m.delete() return response_success(msg="退出成功") class RegisterView(View): @cvb_params(POST_BODY=['userType', 'name', 'account', 'password', 'email', 'gender', 'portrait']) def post(self, request, body_params): Users.objects.user_create( name=body_params["name"], account=body_params["account"], password=body_params["password"], gender=body_params["gender"], email=body_params["email"], portrait=body_params["portrait"], user_type=body_params["userType"], ) return response_success(msg="添加用户成功") class ModifyPasswordView(View): @cvb_token_check @cvb_params(POST_BODY=["oldPassword", "newPassword"]) def post(self, request, user_id, params): """ { "oldPassword":"123456", "newPassword":"1q2w3e4r" } """ try: user = Users.objects.filter(id=user_id).first() if user: if user.authentication(params["oldPassword"]): user.password = user.encryption(params["newPassword"]) user.save() return response_success(msg="密码修改成功", code=0) return response_failure(msg='旧密码错误,请重新输入', code=6) return user_does_not_exists() except BaseException as err: log.error(err) return view_exception() """ 注册: { "userType": 2, "name": "rocky_admin", "account": "13002111111", "password": "1q2w3e4r", "email":"rocky_admin@163com", "gender": 1, "portrait": "www.baidu.com" } 登录: { "account": "13002111111", "password": "1q2w3e4r" } """
3,802
1,233
from compas_plotters.artists import Artist from matplotlib.patches import Circle as CirclePatch # from matplotlib.transforms import ScaledTranslation __all__ = ['CircleArtist'] class CircleArtist(Artist): """""" zorder = 1000 def __init__(self, circle, linewidth=1.0, linestyle='solid', facecolor=(1.0, 1.0, 1.0), edgecolor=(0, 0, 0), fill=True, alpha=1.0): super(CircleArtist, self).__init__(circle) self._mpl_circle = None self.circle = circle self.linewidth = linewidth self.linestyle = linestyle self.facecolor = facecolor self.edgecolor = edgecolor self.fill = fill self.alpha = alpha @property def data(self): points = [ self.circle.center[:2], self.circle.center[:2], self.circle.center[:2], self.circle.center[:2] ] points[0][0] -= self.circle.radius points[1][0] += self.circle.radius points[2][1] -= self.circle.radius points[3][1] += self.circle.radius return points def update_data(self): self.plotter.axes.update_datalim(self.data) def draw(self): circle = CirclePatch( self.circle.center[:2], linewidth=self.linewidth, linestyle=self.linestyle, radius=self.circle.radius, facecolor=self.facecolor, edgecolor=self.edgecolor, fill=self.fill, zorder=self.zorder ) self._mpl_circle = self.plotter.axes.add_artist(circle) self.update_data() def redraw(self): self._mpl_circle.center = self.circle.center[:2] self._mpl_circle.set_radius(self.circle.radius) self._mpl_circle.set_edgecolor(self.edgecolor) self._mpl_circle.set_facecolor(self.facecolor) self.update_data()
1,871
596
# -*- coding: utf-8 -*- """ Created on Tue Sep 18 21:06:14 2018 Taken from Data Structures and Algorithms using Python """ class SortedPriorityQueue(PriorityQueueBase): def __init__(self): self._data = PositionalList() def __len__(self): return len(self._data) def add(self,key,value): newest = self._Item(key,value) walk = self._data.last() while walk is not None and newest < walk.element(): walk = self._data.before(walk) if walk is None: self._data.add_first(newest) else: self._data.add_after(walk,newest) def min(self): if self.is_empty(): raise Empty('Priority Queue is empty') p = self._data.first() item = p.element() return (item._key,item._value) def remove_min(self): if self.is_empty(): raise Empty('Priority queue is empty') item =self._data.delete(self._data.first()) return (item._key, item._value)
1,044
329
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from f5.utils import iapp_parser as ip import pytest good_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' brace_in_quote_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for "" the template } implementation { # TMSH"{}{{}}}}}""{{{{}}"implementation code } presentation { # APL"{}{}{{{{{{" presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' no_desc_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules { ltm } }''' empty_rm_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules { } }''' whitespace_rm_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules {} }''' none_rm_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules none }''' no_open_brace_templ = '''sys application template no_open_brace_templ { actions { definition { html-help # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl {security role} run-as <user context> } } description <template description> partition <partition name> }''' no_close_brace_templ = '''sys application template no_close_brace_template { actions { definition { html-help { # HTML Help for the template # Missing closing braces implementation { # TMSH implementation code ''' no_pres_templ = '''sys application template no_pres_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } role-acl {<security role>} run-as <user context> } } description <template description> partition <partition name> }''' no_name_templ = '''sys application template { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } run-as <user context> } } description <template description> partition <partition name> }''' bad_name_templ = '''sys application template bad#updown { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } role-acl {<security role>} run-as <user context> } } description <template description> partition <partition name> }''' name_brace_templ = '''sys application template name_next_to_brace{ actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } role-acl {security role} run-as <user context> } } description <template description> partition <partition name> }''' good_attr_templ = '''sys application template good_templ { actions { definition { html-help {} implementation {} presentation {} } } description <template description> partition just_a_partition name }''' no_help_templ = '''sys application template good_templ { actions { definition { implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm asm } }''' dot_name_templ = '''sys application template good.dot.templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' dot_hyphen_name_templ = '''sys application template good.-dot-hyphen.-templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' good_templ_dict = { u'name': u'good_templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } brace_in_quote_templ_dict = { u'name': u'good_templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for "" the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH"{}{{}}}}}""{{{{}}"implementation code', u'presentation': u'# APL"{}{}{{{{{{" presentation language' } } } no_help_templ_dict = { u'name': u'good_templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm', u'asm'], 'actions': { 'definition': { u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } none_rm_templ_dict = { u'name': u'good_templ', u'partition': u'<partition name>', u'requiresModules': u'none', 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } dot_name_templ_dict = { u'name': u'good.dot.templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } dot_hyphen_name_templ_dict = { u'name': u'good.-dot-hyphen.-templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } @pytest.fixture def TemplateSectionSetup(request): def tearDown(): prsr.template_sections.remove('notfound') request.addfinalizer(tearDown) prsr = ip.IappParser(good_templ) prsr.template_sections.append('notfound') return prsr def test__init__(): prsr = ip.IappParser(good_templ) assert prsr.template_str == good_templ def test__init__error(): prsr = None with pytest.raises(ip.EmptyTemplateException) as EmptyTemplateExceptInfo: prsr = ip.IappParser('') assert EmptyTemplateExceptInfo.value.message == \ 'Template empty or None value.' assert prsr is None def test_get_section_end_index(): prsr = ip.IappParser(good_templ) impl_start = prsr._get_section_start_index(u'implementation') impl_end = prsr._get_section_end_index(u'implementation', impl_start) templ_impl = unicode('''{ # TMSH implementation code }''') assert good_templ[impl_start:impl_end+1] == templ_impl def test_get_section_start_index_no_open_brace_error(): prsr = ip.IappParser(no_open_brace_templ) with pytest.raises(ip.NonextantSectionException) as \ NonextantSectionExceptInfo: prsr._get_section_start_index(u'html-help') assert NonextantSectionExceptInfo.value.message == \ 'Section html-help not found in template' def test_get_section_end_no_close_brace_error(): prsr = ip.IappParser(no_close_brace_templ) with pytest.raises(ip.CurlyBraceMismatchException) as \ CurlyBraceMismatchExceptInfo: help_start = prsr._get_section_start_index(u'html-help') prsr._get_section_end_index(u'html_help', help_start) assert CurlyBraceMismatchExceptInfo.value.message == \ 'Curly braces mismatch in section html_help.' def test_get_template_name(): prsr = ip.IappParser(good_templ) assert prsr._get_template_name() == u'good_templ' def test_get_template_name_next_to_brace(): prsr = ip.IappParser(name_brace_templ) assert prsr._get_template_name() == u'name_next_to_brace' def test_get_template_name_error(): prsr = ip.IappParser(no_name_templ) with pytest.raises(ip.NonextantTemplateNameException) as \ NonextantTemplateNameExceptInfo: prsr._get_template_name() assert NonextantTemplateNameExceptInfo.value.message == \ 'Template name not found.' def test_get_template_name_bad_name_error(): prsr = ip.IappParser(bad_name_templ) with pytest.raises(ip.NonextantTemplateNameException) as \ NonextantTemplateNameExceptInfo: prsr._get_template_name() assert NonextantTemplateNameExceptInfo.value.message == \ 'Template name not found.' def test_get_template_name_with_dot(): prsr = ip.IappParser(dot_name_templ) assert prsr.parse_template() == dot_name_templ_dict def test_get_template_name_with_dot_hyphen(): prsr = ip.IappParser(dot_hyphen_name_templ) assert prsr.parse_template() == dot_hyphen_name_templ_dict def test_parse_template(): prsr = ip.IappParser(good_templ) assert prsr.parse_template() == good_templ_dict def test_parse_template_brace_in_quote(): prsr = ip.IappParser(brace_in_quote_templ) assert prsr.parse_template() == brace_in_quote_templ_dict def test_parse_template_no_section_found(TemplateSectionSetup): with pytest.raises(ip.NonextantSectionException) as \ NonextantSectionExceptInfo: TemplateSectionSetup.parse_template() assert 'notfound' in TemplateSectionSetup.template_sections assert 'Section notfound not found in template' in \ NonextantSectionExceptInfo.value.message def test_parse_template_no_section_found_not_required(): prsr = ip.IappParser(no_help_templ) templ_dict = prsr.parse_template() assert templ_dict == no_help_templ_dict def test_get_template_attr(): prsr = ip.IappParser(good_attr_templ) attr = prsr._get_template_attr(u'partition') assert attr == u'just_a_partition name' def test_get_template_attr_attr_not_exists(): prsr = ip.IappParser(good_attr_templ) attr = prsr._get_template_attr(u'bad_attr') assert attr is None def test_attr_no_description(): prsr = ip.IappParser(no_desc_templ) templ_dict = prsr.parse_template() assert 'description' not in templ_dict def test_attr_empty_rm_error(): prsr = ip.IappParser(empty_rm_templ) with pytest.raises(ip.MalformedTCLListException) as ex: prsr.parse_template() assert 'requires-modules' in ex.value.message def test_attr_whitespace_rm_error(): prsr = ip.IappParser(whitespace_rm_templ) with pytest.raises(ip.MalformedTCLListException) as ex: prsr.parse_template() assert 'TCL list for "requires-modules" is malformed. If no elements are '\ 'needed "none" should be used without curly braces.' in \ ex.value.message def test_attr_none_rm(): prsr = ip.IappParser(none_rm_templ) templ_dict = prsr.parse_template() assert templ_dict == none_rm_templ_dict
14,576
4,555
#!/usr/env python import pprocess # parallel computing module import os # os utilitites import time # keep track of time import astropy.io.fits as fits # FITS manipulating library import matplotlib.pyplot as plt import numpy as np # numeric python for array manipulation import myscitools # my personal tools #input file informations and variables atributions---------------------- inptname = str(raw_input('Input file (with extension): ')) outptname = os.path.splitext(inptname)[0]+'_z2n_output.fits' inpt = fits.open(inptname) times = inpt[1].data.field('TIME') inpt.close() interval = float(times.max()-times.min()) startf = 1.0/interval print "The start frequency is: ", startf query = str(raw_input("Change the start frequency? (y/n): ")) if (query == 'y') or (query == 'Y'): startf = float(raw_input('Enter the start frequency: ')) else: pass endf = float(raw_input('Enter the last frequency: ')) over = float(raw_input('Enter oversample factor: ')) fact = 1.0/over deltaf = fact/interval print "The frequency step will be: ", deltaf query2 = str(raw_input('Change frequency step? (y/n): ')) if (query2 == 'y') or (query2 == 'Y'): deltaf = float(raw_input('Enter the frequency interval: ')) else: pass freqs = np.arange(startf, endf, deltaf) #harm = int(raw_input('The Harmonic to be considered:')) harm = 1 #----------------- The parallelism starts here ------------------------ nproc = int(raw_input('Enter the number of processor to use: ')) if nproc < 1: nproc = 1 # default number of cpus = 1 freqlist = np.array_split(freqs, nproc) results = pprocess.Map(limit=nproc, reuse=1) parallel_z2n = results.manage(pprocess.MakeReusable(myscitools.z2n)) print "\n Calculating with ", nproc, " processor(s)\n" tic = time.time() [parallel_z2n(somefreqs, times, harm) for somefreqs in freqlist] z2n = [] for result in results: for value in result: z2n.append(value) print 'time = {0}'.format(time.time() - tic) plt.plot(freqs, z2n) plt.xlabel('Frequency (Hz)') plt.ylabel('Z2n Power') plt.title(inptname) plt.show() plt.plot(freqs, z2n) plt.savefig('z2n.png') #create and write the output.fits file col1 = [freqs, 'frequency', 'E', 'Hz'] col2 = [z2n, 'z2nPower', 'E', 'arbitrary'] myscitools.makefits(outptname, col1, col2)
2,284
833
import requests import urllib3 from urllib3 import HTTPConnectionPool class HttpsClient: def __init__(self): pass @staticmethod def get(_url, _query_string={}, _header=None): urllib3.disable_warnings() _resp = requests.get(_url, _query_string, headers=_header, verify=False) return _resp.text @staticmethod def post(_url, _body={}, _header=None): urllib3.disable_warnings() _resp = requests.post(_url, _body, headers=_header, verify=False) return _resp.text if __name__ == '__main__': print(HttpsClient.get('http://127.0.0.1:5000/test'))
625
212
import os import sys from dataclasses import field from typing import List, Optional, Set, cast from unittest import skipUnless from aio_rom import Model from aio_rom.attributes import RedisModelSet if sys.version_info >= (3, 8): from unittest.async_case import IsolatedAsyncioTestCase as TestCase ASYNCTEST = False else: from asynctest import TestCase ASYNCTEST = True from aio_rom.fields import Metadata from aio_rom.session import redis_pool class Bar(Model, unsafe_hash=True): field1: int field2: str field3: List[int] = field(metadata=Metadata(eager=True), hash=False) field4: int = 3 class Foo(Model, unsafe_hash=True): eager_bars: List[Bar] = field(metadata=Metadata(eager=True), hash=False) lazy_bars: Set[Bar] = field(compare=False, metadata=Metadata(cascade=True)) f1: Optional[str] = None class FooBar(Model): foos: Set[Foo] = field(metadata=Metadata(cascade=True, eager=True)) @skipUnless(os.environ.get("CI"), "Redis CI test only") class RedisIntegrationTestCase(TestCase): async def asyncSetUp(self) -> None: self.bar = Bar(1, 123, "value", [1, 2, 3]) async def asyncTearDown(self) -> None: await Foo.delete_all() await Bar.delete_all() await FooBar.delete_all() if ASYNCTEST: tearDown = asyncTearDown # type: ignore[assignment] setUp = asyncSetUp # type: ignore[assignment] async def test_save(self) -> None: await self.bar.save() async with redis_pool() as redis: field1 = await redis.hget("bar:1", "field1") field2 = await redis.hget("bar:1", "field2") field3 = await redis.hget("bar:1", "field3") field3_value = await redis.lrange("bar:1:field3", 0, -1) assert "123" == field1 assert "value" == field2 assert "bar:1:field3" == field3 assert ["1", "2", "3"] == field3_value async def test_get(self) -> None: await self.bar.save() bar = await Bar.get(1) assert self.bar == bar async def test_get_with_references(self) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) await foo.save() gotten_foo = await Foo.get(123) assert foo == gotten_foo await cast(RedisModelSet[Bar], gotten_foo.lazy_bars).load() for bar in gotten_foo.lazy_bars: assert bar in foo.lazy_bars assert len(foo.lazy_bars) == len(gotten_foo.lazy_bars) async def _test_collection_references(self, test_cascade: bool = False) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) if not test_cascade: await foo.save() foobar = FooBar(321, {foo}) await foobar.save() gotten_foobar = await FooBar.get(321) assert foobar == gotten_foobar assert {foo} == gotten_foobar.foos for gotten_foo in gotten_foobar.foos: assert 1 == len(gotten_foo.eager_bars) await cast(RedisModelSet[Bar], gotten_foo.lazy_bars).load() for bar in gotten_foo.lazy_bars: assert bar in foo.lazy_bars async def test_collections(self) -> None: await self._test_collection_references() async def test_collection_cascades_references(self) -> None: await self._test_collection_references(test_cascade=True) async def test_update_collection_references(self) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) foobar = FooBar(321, {foo}) await foobar.save() refreshed = await foobar.refresh() foo2 = Foo(222, [], set()) refreshed.foos.add(foo2) await refreshed.save() gotten_foobar = await FooBar.get(321) assert refreshed == gotten_foobar assert {foo, foo2} == gotten_foobar.foos async def test_update(self) -> None: await self.bar.save() await self.bar.update(field2="updated") async with redis_pool() as redis: field2 = await redis.hget("bar:1", "field2") assert "updated" == field2 bar = await Bar.get(1) assert "updated" == bar.field2 async def test_update_reference(self) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) await foo.save() bar2 = Bar(2, 123, "otherbar", [1, 2, 3, 4]) await bar2.save() foo = await foo.update(lazy_bars={bar2}) async with redis_pool() as redis: lazy_bars = await redis.smembers("foo:123:lazy_bars") assert ["2"] == lazy_bars foo = await foo.update(eager_bars=[bar2]) async with redis_pool() as redis: eager_bars = await redis.lrange("foo:123:eager_bars", 0, -1) assert ["2"] == eager_bars gotten_foo = await Foo.get(123) assert foo == gotten_foo async def test_save_again_overrides_previous(self) -> None: await self.bar.save() bar = await Bar.get(1) bar.field2 = "updated" await bar.save() async with redis_pool() as redis: field2 = await redis.hget("bar:1", "field2") assert "updated" == field2 async def test_delete(self) -> None: await self.bar.save() async with redis_pool() as redis: assert await redis.exists("bar:1") await self.bar.delete() assert not await redis.exists("bar:1") async def test_delete_all(self) -> None: await self.bar.save() async with redis_pool() as redis: await Bar.delete_all() assert not await redis.keys("bar*") async def test_lazy_collection_cascade(self) -> None: foo = Foo(123, [self.bar], {self.bar}) await foo.save() foo = await Foo.get(123) other_bar = Bar(2, 124, "value2", []) foo.lazy_bars.add(other_bar) await foo.save() gotten_foo = await Foo.get(123) assert foo == gotten_foo await cast(RedisModelSet[Bar], gotten_foo.lazy_bars).load() await cast(RedisModelSet[Bar], foo.lazy_bars).load() assert 2 == len(foo.lazy_bars) == len(gotten_foo.lazy_bars)
6,217
2,077
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( str ) : n = len ( str ) C = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] P = [ [ False for i in range ( n ) ] for i in range ( n ) ] j = 0 k = 0 L = 0 for i in range ( n ) : P [ i ] [ i ] = True ; C [ i ] [ i ] = 0 ; for L in range ( 2 , n + 1 ) : for i in range ( n - L + 1 ) : j = i + L - 1 if L == 2 : P [ i ] [ j ] = ( str [ i ] == str [ j ] ) else : P [ i ] [ j ] = ( ( str [ i ] == str [ j ] ) and P [ i + 1 ] [ j - 1 ] ) if P [ i ] [ j ] == True : C [ i ] [ j ] = 0 else : C [ i ] [ j ] = 100000000 for k in range ( i , j ) : C [ i ] [ j ] = min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) return C [ 0 ] [ n - 1 ] #TOFILL if __name__ == '__main__': param = [ ('ydYdV',), ('4446057',), ('0111',), ('keEj',), ('642861576557',), ('11111000101',), ('ram',), ('09773261',), ('1',), ('AVBEKClFdj',) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
1,514
611
from .utils import return_response, api_get_request class StaffMixin(): TIMETAP_API_STAFF = '/staff' api_get_request = api_get_request @return_response def get_staff(self): return self.api_get_request(f'{self.TIMETAP_API_STAFF}') @return_response def get_staff_by_professionalId(self, professionalId: int): if not professionalId: raise ValueError('professionalId has not been set') return self.api_get_request(f'{self.TIMETAP_API_STAFF}/{professionalId}') @return_response def get_service_staff(self, professionalId: int): if not professionalId: raise ValueError('professionalId has not been set') return self.api_get_request(f'{self.TIMETAP_API_STAFF}/{professionalId}/serviceStaff')
787
260
from django.apps import AppConfig class TreatmentConfig(AppConfig): name = 'goutdotcom.treatment'
104
35
# Space: O(1) # Time: O(logn) class Solution: def search(self, nums, target): length = len(nums) if length == 0: return -1 if length == 1: return 0 if nums[0] == target else -1 # First, find out the actual end point of sorted array left, right = 0, length - 1 while left + 1 < right: mid = (left + right) // 2 if nums[mid] > nums[right]: left = mid else: right = mid actual_end_point = right if nums[right] > nums[left] else left # Second, execute regular binary search for target number res = self.binary_search(nums, target, 0, actual_end_point) if res != -1: return res else: return self.binary_search(nums, target, actual_end_point + 1, length - 1) def binary_search(self, alist, target, start, end): left, right = start, end while left <= right: mid = (left + right) // 2 if alist[mid] == target: return mid if alist[mid] < target: left = mid + 1 else: right = mid - 1 return -1
1,201
363
import time import numpy as np from typing import Dict, List, Tuple from nxs_libs.interface.workload_manager import ( NxsBaseWorkloadManagerPolicy, ) from nxs_types.frontend import FrontendModelPipelineWorkloadReport from nxs_types.message import ( NxsMsgPinWorkload, NxsMsgType, NxsMsgReportInputWorkloads, NxsMsgUnpinWorkload, ) from nxs_types.nxs_args import NxsWorkloadManagerArgs class FrontendWorkloads: def __init__(self, frontend: str, model_timeout_secs: float) -> None: self.frontend = frontend self.model_timeout_secs = model_timeout_secs self.uuid2throughput: Dict[str, List[float]] = {} self.uuid2timestamps: Dict[str, List[float]] = {} # self.uuid2pipelineuuid: Dict[str, str] = {} # self.uuid2sessionuuid: Dict[str, str] = {} def add_workload(self, workload: FrontendModelPipelineWorkloadReport): uuid = f"{workload.pipeline_uuid}_{workload.session_uuid}" if uuid not in self.uuid2throughput: self.uuid2throughput[uuid] = [] self.uuid2timestamps[uuid] = [] # self.uuid2pipelineuuid[uuid] = workload.pipeline_uuid # self.uuid2sessionuuid[uuid] = workload.session_uuid self.uuid2throughput[uuid].append(workload.fps) self.uuid2timestamps[uuid].append(time.time()) def _remove_expired(self, uuid: str): timestamps = self.uuid2timestamps.get(uuid, []) for idx in range(len(timestamps)): elapsed = time.time() - timestamps[0] # print(idx, elapsed, self.model_timeout_secs) if elapsed < self.model_timeout_secs: break self.uuid2throughput[uuid].pop(0) self.uuid2timestamps[uuid].pop(0) if not self.uuid2throughput[uuid]: self.uuid2throughput.pop(uuid) self.uuid2timestamps.pop(uuid) # self.uuid2pipelineuuid.pop(uuid) # self.uuid2sessionuuid.pop(uuid) # print(f"Removed workload {uuid} from frontend {self.frontend}") def remove_expired(self): for uuid in list(self.uuid2throughput.keys()): self._remove_expired(uuid) def get_workloads(self) -> Dict[str, float]: data = {} self.remove_expired() for uuid in self.uuid2throughput: fps = np.sum(self.uuid2throughput[uuid]) if fps > 0: duration = max(1, time.time() - self.uuid2timestamps[uuid][0]) data[uuid] = float(fps) / duration return data class NxsSimpleWorkloadManagerPolicy(NxsBaseWorkloadManagerPolicy): def __init__(self, args: NxsWorkloadManagerArgs) -> None: super().__init__(args) # self.frontend2workloads:Dict[str, FrontendWorkloads] = {} self.uuid2throughput: Dict[str, List[float]] = {} self.uuid2timestamps: Dict[str, List[float]] = {} self.pinned_workloads: Dict[str, float] = {} self.t0 = time.time() def add_workload(self, workload: FrontendModelPipelineWorkloadReport) -> bool: is_new_workload = False uuid = f"{workload.pipeline_uuid}_{workload.session_uuid}" if uuid not in self.uuid2throughput: self.uuid2throughput[uuid] = [] self.uuid2timestamps[uuid] = [] # self.uuid2pipelineuuid[uuid] = workload.pipeline_uuid # self.uuid2sessionuuid[uuid] = workload.session_uuid is_new_workload = True self._log(f"Added new workload {uuid}") self.uuid2throughput[uuid].append(workload.fps) self.uuid2timestamps[uuid].append(time.time()) return is_new_workload def _remove_expired(self, uuid: str): timestamps = self.uuid2timestamps.get(uuid, []) for idx in range(len(timestamps)): elapsed = time.time() - timestamps[0] # print(idx, elapsed, self.model_timeout_secs) if elapsed < self.args.model_timeout_secs: break self.uuid2throughput[uuid].pop(0) self.uuid2timestamps[uuid].pop(0) if not self.uuid2throughput[uuid]: self.uuid2throughput.pop(uuid) self.uuid2timestamps.pop(uuid) # self.uuid2pipelineuuid.pop(uuid) # self.uuid2sessionuuid.pop(uuid) # print(f"Removed workload {uuid}") self._log(f"Removed workload {uuid}") def remove_expired(self): for uuid in list(self.uuid2throughput.keys()): self._remove_expired(uuid) def get_workloads(self) -> Dict[str, float]: data = {} self.remove_expired() for uuid in self.uuid2throughput: fps = np.sum(self.uuid2throughput[uuid]) if fps > 0: duration = max(1, time.time() - self.uuid2timestamps[uuid][0]) data[uuid] = float(fps) / duration return data def generate_scheduling_msgs( self, ) -> List[FrontendModelPipelineWorkloadReport]: workloads_dict = {} msgs = [] frontend_workloads_dict = self.get_workloads() for uuid in frontend_workloads_dict: if uuid not in workloads_dict: workloads_dict[uuid] = 0 workloads_dict[uuid] += frontend_workloads_dict[uuid] # process pinned_workloads for uuid in self.pinned_workloads: if uuid not in workloads_dict: workloads_dict[uuid] = 0 workloads_dict[uuid] += self.pinned_workloads[uuid] for uuid in workloads_dict: # print(uuid) pipeline_uuid, session_uuid = uuid.split("_") msg = FrontendModelPipelineWorkloadReport( pipeline_uuid=pipeline_uuid, session_uuid=session_uuid, fps=workloads_dict[uuid], ) msgs.append(msg) return msgs def process_msgs( self, msgs: List[NxsMsgReportInputWorkloads] ) -> Tuple[bool, List[FrontendModelPipelineWorkloadReport]]: to_schedule = False scheduling_msgs = [] for msg in msgs: # print(msg) if msg.type == NxsMsgType.REGISTER_WORKLOADS: # frontend_name = msg.data.frontend_name for workload in msg.data.workload_reports: if ( self.add_workload(workload) and self.args.enable_instant_scheduling ): to_schedule = True elif msg.type == NxsMsgType.PIN_WORKLOADS: pin_msg: NxsMsgPinWorkload = msg uuid = f"{pin_msg.pipeline_uuid}_{pin_msg.session_uuid}" self.pinned_workloads[uuid] = pin_msg.fps to_schedule = True self._log( f"Pinning workload - pipeline_uuid: {pin_msg.pipeline_uuid} - session_uuid: {pin_msg.session_uuid} - fps: {pin_msg.fps}" ) elif msg.type == NxsMsgType.UNPIN_WORKLOADS: unpin_msg: NxsMsgUnpinWorkload = msg uuid = f"{unpin_msg.pipeline_uuid}_{unpin_msg.session_uuid}" if uuid in self.pinned_workloads: self.pinned_workloads.pop(uuid) self._log( f"Unpinning workload - pipeline_uuid: {unpin_msg.pipeline_uuid} - session_uuid: {unpin_msg.session_uuid}" ) if time.time() - self.t0 > self.args.report_workloads_interval: to_schedule = True if to_schedule: # generate scheduling data scheduling_msgs = self.generate_scheduling_msgs() # print(scheduling_msgs) self.t0 = time.time() return to_schedule, scheduling_msgs
7,807
2,453
# -*- coding: utf-8 -*- import os import uuid import platform import warnings from pathlib import Path from collections import defaultdict from dataclasses import replace import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from convergence import Convergence from snl_d3d_cec_verify import (MycekStudy, Report, Result, LiveRunner, Template, Validate) from snl_d3d_cec_verify.result import (get_reset_origin, get_normalised_dims, get_normalised_data, get_normalised_data_deficit) from snl_d3d_cec_verify.text import Spinner matplotlib.rcParams.update({'font.size': 8}) def main(template_type, max_experiments, omp_num_threads): # Steps: # # 1. Define a series of grid studies, doubling resolution # 2. Iterate # 3. Determine U_\infty by running without turbines # 4. Run with turbines # 5. Record results # 6. After 3 runs record asymptotic ratio # 7. If in asymptotic range stop iterating # 8. Calculate resolution at desired GCI # 9. Compute at desired resolution if lower than last iteration # 10. Make report # Set grid resolutions and reporting times grid_resolution = [1 / 2 ** i for i in range(max_experiments)] sigma = [int(2 / delta) for delta in grid_resolution] kwargs = {"dx": grid_resolution, "dy": grid_resolution, "sigma": sigma, "restart_interval": 600} # Choose options based on the template type if template_type == "fm": kwargs["stats_interval"] = [240 / (k ** 2) for k in sigma] elif template_type == "structured": # Set time step based on flexible mesh runs dt_init_all = [0.5, 0.25, 0.1, 0.0375, 0.0125] kwargs["dt_init"] = dt_init_all[:max_experiments] else: raise ValueError(f"Template type '{template_type}' unrecognised") cases = MycekStudy(**kwargs) template = Template(template_type) # Use the LiveRunner class to get real time feedback from the Delft3D # calculation runner = LiveRunner(get_d3d_bin_path(), omp_num_threads=omp_num_threads) u_infty_data = defaultdict(list) u_wake_data = defaultdict(list) transect_data = defaultdict(list) u_infty_convergence = Convergence() u_wake_convergence = Convergence() case_counter = 0 run_directory = Path(template_type) / "runs" run_directory.mkdir(exist_ok=True, parents=True) report = Report(79, "%d %B %Y") report_dir = Path(template_type) / "grid_convergence_report" report_dir.mkdir(exist_ok=True, parents=True) global_validate = Validate() ustar_figs = [] ustar_axs = [] gamma_figs = [] gamma_axs = [] for _ in global_validate: ustar_fig, ustar_ax = plt.subplots(figsize=(5, 3.5), dpi=300) gamma_fig, gamma_ax = plt.subplots(figsize=(5, 3.5), dpi=300) ustar_figs.append(ustar_fig) ustar_axs.append(ustar_ax) gamma_figs.append(gamma_fig) gamma_axs.append(gamma_ax) while True: if case_counter + 1 > len(cases): break case = cases[case_counter] no_turb_case = replace(case, simulate_turbines=False) validate = Validate(case) ncells = get_cells(case) section = f"{case.dx}m Resolution" print(section) no_turb_dir = find_project_dir(run_directory, no_turb_case) if no_turb_dir is not None: try: Result(no_turb_dir) print("Loading pre-existing simulation at path " f"'{no_turb_dir}'") except FileNotFoundError: no_turb_dir = None # Determine $U_\infty$ for case, by running without the turbine if no_turb_dir is None: print("Simulating without turbine") no_turb_dir = get_unique_dir(run_directory) no_turb_dir.mkdir() template(no_turb_case, no_turb_dir) case_path = no_turb_dir / "case.yaml" no_turb_case.to_yaml(case_path) with Spinner() as spin: for line in runner(no_turb_dir): spin(line) result = Result(no_turb_dir) u_infty_ds = result.faces.extract_turbine_centre(-1, no_turb_case) u_infty = u_infty_ds["$u$"].values.take(0) u_infty_data["resolution (m)"].append(case.dx) u_infty_data["# cells"].append(ncells) u_infty_data["$U_\\infty$"].append(u_infty) with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Insufficient grids for analysis") u_infty_convergence.add_grids([(case.dx, u_infty)]) turb_dir = find_project_dir(run_directory, case) if turb_dir is not None: try: Result(turb_dir) print(f"Loading pre-existing simulation at path '{turb_dir}'") except FileNotFoundError: turb_dir = None # Run with turbines if turb_dir is None: print("Simulating with turbine") turb_dir = get_unique_dir(run_directory) turb_dir.mkdir() template(case, turb_dir) case_path = turb_dir / "case.yaml" case.to_yaml(case_path) with Spinner() as spin: for line in runner(turb_dir): spin(line) result = Result(turb_dir) # Collect wake velocity at 1.2D downstream u_wake_ds = result.faces.extract_turbine_centre(-1, case, offset_x=0.84) u_wake = u_wake_ds["$u$"].values.take(0) u_wake_data["resolution (m)"].append(case.dx) u_wake_data["# cells"].append(ncells) u_wake_data["$U_{1.2D}$"].append(u_wake) # Record with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Insufficient grids for analysis") u_wake_convergence.add_grids([(case.dx, u_wake)]) plot_transects(case, validate, result, u_infty, ustar_axs, gamma_axs) get_transect_error(case, validate, result, u_infty, transect_data) case_counter += 1 if case_counter < 3: continue if abs(1 - u_wake_convergence[0].asymptotic_ratio) < 0.01: break if case_counter == max_experiments: break gci_required = 0.01 u_infty_exact = u_infty_convergence[0].fine.f_exact u_infty_gci = u_infty_convergence.get_resolution(gci_required) err = [abs((f0 / u_infty_exact) - 1) for f0 in u_infty_data["$U_\\infty$"]] u_infty_data["error"] = err u_infty_df = pd.DataFrame(u_infty_data) u_wake_exact = u_wake_convergence[0].fine.f_exact u_wake_gci = u_wake_convergence.get_resolution(gci_required) err = [abs((f0 / u_wake_exact) - 1) for f0 in u_wake_data["$U_{1.2D}$"]] u_wake_data["error"] = err u_wake_df = pd.DataFrame(u_wake_data) gamma0_sim = 100 * (1 - u_wake_exact / u_infty_exact) centreline = global_validate[0] gamma0_true = 100 * (1 - centreline.data[0] / centreline.attrs["$U_\infty$"]) gamma0_err = abs((gamma0_sim - gamma0_true) / gamma0_true) transect_df = pd.DataFrame(transect_data) transect_grouped = transect_df.groupby(["Transect"]) transect_summary = "" n_transects = len(global_validate) lower_first = lambda s: s[:1].lower() + s[1:] if s else '' for i, transect in enumerate(global_validate): description = transect.attrs['description'] transect_df = transect_grouped.get_group(description).drop("Transect", axis=1) transect_rmse = transect_df.iloc[-1, 1] transect_summary += ( f"For the {lower_first(description)} transect, the root mean " "square error at the lowest grid resolution was " f"{transect_rmse:.4g}.") if (i + 1) < n_transects: transect_summary += " " report.content.add_heading("Summary", level=2) summary_text = ( f"This is a grid convergence study of {len(cases)} cases. The " f"case with the finest grid resolution, of {case.dx}m, achieved an " f"asymptotic ratio of {u_wake_convergence[0].asymptotic_ratio:.4g} " "(asymptotic range is indicated by a value $\\approx 1$). At zero " "grid resolution, the normalised velocity deficit measured 1.2 " f"diameters downstream from the turbine was {gamma0_sim:.4g}\%, a " f"{gamma0_err * 100:.4g}\% error against the measured value of " f"{gamma0_true:.4g}\%. ") summary_text += transect_summary report.content.add_text(summary_text) report.content.add_heading("Grid Convergence Studies", level=2) report.content.add_heading("Free Stream Velocity", level=3) report.content.add_text( "This section presents the convergence study for the free stream " "velocity ($U_\\infty$). For the final case, with grid resolution of " f"{case.dx}m, an asymptotic ratio of " f"{u_infty_convergence[0].asymptotic_ratio:.4g} was achieved " "(asymptotic range is indicated by a value $\\approx 1$). The free " f"stream velocity at zero grid resolution is {u_infty_exact:.4g}m/s. " "The grid resolution required for a fine-grid GCI of " f"{gci_required * 100}\% is {u_infty_gci:.4g}m.") caption = ("Free stream velocity ($U_\\infty$) per grid resolution " "with computational cells and error against value at zero grid " "resolution") report.content.add_table(u_infty_df, index=False, caption=caption) fig, ax = plt.subplots(figsize=(4, 2.75), dpi=300) u_infty_df.plot(ax=ax, x="# cells", y="error", marker='x') plt.yscale("log") plt.xscale("log") plot_name = "u_infty_convergence.png" plot_path = report_dir / plot_name fig.savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Free stream velocity error against value at zero grid " "resolution per grid resolution ") report.content.add_image(plot_name, caption, width="3.64in") report.content.add_heading("Wake Velocity", level=3) report.content.add_text( "This section presents the convergence study for the wake centerline " "velocity measured 1.2 diameters downstream from the turbine " "($U_{1.2D}$). For the final case, with grid resolution of " f"{case.dx}m, an asymptotic ratio of " f"{u_wake_convergence[0].asymptotic_ratio:.4g} was achieved " "(asymptotic range is indicated by a value $\\approx 1$). The free " f"stream velocity at zero grid resolution is {u_wake_exact:.4g}m/s. " "The grid resolution required for a fine-grid GCI of " f"{gci_required * 100}\% is {u_wake_gci:.4g}m.") caption = ("Wake centerline velocity 1.2 diameters downstream " "($U_{1.2D}$) per grid resolution with computational cells and " "error against value at zero grid resolution") report.content.add_table(u_wake_df, index=False, caption=caption) fig, ax = plt.subplots(figsize=(4, 2.75), dpi=300) u_wake_df.plot(ax=ax, x="# cells", y="error", marker='x') plt.yscale("log") plt.xscale("log") plot_name = "u_wake_convergence.png" plot_path = report_dir / plot_name fig.savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Wake velocity error against value at zero grid resolution " "per grid resolution ") report.content.add_image(plot_name, caption, width="3.64in") report.content.add_heading("Validation", level=3) report.content.add_text( "At zero grid resolution, the normalised deficit of $U_{1.2D}$, " f"($\\gamma_{{0(1.2D)}}$) is {gamma0_sim:.4g}\%, a " f"{gamma0_err * 100:.4g}\% error against the measured value of " f"{gamma0_true:.4g}\%.") report.content.add_heading("Wake Transects", level=2) report.content.add_text( "This section presents axial velocity transects along the turbine " "centreline and at cross-sections along the $y$-axis. Errors are " "reported relative to the experimental data given in [@mycek2014].") for i, transect in enumerate(global_validate): description = transect.attrs['description'] report.content.add_heading(description, level=3) transect_df = transect_grouped.get_group(description).drop("Transect", axis=1) transect_rmse = transect_df.iloc[-1, 1] report.content.add_text( "The root mean square error (RMSE) for this transect at the " f"finest grid resolution of {case.dx}m was {transect_rmse:.4g}.") caption = ("Root mean square error (RMSE) for the normalised " "velocity, $u^*_0$, per grid resolution.") report.content.add_table(transect_df, index=False, caption=caption) transect_true = transect.to_xarray() major_axis = f"${transect.attrs['major_axis']}^*$" transect_true_u0 = get_u0(transect_true, transect_true, 0.8) transect_true_u0.plot(ax=ustar_axs[i], x=major_axis, label='Experiment') ustar_axs[i].legend(loc='center left', bbox_to_anchor=(1, 0.5)) ustar_axs[i].grid() ustar_axs[i].set_title("") plot_name = f"transect_u0_{i}.png" plot_path = report_dir / plot_name ustar_figs[i].savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Normalised velocity, $u^*_0$, (m/s) per grid resolution " "comparison. Experimental data reverse engineered from " f"[@mycek2014, fig. {transect.attrs['figure']}].") report.content.add_image(plot_name, caption, width="5.68in") transect_true_gamma0 = get_gamma0(transect_true, transect_true) transect_true_gamma0.plot(ax=gamma_axs[i], x=major_axis, label='Experiment') gamma_axs[i].legend(loc='center left', bbox_to_anchor=(1, 0.5)) gamma_axs[i].grid() gamma_axs[i].set_title("") plot_name = f"transect_gamma0_{i}.png" plot_path = report_dir / plot_name gamma_figs[i].savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Normalised velocity deficit, $\gamma_0$, (%) per grid " "resolution comparison. Experimental data reverse " "engineered from [@mycek2014, fig. " f"{transect.attrs['figure']}].") report.content.add_image(plot_name, caption, width="5.68in") # Add section for the references report.content.add_heading("References", level=2) # Add report metadata os_name = platform.system() report.title = f"Grid Convergence Study ({os_name})" report.date = "today" # Write the report to file with open(report_dir / "report.md", "wt") as f: for line in report: f.write(line) # Convert file to docx or print report to stdout try: import pypandoc pypandoc.convert_file(f"{report_dir / 'report.md'}", 'docx', outputfile=f"{report_dir / 'report.docx'}", extra_args=['-C', f'--resource-path={report_dir}', '--bibliography=examples.bib', '--reference-doc=reference.docx']) except ImportError: print(report) def get_d3d_bin_path(): env = dict(os.environ) if 'D3D_BIN' in env: root = Path(env['D3D_BIN'].replace('"', '')) print('D3D_BIN found') else: root = Path("..") / "src" / "bin" print('D3D_BIN not found') print(f'Setting bin folder path to {root.resolve()}') return root.resolve() def find_project_dir(path, case): path = Path(path) files = list(Path(path).glob("**/case.yaml")) ignore_fields = ["stats_interval", "restart_interval"] for file in files: test = MycekStudy.from_yaml(file) if test.is_equal(case, ignore_fields): return file.parent return None def get_unique_dir(path, max_tries=1e6): parent = Path(path) for _ in range(int(max_tries)): name = uuid.uuid4().hex child = parent / name if not child.exists(): return child raise RuntimeError("Could not find unique directory name") def get_u0(da, transect, factor, case=None): if case is not None: da = get_reset_origin(da, (case.turb_pos_x, case.turb_pos_y, case.turb_pos_z)) da = get_normalised_dims(da, transect.attrs["$D$"]) da = get_normalised_data(da, factor) return da def get_gamma0(da, transect, case=None): if case is not None: da = get_reset_origin(da, (case.turb_pos_x, case.turb_pos_y, case.turb_pos_z)) da = get_normalised_dims(da, transect.attrs["$D$"]) da = get_normalised_data_deficit(da, transect.attrs["$U_\\infty$"], "$\gamma_0$") return da def plot_transects(case, validate, result, factor, ustar_ax, gamma_ax): for i, transect in enumerate(validate): transect_true = transect.to_xarray() # Compare transect transect_sim = result.faces.extract_z(-1, **transect) # Determine plot x-axis major_axis = f"${transect.attrs['major_axis']}^*$" # Create and save a u0 figure transect_sim_u0 = get_u0(transect_sim["$u$"], transect_true, factor, case) transect_sim_u0.plot(ax=ustar_ax[i], x=major_axis, label=f'{case.dx}m') # Create and save a gamma0 figure transect_sim_gamma0 = get_gamma0(transect_sim["$u$"], transect_true, case) transect_sim_gamma0.plot(ax=gamma_ax[i], x=major_axis, label=f'{case.dx}m') def get_rmse(estimated, observed): estimated = estimated[~np.isnan(estimated)] if len(estimated) == 0: return np.nan observed = observed[:len(estimated)] return np.sqrt(((estimated - observed[:len(estimated)]) ** 2).mean()) def get_transect_error(case, validate, result, factor, data): for i, transect in enumerate(validate): transect_true = transect.to_xarray() # Compare transect transect_sim = result.faces.extract_z(-1, **transect) transect_sim_u0 = get_u0(transect_sim["$u$"], transect_true, factor, case) transect_true_u0 = get_u0(transect_true, transect_true, transect_true.attrs["$U_\infty$"], case) # Calculate RMS error and store rmse = get_rmse(transect_sim_u0.values, transect_true_u0.values) data["resolution (m)"].append(case.dx) data["Transect"].append(transect.attrs['description']) data["RMSE"].append(rmse) def get_cells(case): top = (case.x1 - case.x0) * (case.y1 - case.y0) * case.sigma bottom = case.dx * case.dy return top / bottom def check_positive(value): ivalue = int(value) if ivalue <= 0: msg = f"{value} is an invalid positive int value" raise argparse.ArgumentTypeError(msg) return ivalue if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='MODEL', required=True) parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument('--experiments', type=check_positive, choices=range(3, 6), default=5, help=("number of experiments to run - defaults " "to 5")) parser_fm = subparsers.add_parser('fm', parents=[parent_parser], help='execute flexible mesh model') parser_fm.add_argument('--threads', type=check_positive, default=1, help=("number of CPU threads to utilise - defaults " "to 1")) parser_structured = subparsers.add_parser('structured', parents=[parent_parser], help='execute structured model') args = parser.parse_args() if "threads" not in args: args.threads = 1 main(args.MODEL, args.experiments, args.threads)
23,258
7,306
import numpy as np import matplotlib.pyplot as plt import torch import scipy from GLM.GLM_Model import GLM_Model, PyTorchObj from scipy.optimize import minimize, Bounds from tqdm import tqdm class GLM_Model_GP(GLM_Model.GLM_Model): def __init__(self, params): super().__init__(params) self.kernel_prep_dict = None self.first_time_train_this_covariate = None self.covariate_training = None self.total_likelihood = None self.total_exp = None self.total_kld = None def add_covariate(self, covariate): super().add_covariate(covariate) self.register_parameter(name=f'{covariate.name}_u', param=covariate.time.time_dict['u']) self.bound_duration_check(covariate) def bound_duration_check(self, covariate): filter_inducing_max = covariate.time.time_dict_t['u']().max() filter_inducing_min = covariate.time.time_dict_t['u']().min() inducing_bdd_max = covariate.bounds_params['u'][1] inducing_bdd_min = covariate.bounds_params['u'][0] if filter_inducing_max > inducing_bdd_max: raise ValueError(f'Upper Bound for {covariate.name} Filter less than initial maximum inducing point') if filter_inducing_min < inducing_bdd_min: raise ValueError(f'Lower Bound for {covariate.name} Filter greater than initial minimum inducing point') def train_variational_parameters(self, kernel_prep_dict, i): self.kernel_prep_dict = kernel_prep_dict self.update_time_bounds() for covariate_name, covariate in self.covariates.items(): if covariate.etc_params['use_basis_form']: continue if i <= 2 or (i > 2 and i % 2 == 0): params_to_optimize = [param for param in self.state_dict().keys() if (param.startswith(covariate_name) and not (param.endswith('_hyper'))) and not (param.endswith('_u'))] else: params_to_optimize = [param for param in self.state_dict().keys() if (param.startswith(covariate_name) and not (param.endswith('_hyper')))] params_to_optimize.append('baseline') for name, param in self.named_parameters(): if name not in params_to_optimize: param.requires_grad = False else: param.requires_grad = True self.update_covariate_gp_objects() self.set_training_parameters(params_to_optimize) # self.optimizer = torch.optim.LBFGS(self.training_parameters, lr=1, history_size=10, max_iter=self.params.gp_variational_iter, line_search_fn='strong_wolfe') # optimizer_closure = self.nll_closure() self.first_time_train_this_covariate = True self.covariate_training = covariate_name self.total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) self.total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) self.total_kld = torch.zeros(1, dtype=self.params.torch_d_type) maxiter = self.params.gp_variational_iter with tqdm(total=maxiter) as pbar: def verbose(xk): pbar.update(1) obj = PyTorchObj.PyTorchObjective(self, params_to_optimize, self.scipy_closure) xL = scipy.optimize.minimize(obj.fun, obj.x0, method='TNC', jac=obj.jac, callback=verbose, options={'gtol': 1e-6, 'disp': True, 'maxiter': maxiter}) self.update_covariate_design_matrices() self.update_time_bounds() print('done') def add_noise_parameter(self): for covariate_name, covariate in self.covariates.items(): if covariate.etc_params['use_basis_form']: continue covariate.add_noise_param(self) def train_hyperparameters(self, kernel_prep_dict, i): self.kernel_prep_dict = kernel_prep_dict self.update_gp_param_bounds() if i > 4: self.add_noise_parameter() for covariate_name, covariate in self.covariates.items(): if covariate.etc_params['use_basis_form']: continue params_to_optimize = [param for param in self.state_dict().keys() if (param.startswith(covariate_name) and param.endswith('_hyper'))] for name, param in self.named_parameters(): if name not in params_to_optimize: param.requires_grad = False else: param.requires_grad = True # params_to_optimize = [param for param in self.state_dict().keys() if (not param.startswith('History') and # param.endswith('_hyper'))] self.update_covariate_gp_objects() self.set_training_parameters(params_to_optimize) # self.optimizer = torch.optim.LBFGS(self.training_parameters, lr=0.3, history_size=5, max_iter=self.params.gp_hyperparameter_iter, line_search_fn='strong_wolfe') self.first_time_train_this_covariate = True self.covariate_training = covariate_name self.total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) self.total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) self.total_kld = torch.zeros(1, dtype=self.params.torch_d_type) # optimizer_closure = self.nll_closure_hyper() # self.zero_grad() # print(self.optimizer.step(optimizer_closure)) maxiter = self.params.gp_hyperparameter_iter with tqdm(total=maxiter) as pbar: def verbose(xk): pbar.update(1) obj = PyTorchObj.PyTorchObjective(self, params_to_optimize, self.scipy_closure) xL = scipy.optimize.minimize(obj.fun, obj.x0, method='TNC', jac=obj.jac, callback=verbose, options={'gtol': 1e-6, 'disp': True, 'maxiter': maxiter}) print('done') def scipy_closure(self): self.zero_grad() # TODO self.update_covariate_gp_objects(update_all=False) loss = self.get_nlog_likelihood() return loss def nll_closure(self): def closure(): self.optimizer.zero_grad() # TODO self.update_covariate_gp_objects(update_all=False) loss = self.get_nlog_likelihood() loss.backward() return loss return closure def nll_closure_hyper(self): def closure(): self.optimizer.zero_grad() # TODO self.update_covariate_gp_objects(update_all=False) loss = self.get_nlog_likelihood() loss.backward() return loss return closure def update_covariate_gp_objects(self, update_all=True): if update_all: with torch.no_grad(): for covariate_name, covariate in self.covariates.items(): covariate.gp_obj.update_kernels() covariate.gp_obj.compute_needed_chol_and_inv(self.kernel_prep_dict) self.zero_grad() else: self.covariates[self.covariate_training].gp_obj.update_kernels() self.covariates[self.covariate_training].gp_obj.compute_needed_chol_and_inv(self.kernel_prep_dict) def update_gp_param_bounds(self): for covariate_name, covariate in self.covariates.items(): covariate.update_gp_param_bounds() def update_time_bounds(self): for covariate_name, covariate in self.covariates.items(): covariate.time.update_with_new_bounds('u') def update_covariate_design_matrices(self): for covariate_name, covariate in self.covariates.items(): covariate.update_design_matrix() def get_nlog_likelihood(self, optimize_hyper=False): total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) total_kld = torch.zeros(1, dtype=self.params.torch_d_type) for covariate_name, cov in self.covariates.items(): if covariate_name != self.covariate_training and not self.first_time_train_this_covariate: continue ll, e_arg, gaussian_term = cov.get_log_likelihood_terms() total_likelihood += self.y @ ll total_exp += e_arg total_kld += gaussian_term if covariate_name != self.covariate_training and self.first_time_train_this_covariate: self.total_likelihood += self.y @ ll self.total_exp += e_arg self.total_kld += gaussian_term if self.first_time_train_this_covariate: total_exp = torch.sum(torch.exp(total_exp + self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type))) total_likelihood = total_likelihood + self.y @ (self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) nll = -1 * (total_likelihood - self.params.delta * total_exp + total_kld) self.first_time_train_this_covariate = False else: total_exp = torch.sum(torch.exp(total_exp + self.total_exp + self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type))) total_likelihood = total_likelihood + self.total_likelihood + self.y @ (self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) nll = -1 * (total_likelihood - self.params.delta * total_exp + total_kld + self.total_kld) return nll def get_nats_per_bin(self, y, exp_arg): lambda_0 = torch.sum(y) / (y.shape[0] * self.params.delta) nats_per_bin = y * exp_arg - self.params.delta * torch.exp(exp_arg) nats_per_bin = nats_per_bin - (y * torch.log(lambda_0) - self.params.delta * lambda_0 * torch.ones_like(y, dtype=self.params.torch_d_type)) # nats_per_bin = nats_per_bin - (y * np.log(lambda_0) - self.params.delta * lambda_0 * np.ones_like(y)) total_num_spikes = torch.sum(y) nll_test_mean = torch.sum(nats_per_bin) / total_num_spikes return nll_test_mean def get_loss(self): total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) for covariate_name, cov in self.covariates.items(): ll, e_arg = cov.loss() total_likelihood += self.y @ ll total_exp += e_arg total_exp = (total_exp + self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) total_likelihood = total_likelihood + self.y @ (self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) loss = -1 * (total_likelihood - self.params.delta * torch.sum(torch.exp(total_exp))) loss = self.get_nats_per_bin(self.y, total_exp) return loss def get_test_loss(self): total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) total_exp = torch.zeros(self.y_test.shape[0], dtype=self.params.torch_d_type) for covariate_name, cov in self.covariates.items(): ll, e_arg = cov.test_loss() total_likelihood += self.y_test @ ll total_exp += e_arg total_exp = (total_exp + self.baseline * torch.ones(self.y_test.shape[0], dtype=self.params.torch_d_type)) total_likelihood = total_likelihood + self.y_test @ (self.baseline * torch.ones(self.y_test.shape[0], dtype=self.params.torch_d_type)) loss = -1 * (total_likelihood - self.params.delta * torch.sum(torch.exp(total_exp))) loss = self.get_nats_per_bin(self.y_test, total_exp) return loss def plot_covariates(self, evolution_df_dict, timer_obj): timer_obj.time_waste_start() with torch.no_grad(): nll = self.get_loss() nll_test = self.get_test_loss() plt.style.use("ggplot") fig, axs = plt.subplots(2, int(np.ceil(len(self.covariates.keys())/2)), figsize=(3*len(self.covariates.keys()), 10)) axs = axs.flatten() for dx, (name, covariate) in enumerate(self.covariates.items()): if name == 'History': axs[dx].set_ylim([-7, 2]) plot_mean, plot_std, plot_time, entire_mean, entire_std, entire_time = self.covariates[name].get_values_to_plot() plot_time, plot_mean, plot_std = zip(*sorted(zip(plot_time, plot_mean, plot_std))) plot_time = np.array(plot_time) plot_mean = np.array(plot_mean) plot_std = np.array(plot_std) axs[dx].plot(plot_time, plot_mean, label='posterior mean', color='tomato') axs[dx].fill_between(plot_time, plot_mean - 2 * plot_std, plot_mean + 2 * plot_std, alpha=0.3, color='salmon') if not covariate.etc_params['use_basis_form']: axs[dx].plot(self.covariates[name].time.time_dict_t['u']().data.detach().numpy(), np.zeros(self.covariates[name].time.time_dict['u'].shape[0]), 'o', color='orange', label='inducing points') axs[dx].axhline(y=0, linestyle='--', zorder=0) axs[dx].axvline(x=0, linestyle='--', zorder=0) axs[dx].set_title(name) axs[dx].legend() ev_dx = evolution_df_dict[name].shape[0] evolution_df_dict[name].at[ev_dx, 'plot_mean'] = np.copy(plot_mean) evolution_df_dict[name].at[ev_dx, 'plot_2std'] = np.copy(2 * plot_std) evolution_df_dict[name].at[ev_dx, 'plot_time'] = np.copy(plot_time) evolution_df_dict[name].at[ev_dx, 'entire_mean'] = np.copy(entire_mean) evolution_df_dict[name].at[ev_dx, 'entire_2std'] = np.copy(2 * entire_std) evolution_df_dict[name].at[ev_dx, 'entire_time'] = np.copy(entire_time) evolution_df_dict[name].at[ev_dx, 'nll'] = np.copy(nll.data.detach().numpy()) evolution_df_dict[name].at[ev_dx, 'nll_test'] = np.copy(nll_test.data.detach().numpy()) timer_obj.time_waste_end() evolution_df_dict[name].at[ev_dx, 'time_so_far'] = timer_obj.get_time() timer_obj.time_waste_start() evolution_df_dict[name].to_pickle(f'{self.params.gp_ev_path}_{name}') plt.subplots_adjust(hspace=1.0) plt.savefig(self.params.gp_filter_plot_path, dpi=300) print(f'nll: {nll_test.data.detach().numpy()}') plt.show() timer_obj.time_waste_end()
15,236
5,008
from k5test import * # Test that the kdcpreauth client_keyblock() callback matches the key # indicated by the etype info, and returns NULL if no key was selected. testpreauth = os.path.join(buildtop, 'plugins', 'preauth', 'test', 'test.so') conf = {'plugins': {'kdcpreauth': {'module': 'test:' + testpreauth}, 'clpreauth': {'module': 'test:' + testpreauth}}} realm = K5Realm(create_host=False, get_creds=False, krb5_conf=conf) realm.run([kadminl, 'modprinc', '+requires_preauth', realm.user_princ]) realm.run([kadminl, 'setstr', realm.user_princ, 'teststring', 'testval']) realm.run([kadminl, 'addprinc', '-nokey', '+requires_preauth', 'nokeyuser']) realm.kinit(realm.user_princ, password('user'), expected_msg='testval') realm.kinit('nokeyuser', password('user'), expected_code=1, expected_msg='no key') # Preauth type -123 is the test preauth module type; 133 is FAST # PA-FX-COOKIE; 2 is encrypted timestamp. # Test normal preauth flow. mark('normal') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='testval', expected_trace=msgs) # Test successful optimistic preauth. mark('optimistic') expected_trace = ('Attempting optimistic preauth', 'Processing preauth types: -123', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: -123', 'Decrypted AS reply') realm.run(['./icred', '-o', '-123', realm.user_princ, password('user')], expected_trace=expected_trace) # Test optimistic preauth failing on client, falling back to encrypted # timestamp. mark('optimistic (client failure)') msgs = ('Attempting optimistic preauth', 'Processing preauth types: -123', '/induced optimistic fail', 'Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-o', '-123', '-X', 'fail_optimistic', realm.user_princ, password('user')], expected_trace=msgs) # Test optimistic preauth failing on KDC, falling back to encrypted # timestamp. mark('optimistic (KDC failure)') realm.run([kadminl, 'setstr', realm.user_princ, 'failopt', 'yes']) msgs = ('Attempting optimistic preauth', 'Processing preauth types: -123', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: -123', '/Preauthentication failed', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-o', '-123', realm.user_princ, password('user')], expected_trace=msgs) # Leave failopt set for the next test. # Test optimistic preauth failing on KDC, stopping because the test # module disabled fallback. mark('optimistic (KDC failure, no fallback)') msgs = ('Attempting optimistic preauth', 'Processing preauth types: -123', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: -123', '/Preauthentication failed') realm.run(['./icred', '-X', 'disable_fallback', '-o', '-123', realm.user_princ, password('user')], expected_code=1, expected_msg='Preauthentication failed', expected_trace=msgs) realm.run([kadminl, 'delstr', realm.user_princ, 'failopt']) # Test KDC_ERR_MORE_PREAUTH_DATA_REQUIRED and secure cookies. mark('second round-trip') realm.run([kadminl, 'setstr', realm.user_princ, '2rt', 'secondtrip']) msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='2rt: secondtrip', expected_trace=msgs) # Test client-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # falling back to encrypted timestamp. mark('second round-trip (client failure)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', '/induced 2rt fail', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-X', 'fail_2rt', realm.user_princ, password('user')], expected_msg='2rt: secondtrip', expected_trace=msgs) # Test client-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # stopping because the test module disabled fallback. mark('second round-trip (client failure, no fallback)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', '/induced 2rt fail') realm.run(['./icred', '-X', 'fail_2rt', '-X', 'disable_fallback', realm.user_princ, password('user')], expected_code=1, expected_msg='Pre-authentication failed: induced 2rt fail', expected_trace=msgs) # Test KDC-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # falling back to encrypted timestamp. mark('second round-trip (KDC failure)') realm.run([kadminl, 'setstr', realm.user_princ, 'fail2rt', 'yes']) msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/Preauthentication failed', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='2rt: secondtrip', expected_trace=msgs) # Leave fail2rt set for the next test. # Test KDC-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # stopping because the test module disabled fallback. mark('second round-trip (KDC failure, no fallback)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/Preauthentication failed') realm.run(['./icred', '-X', 'disable_fallback', realm.user_princ, password('user')], expected_code=1, expected_msg='Preauthentication failed', expected_trace=msgs) realm.run([kadminl, 'delstr', realm.user_princ, 'fail2rt']) # Test tryagain flow by inducing a KDC_ERR_ENCTYPE_NOSUPP error on the KDC. mark('tryagain') realm.run([kadminl, 'setstr', realm.user_princ, 'err', 'testagain']) msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/KDC has no support for encryption type', 'Recovering from KDC error 14 using preauth mech -123', 'Preauth tryagain input types (-123): -123, PA-FX-COOKIE (133)', 'Preauth module test (-123) tryagain returned: 0/Success', 'Followup preauth for next request: -123, PA-FX-COOKIE (133)', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='tryagain: testagain', expected_trace=msgs) # Test a client-side tryagain failure, falling back to encrypted # timestamp. mark('tryagain (client failure)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/KDC has no support for encryption type', 'Recovering from KDC error 14 using preauth mech -123', 'Preauth tryagain input types (-123): -123, PA-FX-COOKIE (133)', '/induced tryagain fail', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-X', 'fail_tryagain', realm.user_princ, password('user')], expected_trace=msgs) # Test a client-side tryagain failure, stopping because the test # module disabled fallback. mark('tryagain (client failure, no fallback)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/KDC has no support for encryption type', 'Recovering from KDC error 14 using preauth mech -123', 'Preauth tryagain input types (-123): -123, PA-FX-COOKIE (133)', '/induced tryagain fail') realm.run(['./icred', '-X', 'fail_tryagain', '-X', 'disable_fallback', realm.user_princ, password('user')], expected_code=1, expected_msg='KDC has no support for encryption type', expected_trace=msgs) # Test that multiple stepwise initial creds operations can be # performed with the same krb5_context, with proper tracking of # clpreauth module request handles. mark('interleaved') realm.run([kadminl, 'addprinc', '-pw', 'pw', 'u1']) realm.run([kadminl, 'addprinc', '+requires_preauth', '-pw', 'pw', 'u2']) realm.run([kadminl, 'addprinc', '+requires_preauth', '-pw', 'pw', 'u3']) realm.run([kadminl, 'setstr', 'u2', '2rt', 'extra']) out = realm.run(['./icinterleave', 'pw', 'u1', 'u2', 'u3']) if out != ('step 1\nstep 2\nstep 3\nstep 1\nfinish 1\nstep 2\nno attr\n' 'step 3\nno attr\nstep 2\n2rt: extra\nstep 3\nfinish 3\nstep 2\n' 'finish 2\n'): fail('unexpected output from icinterleave') success('Pre-authentication framework tests')
13,127
4,318
#!/usr/bin/env python3 # ## Licensed to the .NET Foundation under one or more agreements. ## The .NET Foundation licenses this file to you under the MIT license. # ## # Title: antigen_unique_issues.py # # Notes: # # Script to identify unique issues from all partitions and print them on console. # ################################################################################ ################################################################################ # import sys import argparse import os from os import walk from coreclr_arguments import * import re parser = argparse.ArgumentParser(description="description") parser.add_argument("-issues_directory", help="Path to issues directory") unique_issue_dir_pattern = re.compile(r"\*\*\*\* .*UniqueIssue\d+") assertion_patterns = [re.compile(r"Assertion failed '(.*)' in '.*' during '(.*)'"), re.compile(r"Assert failure\(PID \d+ \[0x[0-9a-f]+], Thread: \d+ \[0x[0-9a-f]+]\):(.*)")] def setup_args(args): """ Setup the args. Args: args (ArgParse): args parsed by arg parser Returns: args (CoreclrArguments) """ coreclr_args = CoreclrArguments(args, require_built_core_root=False, require_built_product_dir=False, require_built_test_dir=False, default_build_type="Checked") coreclr_args.verify(args, "run_configuration", lambda unused: True, "Unable to set run_configuration") coreclr_args.verify(args, "issues_directory", lambda issues_directory: os.path.isdir(issues_directory), "issues_directory doesn't exist") return coreclr_args def print_unique_issues_summary(issues_directory): """Merge issues-summary-*-PartitionN.txt files from each partitions and print unique issues Args: issues_directory (string): Issues directory Returns: Number of issues found """ issues_found = 0 unique_issues_all_partitions = {} for file_path, dirs, files in walk(issues_directory, topdown=True): for file_name in files: if not file_name.startswith("issues-summary-") or "Partition" not in file_name: continue issues_summary_file = os.path.join(file_path, file_name) partition_name = file_path.split(os.sep)[-1] add_header = True unique_issues = [] with open(issues_summary_file, 'r') as sf: contents = sf.read() unique_issues = list(filter(None, re.split(unique_issue_dir_pattern, contents))) # Iterate over all unique issues of this partition for unique_issue in unique_issues: # Find the matching assertion message for assertion_pattern in assertion_patterns: issue_match = re.search(assertion_pattern, unique_issue) if issue_match is not None: assert_string = " ".join(issue_match.groups()) # Check if previous partitions has already seen this assert if assert_string not in unique_issues_all_partitions: unique_issues_all_partitions[assert_string] = unique_issue issues_found += 1 if add_header: print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% {} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%".format(partition_name)) add_header = False print(unique_issue.strip()) print("------------------------------------") break print("===== Found {} unique issues.".format(issues_found)) return issues_found def main(main_args): """Main entrypoint Args: main_args ([type]): Arguments to the script """ coreclr_args = setup_args(main_args) issues_directory = coreclr_args.issues_directory issues_found = print_unique_issues_summary(issues_directory) return 1 if issues_found > 0 else 0 if __name__ == "__main__": args = parser.parse_args() sys.exit(main(args))
4,303
1,129
""" .. module:: CMetricTestError :synopsis: Performance Metric: Test Error .. moduleauthor:: Marco Melis <marco.melis@unica.it> """ import sklearn.metrics as skm from secml.array import CArray from secml.ml.peval.metrics import CMetric class CMetricTestError(CMetric): """Performance evaluation metric: Test Error. Test Error score is the percentage (inside 0/1 range) of wrongly predicted labels (inverse of accuracy). The metric uses: - y_true (true ground labels) - y_pred (predicted labels) Attributes ---------- class_type : 'test-error' Examples -------- >>> from secml.ml.peval.metrics import CMetricTestError >>> from secml.array import CArray >>> peval = CMetricTestError() >>> print(peval.performance_score(CArray([0, 1, 2, 3]), CArray([0, 1, 1, 3]))) 0.25 """ __class_type = 'test-error' best_value = 0.0 def _performance_score(self, y_true, y_pred): """Computes the Accuracy score. Parameters ---------- y_true : CArray Ground truth (true) labels or target scores. y_pred : CArray Predicted labels, as returned by a CClassifier. Returns ------- metric : float Returns metric value as float. """ return 1.0 - float(skm.accuracy_score(y_true.tondarray(), y_pred.tondarray()))
1,448
465
from __future__ import division, print_function import argparse import sys, os, time, gzip, glob from collections import defaultdict from base.config import combine_configs from base.io_util import make_dir, remove_dir, tree_to_json, write_json, myopen from base.sequences_process import sequence_set from base.utils import num_date, save_as_nexus, parse_date from base.tree import tree # from base.fitness_model import fitness_model from base.frequencies import alignment_frequencies, tree_frequencies, make_pivots from base.auspice_export import export_metadata_json, export_frequency_json, export_tip_frequency_json import numpy as np from datetime import datetime import json from pdb import set_trace from base.logger import logger from Bio import SeqIO from Bio import AlignIO import cPickle as pickle def collect_args(): parser = argparse.ArgumentParser( description = "Process (prepared) JSON(s)", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('-j', '--json', help="prepared JSON to process") parser.add_argument('--clean', default=False, action='store_true', help="clean build (remove previous checkpoints)") parser.add_argument('--tree_method', type=str, default='raxml', choices=["fasttree", "raxml", "iqtree"], help="specify the method used to build the tree") parser.add_argument('--no_tree', action='store_true', help="do not build a tree") return parser class process(object): """process influenza virus sequences in mutliple steps to allow visualization in browser * filtering and parsing of sequences * alignment * tree building * frequency estimation of clades and mutations * export as json """ def __init__(self, config): """ check config file, make necessary directories, set up logger """ super(process, self).__init__() self.config = combine_configs("process", config) # try: # assert(os.path.basename(os.getcwd()) == self.config["dir"]) # except AssertionError: # print("Run this script from within the {} directory".format(self.config["dir"])) # sys.exit(2) for p in self.config["output"].values(): if not os.path.isdir(p): os.makedirs(p) self.log = logger(self.config["output"]["data"], False) # parse the JSON into different data bits try: with open(self.config["in"], 'r') as fh: data = json.load(fh) except Exception as e: self.log.fatal("Error loading JSON. Error: {}".format(e)) self.info = data["info"] if "time_interval" in data["info"]: self.info["time_interval"] = [datetime.strptime(x, '%Y-%m-%d').date() for x in data["info"]["time_interval"]] self.info["lineage"] = data["info"]["lineage"] if 'leaves' in data: self.tree_leaves = data['leaves'] try: self.colors = data["colors"] except KeyError: self.log.notify("* colours have not been set") self.colors = False try: self.lat_longs = data["lat_longs"] except KeyError: self.log.notify("* latitude & longitudes have not been set") self.lat_longs = False # backwards compatability - set up file_dumps (need to rewrite sometime) # self.sequence_fname = self.input_data_path+'.fasta' self.file_dumps = {} self.output_path = os.path.join(self.config["output"]["data"], self.info["prefix"]) self.file_dumps['seqs'] = self.output_path + '_sequences.pkl.gz' self.file_dumps['tree'] = self.output_path + '_tree.newick' self.file_dumps['nodes'] = self.output_path + '_nodes.pkl.gz' if self.config["clean"] == True: self.log.notify("Removing intermediate files for a clean build") for f in glob.glob(self.output_path+"*"): os.remove(f) if "reference" in data: self.seqs = sequence_set(self.log, data["sequences"], data["reference"], self.info["date_format"]) else: self.log.fatal("No reference provided. Cannot continue.") # self.seqs = sequence_set(self.log, data["sequences"], False, self.info["date_format"]) # backward compatability self.reference_seq = self.seqs.reference_seq self.proteins = self.seqs.proteins for trait in self.info["traits_are_dates"]: self.seqs.convert_trait_to_numerical_date(trait, self.info["date_format"]) # Prepare titers if they are available. if "titers" in data: self.log.debug("Loaded %i titer measurements" % len(data["titers"])) # Convert titer dictionary indices from JSON-compatible strings back # to tuples. self.titers = {eval(key): value for key, value in data["titers"].iteritems()} ## usefull flag to set (from pathogen run file) to disable restoring self.try_to_restore = True def dump(self): ''' write the current state to file ''' self.log.warn("unsure if dump() works") from cPickle import dump from Bio import Phylo for attr_name, fname in self.file_dumps.iteritems(): if hasattr(self,attr_name): print("dumping",attr_name) #if attr_name=='seqs': self.seqs.all_seqs = None with myopen(fname, 'wb') as ofile: if attr_name=='nodes': continue elif attr_name=='tree': #biopython trees don't pickle well, write as newick + node info self.tree.dump(fname, self.file_dumps['nodes']) else: dump(getattr(self,attr_name), ofile, -1) def load(self, debug=False): ''' reconstruct instance from files ''' self.log.warn("unsure if load() works") from cPickle import load for attr_name, fname in self.file_dumps.iteritems(): if attr_name=='tree': continue if os.path.isfile(fname): with myopen(fname, 'r') as ifile: print('loading',attr_name,'from file',fname) setattr(self, attr_name, load(ifile)) tree_name = self.file_dumps['tree'] if os.path.isfile(tree_name): if os.path.isfile(self.file_dumps['nodes']): node_file = self.file_dumps['nodes'] else: node_file = None # load tree, build if no tree file available self.build_tree(tree_name, node_file, root='none', debug=debug) def align(self, codon_align=False, debug=False, fill_gaps=False): ''' (1) Align sequences, remove non-reference insertions NB step 1 is skipped if a valid aln file is found (2) Translate (3) Write to multi-fasta CODON ALIGNMENT IS NOT IMPLEMENTED ''' fnameStripped = self.output_path + "_aligned_stripped.mfa" if self.try_to_restore: self.seqs.try_restore_align_from_disk(fnameStripped) if not hasattr(self.seqs, "aln"): if codon_align: self.seqs.codon_align() else: self.seqs.align(self.config["subprocess_verbosity_level"], debug=debug) # need to redo everything self.try_to_restore = False self.seqs.strip_non_reference() if fill_gaps: self.seqs.make_gaps_ambiguous() else: self.seqs.make_terminal_gaps_ambiguous() AlignIO.write(self.seqs.aln, fnameStripped, 'fasta') if not self.seqs.reference_in_dataset: self.seqs.remove_reference_from_alignment() # if outgroup is not None: # self.seqs.clock_filter(n_iqd=3, plot=False, max_gaps=0.05, root_seq=outgroup) self.seqs.translate() # creates self.seqs.translations # save additional translations - disabled for now # for name, msa in self.seqs.translations.iteritems(): # SeqIO.write(msa, self.output_path + "_aligned_" + name + ".mfa", "fasta") def get_pivots_via_spacing(self): try: time_interval = self.info["time_interval"] assert("pivot_spacing" in self.config) except AssertionError: self.log.fatal("Cannot space pivots without prividing \"pivot_spacing\" in the config") except KeyError: self.log.fatal("Cannot space pivots without a time interval in the prepared JSON") return np.arange(time_interval[1].year+(time_interval[1].month-1)/12.0, time_interval[0].year+time_interval[0].month/12.0, self.config["pivot_spacing"]) def restore_mutation_frequencies(self): if self.try_to_restore: try: with open(self.output_path + "_mut_freqs.pickle", 'rb') as fh: pickle_seqs = pickle.load(fh) assert(pickle_seqs == set(self.seqs.seqs.keys())) pickled = pickle.load(fh) assert(len(pickled) == 3) self.mutation_frequencies = pickled[0] self.mutation_frequency_confidence = pickled[1] self.mutation_frequency_counts = pickled[2] self.log.notify("Successfully restored mutation frequencies") return except IOError: pass except AssertionError as err: self.log.notify("Tried to restore mutation frequencies but failed: {}".format(err)) #no need to remove - we'll overwrite it shortly self.mutation_frequencies = {} self.mutation_frequency_confidence = {} self.mutation_frequency_counts = {} def estimate_mutation_frequencies(self, inertia=0.0, min_freq=0.01, stiffness=20.0, pivots=24, region="global", include_set={}): ''' calculate the frequencies of mutation in a particular region currently the global frequencies should be estimated first because this defines the set of positions at which frequencies in other regions are estimated. ''' if not hasattr(self.seqs, 'aln'): self.log.warn("Align sequences first") return def filter_alignment(aln, region=None, lower_tp=None, upper_tp=None): from Bio.Align import MultipleSeqAlignment tmp = aln if region is not None: if type(region)==str: tmp = [s for s in tmp if s.attributes['region']==region] elif type(region)==list: tmp = [s for s in tmp if s.attributes['region'] in region] else: self.log.warn("region must be string or list") return if lower_tp is not None: tmp = [s for s in tmp if np.mean(s.attributes['num_date'])>=lower_tp] if upper_tp is not None: tmp = [s for s in tmp if np.mean(s.attributes['num_date'])<upper_tp] return MultipleSeqAlignment(tmp) if not hasattr(self, 'pivots'): tps = np.array([np.mean(x.attributes['num_date']) for x in self.seqs.seqs.values()]) self.pivots=make_pivots(pivots, tps) # else: # self.log.notify('estimate_mutation_frequencies: using self.pivots') if not hasattr(self, 'mutation_frequencies'): self.restore_mutation_frequencies() # loop over nucleotide sequences and translations and calcuate # region specific frequencies of mutations above a certain threshold if type(region)==str: region_name = region region_match = region elif type(region)==tuple: region_name=region[0] region_match=region[1] else: self.log.warn("region must be string or tuple") return # loop over different alignment types for prot, aln in [('nuc',self.seqs.aln)] + self.seqs.translations.items(): if (region_name,prot) in self.mutation_frequencies: self.log.notify("Skipping Frequency Estimation for region \"{}\", protein \"{}\"".format(region_name, prot)) continue self.log.notify("Starting Frequency Estimation for region \"{}\", protein \"{}\"".format(region_name, prot)) # determine set of positions that have to have a frequency calculated if prot in include_set: tmp_include_set = [x for x in include_set[prot]] else: tmp_include_set = [] tmp_aln = filter_alignment(aln, region = None if region=='global' else region_match, lower_tp=self.pivots[0], upper_tp=self.pivots[-1]) if ('global', prot) in self.mutation_frequencies: tmp_include_set += set([pos for (pos, mut) in self.mutation_frequencies[('global', prot)]]) time_points = [np.mean(x.attributes['num_date']) for x in tmp_aln] if len(time_points)==0: self.log.notify('no samples in region {} (protein: {})'.format(region_name, prot)) self.mutation_frequency_counts[region_name]=np.zeros_like(self.pivots) continue # instantiate alignment frequency aln_frequencies = alignment_frequencies(tmp_aln, time_points, self.pivots, ws=max(2,len(time_points)//10), inertia=inertia, stiffness=stiffness, method='SLSQP') if prot=='nuc': # if this is a nucleotide alignment, set all non-canonical states to N A = aln_frequencies.aln A[~((A=='A')|(A=='C')|(A=='G')|(A=='T')|('A'=='-'))] = 'N' aln_frequencies.mutation_frequencies(min_freq=min_freq, include_set=tmp_include_set, ignore_char='N' if prot=='nuc' else 'X') self.mutation_frequencies[(region_name,prot)] = aln_frequencies.frequencies self.mutation_frequency_confidence[(region_name,prot)] = aln_frequencies.calc_confidence() self.mutation_frequency_counts[region_name]=aln_frequencies.counts self.log.notify("Saving mutation frequencies (pickle)") with open(self.output_path + "_mut_freqs.pickle", 'wb') as fh: pickle.dump(set(self.seqs.seqs.keys()), fh, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump((self.mutation_frequencies, self.mutation_frequency_confidence, self.mutation_frequency_counts), fh, protocol=pickle.HIGHEST_PROTOCOL) def global_frequencies(self, min_freq, average_global=False, inertia=2.0/12, stiffness=2.0*12): # set pivots and define groups of larger regions for frequency display pivots = self.get_pivots_via_spacing() acronyms = set([x[1] for x in self.info["regions"] if x[1]!=""]) region_groups = {str(x):[str(y[0]) for y in self.info["regions"] if y[1] == x] for x in acronyms} pop_sizes = {str(x):np.sum([y[-1] for y in self.info["regions"] if y[1] == x]) for x in acronyms} total_popsize = np.sum(pop_sizes.values()) # if global frequencies are to be calculated from the set of sequences, do the following if average_global==False: self.estimate_mutation_frequencies(pivots=pivots, min_freq=min_freq, inertia=np.exp(-inertia), stiffness=stiffness) for region in region_groups.iteritems(): self.estimate_mutation_frequencies(region=region, min_freq=min_freq, inertia=np.exp(-inertia), stiffness=stiffness) return # ELSE: # if global frequences are to be calculated from a weighted average of regional ones # the following applies: # determine sites whose frequencies need to be computed in all regions self.seqs.diversity_statistics() include_set = {} for prot in ['nuc'] + self.seqs.translations.keys(): include_set[prot] = np.where(np.sum(self.seqs.af[prot][:-2]**2, axis=0) <np.sum(self.seqs.af[prot][:-2], axis=0)**2-min_freq)[0] # estimate frequencies in individual regions for region in region_groups.iteritems(): self.estimate_mutation_frequencies(pivots=pivots, region=region, min_freq=min_freq, include_set=include_set, inertia=np.exp(-inertia), stiffness=stiffness) # perform a weighted average of frequencies across the regions to determine # global frequencies. # First: compute the weights accounting for seasonal variation and populations size weights = {region: np.array(self.mutation_frequency_counts[region], dtype = float) for region in acronyms} for region in weights: # map maximal count across time to 1.0, weigh by pop size weights[region] = np.maximum(0.1, weights[region]/weights[region].max()) weights[region]*=pop_sizes[region] # compute the normalizer total_weight = np.sum([weights[region] for region in acronyms],axis=0) # average regional frequencies to calculate global for prot in ['nuc'] + self.seqs.translations.keys(): gl_freqs, gl_counts, gl_confidence = {}, {}, {} all_muts = set() for region in acronyms: # list all unique mutations all_muts.update(self.mutation_frequencies[(region, prot)].keys()) for mut in all_muts: # compute the weighted average gl_freqs[mut] = np.sum([self.mutation_frequencies[(region, prot)][mut]*weights[region] for region in acronyms if mut in self.mutation_frequencies[(region, prot)]], axis=0)/total_weight gl_confidence[mut] = np.sqrt(np.sum([self.mutation_frequency_confidence[(region, prot)][mut]**2*weights[region] for region in acronyms if mut in self.mutation_frequencies[(region, prot)]], axis=0)/total_weight) gl_counts = np.sum([self.mutation_frequency_counts[region] for region in acronyms if mut in self.mutation_frequencies[(region, prot)]], axis=0) # save in mutation_frequency data structure self.mutation_frequencies[("global", prot)] = gl_freqs self.mutation_frequency_counts["global"] = gl_counts self.mutation_frequency_confidence[("global", prot)] = gl_confidence def save_tree_frequencies(self): """ Save tree frequencies to a pickle on disk. """ self.log.notify("Saving tree frequencies (pickle)") with open(self.output_path + "_tree_freqs.pickle", 'wb') as fh: pickle.dump(set(self.seqs.seqs.keys()), fh, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump((self.tree_frequencies, self.tree_frequency_confidence, self.tree_frequency_counts, self.pivots), fh, protocol=pickle.HIGHEST_PROTOCOL) def restore_tree_frequencies(self): try: assert(self.try_to_restore == True) with open(self.output_path + "_tree_freqs.pickle", 'rb') as fh: pickle_seqs = pickle.load(fh) assert(pickle_seqs == set(self.seqs.seqs.keys())) pickled = pickle.load(fh) assert(len(pickled) == 4) self.tree_frequencies = pickled[0] self.tree_frequency_confidence = pickled[1] self.tree_frequency_counts = pickled[2] self.pivots = pickled[3] self.log.notify("Successfully restored tree frequencies") return except IOError: pass except AssertionError as err: self.log.notify("Tried to restore tree frequencies but failed: {}".format(err)) #no need to remove - we'll overwrite it shortly self.tree_frequencies = {} self.tree_frequency_confidence = {} self.tree_frequency_counts = {} def estimate_tree_frequencies(self, region='global', pivots=24, stiffness=20.0): ''' estimate frequencies of clades in the tree, possibly region specific ''' if not hasattr(self, 'tree_frequencies'): self.restore_tree_frequencies() if region in self.tree_frequencies: self.log.notify("Skipping tree frequency estimation for region: %s" % region) return if not hasattr(self, 'pivots'): tps = np.array([np.mean(x.attributes['num_date']) for x in self.seqs.seqs.values()]) self.pivots=make_pivots(pivots, tps) self.log.notify('Estimate tree frequencies for %s: using self.pivots' % (region)) # Omit strains sampled prior to the first pivot from frequency calculations. if region=='global': node_filter_func = lambda node: node.attr["num_date"] >= self.pivots[0] else: node_filter_func = lambda node: (node.attr['region'] == region) and (node.attr["num_date"] >= self.pivots[0]) tree_freqs = tree_frequencies(self.tree.tree, self.pivots, method='SLSQP', node_filter = node_filter_func, ws = max(2,self.tree.tree.count_terminals()//10), stiffness = stiffness) tree_freqs.estimate_clade_frequencies() conf = tree_freqs.calc_confidence() self.tree_frequencies[region] = tree_freqs.frequencies self.tree_frequency_confidence[region] = conf self.tree_frequency_counts[region] = tree_freqs.counts self.save_tree_frequencies() def build_tree(self): ''' (1) instantiate a tree object (process.tree) (2) If newick file doesn't exist or isn't valid: build a newick tree (normally RAxML) (3) Make a TimeTree ''' self.tree = tree(aln=self.seqs.aln, proteins=self.proteins, verbose=self.config["subprocess_verbosity_level"]) newick_file = self.output_path + ".newick" if self.try_to_restore and os.path.isfile(newick_file):# and self.tree.check_newick(newick_file): self.log.notify("Newick file \"{}\" can be used to restore".format(newick_file)) else: self.log.notify("Building newick tree.") self.tree.build_newick(newick_file, **self.config["newick_tree_options"]) def clock_filter(self): if self.config["clock_filter"] == False: return self.tree.tt.clock_filter(reroot='best', n_iqd=self.config["clock_filter"]["n_iqd"], plot=self.config["clock_filter"]["plot"]) leaves = [x for x in self.tree.tree.get_terminals()] for n in leaves: if n.bad_branch: self.tree.tt.tree.prune(n) print('pruning leaf ', n.name) if self.config["clock_filter"]["remove_deep_splits"]: self.tree.tt.tree.ladderize() current_root = self.tree.tt.tree.root if sum([x.branch_length for x in current_root])>0.1 \ and sum([x.count_terminals() for x in current_root.clades[:-1]])<5: new_root = current_root.clades[-1] new_root.up=False self.tree.tt.tree.root = new_root with open(self.output_path+"_outliers.txt", 'a') as ofile: for x in current_root.clades[:-1]: ofile.write("\n".join([leaf.name for leaf in x.get_terminals()])+'\n') self.tree.tt.prepare_tree() def timetree_setup_filter_run(self): def try_restore(): try: assert(os.path.isfile(self.output_path + "_timetree.new")) assert(os.path.isfile(self.output_path + "_timetree.pickle")) except AssertionError: return False self.log.notify("Attempting to restore timetree") with open(self.output_path+"_timetree.pickle", 'rb') as fh: pickled = pickle.load(fh) try: assert(self.config["timetree_options"] == pickled["timetree_options"]) assert(self.config["clock_filter"] == pickled["clock_filter_options"]) #assert(set(self.seqs.sequence_lookup.keys()) == set(pickled["original_seqs"])) except AssertionError as e: print(e) self.log.warn("treetime is out of date - rerunning") return False # this (treetime) newick is _after_ clock filtering and remove_outliers_clades # so these methods should not be rerun here self.tree.tt_from_file(self.output_path + "_timetree.new", nodefile=None, root=None) try: self.tree.restore_timetree_node_info(pickled["nodes"]) except KeyError: self.log.warn("treetime node info missing - rerunning") return False self.log.notify("TreeTime successfully restored.") return True if "temporal_confidence" in self.config: self.config["timetree_options"]["confidence"] = True self.config["timetree_options"]["use_marginal"] = True if self.try_to_restore: success = try_restore() else: success = False if not success: self.log.notify("Setting up TimeTree") self.tree.tt_from_file(self.output_path + ".newick", nodefile=None, root="best") self.log.notify("Running Clock Filter") self.clock_filter() self.tree.remove_outlier_clades() # this is deterministic self.log.notify("Reconstructing Ancestral Sequences, branch lengths & dating nodes") self.tree.timetree(**self.config["timetree_options"]) # do we ever not want to use timetree?? If so: # self.tree.ancestral(**kwargs) instead of self.tree.timetree self.tree.save_timetree(fprefix=self.output_path, ttopts=self.config["timetree_options"], cfopts=self.config["clock_filter"]) self.tree.add_translations() self.tree.refine() self.tree.layout() def matchClades(self, clades, offset=-1): ''' finds branches in the tree corresponding to named clades by searching for the oldest node with a particular genotype. - params - clades: a dictionary with clade names as keys and lists of genoypes as values - offset: the offset to be applied to the position specification, typically -1 to conform with counting starting at 0 as opposed to 1 "clade_annotation" is a label to a specific node in the tree that is used to hang a text label in auspice "clade_membership" is an attribute of every node in the tree that defines clade membership, used as coloring in auspice ''' def match(node, genotype): return all([node.translations[gene][pos+offset]==state if gene in node.translations else node.sequence[pos+offset]==state for gene, pos, state in genotype]) ## Label root nodes for each clade as clade_annotation via clades_to_nodes ## NOTE clades_to_nodes is used in the (full) frequencies export self.clades_to_nodes = {} for clade_name, genotype in clades.iteritems(): matching_nodes = filter(lambda x:match(x,genotype), self.tree.tree.get_nonterminals()) matching_nodes.sort(key=lambda x:x.numdate if hasattr(x,'numdate') else x.dist2root) if len(matching_nodes): self.clades_to_nodes[clade_name] = matching_nodes[0] self.clades_to_nodes[clade_name].attr['clade_annotation'] = clade_name else: print('matchClades: no match found for ', clade_name, genotype) for allele in genotype: partial_matches = filter(lambda x:match(x,[allele]), self.tree.tree.get_nonterminals()) print('Found %d partial matches for allele '%len(partial_matches), allele) ## Now preorder traverse the tree with state replacement to set the clade_membership via clade_annotation for node in self.tree.tree.find_clades(): node.attr['clade_membership'] = 'unassigned' ordered_clades = sorted(self.clades_to_nodes.keys(), key=lambda name: self.clades_to_nodes[name].numdate) for clade_annotation in ordered_clades: for node in self.clades_to_nodes[clade_annotation].find_clades(order='preorder'): node.attr['clade_membership'] = clade_annotation def annotate_fitness(self): """Run the fitness prediction model and annotate the tree's nodes with fitness values. Returns the resulting fitness model instance. """ if not hasattr(self, "tree_frequencies"): self.log.warn("Could not find tree frequencies.") return kwargs = { "tree": self.tree.tree, "frequencies": self.tree_frequencies, "time_interval": self.info["time_interval"], "pivots": np.around(self.pivots, 2) } if "predictors" in self.config: kwargs["predictor_input"] = self.config["predictors"] if "epitope_mask" in self.config: kwargs["epitope_masks_fname"] = self.config["epitope_mask"] if "epitope_mask_version" in self.config: kwargs["epitope_mask_version"] = self.config["epitope_mask_version"] if "tolerance_mask_version" in self.config: kwargs["tolerance_mask_version"] = self.config["tolerance_mask_version"] if self.config["subprocess_verbosity_level"] > 0: kwargs["verbose"] = 1 model = fitness_model(**kwargs) model.predict() return model def make_control_json(self, controls): controls_json = {} for super_cat, fields in controls.iteritems(): cat_count = {} for n in self.tree.tree.get_terminals(): tmp = cat_count for field in fields: tmp["name"] = field if field in n.attr: cat = n.attr[field] else: cat='unknown' if cat in tmp: tmp[cat]['count']+=1 else: tmp[cat] = {'count':1, 'subcats':{}} tmp = tmp[cat]['subcats'] controls_json[super_cat] = cat_count return controls_json def auspice_export(self): ''' export the tree, sequences, frequencies to json files for auspice visualization ''' prefix = os.path.join(self.config["output"]["auspice"], self.info["prefix"]) indent = 2 ## ENTROPY (alignment diversity) ## if "entropy" in self.config["auspice"]["extra_jsons"]: self.seqs.export_diversity(fname=prefix+'_entropy.json', indent=indent) ## TREE & SEQUENCES ## if hasattr(self, 'tree') and self.tree is not None: self.tree.export( path = prefix, extra_attr = self.config["auspice"]["extra_attr"] + ["muts", "aa_muts","attr", "clade"], indent = indent, write_seqs_json = "sequences" in self.config["auspice"]["extra_jsons"] ) ## FREQUENCIES ## if "frequencies" in self.config["auspice"]["extra_jsons"]: export_frequency_json(self, prefix=prefix, indent=indent) export_tip_frequency_json(self, prefix=prefix, indent=indent) ## METADATA ## export_metadata_json(self, prefix=prefix, indent=indent) def run_geo_inference(self): if self.config["geo_inference"] == False: self.log.notify("Not running geo inference") return try: kwargs = {"report_confidence": self.config["geo_inference_options"]["confidence"]} except KeyError: kwargs = {} ## try load pickle... try: assert(self.try_to_restore == True) with open(self.output_path + "_mugration.pickle", 'rb') as fh: options = pickle.load(fh) restored_data = pickle.load(fh) assert(options == self.config["geo_inference_options"]) assert(set(restored_data.keys()) == set([x.name for x in self.tree.tree.find_clades()])) except IOError: restored_data = False except AssertionError as err: restored_data = False self.log.notify("Tried to restore mutation frequencies but failed: {}".format(err)) # only run geo inference if lat + longs are defined. if not self.lat_longs or len(self.lat_longs)==0: self.log.notify("no geo inference - no specified lat/longs") return for geo_attr in self.config["geo_inference"]: try: self.tree.restore_geo_inference(restored_data, geo_attr, self.config["geo_inference_options"]["confidence"]) self.log.notify("Restored geo inference for {}".format(geo_attr)) except KeyError: try: kwargs["root_state"] = self.config["geo_inference_options"]["root_state"][geo_attr] except KeyError: pass self.log.notify("running geo inference for {} with parameters {}".format(geo_attr, kwargs)) self.tree.geo_inference(geo_attr, **kwargs) # SAVE MUGRATION RESULTS: attrs = set(self.tree.mugration_attrs) try: data = {} for node in self.tree.tree.find_clades(): assert(len(attrs - set(node.attr.keys()))==0) data[node.name] = {x:node.attr[x] for x in attrs} except AssertionError: self.log.warn("Error saving mugration data - will not be able to restore") return with open(self.output_path + "_mugration.pickle", 'wb') as fh: pickle.dump(self.config["geo_inference_options"], fh, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump(data, fh, protocol=pickle.HIGHEST_PROTOCOL) self.log.notify("Saved mugration data (pickle)") def save_as_nexus(self): save_as_nexus(self.tree.tree, self.output_path + "_timeTree.nex") if __name__=="__main__": print("This shouldn't be called as a script.")
35,592
10,422
# -*- coding: utf-8 -*- # Copyright (c) 2015, nodux and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe import throw, _ class NoduxItemPrice(Document): def validate(self): self.validate_item() self.validate_price_list() self.check_duplicate_item() self.update_price_list_details() self.update_item_details() def validate_item(self): if not frappe.db.exists("Item", self.item_code): throw(_("Item {0} not found").format(self.item_code)) def validate_price_list(self): enabled = frappe.db.get_value("Nodux Price List", self.price_list, "enabled") if not enabled: throw(_("Price List {0} is disabled").format(self.price_list)) def check_duplicate_item(self): if frappe.db.sql("""select name from `tabNodux Item Price` where item_code=%s and price_list=%s and name!=%s""", (self.item_code, self.price_list, self.name)): frappe.throw(_("Item {0} appears multiple times in Price List {1}").format(self.item_code, self.price_list), NoduxItemPriceDuplicateItem) # def update_price_list_details(self): # self.buying, self.selling, self.currency = \ # #frappe.db.get_value("Nodux Price List", {"name": self.price_list, "enabled": 1}, # frappe.db.get_value("Nodux Price List", {"name": self.price_list}, # ["buying", "selling", "currency"]) def update_price_list_details(self): self.buying, self.selling, self.currency = \ frappe.db.get_value("Nodux Price List", {"name": self.price_list, "enabled": 1}, ["buying", "selling", "currency"]) def update_item_details(self): self.item_name, self.item_description = frappe.db.get_value("Item", self.item_code, ["item_name", "description"])
1,777
666
from flask import render_template from flask_mail import Message from main import mail, app def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body mail.send(msg) def send_password_reset_email(clinic): token = clinic.get_password_reset_token() send_email('Foster Finder - Reset Your Password', sender=app.config['ADMIN'], recipients=[clinic.email], text_body=render_template('reset_password_email.txt', clinic=clinic, token=token), html_body=render_template('reset_password_email.html', clinic=clinic, token=token))
799
224
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import Union from cdm.persistence.cdmfolder.types.projections.operation_base import OperationBase from cdm.persistence.cdmfolder.types.type_attribute import TypeAttribute from cdm.persistence.cdmfolder.types.entity_attribute import EntityAttribute from cdm.persistence.cdmfolder.types import AttributeGroupReference class OperationAddArtifactAttribute(OperationBase): """OperationAddArtifactAttribute class""" def __init__(self): super().__init__() self.newAttribute = None # type: Union[str, AttributeGroupReference, TypeAttribute, EntityAttribute] self.insertAtTop = None
779
196
""" Query functions to run against ElasticSearch """ # pylint: disable=invalid-name from ebr_connector.schema.build_results import BuildResults detailed_build_info = { "includes": [ "br_build_date_time", "br_job_name", "br_job_url_key", "br_source", "br_build_id_key", "br_platform", "br_product", "br_status_key", "br_version_key", "br_tests_object", ], "excludes": [ "lhi*", "br_tests_object.br_tests_passed_object.*", "br_tests_object.br_tests_failed_object.*", "br_tests_object.br_tests_skipped_object.*", "br_tests_object.br_suites_object.*", ], } def make_query( # pylint: disable=too-many-arguments index, combined_filter, includes, excludes, agg=None, size=1, start=0 ): """ Simplifies the execution and usage of a typical query, including cleaning up the results. Args: index: index to search on combined_filter: combined set of filters to run the query with includes: list of fields to include on the results (keep as small as possible to improve execution time) excludes: list of fields to explicitly exclude from the results size: [Optional] number of results to return. Defaults to 1. Returns: List of dicts with results of the query. """ search = BuildResults().search(index=index) search = search.source(includes=includes, excludes=excludes) if agg: search = search.aggs.metric("fail_count", agg) search = search.query("bool", filter=[combined_filter])[0:1] search = search[start : start + size] response = search.execute() results = [] if agg: results = response["aggregations"]["fail_count"]["buckets"] else: for hit in response["hits"]["hits"]: results.append(hit["_source"]) return results
1,900
582
#!/usr/bin/env python3 import socket import sys import time import argparse # action can be reflect or drop action = "drop" test = 0 def test_data (data, n_rcvd): n_read = len (data); for i in range(n_read): expected = (n_rcvd + i) & 0xff byte_got = ord (data[i]) if (byte_got != expected): print("Difference at byte {}. Expected {} got {}" .format(n_rcvd + i, expected, byte_got)) return n_read def handle_connection (connection, client_address): print("Received connection from {}".format(repr(client_address))) n_rcvd = 0 try: while True: data = connection.recv(4096) if not data: break; if (test == 1): n_rcvd += test_data (data, n_rcvd) if (action != "drop"): connection.sendall(data) finally: connection.close() def run_tcp_server(ip, port): print("Starting TCP server {}:{}".format(repr(ip), repr(port))) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = (ip, int(port)) sock.bind(server_address) sock.listen(1) while True: connection, client_address = sock.accept() handle_connection (connection, client_address) def run_udp_server(ip, port): print("Starting UDP server {}:{}".format(repr(ip), repr(port))) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = (ip, int(port)) sock.bind(server_address) while True: data, addr = sock.recvfrom(4096) if (action != "drop"): #snd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto (data, addr) def run_server(ip, port, proto): if (proto == "tcp"): run_tcp_server(ip, port) elif (proto == "udp"): run_udp_server(ip, port) def prepare_data(power): buf = [] for i in range (0, pow(2, power)): buf.append(i & 0xff) return bytearray(buf) def run_tcp_client(ip, port): print("Starting TCP client {}:{}".format(repr(ip), repr(port))) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (ip, int(port)) sock.connect(server_address) data = prepare_data(16) n_rcvd = 0 n_sent = len (data) try: sock.sendall(data) timeout = time.time() + 2 while n_rcvd < n_sent and time.time() < timeout: tmp = sock.recv(1500) tmp = bytearray (tmp) n_read = len(tmp) for i in range(n_read): if (data[n_rcvd + i] != tmp[i]): print("Difference at byte {}. Sent {} got {}" .format(n_rcvd + i, data[n_rcvd + i], tmp[i])) n_rcvd += n_read if (n_rcvd < n_sent or n_rcvd > n_sent): print("Sent {} and got back {}".format(n_sent, n_rcvd)) else: print("Got back what we've sent!!"); finally: sock.close() def run_udp_client(ip, port): print("Starting UDP client {}:{}".format(repr(ip), repr(port))) n_packets = 100 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = (ip, int(port)) data = prepare_data(10) try: for i in range (0, n_packets): sock.sendto(data, server_address) finally: sock.close() def run_client(ip, port, proto): if (proto == "tcp"): run_tcp_client(ip, port) elif (proto == "udp"): run_udp_client(ip, port) def run(mode, ip, port, proto): if (mode == "server"): run_server (ip, port, proto) elif (mode == "client"): run_client (ip, port, proto) else: raise Exception("Unknown mode. Only client and server supported") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-m', action='store', dest='mode') parser.add_argument('-i', action='store', dest='ip') parser.add_argument('-p', action='store', dest='port') parser.add_argument('-proto', action='store', dest='proto') parser.add_argument('-a', action='store', dest='action') parser.add_argument('-t', action='store', dest='test') results = parser.parse_args() action = results.action test = results.test run(results.mode, results.ip, results.port, results.proto) #if (len(sys.argv)) < 4: # raise Exception("Usage: ./dummy_app <mode> <ip> <port> [<action> <test>]") #if (len(sys.argv) == 6): # action = sys.argv[4] # test = int(sys.argv[5]) #run (sys.argv[1], sys.argv[2], int(sys.argv[3]))
4,714
1,658
import torch from torch.utils import data import numpy as np import os import cv2 import torchvision.transforms as transforms from PIL import Image import random from PIL import ImageFile def get_transform(opt): transform_list = [] if opt.resize_or_crop == 'resize_and_crop': osize = [opt.loadSize_1, opt.loadSize_2] transform_list.append(transforms.Resize(osize, Image.BICUBIC)) transform_list.append(transforms.RandomCrop((opt.fineSize_1, opt.fineSize_2 ))) elif opt.resize_or_crop == 'crop': transform_list.append(transforms.RandomCrop(opt.fineSize)) elif opt.resize_or_crop == 'scale_width': transform_list.append(transforms.Lambda( lambda img: __scale_width(img, opt.fineSize))) elif opt.resize_or_crop == 'scale_width_and_crop': transform_list.append(transforms.Lambda( lambda img: __scale_width(img, opt.loadSize))) transform_list.append(transforms.RandomCrop(opt.fineSize)) elif opt.resize_or_crop == 'none': transform_list.append(transforms.Lambda( lambda img: __adjust(img))) else: raise ValueError('--resize_or_crop %s is not a valid option.' % opt.resize_or_crop) # if opt.isTrain and not opt.no_flip: # print("="*1000) # # exit() # transform_list.append(transforms.RandomHorizontalFlip()) transform_list += [transforms.ToTensor()] # transforms.Normalize((0.5, 0.5, 0.5), # (0.5, 0.5, 0.5))] return transforms.Compose(transform_list) class Dataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, opt): 'Initialization' self.transform = get_transform(opt) self.dataroot = opt.dataroot self.AB_paths = os.listdir(opt.dataroot) self.train = opt.train self.opt = opt def __len__(self): 'Denotes the total number of samples' return len(self.AB_paths) def __getitem__(self, index): AB_path = self.dataroot + '/' + self.AB_paths[index] AB = Image.open(AB_path).convert('RGB') if self.train: w, h = AB.size w2 = int(w / 2) B = AB.crop((w2, 0, w, h)).resize((self.opt.loadSize_1, self.opt.loadSize_2), Image.BICUBIC) else: B = AB seed = random.randint(0,2**32) random.seed(seed) # B = transforms.ToTensor()(B) B = self.transform(B) w_offset = random.randint(0, max(0, self.opt.loadSize_1 - self.opt.fineSize_1 - 1)) h_offset = random.randint(0, max(0, self.opt.loadSize_2 - self.opt.fineSize_2 - 1)) B = B[:, h_offset:h_offset + self.opt.fineSize_2, w_offset:w_offset + self.opt.fineSize_1] return B, 0
2,806
974
################################################################################################################################################################ # @project Open Space Toolkit ▸ Physics # @file bindings/python/test/time/test_time.py # @author Lucas Brémond <lucas@loftorbital.com> # @license Apache License 2.0 ################################################################################################################################################################ import pytest from ostk.physics.time import Time ################################################################################################################################################################ def test_time_constructors (): assert Time(0, 0, 0) is not None ################################################################################################################################################################ def test_time_undefined (): assert Time.undefined() is not None ################################################################################################################################################################ def test_time_midnight (): assert Time.midnight() is not None ################################################################################################################################################################ def test_time_noon (): assert Time.noon() is not None ################################################################################################################################################################ def test_time_parse (): assert Time.parse('00:00:00') is not None assert Time.parse('00:00:00', Time.Format.Standard) is not None assert Time.parse('00:00:00', Time.Format.ISO8601) is not None ################################################################################################################################################################ def test_time_operators (): time = Time(0, 0, 0) assert (time == time) is not None assert (time != time) is not None ################################################################################################################################################################ def test_time_is_defined (): time = Time(0, 0, 0) assert time.is_defined() is not None ################################################################################################################################################################ def test_time_get_hour (): time = Time(0, 0, 0) assert time.get_hour() is not None ################################################################################################################################################################ def test_time_get_minute (): time = Time(0, 0, 0) assert time.get_minute() is not None ################################################################################################################################################################ def test_time_get_second (): time = Time(0, 0, 0) assert time.get_second() is not None ################################################################################################################################################################ def test_time_get_millisecond (): time = Time(0, 0, 0) assert time.get_millisecond() is not None ################################################################################################################################################################ def test_time_get_microsecond (): time = Time(0, 0, 0) assert time.get_microsecond() is not None ################################################################################################################################################################ def test_time_get_nanosecond (): time = Time(0, 0, 0) assert time.get_nanosecond() is not None ################################################################################################################################################################ def test_time_get_floating_seconds (): time = Time(0, 0, 0) assert time.get_floating_seconds() is not None ################################################################################################################################################################ def test_time_to_string (): time = Time(0, 0, 0) assert time.to_string() is not None assert time.to_string(Time.Format.Standard) is not None assert time.to_string(Time.Format.ISO8601) is not None ################################################################################################################################################################ def test_time_set_hour (): time = Time(0, 0, 0) time.set_hour(1) ################################################################################################################################################################ def test_time_set_minute (): time = Time(0, 0, 0) time.set_minute(1) ################################################################################################################################################################ def test_time_set_second (): time = Time(0, 0, 0) time.set_second(1) ################################################################################################################################################################ def test_time_set_millisecond (): time = Time(0, 0, 0) time.set_millisecond(1) ################################################################################################################################################################ def test_time_set_microsecond (): time = Time(0, 0, 0) time.set_microsecond(1) ################################################################################################################################################################ def test_time_set_nanosecond (): time = Time(0, 0, 0) time.set_nanosecond(1) ################################################################################################################################################################
6,290
1,260
from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from datetime import datetime, timedelta from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.header import Header import psycopg2.extensions import psycopg2 import smtplib import pickle import select import os EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS') EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD') db_conn = psycopg2.connect( host = "localhost", port = "6432", dbname = "server", user = "hideyoshi", password = "vhnb2901" ) db_conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) db = db_conn.cursor() db.execute('LISTEN novo_pedido') while 1: if not select.select([db_conn], [], [], 5) == ([], [], []): db_conn.poll() while db_conn.notifies: notify = db_conn.notifies.pop() id_pedido, c_cpf, id_servico, quantidade, valor_total, date = notify.payload.replace('(','').replace(')','').split(',') year,month,day = date.replace('"','').split()[0].split('-') hour,minute,sec = date.replace('"','').split()[1].split(':') sec = sec.split('.')[0] date = datetime(int(year),int(month),int(day),int(hour),int(minute),int(sec)) months = [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Augosto", "Setembro", "Outubro", "Novembro", "Dezembro"] month = months[date.month] week = [ "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"] dow = week[date.weekday()] db.execute('SELECT DISTINCT nome FROM cliente, pedido WHERE cliente.cpf = pedido.cpf and pedido.id ='+id_pedido+';') c_nome = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') db.execute('SELECT DISTINCT email FROM cliente, pedido WHERE cliente.cpf = pedido.cpf and pedido.id ='+id_pedido+';') c_email = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') db.execute('SELECT DISTINCT nome FROM servico, pedido WHERE servico.id = id_servico AND pedido.id = '+id_pedido+';') p_nome = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') db.execute("SELECT DISTINCT endereco.logradouro,endereco.complemento,endereco.numero,endereco.cidade,' - ',endereco.estado FROM endereco, cliente, pedido WHERE cliente.cpf = pedido.cpf AND cliente.id_endereco = endereco.id AND pedido.id = "+id_pedido+";") endereco = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Compra realizada com Sucesso' msgRoot['From'] = EMAIL_ADDRESS msgRoot['To'] = c_email message = """\ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <!--[if gte mso 9]><xml><o:OfficeDocumentSettings><o:AllowPNG/><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml><![endif]--> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <meta content="width=device-width" name="viewport"/> <!--[if !mso]><!--> <meta content="IE=edge" http-equiv="X-UA-Compatible"/> <!--<![endif]--> <title></title> <!--[if !mso]><!--> <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet" type="text/css"/> <!--<![endif]--> <style type="text/css"> body { margin: 0; padding: 0; } table, td, tr { vertical-align: top; border-collapse: collapse; } * { line-height: inherit; } a[x-apple-data-detectors=true] { color: inherit !important; text-decoration: none !important; } </style> <style id="media-query" type="text/css"> @media (max-width: 670px) { .block-grid, .col { min-width: 320px !important; max-width: 100% !important; display: block !important; } .block-grid { width: 100% !important; } .col { width: 100% !important; } .col>div { margin: 0 auto; } img.fullwidth, img.fullwidthOnMobile { max-width: 100% !important; } .no-stack .col { min-width: 0 !important; display: table-cell !important; } .no-stack.two-up .col { width: 50% !important; } .no-stack .col.num4 { width: 33% !important; } .no-stack .col.num8 { width: 66% !important; } .no-stack .col.num4 { width: 33% !important; } .no-stack .col.num3 { width: 25% !important; } .no-stack .col.num6 { width: 50% !important; } .no-stack .col.num9 { width: 75% !important; } .video-block { max-width: none !important; } .mobile_hide { min-height: 0px; max-height: 0px; max-width: 0px; display: none; overflow: hidden; font-size: 0px; } .desktop_hide { display: block !important; max-height: none !important; } } </style> </head> <body class="clean-body" style="margin: 0; padding: 0; -webkit-text-size-adjust: 100%; background-color: #482c71;"> <!--[if IE]><div class="ie-browser"><![endif]--> <table bgcolor="#482c71" cellpadding="0" cellspacing="0" class="nl-container" role="presentation" style="table-layout: fixed; vertical-align: top; min-width: 320px; Margin: 0 auto; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: #482c71; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top;" valign="top"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center" style="background-color:#482c71"><![endif]--> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:0px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 650px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:0px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div class="mobile_hide"> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" height="15" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 0px solid transparent; height: 15px; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td height="15" style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 1px solid #C879F1; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:10px; padding-bottom:0px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:1px solid #C879F1; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:10px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth fixedwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--><img align="center" alt="Image" border="0" class="center autowidth fixedwidth" src="cid:swirls_1.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 618px; display: block;" title="Image" width="618"/> <div style="font-size:1px;line-height:20px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:5px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:0px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center fixedwidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Image" border="0" class="center fixedwidth" src="cid:logoflower.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 259px; display: block;" title="Image" width="259"/> <div style="font-size:1px;line-height:20px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:40px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:40px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 1px dotted #C879F1; width: 95%;" valign="top" width="95%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 30px; padding-bottom: 15px; font-family: serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:30px;padding-right:40px;padding-bottom:15px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; word-break: break-word; text-align: center; font-family: Merriwheater, Georgia, serif; font-size: 30px; mso-line-height-alt: 45px; margin: 0;"><span style="font-size: 30px; color: #00ad99;">SUA RESERVA</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 5px; padding-bottom: 20px; font-family: 'Trebuchet MS', Tahoma, sans-serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:1.5;padding-top:5px;padding-right:40px;padding-bottom:20px;padding-left:40px;"> <div style="font-size: 12px; line-height: 1.5; font-family: 'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="font-size: 20px; line-height: 1.5; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 30px; margin: 0;"><span style="font-size: 20px;"><span style="font-size: 18px;">"""+dow+", "+day+" "+month+" "+year+"""</span><br/><span style="font-size: 18px;">Serviço: """+p_nome+"""</span><br/><span style="font-size: 18px;">Duração: """+date.strftime("%H:%M")+" - "+(date+timedelta(hours=2)).strftime("%H:%M")+"""</span><br/></span></p> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:30px;padding-right:40px;padding-bottom:15px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; word-break: break-word; text-align: center; font-family: Merriwheater, Georgia, serif; font-size: 30px; mso-line-height-alt: 45px; margin: 0;"><span style="font-size: 30px; color: #00ad99;">VALOR</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 5px; padding-bottom: 20px; font-family: 'Trebuchet MS', Tahoma, sans-serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:1.5;padding-top:5px;padding-right:40px;padding-bottom:20px;padding-left:40px;"> <div style="font-size: 12px; line-height: 1.5; font-family: 'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="font-size: 20px; line-height: 1.5; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 30px; margin: 0;"><span style="font-size: 20px;"><span style="font-size: 18px;">R$ """+valor_total+"""</span><br/></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth fullwidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--> <div style="font-size:1px;line-height:10px"> </div><img align="center" alt="Image" border="0" class="center autowidth fullwidth" src="cid:diveinto.jpeg" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 648px; display: block;" title="Image" width="648"/> <!--[if mso]></td></tr></table><![endif]--> </div> <div class="mobile_hide"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 55px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#FFFFFF;font-family:'Merriwheater', 'Georgia', serif;line-height:1.2;padding-top:55px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: 'Merriwheater', 'Georgia', serif; font-size: 12px; color: #FFFFFF; mso-line-height-alt: 14px;"> <p style="font-size: 38px; line-height: 1.2; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 46px; margin: 0;"><span style="font-size: 38px;">DIVE INTO RELAX</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top: 15px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#FFFFFF;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:15px;padding-right:0px;padding-bottom:0px;padding-left:0px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #FFFFFF; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 28px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 34px; margin: 0;"><span style="font-size: 28px;"><em><span style="color: #00ad99;"><span style="">Enjoy Your Day Spa</span></span></em></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:55px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:55px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 10px; padding-bottom: 20px; font-family: serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:10px;padding-right:40px;padding-bottom:20px;padding-left:40px;"> <div style="font-size: 12px; line-height: 1.5; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="font-size: 18px; line-height: 1.5; word-break: break-word; text-align: center; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 27px; margin: 0;"><span style="font-size: 18px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elementum nisl id neque ullamcorper, vel mattis nisl rutrum. Sed pulvinar aliquam dolor et euismod.</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #3f2765;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:#3f2765;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:#3f2765"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:#3f2765;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:30px; padding-bottom:5px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:30px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center fixedwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--> <div style="font-size:1px;line-height:15px"> </div><img align="center" alt="Image" border="0" class="center fixedwidth" src="cid:swirlup.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 291px; display: block;" title="Image" width="291"/> <div style="font-size:1px;line-height:10px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 30px; padding-bottom: 30px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.2;padding-top:30px;padding-right:10px;padding-bottom:30px;padding-left:10px;"> <div style="line-height: 1.2; font-family: 'Merriwheater', 'Georgia', serif; font-size: 12px; color: #ffffff; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 30px; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 36px; margin: 0;"><span style="font-size: 30px;">TRATAMENTOS</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid four-up" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #3f2765;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:#3f2765;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:#3f2765"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid #C879F1; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 161px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid #C879F1; border-right:0px solid transparent; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:bea_1.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Head Massage</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">50$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 162px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:feet.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Feet Treatment</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">65$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 162px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:massagstone.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Stone massage</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">20$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid ; border-left: 0px solid ; border-bottom: 0px solid ; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 161px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid ; border-left:0px solid ; border-bottom:0px solid ; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:face.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Stone massage</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">35$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #3f2765;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:#3f2765;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:#3f2765"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:#3f2765;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:40px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:0px; padding-bottom:40px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center fixedwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--> <div style="font-size:1px;line-height:15px"> </div><img align="center" alt="Image" border="0" class="center fixedwidth" src="cid:swirl.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 291px; display: block;" title="Image" width="291"/> <div style="font-size:1px;line-height:10px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 1px solid #C879F1; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:0px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:1px solid #C879F1; border-right:1px solid #C879F1; padding-top:0px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 35px; padding-bottom: 30px; font-family: serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:35px;padding-right:40px;padding-bottom:30px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 14px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 21px; margin: 0;"><span style="font-size: 14px;"><span style="font-size: 14px;"><em><span style="color: #00ad99; font-size: 14px;"><strong>Flower Spa</strong></span> </em>- Barkley street, 67 - Seattle</span></span></p> <p style="line-height: 1.5; font-size: 18px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 27px; margin: 0;"><span style="font-size: 18px;"><span style="font-size: 14px;">www.example.com | bookings@example.com</span><br/><span style="font-size: 14px;">© All rights reserved </span><br/></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <div align="center" class="img-container center autowidth fullwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--><img align="center" alt="Image" border="0" class="center autowidth fullwidth" src="cid:swirls_2.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 618px; display: block;" title="Image" width="618"/> <div style="font-size:1px;line-height:10px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top:10px; padding-bottom:10px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 650px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:10px; padding-bottom:10px; padding-right: 10px; padding-left: 10px;"> <!--<![endif]--> <div class="mobile_hide"> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" height="15" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 0px solid transparent; height: 15px; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td height="15" style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> </td> </tr> </tbody> </table> <!--[if (IE)]></div><![endif]--> </body> </html>""" msgText = MIMEText(message, 'html') msgRoot.attach(msgText) images = [ ["./images/bea_1.png", "<bea_1.png>"], ["./images/diveinto.jpeg", "<diveinto.jpeg>"], ["./images/face.png", "<face.png>"], ["./images/feet.png", "<feet.png>"], ["./images/logoflower.png", "<logoflower.png>"], ["./images/massagstone.png", "<massagstone.png>"], ["./images/swirl.png", "<swirl.png>"], ["./images/swirls_1.png", "<swirls_1.png>"], ["./images/swirls_2.png", "<swirls_2.png>"], ["./images/swirlup.png", "<swirlup.png>"] ] for image in images: with open(image[0],'rb') as f: msgImage = MIMEImage(f.read()) f.close() msgImage.add_header('Content-ID', image[1]) msgRoot.attach(msgImage) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msgRoot) smtp.quit() credentials = pickle.load(open("./token.pkl","rb")) service = build("calendar","v3",credentials=credentials) id = service.calendarList().list().execute()['items'][0]['id'] event = { 'summary': 'Horário marcado '+c_nome, 'location': endereco, 'description': 'Horário marcado com '+c_nome+' para '+p_nome+'.', 'start': { 'dateTime': date.strftime("%Y-%m-%dT%H:%M:%S"), 'timeZone': "America/Sao_Paulo", }, 'end': { 'dateTime': (date + timedelta(hours=4)).strftime("%Y-%m-%dT%H:%M:%S"), 'timeZone': "America/Sao_Paulo", }, 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'email', 'minutes': 60}, {'method': 'popup', 'minutes': 30}, ], }, } event = service.events().insert(calendarId=id, body=event).execute()
61,602
23,378
from datetime import datetime, timedelta from flask import current_app import jwt from api import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(128), unique=True, nullable=False) email = db.Column(db.String(128), unique=True, nullable=False) password_hash = db.Column(db.String(255), nullable=False) active = db.Column(db.Boolean(), default=True, nullable=False) created_date = db.Column( db.DateTime, default=datetime.utcnow, nullable=False ) def __init__(self, username, email, password): self.username = username self.email = email self.password_hash = bcrypt.generate_password_hash( password, current_app.config.get("BCRYPT_LOG_ROUNDS") ).decode() def to_json(self): return { "id": self.id, "username": self.username, "email": self.email, "active": self.active, } def encode_auth_token(self): try: payload = { "exp": datetime.utcnow() + timedelta( days=current_app.config.get("TOKEN_EXPIRATION_DAYS"), seconds=current_app.config.get("TOKEN_EXPIRATION_SECONDS"), ), "iat": datetime.utcnow(), "sub": self.id, } return jwt.encode( payload, current_app.config.get("SECRET_KEY"), algorithm="HS256", ) except Exception as e: return e @staticmethod def decode_auth_token(auth_token): try: payload = jwt.decode( auth_token, current_app.config.get("SECRET_KEY") ) return payload["sub"] except jwt.ExpiredSignatureError: return "Signature expired" except jwt.InvalidTokenError: return "Invalid token"
2,022
595
import ccs team = ccs.team(raw_input("Team Number: ")) summary = team.summary print "Team {} ({} {}) - {} images ({} points) - {}/{} {}".format( summary.number, summary.division, summary.location, summary.images, summary.score, summary.playtime, summary.scoretime, summary.warn) for image in team.images: print "\t{}: {}/{} vulns in {} ({} points, {} penalties) {}".format( image.name, image.found, image.found+image.remaining, image.time, image.score, image.penalties, image.warn)
522
169
# Copyright 2015, 2017 IBM Corp. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet from oslo_log import log as logging from pypowervm.tasks import cna as pvm_cna from pypowervm.wrappers import managed_system as pvm_ms from pypowervm.wrappers import network as pvm_net from taskflow import task from nova import conf as cfg from nova import exception from nova.virt.powervm import vif from nova.virt.powervm import vm LOG = logging.getLogger(__name__) CONF = cfg.CONF SECURE_RMC_VSWITCH = 'MGMTSWITCH' SECURE_RMC_VLAN = 4094 class PlugVifs(task.Task): """The task to plug the Virtual Network Interfaces to a VM.""" def __init__(self, virt_api, adapter, instance, network_infos): """Create the task. Provides 'vm_cnas' - the list of the Virtual Machine's Client Network Adapters as they stand after all VIFs are plugged. May be None, in which case the Task requiring 'vm_cnas' should discover them afresh. :param virt_api: The VirtAPI for the operation. :param adapter: The pypowervm adapter. :param instance: The nova instance. :param network_infos: The network information containing the nova VIFs to create. """ self.virt_api = virt_api self.adapter = adapter self.instance = instance self.network_infos = network_infos or [] self.crt_network_infos, self.update_network_infos = [], [] # Cache of CNAs that is filled on initial _vif_exists() call. self.cnas = None super(PlugVifs, self).__init__( name='plug_vifs', provides='vm_cnas', requires=['lpar_wrap']) def _vif_exists(self, network_info): """Does the instance have a CNA for a given net? :param network_info: A network information dict. This method expects it to contain key 'address' (MAC address). :return: True if a CNA with the network_info's MAC address exists on the instance. False otherwise. """ if self.cnas is None: self.cnas = vm.get_cnas(self.adapter, self.instance) vifs = self.cnas return network_info['address'] in [vm.norm_mac(v.mac) for v in vifs] def execute(self, lpar_wrap): # Check to see if the LPAR is OK to add VIFs to. modifiable, reason = lpar_wrap.can_modify_io() if not modifiable: LOG.error("Unable to create VIF(s) for instance in the system's " "current state. The reason from the system is: %s", reason, instance=self.instance) raise exception.VirtualInterfaceCreateException() # We will have two types of network infos. One is for newly created # vifs. The others are those that exist, but should be re-'treated' for network_info in self.network_infos: if self._vif_exists(network_info): self.update_network_infos.append(network_info) else: self.crt_network_infos.append(network_info) # If there are no vifs to create or update, then just exit immediately. if not self.crt_network_infos and not self.update_network_infos: return [] # For existing VIFs that we just need to update, run the plug but do # not wait for the neutron event as that likely won't be sent (it was # already done). for network_info in self.update_network_infos: LOG.info("Updating VIF with mac %s for instance.", network_info['address'], instance=self.instance) vif.plug(self.adapter, self.instance, network_info, new_vif=False) # For the new VIFs, run the creates (and wait for the events back) try: with self.virt_api.wait_for_instance_event( self.instance, self._get_vif_events(), deadline=CONF.vif_plugging_timeout, error_callback=self._vif_callback_failed): for network_info in self.crt_network_infos: LOG.info('Creating VIF with mac %s for instance.', network_info['address'], instance=self.instance) new_vif = vif.plug( self.adapter, self.instance, network_info, new_vif=True) if self.cnas is not None: self.cnas.append(new_vif) except eventlet.timeout.Timeout: LOG.error('Error waiting for VIF to be created for instance.', instance=self.instance) raise exception.VirtualInterfaceCreateException() return self.cnas def _vif_callback_failed(self, event_name, instance): LOG.error('VIF Plug failure for callback on event %s for instance.', event_name, instance=self.instance) if CONF.vif_plugging_is_fatal: raise exception.VirtualInterfaceCreateException() def _get_vif_events(self): """Returns the VIF events that need to be received for a VIF plug. In order for a VIF plug to be successful, certain events should be received from other components within the OpenStack ecosystem. This method returns the events neutron needs for a given deploy. """ # See libvirt's driver.py -> _get_neutron_events method for # more information. if CONF.vif_plugging_is_fatal and CONF.vif_plugging_timeout: return [('network-vif-plugged', network_info['id']) for network_info in self.crt_network_infos if not network_info.get('active', True)] def revert(self, lpar_wrap, result, flow_failures): if not self.network_infos: return LOG.warning('VIF creation being rolled back for instance.', instance=self.instance) # Get the current adapters on the system cna_w_list = vm.get_cnas(self.adapter, self.instance) for network_info in self.crt_network_infos: try: vif.unplug(self.adapter, self.instance, network_info, cna_w_list=cna_w_list) except Exception: LOG.exception("An exception occurred during an unplug in the " "vif rollback. Ignoring.", instance=self.instance) class UnplugVifs(task.Task): """The task to unplug Virtual Network Interfaces from a VM.""" def __init__(self, adapter, instance, network_infos): """Create the task. :param adapter: The pypowervm adapter. :param instance: The nova instance. :param network_infos: The network information containing the nova VIFs to create. """ self.adapter = adapter self.instance = instance self.network_infos = network_infos or [] super(UnplugVifs, self).__init__(name='unplug_vifs') def execute(self): # If the LPAR is not in an OK state for deleting, then throw an # error up front. lpar_wrap = vm.get_instance_wrapper(self.adapter, self.instance) modifiable, reason = lpar_wrap.can_modify_io() if not modifiable: LOG.error("Unable to remove VIFs from instance in the system's " "current state. The reason reported by the system is: " "%s", reason, instance=self.instance) raise exception.VirtualInterfaceUnplugException(reason=reason) # Get all the current Client Network Adapters (CNA) on the VM itself. cna_w_list = vm.get_cnas(self.adapter, self.instance) # Walk through the VIFs and delete the corresponding CNA on the VM. for network_info in self.network_infos: vif.unplug(self.adapter, self.instance, network_info, cna_w_list=cna_w_list) class PlugMgmtVif(task.Task): """The task to plug the Management VIF into a VM.""" def __init__(self, adapter, instance): """Create the task. Requires 'vm_cnas' from PlugVifs. If None, this Task will retrieve the VM's list of CNAs. Provides the mgmt_cna. This may be None if no management device was created. This is the CNA of the mgmt vif for the VM. :param adapter: The pypowervm adapter. :param instance: The nova instance. """ self.adapter = adapter self.instance = instance super(PlugMgmtVif, self).__init__( name='plug_mgmt_vif', provides='mgmt_cna', requires=['vm_cnas']) def execute(self, vm_cnas): LOG.info('Plugging the Management Network Interface to instance.', instance=self.instance) # Determine if we need to create the secure RMC VIF. This should only # be needed if there is not a VIF on the secure RMC vSwitch vswitch = None vswitches = pvm_net.VSwitch.search( self.adapter, parent_type=pvm_ms.System.schema_type, parent_uuid=self.adapter.sys_uuid, name=SECURE_RMC_VSWITCH) if len(vswitches) == 1: vswitch = vswitches[0] if vswitch is None: LOG.warning('No management VIF created for instance due to lack ' 'of Management Virtual Switch', instance=self.instance) return None # This next check verifies that there are no existing NICs on the # vSwitch, so that the VM does not end up with multiple RMC VIFs. if vm_cnas is None: has_mgmt_vif = vm.get_cnas(self.adapter, self.instance, vswitch_uri=vswitch.href) else: has_mgmt_vif = vswitch.href in [cna.vswitch_uri for cna in vm_cnas] if has_mgmt_vif: LOG.debug('Management VIF already created for instance', instance=self.instance) return None lpar_uuid = vm.get_pvm_uuid(self.instance) return pvm_cna.crt_cna(self.adapter, None, lpar_uuid, SECURE_RMC_VLAN, vswitch=SECURE_RMC_VSWITCH, crt_vswitch=True)
10,795
3,116
import random import networkx as nx from ..node import Node def generate(input_data): graph = nx.Graph() groups_size = [random.choice(range(input_data['min_group_nodes'], input_data['max_group_nodes']+1)) for i in range(input_data['num_groups'])] num_attacker = int(sum(groups_size) * input_data['num_attacker_to_num_honest']) num_sybil = int(input_data['num_sybil_to_num_attacker'] * num_attacker) categories = { 'Seed': {'nodes': [], 'num': input_data['num_seed_nodes']}, 'Honest': {'nodes': [], 'num': sum(groups_size) - input_data['num_seed_nodes'] - num_attacker}, 'Attacker': {'nodes': [], 'num': num_attacker}, 'Sybil': {'nodes': [], 'num': num_sybil}, } start_node = input_data.get('start_node', 0) counter = start_node for category in categories: for i in range(categories[category]['num']): node = Node(counter, category) categories[category]['nodes'].append(node) graph.add_node(node) counter += 1 non_sybils = categories['Honest']['nodes'] + \ categories['Seed']['nodes'] + categories['Attacker']['nodes'] random.shuffle(non_sybils) for group_num, size in enumerate(groups_size): group_name = 'group_{0}'.format(group_num) start_point = sum(groups_size[:group_num]) end_point = start_point + size groups_nodes = non_sybils[start_point:end_point] for node in groups_nodes: node.groups.add(group_name) groups = set(sum([list(node.groups) for node in non_sybils], [])) i = 0 while i < input_data['num_joint_node']: joint_node = random.choice(non_sybils) other_groups = groups - joint_node.groups if len(other_groups) > 0: random_group = random.choice(list(other_groups)) joint_node.groups.add(random_group) i += 1 if input_data['num_seed_groups'] != 0: seed_groups = ['seed_group_{0}'.format(i) for i in range(input_data['num_seed_groups'])] for node in categories['Seed']['nodes']: node.groups.add(random.choice(seed_groups)) for group in groups: nodes = [node for node in non_sybils if group in node.groups] nodes_degree = dict((node, 0) for node in nodes) min_degree = int(input_data['min_known_ratio'] * len(nodes)) avg_degree = int(input_data['avg_known_ratio'] * len(nodes)) max_degree = min( int(input_data['max_known_ratio'] * len(nodes)), len(nodes) - 1) low_degrees = range(min_degree, avg_degree) if min_degree != avg_degree else [min_degree] up_degrees = range(avg_degree, max_degree + 1) for i, node in enumerate(nodes): group_degree = sum(nodes_degree.values()) / (i+1) if group_degree < avg_degree: degree = random.choice(up_degrees) else: degree = random.choice(low_degrees) j = counter = 0 pairs = [] while j < degree: pair = random.choice(nodes) if node != pair and nodes_degree[pair] <= max_degree and pair not in pairs: graph.add_edge(node, pair) pairs.append(pair) j += 1 nodes_degree[node] += 1 else: counter += 1 if counter > 100*degree: # j += 1 raise Exception( "Can't find pair. group_degree={}".format(group_degree)) num_connection_to_attacker = max( int(input_data['sybil_to_attackers_con'] * categories['Attacker']['num']), 1) for i, node in enumerate(categories['Sybil']['nodes']): pairs = [] j = 0 while j < num_connection_to_attacker: pair = random.choice(categories['Attacker']['nodes']) if pair not in pairs: graph.add_edge(node, pair) pairs.append(pair) j += 1 for node in categories['Attacker']['nodes'] + categories['Sybil']['nodes']: node.groups.add('attacker') # Add inter-group connections i = 0 inter_group_pairs = [] while i < input_data['num_inter_group_con']: node = random.choice(non_sybils) pair = random.choice(non_sybils) if len(node.groups & pair.groups) == 0 and (node, pair) not in inter_group_pairs: graph.add_edge(node, pair) inter_group_pairs.append((node, pair)) i += 1 # sew graph parts together if not nx.is_connected(graph): components = list(nx.connected_components(graph)) biggest_comp = [] for i, component in enumerate(components): if len(component) > len(biggest_comp): biggest_comp = list(component) for component in components: if component == biggest_comp: continue non_sybils = False i = 0 while not non_sybils: i += 1 left_node = random.choice(list(component)) right_node = random.choice(biggest_comp) if left_node.node_type != 'Sybil' and right_node.node_type != 'Sybil': graph.add_edge(left_node, right_node) print( 'Add Edge: {0} --> {1}'.format(left_node, right_node)) non_sybils = True if i > len(biggest_comp): print(['%s %s'%(node.name, node.node_type) for node in component]) raise("Can't sew above component to the biggest_comp") return graph
5,752
1,769
#!/usr/bin/env python3 sx, sy, tx, ty = map(int, input().split()) x, y = tx - sx, ty - sy print("R"*x + "U"*-~y + "L"*-~x + "D"*-~y + "R" + "U"*y + "R"*-~x + "D"*-~y + "L"*-~x + "U")
182
109
a = list(map(int, input().split())) [i[0] for i in sorted(enumerate(a), key=lambda x:x[1])]
92
39
"""This module provides the RP To-Do CLI.""" from typing import Optional import typer from rptodo import __app_name__, __version__ app = typer.Typer() def _version_callback(value: bool) -> None: if value: typer.echo(f"{__app_name__} v{__version__}") raise typer.Exit() @app.callback() def main( version: Optional[bool] = typer.Option( None, "--version", "-v", help="Show the application's version and exit.", callback=_version_callback, is_eager=True, ) ) -> None: return
560
186
import asyncio import logging import pigpio class Relay: """Simple to use relay class implemented with pigpio :param pin: GPIO pin number :type pin: int :param on_level_low: Determines the logic level of the on-state. If set to True, the relay is on when the GPIO pin state is LOW. Defaults to True. :type on_level_low: bool, optional :param initial_state_off: Determines whether the relay should be set to off-state when initialized. If set to False, the relay is set to on-state at init. Defaults to True. :type initial_state_off: bool, optional :raises RuntimeError: If cannot connect to pigpio daemon :raises RuntimeError: If methods are called after calling stop """ def __init__(self, pin, on_level_low=True, initial_state_off=True): self._pin = pin self._on_level_low = on_level_low self._stopped = False if on_level_low: self._on_level = pigpio.LOW self._off_level = pigpio.HIGH else: self._on_level = pigpio.HIGH self._off_level = pigpio.LOW self._pi = pigpio.pi() if not self._pi.connected: raise RuntimeError("Could not connect to pigpio daemon") self._pi.set_mode(self._pin, pigpio.OUTPUT) if initial_state_off: self.off() else: self.on() def on(self): """Turns the relay on""" self._check_if_stopped() self._pi.write(self._pin, self._on_level) def off(self): """Turns the relay off""" self._check_if_stopped() self._pi.write(self._pin, self._off_level) def toggle(self): """Toggles the relay's state Turns the relay on if the state was previously off, and vice versa. """ self._check_if_stopped() if self.is_on(): self.off() else: self.on() async def press_once(self, press_time): """Turns the relay on and off, waiting press_time seconds in between :param press_time: Time in seconds to wait between turning the relay on and off :type press_time: float or int """ assert isinstance(press_time, float) or isinstance( press_time, int ), "press_time should be float or int" self._check_if_stopped() if self.is_on(): logging.warning( "Relay is already on when pressing once! Will turn relay off " f"in {press_time} seconds." ) self.on() await asyncio.sleep(press_time) self.off() def is_on(self): """Checks if the relay is turned on :return: True if the relay is turned on :rtype: bool """ self._check_if_stopped() return self._pi.read(self._pin) == self._on_level def is_off(self): """Checks if the relay is turned off :return: True if the relay is turned off :rtype: bool """ self._check_if_stopped() return not self.is_on() def on_level_is_low(self): """Checks if the relay is on when the GPIO state is LOW :return: True if the relay is on when the GPIO state is LOW :rtype: bool """ self._check_if_stopped() return self._on_level_low def _check_if_stopped(self): if self._stopped: raise RuntimeError("Relay already stopped") def stop(self): """Sets the pin to input state and stops pigpio daemon connection""" self._check_if_stopped() self._pi.set_pull_up_down(self._pin, pigpio.PUD_OFF) self._pi.set_mode(self._pin, pigpio.INPUT) self._pi.stop() self._stopped = True if __name__ == "__main__": async def main(): relay = Relay(26) print(f"Relay on level is low: {relay.on_level_is_low()}") print(f"Relay is initially on: {relay.is_on()}") await asyncio.sleep(0.5) print("Turning the relay on") relay.on() await asyncio.sleep(1) print("Turning the relay off") relay.off() await asyncio.sleep(2) print("Pressing the relay once for 1 second") await relay.press_once(1) await asyncio.sleep(2) print("Toggle relay state") relay.toggle() print(f"Relay is now on: {relay.is_on()}") await asyncio.sleep(1) print("Toggle relay state again") relay.toggle() print(f"Relay is now off: {relay.is_off()}") relay.stop() asyncio.run(main())
4,629
1,443
""" MIT License Copyright (c) 2020 ValkyriaKing711 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import asyncio import os from asyncio import AbstractEventLoop from datetime import datetime from typing import TypeVar, Union import discord from async_timeout import timeout from cogs.utils import utils from discord import (AudioSource, FFmpegPCMAudio, Guild, PCMVolumeTransformer, TextChannel) from discord.ext import commands, tasks from discord.ext.commands import Cog, Context from youtube_dl import YoutubeDL utcnow = datetime.utcnow Y = TypeVar("Y", bound="YTDLSource") FFMPEG_EXECUTABLE = "ffmpeg" FFMPEG_OPTIONS = { "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5", "options": "-vn" } ytdl = YoutubeDL({ "format": "bestaudio/best", "outtmpl": "downloads/%(autonumber)s-%(extractor)s-%(id)s-%(title)s.%(ext)s", "restrictfilenames": True, "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": False, "logtostderr": False, "quiet": False, "verbose": True, "no_warnings": True, "default_search": "auto", "source_address": "0.0.0.0", "geo_bypass_country": "FI", "age_limit": 30 }) class YTDLSource(PCMVolumeTransformer): def __init__(self, source: AudioSource, *, data: dict, volume=1.0): super().__init__(source, volume) self.data = data self.title = data.get("title") self.url = data.get("url") @classmethod async def from_query(cls, query: str, *, loop: AbstractEventLoop = None, stream: bool = True, partial: bool = False, ctx: Context = None) -> Union[dict, Y]: if not stream and partial: raise ValueError("partial cannot be True when not streaming") loop = loop or asyncio.get_running_loop() data = await loop.run_in_executor( None, lambda: ytdl.extract_info(query, download=not stream) ) if "entries" in data: data = data["entries"][0] if ctx: data["context"] = ctx if partial: for key in ("formats", "http_headers", "downloader_options", "thumbnails", "url"): try: del data[key] except Exception: pass return data options = FFMPEG_OPTIONS.copy() if stream: source = data["url"] else: source = ytdl.prepare_filename(data) data["filename"] = source options.pop("before_options") return cls(FFmpegPCMAudio(source, **options), data=data) @classmethod async def regather_stream(cls, data: dict, *, loop: AbstractEventLoop = None) -> Y: loop = loop or asyncio.get_running_loop() ctx = data.get("context") data = await loop.run_in_executor( None, lambda: ytdl.extract_info(data["webpage_url"], download=False) ) if ctx: data["context"] = ctx return cls(FFmpegPCMAudio(data["url"]), data=data) class MusicPlayer: def __init__(self, ctx: Context): self.bot: utils.Bot = ctx.bot self._channel: TextChannel = ctx.channel self._cog: Cog = ctx.cog self._guild: Guild = ctx.guild self.next = asyncio.Event() self.queue = asyncio.Queue() self.current = None self.volume = 1.0 self.first_play_id = None self.skipped = None self.player_loop.start() # pylint: disable=no-member @tasks.loop() async def player_loop(self): self.next.clear() try: async with timeout(300): source = await self.queue.get() except asyncio.TimeoutError: print("timeout") return await self.destroy(self._guild) if not isinstance(source, YTDLSource): try: source = await YTDLSource.regather_stream( source, loop=self.bot.loop ) except Exception as e: embed = discord.Embed( description=f"```css\n{e}\n```", color=0xF6DECF, timestamp=utcnow() ) embed.set_author( name="An error occurred while processing the track.", icon_url=self._guild.me.display_avatar.url ) return await self._channel.send(embed=embed) ctx = source.data["context"] source.volume = self.volume self.current = source self._guild.voice_client.play( source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set) ) if self.skipped: embed = discord.Embed( description=f"**Now playing {self.current.data['title']}**", color=0xF6DECF, timestamp=utcnow() ) embed.set_author( name=f"Skipped {self.skipped.data['title']}", icon_url=self.skipped.data["skipper"].display_avatar.url, url=source.data["webpage_url"] ) self.skipped = None if source.data["is_live"]: duration = "🔴 LIVE" else: duration = utils.format_time(source.data["duration"]) embed.add_field(name="Uploader", value=source.data["uploader"]) embed.add_field(name="Duration", value=duration) embed.add_field(name="Requested by", value=ctx.author.mention) embed.set_thumbnail(url=source.data["thumbnail"]) await self._channel.send(embed=embed) elif ctx.message.id != self.first_play_id: embed = discord.Embed( color=0xF6DECF, timestamp=utcnow() ) embed.set_author( name=f"Now playing {source.title}", icon_url=ctx.author.display_avatar.url, url=source.data["webpage_url"] ) if source.data["is_live"]: duration = "🔴 LIVE" else: duration = utils.format_time(source.data["duration"]) embed.add_field(name="Uploader", value=source.data["uploader"]) embed.add_field(name="Duration", value=duration) embed.add_field(name="Requested by", value=ctx.author.mention) embed.set_thumbnail(url=source.data["thumbnail"]) await self._channel.send(embed=embed) await self.next.wait() source.cleanup() self.current = None filename = source.data.get("filename") if filename and os.path.isfile(filename): os.remove(filename) @player_loop.before_loop async def wait_until_ready(self): await self.bot.wait_until_ready() def destroy(self, guild: Guild): return self._cog.cleanup(guild)
8,322
2,611
class Solution: def getHint(self, secret: str, guess: str) -> str: bull = 0 cow = 0 values = dict() for i in range(len(secret)): if secret[i] == guess[i]: bull += 1 elif secret[i] in values: values[secret[i]] += 1 else: values[secret[i]] = 1 for i in range(len(secret)): if secret[i] != guess[i]: if guess[i] in values: if values[guess[i]] > 0: cow +=1 values[guess[i]] -= 1 return str(bull) + "A" + str(cow) + "B"
689
202
from django.conf.urls import url from . import classviews urlpatterns = [ url(r'^event/$', classviews.HookEvent.as_view()), ]
131
46
"""Stream class for tap-parquet.""" import requests from copy import deepcopy from pathlib import Path from typing import Any, Dict, Optional, Union, List, Iterable from singer_sdk.streams import Stream from singer_sdk.typing import ( ArrayType, BooleanType, DateTimeType, IntegerType, NumberType, ObjectType, PropertiesList, Property, StringType, JSONTypeHelper, ) import pyarrow.parquet as pq SCHEMAS_DIR = Path(__file__).parent / Path("./schemas") def get_jsonschema_type(ansi_type: str) -> JSONTypeHelper: """Return a JSONTypeHelper object for the given type name.""" if "int" in ansi_type: return IntegerType() if "string" in ansi_type: return StringType() if "bool" in ansi_type: return BooleanType() if "timestamp[ns]" in ansi_type: return DateTimeType() raise ValueError(f"Unmappable data type '{ansi_type}'.") class ParquetStream(Stream): """Stream class for Parquet streams.""" @property def filepath(self) -> str: """Return the filepath for the parquet stream.""" return self.config["filepath"] @property def schema(self) -> dict: """Dynamically detect the json schema for the stream. This is evaluated prior to any records being retrieved. """ properties: List[Property] = [] parquet_schema = pq.ParquetFile(self.filepath).schema_arrow for i in range(len(parquet_schema.names)): name, dtype = parquet_schema.names[i], parquet_schema.types[i] properties.append(Property(name, get_jsonschema_type(str(dtype)))) return PropertiesList(*properties).to_dict() def get_records(self, partition: Optional[dict] = None) -> Iterable[dict]: """Return a generator of row-type dictionary objects.""" try: parquet_file = pq.ParquetFile(self.filepath) except Exception as ex: raise IOError(f"Could not read from parquet file '{self.filepath}': {ex}") for i in range(parquet_file.num_row_groups): table = parquet_file.read_row_group(i) for batch in table.to_batches(): for row in zip(*batch.columns): yield { table.column_names[i]: val.as_py() for i, val in enumerate(row, start=0) }
2,392
697
import sys import random from design import * from PyQt5.QtWidgets import QMainWindow, QApplication from PyQt5 import QtGui ppt = ['Rock', 'Paper', 'Scissors'] game = [] def aChoice(): esc = random.choice(ppt) game.append(esc) class App(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) self.windowStart.setPixmap(QtGui.QPixmap('./img/pptHome.png')) #self.stackedWidget.setCurrentWidget(self.page_1) #self.btnAddRegiao.clicked.connect(lambda: self.stackedWidget.setCurrentWidget(self.page_2)) self.btnRestart.clicked.connect(self.restart) self.btnRock.clicked.connect(self.rock) self.btnPaper.clicked.connect(self.paper) self.btnScissors.clicked.connect(self.scissors) def restart(self): self.stackedWidget.setCurrentWidget(self.page_1) game.clear() self.computador.setPixmap(QtGui.QPixmap('')) self.player.setPixmap(QtGui.QPixmap('')) self.infoText.setText('') def rock(self): self.stackedWidget.setCurrentWidget(self.page_2) self.player.setPixmap(QtGui.QPixmap('./img/rock.png')) game.append('Rock') aChoice() if game[1] == 'Rock': self.computador.setPixmap(QtGui.QPixmap('./img/rock.png')) self.infoText.setText('Nobody won, play again.') if game[1] == 'Paper': self.computador.setPixmap(QtGui.QPixmap('./img/paper.png')) self.infoText.setText('You lost, try again :(') self.infoText.setStyleSheet('color: #ffaa00; font: 20pt \"MS Shell Dlg 2\";\n') if game[1] == 'Scissors': self.computador.setPixmap(QtGui.QPixmap('./img/scissors.png')) self.infoText.setText('You win, congratulations!!! :)') self.infoText.setStyleSheet('color: rgb(85, 255, 127); font: 20pt \"MS Shell Dlg 2\";\n') def paper(self): self.stackedWidget.setCurrentWidget(self.page_2) self.player.setPixmap(QtGui.QPixmap('./img/paper.png')) game.append('Paper') aChoice() if game[1] == 'Paper': self.computador.setPixmap(QtGui.QPixmap('./img/paper.png')) self.infoText.setText('Nobody won, play again.') if game[1] == 'Scissors': self.computador.setPixmap(QtGui.QPixmap('./img/scissors.png')) self.infoText.setText('You lost, try again :(') self.infoText.setStyleSheet('color: #ffaa00; font: 20pt \"MS Shell Dlg 2\";\n') if game[1] == 'Rock': self.computador.setPixmap(QtGui.QPixmap('./img/rock.png')) self.infoText.setText('You win, congratulations!!! :)') self.infoText.setStyleSheet('color: rgb(85, 255, 127); font: 20pt \"MS Shell Dlg 2\";\n') def scissors(self): self.stackedWidget.setCurrentWidget(self.page_2) self.player.setPixmap(QtGui.QPixmap('./img/scissors.png')) game.append('Scissors') aChoice() if game[1] == 'Scissors': self.computador.setPixmap(QtGui.QPixmap('./img/scissors.png')) self.infoText.setText('Nobody won, play again.') if game[1] == 'Rock': self.computador.setPixmap(QtGui.QPixmap('./img/rock.png')) self.infoText.setText('You lost, try again :(') self.infoText.setStyleSheet('color: #ffaa00; font: 20pt \"MS Shell Dlg 2\";\n') if game[1] == 'Paper': self.computador.setPixmap(QtGui.QPixmap('./img/paper.png')) self.infoText.setText('You win, congratulations!!! :)') self.infoText.setStyleSheet('color: rgb(85, 255, 127); font: 20pt \"MS Shell Dlg 2\";\n') if __name__ == '__main__': qt = QApplication(sys.argv) app = App() app.show() qt.exec_()
3,851
1,411
import unittest from geopy.point import Point from geopy.format import format_degrees class TestFormat(unittest.TestCase): @unittest.skip("") def test_format(self): """ format_degrees """ self.assertEqual( format_degrees(Point.parse_degrees('-13', '19', 0)), "-13 19\' 0.0\"" )
354
124
# -*- coding: utf-8 -*- """ Created on Sun Oct 20 20:52:56 2019 @author: 陈彪,版权所有 这个是一个排序算法的总结,将所有的排序算法都重新写一遍,然后我们首先会分析算法的时间 复杂度,然后简单介绍一下这些算法的原理,最后使用python实现,然后我们会使用测试案例 来进行测试。 """ import random '''首先映入眼帘的就是冒泡排序,这是一个让人理解起来最简单的排序算法,这个算法的时间复 杂度是O(N^2),从下面的程序中也能看出来这个算法的时间复杂度确实是O(N^2). ''' def bubble(a): for i in range(len(a)): for j in range(i,len(a)): if(a[i]>a[j]): temp=a[i] a[i]=a[j] a[j]=temp return a if __name__=="__main__": a=[] for i in range(10): a.append(random.randint(10,40)) print(a) print(bubble(a)) print('hello world!')
653
430
# # Usage: # # % brownie console # >>> from scripts import token # >>> green = token.main() # >>> token.issue(green) # >>> token.transfer(green, accounts[1], accounts[2], 1) # from brownie import Token, accounts admin = accounts[0] issuer = accounts[1] holders = accounts[2:9] max_supply = pow(10, 18+9) # 1,000,000,000 def main(): return Token.deploy("Green", "GREEN", 18, admin, issuer, max_supply, {'from': admin}) def issue(token): amount = 1000 for account in holders: token.mint(account.address, amount, {'from': issuer}) amount = amount * 2 def transfer(token, sender, recipient, value): token.transfer(recipient.address, value, {'from': sender})
722
260
import string WIKI_BESTAND = '/Users/tom/Downloads/\ nlwiktionary-20191020-pages-articles-multistream-index.txt' WOORD_BESTAND = 'woord-frequenties.txt' SLECHT_BESTAND = 'slechte-woorden.txt' BLACKLIST = {i.strip() for i in open(SLECHT_BESTAND)} AANTAL = 1000000000000000 MIN = 4 MIN_ACHTERVOEGSEL = 4 VOORVOEGSELS = ( 'aan', 'achter', 'achterop', 'af', 'be', 'bij', 'binnen', 'boven', 'door', 'er', 'goed', 'her', 'in', 'los', 'mee', 'mis', 'na', 'neer', 'om', 'onder', 'ont', 'op', 'over', 'samen', 'tegen', 'teleur', 'toe', 'tussen', 'uit', 'vast', 'ver', 'vol', 'voor', 'voorbe', 'vrij', 'weer', 'weg', 'zwart', ) is_woord = set(string.ascii_lowercase).issuperset def wikitionary(): for lijn in open(WIKI_BESTAND): _, _, woord = lijn.strip().split(':', maxsplit=2) if is_woord(woord): yield woord def freq(): for lijn in open(WOORD_BESTAND): woord, _ = lijn.strip().rsplit(maxsplit=1) yield woord def werkwoorden(woorden): alle = set() resultaat = {} for woord in woorden: if not (woord.endswith('en') or woord.endswith('gaan')): continue alle.add(woord) for v in VOORVOEGSELS: if not woord.startswith(v): continue achtervoegsel = woord[len(v):] if len(achtervoegsel) < MIN_ACHTERVOEGSEL: continue if achtervoegsel.startswith('ge') and achtervoegsel != 'geven': continue if achtervoegsel in BLACKLIST: continue resultaat.setdefault(achtervoegsel, []).append(woord) for achtervoegsel, lijst in resultaat.items(): if achtervoegsel in alle: lijst.append(achtervoegsel) lijst.sort() resultaat = {k: v for k, v in resultaat.items() if len(v) > 1} return sorted(resultaat.items(), key=lambda v: len(v[1]), reverse=True) def druck_werkwoorden(werkwoorden): for i, (k, v) in enumerate(werkwoorden): print(k) for j in v: print(' ', j) print() if i > AANTAL: break def classic_extract(): wiki = list(wikitionary()) ww = werkwoorden(wiki) druck_werkwoorden(ww) print() print('----------------') print() for i, (k, v) in enumerate(ww): if i > 10: break words = set(w for w in wiki if w.endswith(k)) print(k) for missing in sorted(words.difference(v)): print(' ', missing) if __name__ == '__main__': classic_extract()
2,711
1,026
import os import random import numpy as np import pandas as pd def set_random_seed(seed=42): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) def set_display_options(): pd.set_option("max_colwidth", 1000) pd.set_option("max_rows", 50) pd.set_option("max_columns", 100) pd.options.display.float_format = "{:,.2f}".format
384
152
offset = -8 while offset != 0 : print('Benar') if offset > 0 : offset = offset -3 else: offset = offset +2 print(offset)
158
54
from tortoise.contrib.fastapi import register_tortoise as config_tortoise from config.settings import settings DB_URL = f'postgres://{settings.DB_USERNAME}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_DATABASE}' TORTOISE_MODULES = ['app.example.model'] TORTOISE_ORM_MODULES = TORTOISE_MODULES TORTOISE_ORM_MODULES.append('aerich.models') TORTOISE_ORM = { 'connections': { 'default': DB_URL }, 'apps': { 'models': { 'models': TORTOISE_ORM_MODULES, 'default_connection': 'default' } } } def register_tortoise(app): config_tortoise( app, db_url=DB_URL, modules={'models': TORTOISE_MODULES}, generate_schemas=False, add_exception_handlers=True, )
832
301
from django.shortcuts import redirect def login_redirect(request): return redirect('/account/login')
105
27
# Copyright (c) 2020 Aiven, Helsinki, Finland. https://aiven.io/ from setuptools import setup import version version = version.get_project_version("rpm_s3_mirror/version.py") setup( name="rpm_s3_mirror", packages=["rpm_s3_mirror"], version=version, description="Tool for syncing RPM repositories with S3", license="Apache 2.0", author="Aiven", author_email="willcoe@aiven.io", url="https://github.com/aiven/rpm-s3-mirror", install_requires=[ "defusedxml", "requests", "python-dateutil", "boto3", "lxml", ], entry_points={ "console_scripts": [ "rpm_s3_mirror = rpm_s3_mirror.__main__:main", ], }, classifiers=[ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "Programming Language :: Python :: 3.7", "Natural Language :: English", ], )
982
332
import time from pytest_bdd import scenarios, when, then, given, parsers from pages.search import SearchTests from pages.register_page import RegisterPage # Scenarios scenarios('../features/test_register_search_scenario.feature') @given('open the page') def open_page(browser): negative = SearchTests(browser) negative.load_page() @when(parsers.cfparse('we wrote haine "{haine}" in the search field')) @when('we wrote haine "<haine>" in the search field') def check_email(browser, haine): negative = SearchTests(browser) negative.search_pijama_click(haine) @given('open the register page') def open_page(browser): utile = RegisterPage(browser) utile.load_page() @when('generate random email') def random_email(browser): utile = RegisterPage(browser) utile.get_random_mail(5) @when('generate random firstname lastname password') def random_name_pass(browser): utile = RegisterPage(browser) utile.get_random_string(8, 10, 8) time.sleep(5) @when('searching element fuste') def search_element(browser): utile = RegisterPage(browser) utile.get_search() @when('searching element assert') def search_cautare(browser): utile = RegisterPage(browser) utile.get_cautare() @when('searching element pijama') def search_cautare(browser): utile = RegisterPage(browser) utile.get_pijama() #utile.text_cautare() # steps @given('open the search page') def open_page(browser): search_page = SearchTests(browser) search_page.load_page() @when(parsers.cfparse('the user types "{searched_item}" in the search bar')) def search_product(browser, searched_item): # dam searched item ca arametru s aputem cauta cu orice valoare vrem noi ca daca nu tot timpul # scrie pijama search_page = SearchTests(browser) search_page.click_search_button() search_page.search_product(searched_item) @then(parsers.cfparse('each result contains "{searched_item}" in name')) def check_results(browser, searched_item): search_page = SearchTests(browser) search_page.check_results(searched_item)
2,074
675
import codecs from logging import getLogger import os from pendium import app from pendium.plugins import IRenderPlugin from pendium.plugins import ISearchPlugin from yapsy.PluginManager import PluginManager log = getLogger(__name__) # Populate plugins lib_path = os.path.abspath(os.path.dirname(__file__)) manager = PluginManager() manager.setPluginPlaces([os.path.join(lib_path, "plugins")]) manager.setCategoriesFilter( {"Search": ISearchPlugin, "Render": IRenderPlugin,} ) manager.collectPlugins() class PathExists(Exception): pass class PathNotFound(Exception): pass class CannotRender(Exception): pass class NoSearchPluginAvailable(Exception): pass class Wiki(object): def __init__( self, basepath, extensions={}, default_renderer=None, plugins_config={}, has_vcs=False, ): self.basepath = basepath self.extensions = extensions self.default_renderer = default_renderer self.has_vcs = has_vcs self.vcs = None if self.has_vcs: try: from pendium import git_wrapper self.vcs = git_wrapper.GitWrapper(basepath) except: raise Exception("You need to install GitPython") # Plugin configuration for name, configuration in plugins_config.items(): for cat in ["Search", "Render"]: plugin = manager.getPluginByName(name, category=cat) if not plugin: continue msg = "Configuring plugin: %s with :%s" % (name, configuration) log.debug(msg) plugin.plugin_object.configure(configuration) def search(self, term): best_plugin_score = 0 best_plugin = None for plugin in manager.getPluginsOfCategory("Search"): if plugin.plugin_object.search_speed > best_plugin_score: best_plugin_score = plugin.plugin_object.search_speed best_plugin = plugin if best_plugin is None: raise NoSearchPluginAvailable log.debug("Searching with %s" % best_plugin.name) return best_plugin.plugin_object.search(self, term) def root(self): return self.get(".") def get(self, path): completepath = os.path.normpath(os.path.join(self.basepath, path)) if os.path.isdir(completepath): return WikiDir(self, path) else: return WikiFile(self, path) def refresh(self): if not self.has_vcs: return "" return self.vcs.refresh() class WikiPath(object): def __init__(self, wiki, path): self.path = path self.wiki = wiki self.abs_path = os.path.join(wiki.basepath, path) self.abs_path = os.path.normpath(self.abs_path) self.name = os.path.split(self.path)[1] self.is_node = False self.is_leaf = False if not os.path.exists(self.abs_path): raise PathNotFound(self.abs_path) def ancestor(self): if self.path == "": return None ancestor_dir = os.path.split(self.path)[0] return self.wiki.get(ancestor_dir) def ancestors(self): if self.ancestor(): return self.ancestor().ancestors() + [self.ancestor()] return [] def items(self): if not os.path.isdir(self.abs_path): self = self.ancestor() filenames = [] for f in os.listdir(self.abs_path): if f.find(".") == 0: continue if os.path.splitext(f)[1][1:] in app.config["BLACKLIST_EXTENSIONS"]: continue complete_path = os.path.join(self.path, f) filenames.append(self.wiki.get(complete_path)) return sorted(filenames, key=lambda Wiki: Wiki.is_leaf) @property def editable(self): if app.config["EDITABLE"]: return os.access(self.abs_path, os.W_OK) return False def delete(self): top = self.abs_path for root, dirs, files in os.walk(top, topdown=False): for name in files: log.debug("Will remove FILE: %s", os.path.join(root, name)) os.remove(os.path.join(root, name)) for name in dirs: log.debug("Will remove DIR: %s", os.path.join(root, name)) os.rmdir(os.path.join(root, name)) if self.is_node: log.debug("Will remove DIR: %s", self.abs_path) os.rmdir(self.abs_path) else: log.debug("Will remove FILE: %s", self.abs_path) os.remove(self.abs_path) if self.wiki.has_vcs: self.wiki.vcs.delete(path=self.path) class WikiFile(WikiPath): def __init__(self, *args, **kwargs): super(WikiFile, self).__init__(*args, **kwargs) self.is_leaf = True self.extension = os.path.splitext(self.name)[1][1:] self._content = "" def renderer(self): for plugin in manager.getPluginsOfCategory("Render"): log.debug("Testing for plugin %s", plugin.plugin_object.name) extensions = self.wiki.extensions.get(plugin.plugin_object.name, None) if extensions is None: continue # Try the next plugin if self.extension in extensions: log.debug(self.extension) log.debug(plugin.plugin_object.name) return plugin.plugin_object # If no renderer found and binary, give up if self.is_binary: return None # If is not binary and we have a default renderer # return it if self.wiki.default_renderer: return self.wiki.default_renderer return None @property def can_render(self): return bool(self.renderer()) def render(self): if self.can_render: renderer = self.renderer() return renderer.render(self.content()) # No renderer found if self.is_binary: return self.content(decode=False) return self.content() @property def is_binary(self): """ Return true if the file is binary. """ fin = open(self.abs_path, "rb") try: CHUNKSIZE = 1024 while 1: chunk = fin.read(CHUNKSIZE).decode("utf-8") if "\0" in chunk: # Found null byte return True if len(chunk) < CHUNKSIZE: break # Done finally: fin.close() return False @property def refs(self): """ Special property for Git refs """ if self.wiki.has_vcs: return self.wiki.vcs.file_refs(self.path) return [] def ref(self, ref): """ Update file content with appropriate reference from git to display older file versions """ try: content = self.wiki.vcs.show(filepath=self.path, ref=ref) self._content = content.decode("utf8") return True except: return False def content(self, content=None, decode=True): """ Helper method, needs refactoring """ if self._content and content is None: return self._content fp = open(self.abs_path, "r") ct = fp.read() if decode: ct = ct fp.close() if not content: self._content = ct return ct self._content = content if content == ct: return ct def save(self, comment=None): fp = codecs.open(self.abs_path, "w", "utf-8") fp.write(self._content) fp.close() if self.wiki.has_vcs: self.wiki.vcs.save(path=self.path, comment=comment) class WikiDir(WikiPath): def __init__(self, *args, **kwargs): super(WikiDir, self).__init__(*args, **kwargs) self.is_node = True def create_file(self, filename): new_abs_path = os.path.join(self.abs_path, filename) if os.path.exists(new_abs_path): raise PathExists(new_abs_path) fp = open(new_abs_path, "w") fp.close() return self.wiki.get(os.path.join(self.path, filename)) def create_directory(self, name): new_abs_path = os.path.join(self.abs_path, name) if os.path.exists(new_abs_path): raise PathExists(new_abs_path) os.makedirs(new_abs_path) np = self.wiki.get(os.path.join(self.path, name)) return np
8,668
2,601
import random import numpy as np import pandas as pd import math from sklearn import preprocessing import scipy.stats as stats def edge_in_cliq(edge, nodes_in_cliq): if edge[0] in nodes_in_cliq: return True else: return False def edges_to_remove_neighbourhood(all_edges, neighbourhood_density, nbh_nodes): neighbourhood_edges = [e for e in all_edges if edge_in_cliq(e, nbh_nodes)] sample_size = int(len(neighbourhood_edges) * (1-neighbourhood_density)) # sample random edges chosen_edges = random.sample(neighbourhood_edges, sample_size) return chosen_edges def what_neighbourhood(index, neighbourhood_nodes): for n in neighbourhood_nodes: if index in neighbourhood_nodes[n]: return n raise ValueError('Neighbourhood not found.') def what_coordinates(neighbourhood_name, dataset): for x in range(len(dataset)): if neighbourhood_name in dataset[x]: return dataset[x][1]['lon'], dataset[x][1]['lat'], raise ValueError("Corresponding coordinates not found") def what_informality(neighbourhood_name, dataset): for x in range(len(dataset)): if neighbourhood_name in dataset[x]: try: return dataset[x][1]['Informal_residential'] except: return None raise ValueError("Corresponding informality not found") def confidence_interval(data, av): sample_stdev = np.std(data) sigma = sample_stdev/math.sqrt(len(data)) return stats.t.interval(alpha=0.95, df=24, loc=av, scale=sigma) def generate_district_data(number_of_agents, path, max_districts=None): """ Transforms input data on informal residential, initial infections, and population and transforms it to a list of organised data for the simulation. :param number_of_agents: number of agents in the simulation, integer :param max_districts: (optional) maximum amount of districts simulated, integer :return: data set containing district data for simulation, list """ informal_residential = pd.read_csv('{}/f_informality.csv'.format(path))#.iloc[:-1] inital_infections = pd.read_csv('{}/f_initial_cases.csv'.format(path), index_col=1) inital_infections = inital_infections.sort_index() population = pd.read_csv('{}/f_population.csv'.format(path)) # normalise district informality x = informal_residential[['Informal_residential']].values.astype(float) min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) informal_residential['Informal_residential'] = pd.DataFrame(x_scaled) population['Informal_residential'] = informal_residential['Informal_residential'] # determine smallest district based on number of agents smallest_size = population['Population'].sum() / number_of_agents # generate data set for model input districts_data = [] for i in range(len(population)): if population['Population'].iloc[i] > smallest_size: districts_data.append( [int(population['WardID'].iloc[i]), {'Population': population['Population'].iloc[i], #'lon': population['lon'].iloc[i], #'lat': population['lat'].iloc[i], 'Informal_residential': population['Informal_residential'].iloc[i], 'Cases_With_Subdistricts': inital_infections.loc[population['WardID'].iloc[i]][ 'Cases'], }, ]) if max_districts is None: max_districts = len(districts_data) # this can be manually shortened to study dynamics in some districts return districts_data[:max_districts]
3,957
1,164
import tempfile import speech.models import speech.loader import shared def test_save(): freq_dim = 120 model = speech.models.Model(freq_dim, shared.model_config) batch_size = 2 data_json = "test.json" preproc = speech.loader.Preprocessor(data_json) save_dir = tempfile.mkdtemp() speech.save(model, preproc, save_dir) s_model, s_preproc = speech.load(save_dir) assert hasattr(s_preproc, 'mean') assert hasattr(s_preproc, 'std') assert hasattr(s_preproc, 'int_to_char') assert hasattr(s_preproc, 'char_to_int') msd = model.state_dict() for k, v in s_model.state_dict().items(): assert k in msd assert hasattr(s_model, 'encoder_dim') assert hasattr(s_model, 'is_cuda')
767
280
import matplotlib.pyplot as plt # TODO: port away from matplotlib to a seaborn # Probability Distribution Function (PDF). # Cumulative Distribution Function (CDF) # TODO: put all of these functions within a custom function image = plt.imread('900px-Astronaut-EVA.jpg') plt.subplot(2, 1, 1) plt.imshow(image, cmap='gray') plt.title('Original image') plt.axis('off') pixels = image.flatten() # Display a histogram of the pixels in the bottom subplot plt.subplot(2, 1, 2) pdf = plt.hist(pixels, bins=64, range=(0, 256), normed=False, color='red', alpha=0.4) plt.grid('off') # Use plt.twinx() to overlay the CDF in the bottom subplot plt.twinx() # Display a cumulative histogram of the pixels cdf = plt.hist(pixels, bins=64, range=(0, 256), normed=True, cumulative=True, color='blue', alpha=0.4) plt.xlim((0, 256)) plt.grid('off') plt.title('PDF - red & CDF - blue (original image)') plt.show()
928
356
from .model_zoo import load_weights
35
12
from logging_logger import loggerClass import logging loggerClass.WritetoScreen(loggerClass,logging.INFO,"testing...", '%(levelname)s:%(message)s') loggerClass.Writetofile(loggerClass,'sample.log',logging.WARNING,"testing...", '%(levelname)s:%(message)s')
282
86
formatter = "{} {} {} {}" print(formatter.format(1, 2, 3, 4)) print(formatter.format("a", "b", "c", "d", "r"))
111
52
""" The HR solver and algorithm. """ from matching import Game, Matching from matching import Player as Resident from matching.players import Hospital from .util import delete_pair, match_pair class HospitalResident(Game): """ A class for solving instances of the hospital-resident assignment problem (HR). In this case, a blocking pair is any resident-hospital pair that satisfies **all** of the following: - They are present in each other's preference lists; - either the resident is unmatched, or they prefer the hospital to their current match; - either the hospital is under-subscribed, or they prefer the resident to at least one of their current matches. Parameters ---------- residents : list of Player The residents in the matching game. Each resident must rank a subset of those in :code:`hospitals`. hospitals : list of Hospital The hospitals in the matching game. Each hospital must rank all of (and only) the residents which rank it. Attributes ---------- matching : Matching or None Once the game is solved, a matching is available as a :code:`Matching` object with the hospitals as keys and their resident matches as values. Initialises as :code:`None`. blocking_pairs : list of (Player, Hospital) or None Initialises as `None`. Otherwise, a list of the resident-hospital blocking pairs. """ def __init__(self, residents=None, hospitals=None): self.residents = residents self.hospitals = hospitals super().__init__() self._check_inputs() @classmethod def create_from_dictionaries( cls, resident_prefs, hospital_prefs, capacities ): """ Create an instance of :code:`HospitalResident` from two preference dictionaries and capacities. """ residents, hospitals = _make_players( resident_prefs, hospital_prefs, capacities ) game = cls(residents, hospitals) return game def solve(self, optimal="resident"): """ Solve the instance of HR using either the resident- or hospital-oriented algorithm. Return the matching. """ self._matching = Matching( hospital_resident(self.residents, self.hospitals, optimal) ) return self.matching def check_validity(self): """ Check whether the current matching is valid. """ self._check_resident_matching() self._check_hospital_capacity() self._check_hospital_matching() return True def check_stability(self): """ Check for the existence of any blocking pairs in the current matching, thus determining the stability of the matching. """ blocking_pairs = [] for resident in self.residents: for hospital in self.hospitals: if ( _check_mutual_preference(resident, hospital) and _check_resident_unhappy(resident, hospital) and _check_hospital_unhappy(resident, hospital) ): blocking_pairs.append((resident, hospital)) self.blocking_pairs = blocking_pairs return not any(blocking_pairs) def _check_resident_matching(self): """ Check that no resident is matched to an unacceptable hospital. """ errors = [] for resident in self.residents: if ( resident.matching is not None and resident.matching not in resident.prefs ): errors.append( ValueError( f"{resident} is matched to {resident.matching} but " "they do not appear in their preference list: " f"{resident.prefs}." ) ) if errors: raise Exception(*errors) return True def _check_hospital_capacity(self): """ Check that no hospital is over-subscribed. """ errors = [] for hospital in self.hospitals: if len(hospital.matching) > hospital.capacity: errors.append( ValueError( f"{hospital} is matched to {hospital.matching} which " f"is over their capacity of {hospital.capacity}." ) ) if errors: raise Exception(*errors) return True def _check_hospital_matching(self): """ Check that no hospital is matched to an unacceptable resident. """ errors = [] for hospital in self.hospitals: for resident in hospital.matching: if resident not in hospital.prefs: errors.append( ValueError( f"{hospital} has {resident} in their matching but " "they do not appear in their preference list: " f"{hospital.prefs}." ) ) if errors: raise Exception(*errors) return True def _check_inputs(self): """ Raise an error if any of the conditions of the game have been broken. """ self._check_resident_prefs() self._check_hospital_prefs() def _check_resident_prefs(self): """ Make sure that the residents' preferences are all subsets of the available hospital names. Otherwise, raise an error. """ errors = [] for resident in self.residents: if not set(resident.prefs).issubset(set(self.hospitals)): errors.append( ValueError( f"{resident} has ranked a non-hospital: " f"{set(resident.prefs)} != {set(self.hospitals)}" ) ) if errors: raise Exception(*errors) return True def _check_hospital_prefs(self): """ Make sure that every hospital ranks all and only those residents that have ranked it. Otherwise, raise an error. """ errors = [] for hospital in self.hospitals: residents_that_ranked = [ res for res in self.residents if hospital in res.prefs ] if set(hospital.prefs) != set(residents_that_ranked): errors.append( ValueError( f"{hospital} has not ranked all the residents that " f"ranked it: {set(hospital.prefs)} != " f"{set(residents_that_ranked)}." ) ) if errors: raise Exception(*errors) return True def _check_mutual_preference(resident, hospital): """ Determine whether two players each have a preference of the other. """ return resident in hospital.prefs and hospital in resident.prefs def _check_resident_unhappy(resident, hospital): """ Determine whether a resident is unhappy because they are unmatched, or they prefer the hospital to their current match. """ return resident.matching is None or resident.prefers( hospital, resident.matching ) def _check_hospital_unhappy(resident, hospital): """ Determine whether a hospital is unhappy because they are under-subscribed, or they prefer the resident to at least one of their current matches. """ return len(hospital.matching) < hospital.capacity or any( [hospital.prefers(resident, match) for match in hospital.matching] ) def unmatch_pair(resident, hospital): """ Unmatch a (resident, hospital)-pair. """ resident.unmatch() hospital.unmatch(resident) def hospital_resident(residents, hospitals, optimal="resident"): """ Solve an instance of HR using an adapted Gale-Shapley algorithm. A unique, stable and optimal matching is found for the given set of residents and hospitals. The optimality of the matching is found with respect to one party and is subsequently the worst stable matching for the other. Parameters ---------- residents : list of Player The residents in the game. Each resident must rank a non-empty subset of the elements of ``hospitals``. hospitals : list of Hospital The hospitals in the game. Each hospital must rank all the residents that have ranked them. optimal : str, optional Which party the matching should be optimised for. Must be one of ``"resident"`` and ``"hospital"``. Defaults to the former. Returns ------- matching : Matching A dictionary-like object where the keys are the members of ``hospitals``, and the values are their matches ranked by preference. """ if optimal == "resident": return resident_optimal(residents, hospitals) if optimal == "hospital": return hospital_optimal(hospitals) def resident_optimal(residents, hospitals): """ Solve the instance of HR to be resident-optimal. The algorithm is as follows: 0. Set all residents to be unmatched, and all hospitals to be totally unsubscribed. 1. Take any unmatched resident with a non-empty preference list, :math:`r`, and consider their most preferred hospital, :math:`h`. Match them to one another. 2. If, as a result of this new matching, :math:`h` is now over-subscribed, find the worst resident currently assigned to :math:`h`, :math:`r'`. Set :math:`r'` to be unmatched and remove them from :math:`h`'s matching. Otherwise, go to 3. 3. If :math:`h` is at capacity (fully subscribed) then find their worst current match :math:`r'`. Then, for each successor, :math:`s`, to :math:`r'` in the preference list of :math:`h`, delete the pair :math:`(s, h)` from the game. Otherwise, go to 4. 4. Go to 1 until there are no such residents left, then end. """ free_residents = residents[:] while free_residents: resident = free_residents.pop() hospital = resident.get_favourite() match_pair(resident, hospital) if len(hospital.matching) > hospital.capacity: worst = hospital.get_worst_match() unmatch_pair(worst, hospital) free_residents.append(worst) if len(hospital.matching) == hospital.capacity: successors = hospital.get_successors() for successor in successors: delete_pair(hospital, successor) if not successor.prefs: free_residents.remove(successor) return {r: r.matching for r in hospitals} def hospital_optimal(hospitals): """ Solve the instance of HR to be hospital-optimal. The algorithm is as follows: 0. Set all residents to be unmatched, and all hospitals to be totally unsubscribed. 1. Take any hospital, :math:`h`, that is under-subscribed and whose preference list contains any resident they are not currently assigned to, and consider their most preferred such resident, :math:`r`. 2. If :math:`r` is currently matched, say to :math:`h'`, then unmatch them from one another. In any case, match :math:`r` to :math:`h` and go to 3. 3. For each successor, :math:`s`, to :math:`h` in the preference list of :math:`r`, delete the pair :math:`(r, s)` from the game. 4. Go to 1 until there are no such hospitals left, then end. """ free_hospitals = hospitals[:] while free_hospitals: hospital = free_hospitals.pop() resident = hospital.get_favourite() if resident.matching: curr_match = resident.matching unmatch_pair(resident, curr_match) if curr_match not in free_hospitals: free_hospitals.append(curr_match) match_pair(resident, hospital) if len(hospital.matching) < hospital.capacity and [ res for res in hospital.prefs if res not in hospital.matching ]: free_hospitals.append(hospital) successors = resident.get_successors() for successor in successors: delete_pair(resident, successor) if ( not [ res for res in successor.prefs if res not in successor.matching ] and successor in free_hospitals ): free_hospitals.remove(successor) return {r: r.matching for r in hospitals} def _make_players(resident_prefs, hospital_prefs, capacities): """ Make a set of residents and hospitals from the dictionaries given, and add their preferences. """ resident_dict, hospital_dict = _make_instances( resident_prefs, hospital_prefs, capacities ) for resident_name, resident in resident_dict.items(): prefs = [hospital_dict[name] for name in resident_prefs[resident_name]] resident.set_prefs(prefs) for hospital_name, hospital in hospital_dict.items(): prefs = [resident_dict[name] for name in hospital_prefs[hospital_name]] hospital.set_prefs(prefs) residents = list(resident_dict.values()) hospitals = list(hospital_dict.values()) return residents, hospitals def _make_instances(resident_prefs, hospital_prefs, capacities): """ Create ``Player`` (resident) and ``Hospital`` instances for the names in each dictionary. """ resident_dict, hospital_dict = {}, {} for resident_name in resident_prefs: resident = Resident(name=resident_name) resident_dict[resident_name] = resident for hospital_name in hospital_prefs: capacity = capacities[hospital_name] hospital = Hospital(name=hospital_name, capacity=capacity) hospital_dict[hospital_name] = hospital return resident_dict, hospital_dict
14,115
3,798
#!/usr/bin/env python # coding: utf-8 # based on public kernel https://www.kaggle.com/corochann/ashrae-feather-format-for-fast-loading import os import random import gc import tqdm import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def prepare(root, output): train_df = pd.read_csv(os.path.join(root, 'train.csv')) test_df = pd.read_csv(os.path.join(root, 'test.csv')) building_meta_df = pd.read_csv(os.path.join(root, 'building_metadata.csv')) sample_submission = pd.read_csv(os.path.join(root, 'sample_submission.csv')) weather_train_df = pd.read_csv(os.path.join(root, 'weather_train.csv')) weather_test_df = pd.read_csv(os.path.join(root, 'weather_test.csv')) train_df['timestamp'] = pd.to_datetime(train_df['timestamp']) test_df['timestamp'] = pd.to_datetime(test_df['timestamp']) weather_train_df['timestamp'] = pd.to_datetime(weather_train_df['timestamp']) weather_test_df['timestamp'] = pd.to_datetime(weather_test_df['timestamp']) # # Save data in feather format train_df.to_feather(os.path.join(output,'train.feather')) test_df.to_feather(os.path.join(output,'test.feather')) weather_train_df.to_feather(os.path.join(output,'weather_train.feather')) weather_test_df.to_feather(os.path.join(output,'weather_test.feather')) building_meta_df.to_feather(os.path.join(output,'building_metadata.feather')) sample_submission.to_feather(os.path.join(output,'sample_submission.feather')) # # Read data in feather format train_df = pd.read_feather(os.path.join(output, 'train.feather')) weather_train_df = pd.read_feather(os.path.join(output, 'weather_train.feather')) test_df = pd.read_feather(os.path.join(output, 'test.feather')) weather_test_df = pd.read_feather(os.path.join(output, 'weather_test.feather')) building_meta_df = pd.read_feather(os.path.join(output, 'building_metadata.feather')) sample_submission = pd.read_feather(os.path.join(output, 'sample_submission.feather')) # # Count zero streak train_df = train_df.merge(building_meta_df, on='building_id', how='left') train_df = train_df.merge(weather_train_df, on=['site_id', 'timestamp'], how='left') train_df['black_count']=0 for bid in train_df.building_id.unique(): df = train_df[train_df.building_id==bid] for meter in df.meter.unique(): dfm = df[df.meter == meter] b = (dfm.meter_reading == 0).astype(int) train_df.loc[(train_df.building_id==bid) & (train_df.meter == meter), 'black_count'] = b.groupby((~b.astype(bool)).cumsum()).cumsum() #train_df[train_df.building_id == 0].meter_reading.plot() #train_df[train_df.building_id == 0].black_count.plot() train_df.to_feather(os.path.join(output, 'train_black.feather')) if __name__ == '__main__': root = 'input' output = 'processed' prepare(root, output)
2,931
1,063
import copy import functools import os import numpy as np from scipy import sparse from spinsys import constructors, half, dmrg, exceptions from cffi import FFI class SiteVector(constructors.PeriodicBCSiteVector): def __init__(self, ordered_pair, Nx, Ny): super().__init__(ordered_pair, Nx, Ny) def angle_with(self, some_site): """Returns the angle * 2 between (some_site - self) with the horizontal. Only works on nearest neighbors """ Δx, Δy = some_site - self if Δx == 0: if Δy != 0: return -2 * np.pi / 3 elif Δy == 0: if Δx != 0: return 0 else: return 2 * np.pi / 3 def a1_hop(self, stride): vec = self.xhop(stride) if vec == self: raise exceptions.SameSite return vec def a2_hop(self, stride): vec = self.xhop(-1 * stride).yhop(stride) if vec == self: raise exceptions.SameSite return vec def a3_hop(self, stride): vec = self.yhop(-stride) if vec == self: raise exceptions.SameSite return vec def b1_hop(self, stride): """hop in the a1 - a3 aka b1 direction. Useful for second nearest neighbor coupling interactions """ vec = self.xhop(stride).yhop(stride) if vec == self: raise exceptions.SameSite return vec def b2_hop(self, stride): vec = self.xhop(-2 * stride).yhop(stride) if vec == self: raise exceptions.SameSite return vec def b3_hop(self, stride): vec = self.b1_hop(-stride).b2_hop(-stride) if vec == self: raise exceptions.SameSite return vec def _neighboring_sites(self, strides, funcs): neighbors = [] for stride in strides: for func in funcs: try: neighbors.append(func(stride)) except exceptions.SameSite: continue return neighbors @property def nearest_neighboring_sites(self, all=False): strides = [1, -1] if all else [1] funcs = [self.a1_hop, self.a2_hop, self.a3_hop] return self._neighboring_sites(strides, funcs) @property def second_neighboring_sites(self, all=False): """with the all option enabled the method will enumerate all the sites that are second neighbors to the current site. Otherwise it will only enumerate the sites along the b1, b2 and b3 directions """ strides = [1, -1] if all else [1] funcs = [self.b1_hop, self.b2_hop, self.b3_hop] return self._neighboring_sites(strides, funcs) @property def third_neighboring_sites(self, all=False): strides = [2, -2] if all else [2] funcs = [self.a1_hop, self.a2_hop, self.a3_hop] return self._neighboring_sites(strides, funcs) class SemiPeriodicBCSiteVector(SiteVector): """A version of SiteVector that is periodic only along the x direction """ def __init__(self, ordered_pair, Nx, Ny): super().__init__(ordered_pair, Nx, Ny) def diff(self, other): """Finds the shortest distance from this site to the other""" Δx = self.x - other.x Δy = self.y - other.y return (Δx, Δy) def yhop(self, stride): new_vec = copy.copy(self) new_y = self.y + stride if new_y // self.Ny == self.x // self.Ny: new_vec.y = new_y else: raise exceptions.OutOfBoundsError("Hopping off the lattice") return new_vec @property def neighboring_sites(self): neighbors = [] funcs = [self.xhop, self.yhop] for Δ in [1, -1]: for func in funcs: try: neighbors.append(func(Δ).lattice_index) except exceptions.OutOfBoundsError: continue try: neighbors.append(self.xhop(Δ).yhop(-Δ).lattice_index) except exceptions.OutOfBoundsError: continue return neighbors @functools.lru_cache(maxsize=None) def _generate_bonds(Nx, Ny): N = Nx * Ny vec = SiteVector((0, 0), Nx, Ny) # range_orders = [set(), set(), set()] # sets de-duplicates the list of bonds range_orders = [[], [], []] for i in range(N): nearest_neighbor = vec.nearest_neighboring_sites second_neighbor = vec.second_neighboring_sites third_neighbor = vec.third_neighboring_sites neighbors = [nearest_neighbor, second_neighbor, third_neighbor] for leap, bonds in enumerate(range_orders): for n in neighbors[leap]: # sort them so identical bonds will always have the same hash bond = sorted((vec, n)) bonds.append(tuple(bond)) vec = vec.next_site() return range_orders @functools.lru_cache(maxsize=None) def _gen_full_ops(N): σ_p = constructors.raising() σ_m = constructors.lowering() σz = constructors.sigmaz() p_mats = [half.full_matrix(σ_p, k, N) for k in range(N)] m_mats = [half.full_matrix(σ_m, k, N) for k in range(N)] z_mats = [half.full_matrix(σz, k, N) for k in range(N)] return p_mats, m_mats, z_mats def _gen_z_pm_ops(N, bonds): """generate the H_z and H_pm components of the Hamiltonian""" H_pm = H_z = 0 p_mats, m_mats, z_mats = _gen_full_ops(N) for bond in bonds: site1, site2 = bond i, j = site1.lattice_index, site2.lattice_index H_pm += p_mats[i].dot(m_mats[j]) + m_mats[i].dot(p_mats[j]) H_z += z_mats[i].dot(z_mats[j]) return H_pm, H_z @functools.lru_cache(maxsize=None) def hamiltonian_dp_components(Nx, Ny): """Generate the reusable pieces of the hamiltonian""" N = Nx * Ny nearest, second, third = _generate_bonds(Nx, Ny) H_pm1, H_z1 = _gen_z_pm_ops(N, nearest) H_pm2, H_z2 = _gen_z_pm_ops(N, second) H_pm3, H_z3 = _gen_z_pm_ops(N, third) H_ppmm = H_pmz = 0 p_mats, m_mats, z_mats = _gen_full_ops(N) for bond in nearest: site1, site2 = bond i, j = site1.lattice_index, site2.lattice_index γ = np.exp(1j * site1.angle_with(site2)) H_ppmm += \ γ * p_mats[i].dot(p_mats[j]) + \ γ.conj() * m_mats[i].dot(m_mats[j]) H_pmz += 1j * (γ.conj() * z_mats[i].dot(p_mats[j]) - γ * z_mats[i].dot(m_mats[j]) + γ.conj() * p_mats[i].dot(z_mats[j]) - γ * m_mats[i].dot(z_mats[j])) return H_pm1, H_z1, H_ppmm, H_pmz, H_pm2, H_z2, H_z3, H_pm3 def hamiltonian_dp(Nx, Ny, J_pm=0, J_z=0, J_ppmm=0, J_pmz=0, J2=0, J3=0): """Generates hamiltonian for the triangular lattice model with direct product Parameters -------------------- Nx: int number of sites along the x-direction Ny: int number of sites along the y-direction J_pm: float J_+- parameter J_z: float J_z parameter J_ppmm: float J_++-- parameter J_pmz: float J_+-z parameter J2: float second nearest neighbor interaction parameter J3: float third nearest neighbor interaction parameter Returns -------------------- H: scipy.sparse.csc_matrix """ components = hamiltonian_dp_components(Nx, Ny) H_pm1, H_z1, H_ppmm, H_pmz, H_pm2, H_z2, H_z3, H_pm3 = components nearest_neighbor_terms = J_pm * H_pm1 + J_z * H_z1 + J_ppmm * H_ppmm + J_pmz * H_pmz second_neighbor_terms = third_neighbor_terms = 0 if not J2 == 0: second_neighbor_terms = J2 * (H_pm2 + J_z / J_pm * H_z2) if not J3 == 0: third_neighbor_terms = J3 * (H_pm3 + J_z / J_pm * H_z3) return nearest_neighbor_terms + second_neighbor_terms + third_neighbor_terms class DMRG_Hamiltonian(dmrg.Hamiltonian): def __init__(self, Nx, Ny, J_pm=0, J_z=0, J_ppmm=0, J_pmz=0): self.generators = { '+': constructors.raising(), '-': constructors.lowering(), 'z': constructors.sigmaz() } self.N = Nx * Ny self.Nx = Nx self.Ny = Ny self.J_pm = J_pm self.J_z = J_z self.J_ppmm = J_ppmm self.J_pmz = J_pmz super().__init__() def initialize_storage(self): init_block = sparse.csc_matrix(([], ([], [])), dims=[2, 2]) init_ops = self.generators self.storage = dmrg.Storage(init_block, init_block, init_ops) def newsite_ops(self, size): return dict((i, sparse.kron(sparse.eye(size // 2), self.generators[i])) for i in self.generators.keys()) # TODO: Inconsistent shapes error at runtime def block_newsite_interaction(self, block_key): block_side, curr_site = block_key site = SemiPeriodicBCSiteVector.from_index(curr_site, self.Nx, self.Ny) neighbors = [i for i in site.neighboring_sites if i < curr_site] H_pm_new = H_z_new = H_ppmm_new = H_pmz_new = 0 for i in neighbors: key = (block_side, i + 1) block_ops = self.storage.get_item(key).ops site_ops = self.generators H_pm_new += \ sparse.kron(block_ops['+'], site_ops['-']) + \ sparse.kron(block_ops['-'], site_ops['+']) H_z_new += sparse.kron(block_ops['z'], site_ops['z']) H_ppmm_new += \ sparse.kron(block_ops['+'], site_ops['+']) + \ sparse.kron(block_ops['-'], site_ops['-']) H_pmz_new += \ sparse.kron(block_ops['z'], site_ops['+']) + \ sparse.kron(block_ops['z'], site_ops['-']) + \ sparse.kron(block_ops['+'], site_ops['z']) + \ sparse.kron(block_ops['-'], site_ops['z']) return self.J_pm * H_pm_new + self.J_z * H_z_new + \ self.J_ppmm * H_ppmm_new + self.J_pmz * H_pmz_new ########################################################## ### FFI wrapper code for functions implemented in Rust ### ########################################################## ffi = FFI() modpath = os.path.dirname(__file__) rootdir = os.path.split(modpath)[0] rust_dir = os.path.join(rootdir, "rust", "triangular_lattice_ext") # Only define the following functions if the shared object is compiled or else # Python is going to throw exceptions on import. # The header file only exists if the Rust shared object is compiled. if os.path.exists(os.path.join(rust_dir, "triangular_lattice_ext.h")): with open(os.path.join(rust_dir, "triangular_lattice_ext.h")) as header: # remove directives from header file since cffi can't process directives yet h = [line for line in header.readlines() if not line[0] == "#"] ffi.cdef(''.join(h)) _lib = ffi.dlopen(os.path.join(rust_dir, "target", "release", "libtriangular_lattice_ext.so")) class CoordMatrix: """A class that encapsulates the matrix and provides methods that would help memoery management across the FFI boundary """ def __init__(self, mat): """Initializer Parameters -------------------- mat: CoordMatrix """ self.__obj = mat # the pointer to the pointers to the arrays self.data = np.frombuffer(ffi.buffer(mat.data.ptr, mat.data.len * 16), np.complex128) self.col = np.frombuffer(ffi.buffer(mat.col.ptr, mat.col.len * 4), np.int32) self.row = np.frombuffer(ffi.buffer(mat.row.ptr, mat.row.len * 4), np.int32) self.ncols = mat.ncols self.nrows = mat.nrows def __enter__(self): """For use with context manager""" return self def __exit__(self, exc_type, exc_value, traceback): """For use with context manager""" self.data = None self.col = None self.row = None _lib.request_free(self.__obj) # deallocates Rust object self.__obj = None def to_csc(self): """Returns a CSC matrix""" return sparse.csc_matrix((self.data, (self.col, self.row)), shape=(self.nrows, self.ncols)) def to_csr(self): """Returns a CSR matrix""" return sparse.csr_matrix((self.data, (self.col, self.row)), shape=(self.nrows, self.ncols)) def h_ss_z_consv_k(Nx, Ny, kx, ky, l): """construct the H_z matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_z(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_xy_consv_k(Nx, Ny, kx, ky, l): """construct the H_xy matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_xy(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_ppmm_consv_k(Nx, Ny, kx, ky, l): """construct the H_ppmm matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_ppmm(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_pmz_consv_k(Nx, Ny, kx, ky, l): """construct the H_pmz matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_pmz(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_sss_chi_consv_k(Nx, Ny, kx, ky): """construct the H_chi matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_sss_chi(Nx, Ny, kx, ky) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_z_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the H_z matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.ks_h_ss_z(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_xy_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the H_xy matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.ks_h_ss_xy(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_sss_chi_consv_k_s(Nx, Ny, kx, ky, nup): """construct the H_chi matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone nup: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.ks_h_sss_chi(Nx, Ny, kx, ky, nup) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def ss_z_consv_k(Nx, Ny, kx, ky, l): """construct the Σsz_i * sz_j operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone l: int the separation between sites: |i - j| Returns -------------------- ss_z: scipy.sparse.csr_matrix """ mat = _lib.k_ss_z(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def ss_xy_consv_k(Nx, Ny, kx, ky, l): """construct the Σ(sx_i * sx_j + sy_i * sy_j) operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone l: int the separation between sites: |i - j| Returns -------------------- ss_xy: scipy.sparse.csr_matrix """ mat = _lib.k_ss_xy(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def ss_z_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the Σsz_i * sz_j operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int the separation between sites: |i - j| Returns -------------------- ss_z: scipy.sparse.csr_matrix """ mat = _lib.ks_ss_z(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def ss_xy_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the Σ(sx_i * sx_j + sy_i * sy_j) operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int the separation between sites: |i - j| Returns -------------------- ss_xy: scipy.sparse.csr_matrix """ mat = _lib.ks_ss_xy(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def min_necessary_ks(Nx, Ny): """Returns the momentum that we absolutely need to compute Parameters -------------------- Nx: int Ny: int Returns -------------------- list of ints """ ks = [] arrs = [] for kx in range(Nx): for ky in range(Ny): arr = np.outer(np.exp(2j * np.pi * kx * np.arange(Nx) / Nx), np.exp(2j * np.pi * ky * np.arange(Ny) / Ny)) for arr0 in arrs: if np.allclose(arr0, arr) or np.allclose(arr0, arr.conjugate()): break else: ks.append((kx, ky)) arrs.append(arr) return ks
23,531
7,816
import pandas as pd import copy from pathlib import Path import pandas as pd import numpy as np import math from datetime import datetime,timedelta import matplotlib.pyplot as plt from predictor.utility import msg2log def Forcast_imbalance_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_27102020.csv") src_col_name = "Forcasting" src1_col_name = "Real_demand" dst_col_name = "FrcImbalance" ds[dst_col_name] =[round(ds[src_col_name][i]-ds[src1_col_name][i],2) for i in range(len(ds)) ] ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_27102020_CommonAnalyze.csv", index=False) return def WindTurbine_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_20102020_WindGenPower.csv") aux_col_name = "Programmed_demand" dest_col_name="Real_demand" src_col_name="WindGen_Power_" ds[aux_col_name]=[ 0.0 for i in range(len(ds[aux_col_name]))] ds[dest_col_name]=ds[src_col_name] ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/editedElHiero_24092020_20102020_WindGenPower.csv", index=False) return def profivateHouse_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PrivateHouseElectricityConsumption_21012020.csv") col_name='lasts' dt_col_name='Date Time' aux_col_name="Programmed_demand" data_col_name="Demand" v=ds[col_name].values for i in range (len(ds[col_name].values)): a=v[i].split('-') v[i]='T'+a[0]+":00.000+02:00" ds[col_name]=copy.copy(v) for i in range(len(ds[col_name])): ds[dt_col_name][i] =ds[dt_col_name][i] + v[i] ds1 =ds.drop([col_name], axis=1) add_col=[] for i in range(len(ds[dt_col_name])): add_col.append(ds[data_col_name].values[i] * 2 ) ds1[aux_col_name]=add_col ds1.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/PrivateHouseElectricityConsumption_21012020.csv", index=False) pass def powerSolarPlant_edit(): # ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PowerGenOfSolarPlant_21012020.csv") ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__SolarPlantPowerGen_21012020.csv") # col_name = 'lasts' dt_col_name = 'Date Time' aux_col_name = "Programmed_demand" data_col_name = "PowerGen" v = ds[dt_col_name].values for i in range(len(ds[dt_col_name].values)): a = v[i].split(' ') b=a[0].split('.') if len(a[1])<5: a[1]='0'+a[1] v[i]='2020-'+b[1]+"-"+b[0]+'T'+a[1]+':00.000+02:00' ds[dt_col_name] = copy.copy(v) # ds1 = ds.drop([col_name], axis=1) add_col = [] for i in range(len(ds[dt_col_name])): add_col.append(ds[data_col_name].values[i] * 2) ds[aux_col_name] = add_col # ds1.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/PowerGenOfSolarPlant_21012020.csv", index=False) ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/SolarPlantPowerGen_21012020_21012020.csv", index=False) pass def powerSolarPlant_Imbalance(): # ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PowerGenOfSolarPlant_21012020.csv") ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/SolarPlantPowerGen_21012020.csv") # col_name = 'lasts' dt_col_name = 'Date Time' aux_col_name = "Programmed_demand" data_col_name = "PowerGen" ds["Imbalance"] = [ds[aux_col_name].values[i]-ds[data_col_name].values[i] for i in range(len(ds)) ] ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/SolarPlantPowerGen_21012020.csv", index=False) pass def powerElHiero_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/_ElHiero_24092020_20102020_additionalData.csv") dt_col_name = 'Date Time' aux_col_name = "Programmed_demand" data_col_name = "PowerGen" v = ds[dt_col_name].values for i in range(len(ds[dt_col_name].values)): a = v[i].split(' ') b = a[0].split('.') if len(a[1]) < 5: a[1] = '0' + a[1] v[i] = '2020-' + b[1] + "-" + b[0] + 'T' + a[1] + ':00.000+02:00' ds[dt_col_name] = copy.copy(v) ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_20102020_additionalData.csv", index=False) pass def datosElHiero_edit(): # ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PowerGenOfSolarPlant_21012020.csv") ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/Datos_de_El_Hierro_2016.csv") # col_name = 'lasts' dt_col_name = 'Date Time' v = ds[dt_col_name].values for i in range(len(ds[dt_col_name].values)): a = v[i].split(' ') #29-12-2016 3:00:00 b=a[0].split('-') # dd mm year a0new="{}-{}-{}".format(b[2],b[1],b[0]) c=a[1].split(':') #h mm ss if len(c[0])<2: c[0]='0{}'.format(c[0]) a1new='{}:{}:{}.000+00:00'.format(c[0],c[1],c[2]) v[i]="{}T{}".format(a0new,a1new) ds[dt_col_name] = copy.copy(v) ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.", index=False) pass def datosElHiero_PerDay(): src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_Days.csv" ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = 'Date Time' data_col_name = 'Real_demand' v=ds[data_col_name].values n_v=len(v) col_names=["{}:{}".format(int(i/6), (i%6)*10) for i in range(144)] v_dict = {col_names[i]:[] for i in range(144)} # d_dict = {"Date Time": [ds[dt_col_name][i] for i in range(0, n_v, 144)]} # d_dict={"Date": [pd.to_datetime(ds[dt_col_name][i],dayfirst=True).date() for i in range(0,n_v,144)]} d_dict = {"Date": [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, 144)]} for i in range(n_v): v_dict[col_names[i%144]].append(v[i]) # last list 365-size, we add v[0] d={**d_dict,**v_dict} ds1=pd.DataFrame(d) ds1.to_csv(dst_csv) return def datosElHiero_PerTimeStamps(): src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = 'Date Time' data_col_name = 'Real_demand' v=ds[data_col_name].values n_v=len(v) col_names= [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, 144)] row_names=["{}:{}".format(int(i/6), (i%6)*10) for i in range(144)] v_dict={} # v_dict = {item:[] for item in col_names} # d_dict = {"Date Time": [ds[dt_col_name][i] for i in range(0, n_v, 144)]} # d_dict={"Date": [pd.to_datetime(ds[dt_col_name][i],dayfirst=True).date() for i in range(0,n_v,144)]} d_dict = {"Date": [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, 144)]} d_dict = {"Timestamp": row_names} n_start=0 n_series=144 # obsefvation points n_features=366 # days for icol in col_names: v_dict[icol]=v[n_start:n_start+n_series].tolist() n_start=n_start+n_series # last list 365-size, we add v[0] d={**d_dict,**v_dict} ds1=pd.DataFrame(d) ds1.to_csv(dst_csv) return def datosElHiero_PerTimeStamps(): dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016-Est.csv" src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = 'Timestamp' d_dst={} vts=ds['Timestamp'].values.tolist() vts.append('ave') vts.append('std') vts.append('min') vts.append('max') d_dst["RowName"]=vts for col in ds.columns: if 'Unnamed' in col or 'Timestamp' in col: continue v=ds[col].values.tolist() a=np.array(v) ave=a.mean() std=a.std() minv=a.min() maxv=a.max() v.append(round(ave,3)) v.append(round(std,3)) v.append(round(minv,2)) v.append(round(maxv,2)) d_dst[col]=v ds1 = pd.DataFrame(d_dst) n_ds1=len(ds1) ave = [] std = [] minv = [] maxv = [] for i in range(n_ds1): v=[] for col in ds1.columns[1:]: v.append(ds1[col][i]) a=np.array(v) ave.append(round(a.mean(),3)) std.append(round(a.std(),3)) minv.append(round(a.min(),2)) maxv.append(round(a.max(),2)) ds1['ave']=ave ds1['std'] = std ds1['min'] = minv ds1['max'] = maxv ds1.to_csv(dst_csv) return """ transform time series (feature in source dataset) matrix Nrows * Mcols. The source dataset must comprise a timestamp feature(column) named 'dt_col_name' or index column. The 'data_col_name'- feature must be a time series (TS) are ordered by index ot timestamp feature('dt_col_name') , that is, the observation must be equidistant and without gaps. Additional, the beginning timestamp must be 00:00:00 (or 0 for index). The 'period' and 'direction' determine the formation of the matrix. If the 'direction' is along the 'X'- axis, then the segments of the TS corresponding to the 'period' are the rows of the matrix. Column names are derived from observation times within a period, for example, "00: 00,00: 10, ..., 23:50" to 10 minutes discretization and a period of 1 day. If the direction is along 'Y'-axis, then the segment of the TS corresponding to the 'period' are the column of matrix. The column names are derived from the period in the timestamp, i.g. data string if the period is 1 day like as '2016-03-27', and row names are derived from observations within period, for example, "00:00,...,23:50". """ def ts2matrix(source_csv:str=None, dest_csv:str=None, dt_col_name:str="Date Time", data_col_name:str='Real_demand', outRowIndex="rowNames", discret:int=10,period:object=None, direction:str='x', title:str="", f:object=None): if source_csv is None or not Path(source_csv).exists() : msg="The source dataset path is invalid: {}".format(source_csv) msg2log(None,msg,f) return None ds=pd.read_csv(source_csv) if dt_col_name not in ds.columns or data_col_name not in ds.columns: msg = "{} or {} not found in the dataset {}".format(dt_col_name,data_col_name, source_csv) msg2log(None, msg, f) return None folder_csv=Path(source_csv).parent dest_csv = Path(folder_csv / "{}_{}".format(title,data_col_name)).with_suffix(".csv") dest_se_csv = Path(folder_csv / "{}_{}_StatEst".format(title, data_col_name)).with_suffix(".csv") if direction=="X" or direction == "x": dsMatrix = ts2matrix_X(ds=ds, dt_col_name=dt_col_name, data_col_name=data_col_name,outRowIndex=outRowIndex, discret=discret, period=period, f=f) elif direction=="Y" or direction == "y": dsMatrix = ts2matrix_Y(ds=ds, dt_col_name=dt_col_name, data_col_name=data_col_name, outRowIndex=outRowIndex, discret=discret, period=period, f=f) else: msg = "{} invalid direction ".format(direction) msg2log(None, msg, f) return None dsMatrix.to_csv(dest_csv) dsMatrixStatEst=ts2matrix_statest(ds=dsMatrix, rowIndexName=outRowIndex, f=f) dsMatrixStatEst.to_csv(dest_se_csv) return def ts2matrix_X(ds:pd.DataFrame=None, dt_col_name:str='Date Time',data_col_name:str='Real_demand', outRowIndex:str="rowNames", discret:int=10,period:int=144, f:object=None)->pd.DataFrame: # src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" # dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_Days.csv" # ds = pd.read_csv(src_csv) # # col_name = 'lasts' # dt_col_name = 'Date Time' # data_col_name = 'Real_demand' h_period_sr=60/discret # hour in sample resolution, 6 d_period_sr = period # day period in sample resolution, 144 v=ds[data_col_name].values n_v=len(v) if n_v%d_period_sr!=0: msg="Time series size is {} and it is not multiply of {} period".format(n_v,d_period_sr) msg2log(None,msg,f) return None col_names = ["{}:{}".format(int(i / h_period_sr), int((i % h_period_sr) * 10)) for i in range(d_period_sr)] v_dict = {col_names[i]:[] for i in range(d_period_sr)} d_dict = {outRowIndex: [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') \ for i in range(0, n_v, d_period_sr)]} for i in range(n_v): v_dict[col_names[i%144]].append(v[i]) d={**d_dict,**v_dict} ds1=pd.DataFrame(d) # ds1.to_csv(dst_csv) return ds1 def ts2matrix_Y(ds:pd.DataFrame=None, dt_col_name:str='Date Time',data_col_name:str='Real_demand', outRowIndex:str="rowNames", discret:int=10,period:int=144, f:object=None)->pd.DataFrame: # src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" # dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" # ds = pd.read_csv(src_csv) # # col_name = 'lasts' # dt_col_name = 'Date Time' # data_col_name = 'Real_demand' # # v=ds[data_col_name].values n_v=len(v) h_period_sr = 60 / discret # hour in sample resolution, 6 d_period_sr = period # day period in sample resolution, 144 v = ds[data_col_name].values n_v = len(v) if n_v % d_period_sr != 0: msg = "Time series size is {} and it is not multiply of {} period".format(n_v, d_period_sr) msg2log(None, msg, f) return None col_names= [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, d_period_sr)] row_names=["{}:{}".format(int(i/h_period_sr), int((i%h_period_sr)*10)) for i in range(d_period_sr)] v_dict={} d_dict = {outRowIndex: row_names} n_start=0 n_series=d_period_sr # obsefvation points n_features=366 # days for icol in col_names: v_dict[icol]=v[n_start:n_start+n_series].tolist() n_start=n_start+n_series d={**d_dict,**v_dict} ds1=pd.DataFrame(d) # ds1.to_csv(dst_csv) return ds1 def ts2matrix_statest(ds:pd.DataFrame=None,rowIndexName:str="rowNames",f:object=None): # dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016-Est.csv" # src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" # ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = rowIndexName d_dst={} vts=ds[rowIndexName].values.tolist() vts.append('ave') vts.append('std') vts.append('min') vts.append('max') d_dst[rowIndexName]=vts for col in ds.columns: if 'Unnamed' in col or rowIndexName in col: continue v=ds[col].values.tolist() a=np.array(v) ave=a.mean() std=a.std() minv=a.min() maxv=a.max() v.append(round(ave,3)) v.append(round(std,3)) v.append(round(minv,2)) v.append(round(maxv,2)) d_dst[col]=v ds1 = pd.DataFrame(d_dst) n_ds1=len(ds1) ave = [] std = [] minv = [] maxv = [] for i in range(n_ds1): v=[] for col in ds1.columns[1:]: v.append(ds1[col][i]) a=np.array(v) ave.append(round(a.mean(),3)) std.append(round(a.std(),3)) minv.append(round(a.min(),2)) maxv.append(round(a.max(),2)) ds1['ave']=ave ds1['std'] = std ds1['min'] = minv ds1['max'] = maxv # ds1.to_csv(dst_csv) return ds1 if __name__=="__main__": # privateHouse_edit() # powerSolarPlant_edit() # powerElHiero_edit() #WindTurbine_edit() # Forcast_imbalance_edit() # powerSolarPlant_Imbalance() # powerSolarPlant_analysis() # datosElHiero_edit() # datosElHiero_PerDay() # datosElHiero_PerTimeStamps() # datosElHiero_PerTimeStamps() src_csv = "/home/dmitryv/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" with open("loglog.log",'w+') as ff: ts2matrix(source_csv=src_csv, dt_col_name = "Date Time", data_col_name= 'Real_demand', outRowIndex = "rowNames", discret = 10, period=144, direction = 'x', title = "X_direction", f=ff) ts2matrix(source_csv=src_csv, dt_col_name="Date Time", data_col_name='Real_demand', outRowIndex="rowNames", discret=10, period=144, direction='y', title="Y_direction", f=ff) pass
16,528
6,994
# -*- coding: utf-8 -*- import requests, json from bs4 import BeautifulSoup from mspider.spider import MSpider class Get_indic_idSpider(MSpider): def __init__(self): self.name = "get_count_id" self.indics = ['GDP', 'GDP-based-on-PPP', 'Real-GDP-growth', 'GDP-per-capita', 'GDP-per-capita-based-on-PPP', 'Inflation-rate', 'Unemployment-rate', 'Current-account-balance', 'Current-account-balance-as-a-share-of-GDP', 'Government-gross-debt-as-a-share-of-GDP', 'Poverty-rate', 'International-reserves', 'Primary-energy-production', 'Primary-energy-consumption', 'Energy-intensity', 'Energy-imports', 'Alternative-and-nuclear-energy-use', 'Fossil-fuel-energy-consumption', 'Diesel-price', 'Gasoline-price', 'Air-transport-freight', 'Number-of-air-passengers-carried', 'Volume-of-goods-transported-by-railways', 'Number-of-passengers-carried-by-railways', 'Length-of-rail-lines', 'Road-density', 'Share-of-the-Internet-users', 'Share-of-households-with-Internet', 'Number-of-mobile-cellular-subscriptions', 'Military-expenditure', 'Military-expenditure-as-a-share-of-GDP', 'Arms-exports', 'Arms-imports', 'Exports', 'Goods-exports', 'Service-exports', 'Merchandise-exports', 'Food-exports', 'Fuel-exports', 'High-technology-exports', 'High-technology-exports-as-a-share-of-exports', 'Imports', 'Goods-imports', 'Service-imports', 'Merchandise-imports', 'Food-imports', 'Fuel-imports', 'Number-of-arrivals', 'Number-of-departures', 'Tourism-expenditures', 'Tourism-expenditures-as-a-share-of-imports', 'Expenditures-for-passenger-transport-items', 'Expenditures-for-travel-items', 'Tourism-receipts', 'Tourism-receipts-as-a-share-of-exports', 'Receipts-for-passenger-transport-items', 'Receipts-for-travel-items', 'CO2-emissions', 'CO2-emissions-per-capita', 'CO2-emissions-intensity', 'Quantity-of-municipal-waste-collected', 'Human-development-index', 'Ease-of-doing-business-index', 'Global-competitiveness-index', 'Corruption-perceptions-index', 'Index-of-economic-freedom', 'Press-freedom-index', 'Political-rights-index', 'Civil-liberties-index', 'Property-rights-index', 'Prosperity-index', 'Happiness', 'Population', 'Population-growth-rate', 'Population-density', 'Urban-population', 'Birth-rate', 'Death-rate', 'Fertility-rate', 'Population-aged-0-14-years', 'Population-aged-15-64-years', 'Population-aged-65-years-and-above', 'Female-population', 'Employment-to-population-ratio', 'Land-area', 'Agricultural-land-area', 'Agricultural-land-as-a-share-of-land-area', 'Forest-area-as-a-share-of-land-area', 'Agriculture-value-added-per-worker', 'Food-production-index', 'Livestock-production-index', 'Crop-production-index', 'Cereal-production', 'Cereal-yield', 'Land-under-cereal-production', 'Number-of-tractors', 'Fertilizer-consumption', 'Neonatal-mortality-rate', 'Infant-mortality-rate', 'Child-mortality-rate', 'Maternal-mortality-ratio', 'Life-expectancy', 'Health-expenditure-as-a-share-of-GDP', 'Health-expenditure-per-capita', 'HIV-prevalence', 'Incidence-of-tuberculosis', 'Female-obesity-prevalence', 'Male-obesity-prevalence', 'Education-expenditure', 'Primary-enrollment', 'Duration-of-primary-education', 'Duration-of-secondary-education', 'Pupil-teacher-ratio-in-primary-education', 'Pupil-teacher-ratio-in-secondary-education', 'Adult-literacy-rate', 'Youth-literacy-rate', 'Homicide-rate', 'Number-of-homicides', 'Number-of-homicides-by-firearm', 'Share-of-homicides-by-firearm', 'Homicides-by-firearm-rate', 'Assault-rate', 'Kidnapping-rate', 'Robbery-rate', 'Rape-rate', 'Burglary-rate', 'Private-car-theft-rate', 'Motor-vehicle-theft-rate', 'Burglary-and-housebreaking-rate', 'Poverty-rate-at-dollar19-a-day', 'Poverty-rate-at-dollar32-a-day', 'Poverty-rate-at-national-poverty-line', 'Rural-poverty-rate', 'Urban-poverty-rate', 'GINI-index', 'Income-share-held-by-lowest-10percent', 'Income-share-held-by-highest-10percent', 'Prevalence-of-undernourishment', 'Number-of-undernourished-people', 'Food-deficit', 'Dietary-energy-supply-adequacy', 'Precipitation', 'Precipitation-volume', 'Rainfall-index', 'Volume-of-groundwater-produced', 'Volume-of-surface-water-produced', 'Internal-renewable-water-resources-per-capita', 'Renewable-water-resources-per-capita', 'Dependency-ratio', 'Freshwater-withdrawals', 'Water-productivity', 'RandD-expenditure', 'Number-of-researchers-in-RandD', 'Number-of-technicians-in-RandD', 'Number-of-scientific-journal-articles', 'Number-of-patent-applications'] self.urls = ['https://knoema.com/atlas/United-States-of-America/%s' %(indic) for indic in self.indics] self.source = list(zip(self.indics, self.urls)) self.file = open('./indicators.json', 'w', encoding='utf-8') super(Get_indic_idSpider, self).__init__(self.basic_func, self.source) def basic_func(self, index, src_item): indic, url = src_item html = self.sess.get(url).text soup = BeautifulSoup(html, 'lxml') payload_data = json.loads(soup.find('input', {'name': 'datadescriptor'}).attrs['value']) item = {} item['id'] = str(payload_data['Stub'][0]['Members'][0]) item['name'] = indic # print(item) self.save_item(item) def save_item(self, item): content = json.dumps(item, ensure_ascii=False) + '\n' self.file.write(content) self.file.flush() if __name__=="__main__": spider = Get_indic_idSpider() # spider.test() spider.crawl() spider.file.close()
5,450
2,097
from random import choice from copy import deepcopy def minCut(G): # the function which randomly chooses the edges and fuses the nodes which are linked with that edge # input: the graph G, represented by a dictionary # output: the min cut # while the graph has more than two nodes, randomly choose two nodes and fuse them while len(G) > 2: vertex1 = choice(list(G.keys())) vertex2 = choice(G[vertex1]) fuse(vertex1, vertex2, G) # pop the second element, return the length of it which is the min cut return len(G.popitem()[1]) def fuse(node1, node2, G): # the function which fuses nodes based on the randomly chosen edge # it also removes the self edges # input: node1 - the first node # node2 - the second node # G - the graph # add the edges of node2 to node1 G[node1].extend(G[node2]) # look at all edges of node2, then go to the nodes which are linked with those # edges and change the direction from node2 to node1 for edge in G[node2]: lst = G[edge] for i in range(0, len(lst)): if lst[i] == node2: lst[i] = node1 # remove self-loops from node1 while node1 in G[node1]: G[node1].remove(node1) # remove node2 from the graph del G[node2] # read the file lista = "D:/Workbench/Online Courses/Design and Analysis of Algorithms, Part 1/Programming Assignment 3/file.txt" f = open(lista, 'r') line_list = f.readlines() G = {int(line.split()[0]): [int(val) for val in line.split()[1:] if val] for line in line_list if line} # initialize the value of mincut to a very large number mincut = 10000000000000 # iterate a thousand times with different random choices to get the min cut value # In theory the number of iterations should be n^2logn, which in our case would be 305600 # On a decent computer, it would take days to run it, so instead I chose to run a thousand iterations # The probability of getting the wrong min cut is bigger than 1/200, but it still should be small enough # Obviously, the theoretical guarantee here is lacking, but at worst case it should give us a good min cut. for i in range(1000): curr = minCut(deepcopy(G)) if curr < mincut: mincut = curr # print the best value from mincut print str(mincut)
2,556
794
import tvm from tvm.tensor_graph.core2.graph.concrete import Compute, Tensor from .padding import zero_pad2d ###################################################################### # for functional, all states are inputs, data from inside functionals # can only be constants ###################################################################### def conv2d_nchw(inputs, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, output_dtype="float32", requires_grad=False): """Convolution 2d NCHW layout Args: ----------------------------- inputs : Tensor shape [batch, channel, height, width] weight : Tensor shape [out_channel, channel // groups, kernel_height, kernel_width] bias : (optional:None) Tensor shape [out_channel] stride : (optional:1) int or tuple padding : (optional:0) int or tuple dilation: (optional:1) int groups : (optional:1) int ----------------------------- Returns: ----------------------------- Tensor shape [batch, out_channel, output_height, output_width] ----------------------------- """ batch_size, in_channel, in_h, in_w = inputs.shape out_channel, channel_per_group, k_h, k_w = weight.shape assert channel_per_group * groups == in_channel, "%d vs. %d" % (channel_per_group * groups, in_channel) out_channel_per_group = out_channel // groups assert out_channel_per_group * groups == out_channel stride = (stride, stride) if isinstance(stride, (int, tvm.tir.IntImm)) else stride padding = (padding, padding) if isinstance(padding, (int, tvm.tir.IntImm)) else padding dilation = (dilation, dilation) if isinstance(dilation, (int, tvm.tir.IntImm)) else dilation assert isinstance(stride, tuple) and len(stride) == 2 assert isinstance(padding, tuple) and len(padding) == 2 assert isinstance(dilation, tuple) and len(dilation) == 2 out_h = (in_h + 2 * padding[0] - dilation[0] * (k_h - 1) - 1) // stride[0] + 1 out_w = (in_w + 2 * padding[1] - dilation[1] * (k_w - 1) - 1) // stride[1] + 1 padded = zero_pad2d(inputs, padding=padding, output_dtype=output_dtype, requires_grad=requires_grad) conv_out_shape = (batch_size, out_channel, out_h, out_w) if bias is not None: if groups > 1: def _inner_conv2d_nchw(padded, weight, bias): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, c // out_channel_per_group * channel_per_group + rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) + bias[c] / (channel_per_group*k_w*k_h) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, bias, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out else: def _inner_conv2d_nchw(padded, weight, bias): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) + bias[c] / (channel_per_group*k_w*k_h) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, bias, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out else: if groups > 1: def _inner_conv2d_nchw(padded, weight): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, c // out_channel_per_group * channel_per_group + rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out else: def _inner_conv2d_nchw(padded, weight): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out
5,223
1,745
import numpy as np from functools import lru_cache, wraps #from fastcache import clru_cache def np_lru_cache(*args, **kwargs): """ LRU cache implementation for functions whose FIRST parameter is a numpy array forked from: https://gist.github.com/Susensio/61f4fee01150caaac1e10fc5f005eb75 """ def decorator(function): @wraps(function) def wrapper(np_array): return cached_wrapper( tuple(np_array)) @lru_cache(*args, **kwargs) #@clru_cache(*args, **kwargs) def cached_wrapper(hashable_array): return function(np.array(hashable_array)) # copy lru_cache attributes over too wrapper.cache_info = cached_wrapper.cache_info wrapper.cache_clear = cached_wrapper.cache_clear return wrapper return decorator if __name__ == '__main__': ar = np.random.randint(0, 100, (1000, 100)) f = lambda arr: np.std(arr + arr/(1 + arr**2) - arr + np.sin(arr) * np.cos(arr) + 2) def no_c(arr): return f(arr) @np_lru_cache(maxsize = 700, typed = True) def with_c(arr): return f(arr) #%time for _ in range(50): [no_c(arr) for arr in ar[np.random.rand(ar.shape[0]).argsort()]] #%time for _ in range(50): [with_c(arr) for arr in ar[np.random.rand(ar.shape[0]).argsort()]]
1,352
501
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from auto_scan_test import OPConvertAutoScanTest, BaseNet from hypothesis import reproduce_failure import hypothesis.strategies as st import numpy as np import unittest import paddle class Net0(BaseNet): """ simple Net """ def __init__(self, config=None): super(Net0, self).__init__(config) self.lstm = paddle.nn.LSTM( input_size=self.config["input_size"], hidden_size=self.config["hidden_size"], num_layers=self.config["num_layers"], direction=self.config["direction"], time_major=self.config["time_major"]) def forward(self, inputs, prev_h, prev_c): """ forward """ y, (h, c) = self.lstm(inputs, (prev_h, prev_c)) return y class Net1(BaseNet): """ simple Net """ def __init__(self, config=None): super(Net1, self).__init__(config) self.gru = paddle.nn.GRU(input_size=self.config["input_size"], hidden_size=self.config["hidden_size"], num_layers=self.config["num_layers"], direction=self.config["direction"], time_major=self.config["time_major"]) def forward(self, inputs, prev_h): """ forward """ y, h = self.gru(inputs, prev_h) return y class TestRNNConvert0(OPConvertAutoScanTest): """ api: paddle.nn.LSTM OPset version: 7, 9, 15 """ def sample_convert_config(self, draw): input_shape = draw( st.lists( st.integers( min_value=4, max_value=10), min_size=3, max_size=3)) dtype = draw(st.sampled_from(["float32"])) hidden_size = 32 num_layers = 2 time_major = draw(st.booleans()) if time_major == True: t, b, input_size = input_shape else: b, t, input_size = input_shape direction = draw(st.sampled_from(["forward", "bidirect"])) if direction == "forward": num_directions = 1 else: num_directions = 2 prev_h_shape = [num_layers * num_directions, b, hidden_size] prev_c_shape = [num_layers * num_directions, b, hidden_size] config = { "op_names": ["rnn"], "test_data_shapes": [input_shape, prev_h_shape, prev_c_shape], "test_data_types": [[dtype], [dtype], [dtype]], "opset_version": [7, 9, 15], "input_spec_shape": [], "input_size": input_size, "hidden_size": hidden_size, "num_layers": num_layers, "direction": direction, "time_major": time_major, } models = Net0(config) return (config, models) def test(self): self.run_and_statis(max_examples=30) class TestRNNConvert1(OPConvertAutoScanTest): """ api: paddle.nn.GRU OPset version: 7, 9, 15 """ def sample_convert_config(self, draw): input_shape = draw( st.lists( st.integers( min_value=4, max_value=10), min_size=3, max_size=3)) dtype = draw(st.sampled_from(["float32"])) hidden_size = 32 num_layers = 2 time_major = draw(st.booleans()) if time_major == True: t, b, input_size = input_shape else: b, t, input_size = input_shape direction = draw(st.sampled_from(["forward", "bidirect"])) if direction == "forward": num_directions = 1 else: num_directions = 2 prev_h_shape = [num_layers * num_directions, b, hidden_size] config = { "op_names": ["rnn"], "test_data_shapes": [input_shape, prev_h_shape], "test_data_types": [[dtype], [dtype]], "opset_version": [7, 9, 15], "input_spec_shape": [], "input_size": input_size, "hidden_size": hidden_size, "num_layers": num_layers, "direction": direction, "time_major": time_major, } models = Net1(config) return (config, models) def test(self): self.run_and_statis(max_examples=30) if __name__ == "__main__": unittest.main()
4,951
1,562
# Generated by Django 4.0.1 on 2022-01-28 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project_organizer', '0008_rename_tg_id_student_tg_user_project_manager_tg_user_and_more'), ] operations = [ migrations.AddField( model_name='project_manager', name='from_time', field=models.TimeField(blank=True, null=True, verbose_name='Available from a time'), ), migrations.AddField( model_name='project_manager', name='until_time', field=models.TimeField(blank=True, null=True, verbose_name='Available until a time'), ), ]
706
225
from bintray.bintray import Bintray def test_get_user(): bintray = Bintray() response = bintray.get_user("uilianries") assert response.get("name") == "uilianries" assert response.get("error") == False assert response.get("statusCode") == 200 def test_get_organization(): bintray = Bintray() response = bintray.get_organization("jfrog") assert response.get("name") == "jfrog" assert response.get("error") == False assert response.get("statusCode") == 200 def test_get_followers(): bintray = Bintray() response = bintray.get_followers("uilianries") assert [{'name': 'solvingj'}, {'error': False, 'statusCode': 200}] == response def test_search_user(): bintray = Bintray() response = bintray.search_user("uilianries") assert {'error': False, 'statusCode': 200} in response
842
291
#! /usr/bin/env python import sys import os version_file = os.path.join( os.path.abspath(os.path.dirname(__file__)), "problog/version.py" ) version = {} with open(version_file) as fp: exec(fp.read(), version) version = version["version"] if __name__ == "__main__" and len(sys.argv) == 1: from problog import setup as problog_setup problog_setup.install() elif __name__ == "__main__": from setuptools import setup, find_packages from setuptools.command.install import install class ProbLogInstall(install): def run(self): install.run(self) before_dir = os.getcwd() sys.path.insert(0, self.install_lib) from problog import setup as problog_setup try: problog_setup.install() except Exception as err: print("Optional ProbLog installation failed: %s" % err, file=sys.stderr) os.chdir(before_dir) package_data = { "problog": [ "bin/darwin/cnf2dDNNF_wine", "bin/darwin/dsharp", "bin/darwin/maxsatz", "bin/linux/dsharp", "bin/linux/maxsatz", "bin/source/maxsatz/maxsatz2009.c", "bin/windows/dsharp.exe", "bin/windows/maxsatz.exe", "bin/windows/libgcc_s_dw2-1.dll", "bin/windows/libstdc++-6.dll", "web/*.py", "web/editor_local.html" "web/editor_adv.html", "web/js/problog_editor.js", "library/*.pl", "library/*.py", "library/nlp4plp.d/*", ] } setup( name="problog", version=version, description="ProbLog2: Probabilistic Logic Programming toolbox", url="https://dtai.cs.kuleuven.be/problog", author="ProbLog team", author_email="anton.dries@cs.kuleuven.be", license="Apache Software License", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: Apache Software License", "Intended Audience :: Science/Research", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Prolog", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], keywords="prolog probabilistic logic", packages=find_packages(), extras_require={"sdd": ["pysdd>=0.2.6"]}, entry_points={"console_scripts": ["problog=problog.tasks:main"]}, package_data=package_data, cmdclass={"install": ProbLogInstall}, ) def increment_release(v): v = v.split(".") if len(v) == 4: v = v[:3] + [str(int(v[3]) + 1)] else: v = v[:4] return ".".join(v) def increment_dev(v): v = v.split(".") if len(v) == 4: v = v[:3] + [str(int(v[3]) + 1), "dev1"] else: v = v[:4] + ["dev" + str(int(v[4][3:]) + 1)] return ".".join(v) def increment_version_dev(): v = increment_dev(version) os.path.dirname(__file__) with open(version_file, "w") as f: f.write("version = '%s'\n" % v) def increment_version_release(): v = increment_release(version) with open(version_file, "w") as f: f.write("version = '%s'\n" % v)
3,424
1,140