text
stringlengths
38
1.54M
import logging from collections import deque from combo import Combo from ability import Ability class Rotation(): deck = deque() def use(self, action): """ This method is designed for fully formed combos that manage their own hotkey callbacks and doesn't require a copy to be made. """ if isinstance(action, Combo): if action not in self.combo_list: self.combo_list.append(action) elif isinstance(action, Ability): if action not in self.ability_list: self.ability_list.append(action) else: logging.debug("Invalid action passed to Rotation") def add(self, round): self.deck.append(round) def get_combo_at(self, position): try: combo = (i for i in self.deck[position] if isinstance(i, Combo)) return next(combo) except StopIteration as e: return None def print_rotation(self): """ Print a string representation of the actions associated with this roatation. If this is a priority-based rotation, show the next 10 items. """ pass def __str__(self): """ Returns as a string the 'word' for the current rotation queue. """ word = list() for i, actions in sorted(self.actions.items()): for a in actions: word.append(a.word) return ''.join(word)
import png from node import Node from color import Color # Takes in a color list and creates a png def listToPNG(colorList, directory, filename): # Create a writer object picheight = 80 # the height of the pic bandwidth = 2 # The width each color gets outputer = png.Writer(size=(bandwidth*len(colorList), picheight)) # Create a 'layer' of colors colorlayer = [] for col in colorList: for x in range(bandwidth): colorlayer.append(col.red) colorlayer.append(col.green) colorlayer.append(col.blue) # Repeat the layers until it satisfies the height totallayers = [] for i in range(picheight): totallayers.append(colorlayer) # Open and write to the file picfile = open(directory+'/'+filename, 'wb') outputer.write(picfile, totallayers)
#!/usr/bin/python import sys import sip from PyQt4.Qt import * #wrap raw pointer to specified Qt-class def wrap(type, ptr): return sip.wrapinstance(ptr, type) #def main(): # ts_raw - loaded from C++ environment print("raw value:", ts_raw); ts_wrapped = ts_raw; ts_wrapped.trigger_str("hello from python!") app = QCoreApplication.instance() if not (app): app = QApplication(sys.argv) print("raw www:", www); www = QWidget() print("raw2 www:", www); www.resize(250, 150) www.move(300, 300) www.setWindowTitle('Simple') btn = QPushButton('Button', www) btn.setToolTip('This is a <b>QPushButton</b> widget') btn.resize(btn.sizeHint()) btn.move(50, 50) btn.clicked.connect(ts_wrapped.trigger) www.show() #sys.exit(app.exec_()) #if __name__ == '__main__': #main()
# import the random module import random while(True): # creating a loop because user can play this game as his or her wish times print("Dear user you have option!, they are:") print("'rock','paper','scissors'") # take input from the user using input() function in python. # Then create the computer choice using randint() function from the Random module. userchoice = input("Enter your choice: ") com_choice = random.randint(1,3) # Now, we will convert the computer's input from 1, 2, 3 into 'p', 'r','s'. if com_choice == 1: com_choice = "rock" elif com_choice == 2: com_choice = "paper" elif com_choice == 3: com_choice = "scissors" else: print("sorry, something went wrong!") # Now, compare the user choice with computer choice using nested if...else. # And if both choices are same there is a tie. if com_choice == userchoice: print("It's a tie") elif userchoice == "rock": if com_choice == "scissors": print("Congratulations,you won !") else: print("Computer won!") elif userchoice == "paper": if com_choice == "rock": print("Congratulations,you won !") else: print("Computer won!") elif userchoice == "scissors": if com_choice == "paper": print("Congratulation,you won !") else: print("Computer won") # Now, take input whether the user wants to play again if no then break the loop. print("Do you want to play agin?") print("Then Enter (y/n) for answer") ans = input() if ans == "n" or ans == "N": break
import tensorflow as tf import numpy as np c = tf.constant([[1,2,3], [4,5,6]]) print("Python list input: {}".format(c.get_shape())) c = tf.constant([[[1,2,3],[4,5,6]], [[1,1,1], [2,2,2]]]) print("3d NumPy array Input: {}".format(c.get_shape())) # One method to avoid constantly refering to the session var is to use InteractiveSession sess = tf.InteractiveSession() c = tf.lin_space(0.0, 4.0, 5) print("The content of 'c':\n {}\n".format(c.eval())) sess.close()
def currentModule(request): from django.conf import settings from menu.models import Entry # Get candidates and current path candidates = [] for menuEntry in Entry.objects.all(): candidates.append({ 'name': menuEntry.name, 'path': menuEntry.path, }) path = request.path # Determine the best candidate best = { 'name': 'default', 'length': 0, } for candidate in candidates: if (candidate['path'] == path[:len(candidate['path'])] and len(candidate['path']) > best['length']): best['name'] = candidate['name'] best['length'] = len(candidate['path']) if best['length'] > 0: currentModule = best['name'] else: currentModule = settings.DEFAULT_MODULE return {'currentModule': currentModule}
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-02 21:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('eBedTrack', '0004_auto_20171002_1140'), ] operations = [ migrations.AlterField( model_name='bed', name='bed_type', field=models.CharField(choices=[('AD ICU/CC', 'AD ICU/CC'), ('ER', 'ER'), ('MED/SURG', 'MED/SURG'), ('OB', 'OB'), ('SICU', 'SICU'), ('Neg Pres/Iso', 'Neg Pres/Iso'), ('OR', 'OR'), ('Peds', 'Peds'), ('PICU', 'PICU'), ('NICU', 'NICU'), ('Burn', 'Burn'), ('Mental_Health', 'Mental_Health'), ('Other', 'Other')], max_length=50), ), ]
from codetiming import Timer # code snippet which using decorators to calculate function execution time # the code prints Elapsed Time - saying hello: 0.0001265000000000016 secs @Timer(name='saying hello', text='Elapsed Time - {name}: {} secs') def say_hello(): print('Hello World!') say_hello()
import argparse import torch import torch.nn as nn import torch.nn.functional as F class RejectionCrossEntropyLoss(nn.Module): """ Based on https://arxiv.org/pdf/1907.00208.pdf o (payoff) should be between 1 < o < num_classes """ def __init__(self, o, out_vocab, rejection_index, reduction="none", weight=None): super(RejectionCrossEntropyLoss, self).__init__() assert 0 <= rejection_index < out_vocab assert reduction == "none", 'Only reduction="none" is currently supported' assert o is not None self.reduction = reduction self.rejection_index = rejection_index self.o = o self.softmax = nn.Softmax(dim=-1) self.weight = weight def forward(self, x, y): p = self.softmax(x) p_m = p.select(-1, self.rejection_index).unsqueeze(dim=1) loss = F.nll_loss( torch.log(p * self.o + p_m), y, reduction="none", weight=self.weight ) return loss @staticmethod def args(): parser = argparse.ArgumentParser("RejectionCrossEntropyLoss", add_help=False) parser.add_argument( "--o", type=float, help="Payoff value, should in range 1 < o < num_classes" ) return parser
import requests from bs4 import BeautifulSoup from datetime import datetime, timedelta import locale locale.setlocale(locale.LC_ALL, 'ID') import re import pandas as pd from selenium import webdriver from selenium.webdriver.chrome.options import Options import html import json import time from requests.exceptions import ConnectionError import unicodedata import mysql.connector class Tempo: def getAllBerita(self, details, date=datetime.strftime(datetime.today(), '%Y/%m/%d')): """ Untuk mengambil seluruh url link pada indeks category tertentu date format : YYYY-mm-dd """ url = "https://www.tempo.co/indeks/"+date print(url) # Make the request and create the response object: response try: response = requests.get(url) except ConnectionError: print("Connection Error, but it's still trying...") time.sleep(10) details = self.getAllBerita(details, date) # Extract HTML texts contained in Response object: html html = response.text # Create a BeautifulSoup object from the HTML: soup soup = BeautifulSoup(html, "html5lib") contentDiv = soup.find('section', {'id':'article'}).find('section', class_="list list-type-1") indeks = contentDiv.findAll('li') if indeks: for post in indeks: link = [post.find('a', {'class':'col'}, href=True)['href'], ""] con = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='news_db') cursor = con.cursor() query = "SELECT count(*) FROM article WHERE url like '"+link[0]+"'" cursor.execute(query) result = cursor.fetchone() cursor.close() con.close() if(result[0] <= 0): detail = self.getDetailBerita(link) if detail: if self.insertDB(detail): details.append(detail) return 'berhasil ambil semua berita' def getDetailBerita(self, link): """ Mengambil seluruh element dari halaman berita """ time.sleep(2) articles = {} #link url = link[0] print(url) try: response = requests.get(url) except ConnectionError: print("Connection Error, but it's still trying...") time.sleep(10) self.getDetailBerita(link) except: return False html2 = response.text # Create a BeautifulSoup object from the HTML: soup soup = BeautifulSoup(html2, "html5lib") #extract scrip json ld scripts_all = soup.findAll('script', attrs={'type':'application/ld+json'}) if scripts_all: scripts1 = re.sub(r'\n|\t|\b|\r','',unicodedata.normalize("NFKD",scripts_all[0].get_text(strip=True))) scripts_akhir = re.sub(r"(\s*\"articleBody\" *: *\".*\"(,|(?=\s+\})))(?=\s*\"datePublished\" *: *\".*\"(,|(?=\s+\})))","\n",scripts1) # print(scripts) try: scripts = json.loads(html.unescape(scripts_akhir)) except: return False scripts2 = re.sub(r'\n|\t|\b|\r','',unicodedata.normalize("NFKD",scripts_all[1].get_text(strip=True))) scripts2 = json.loads(html.unescape(scripts2)) else: return False #category articles['category'] = scripts2['itemListElement'][-2]['item']['name'] articles['subcategory'] = scripts2['itemListElement'][-1]['item']['name'] articles['url'] = url article = soup.find('article', {'itemtype':"http://schema.org/NewsArticle"}) if not article: return False #extract date pubdate = scripts['datePublished'] pubdate = pubdate[0:19].strip(' \t\n\r') articles['pubdate'] = datetime.strftime(datetime.strptime(pubdate, "%Y-%m-%dT%H:%M:%S"), '%Y-%m-%d %H:%M:%S') id = soup.find('meta', {'property':"dable:item_id"}) articles['id'] = int(id['content']) if id else int(datetime.strptime(pubdate, "%d-%b-%Y %H:%M").timestamp()) + len(url) #extract author articles['author'] = scripts['editor']['name'] #extract title articles['title'] = scripts['headline'] #source articles['source'] = 'tempo' #extract comments count articles['comments'] = 0 #extract tags tags = article.find('div', class_="tags clearfix") articles['tags'] = ','.join([x.get_text(strip=True) for x in tags.findAll('a')]) if tags else '' #extract images articles['images'] = scripts['image']['url'] #extract detail detail = article.find('div', attrs={'id':'isi'}) #hapus div if detail.findAll('div'): for div in detail.findAll('div'): if div.find('script'): div.decompose() #hapus link sisip if detail.findAll('p'): for p in detail.findAll('p'): if ("baca:" in p.get_text(strip=True).lower()): p.decompose() #extract content detail = BeautifulSoup(detail.decode_contents().replace('<br/>', ' '), "html5lib") content = re.sub(r'\n|\t|\b|\r','',unicodedata.normalize("NFKD",detail.get_text(strip=True))) articles['content'] = content print('memasukkan berita id ', articles['id']) return articles def insertDB(self, articles): """ Untuk memasukkan berita ke DB """ con = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='news_db') print("Insert berita ", articles['title']) cursor = con.cursor() query = "SELECT count(*) FROM article WHERE url like '"+articles['url']+"'" cursor.execute(query) result = cursor.fetchone() if result[0] <= 0: add_article = ("INSERT INTO article (post_id, author, pubdate, category, subcategory, content, comments, images, title, tags, url, source) VALUES (%(id)s, %(author)s, %(pubdate)s, %(category)s, %(subcategory)s, %(content)s, %(comments)s, %(images)s, %(title)s, %(tags)s, %(url)s, %(source)s)") # Insert article cursor.execute(add_article, articles) con.commit() print('masuk') cursor.close() con.close() return True else: cursor.close() print('salah2') con.close() return False
# Generated by Django 3.2.3 on 2021-05-31 13:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bis', '0001_initial'), ] operations = [ migrations.CreateModel( name='Hizlaria', fields=[ ('h_id', models.AutoField(primary_key=True, serialize=False)), ('abizenak', models.CharField(max_length=100, unique=True)), ('alderdia', models.CharField(choices=[('ARARTEKO', 'Arartekoa'), ('EAJ', 'EAJ'), ('EB', 'Ezker Batua'), ('EH Bildu', 'Bildu'), ('EP', 'Elkarrekin Podemos'), ('N', 'Ezezaguna'), ('PP', 'PP'), ('PSE-EE', 'PSE'), ('UPyD', 'UPyD')], max_length=100)), ('generoa', models.CharField(choices=[('E', 'Emakume'), ('G', 'Gizon'), ('N', 'Ezezagun')], max_length=100)), ('informazioa', models.CharField(blank=True, max_length=200)), ], options={ 'verbose_name_plural': 'Hizlariak', }, ), migrations.CreateModel( name='ParteHartzea', fields=[ ('p_id', models.AutoField(primary_key=True, serialize=False)), ('data', models.DateField(verbose_name='parte-hartzearen data')), ('p_ordena', models.IntegerField(default=0)), ('hizlaria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='bis.hizlaria')), ], options={ 'verbose_name_plural': 'ParteHartzeak', 'unique_together': {('data', 'p_ordena')}, }, ), migrations.CreateModel( name='Testua', fields=[ ('t_id', models.AutoField(primary_key=True, serialize=False)), ('t_ordena', models.IntegerField(default=0)), ('testua', models.TextField()), ('hizkuntza', models.CharField(max_length=10)), ('entitateak', models.TextField()), ('parteHartzea', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='bis.partehartzea')), ], options={ 'verbose_name_plural': 'Testuak', 'unique_together': {('parteHartzea', 't_ordena')}, }, ), migrations.DeleteModel( name='Choice', ), migrations.DeleteModel( name='Question', ), ]
from common import db, ma from flask import jsonify from flask_restful import Resource # reading workload simple class ReadingWorkloadSimple(db.Model): id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(10)) amount = db.Column(db.Float) intercept = db.Column(db.Float) def __init__(self, code, attr_list): self.code = code self.amount = attr_list[0] self.intercept = attr_list[1] def update(self, attr_list): self.amount = attr_list[0] self.intercept = attr_list[1] class ReadingWorkloadSimpleSchema(ma.ModelSchema): class Meta: model = ReadingWorkloadSimple reading_workload_simple_schema = ReadingWorkloadSimpleSchema(strict=True) class ReadingWorkloadSimpleResource(Resource): def get(self, module_code): query = ReadingWorkloadSimple.query.filter_by(code=module_code).first() result = reading_workload_simple_schema.dump(query).data return jsonify(result) # reading workload complex class ReadingWorkloadComplex(db.Model): id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(10)) cap = db.Column(db.Float) semesters = db.Column(db.Float) credits = db.Column(db.Float) amount = db.Column(db.Float) intercept = db.Column(db.Float) def __init__(self, code, attr_list): self.code = code self.cap = attr_list[0] self.semesters = attr_list[1] self.credits = attr_list[2] self.amount = attr_list[3] self.intercept = attr_list[4] def update(self, attr_list): self.cap = attr_list[0] self.semesters = attr_list[1] self.credits = attr_list[2] self.amount = attr_list[3] self.intercept = attr_list[4] class ReadingWorkloadComplexSchema(ma.ModelSchema): class Meta: model = ReadingWorkloadComplex reading_workload_complex_schema = ReadingWorkloadComplexSchema(strict=True) class ReadingWorkloadComplexResource(Resource): def get(self, module_code): query = ReadingWorkloadComplex.query.filter_by(code=module_code).first() result = reading_workload_complex_schema.dump(query).data return jsonify(result)
#### This problem will be graded manually. #### Please ignore the points given out by Tutor. def addRowMulByC(matA,i,c,j): nl =[] nnl = [] for k in matA[i]: nl.append(k*c) for c in range(len(matA[0])): nnl.append(matA[j][c]+nl[c]) del matA[j] matA.insert(j,nnl) return matA print addRowMulByC([[0,2,1,-1],[0,0,3,1],[0,0,0,0]],0,0.5,1)
# -------------------------------------------------------------- # # Daily Code 03/04/2021 # "Name Greeting!" Lesson from edabit.com # Coded by: Banehowl # -------------------------------------------------------------- # Create a function that takes a name and returns a greeting in the form of a string. # hello_name("Gerald") -> "Hello Gerald!" # hello_name("Tiffany") -> "Hello Tiffany!" # hello_name("Ed") -> "Hello Ed!" def hello_name(name): greet = "Hello %s!" % name return greet print hello_name("Gerald") print hello_name("Tiffany") print hello_name("Ed")
__author__ = 'tan' import socket import fcntl import struct from juliabox.jbox_util import LoggerMixin, JBoxPluginType, JBoxCfg import random class JBPluginCloud(LoggerMixin): """ Interfaces with cloud service providers or provides similar services locally. - `JBPluginCloud.JBP_BUCKETSTORE`, `JBPluginCloud.JBP_BUCKETSTORE_S3`: Provides storage for blobs of data in named buckets. Similar to Amazon S3 or OpenStack Swift. - `push(bucket, local_file, metadata=None)` - `pull(bucket, local_file, metadata_only=False)` - `delete(bucket, local_file)` - `copy(from_file, to_file, from_bucket, to_bucket=None)` - `move(from_file, to_file, from_bucket, to_bucket=None)` - `JBPluginCloud.JBP_DNS`, `JBPluginCloud.JBP_DNS_ROUTE53`: DNS service. - `configure()`: Read and store configuration from JBoxCfg. - `domain()`: Return the domain name configured to be used - `add_cname(name, value)`: Add a CNAME entry - `delete_cname(name)`: Delete the specified CNAME entry. - `JBPluginCloud.JBP_SENDMAIL`, `JBPluginCloud.JBP_SENDMAIL_SES`: E-Mail sending service. - `configure()`: Read and store configuration from JBoxCfg. - `get_email_rates()`: Rate limits to adhere to, as `daily_quota_remaining`,`rate_per_sec` - `send_email(rcpt, sender, subject, body)`: Send email as specified. - `JBPluginCloud.JBP_COMPUTE`, `JBPluginCloud.JBP_COMPUTE_EC2`, `JBPluginCloud.JBP_COMPUTE_SINGLENODE`: Compute facility - start/stop instances to scale the cluster up or down based on the decided loading pattern, DNS, record and query load statistics which will be used in scaling decisions. - `configure()`: Read and store configuration from JBoxCfg. - `get_install_id()`: Returns an unique ID for the installation. This allows multiple installations on shared infrastructure. - `get_instance_id()`: Returns an identifier for each instance/machine. - `get_alias_hostname()`: Returns a hostname belonging to the installation domain with which the current instance can be reached. - `get_all_instances(gname=None)` - `get_instance_public_hostname(instance_id=None)`: hostname accessing from public network (may not be same as get_alias_hostname) - `get_instance_local_hostname(instance_id=None)`: hostname accessible within the cluster, but not from public network - `get_instance_public_ip(instance_id=None)` - `get_instance_local_ip(instance_id=None)` - `publish_stats(stat_name, stat_unit, stat_value)`: Record performance/load statistics. - `publish_stats_multi(stats)`: Record multiple performance/load statistics. - `get_instance_stats(instance, stat_name, namespace=None)`: Query recorded statistics. - `get_cluster_stats(stat_name, namespace=None)`: Query cluster wide recorded statistics. - `get_cluster_average_stats(stat_name, namespace=None, results=None)`: Query cluster wide averages of recorded statistics. - `terminate_instance(instance=None)`: Terminate the specified instance. Self if instance is None. - `can_terminate(is_leader)`: Whether the instance can be terminated now (to scale down). - `should_accept_session(is_leader)`: Whether the instance can accept more load. - `get_redirect_instance_id()`: If the current instance is not ready to accept further load, a suggestion on which instance to load instead. - `get_image_recentness(instance=None)`: Whether the application image running on the instance is the latest. - `get_available_instances()`: Returns a list of instance props when using fixed size cluster. """ JBP_BUCKETSTORE = "cloud.bucketstore" JBP_BUCKETSTORE_S3 = "cloud.bucketstore.s3" JBP_BUCKETSTORE_GS = "cloud.bucketstore.gs" JBP_DNS = "cloud.dns" JBP_DNS_ROUTE53 = "cloud.dns.route53" JBP_DNS_GCD = "cloud.dns.gcd" JBP_SENDMAIL = "cloud.sendmail" JBP_SENDMAIL_SES = "cloud.sendmail.ses" JBP_SENDMAIL_SMTP = "cloud.sendmail.smtp" JBP_COMPUTE = "cloud.compute" JBP_COMPUTE_EC2 = "cloud.compute.ec2" JBP_COMPUTE_SINGLENODE = "cloud.compute.singlenode" JBP_COMPUTE_GCE = "cloud.compute.gce" JBP_MIGRATE = "cloud.migrate" JBP_MONITORING = "cloud.monitoring" JBP_MONITORING_GOOGLE = "cloud.monitoring.google" JBP_MONITORING_GOOGLE_V2 = "cloud.monitoring.google.v2" JBP_MONITORING_GOOGLE_V3 = "cloud.monitoring.google.v3" JBP_SCALER = "cloud.scaler" __metaclass__ = JBoxPluginType class Compute(LoggerMixin): impl = None SCALE = False @staticmethod def configure(): plugin = JBPluginCloud.jbox_get_plugin(JBPluginCloud.JBP_COMPUTE) if plugin is None: Compute.log_error("No plugin found for compute host") raise Exception("No plugin found for compute host") plugin.configure() Compute.impl = plugin Compute.SCALE = JBoxCfg.get('cloud_host.scale_down') @staticmethod def get_install_id(): return Compute.impl.get_install_id() @staticmethod def get_instance_id(): return Compute.impl.get_instance_id() @staticmethod def get_all_instances(gname=None): return Compute.impl.get_all_instances(gname) @staticmethod def get_alias_hostname(): return Compute.impl.get_alias_hostname() @staticmethod def get_instance_public_hostname(instance_id=None): return Compute.impl.get_instance_public_hostname(instance_id) @staticmethod def get_instance_local_hostname(instance_id=None): return Compute.impl.get_instance_local_hostname(instance_id) @staticmethod def get_instance_public_ip(instance_id=None): return Compute.impl.get_instance_public_ip(instance_id) @staticmethod def get_instance_interface_ip(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) siocgifaddr = 0x8915 ifn = struct.pack('256s', ifname[:15]) addr = fcntl.ioctl(s.fileno(), siocgifaddr, ifn)[20:24] return socket.inet_ntoa(addr) @staticmethod def get_docker_bridge_ip(): return Compute.get_instance_interface_ip('docker0') @staticmethod def get_instance_local_ip(instance_id=None): return Compute.impl.get_instance_local_ip(instance_id) @staticmethod def publish_stats(stat_name, stat_unit, stat_value): return Compute.impl.publish_stats(stat_name, stat_unit, stat_value) @staticmethod def publish_stats_multi(stats): return Compute.impl.publish_stats_multi(stats) @staticmethod def get_instance_stats(instance, stat_name, namespace=None): return Compute.impl.get_instance_stats(instance, stat_name, namespace) @staticmethod def get_cluster_stats(stat_name, namespace=None): return Compute.impl.get_cluster_stats(stat_name, namespace) @staticmethod def get_cluster_average_stats(stat_name, namespace=None, results=None): return Compute.impl.get_cluster_average_stats(stat_name, namespace, results) @staticmethod def terminate_instance(instance=None): return Compute.impl.terminate_instance(instance) @staticmethod def can_terminate(is_leader): if not Compute.SCALE: Compute.log_debug("not terminating as cluster size is fixed") return False return Compute.impl.can_terminate(is_leader) @staticmethod def get_available_instances(): return Compute.impl.get_available_instances() @staticmethod def get_redirect_instance_id(): if not Compute.SCALE: Compute.log_debug("cluster size is fixed") available_nodes = Compute.get_available_instances() if len(available_nodes) > 0: return random.choice(available_nodes) else: return None return Compute.impl.get_redirect_instance_id() @staticmethod def should_accept_session(is_leader): self_instance_id = Compute.get_instance_id() self_load = Compute.get_instance_stats(self_instance_id, 'Load') if not Compute.SCALE: accept = self_load < 100 Compute.log_debug("cluster size is fixed. accept: %r", accept) return accept return Compute.impl.should_accept_session(is_leader) @staticmethod def get_image_recentness(instance=None): if not Compute.SCALE: Compute.log_debug("ignoring image recentness as cluster size is fixed") return 0 return Compute.impl.get_image_recentness(instance) @staticmethod def register_instance_dns(): plugin = JBPluginCloud.jbox_get_plugin(JBPluginCloud.JBP_DNS) if plugin is None: return plugin.add_cname(Compute.get_alias_hostname(), Compute.get_instance_public_hostname()) @staticmethod def deregister_instance_dns(): plugin = JBPluginCloud.jbox_get_plugin(JBPluginCloud.JBP_DNS) if plugin is None: return plugin.delete_cname(Compute.get_alias_hostname())
WHITE = (255, 255, 255) BLACK = (0, 0, 0) DARKGREY = (40, 40, 40) LIGHTGREY = (100, 100, 100) GREEN = (0, 255, 0) DARKGREEN = (160, 255, 160) RED = (255, 0, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) NIGHT_COLOR = (20, 20, 20) LIGHT_RADIUS = (500, 500) LIGHT_MASK = "light_350_soft.png" WIDTH = 1024 HEIGHT = 768 FPS = 60 TITLE = "Gra w pygame" BGCOLOR = DARKGREY TILESIZE = 32 GRIDWIDTH = WIDTH / TILESIZE GRIDHEIGHT = HEIGHT / TILESIZE BAR_LENGTH = 100 BAR_HEIGHT = 20 LEVEL_AMOUNT = 2 PLAYER_SPEED = 300 PLAYER_HEALTH = 100
import functools @functools.lru_cache(maxsize=2) def expensive(a, b): print('called expensive({}, {})'.format(a, b)) return a * b def make_call(a, b): print('({}, {})'.format(a, b), end=' ') pre_hits = expensive.cache_info().hits expensive(a, b) post_hits = expensive.cache_info().hits if post_hits > pre_hits: print('cache hit') make_call(1, 2) try: make_call([1], 2) except TypeError as err: print('ERROR: {}'.format(err)) try: make_call(1, {'2': 'two'}) except TypeError as err: print('ERROR: {}'.format(err))
from django.shortcuts import render, redirect from .models import Order, Product from django.db.models import Sum def index(request): context = { "all_products": Product.objects.all() } return render(request, "store/index.html", context) def buy(request): quantity_from_form = int(request.POST["quantity"]) product = Product.objects.get(id=request.POST['product_id']) price_from_form = product.price total_charge = quantity_from_form * price_from_form print(Order.objects.all().values) print("Charging credit card...") Order.objects.create(quantity_ordered=quantity_from_form, total_price=total_charge) return redirect('/checkout') def checkout(request): context = { 'orders': Order.objects.last(), 'numberOfItems': len(Order.objects.all()), 'total': Order.objects.aggregate(Sum('total_price'))['total_price__sum'], } return render(request, 'store/checkout.html', context)
import pygame pygame.init() # initialize # set the size of screen screen_width = 480 # width size screen_height = 640 # height size screen = pygame.display.set_mode((screen_width, screen_height)) # set the title of game pygame.display.set_caption("Nado Game") # game title # FPS clock = pygame.time.Clock() # Loading the background image background = pygame.image.load( r"C:\Users\user01\python\nadocoding\game\background.png") # loading characters character = pygame.image.load( r"C:\Users\user01\python\nadocoding\game\character.png") character_size = character.get_rect().size # get the image size character_width = character_size[0] # character's width character_height = character_size[1] # characeter's height character_x_pos = (screen_width / 2) - (character_width / 2) # the middle of screen width character_y_pos = screen_height - character_height # the bottom of screen heigth # move position to_x = 0 to_y = 0 # move speed charactr_speed = 0.6 # enemy enemy = pygame.image.load(r"C:\Users\user01\python\nadocoding\game\enemy.png") enemy_size = enemy.get_rect().size # get the image size enemy_width = enemy_size[0] # character's width enemy_height = enemy_size[1] # characeter's height # the middle of screen width enemy_x_pos = (screen_width / 2) - (enemy_width / 2) enemy_y_pos = (screen_height / 2) - (enemy_height / 2) # the bottom of screen heigth # even loop running=True while running: dt=clock.tick(60) # 30 frame per 1 second # conditions # character can move in 100 pixel # 10 fps : 10 * 10 = 100 # 20 fps : 20 * 5 = 100 for event in pygame.event.get(): # which event raise? if event.type == pygame.QUIT: # The event which close windows raise running=False if event.type == pygame.KEYDOWN: # check if key is pressed. if event.key == pygame.K_LEFT: to_x -= charactr_speed elif event.key == pygame.K_RIGHT: to_x += charactr_speed elif event.key == pygame.K_UP: to_y -= charactr_speed elif event.key == pygame.K_DOWN: to_y += charactr_speed if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: to_x=0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: to_y=0 character_x_pos += to_x * dt character_y_pos += to_y * dt # width boundary limit if character_x_pos < 0: character_x_pos=0 elif character_x_pos > screen_width - character_width: character_x_pos=screen_width - character_width if character_y_pos < 0: character_y_pos=0 elif character_y_pos > screen_height - character_height: character_y_pos=screen_height - character_height # collision for updating positions character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos enemy_rect = enemy.get_rect() enemy_rect.left = enemy_x_pos enemy_rect.top = enemy_y_pos # check if the collision occurs if character_rect.colliderect(enemy_rect): print("the collision occurs") running = False # screen.fill((0,0,255)) screen.blit(background, (0, 0)) # draw the background screen.blit(character, (character_x_pos, character_y_pos)) screen.blit(enemy, (enemy_x_pos, enemy_y_pos)) pygame.display.update() # redrawing # pygame exit pygame.quit()
''' Experiment class for unified model ''' import config import torch from experiment import Experiment from torch import nn from misc import unified_ans_acc, calc_bleu_scores_unified from itertools import cycle class ExperimentUnified( Experiment ): def __init__( self, args ): super(ExperimentUnified, self).__init__( args ) self.unified_vocab = self.data_loader['train']\ .dataset.dataset.unified_vocab def evaluate_gen_qa( self, batch_sample ): ''' Helper routine to evaluate generated qst+ans ''' self.vqa_model.eval() # import pdb; pdb.set_trace() image = batch_sample['image'].to(config.DEVICE) qa_str = batch_sample['qa_str'] image_path = batch_sample['image_path'] # ground truth question+answer qa_str = [ self.unified_vocab.arr2qst( qa ) for qa in qa_str ] # generated question-answer with torch.no_grad(): gen_qa_str = self.vqa_model.generate( image ) gen_qa_str = [ self.unified_vocab.arr2qst( qa ) for qa in gen_qa_str ] n = min( 4, len( image ) ) self.log( 'Evaluating question answer pairs' ) for i in range( n ): self.log( f'image path:{image_path[i]}' ) self.log( f'ground truth qa: {qa_str[i]}' ) self.log( f'generated qa: {gen_qa_str[i]}' ) def train( self ): self.vqa_model.train() total_loss = 0 total_ans_acc = 0 num_batches = len( self.data_loader['train'] ) valid_queue_iter = cycle( iter( self.data_loader['valid'] ) ) lr = self.scheduler.get_lr()[0] # import pdb; pdb.set_trace() for batch_idx, batch_sample in enumerate( self.data_loader['train'] ): # get training data image = batch_sample['image'].to(config.DEVICE) qa_str = batch_sample['qa_str'].to(config.DEVICE) # STAGE1: architecture update if self.arch_type == 'darts' and \ ( batch_idx % self.arch_update_freq == 0 ): batch_sample = next( valid_queue_iter ) val_image = batch_sample['image'].to(config.DEVICE) val_qa_str = batch_sample['qa_str'].to(config.DEVICE) label, val_label = None, None # import pdb; pdb.set_trace() self.architect.step( image, qa_str, label, val_image, val_qa_str, val_label, lr ) # train model self.optimizer.zero_grad() qa_out = self.vqa_model(image, qa_str) qa_flat = qa_str[:, 1:].flatten() qa_pred_flat = qa_out[:, :-1].flatten(end_dim=1) loss = self.criterion( qa_pred_flat, qa_flat ) loss.backward() nn.utils.clip_grad_norm_(self.vqa_model.parameters(), self.grad_clip) self.optimizer.step() total_loss += loss.item() # calculate accuracy qa_pred = torch.argmax( qa_out, dim=2 ) ans_acc = unified_ans_acc( qa_str, qa_pred, self.unified_vocab ) total_ans_acc += ans_acc if batch_idx % self.report_freq == 0: self.log( '| TRAIN SET | STAGE2 | ' + f'EPOCH [{self.current_epoch+1:02d}/{self.epochs:02d}] ' + f'Step [{batch_idx:04d}/{num_batches:04d}] ' + f'Loss: {loss.item():.4f} Ans-acc: {ans_acc:.4f}' ) # calculate epoch stats avg_loss = total_loss / num_batches avg_ans_acc = total_ans_acc / num_batches self.train_loss.append( avg_loss ) self.train_ans_acc.append( avg_ans_acc ) self.log( f'| TRAIN_SET | EPOCH [{self.current_epoch+1:02d}/' + f'{self.epochs:02d}] Loss: {avg_loss:.4f} ' + f'Ans-acc: {avg_ans_acc:.4f} ') self.evaluate_gen_qa( batch_sample ) def val( self ): self.vqa_model.eval() total_loss = 0 total_ans_acc = 0 total_b4 = 0 num_batches = len( self.data_loader['valid'] ) with torch.no_grad(): for batch_idx, batch_sample in enumerate( self.data_loader['valid'] ): # get validation data image = batch_sample['image'].to(config.DEVICE) qa_str = batch_sample['qa_str'].to(config.DEVICE) image_name = batch_sample['image_name'] # calculate loss qa_out = self.vqa_model(image, qa_str) qa_flat = qa_str[:, 1:].flatten() qa_pred_flat = qa_out[:, :-1].flatten(end_dim=1) loss = self.criterion( qa_pred_flat, qa_flat ) total_loss += loss.item() # calculate accuracy qa_pred = torch.argmax( qa_out, dim=2 ) ans_acc = unified_ans_acc( qa_str, qa_pred, self.unified_vocab ) total_ans_acc += ans_acc # calculate bleu score qa_gen = self.vqa_model.generate( image ) b4 = calc_bleu_scores_unified( image_name, qa_gen, self.unified_vocab, self.vqa_struct ) total_b4 += b4 if batch_idx % self.report_freq == 0: self.log( '| VAL SET | ' + f'EPOCH [{self.current_epoch+1:02d}/{self.epochs:02d}] ' + f'Step [{batch_idx:04d}/{num_batches:04d}] ' + f'Loss: {loss.item():.4f} Ans-acc: {ans_acc:.4f} ' + f'BLEU4: {b4:.4f} ') # print stats avg_loss = total_loss / num_batches avg_ans_acc = total_ans_acc / num_batches avg_b4 = total_b4 / num_batches self.val_loss.append( avg_loss ) self.val_ans_acc.append( avg_ans_acc ) self.val_b4.append( avg_b4 ) self.log( f'| VAL_SET | EPOCH [{self.current_epoch+1:02d}/' + f'{self.epochs:02d}] Loss: {avg_loss:.4f} ' + f'Ans-acc: {avg_ans_acc:.4f} ' + f'BLEU4: {avg_b4:.4f} ')
# -*- coding: utf-8 -*- import re from openerp import api, models, _ from openerp.exceptions import UserError class ResBank(models.Model): _inherit = 'res.bank' @api.one @api.constrains('bic') def _check_bic(self): # ISO 9362:2009 bic_check = re.compile(r'^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$') if self.bic and not bic_check.match(self.bic): raise UserError(_('Incorrect BIC/SWIFT'))
from django.http import HttpRequest from django.urls import resolve from django.test import TestCase from .views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): self.assertEqual(resolve('/').func, home_page) def test_home_page_returns_welcome_html(self): request = HttpRequest() response = home_page(request) html = response.content.decode('utf8') self.assertTrue(html.startswith('<html>')) self.assertIn('<title>Superlists</title>', html) self.assertTrue(html.endswith('</html>'))
# coding:utf-8 import matplotlib import numpy as np import matplotlib.pyplot as plt import cv2 #ファイルの入出力 file = open("file.txt","r") for line in file: print(line) file = open("file.txt", "w") file.write("Hello world") file.write("This is out new text file") file.write("and this is another line.") file.close() print("終了") #画像データの読み込み img = cv2.imread("orange.jpg") # print(img.shape) #画像を表示する _img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(_img) # plt.show() #画像を保存する plt.imsave("orange2.jpg", _img) #画像をリサイズする #print(img.shape) #-->(y,x,channel) = (768, 1024, 3) # resized_img = cv2.resize(img, (new_y,new_x)) resized_img = cv2.resize(img, (400,300)) # plt.imshow(resized_img) # plt.show() # plt.imsave("orange3.jpg", resized_img) #画像を指定範囲でクロップする # cropped = img[y1:y2,x1:x2] cropped = img[300:500,400:600] # plt.imshow(cropped) # plt.show() # plt.imsave("orange4.jpg", cropped) #グレースケールに変換 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) plt.imshow(gray, cmap="gray") plt.show() plt.imsave("orange5.jpg", gray)
def rotate_array(array, N): if N == 0: return if N > 0: while N > 0: # TOREAD: insert(position, value) # this is perpend array.insert(0, array.pop()) N -= 1 return if N < 0: while N < 0: array.append(array.pop(0)) N += 1 return #@ working with distance!! # # what if N is larger than len(array)??? # N = len(array) % N # if N<0, then N = len(array) + N def rotate_array_rec(array, N): # TOREAD: reverse in place def reverse_inplace(array, start, end): while start < end: array[start], array[end] = array[end], array[start] start += 1 end -= 1 length = len(array) # TOREAD: % process negative value # do it, don't need to test # when do %, like -11 % 5 = 4 # it already processed negative value N %= length reverse_inplace(array, 0, length - 1) reverse_inplace(array, 0, N - 1) reverse_inplace(array, N, length - 1) if __name__ == '__main__': array = [1, 10, 20, 0, 59] res1 = [10, 20, 0, 59, 1] # rotate -1 res2 = [0, 59, 1, 10, 20] # rotate 2 rotate_array(array, -1) assert res1 == array array = [1, 10, 20, 0, 59] rotate_array(array, 2) assert res2 == array array = [1, 10, 20, 0, 59] rotate_array_rec(array, -1) print array print 'test passed.'
def to_c(from_f): celsius = (from_f - 32) * (5 / 9) return celsius # Main Routine temperatures = [0, 40, 100] converted = [] for item in temperatures: answer = to_c(item) ans_statement = "{} degrees C is {} degrees F".format(item, answer) converted.append(ans_statement) print(converted)
def matrix_mul(a, b): m = len(a) # number of rows of A n = len(a[0]) # number of cols of A r = len(b) # number of rows of B s = len(b[0]) # number of cols of B c = [[0] * s for _ in range(m)] # allocate empty result # cycle over all the rows of C (== rows of A) for i in range(m): # then, cycle over all the cols of C (== cols of B) for j in range(s): for k in range(n): c[i][j] += a[i][k] * b[k][j] return c a = [[3,2], [4,5]] b = [[1,-1], [-2, -3]] r = [[-1,-9], [-6,-19]] c = matrix_mul(a, b) for i in range(len(c)): for j in range(len(c[0])): print(c[i][j],end=" ") print() print("{} * {} = {}".format(a, b, c))
import re import sys import shutil from subprocess import check_call from setuptools import setup, find_packages if sys.argv[-1] == 'cheeseit!': check_call('nosetests -v') check_call('python setup.py sdist bdist_wheel') check_call('twine upload dist/*') shutil.rmtree('dist') sys.exit() elif sys.argv[-1] == 'testit!': check_call('nosetests -v') check_call('python setup.py sdist bdist_wheel upload -r pypitest') sys.exit() def get_info(pyfile): '''Retrieve dunder values from a pyfile''' info = {} info_re = re.compile(r"^__(\w+)__ = ['\"](.*)['\"]") with open(pyfile, 'r') as f: for line in f.readlines(): match = info_re.search(line) if match: info[match.group(1)] = match.group(2) return info info = get_info('scrim/__init__.py') with open('README.rst', 'r') as f: long_description = f.read() setup( name=info['title'], version=info['version'], url=info['url'], license=info['license'], author=info['author'], author_email=info['email'], description=info['description'], long_description=long_description, install_requires=[ 'click>=6.7', 'psutil>=5.2', 'fstrings>=0.1.0', 'six>=1.10.0' ], packages=['scrim'], package_data={ 'scrim': ['bin/*.*'] }, entry_points={ 'console_scripts': [ 'scrim = scrim.__main__:cli' ] }, classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', ), )
import unittest from com.ea.pages import fangkuan_taizhang_report_page from com.ea.common import tools, web_login from com.ea.resource import globalparameter as gl import time import os import sys class MyTestCase(unittest.TestCase): u"""贷款审批报表""" screenshot_path = os.path.join(gl.screenshot_path, os.path.splitext(os.path.basename(__file__))[0]) start_date = '2018-01-01' end_date = '2018-01-31' count = '531' loan_count = '13,225.00' @classmethod def setUpClass(cls): cls.webdriver = tools.get_chrome_driver() web_login.login(cls.webdriver) def setUp(self): pass def tearDown(self): pass @classmethod def tearDownClass(cls): cls.webdriver.quit() def test_loan_code_fangkuan_taizhang(self): u"""放款台账->贷款单放款台帐报表""" casename = sys._getframe().f_code.co_name try: loancodepage = fangkuan_taizhang_report_page.LoanCode(self.webdriver) url = loancodepage.get_url() self.webdriver.get(url) loancodepage.input_loan_date_start(self.start_date) loancodepage.input_loan_date_end(self.end_date) loancodepage.click_search_button() time.sleep(3) loancodepage.page_down() time.sleep(1) assert self.count == loancodepage.get_count() except Exception as e: tools.screenshot(self.webdriver, self.screenshot_path, casename) raise e def test_liutongdai_fangkuan_taizhang(self): u"""放款台账->流通贷放款台账查询""" casename = sys._getframe().f_code.co_name try: liutongdaipage = fangkuan_taizhang_report_page.LiutongdaiPage(self.webdriver) url = liutongdaipage.get_url() self.webdriver.get(url) liutongdaipage.input_loan_date_start(self.start_date) liutongdaipage.input_loan_date_end(self.end_date) liutongdaipage.click_search_button() time.sleep(5) liutongdaipage.page_down() time.sleep(1) assert self.loan_count == liutongdaipage.get_loan_count() except Exception as e: tools.screenshot(self.webdriver, self.screenshot_path, casename) raise e if __name__ == '__main__': unittest.main()
import unittest import os from dotenv import load_dotenv import nlpaug.augmenter.audio as naa from nlpaug.util import AudioLoader class TestAudio(unittest.TestCase): @classmethod def setUpClass(cls): env_config_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "..", ".env") ) load_dotenv(env_config_path) # https://freewavesamples.com/yamaha-v50-rock-beat-120-bpm cls.sample_wav_file = os.path.join( os.environ.get("TEST_DIR"), "res", "audio", "Yamaha-V50-Rock-Beat-120bpm.wav", ) cls.audio, cls.sampling_rate = AudioLoader.load_audio(cls.sample_wav_file) def test_multi_thread(self): n = 3 augs = [ naa.CropAug(sampling_rate=self.sampling_rate), naa.PitchAug(sampling_rate=self.sampling_rate), ] for num_thread in [1, 3]: for aug in augs: augmented_data = aug.augment(self.audio, n=n, num_thread=num_thread) self.assertEqual(len(augmented_data), n) def test_coverage_and_zone(self): params = [((0.3, 0.7), 1), ((0, 1), 1)] for zone, coverage in params: augs = [ naa.LoudnessAug(zone=zone, coverage=coverage, stateless=False), naa.MaskAug(zone=zone, coverage=coverage, stateless=False), naa.NoiseAug(zone=zone, coverage=coverage, stateless=False), naa.PitchAug( zone=zone, coverage=coverage, stateless=False, sampling_rate=self.sampling_rate, ), naa.SpeedAug(zone=zone, coverage=coverage, stateless=False), naa.VtlpAug( zone=zone, coverage=coverage, stateless=False, sampling_rate=self.sampling_rate, ), ] for aug in augs: aug_data = aug.augment(self.audio) self.assertTrue( len(aug_data[aug.start_pos : aug.end_pos]), int(len(self.audio) * (zone[1] - zone[0]) * coverage), )
""" Utility methods. - Methods: - clean_array: returns input array with nan and infinite values removed - controlled_compute: performs computation with Dask - rescale_array: performs edge trimming on values of the input vector - show_progress: performs computation with Dask and shows progress bar - system_call: executes a command in the underlying operative system - rolling_window: applies rolling window mean over a vector """ from loguru import logger import sys import numpy as np from tqdm.dask import TqdmCallback from dask.array.core import Array from tqdm.auto import tqdm as std_tqdm from numba import jit __all__ = [ "logger", "tqdmbar", "set_verbosity", "get_log_level", "system_call", "rescale_array", "clean_array", "show_dask_progress", "controlled_compute", "rolling_window", ] logger.remove() logger.add( sys.stdout, colorize=True, format="<level>{level}</level>: {message}", level="INFO" ) tqdm_params = { "bar_format": "{desc}: {percentage:3.0f}%| {bar} {n_fmt}/{total_fmt} [{elapsed}]", "ncols": 500, "colour": "#34abeb", } def get_log_level(): # noinspection PyUnresolvedReferences return logger._core.min_level def tqdmbar(*args, **kwargs): params = dict(tqdm_params) for i in kwargs: if i in params: del params[i] if "disable" not in kwargs and "disable" not in params: if get_log_level() <= 20: params["disable"] = False else: params["disable"] = True return std_tqdm(*args, **kwargs, **params) def set_verbosity(level: str = None, filepath: str = None): """ Set verbosity level of Scarf's output. Setting value of level='CRITICAL' should silence all logs. Progress bars are automatically disabled for levels above 'INFO'. Args: level: A valid level name. Run without any parameter to see available options filepath: The output file path. All logs will be saved to this file. If no file path is is provided then all the logs are printed on standard output. Returns: """ # noinspection PyUnresolvedReferences available_levels = logger._core.levels.keys() if level is None or level not in available_levels: raise ValueError( f"Please provide a value for level: {', '.join(available_levels)}" ) logger.remove() if filepath is None: filepath = sys.stdout logger.add( filepath, colorize=True, format="<level>{level}</level>: {message}", level=level, ) def rescale_array(a: np.ndarray, frac: float = 0.9) -> np.ndarray: """ Performs edge trimming on values of the input vector. Performs edge trimming on values of the input vector and constraints them between within frac and 1-frac density of normal distribution created with the sample mean and std. dev. of a. Args: a: numeric vector frac: Value between 0 and 1. Return: The input array, edge trimmed and constrained. """ from scipy.stats import norm loc = (np.median(a) + np.median(a[::-1])) / 2 dist = norm(loc, np.std(a)) minv, maxv = dist.ppf(1 - frac), dist.ppf(frac) a[a < minv] = minv a[a > maxv] = maxv return a def clean_array(x, fill_val: int = 0): """ Returns input array with nan and infinite values removed. Args: x (np.ndarray): input array fill_val: value to fill zero values with (default: 0) """ x = np.nan_to_num(x, copy=True) x[(x == np.Inf) | (x == -np.Inf)] = 0 x[x == 0] = fill_val return x def controlled_compute(arr, nthreads): """ Performs computation with Dask. Args: arr: nthreads: number of threads to use for computation Returns: Result of computation. """ from multiprocessing.pool import ThreadPool import dask with dask.config.set(schedular="threads", pool=ThreadPool(nthreads)): res = arr.compute() return res def show_dask_progress(arr: Array, msg: str = None, nthreads: int = 1): """ Performs computation with Dask and shows progress bar. Args: arr: A Dask array msg: message to log, default None nthreads: number of threads to use for computation, default 1 Returns: Result of computation. """ params = dict(tqdm_params) if "disable" not in params: if get_log_level() <= 20: params["disable"] = False else: params["disable"] = True with TqdmCallback(desc=msg, **params): res = controlled_compute(arr, nthreads) return res def system_call(command): """Executes a command in the underlying operative system.""" import subprocess import shlex process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) while True: output = process.stdout.readline() if process.poll() is not None: break if output: logger.info(output.strip()) process.poll() return None @jit(nopython=True) def rolling_window(a, w): n, m = a.shape b = np.zeros(shape=(n, m)) for i in range(n): if i < w: x = i y = w - i elif (n - i) < w: x = w - (n - i) y = n - i else: x = w // 2 y = w // 2 x = i - x y = i + y for j in range(m): b[i, j] = a[x:y, j].mean() return b
import logging import os from evaluator import unit from evaluator.attributes import UNDEFINED from evaluator.datasets import MeasurementSource, PhysicalPropertyDataSet, PropertyPhase from evaluator.properties import EnthalpyOfVaporization from evaluator.substances import Substance from evaluator.thermodynamics import ThermodynamicState from nistdataselection.curation.filtering import filter_undefined_stereochemistry from nistdataselection.processing import save_processed_data_set from nistdataselection.utils import SubstanceType from nistdataselection.utils.utils import data_frame_to_pdf logger = logging.getLogger(__name__) def main(): # Set up logging logging.basicConfig(level=logging.INFO) # Build a data set containing the training set Hvap measurements sourced # from the literature. h_vap_data_set = PhysicalPropertyDataSet() h_vap_phase = PropertyPhase(PropertyPhase.Liquid | PropertyPhase.Gas) h_vap_data_set.add_properties( # Formic Acid EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("OC=O"), value=46.3 * unit.kilojoule / unit.mole, uncertainty=0.25 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.3891/acta.chem.scand.24-2612"), ), # Acetic Acid EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(O)=O"), value=51.6 * unit.kilojoule / unit.mole, uncertainty=0.75 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.3891/acta.chem.scand.24-2612"), ), # Propionic Acid EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(O)=O"), value=55 * unit.kilojoule / unit.mole, uncertainty=1 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.3891/acta.chem.scand.24-2612"), ), # Butyric Acid EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCC(O)=O"), value=58 * unit.kilojoule / unit.mole, uncertainty=2 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.3891/acta.chem.scand.24-2612"), ), # Isobutyric Acid EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)C(O)=O"), value=53 * unit.kilojoule / unit.mole, uncertainty=2 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.3891/acta.chem.scand.24-2612"), ), # Methanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CO"), value=37.83 * unit.kilojoule / unit.mole, uncertainty=0.11349 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # Ethanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCO"), value=42.46 * unit.kilojoule / unit.mole, uncertainty=0.12738 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # 1-Propanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCO"), value=47.5 * unit.kilojoule / unit.mole, uncertainty=0.1425 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # Isopropanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)O"), value=45.48 * unit.kilojoule / unit.mole, uncertainty=0.13644 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # n-Butanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCO"), value=52.42 * unit.kilojoule / unit.mole, uncertainty=0.15726 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # Isobutanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)CO"), value=50.89 * unit.kilojoule / unit.mole, uncertainty=0.15267 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # 2-Butanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(C)O"), value=49.81 * unit.kilojoule / unit.mole, uncertainty=0.14943 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # t-butanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)(C)O"), value=46.75 * unit.kilojoule / unit.mole, uncertainty=0.14025 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # n-pentanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCO"), value=44.36 * unit.kilojoule / unit.mole, uncertainty=0.13308 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0378-3812(85)90026-3"), ), # 1-hexanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCCO"), value=61.85 * unit.kilojoule / unit.mole, uncertainty=0.2 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(77)90202-6"), ), # 1-heptanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCCCO"), value=66.81 * unit.kilojoule / unit.mole, uncertainty=0.2 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(77)90202-6"), ), # 1-octanol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCCCCO"), value=70.98 * unit.kilojoule / unit.mole, uncertainty=0.42 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(77)90202-6"), ), # Propyl formate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCOC=O"), value=37.49 * unit.kilojoule / unit.mole, uncertainty=0.07498 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Butyl formate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCOC=O"), value=41.25 * unit.kilojoule / unit.mole, uncertainty=0.0825 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Methyl acetate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("COC(C)=O"), value=32.3 * unit.kilojoule / unit.mole, uncertainty=0.0646 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Ethyl acetate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCOC(C)=O"), value=35.62 * unit.kilojoule / unit.mole, uncertainty=0.07124 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Propyl acetate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCOC(C)=O"), value=39.83 * unit.kilojoule / unit.mole, uncertainty=0.07966 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Methyl propionate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(=O)OC"), value=35.85 * unit.kilojoule / unit.mole, uncertainty=0.0717 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Ethyl propionate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCOC(=O)CC"), value=39.25 * unit.kilojoule / unit.mole, uncertainty=0.0785 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Butyl acetate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=313.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCOC(C)=O"), value=42.96 * unit.kilojoule / unit.mole, uncertainty=0.08592 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Propyl propionate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=313.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCOC(=O)CC"), value=42.14 * unit.kilojoule / unit.mole, uncertainty=0.08428 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1135/cccc19803233"), ), # Methyl Butanoate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCC(=O)OC"), value=40.1 * unit.kilojoule / unit.mole, uncertainty=0.4 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1007/BF00653098"), ), # Methyl Pentanoate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCC(=O)OC"), value=44.32 * unit.kilojoule / unit.mole, uncertainty=0.5 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1007/BF00653098"), ), # Ethyl Butanoate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCC(=O)OCC"), value=42.86 * unit.kilojoule / unit.mole, uncertainty=0.1 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(86)90070-4"), ), # Ethylene glycol diacetate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(=O)OCCOC(=O)C"), value=61.44 * unit.kilojoule / unit.mole, uncertainty=0.15 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(86)90070-4"), ), # Methyl formate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=293.25 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("COC=O"), value=28.7187400224 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19760001"), ), # Ethyl formate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=304 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCOC=O"), value=31.63314346416 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19760001"), ), # 1,3-propanediol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("OCCCO"), value=70.5 * unit.kilojoule / unit.mole, uncertainty=0.3 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1021/je060419q"), ), # 2,4 pentanediol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(CC(C)O)O"), value=72.5 * unit.kilojoule / unit.mole, uncertainty=0.3 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1021/je060419q"), ), # 2-Me-2,4-pentanediol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(O)CC(C)(C)O"), value=68.9 * unit.kilojoule / unit.mole, uncertainty=0.4 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1021/je060419q"), ), # 2,2,4-triMe-1,3-pentanediol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)C(O)C(C)(C)CO"), value=75.3 * unit.kilojoule / unit.mole, uncertainty=0.5 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1021/je060419q"), ), # glycerol EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("C(C(CO)O)O"), value=91.7 * unit.kilojoule / unit.mole, uncertainty=0.9 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(88)90173-5"), ), # Diethyl Malonate EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCOC(=O)CC(=O)OCC"), value=61.70 * unit.kilojoule / unit.mole, uncertainty=0.25 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1021/je100231g"), ), # 1,4-dioxane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("C1COCCO1"), value=38.64 * unit.kilojoule / unit.mole, uncertainty=0.05 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1039/P29820000565"), ), # oxane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("C1CCOCC1"), value=34.94 * unit.kilojoule / unit.mole, uncertainty=0.84 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1039/TF9615702125"), ), # methyl tert butyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("COC(C)(C)C"), value=32.42 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # diisopropyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)OC(C)C"), value=32.12 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # Dibutyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCOCCCC"), value=44.99 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # cyclopentanone EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.16 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("O=C1CCCC1"), value=42.63 * unit.kilojoule / unit.mole, uncertainty=0.42 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1002/hlca.19720550510"), ), # 2-pentanone EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCC(C)=O"), value=38.43 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(83)90091-5"), ), # cyclohexanone EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.16 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("O=C1CCCCC1"), value=44.89 * unit.kilojoule / unit.mole, uncertainty=0.63 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1002/hlca.19720550510"), ), # cycloheptanone EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.16 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("O=C1CCCCCC1"), value=49.54 * unit.kilojoule / unit.mole, uncertainty=0.63 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1002/hlca.19720550510"), ), # cyclohexane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("C1CCCCC1"), value=33.02 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # hexane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCC"), value=31.55 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # methylcyclohexane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC1CCCCC1"), value=35.38 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # heptane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCCC"), value=36.58 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # iso-octane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)CC(C)(C)C"), value=35.13 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # decane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCCCCCC"), value=51.35 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.3891/acta.chem.scand.20-0536"), ), # acetone EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=300.4 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(C)=O"), value=30.848632 * unit.kilojoule / unit.mole, uncertainty=0.008368 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1021/ja01559a015"), ), # butan-2-one EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(C)=O"), value=34.51 * unit.kilojoule / unit.mole, uncertainty=0.04 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="0021-9614(79)90127-7"), ), # pentan-3-one EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(=O)CC"), value=38.52 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(83)90091-5"), ), # 4-methylpentan-2-one EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CC(=O)CC(C)C"), value=40.56 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(83)90091-5"), ), # 3-hexanone EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCC(=O)CC"), value=42.45 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1016/0021-9614(83)90091-5"), ), # 2-methylheptane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCC(C)C"), value=39.66 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # 3-methylpentane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(C)CC"), value=30.26 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # 2-Methylhexane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCC(C)C"), value=34.85 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # 2,3-Dimethylpentane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCC(C)C(C)C"), value=34.25 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # Octane EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCCCCC"), value=41.47 * unit.kilojoule / unit.mole, uncertainty=UNDEFINED, source=MeasurementSource(doi="10.1135/cccc19790637"), ), # Methyl Propyl Ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCOC"), value=27.57 * unit.kilojoule / unit.mole, uncertainty=0.068925 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # Ethyl isopropyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCOC(C)C"), value=30.04 * unit.kilojoule / unit.mole, uncertainty=0.0751 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # Dipropyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCOCCC"), value=35.68 * unit.kilojoule / unit.mole, uncertainty=0.0892 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # butyl methyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("CCCCOC"), value=32.43 * unit.kilojoule / unit.mole, uncertainty=0.081075 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), # methyl isopropyl ether EnthalpyOfVaporization( thermodynamic_state=ThermodynamicState( temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere ), phase=h_vap_phase, substance=Substance.from_components("COC(C)C"), value=26.41 * unit.kilojoule / unit.mole, uncertainty=0.066025 * unit.kilojoule / unit.mole, source=MeasurementSource(doi="10.1016/0021-9614(80)90152-4"), ), ) output_directory = "sourced_h_vap_data" os.makedirs(output_directory, exist_ok=True) data_frame = h_vap_data_set.to_pandas() # Check for undefined stereochemistry filtered_data_frame = filter_undefined_stereochemistry(data_frame) filtered_components = {*data_frame["Component 1"]} - { *filtered_data_frame["Component 1"] } logger.info( f"Compounds without stereochemistry were removed: {filtered_components}" ) save_processed_data_set( output_directory, filtered_data_frame, EnthalpyOfVaporization, SubstanceType.Pure, ) file_path = os.path.join(output_directory, "enthalpy_of_vaporization_pure.pdf") data_frame_to_pdf(filtered_data_frame, file_path) if __name__ == "__main__": main()
from notebook.notebookapp import NotebookApp, flags from traitlets import Unicode from .config import NteractConfig nteract_flags = dict(flags) nteract_flags['dev'] = ( {'NteractConfig': {'asset_url':'http://localhost:8080/'}}, "Start nteract in dev mode, running off your source code, with hot reloads." ) class NteractApp(NotebookApp): """Application for runing nteract on a jupyter notebook server. """ default_url = Unicode('/nteract/edit', help="nteract's default starting location") classes = [*NotebookApp.classes, NteractConfig] flags = nteract_flags main = launch_new_instance = NteractApp.launch_instance if __name__ == '__main__': main()
"""A UnitTestController Module.""" from masonite.request import Request from masonite.controllers import Controller class UnitTestController(Controller): """UnitTestController Controller Class.""" def __init__(self, request: Request): """UnitTestController Initializer Arguments: request {masonite.request.Request} -- The Masonite Request class. """ self.request = request def show(self): return 'got' def store(self): return 'posted' def params(self): return self.request.input('test') def get_params(self): return self.request.input('test') def user(self): return self.request.user().name def json(self): return self.request.input('test') def response(self): return { 'count': 5, 'iterable': [1, 2, 3] } def multi(self): return { 'author': { 'name': 'Joe' } } def multi_count(self): return {"count": 5, "iterable": [1, 2, 3]} def patch(self): return self.request.input('test') def param(self): return self.request.param('post_id')
import png import zlib import string def get_decompressed_data(filename): img = png.Reader(filename) for chunk in img.chunks(): if chunk[0] == "IDAT": print len(chunk[1]) return zlib.decompress(chunk[1]) data = get_decompressed_data("ninth.png") len_data = str(len(data)) print '{0}'.format('len_data = :' + len_data) image_width = 1200 image_height = 848 bytes_per_pixel = 3 bytes_per_filter = 1 data = data[(image_width*bytes_per_pixel + bytes_per_fileter)*image_height:] print ''.join([x for xin data if x in string.printable])
def mutate_string(string, position, character): l = list(string) l[position]=character s="" s=s.join(l) return s
#Leetcode 682. Baseball Game class Solution: def calPoints(self, ops: List[str]) -> int: result = [] for i in ops: if i == "C": del result[-1] elif i == "D": result.append(2*int(result[-1])) elif i == "+": result.append(int(result[-1])+int(result[-2])) else: result.append(i) print(result) output = 0 for res in result: output += int(res) return output
#!/usr/bin/env python3 # LoRaMaDoR (LoRa-based mesh network for hams) project # Mesh network simulator / routing algorithms testbed # Copyright (c) 2019 PU5EPX # Modifiers of packets that are going to be forwarded class Rreqi: @staticmethod def match(pkt): return ("RREQ" in pkt.params or "RRSP" in pkt.params) and len(pkt.to) > 2 @staticmethod def handle(station, pkt): msg = pkt.msg + "\n" + station.callsign return None, msg class RetransBeacon: @staticmethod def match(pkt): return len(pkt.to) == 2 and pkt.to in ("QB", "QC") and "R" not in pkt.params @staticmethod def handle(station, pkt): return {"R": None}, None fwd_modifiers = [ Rreqi, RetransBeacon ]
import sys, os reader=open("Input5000fa","r") writer=open("corpusFile.txt","w") x=reader.readlines() for i in range(1,len(x)): line = x[i].strip("\n") ids = line.split("- ",1)[0] sen = line.split("- ",1)[1] size = len(sen.split(" ")) print ids + " " + str(size)
name = input('enter a file name') try: fin = open(name) except: print('file cannot open ', name) exit() r = dict() for line in fin: line = line.rstrip() for w in line.split(): r[w] = r.get(w, 0) + 1 print(r)
from bs4 import BeautifulSoup import requests import time import os def get_time_slot(path, locations): for id in locations: url = path + str(id) response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') try: appt_list = soup.find(id='timeslots') if appt_list.a.div['class'][1] == "availableTimeslot": print(soup.main.find('ul').li.get_text()) print(url) t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print(current_time) os.system('say "Found an appointment"') os.system('say "Found an appointment"') os.system('say "Found an appointment"') except Exception: continue path = "https://telegov.njportal.com/njmvc/AppointmentWizard/15/" locations = range(186, 208) while True: get_time_slot(path, locations) time.sleep(60)
#!/usr/bin/env python3 """Compare Strings by Count of Characters. Create a function that takes two strings as arguments and return either True or False depending on whether the total number of characters in the first string is equal to the total number of characters in the second string. Source: https://edabit.com/challenge/C3N2JEfFQoh4cqQ98 """ def comp(*args) -> bool: """Compare string lengths.""" return len(set([len(arg) for arg in args])) == 1 def main(): """Run sample comp functions. Do not import.""" assert comp("AB", "CD") is True assert comp("ABC", "DE") is False assert comp("hello", "edabit") is False assert comp("meow", "woof") is True assert comp("jrnvjrnnt", "cvjknfjvmfvnfjn") is False assert comp("jkvnjrt", "krnf") is False assert comp("Facebook", "Snapchat") is True assert comp("AB", "CD", "EF") is True assert comp("ABC", "DE", "ABC") is False print('Passed.') if __name__ == "__main__": main()
import AuthenticationServices from PyObjCTools.TestSupport import TestCase, min_sdk_level import objc class TestASAuthorizationProviderExtensionRegistrationHandlerHelper( AuthenticationServices.NSObject ): def beginDeviceRegistrationUsingLoginManager_options_completion_(self, a, b, c): pass def beginUserRegistrationUsingLoginManager_userName_authenticationMethod_options_completion_( self, a, b, c, d, e ): pass class TestASAuthorizationProviderExtensionRegistrationHandler(TestCase): def test_constants(self): self.assertIsEnumType( AuthenticationServices.ASAuthorizationProviderExtensionAuthenticationMethod ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionAuthenticationMethodPassword, 1, ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionAuthenticationMethodUserSecureEnclaveKey, 2, ) self.assertIsEnumType( AuthenticationServices.ASAuthorizationProviderExtensionRequestOptions ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRequestOptionsNone, 0 ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRequestOptionsUserInteractionEnabled, 1 << 0, ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRequestOptionsRegistrationRepair, 1 << 1, ) self.assertIsEnumType( AuthenticationServices.ASAuthorizationProviderExtensionRegistrationResult ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRegistrationResultSuccess, 0, ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRegistrationResultFailed, 1, ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRegistrationResultUserInterfaceRequired, 2, ) self.assertEqual( AuthenticationServices.ASAuthorizationProviderExtensionRegistrationResultFailedNoRetry, 3, ) @min_sdk_level("13.0") def test_protocols(self): self.assertProtocolExists("ASAuthorizationProviderExtensionRegistrationHandler") def test_methods(self): self.assertArgHasType( TestASAuthorizationProviderExtensionRegistrationHandlerHelper.beginDeviceRegistrationUsingLoginManager_options_completion_, 1, objc._C_NSUInteger, ) self.assertArgIsBlock( TestASAuthorizationProviderExtensionRegistrationHandlerHelper.beginDeviceRegistrationUsingLoginManager_options_completion_, 2, b"v" + objc._C_NSInteger, ) self.assertArgHasType( TestASAuthorizationProviderExtensionRegistrationHandlerHelper.beginUserRegistrationUsingLoginManager_userName_authenticationMethod_options_completion_, 2, objc._C_NSInteger, ) self.assertArgHasType( TestASAuthorizationProviderExtensionRegistrationHandlerHelper.beginUserRegistrationUsingLoginManager_userName_authenticationMethod_options_completion_, 3, objc._C_NSUInteger, ) self.assertArgIsBlock( TestASAuthorizationProviderExtensionRegistrationHandlerHelper.beginUserRegistrationUsingLoginManager_userName_authenticationMethod_options_completion_, 4, b"v" + objc._C_NSInteger, )
from IPython import embed # Load the Pima Indians diabetes dataset from CSV URL import numpy as np import pandas as pd import urllib import matplotlib import pylab import matplotlib.pyplot as plt from pandas import DataFrame df = pd.read_csv('users 3.csv') embed() #df.plot(x='followers_count', y='followings_count', style='o') df.plot.scatter(x='followers_count', y='followings_count', c='k', alpha=.15) plt.xlim(0, 100) plt.ylim(150, 350) plt.show() # separate the data from the target attributes # Misc code
import unittest import os from python.housinginsights.ingestion.Cleaners import ProjectCleaner, PYTHON_PATH from python.housinginsights.ingestion.Manifest import Manifest from python.housinginsights.ingestion.functions import load_meta_data class CleanerTestCase(unittest.TestCase): def setUp(self): # use test data test_data_path = os.path.abspath(os.path.join(PYTHON_PATH, 'tests', 'test_data')) self.meta_path = os.path.abspath(os.path.join(test_data_path, 'meta_load_data.json')) self.manifest_path = os.path.abspath( os.path.join(test_data_path, 'manifest_load_data.csv')) self.database_choice = 'docker_database' self.manifest = Manifest(path=self.manifest_path) def test_add_geocode_from_mar(self): # get rows for test cases dchousing_manifest_row = self.manifest.get_manifest_row( unique_data_id='dchousing_project') # mar_id test cases - except for ward other fields are typically Null mar_ids = [148655, 289735, 311058, 308201] fields = ['Ward2012', 'Cluster_tr2000', 'Cluster_tr2000_name', 'Proj_Zip', 'Anc2012', 'Geo2010', 'Status', 'Proj_addre', 'Proj_image_url', 'Proj_streetview_url', 'Psa2012', 'Proj_City', 'Proj_ST'] rows = list() # populate fields for each case as 'Null' for ids in mar_ids: id_dict = dict() id_dict.setdefault('mar_id', ids) for field in fields: if field == 'Proj_streetview_url': id_dict[field] = "dummy" else: id_dict[field] = 'Null' rows.append(id_dict) # verify add_geocode_from_mar() cleaner = ProjectCleaner(load_meta_data(self.meta_path), dchousing_manifest_row) for row in rows: result = cleaner.add_geocode_from_mar(row) for field in fields: self.assertFalse(result[field] == 'Null', "no 'Nulls' left.") if __name__ == '__main__': unittest.main()
import datetime from decimal import Decimal from django.test import TestCase from django.utils.timezone import make_aware from chat_wars_database.app.business_exchange.management.commands.calculate_statistics import apply_regex_for_each_line from chat_wars_database.app.business_exchange.management.commands.calculate_statistics import calculate from chat_wars_database.app.business_exchange.models import ExchangeMessages from chat_wars_database.app.business_exchange.models import StatsByDay class TestCalculateExchangeCommands(TestCase): def test_regex_should_extract_correct_information(self): self.assertEqual(apply_regex_for_each_line("🥔SmashinDeezNuts => 🥔Malte, 1 x 1💰").group("quantity"), "1") self.assertEqual(apply_regex_for_each_line("🦌whitetale => 🌑Taneleer Tivan, 15 x 5💰").group("quantity"), "15") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🦅LuluVi0, 1 x 7💰").group("quantity"), "1") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🦈Minie, 3 x 7💰").group("quantity"), "3") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🐉Rasputin, 10 x 7💰").group("quantity"), "10") self.assertEqual(apply_regex_for_each_line("🥔Malte => 🐉Sun Wokong, 15 x 6💰").group("quantity"), "15") self.assertEqual(apply_regex_for_each_line("🐺Silverstream => 🐉Sun Wokong, 30 x 6💰").group("quantity"), "30") self.assertEqual(apply_regex_for_each_line("🐺MegaDeth => 🥔Malte, 1 x 100💰").group("quantity"), "1") self.assertEqual(apply_regex_for_each_line("🦌Ilvatar => 🥔Malte, 573 x 1💰").group("quantity"), "573") self.assertEqual(apply_regex_for_each_line("🥔MORGANA => 🐺PABLO ESCOBAR, 1 x 2💰").group("quantity"), "1") self.assertEqual(apply_regex_for_each_line("🐉iBittz => 🐺Silverstream, 13 x 6💰").group("quantity"), "13") self.assertEqual(apply_regex_for_each_line("🥔Moka => 🥔Malte, 1 x 31💰").group("quantity"), "1") self.assertEqual(apply_regex_for_each_line("🥔SmashinDeezNuts => 🥔Malte, 1 x 1💰").group("value"), "1") self.assertEqual(apply_regex_for_each_line("🦌whitetale => 🌑Taneleer Tivan, 15 x 5💰").group("value"), "5") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🦅LuluVi0, 1 x 7💰").group("value"), "7") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🦈Minie, 3 x 7💰").group("value"), "7") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🐉Rasputin, 10 x 7💰").group("value"), "7") self.assertEqual(apply_regex_for_each_line("🥔Malte => 🐉Sun Wokong, 15 x 6💰").group("value"), "6") self.assertEqual(apply_regex_for_each_line("🐺Silverstream => 🐉Sun Wokong, 30 x 6💰").group("value"), "6") self.assertEqual(apply_regex_for_each_line("🐺MegaDeth => 🥔Malte, 1 x 1💰").group("value"), "1") self.assertEqual(apply_regex_for_each_line("🦌Ilvatar => 🥔Malte, 1 x 100💰").group("value"), "100") self.assertEqual(apply_regex_for_each_line("🥔MORGANA => 🐺PABLO ESCOBAR, 1 x 2💰").group("value"), "2") self.assertEqual(apply_regex_for_each_line("🐉iBittz => 🐺Silverstream, 13 x 6💰").group("value"), "6") self.assertEqual(apply_regex_for_each_line("🥔Moka => 🥔Malte, 1 x 31💰").group("value"), "31") self.assertEqual(apply_regex_for_each_line("🥔SmashinDeezNuts => 🥔Malte, 1 x 1💰").group()[3], "🥔") self.assertEqual(apply_regex_for_each_line("🦌whitetale => 🌑Taneleer Tivan, 15 x 5💰").group()[3], "🌑") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🦅LuluVi0, 1 x 7💰").group()[3], "🦅") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🦈Minie, 3 x 7💰").group()[3], "🦈") self.assertEqual(apply_regex_for_each_line("🌑Minion => 🐉Rasputin, 10 x 7💰").group()[3], "🐉") self.assertEqual(apply_regex_for_each_line("🥔Malte => 🐉Sun Wokong, 15 x 6💰").group()[3], "🐉") self.assertEqual(apply_regex_for_each_line("🐺Silverstream => 🐉Sun Wokong, 30 x 6💰").group()[3], "🐉") self.assertEqual(apply_regex_for_each_line("🐺MegaDeth => 🥔Malte, 1 x 1💰").group()[3], "🥔") self.assertEqual(apply_regex_for_each_line("🦌Ilvatar => 🥔Malte, 1 x 1💰").group()[3], "🥔") self.assertEqual(apply_regex_for_each_line("🥔MORGANA => 🐺PABLO ESCOBAR, 1 x 2💰").group()[3], "🐺") self.assertEqual(apply_regex_for_each_line("🐉iBittz => 🐺Silverstream, 13 x 6💰").group()[3], "🐺") self.assertEqual(apply_regex_for_each_line("🥔Moka => 🥔Malte, 1 x 31💰").group()[3], "🥔") def test_should_create_daily_stats_1(self): dt = make_aware(datetime.datetime(1981, 6, 21)).date() ExchangeMessages.objects.create( message_id=1, message_date=dt, message_text="""Pelt: 🦌Medivh => 🐺Bloodhunter, 1 x 2💰 🐺Zafit => 🐺Bloodhunter, 2 x 1💰 Coal: 🌑Taneleer Tivan => 🥔Malte, 2 x 10💰 🐺GrumpyGecko => 🥔Malte, 2 x 1💰""", ) calculate(dt) self.assertEqual(StatsByDay.objects.count(), 2) st: StatsByDay = StatsByDay.objects.filter(item__name="Pelt").first() self.assertEqual(st.date, dt) self.assertEqual(st.min_value, 1) self.assertEqual(st.max_value, 2) self.assertEqual(st.units, 3) self.assertEqual(st.min_value_message_id, 1) self.assertEqual(st.max_value_message_id, 1) self.assertEqual(st.deerhorn_castle_seller, 1) self.assertEqual(st.deerhorn_castle_buyer, 0) self.assertEqual(st.dragonscale_castle_seller, 0) self.assertEqual(st.dragonscale_castle_buyer, 0) self.assertEqual(st.highnest_castle_seller, 0) self.assertEqual(st.highnest_castle_buyer, 0) self.assertEqual(st.moonlight_castle_seller, 0) self.assertEqual(st.moonlight_castle_buyer, 0) self.assertEqual(st.potato_castle_seller, 0) self.assertEqual(st.potato_castle_buyer, 0) self.assertEqual(st.sharkteeth_castle_seller, 0) self.assertEqual(st.sharkteeth_castle_buyer, 0) self.assertEqual(st.wolfpack_castle_seller, 2) self.assertEqual(st.wolfpack_castle_buyer, 3) self.assertAlmostEquals(st.average_value, Decimal(1.33)) self.assertEqual(st.mean_value, 1) st: StatsByDay = StatsByDay.objects.filter(item__name="Coal").first() self.assertEqual(st.date, dt) self.assertEqual(st.min_value, 1) self.assertEqual(st.max_value, 10) self.assertEqual(st.units, 4) self.assertEqual(st.deerhorn_castle_seller, 0) self.assertEqual(st.deerhorn_castle_buyer, 0) self.assertEqual(st.dragonscale_castle_seller, 0) self.assertEqual(st.dragonscale_castle_buyer, 0) self.assertEqual(st.highnest_castle_seller, 0) self.assertEqual(st.highnest_castle_buyer, 0) self.assertEqual(st.moonlight_castle_seller, 2) self.assertEqual(st.moonlight_castle_buyer, 0) self.assertEqual(st.potato_castle_seller, 0) self.assertEqual(st.potato_castle_buyer, 4) self.assertEqual(st.sharkteeth_castle_seller, 0) self.assertEqual(st.sharkteeth_castle_buyer, 0) self.assertEqual(st.wolfpack_castle_seller, 2) self.assertEqual(st.wolfpack_castle_buyer, 0) self.assertAlmostEquals(st.average_value, Decimal(5.5)) self.assertEqual(st.mean_value, 5) def test_should_create_daily_stats_2(self): dt = make_aware(datetime.datetime(1981, 6, 21)).date() ExchangeMessages.objects.create( message_id=1, message_date=dt, message_text="""Stick: 🐺Sayur Kol => 🦈Godo, 5 x 1💰 🐺Sayur Kol => 🦈Godo, 5 x 1💰 Thread: 🦌metal queen => 🌑hasserodeer, 18 x 6💰 🦌metal queen => 🌑Tarkus, 50 x 6💰 🦌metal queen => 🌑Tarkus, 32 x 6💰 Metal plate: 🌑ebonyhoof => 🐺Bl4ckBull, 9 x 7💰 Bone: 🐺Hyx_Death_Knight => 🐺Arthas_Lich_King, 1 x 123💰 🐺Hyx_Death_Knight => 🐺Dettlaf, 1 x 112💰 🐺Hyx_Death_Knight => 🐺Unstoppable, 1 x 244💰 Rope: 🦌UP aGAIN oo => 🐺Bl4ckBull, 7 x 5💰""", ) ExchangeMessages.objects.create( message_id=2, message_date=dt, message_text="""Thread: 🐺Anshultz => 🐉Connor Kenway, 10 x 6💰 🌑brok => 🐺vincent, 1 x 7💰 🌑Minion => 🐺vincent, 1 x 7💰 🌑Minion => 🐺vincent, 1 x 7💰 🐺Anshultz => 🌑Tarkus, 25 x 6💰 🐺Anshultz => 🌑Tarkus, 48 x 6💰 🌑brok => 🐉SagasuGin, 4 x 7💰 Bone: 🐺Meliodas Son-DOC => 🐉a porn star, 1 x 16💰""", ) calculate(dt) self.assertEqual(StatsByDay.objects.count(), 5) st: StatsByDay = StatsByDay.objects.filter(item__name="Bone").first() self.assertEqual(st.date, dt) self.assertEqual(st.min_value, 16) self.assertEqual(st.max_value, 244) self.assertEqual(st.units, 4) self.assertEqual(st.min_value_message_id, 2) self.assertEqual(st.max_value_message_id, 1) self.assertEqual(st.deerhorn_castle_seller, 0) self.assertEqual(st.deerhorn_castle_buyer, 0) self.assertEqual(st.dragonscale_castle_seller, 0) self.assertEqual(st.dragonscale_castle_buyer, 1) self.assertEqual(st.highnest_castle_seller, 0) self.assertEqual(st.highnest_castle_buyer, 0) self.assertEqual(st.moonlight_castle_seller, 0) self.assertEqual(st.moonlight_castle_buyer, 0) self.assertEqual(st.potato_castle_seller, 0) self.assertEqual(st.potato_castle_buyer, 0) self.assertEqual(st.sharkteeth_castle_seller, 0) self.assertEqual(st.sharkteeth_castle_buyer, 0) self.assertEqual(st.wolfpack_castle_seller, 4) self.assertEqual(st.wolfpack_castle_buyer, 3) # # self.assertAlmostEquals(st.average_value, Decimal(1.33)) # self.assertEqual(st.mean_value, 1)
from flask import Blueprint tagsBP = Blueprint('tagsBlueprint', __name__) tagsAdminBP = Blueprint('tagsAdminBlueprint', __name__) tagsApiBP = Blueprint('tagsAPIBlueprint', __name__) from . import views,admin,api
# *** RECURSOS *** import time import msvcrt import random as ran from os import system # *** FUNCIONES BASE *** def clean(): # Limpia la consola system("cls") def time1(var): # Pausa de tiempo time.sleep(var) # *** DATOS *** # Intro intro = ("El juego consiste en un tablero donde está el Gato y el Raton", "Ambos aparecen al inicio de forma aleatoria", "Gato puede estar en las esquinas inferiores", "Raton en la primer fila", "Gato se mueve en diagonal y en una ruta unica depende de su posicion inicial", "Raton se mueve en cruz", "Gato se puede quedar dormido, si es asi, se queda quieto hasta despertar", "Si raton intenta moverse fuera del tablero, se hace un chichon y no se mueve hasta la siguiente jugada", "Si gato y raton estan en la misma casilla, pero gato esta dormido, no pasa nada...", "Si al contrario, esta despierto, raton es comido por gato, y se pierde la partida", "Tambien se pierde si se acaban los intentos...", "Para ganar, raton debe llegar a la salida antes de que se lo coman", "!!! Suerte !!!" ) # General c = 0 mensaje_f = 0 mensaje_f2 = "Se han acabado los intentos" mensaje_f3 = "Gato se ha comido al Raton" mensaje_f4 = "Raton ha llegado a la salida" mensaje_st = 0 final_st = True # T => Juego Ganado, F => Juego Perdido g_r = False # Gato despierto y raton en misma casilla s_r = False # Raton en salida t = [] # Tablero # Gato gato_x, gato_y = 0, 0 # Coordenadas gato_pos = 0 # Posicion Inicial (1 = esquina inf izq, 2 == esquina inf der) gato_st = True # T = Despierto, F = Dormido gato_symbol = 0 # Simbolo Real gato_symbol2 = 0 # Simbolo Estadistica # Raton raton_x, raton_y = 0, 0 # Coordenadas raton_ch = 0 # Chichones raton_st = True # T = Normal, F = Noqueado raton_symbol = 0 # Simbolo Real raton_symbol2 = 0 # Simbolo Estadistica # Salida salida_x, salida_y = 0, 0 # Coordenadas salida_symbol = "S" # Simbolo # *** JUEGO *** # Intro clean() print("*** Bienvenido al juego del Gato y el Raton! ***") # Omitir intro while True: intro_in = input("Omitir intro? (S/n) => ") intro_r = intro_in.lower() clean() if (intro_r != "s") and (intro_r != "n"): print("Escribe un valor correcto...") continue elif intro_r == "s": break elif intro_r == "n": for i in intro: time1(3) print(f"{i}\n") print("Presiona enter para continuar") msvcrt.getch() break while True: clean() # Entradas de dimension del tablero e intentos dimension_r = False intentos_r = False while (dimension_r and intentos_r) == False: try: if dimension_r == False: dimension_t = int(input("Ingresa la dimensión del tablero (entre 4 a 15) ==> ")) if (dimension_t >= 4) and (dimension_t <= 15): dimension_r = True else: clean() print("Escribe un numero entre 4 a 15...") if intentos_r == False and dimension_r == True: intentos = int(input("Ingresa la cantidad de intentos (entre 10 a 250) ==> ")) if (intentos >= 10) and (intentos <= 250): intentos_r = True else: clean() print("Escribe un numero entre 10 a 250...") except ValueError: clean() print("Escribe un numero, no un caracter...") clean() # Creacion de la matriz for i in range(dimension_t): t.append([]) for j in range(dimension_t): t[i].append("*") # Coordenadas iniciales gato_x, gato_y = ran.choice([1, dimension_t]), dimension_t # Random Gato raton_x, raton_y = ran.randint(1, dimension_t), 1 # Random Raton # Random salida salida_y = dimension_t if gato_x == 1: salida_x = ran.randint(2, dimension_t) gato_pos = 1 else: salida_x = ran.randint(1, (dimension_t - 1)) gato_pos = 2 while True: b = ran.choice([True, False]) # Random mov de gato r = ran.choice([1, 2, 3, 4]) # Random mov de Raton # Movimientos Gato (En diagonal) if c == 1 and gato_st == True: # Comprueba desde 2da vuelta, y si gato está despierto if gato_pos == 1: # Ruta barra invertida \ if (gato_x == 1) and (gato_y == dimension_t): # Esquina Inferior Izquierda # Diagonal arriba derecha gato_x += 1 gato_y -= 1 elif (gato_x == dimension_t) and (gato_y == 1): # Esquina Superior Derecha # Diagonal abajo izquierda gato_x -= 1 gato_y += 1 else: # Si no esta en las esquinas, pero en la ruta \ # Movimiento random if b == True: # Diagonal arriba derecha gato_x += 1 gato_y -= 1 else: # Diagonal abajo izquierda gato_x -= 1 gato_y += 1 else: # Ruta barra derecha / if (gato_x and gato_y) == dimension_t: # Esquina Inferior Derecha # Diagonal arriba izquierda gato_x -= 1 gato_y -= 1 elif (gato_x and gato_y) == 1: # Esquina Superior Izquierda # Diagonal abajo derecha gato_x += 1 gato_y += 1 else: # Si no esta en las esquinas, pero en la ruta / # Movimiento random if b == True: # Diagonal arriba izquierda gato_x -= 1 gato_y -= 1 else: # Diagonal abajo derecha gato_x += 1 gato_y += 1 # Movimientos Raton (En cruz) if c == 1 and raton_st == True: # Comprueba desde 2da vuelta, y si raton está bien if r == 1: # Intenta ir hacia arriba if raton_y == 1: # Si no puede, chichon +1 y se queda quieto raton_ch += 1 raton_st = False else: # Si puede, se mueve raton_y -= 1 elif r == 3: # Intenta ir hacia la derecha if raton_x == dimension_t: # Si no puede, chichon +1 y se queda quieto raton_ch += 1 raton_st = False else: # Si puede, se mueve raton_x += 1 elif r == 2: # Intenta ir hacia abajo if raton_y == dimension_t: # Si no puede, chichon +1 y se queda quieto raton_ch += 1 raton_st = False else: # Si puede, se mueve raton_y += 1 elif r == 4: # Intenta ir hacia la izquierda if raton_x == 1: # Si no puede, chichon +1, y se queda quieto raton_ch += 1 raton_st = False else: # Si puede, se mueve raton_x -= 1 if c == 0: c += 1 # Hace que Gato y Raton se muevan despues de la 1ra vuelta # Comprobamos Estado Gato if gato_st == True: gato_symbol = "G" gato_symbol2 = "Despierto" else: gato_symbol = "g" gato_symbol2 = "Dormido" # Comprobamos Estado Raton if raton_st == True: raton_symbol = "R" raton_symbol2 = "Normal" else: raton_symbol = "r" raton_symbol2 = "Noqueado" # Actualizando Tablero t[gato_y-1][gato_x-1] = gato_symbol # Gato t[salida_y-1][salida_x-1] = salida_symbol # Salida # Raton if (gato_x == raton_x) and (gato_y == raton_y): # Comprueba si gato y raton en misma coordenada t[raton_y - 1][raton_x - 1] = f"{gato_symbol}*{raton_symbol}" # Los imprime como (G*R) if gato_st == True: g_r = True elif (raton_x == salida_x) and (raton_y == salida_y): t[raton_y - 1][raton_x - 1] = f"{salida_symbol}*{raton_symbol}" s_r = True else: # Si estan en diferente coordenada t[raton_y - 1][raton_x - 1] = raton_symbol # Estadisticas a = [ "Juego\n", f"Intentos => {intentos}", f"Tablero => {dimension_t}x{dimension_t}", "- " * 20, "Gato\n", f"Coordenadas => ({gato_x},{gato_y})", f"Estado => {gato_symbol2}", "- " * 20, "Raton\n", f"Coordenadas => ({raton_x},{raton_y})", f"Estado => {raton_symbol2}", f"Chichones => {raton_ch}" ] # Impresion del tablero for i in range(dimension_t): for j in range(dimension_t): print(f"\t{t[i][j]}", end="") print("\n\n") # Impresion de las estadisticas for i in a: print(f"\t{i}") # Actualizando Estados gato_st = ran.choice([True, False, True]) # Gato raton_st = True # Borrando Simbolos t[gato_y - 1][gato_x - 1] = "*" t[raton_y - 1][raton_x - 1] = "*" # Espera y limpieza time1(1.2) clean() # Logica Final if g_r == False: if intentos == 0: mensaje_f = mensaje_f2 final_st = False break elif intentos > 0: intentos -= 1 else: mensaje_f = mensaje_f3 final_st = False break if s_r == True: mensaje_f = mensaje_f4 final_st = True break # *** Fin de la partida *** # Logica de Juego Ganado/Perdido if final_st == True: mensaje_st = "Haz ganado" else: mensaje_st = "Haz perdido" print("\n=" + "=" * 39) print(f"{mensaje_f} !\n\n{mensaje_st} !") time1(4) while True: final_q = input("Desea jugar de nuevo? (S/n) => ") final_r = final_q.lower() clean() if (final_r != "s") and (final_r != "n"): print("Escribe una opcion valida...") continue else: break # Verificacion de si desea jugar de nuevo if final_r == "s": # Reset de estadisticas t[salida_y - 1][salida_x - 1] = "*" c, mensaje_f ,mensaje_st = 0, 0, 0 final_st, g_r, s_r = True, False, False t = [] gato_x, gato_y, raton_x, raton_y = 0, 0, 0, 0 raton_ch, raton_symbol, raton_symbol2 = 0, 0, 0 gato_pos, gato_symbol, gato_symbol2 = 0, 0, 0 gato_st, raton_st = True, True salida_x, salida_y = 0, 0 continue else: break # *** FIN DEL JUEGO *** print("*** JUEGO TERMINADO ***") time1(3)
#!/usr/bin/env python import os import re import sys from prettytable import PrettyTable # Paths script_root_directory = sys.path[0] nmap_output_path = script_root_directory + "/nmap_output.txt" dictionary_ref_path = script_root_directory + "/dictionary_reference.txt" # Configuration ip_range = "10.0.0.1-20" ip_range_regex = "10\.0\.0\.(.*)" # This regex, of course, needs to be modified to suit your own IP structure. local_ip = "10.0.0.8" local_mac = "B8:27:EB:AA:C3:AA" os.system("echo 'Beginning Scan...'") os.system("sudo nmap -sP " + ip_range + " > " + nmap_output_path) # This, of course, is the output from Nmap nmap = open(nmap_output_path, "r") ip_addresses = [] mac_addresses = [] match_ip_var = None for line in nmap: match_ip = re.search(ip_range_regex, line) match_mac = re.search("..:..:..:..:..:..", line) if (not match_ip) and (not match_mac): continue if match_ip: ip_addresses.insert(0, match_ip.group(0)) match_ip_var = match_ip.group(0) elif match_ip_var == local_ip: # For some reason the rPi's own MAC address doesn't register. # This manually ads it in when it's static ip is detected mac_addresses.insert(0, local_mac) if match_mac: mac_addresses.insert(0, match_mac.group(0)) nmap.close() # This is where we get the Hostname/MAC address combos dictionary_ref = open(dictionary_ref_path, "r") mac_and_hostnames = {} for line in dictionary_ref: mac, hostname = line.strip().split('=') mac_and_hostnames[mac.strip()] = hostname.strip() dictionary_ref.close() table = PrettyTable(["Hostname", "MAC", "IP"]) table.align["Hostname", "MAC", "IP"] = "c" table.padding_width = 1 number_hosts = len(mac_addresses) for i in xrange(0, number_hosts, 1): if mac_addresses[i] in mac_and_hostnames: current_hostname = mac_and_hostnames[mac_addresses[i]] else: current_hostname = "UNKNOWN" table.add_row([current_hostname, mac_addresses[i], ip_addresses[i]]) print table print "Number of Hosts: " + str(number_hosts)
from Simulator import Simulator, Packet, EventEntity from enum import Enum from struct import pack, unpack import sys # In this class you will implement a full-duplex Go-Back-N client. Full-duplex means that this client can # both send and receive data. You are responsible for implementing a Go-Back-N protocol in a simulated # Transport layer. We are not going to use real network calls in this project, as we want to precisely # simulate when packet delay, loss, and corruption occurs. As such, your simulated transport protocol # will interface with the Simulator object to communicate with simulated Application and Network layers. # # The Simulator will call three functions that you are responsible for implementing. These functions define # the interface by which the simulated Application and Network layers communicate with your transport layer: # - receive_from_application_layer(payload) will be called when the Simulator has new data from the application # layer that needs to be sent across the network # - receive_from_network_layer(byte_data) will be called when the Simulator has received a new packet from the # network layer that the transport layer needs to process # - timer_interrupt() will be called when the Simulator detects that a timer has expired # # Your code can communicate with the Simulator by calling three methods: # - Call self.simulator.to_layer5(payload) when your Transport layer has successfully received and processed # a data packet from the other host that needs to be delivered up to the Application layer # * to_layer5() expects to receive the payload of a packet as a decoded string, not as the bytes object # generated by unpack # - Call self.simulator.to_layer3(byte_data) when your Transport layer has created a data packet or an ACK packet # that needs to be sent across the network to the other host # * to_layer3() expects to receive a packet that has been converted into a bytes object using pack. See the # next section in this comment for more detail # - Call self.simulator.start_timer(self.entity, self.timer_interval) when you want to start a timer # # Additionally, you will need to write code to pack/unpack data into a byte representation appropriate for # communication across a network. For this assignment, you will assume that all packets use the following header: # - Sequence Number (int) -- Set to 0 if this is an ACK # - Acknowledgement Number (int) -- Set to 0 if this is not an ACK # - Checksum (half) -- Compute the Internet Checksum, as discussed in class # - Acknowledgement Flag (boolean) -- Set to True if sending an ACK, otherwise False # - Payload length, in bytes (int) -- Set this to 0 when sending an ACK message, as these will not carry a payload # - Payload (string) -- Leave this empty when sending an ACK message # When unpacking data in this format, it is recommended to first unpack the fixed length header. After unpacking the # header, you can determine if there is a payload, based on the size of Payload Length. # NOTE: It is possible for payload length to be corrupted. In this case, you will get an Exception similar to # "unpack requires a buffer of ##### bytes". If you receive this exception, this is a sign that the packet is # corrupt. This is not the only way the packet can be corrupted, but is a special case of corruption that will # prevent you from unpacking the payload. If you can unpack the payload, use the checksum to determine if the # packet is corrupted. If you CAN'T unpack the payload, then you already KNOW that the packet is corrupted. # When unpacking a packet, you can store the values in the Packet class, defined in the constructor. You MUST send # data between hosts in a byte representation, but after receiving a packet you may find it convenient to # store the values in this class, as it will allow you to refer to them by name in your code, rather than via # the array indicies produced by unpack(). # # Finally, you will need to implement the Internet Checksum algorithm for your packets. As discussed in class, # sum each of the 16-bit words of the packet, carrying around any overflow bits. Once you have summed all of the # 16-bit words, perform the 1's complement. If a packet contains an odd number of bytes (i.e. the last byte doesn't # fit into a 16-bit word), pad the packet (when computing the checksum) with a 0 byte. When receiving a packet, # check that it is valid using this checksum. # # NOTE: By default, all of the test cases created for this program capture print() output and save it in a log # file with the same name as the test case being run. You can disable this functionality by editing # the test***.cfg file and removing the --capture_log argument (just delete it). Do NOT change any other # of the option parameters in test***.cfg class GBNHost(): # The __init__ method accepts: # - a reference to the simulator object # - the name for this entity (EntityType.A or EntityType.B) # - the interval for this entity's timer # - the size of the window used for the Go-Back-N algorithm def __init__(self, simulator, entity, timer_interval, window_size): # These are important state values that you will need to use in your code self.simulator = simulator self.entity = entity # Sender properties self.timer_interval = timer_interval # The duration the timer lasts before triggering self.window_size = window_size # The size of the seq/ack window self.last_ACKed = 0 # The last ACKed packet. This starts at 0 because no packets # have been ACKed self.current_seq_number = 1 # The SEQ number that will be used next self.app_layer_buffer = [] # A buffer that stores all data received from the application # layer that hasn't yet been sent self.unACKed_buffer = {} # A buffer that stores all sent but unACKed packets # Receiver properties self.expected_seq_number = 1 # The next SEQ number expected # ACK response with an ACK # of 0 self.last_ACK_pkt = pack('!iiH?i', 0, 0, 65279, True, 0) # The last ACK pkt sent. # TODO: This should be initialized to an ACK response with an # ACK number of 0. If a problem occurs with the first # packet that is received, then this default ACK should # be sent in response, as no real packet has been rcvd yet ########################################################################################################### ## Core Interface functions that are called by Simulator # This function implements the SENDING functionality. It should implement retransmit-on-timeout. # Refer to the GBN sender flowchart for details about how this function should be implemented # NOTE: DIFFERENCE FROM GBN FLOWCHART # If this function receives data to send while it does NOT have an open slot in the sending window, # it should store this data in self.app_layer_buffer. This data should be immediately sent # when slots open up in the sending window. # TODO: Implement this method def receive_from_application_layer(self, payload): base = self.last_ACKed + 1 # rdt_send(data) # if (nextseqnum < Base + N) if (self.current_seq_number < (base + self.window_size)): # make a packet with payload pkt = self.make_pkt(payload) # sndpkt[nextseqnum] = make_pkt(nextseqnum, data, checksum) self.unACKed_buffer[self.current_seq_number] = pkt # udt_send(sndpkt[nextseqnum]) self.simulator.to_layer3(self.entity, self.unACKed_buffer[self.current_seq_number], False) # if base == nextseqnum if (base == self.current_seq_number): self.simulator.start_timer(self.entity, self.timer_interval) # nextseqnum ++ self.current_seq_number += 1 # sending window closed, add to buffer else: self.app_layer_buffer.append(payload) # This function implements the RECEIVING functionality. This function will be more complex that # receive_from_application_layer(), as it must process both packets containing new data, and packets # containing ACKs. You will need to handle received data differently depending on if it is an ACK # or a packet containing data. # Refer to the GBN receiver flowchart for details about how to implement responding to data pkts, and # refer to the GBN sender flowchart for details about how to implement responidng to ACKs # NOTE: DIFFERENCE FROM GBN FLOWCHART # If the received packet is corrupt, you should always resend the last sent ACK. If the packet # is corrupt, we can't be certain if it was an ACK or a packet containing data. In the flowchart # we do nothing if the corrupted packet was an ACK, but we re-send the last ACK if the corrupted # packet had data. Re-sending an extra ACK won't cause any problems, so we'd rather do that than # not send an ACK when we should have # TODO: Implement this method def receive_from_network_layer(self, byte_data): # check for corruption corrupt = self.checkCorruption(byte_data) #unpack fixed length header header = unpack("!iiH?i", byte_data[:15]) # Check to see if the length of the packet is greater # than zero. If so, unpack the payload try: if header[4] > 0: payload = unpack('!%is'%header[4], byte_data[15:])[0].decode() else: payload = None pkt = Packet(header, payload, byte_data) # if header length is corrupt, make an empty packet and set corrupt to True except Exception as e: pkt = Packet(header, None, byte_data) corrupt = True # ACK MESSAGE # rdt_rcv(rcvpkt) && notcorrupt(rcvpkt) if (pkt.ackflag == True and corrupt == False): # base = getacknum(rcvpkt)+1 self.last_ACKed = pkt.acknum # if (base == nextseqnum) if self.last_ACKed + 1 == self.current_seq_number: #stop_timer self.simulator.stop_timer(self.entity) # PAYLOAD MESSAGE # rdt_rcv(rcvpkt) && notcurrupt(rcvpkt) && hasseqnum(rcvpkt, expectedseqnum) # if packet contains data elif (pkt.ackflag == False and corrupt == False and pkt.seqnum == self.expected_seq_number): # deliver_data(data) self.simulator.to_layer5(self.entity, pkt.payload) #sndpkt = make_pkt(expectedseqnum,ACK, chksum) pkt = self.make_pkt(False) # new Last_ACK_pkt self.last_ACK_pkt = pkt #udt_send(sndpkt) self.simulator.to_layer3(self.entity, pkt, True) #expectedseqnum++ self.expected_seq_number += 1 # if expected seq number is out of order elif (pkt.ackflag == False and corrupt == False and pkt.seqnum != self.expected_seq_number): self.simulator.to_layer3(self.entity, self.last_ACK_pkt, True) # if data is corrupt elif corrupt == True: self.simulator.to_layer3(self.entity, self.last_ACK_pkt, True) # This function is called by the simulator when a timer interrupt is triggered due to an ACK not being # received in the expected time frame. All unACKed data should be resent, and the timer restarted # TODO: Implement this method def timer_interrupt(self): max = self.current_seq_number base = self.last_ACKed+1 # start timer self.simulator.start_timer(self.entity, self.timer_interval) # resend unACKed messages for i in range(base, max, 1): self.simulator.to_layer3(self.entity, self.unACKed_buffer[i], False) # this function makes a packet with or without a payload def make_pkt(self, data = False): # if there is NOT a payload # ACK pkt if (data == False): pkt = pack('!ii?i', 0, self.expected_seq_number, True, 0) checksum = self.getChecksum(pkt) pkt = pack('!iiH?i', 0, self.expected_seq_number, checksum, True, 0) return pkt # if there IS a payload # data pkt else: size = len(data) pkt = pack('!ii?i' + str(size) + 's', self.current_seq_number, 0, False, size, data.encode()) checksum = self.getChecksum(pkt) pkt = pack('!iiH?i' + str(size) + 's', self.current_seq_number, 0, checksum, False, size, data.encode()) return pkt # calculates checksum for a packet being sent def getChecksum(self, packet): padded_pkt = None # if byte array is odd, pad it to make it even if len(packet) % 2 == 1: padded_pkt = packet + bytes(1) # otherwise do nothing else: padded_pkt = packet s = 0x0000 # split into 16 bit words for i in range(0, len(padded_pkt), 2): w = padded_pkt[i] << 8 | padded_pkt[i+1] s = self.carry(s, w) return ~s & 0xffff # splits byte array up into 16 bit words, adds them, and checks if sum is all 1's # returns False if all 1's (no corruption), and True otherwise def checkCorruption(self, packet): padded_pkt = None if len(packet) % 2 == 1: padded_pkt = packet + bytes(1) else: padded_pkt = packet s = 0x0000 for i in range(0, len(padded_pkt), 2): w = padded_pkt[i] << 8 | padded_pkt[i+1] s = self.carry(s, w) if s == 65535: return False else: return True # carries binary addition overflow def carry(self, a, b): c = a + b return (c & 0xffff) + (c >> 16)
#EJERCICIO 8 numCliente = input("Ingrese número de cliente: ") facturaTotal = int(input("Ingrese el total de la factura: ")) descuento = (facturaTotal * 2)/100 interes = (facturaTotal * 10)/100 if(120 < descuento): importeDescuento = facturaTotal - 120 else: importeDescuento = facturaTotal - descuento if(150 > interes): importeInteres = facturaTotal + 150 else: importeInteres = facturaTotal + interes print("El precio durante los primeros 10 días del mes es de:", importeDescuento) print("El precio entre el día 11 y 20 del mes es de:", facturaTotal) print("El precio a partir del día 21 del mes es de:", importeInteres)
# coding: utf-8 from ConfigParser import ConfigParser from datetime import datetime import requests import matplotlib.pyplot as plt from watson_developer_cloud import AlchemyLanguageV1 as alchemy class Sentimental(): def __init__(self): self.alchemy_client = self._get_alchemy_client() self.prev_score = 0.5 @staticmethod def _get_alchemy_client(): alchemy_config = ConfigParser() alchemy_config.read(u'alchemy.conf') API_KEY = alchemy_config.get(u'credentials', 'API_KEY') return alchemy(api_key=API_KEY) def _get_sentiment(self, text): return self.alchemy_client.combined( text=text, extract=['doc-sentiment'], language='russian' ).get(u'docSentiment') def sentiment_score(self, text): self.prev_score = self._get_sentiment(text).get(u'score', self.prev_score) return self.prev_score def sentiment_over_time(self, data, avg_window=3, output='sentimental.png'): """ Draws a time series chart of text sentiment given: :param data: list of tuples (str, datetime object) :param avg_window: size of moving average window :param output: (optional) output file """ text_list, time_list = zip(*data) score_list = [float(self.sentiment_score(text)) for text in text_list] avg = lambda l: sum(l) / len(l) avg_score_list = [ avg(score_list[idx:idx + avg_window]) for idx in range(len(score_list) - avg_window - 1) ] plt.plot(time_list, score_list) plt.savefig(output) if __name__ == '__main__': data = [] # e.x. Comment.objects.values_list('text', 'created_at') sent = Sentimental() sent.sentiment_over_time(data)
#!/usr/bin/env python # # Major mods by Roger Burnham January 2012 # from the rov_joystick module started by Steve Phillips # import argparse import logging import platform import pygame import serial import sys import time from ArduinoPorts import findServoPort from math import floor sysPlatform = platform.system() usbPort, dev = None, None X_AXIS = 0 Y_AXIS = 1 THROTTLE_AXIS = 2 # Throttle Z_AXIS = 3 RUDDER_AXIS = 4 BUTTONS = {0: 'Trigger', 1: 'Action 2', 2: 'Action 3', 3: 'Action 4', 4: 'Action 5', 5: 'Action 6', 6: 'Action 7', 7: 'Action 8', 8: 'Action 9', 9: 'Action 10', 10: 'ST', 11: 'SE'} # lambda to convert integer into a string of the binary representation bstr = lambda n, l=16: n<0 and binarystr((2L<<l)+n) or n and bstr(n>>1).lstrip('0')+str(n&1) or '0' # allow multiple joysticks joy = [] def logJoyDict(e): for k in e.dict.keys(): logging.debug(' %s->%s' % (k, `e.dict[k]`)) def fix(bits): if bits & 0b00100000: return 63-bits else: return bits # handle joystick event def handleJoyEvent(e): if e.type == pygame.JOYAXISMOTION: axis = "unknown" bits = 0b00000000 if (e.dict['axis'] == X_AXIS): axis = "X" bits = 0b10000000 # Throw away; don't change anything if (e.dict['axis'] == Y_AXIS): axis = "Y" bits = 0b10000000 if (e.dict['axis'] == THROTTLE_AXIS): axis = "T" bits = 0b01000000 if (e.dict['axis'] == Z_AXIS): axis = "Z" bits = 0b11000000 if (axis != "unknown"): logging.debug('JoyAxisEvent %s %s %s, bitmask: %s' % (e.type, axis, pygame.event.event_name(e.type), bstr(bits))) scale = 63 # From 0 to __ scale /= 2 bottom5 = int( scale*(e.dict['value']+1) ) logging.debug(" From joystick: %s %s" % (axis, bottom5)) logging.debug(" bits+bottom5: %s" % `bits+bottom5`) dev.write(chr(bits+bottom5)) logging.debug(" %s %f" % (axis, e.dict['value']+1)) from_arduino = dev.read(1) logging.debug(" from_arduino: %s" % `from_arduino`) time.sleep(.030) # for num in range(256): # print "Sending " + str(num) # dev.write(chr(num)) # time.sleep(.005) # Arduino joystick-servo hack if (axis == "X"): pos = e.dict['value'] # convert joystick position to servo increment, 0-180 move = round(pos * 90, 0) if (move < 0): serv = int(90 - abs(move)) else: serv = int(move + 90) # convert position to ASCII character servoPosition = serv # and send to Arduino over serial connection logging.debug("???servo.move(1, %s)" % servoPosition) # Arduino joystick-servo hack if (axis == "Y"): pos = e.dict['value'] # convert joystick position to servo increment, 0-180 move = round(pos * 90, 0) if (move < 0): serv = int(90 - abs(move)) else: serv = int(move + 90) # convert position to ASCII character servoPosition = serv # and send to Arduino over serial connection logging.debug("???servo.move(2, %s)" % servoPosition) elif e.dict['axis'] == RUDDER_AXIS: rudderVal = e.dict['value'] logging.debug('RudderEvent %s %s -> %.4f' % (e.type, pygame.event.event_name(e.type), rudderVal)) else: logging.error('unknown axis: %s' % `e.dict['axis']`) logJoyDict(e) elif e.type == pygame.JOYHATMOTION: xVal, yVal = e.dict['value'] logging.debug('JoyHatEvent %s %s -> %s' % (e.type, pygame.event.event_name(e.type), `(xVal, yVal)`)) elif e.type == pygame.JOYBUTTONDOWN: button = e.dict['button'] logging.debug('JoyButtonDownEvent %s %s -> %s' % (e.type, pygame.event.event_name(e.type), BUTTONS[button])) elif e.type == pygame.JOYBUTTONUP: button = e.dict['button'] logging.debug('JoyButtonUpEvent %s %s -> %s' % (e.type, pygame.event.event_name(e.type), BUTTONS[button])) # wait for joystick input def joystickControl(): logging.info('entering joystick control loop') while 1: e = pygame.event.wait() if (e.type in [pygame.JOYAXISMOTION, pygame.JOYBUTTONDOWN, pygame.JOYBUTTONUP, pygame.JOYHATMOTION]): handleJoyEvent(e) else: logging.debug('unhandled event %s: %s' % (`e.type`, pygame.event.event_name(e.type))) logJoyDict(e) # main method def main(): global dev, usbport logLevel = logging.INFO parser = argparse.ArgumentParser(description='Joystick control of a servo') parser.add_argument('-debug', action='store_true') args = parser.parse_args() if args.debug: logLevel = logging.DEBUG # set up logging to file - see previous section for more details logging.basicConfig(level=logLevel, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='./%s.log' % sys.argv[0], filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.DEBUG) # set a format which is simpler for console use formatter = logging.Formatter('%(name)-6s: %(levelname)-8s %(message)s') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) usbPort, dev = findServoPort() logging.info('Arduino servo found on part %s' % usbPort) # initialize pygame logging.info('initializing joystick...') pygame.joystick.init() logging.info('initializing display...') pygame.display.init() if not pygame.joystick.get_count(): logging.error('Please connect a joystick and run again.') quit() for i in range(pygame.joystick.get_count()): myjoy = pygame.joystick.Joystick(i) myjoy.init() joy.append(myjoy) logging.debug("Joystick %d: " % (i+1) + joy[i].get_name()) # run joystick listener loop joystickControl() # allow use as a module or standalone script if __name__ == "__main__": main()
import urllib2, urllib, json, csv import scraperwiki headers = {'X-Requested-With': 'XMLHttpRequest'} data = urllib.urlencode({ 'Position': '0,0', 'Bounds': '-100,-100,100,100', }) url = 'https://www.greggs.co.uk/home/shop-finder' # run the request raw_res = urllib2.urlopen(urllib2.Request( url, data=data, headers=headers, )).read() # jsonify and listify the output res = [{'id': id_, 'name': x['Name'], 'lat': x['Latitude'], 'long': x['Longitude'], 'phone': x['Telephone'], 'addr': x['HTMLAddress']} for id_, x in json.loads(raw_res).items()] # save it scraperwiki.sqlite.save(unique_keys=['id'], data=res) # with open('out.csv', 'wb') as f: # w = csv.DictWriter(f, res[0].keys()) # w.writeheader() # w.writerows(res)
import urllib.request, json from .models import News_Update from .models import Article api_key = None base_url = None articles_url = None def configure_request(app): global api_key, base_url, articles_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] articles_url = app.config['ARTICLES_BASE_URL'] def get_updates(category): ''' function to get json response of out request :param category :return: ''' get_updates_url = base_url.format(category, api_key) print(get_updates_url) with urllib.request.urlopen(get_updates_url) as url: get_updates_data = url.read() get_updates_response = json.loads(get_updates_data) update_results = [] if get_updates_response['sources']: update_results = get_updates_response['sources'] update_results = process_results(update_results) return update_results def process_results(update_results_list): ''' process update result and transform to list of object ''' update_results = [] for update_content in update_results_list: id = update_content.get('id') name = update_content.get('name') category = update_content.get('category') url = update_content.get('url') update_object = News_Update(id, name, category, url) update_results.append(update_object) return update_results def get_articles(id): get_articles_url = articles_url.format(id, api_key) print(get_articles_url) with urllib.request.urlopen(get_articles_url) as url: get_articles_data = url.read() get_articles_response = json.loads(get_articles_data) articles_results = None if get_articles_response['articles']: articles_results = get_articles_response['articles'] articles_results = process_articles(articles_results) return articles_results # articles_results = json.loads(url.read()) # articles_object = None # if articles_results['articles']: # articles_object = process_articles(articles_results['articles']) # # return articles_object def process_articles(articles_list): articles_results = [] for article_cont in articles_list: id = article_cont.get('id') author = article_cont.get('author') title = article_cont.get('title') description = article_cont.get('description') url = article_cont.get('url') image = article_cont.get('urlToImage') date = article_cont.get('publishedAt') articles_object = Article(id,author,title,description,url,image,date) articles_results.append(articles_object) return articles_results
from threading import RLock from typing import Any, Callable, Dict, List, Optional import optuna from optuna.study import Study from tune import ( Choice, NonIterativeObjectiveFunc, NonIterativeObjectiveLocalOptimizer, Rand, RandInt, TransitionChoice, Trial, TrialReport, ) from tune._utils.math import _IGNORABLE_ERROR, uniform_to_discrete, uniform_to_integers from tune.concepts.space import TuningParametersTemplate class OptunaLocalOptimizer(NonIterativeObjectiveLocalOptimizer): def __init__( self, max_iter: int, create_study: Optional[Callable[[], Study]] = None ): self._max_iter = max_iter self._create_study = create_study or optuna.create_study def run(self, func: NonIterativeObjectiveFunc, trial: Trial) -> TrialReport: template = trial.params if len(template.params) == 0: return func.run(trial) lock = RLock() best_report: List[TrialReport] = [] def obj(otrial: optuna.trial.Trial) -> float: params = template.fill_dict(_convert(otrial, template)) report = func.run(trial.with_params(params)) with lock: if len(best_report) == 0: best_report.append(report) elif report.sort_metric < best_report[0].sort_metric: best_report[0] = report return report.sort_metric study = self._create_study() study.optimize(obj, n_trials=self._max_iter) assert 1 == len(best_report) return best_report[0] def _convert( trial: optuna.trial.Trial, template: TuningParametersTemplate ) -> Dict[str, Any]: result: Dict[str, Any] = {} for k, v in template.params_dict.items(): if isinstance(v, RandInt): if v.log and v.q is not None: value = trial.suggest_float(name=k, low=0, high=1.0) result[k] = uniform_to_integers( value, low=v.low, high=v.high, q=v.q, # type: ignore log=True, include_high=v.include_high, ) else: _high: Any = v.high if v.include_high else v.high - 1 result[k] = trial.suggest_int( name=k, low=v.low, high=_high, step=v.q, log=v.log ) elif isinstance(v, Rand): if v.log and v.q is not None: value = trial.suggest_float(name=k, low=0, high=1.0) result[k] = uniform_to_discrete( value, low=v.low, high=v.high, q=v.q, log=True, include_high=v.include_high, ) else: _high = v.high if v.q is not None and not v.include_high: _high -= _IGNORABLE_ERROR result[k] = trial.suggest_float( name=k, low=v.low, high=_high, step=v.q, log=v.log ) elif isinstance(v, TransitionChoice): result[k] = v.values[ trial.suggest_int(name=k, low=0, high=len(v.values) - 1) ] elif isinstance(v, Choice): result[k] = trial.suggest_categorical(name=k, choices=v.values) else: # pragma: no cover raise NotImplementedError return result
''' Когда Павел учился в школе, он запоминал таблицу умножения прямоугольными блоками. Для тренировок ему бы очень пригодилась программа, которая показывала бы блок таблицы умножения. Напишите программу, на вход которой даются четыре числа a, b, c и d, каждое в своей строке. Программа должна вывести фрагмент таблицы умножения для всех чисел отрезка [a;b] на все числа отрезка [c;d]. Числа a, b, c и d являются натуральными и не превосходят 10, a≤b, c≤d. Следуйте формату вывода из примера, для разделения элементов внутри строки используйте '\t' — символ табуляции. Заметьте, что левым столбцом и верхней строкой выводятся сами числа из заданных отрезков — заголовочные столбец и строка таблицы. Sample Input 1: 7 10 5 6 Sample Output 1: 5 6 7 35 42 8 40 48 9 45 54 10 50 60 Sample Input 2: 5 5 6 6 Sample Output 2: 6 5 30 Sample Input 3: 1 3 2 4 Sample Output 3: 2 3 4 1 2 3 4 2 4 6 8 3 6 9 12 ''' a = int(input()) b = int(input()) c = int(input()) d = int(input()) print(end = '\t') for i in range(c, d+1): print(i, end='\t') print() for i in range(a, b+1): print(i, end='\t') for j in range(c, d+1): print(i*j, end = '\t') print()
obs_functions = [ # lambda x, v: math.pow(x, 2) / 20 + v, # lambda x, v: math.pow(x, 2) / 20 + v, # lambda x, v: math.pow(x, 2) / 20 + v lambda x, v: x / 2 + v, lambda x, v: x / 2 + v, lambda x, v: x / 2 + v ]
def rm(nums, con): for i in con: nums.remove(i) def check(nums, index, value, con): if index >= len(nums) or value < nums[index]: return False elif nums[index]==value: con.append(nums[index]) return True elif check(nums, index+1, value, con)==True: return True elif check(nums, index+1, value-nums[index], con)==True: con.append(nums[index]) return True else: return False def compute(div, nums, value): if div==0: return True con = [] if check(nums, 0, value, con)==False: return False print(con) rm(nums, con) return compute(div-1, nums, value) def f(div, nums): print(compute(div, nums, sum(nums)/div), '---') nums = [4,3,2,3,5,2,1] sorted_nums = sorted(nums, reverse=True) div = 4 f(div, nums)
### List lst = [1,2,"ram","tom",1.3,7+2j,True,"A"] #making a list (using square brackets) lst[2] # accessing a list element lst[2:] # accessing multiple list elements together lst[2]="rem" # updating an element cities = [[1,2,3],[5,[4,6,7],8],9] cities[1][1][1] #inherent index accessing # List methods lst.append(1) # add element at the last lst.insert(1,5) # add at element at a desires index (index, element) lst2 = [6,7,7,8,9] lst.extend(lst2) # adding a whole collection at the end lst+lst2 # adding a whole list at the end (only same type of collections can be concatenated) lst.remove("rem") # delete an element (if multiple then the first element index-wise get deleted) lst.pop() # pops out the last element lst.pop(2) # pops out the element at desired index lst.reverse() # reverses the list lst2.sort() # sorts the list lst2.sort(reverse=True) # sorts the list in reverse lst.clear() # clears the whole list lst = lst2.copy() # copying a list ### Tuple tup = (1,2,"ram","tom",1.3,7+2j,True,"A") #making a tuple (using brackets) tup[2] # accessing a tuple element tup[:-1] # accessing multiple tuple elements together # Tuple methods tup.index(2) #tell the index of an element tup.count("ram") #tell the count of the element ### Set (No Order) st1 = {1,2,"ram","tom",1.3,7+2j,True,"A"} #making a set (using curly brackets) st2 = {1,2,6,8,90,22} # Set Methods st1.add(7) # adds an element to any arbitrary position st2.difference(st1) # tells the difference (shows the elements of st2 which are not in st1) st1.union(st2) # mathematical union st1.intersection(st2) # mathematical intersection ### Dictionary dct = {"name":"akhil","college":"bvp","roll":"412"} #making a dictionary {"key":"value"} dct["name"] # accessing a value using the key dct["name"]="arjun" # updating a value dct["phone"]=19299349001 students = {"roll":[1,2,3,4],"name":["a","b","c","d"]} students["roll"][2] # Dictionary methods nam = dct.get("name") # gets the value using the key dct.keys() # gives us all the keys dct.values() # gives us all the values dct.items() # gives the key:value pair in tuple form dct.update({"address":"delhi"}) dct.pop("roll") # pops the item using key dct.popitem() # pops the whole dictionary dct.fromkeys(tup) # we can create a dictionary using the an collection and these will become the keys students.clear() # clears the dictionary for col,row in dct.items(): # looping thru the dict print(col,row) # Making a dictionary using zip method x = ["name","age","clg"] y = ["akhil","20","bvp"] newdct = dict(zip(x,y)) ## IF ELSE and ELIF per = int(input("Enter Your Percentage ")) if per >= 80: print("Grade A+") elif per < 80 and per >= 60: print("Grade A") elif per < 60 and per >= 40: print("Grade B") else: print("Fail") ## NESTED IF ELSE print("Write Y for Yes and N for No") lk = input("Battery Leakage? ") ch = input("Chargable? ") wt = input("Weight?(L or H) ") bckup = int(input("Enter Backup ")) if lk=="Y": print("Battery has leakage problem") else: if ch=="Y": if wt=="L": if bckup>7: print("Battery is best") else: print("Battery has leakage problem") else: print("Battery has weight problem") else: print("Battery is not chargable") ## Using range #range(n) #range(start, stop) #range(start, stop, diff) ## FOR LOOP #for iterator in iterable: # statements for i in range(1,11): print(i) ## NESTED FOR LOOP for i in range(1,11): for j in range(2,11): #print(i,"x",j,"=",i*j,end=' ') print("%4d" %(i*j),end=" ") print() ## WHILE LOOP #while cond: # statement # increment i=1 while i<=10: j=2 while j<=10: print("%4d" %(i*j),end=" ") j+=1 print() i+=1
from django.conf import settings from django.db import models from django.utils import timezone class job (models.Model): job_title = models.CharField('Заголовок', max_length=200) job_list = models.TextField('Текст') def __str__(self): return self.job_title class Meta: verbose_name = 'Описание' verbose_name_plural = 'Описание' class job_file(models.Model): job_file_title = models.CharField('Заголовок', max_length=200) job_file_files = models.FileField('файл', upload_to='uploads/', null=True) def __str__(self): return self.job_file_title class Meta: verbose_name = 'Вакансии' verbose_name_plural = 'Вакансии'
import scrapy #run file by 'scrapy crawl <name_of_the_spider> -o <output_file_name>.json' class EventSpider(scrapy.Spider): name = "event" #every spider needs a name def start_requests(self): url = "https://www.tapology.com/fightcenter/events/54138-ufc-fight-night-143" yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): for row in response.css(".fightCard .fightCardBout"): yield { "number": row.css("div.fightCardBoutNumber::text").extract_first(), "nameleft": row.css("div.fightCardFighterName.left a::text").extract_first(), "recordright": ''.join(row.css('div.fightCardFighterBout.right div.fightCardRecord::text').getall()).strip(), "recordleft": ''.join(row.css("div.fightCardFighterBout.left div.fightCardRecord::text").getall()).strip(), "nameright": row.css("div.fightCardFighterName.right a::text").extract_first() } #recordright is only grabbing the \n..... #''.join(row.css('div.fightCardFighterBout.right div.fightCardRecord::text').getall()).strip() #Resources #https://www.reddit.com/r/scrapy/comments/a5gs19/first_time_using_scrapy_cant_seem_to_scrape_mma/ebnmiv7/?context=3 #https://medium.com/@mottet.dev/scrapy-and-scrapyrt-how-to-create-your-own-api-from-almost-any-website-ecfb0058ad64
import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, make_response ) from flask_adventure_game.map import Map from flask_adventure_game.lexicon import scan bp = Blueprint('engine', __name__) @bp.route('/', methods=('GET', 'POST')) def game(): if (request.method == 'POST'): map = Map() command = scan(request.form['command']) location = request.cookies.get('current_room') if location == None: location = 'south_cell' if command['type'] == 'movement': destination = getattr(map, location).adjacent_rooms[command['detail']] if destination: resp = make_response(render_template('index.html', message=map.next_room(destination))) resp.set_cookie('current_room', destination) return resp elif command['type'] == 'error': text = command['detail'] return render_template('index.html', message=map.next_room(location), error=text) resp = make_response(render_template('index.html', message=map.next_room(location))) resp.set_cookie('current_room', location) return resp return render_template('index.html', message='Welcome to Dungeon Escape!\nPress submit to continue...') @bp.route('/reset', methods=['GET']) def reset(): resp = make_response(render_template('index.html', message='Welcome to Dungeon Escape!\nPress submit to continue...')) resp.set_cookie('current_room', 'south_cell') return resp
def format_number(s): new_s = '' for c in s: if c.isdigit() or c in (',', '.'): if c == ',': new_s += '.' else: new_s += c return new_s
# addition print "5+4=",5+4 # subtraction print "5-4=",5-4 # division print "5/4=",5/4 # multiplication print "5*4=",5*4 # modulo print "5%4=",5%4 # less than print "Is 5<4?",5<4 # greater than print "Is 5>4?",5>4 # less than or equal to print "Is 5<=4?",5<=4 # greater than or equal to print "Is 5>=4?",5>=4
""" Test atom.py Example feed: <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://example.org/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>John Doe</name> </author> <generator uri="/myblog.php" version="1.0"> Example Toolkit </generator> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://example.org/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed> """ from item import Item from website import Website from atom import Atom TEST_WEBSITE = Website('tests/config/test_magnetizer.cfg') TEST_WEBSITE.refresh() ATOM = Atom(TEST_WEBSITE) FEED = ATOM.feed(['004-invalid-article.md', '003-another-article.md', '002-article-with-h1-break-and-date.md', '001-basic-article.md', 'dont-index-this-article.md', '100-ignore-this.txt']) def test_feed(): """ Test to ensure Atom feed is correct """ # Should start with xml version assert FEED.startswith('<?xml version="1.0" encoding="utf-8"?>') # XML namespace should be Atom assert '<feed xmlns="http://www.w3.org/2005/Atom">' in FEED # Title should be website name - tagline (amps must be escaped) assert '<title>Test website name - test tag &amp; line</title>' in FEED # Author should be site author assert '<author><name>Test Author</name></author>' in FEED # Generator should be Magnetizer assert ('<generator uri="https://github.com/magnusdahlgren/magnetizer">' + 'Magnetizer</generator>') in FEED # Id should be site URL assert '<id>https://example.com/</id>' in FEED # Updated should be when the latest post was updated assert '<updated>1998-08-02T00:00:02Z</updated>' in FEED # Feed should have 3 entries assert FEED.count('<entry>') == 3 # Feed tag should be closed assert FEED.endswith('</feed>') def test_feed_entry(): """ Test to ensure Atom entry is correct """ item = Item(TEST_WEBSITE) item.from_md_filename('002-article-with-h1-break-and-date.md') entry = item.feed_entry() # Entry should be nested in <entry></entry> assert entry.startswith('<entry>') assert entry.endswith('</entry>') # Title should be article title assert '<title>This should be the title - Test website name</title>' in entry # Link and id should both be full article URL assert '<link href="https://example.com/article-with-h1-break-and-date.html"/>' in entry assert '<id>https://example.com/article-with-h1-break-and-date.html</id>' in entry # Updated should be date of the article assert '<updated>1998-08-01T00:00:01Z</updated>' in entry # Summary should be article abstract (amps must be escaped) assert ("<summary>This text should always be here Don't show this bit on " + "the index page</summary>") in entry def test_write_feed_from_directory(): """ Test to ensure Atom feed is correct when generated from files in a directory """ TEST_WEBSITE.wipe() atom = Atom(TEST_WEBSITE) atom.write() with open(TEST_WEBSITE.config.value('output_path') + 'atom.xml', 'r') as myfile: feed = myfile.read() # Feed should be atom feed assert '<feed xmlns="http://www.w3.org/2005/Atom">' in feed # Feed should contain a number of articles assert feed.count('<entry>') >= 3 TEST_WEBSITE.wipe()
#-----------------------------------------------------METHOD 1--------------------------------------------------------------------# def height(root): if not root: return 0 return 1 + max(height(root.left),height(root.right)) def printLeftView(root,level,flag): if root and not flag[0]: if level==0: if flag[0] == False: print(root.data,end=" ") flag[0] = True printLeftView(root.left,level-1,flag) printLeftView(root.right,level-1,flag) def LeftView(root): h = height(root) for i in range(h): flag = [False] printLeftView(root,i,flag) #-----------------------------------------------------METHOD 2--------------------------------------------------------------------# def printLeftView(root,level,d): if root: d[level] = root.data printLeftView(root.right,level+1,d) printLeftView(root.left,level+1,d) def LeftView(root): d = dict() printLeftView(root,0,d) for i in d.values(): print(i,end=" ")
#Ch.2: Challenge 2 # Favorite foods program def fav_food(): fav_food1 = input("Enter your favorite food: ") fav_food2 = input("Enter your second favorite food: ") combined = fav_food1 + fav_food2 print("\nYour favorite foods combined equals", combined.replace(" ", "")) fav_food()
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html from datetime import datetime from scrapy.item import Field from scrapy.item import Item from scrapy.loader.processors import MapCompose from scrapy.loader.processors import TakeFirst def remove_quotes(text): # strip the unicode quotes text = text.strip(u"\u201c" u"\u201d") return text def convert_date(text): # convert string March 14, 1879 to Python date return datetime.strptime(text, "%B %d, %Y") def parse_location(text): # parse location "in Ulm, Germany" # this simply remove "in ", you can further parse city, state, country, etc. return text[3:] # class QuoteItem(Item): # quote_content = Field( # input_processor=MapCompose(remove_quotes), # # TakeFirst return the first value not the whole list # output_processor=TakeFirst() # ) # author_name = Field( # input_processor=MapCompose(str.strip), # output_processor=TakeFirst() # ) # author_birthday = Field( # input_processor=MapCompose(convert_date), # output_processor=TakeFirst() # ) # author_bornlocation = Field( # input_processor=MapCompose(parse_location), # output_processor=TakeFirst() # ) # author_bio = Field( # input_processor=MapCompose(str.strip), # output_processor=TakeFirst() # ) # tags = Field() class CarSparePart(Item): _id = Field() ad_id = Field() image = Field() category_name = Field() category_id = Field() images_count = Field() is_boost = Field() is_top = Field() paid_info = Field() price = Field() price_obj = Field() region_name = Field() region_slug = Field() short_description = Field() title = Field() api_url = Field() web_url = Field() user_id = Field() user_phone = Field() tops_count = Field() attributes = Field() badge_info = Field() booster_info = Field() count_views = Field() date_created = Field() date_edited = Field() date_moderated = Field() fav_count = Field() description = Field() images = Field() images_data = Field() is_active = Field() is_closed = Field() is_request_seller_to_call_back_show = Field() price_history = Field() services_info = Field() similar_ads_href = Field() status_color = Field() status = Field() seller = Field() og_title = Field() og_url = Field() og_product_data = Field() breadcrumbs_data = Field() crawled_at = Field() price_currency = Field()
import unittest from my_dict import Dict class TestDict(unittest.TestCase): def test_init(self): d = Dict(a = 1,b = 'test') self.assertEqual(d.a,1) self.assertEqual(d.b,'test') self.assertTrue(isinstance(d,dict)) def test_key(self): d = Dict() d['hong'] = 1 self.assertEqual(d.hong,1) def test_attr(self): d = Dict() d.fox = 'fox' self.assertEqual(d['fox'],'fox') def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): value = d['none'] with self.assertRaises(AttributeError): value = d.none
from sanic.response import json, text from sanic import Blueprint bp_cookie = Blueprint('cookie_blueprint', url_prefix='/cookie') @bp_cookie.route('/') async def bp_root(request): return json({'Bluprint': 'cookie'}) @bp_cookie.route('/set') async def set_cookie(request): response = text("There's a cookie up in this response") response.cookies['test'] = 'It worked!' response.cookies['test']['domain'] = '.gotta-go-fast.com' response.cookies['test']['httponly'] = True return response @bp_cookie.route('/get') async def get_cookie(request): test_cookie = request.cookies.get('test') return text("Test cookie set to: {}".format(test_cookie)) from sanic.views import HTTPMethodView class CookieView(HTTPMethodView): async def get(self, request): return text('This is async get method.') def post(self, request): pass bp_cookie.add_route(CookieView.as_view(), '/cls')
#MenuTitle: 擴大選取範圍到完整外框 # -*- coding: utf-8 -*- # # (c) But Ko, 2021. # https://zi-hi.com/ # https://github.com/ButTaiwan/GlyphsTools # https://www.facebook.com/groups/glyphszhtw # from GlyphsApp import Glyphs if Glyphs.font.selectedLayers is not None and len(Glyphs.font.selectedLayers) == 1: layer = Glyphs.font.selectedLayers[0] nodes = [obj for obj in layer.selection if type(obj)==GSNode] for n in nodes: path = n.parent path.selected = True
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 21:12:57 2018 @author: praveen kumar """ #Grid search # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('C:/Users/praveen/Desktop/machine-learning udemy a-z/Machine Learning A-Z Template Folder/Part 3 - Classification/Section 14 - Logistic Regression/Logistic_Regression/Social_Network_Ads.csv') X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 4].values # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting svm to the Training set #Here in kernel only rbf is better option among linear,poly,sigmoid because rbf having better accuracy than that on from sklearn.svm import SVC classifier=SVC(kernel='rbf',random_state=0) classifier.fit(X_train,y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #Applying k-fold cross validation from sklearn.cross_validation import cross_val_score accurecies=cross_val_score(estimator=classifier,X=X_train,y=y_train,cv=10) accurecies.mean() accurecies.std() #Applying grid search #It gives idea about which model we should prefer for given data set with high accurecy from sklearn.model_selection import GridSearchCV parameters = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']}, {'C': [1, 10, 100, 1000], 'kernel': ['rbf'], 'gamma': [0.7, 0.72, 0.74, 0.76, 0.78, 0.8, 0.82, 0.84, 0.86]}] grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 10, n_jobs = -1) grid_search = grid_search.fit(X_train, y_train) best_accuracy = grid_search.best_score_ best_parameters = grid_search.best_params_ # Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('SVM (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('SVM (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
import logging logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) class PanCalculator: def __init__(self, fov, image_width): self.__fov = fov self.__image_width = image_width self.__gradient = (fov / float(image_width)) self.__camera_x = image_width / 2.0 logging.info("image width is : {} gradient is: {}".format(image_width, self.__gradient)) # in python3 division of int by another int returns a float # in python def calculate_pan_angle(self, target_x_position): pan_angle = (target_x_position - self.__camera_x) * self.__gradient * 0.2 * -1.0 logging.info("the calculated pan angle for {} is {}".format(target_x_position - self.__camera_x, pan_angle)) return pan_angle
import re import numpy as np import sys TIME_UNIT = 1e-06 FILE_SIZE = 1024 PATTERN = '[1-9][0-9]+' with open(sys.argv[1], 'r') as f: # first line is the thread number s = f.readline() thread_num = int(s) # every thread_num lines we find a maximum second count = 0 total_arr = [] tmp_ls = [] for line in f: tmp_ls.append(line) count += 1 if count == thread_num: s = ' '.join(tmp_ls) total_arr.append(max(list(map(int, re.findall(PATTERN, s))))) # reset the counter tmp_ls = [] count = 0 # calculate throughput for this thread_num time_arr = np.asarray(total_arr, dtype=np.float32) * TIME_UNIT result_arr = np.ones(time_arr.size) * FILE_SIZE * thread_num result_arr = result_arr / time_arr print('min: {}, median: {}, max: {}, std: {}'.format(np.min(result_arr), np.median(result_arr), np.max(result_arr), np.std(result_arr))) np.save(sys.argv[2], result_arr)
N = int(input()) answer_list = [input() for _ in range(N)] my_set = set(answer_list) answer_list = list(my_set) answer_list.sort() # 사전순 정렬 answer_list.sort(key=lambda x: len(x)) for i in answer_list: print(i, end='\n')
k= 0 #Coefficient de raideur du ressort l0= 0 #Longueur a vide m= 0 #Masse d'une maille dt= 0.01 class Vec3f: def __init__(self): self.x = 0 self.y = 0 self.z = 0 def dot_product(self, vec): return self.x*vec.x + self.y*vec.y + self.z*vec.z def cross_product(self, vec): ret = Vec3f() ret.x = self.y*vec.z-vec.y*self.z ret.y = self.z*vec.x-vec.z*self.x ret.z = self.x*vec.y-vec.x*self.y return ret def add(self, vec): ret = Vec3f() ret.x, ret.y, ret.z = self.x + vec.x, self.y + vec.y, self.z + vec.z return ret def mult(self , scal): self.x *= scal # a*=l <=> a = a * l marche aussi avec | & && || << >> < > ! % + - / // ** self.y *= scal self.z *= scal class Node: def __init__(self, pos): self.pos = pos self.velocity = Vec3f(); self.mass = m self.neigbhour = [] #other vars #here are the definitions of local Node parameters aka (mass, velocity, position, and such ...) def iterate(nd_lst): #nd_lst stand for Node[] #differential equation # ....... good luck for i in range(len(nd_lst)): for j in range(len(nd_lst[i].neigbhour)): nd_lst[i].velocity = nd_lst[i].velocity.add(nd_lst[i].position.mult(-1)).add(nd_list[nd_list[i].neigbhour[j]].position).add(l0*(nd_lst[i].position.mult(-1)).add(nd_list[nd_list[i].neigbhour[j]].position)/((nd_lst[i].position.mult(-1)).add(nd_list[nd_list[i].neigbhour[j]].position).lenght())).mult((dt/m)*k) nd_lst[i].position = nd_lst[i].position.add(nd_lst[i].velocity.mult(dt)) return nd_lst def surfacegrid(length,width,precision): nd_lst = [] for i in range(0, lenght): for j in range(0,width): nd_lst.append(Node(Vec3f(i*precision, j*precision, 0)) ) return nd_lst #a executer pour beaucoup de pt de la liste def impact(p,force): nd_list[p].velocity += dt*force/nd_list[p].mass vb += - dt*force/mb #modéliser l'impact de la balle sur le maillage et appliquer les modifications que subit le tissu def finalmod(p,q,vb,mb,length,width,precision,k,l0,m,dt): grid=surfacegrid(length,width,precision) #à partir des conditions initiales, présenter le modèle et ça déformation (si possible intégrer images)
from django import forms from django.core.exceptions import ValidationError from django.db.models import fields from .models import * from django.utils.translation import ugettext_lazy as _ class ArticleForm(forms.ModelForm): class Meta: model = blogs fields = "__all__" class SignupForm(forms.ModelForm): class Meta: model = User fields = "__all__" password = forms.PasswordInput() def clean_email(self): email = self.cleaned_data.get("email") db_email = User.objects.filter(email__iexact=email) if db_email: raise ValidationError("Email already exist") return email def clean_password(self): password = self.cleaned_data.get("password") if len(password) < 8: raise ValidationError("Length of password is less than 8") if password.isalpha(): raise ValidationError("Password should contains both letters and numbers") if password.isnumeric(): raise ValidationError("Password should contains both letters and numbers") return password class LoginForm(forms.Form): email = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(),max_length=20) class password_resetForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput(),max_length=20) password2 = forms.CharField(widget=forms.PasswordInput(),max_length=20) def clean(self): cleaned_data = super(password_resetForm, self).clean() password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") print(password, password2) if len(password) < 8: raise forms.ValidationError({"password":"Length of password is less than 8"}) if password.isalpha(): raise ValidationError({"password":"Password should contains both letters and numbers"}) if password.isnumeric(): raise ValidationError({"password":"Password should contains both letters and numbers"}) if password != password2: raise ValidationError({"password":"Password must match"}) return cleaned_data class ResetForms(forms.Form): email = forms.EmailField() class NewPasswordResetForm(forms.Form): password1 = forms.CharField(widget=forms.PasswordInput()) password2 = forms.CharField(widget=forms.PasswordInput()) def clean(self): cleaned_data = super(password_resetForm, self).clean() password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") print(password, password2) if len(password) < 8: raise ValidationError("Length of password is less than 8") if password.isalpha(): raise ValidationError("Password should contains both letters and numbers") if password.isnumeric(): raise ValidationError("Password should contains both letters and numbers") if password != password2: raise ValidationError(_("Password must match")) return cleaned_data
"""Flower: Celery monitoring and management app Usage: celery-flower.py [options] Options: -h --help Show this screen. """ from web_backend.server import IUBackendService from web_backend.server import ConfigParser from web_backend.server import CONFIG_FILE as SERVER_CONFIG_FILE from docopt import docopt from flower.command import FlowerCommand import flower.options as options FLOWER_CONFIG_FILE = '/etc/celery-flower.conf' def main(): args = docopt(__doc__) app_options = ConfigParser.parse_config_file(SERVER_CONFIG_FILE) application = IUBackendService(app_options) application.connect() options.port = 8888 try: flower = FlowerCommand(app=application.celery_app) flower.app = application.celery_app flower.execute_from_commandline() except: import sys print(bugreport(app=flower.app), file=sys.stderr) raise if __name__ == "__main__": main()
import pandas as pd import numpy as np data = { 'group': np.random.randint(1,5,(100,)), 'actual': np.random.random((100,)), 'predict': np.random.random((100,)), } # np.random.random((20,)) # np.random.randint(1,5,(20,)) df = pd.DataFrame(data) df = df.sort_values(["group", "predict"], ascending=[True, True]).reset_index(drop=True) ascending = True df["rank"] = df.groupby("group")["actual"].rank(ascending=ascending, pct=True) k = 10 rdf = df.groupby("group").head(k).groupby("group")[["actual", "rank"]].mean() rdf rdf["random"] = np.array(df.groupby("group")["actual"].mean()) rdf rdf.reset_index(inplace=True) rdf
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'schedular.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(619, 422) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName("gridLayout_2") self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setObjectName("gridLayout") self.tableWidget = QtWidgets.QTabWidget(self.centralwidget) self.tableWidget.setObjectName("tableWidget") self.fcfs = QtWidgets.QWidget() self.fcfs.setObjectName("fcfs") self.gridLayout_5 = QtWidgets.QGridLayout(self.fcfs) self.gridLayout_5.setObjectName("gridLayout_5") self.lineEdit_2 = QtWidgets.QLineEdit(self.fcfs) self.lineEdit_2.setObjectName("lineEdit_2") self.gridLayout_5.addWidget(self.lineEdit_2, 5, 0, 1, 1) self.tableWidgetfcfs = QtWidgets.QTableWidget(self.fcfs) self.tableWidgetfcfs.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents) self.tableWidgetfcfs.setAlternatingRowColors(False) self.tableWidgetfcfs.setObjectName("tableWidgetfcfs") self.tableWidgetfcfs.setColumnCount(2) self.tableWidgetfcfs.setRowCount(2) item = QtWidgets.QTableWidgetItem() self.tableWidgetfcfs.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetfcfs.setVerticalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetfcfs.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetfcfs.setHorizontalHeaderItem(1, item) self.gridLayout_5.addWidget(self.tableWidgetfcfs, 2, 0, 1, 2) self.label = QtWidgets.QLabel(self.fcfs) self.label.setObjectName("label") self.gridLayout_5.addWidget(self.label, 0, 0, 1, 1) self.label_2 = QtWidgets.QLabel(self.fcfs) self.label_2.setObjectName("label_2") self.gridLayout_5.addWidget(self.label_2, 4, 0, 1, 1) self.lineEditfcfs = QtWidgets.QLineEdit(self.fcfs) self.lineEditfcfs.setObjectName("lineEditfcfs") self.gridLayout_5.addWidget(self.lineEditfcfs, 1, 0, 1, 2) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.pushButton_10 = QtWidgets.QPushButton(self.fcfs) self.pushButton_10.setObjectName("pushButton_10") self.horizontalLayout.addWidget(self.pushButton_10) self.push_Buttonclear = QtWidgets.QPushButton(self.fcfs) self.push_Buttonclear.setObjectName("push_Buttonclear") self.horizontalLayout.addWidget(self.push_Buttonclear) self.gridLayout_5.addLayout(self.horizontalLayout, 5, 1, 1, 1) self.tableWidget.addTab(self.fcfs, "") self.sif = QtWidgets.QWidget() self.sif.setObjectName("sif") self.gridLayout_6 = QtWidgets.QGridLayout(self.sif) self.gridLayout_6.setObjectName("gridLayout_6") self.lineEditsjf = QtWidgets.QLineEdit(self.sif) self.lineEditsjf.setObjectName("lineEditsjf") self.gridLayout_6.addWidget(self.lineEditsjf, 1, 0, 1, 1) self.tableWidgetsjf = QtWidgets.QTableWidget(self.sif) self.tableWidgetsjf.setObjectName("tableWidgetsjf") self.tableWidgetsjf.setColumnCount(2) self.tableWidgetsjf.setRowCount(2) item = QtWidgets.QTableWidgetItem() self.tableWidgetsjf.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetsjf.setVerticalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetsjf.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetsjf.setHorizontalHeaderItem(1, item) self.gridLayout_6.addWidget(self.tableWidgetsjf, 2, 0, 1, 2) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.pushButton_4 = QtWidgets.QPushButton(self.sif) self.pushButton_4.setObjectName("pushButton_4") self.horizontalLayout_2.addWidget(self.pushButton_4) self.push_Buttonclear1 = QtWidgets.QPushButton(self.sif) self.push_Buttonclear1.setObjectName("push_Buttonclear1") self.horizontalLayout_2.addWidget(self.push_Buttonclear1) self.gridLayout_6.addLayout(self.horizontalLayout_2, 4, 1, 1, 1) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.radioButton = QtWidgets.QRadioButton(self.sif) self.radioButton.setObjectName("radioButton") self.horizontalLayout_3.addWidget(self.radioButton) self.radioButton_2 = QtWidgets.QRadioButton(self.sif) self.radioButton_2.setObjectName("radioButton_2") self.horizontalLayout_3.addWidget(self.radioButton_2) self.gridLayout_6.addLayout(self.horizontalLayout_3, 0, 1, 2, 1) self.lineEdit_4 = QtWidgets.QLineEdit(self.sif) self.lineEdit_4.setObjectName("lineEdit_4") self.gridLayout_6.addWidget(self.lineEdit_4, 4, 0, 1, 1) self.label_3 = QtWidgets.QLabel(self.sif) self.label_3.setObjectName("label_3") self.gridLayout_6.addWidget(self.label_3, 0, 0, 1, 1) self.label_4 = QtWidgets.QLabel(self.sif) self.label_4.setObjectName("label_4") self.gridLayout_6.addWidget(self.label_4, 3, 0, 1, 1) self.tableWidget.addTab(self.sif, "") self.roundroubin = QtWidgets.QWidget() self.roundroubin.setObjectName("roundroubin") self.gridLayout_9 = QtWidgets.QGridLayout(self.roundroubin) self.gridLayout_9.setObjectName("gridLayout_9") self.label_6 = QtWidgets.QLabel(self.roundroubin) self.label_6.setObjectName("label_6") self.gridLayout_9.addWidget(self.label_6, 3, 0, 1, 1) self.lineEdit_6 = QtWidgets.QLineEdit(self.roundroubin) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(30) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEdit_6.sizePolicy().hasHeightForWidth()) self.lineEdit_6.setSizePolicy(sizePolicy) self.lineEdit_6.setMinimumSize(QtCore.QSize(30, 0)) self.lineEdit_6.setObjectName("lineEdit_6") self.gridLayout_9.addWidget(self.lineEdit_6, 4, 0, 1, 1) self.tableWidgetrr = QtWidgets.QTableWidget(self.roundroubin) self.tableWidgetrr.setObjectName("tableWidgetrr") self.tableWidgetrr.setColumnCount(2) self.tableWidgetrr.setRowCount(2) item = QtWidgets.QTableWidgetItem() self.tableWidgetrr.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetrr.setVerticalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetrr.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetrr.setHorizontalHeaderItem(1, item) self.gridLayout_9.addWidget(self.tableWidgetrr, 2, 0, 1, 3) self.gridLayout_3 = QtWidgets.QGridLayout() self.gridLayout_3.setObjectName("gridLayout_3") self.pushButton_5 = QtWidgets.QPushButton(self.roundroubin) self.pushButton_5.setObjectName("pushButton_5") self.gridLayout_3.addWidget(self.pushButton_5, 0, 0, 1, 1) self.push_Buttonclear2 = QtWidgets.QPushButton(self.roundroubin) self.push_Buttonclear2.setObjectName("push_Buttonclear2") self.gridLayout_3.addWidget(self.push_Buttonclear2, 0, 1, 1, 1) self.gridLayout_9.addLayout(self.gridLayout_3, 4, 1, 1, 2) self.label_5 = QtWidgets.QLabel(self.roundroubin) self.label_5.setObjectName("label_5") self.gridLayout_9.addWidget(self.label_5, 0, 0, 1, 1) self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.label_7 = QtWidgets.QLabel(self.roundroubin) self.label_7.setObjectName("label_7") self.horizontalLayout_4.addWidget(self.label_7) self.lineEdit_7 = QtWidgets.QLineEdit(self.roundroubin) self.lineEdit_7.setObjectName("lineEdit_7") self.horizontalLayout_4.addWidget(self.lineEdit_7) self.gridLayout_9.addLayout(self.horizontalLayout_4, 1, 2, 1, 1) self.lineEditrr = QtWidgets.QLineEdit(self.roundroubin) self.lineEditrr.setObjectName("lineEditrr") self.gridLayout_9.addWidget(self.lineEditrr, 1, 0, 1, 2) self.tableWidget.addTab(self.roundroubin, "") self.priority = QtWidgets.QWidget() self.priority.setObjectName("priority") self.gridLayout_7 = QtWidgets.QGridLayout(self.priority) self.gridLayout_7.setObjectName("gridLayout_7") self.lineEditper = QtWidgets.QLineEdit(self.priority) self.lineEditper.setObjectName("lineEditper") self.gridLayout_7.addWidget(self.lineEditper, 1, 0, 1, 1) self.label_8 = QtWidgets.QLabel(self.priority) self.label_8.setObjectName("label_8") self.gridLayout_7.addWidget(self.label_8, 0, 0, 1, 1) self.horizontalLayout_7 = QtWidgets.QHBoxLayout() self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.radioButton_3 = QtWidgets.QRadioButton(self.priority) self.radioButton_3.setObjectName("radioButton_3") self.horizontalLayout_7.addWidget(self.radioButton_3) self.radioButton_4 = QtWidgets.QRadioButton(self.priority) self.radioButton_4.setObjectName("radioButton_4") self.horizontalLayout_7.addWidget(self.radioButton_4) self.gridLayout_7.addLayout(self.horizontalLayout_7, 0, 1, 2, 1) self.tableWidgetper = QtWidgets.QTableWidget(self.priority) self.tableWidgetper.setObjectName("tableWidgetper") self.tableWidgetper.setColumnCount(3) self.tableWidgetper.setRowCount(2) item = QtWidgets.QTableWidgetItem() self.tableWidgetper.setVerticalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetper.setVerticalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetper.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetper.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tableWidgetper.setHorizontalHeaderItem(2, item) self.gridLayout_7.addWidget(self.tableWidgetper, 2, 0, 1, 2) self.label_9 = QtWidgets.QLabel(self.priority) self.label_9.setObjectName("label_9") self.gridLayout_7.addWidget(self.label_9, 3, 0, 1, 1) self.horizontalLayout_6 = QtWidgets.QHBoxLayout() self.horizontalLayout_6.setObjectName("horizontalLayout_6") self.pushButton_7 = QtWidgets.QPushButton(self.priority) self.pushButton_7.setObjectName("pushButton_7") self.horizontalLayout_6.addWidget(self.pushButton_7) self.push_Buttonclear3 = QtWidgets.QPushButton(self.priority) self.push_Buttonclear3.setObjectName("push_Buttonclear3") self.horizontalLayout_6.addWidget(self.push_Buttonclear3) self.gridLayout_7.addLayout(self.horizontalLayout_6, 4, 1, 1, 1) self.lineEdit_9 = QtWidgets.QLineEdit(self.priority) self.lineEdit_9.setObjectName("lineEdit_9") self.gridLayout_7.addWidget(self.lineEdit_9, 4, 0, 1, 1) self.tableWidget.addTab(self.priority, "") self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 619, 26)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.tableWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.tableWidgetfcfs.setToolTip(_translate("MainWindow", "<html><head/><body><p>table</p></body></html>")) item = self.tableWidgetfcfs.verticalHeaderItem(0) item.setText(_translate("MainWindow", "1")) item = self.tableWidgetfcfs.verticalHeaderItem(1) item.setText(_translate("MainWindow", "2")) item = self.tableWidgetfcfs.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "Arrival time")) item = self.tableWidgetfcfs.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "Burst time")) self.label.setText(_translate("MainWindow", "Enter nomber of process")) self.label_2.setText(_translate("MainWindow", "Average waiting time")) self.pushButton_10.setText(_translate("MainWindow", "submit")) self.push_Buttonclear.setText(_translate("MainWindow", "clear")) self.tableWidget.setTabText(self.tableWidget.indexOf(self.fcfs), _translate("MainWindow", "FCFS")) self.tableWidgetsjf.setToolTip(_translate("MainWindow", "<html><head/><body><p>table</p></body></html>")) item = self.tableWidgetsjf.verticalHeaderItem(0) item.setText(_translate("MainWindow", "1")) item = self.tableWidgetsjf.verticalHeaderItem(1) item.setText(_translate("MainWindow", "2")) item = self.tableWidgetsjf.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "Arrival time")) item = self.tableWidgetsjf.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "Burst time")) self.pushButton_4.setText(_translate("MainWindow", "submit")) self.push_Buttonclear1.setText(_translate("MainWindow", "clear")) self.radioButton.setText(_translate("MainWindow", "Premetive")) self.radioButton_2.setText(_translate("MainWindow", "Non-Perimitive")) self.label_3.setText(_translate("MainWindow", "Enter nomber of process")) self.label_4.setText(_translate("MainWindow", "Average waiting time")) self.tableWidget.setTabText(self.tableWidget.indexOf(self.sif), _translate("MainWindow", "SJF")) self.label_6.setText(_translate("MainWindow", "Average waiting time")) self.tableWidgetrr.setToolTip(_translate("MainWindow", "<html><head/><body><p>table</p></body></html>")) item = self.tableWidgetrr.verticalHeaderItem(0) item.setText(_translate("MainWindow", "1")) item = self.tableWidgetrr.verticalHeaderItem(1) item.setText(_translate("MainWindow", "2")) item = self.tableWidgetrr.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "Arrival time")) item = self.tableWidgetrr.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "Burst time")) self.pushButton_5.setText(_translate("MainWindow", "submit")) self.push_Buttonclear2.setText(_translate("MainWindow", "clear")) self.label_5.setText(_translate("MainWindow", "Enter nomber of process")) self.label_7.setText(_translate("MainWindow", "Quatum")) self.tableWidget.setTabText(self.tableWidget.indexOf(self.roundroubin), _translate("MainWindow", "Round Robin")) self.label_8.setText(_translate("MainWindow", "Enter nomber of process")) self.radioButton_3.setText(_translate("MainWindow", "Premetive")) self.radioButton_4.setText(_translate("MainWindow", "Non-Perimitive")) self.tableWidgetper.setToolTip(_translate("MainWindow", "<html><head/><body><p>table</p></body></html>")) item = self.tableWidgetper.verticalHeaderItem(0) item.setText(_translate("MainWindow", "1")) item = self.tableWidgetper.verticalHeaderItem(1) item.setText(_translate("MainWindow", "2")) item = self.tableWidgetper.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "Arrival time")) item = self.tableWidgetper.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "Burst time")) item = self.tableWidgetper.horizontalHeaderItem(2) item.setText(_translate("MainWindow", "Piority")) self.label_9.setText(_translate("MainWindow", "Average waiting time")) self.pushButton_7.setText(_translate("MainWindow", "submit")) self.push_Buttonclear3.setText(_translate("MainWindow", "clear")) self.tableWidget.setTabText(self.tableWidget.indexOf(self.priority), _translate("MainWindow", "Priority")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
class state(): name = "" transition = [] def __init__(self, name): self.name = name self.transition = [] def setTransition(self, transition): self.transition.append(transition) class transition(): end = "" events = [] def __init__(self, end): self.end = end def addEvent(self, event): self.events.append(event) class event(): transition = "" variable = "" value = 0 def __init__(self,transition, variable, value): self.transition = transition self.variable = variable self.value = value class variable(): name = "" value = 0 min_value = 0 max_value = 0 def __init__(self,name, min, max): self.name = name self.min_value = min self.max_value = max def increase(self): if self.value < self.max_value: self.value += 1 def decrease(self): if self.value > self.min_value: self.value -= 1 def setVariable(self, value): if self.value > self.min_value and self.value < self.max_value: self.value = value class machine(): current_count = -1 list_state = [] list_var = [] name = "" state = state("") def name(self, name ): self.name = name return self def state_add(self, name): newState = state(name) self.list_state.append(newState) if self.state.name == "": self.state = newState self.current_count += 1 return self def transition(self, end): newTransition = transition(end) self.list_state[self.current_count].setTransition(newTransition) return self def variable(self, name, min, max): newVar = variable(name,min,max) self.list_var.append(newVar) return self def addEvent(self,transition, variable, value): index = (len(self.state.transition) -1) newEvent = event(transition,variable,value) self.state.transition[index].addEvent(newEvent) return self def execute(self,execute_list): for i in range(len(execute_list)): for j in self.list_state: if execute_list[i] == j.name: self.changestate(j) break for k in self.list_var: if execute_list[i].lower() == k.name.lower(): if execute_list[i+1].lower() == "up": print("Variable " + k.name + " changed from " + str(k.value) + " to " + str(k.value + 1)) k.increase() elif execute_list[i+1].lower() == "down": print("Variable " + k.name + " changed from " + str(k.value) + " to " + str(k.value - 1)) k.decrease() i += 1 break return self def changestate(self, new_state): for i in self.state.transition: if i.end.lower() == new_state.name.lower(): print("Transition from " + self.state.name + " to " + new_state.name) for event in i.events: if event.transition == i.end: for v in self.list_var: if v.name == event.variable: print("Variable " + v.name + " changed from " + str(v.value) + " to " + str(event.value)) v.setVariable(event.value) self.state = new_state class interperter(): stm = 0 def __init__(self, statemachine): self.stm = statemachine def print(self): print(self.stm.name) print("Current state: " + self.stm.state.name) for v in self.stm.list_var: print("Variable " + v.name + " Min: " + str(v.min_value) + " Max: " + str(v.max_value) + " Value: " + str( v.value)) for i in self.stm.list_state: print("State: " + i.name) for j in i.transition: print("Transition: " + i.name + " " + j.end) class querybuilder(): query = [] def changeStateTo(self, name): self.query.append(name) return self def incrementVariable(self, var): self.query.append(var) self.query.append("up") return self def decrementVariable(self, var): self.query.append(var) self.query.append("down") return self def print(self): return self.query TV = machine() { TV.name("TV"). variable("Volume",0,100). variable("Channel",0,100). state_add("ON"). transition("OFF"). addEvent("OFF","Volume", 0). addEvent("OFF","Channel", 0). state_add("OFF"). transition("ON") } print(TV.name) print(interperter(TV).print()) print("") TV.execute(querybuilder().changeStateTo("OFF").changeStateTo("ON").incrementVariable("Volume").query) print("") print(interperter(TV).print())
# -*- coding: utf-8 -*- import json undefined = object() class JSONFormEncoder(json.JSONEncoder): def default(self, obj): if obj == undefined: return None else: return super(JSONFormEncoder, self).default(obj) def parse_path(path): """ http://www.w3.org/TR/2014/WD-html-json-forms-20140529/#dfn-steps-to-parse-a-json-encoding-path """ original = path failure = [(original, {'last': True, 'type': object})] steps = [] try: first_key = path[:path.index("[")] if not first_key: return original steps.append((first_key, {'type': 'object'})) path = path[path.index("["):] except ValueError: return failure while path: if path.startswith("[]"): steps[-1][1]['append'] = True path = path[2:] if path: return failure elif path[0] == "[": path = path[1:] try: key = path[:path.index("]")] path = path[path.index("]")+1:] except ValueError: return failure try: steps.append((int(key), {'type': 'array'})) except ValueError: steps.append((key, {'type': 'object'})) else: return failure for i in range(len(steps)-1): steps[i][1]['type'] = steps[i+1][1]['type'] steps[-1][1]['last'] = True return steps def set_value(context, step, current_value, entry_value): """ http://www.w3.org/TR/2014/WD-html-json-forms-20140529/#dfn-steps-to-set-a-json-encoding-value """ key, flags = step if flags.get('last', False): if current_value == undefined: if flags.get('append', False): context[key] = [entry_value] else: if isinstance(context, list) and len(context) <= key: context.extend([undefined] * (key - len(context) + 1)) context[key] = entry_value elif isinstance(current_value, list): context[key].append(entry_value) elif isinstance(current_value, dict): set_value( current_value, ("", {'last': True}), current_value.get("", undefined), entry_value) else: context[key] = [current_value, entry_value] return context else: if current_value == undefined: if flags.get('type') == 'array': context[key] = [] else: if isinstance(context, list) and len(context) <= key: context.extend([undefined] * (key - len(context) + 1)) context[key] = {} return context[key] elif isinstance(current_value, dict): return context[key] elif isinstance(current_value, list): if flags.get('type') == 'array': return current_value else: obj = {} for i, item in enumerate(current_value): if item != undefined: obj[i] = item else: context[key] = obj return obj else: obj = {"": current_value} context[key] = obj return obj def encode(pairs): """ The application/json form encoding algorithm. http://www.w3.org/TR/2014/WD-html-json-forms-20140529/#the-application-json-encoding-algorithm """ result = {} for key, value in pairs: steps = parse_path(key) context = result for step in steps: try: current_value = context.get(step[0], undefined) except AttributeError: try: current_value = context[step[0]] except IndexError: current_value = undefined context = set_value(context, step, current_value, value) return result
"""This file contains 2 functions to multiprocessor analysis""" from myfunction import * from netCDF4 import Dataset import urlparse import csv import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from matplotlib.patches import Polygon as po from matplotlib.collections import PatchCollection from shutil import copyfile def workerUrl(username,url): """This method analyzes which point of online netCDF belong to polygon or not; then it create a csv file where it storage every info""" print("------------------------------------------------------------------------------------") print("Analysis online netCDF file") count = 0 managedb = ManageDB() mytool = MyTools() pre, ext = os.path.splitext(os.path.basename(urlparse.urlsplit(url).path)) csvfile = pre + ".csv" print(url) print(csvfile) if "_d01_" in csvfile: print("resolution d01") resolution = "d01" elif "_d02_" in csvfile: print("resolution d02") resolution = "d02" elif "_d03_" in csvfile: print("resolution d03") resolution = "d03" else: return False dirName = "static/user_files/" + username print(dirName) if not os.path.exists(dirName): os.mkdir(dirName) print("Directory ", dirName, " Created ") else: print("Directory ", dirName, " already exists") dirTemp = dirName + "/temp" if not os.path.exists(dirTemp): os.mkdir(dirTemp) print("Directory ", dirTemp, " Created ") else: print("Directory ", dirTemp, " already exists") pathCSVFile = dirName + "/temp/" + csvfile pathCSVFileDef = dirName + "/" + csvfile print(pathCSVFile) print(pathCSVFileDef) with open(pathCSVFile, "w") as f: fieldnames = ["LONGITUDE","LATITUDE","T2C","SLP", "WSPD10","WDIR10","RH2","UH","MCAPE","TC500","TC850","GPH500", "GPH850","CLDFRA_TOTAL","U10M","V10M","DELTA_WSPD10", "DELTA_WDIR10","DELTA_RAIN","resolution", "type"] writer1 = csv.DictWriter(f,extrasaction='ignore', fieldnames=fieldnames) writer1.writeheader() #pointX = [] #pointY = [] #polygonX = [] #polygonY = [] try: nc = Dataset(url, "r") except Exception as e: print("Error: there isn't nc file online", str(e)) return False hours1 = int(nc.variables["time"][0]) date1 = datetime(1900, 1, 1) + timedelta(hours=hours1) print("date of file :",date1) count1 = 0 polygons, typePolygons = mytool.getPolygon(date1,managedb) if polygons == None: raise ValueError('problem with DB') if (len(polygons) >0): fig, ax = plt.subplots() patches = [] # color = [] # c = np.random.random((1, 3)).tolist()[0] for i in range(0, len(polygons)): print(polygons[i]) x, y = polygons[i].exterior.xy po1 = po(zip(x, y)) patches.append(po1) p = PatchCollection(patches, edgecolors=(0, 0, 0, 1), linewidths=1, alpha=0.5) ax.add_collection(p) #print(len(nc.dimensions['longitude'])) #print(len(nc.dimensions['latitude'])) for i in range(0, len(nc.dimensions['longitude'])): for j in range(0, len(nc.dimensions['latitude'])): count1 = count1 + 1 # print("lng: {} | lat: {}".format(nc.variables["longitude"][i],nc.variables["latitude"][j])) lng = nc.variables["longitude"][i] lat = nc.variables["latitude"][j] pt = Point(lng, lat) flag = False for k in range(0, len(polygons)): if (polygons[k].contains(pt)): flag = True count = count + 1 #pointX.append(lng) #pointY.append(lat) print("count {}) lng: {} | lat: {} | type: {}".format(count, lng,lat,typePolygons[k])) #writer1.writerow({"type": typePolygons[k]}) writer1.writerow({"LONGITUDE":lng, "LATITUDE":lat, "T2C": nc.variables["T2C"][0][j][i], "SLP": nc.variables["SLP"][0][j][i], "WSPD10": nc.variables["WSPD10"][0][j][i], "WDIR10": nc.variables["WDIR10"][0][j][i], "RH2": nc.variables["RH2"][0][j][i], "UH": nc.variables["UH"][0][j][i], "MCAPE": nc.variables["MCAPE"][0][j][i], "TC500": nc.variables["TC500"][0][j][i], "TC850": nc.variables["TC850"][0][j][i], "GPH500": nc.variables["GPH500"][0][j][i], "GPH850": nc.variables["GPH850"][0][j][i], "CLDFRA_TOTAL": nc.variables["CLDFRA_TOTAL"][0][j][i], "U10M": nc.variables["U10M"][0][j][i], "V10M": nc.variables["V10M"][0][j][i], "DELTA_WSPD10": nc.variables["DELTA_WSPD10"][0][j][i], "DELTA_WDIR10": nc.variables["DELTA_WDIR10"][0][j][i], "DELTA_RAIN": nc.variables["DELTA_RAIN"][0][j][i], "resolution":resolution, "type": typePolygons[k]}) if (not flag): #writer1.writerow({"type": 0}) writer1.writerow({"LONGITUDE":lng, "LATITUDE":lat, "T2C": nc.variables["T2C"][0][j][i], "SLP": nc.variables["SLP"][0][j][i], "WSPD10": nc.variables["WSPD10"][0][j][i], "WDIR10": nc.variables["WDIR10"][0][j][i], "RH2": nc.variables["RH2"][0][j][i], "UH": nc.variables["UH"][0][j][i], "MCAPE": nc.variables["MCAPE"][0][j][i], "TC500": nc.variables["TC500"][0][j][i], "TC850": nc.variables["TC850"][0][j][i], "GPH500": nc.variables["GPH500"][0][j][i], "GPH850": nc.variables["GPH850"][0][j][i], "CLDFRA_TOTAL": nc.variables["CLDFRA_TOTAL"][0][j][i], "U10M": nc.variables["U10M"][0][j][i], "V10M": nc.variables["V10M"][0][j][i], "DELTA_WSPD10": nc.variables["DELTA_WSPD10"][0][j][i], "DELTA_WDIR10": nc.variables["DELTA_WDIR10"][0][j][i], "DELTA_RAIN": nc.variables["DELTA_RAIN"][0][j][i], "resolution":resolution, "type": 0}) print("N. point",count1) #plt.plot(pointX, pointY, 'b,') #plt.show() else: print("No polygons") #print(len(nc.variables['longitude'])) #print(len(nc.variables['latitude'])) for i in range(0, len(nc.dimensions['longitude'])): for j in range(0, len(nc.dimensions['latitude'])): lng = nc.variables["longitude"][i] lat = nc.variables["latitude"][j] count1 = count1 + 1 #writer1.writerow({"type": 0}) writer1.writerow({"LONGITUDE":lng, "LATITUDE":lat, "T2C": nc.variables["T2C"][0][j][i], "SLP": nc.variables["SLP"][0][j][i], "WSPD10": nc.variables["WSPD10"][0][j][i], "WDIR10": nc.variables["WDIR10"][0][j][i], "RH2": nc.variables["RH2"][0][j][i], "UH": nc.variables["UH"][0][j][i], "MCAPE": nc.variables["MCAPE"][0][j][i], "TC500": nc.variables["TC500"][0][j][i], "TC850": nc.variables["TC850"][0][j][i], "GPH500": nc.variables["GPH500"][0][j][i], "GPH850": nc.variables["GPH850"][0][j][i], "CLDFRA_TOTAL": nc.variables["CLDFRA_TOTAL"][0][j][i], "U10M": nc.variables["U10M"][0][j][i], "V10M": nc.variables["V10M"][0][j][i], "DELTA_WSPD10": nc.variables["DELTA_WSPD10"][0][j][i], "DELTA_WDIR10": nc.variables["DELTA_WDIR10"][0][j][i], "DELTA_RAIN": nc.variables["DELTA_RAIN"][0][j][i], "resolution":resolution, "type": 0}) print("N. point",count1) nc.close() managedb.client.close() copyfile(pathCSVFile, pathCSVFileDef) if os.path.exists( pathCSVFile): os.remove(pathCSVFile) else: print("The file does not exist") return True def workerNcfile(username,ncfile): """This method analyzes which point of local netCDF belong to polygon or not; then it create a csv file where it storage every info""" print("------------------------------------------------------------------------------------") print("Analysis local netCDF file") print(ncfile) count = 0 managedb = ManageDB() mytool = MyTools() pre, ext = os.path.splitext(os.path.basename(urlparse.urlsplit(ncfile).path)) csvfile = pre + ".csv" print(csvfile) if "_d01_" in csvfile: print("resolution d01") resolution = "d01" elif "_d02_" in csvfile: print("resolution d02") resolution = "d02" elif "_d03_" in csvfile: print("resolution d03") resolution = "d03" else: return False dirName = "static/user_files/" + username print(dirName) if not os.path.exists(dirName): os.mkdir(dirName) print("Directory ", dirName, " Created ") else: print("Directory ", dirName, " already exists") pathCSVFile = dirName + "/temp/" + csvfile pathCSVFileDef = dirName + "/" + csvfile dirTemp = dirName + "/temp" if not os.path.exists(dirTemp): os.mkdir(dirTemp) print("Directory ", dirTemp, " Created ") else: print("Directory ", dirTemp, " already exists") print(pathCSVFile) print(pathCSVFileDef) with open(pathCSVFile, "w") as f: fieldnames = ["LONGITUDE","LATITUDE","T2C","SLP", "WSPD10","WDIR10","RH2","UH","MCAPE","TC500","TC850","GPH500", "GPH850","CLDFRA_TOTAL","U10M","V10M","DELTA_WSPD10", "DELTA_WDIR10","DELTA_RAIN","resolution", "type"] writer1 = csv.DictWriter(f, extrasaction='ignore',fieldnames=fieldnames) writer1.writeheader() #pointX = [] #pointY = [] #polygonX = [] #polygonY = [] try: nc = Dataset(ncfile, "r") except Exception as e: print("Error: there isn't nc file in local", str(e)) return False hours1 = int(nc.variables["time"][0]) date1 = datetime(1900, 1, 1) + timedelta(hours=hours1) print("date of file:",date1) count1 = 0 polygons, typePolygons = mytool.getPolygon(date1,managedb) if (len(polygons) != 0 and polygons != None): print("Number of polygon n.",len(polygons)) fig, ax = plt.subplots() patches = [] # color = [] # c = np.random.random((1, 3)).tolist()[0] for i in range(0, len(polygons)): #print(polygons[i]) x, y = polygons[i].exterior.xy po1 = po(zip(x, y)) patches.append(po1) p = PatchCollection(patches, edgecolors=(0, 0, 0, 1), linewidths=1, alpha=0.5) ax.add_collection(p) #print("longitude n.",len(nc.dimensions['longitude'])) #print("latitude n.",len(nc.dimensions['latitude'])) for i in range(0, len(nc.dimensions['longitude'])): for j in range(0, len(nc.dimensions['latitude'])): count1 = count1 + 1 #print("lng: {} | lat: {}".format(nc.variables["longitude"][i],nc.variables["latitude"][j])) lng = nc.variables["longitude"][i] lat = nc.variables["latitude"][j] pt = Point(lng, lat) flag = False for k in range(0, len(polygons)): if (polygons[k].contains(pt)): flag = True count = count + 1 #pointX.append(lng) #pointY.append(lat) print("count {}) lng: {} | lat: {} | type: {}".format(count, lng,lat,typePolygons[k])) #writer1.writerow({"LONGITUDE":lng,"LATITUDE":lat,"type": typePolygons[k]}) writer1.writerow({"LONGITUDE":lng, "LATITUDE":lat, "T2C": nc.variables["T2C"][0][j][i], "SLP": nc.variables["SLP"][0][j][i], "WSPD10": nc.variables["WSPD10"][0][j][i], "WDIR10": nc.variables["WDIR10"][0][j][i], "RH2": nc.variables["RH2"][0][j][i], "UH": nc.variables["UH"][0][j][i], "MCAPE": nc.variables["MCAPE"][0][j][i], "TC500": nc.variables["TC500"][0][j][i], "TC850": nc.variables["TC850"][0][j][i], "GPH500": nc.variables["GPH500"][0][j][i], "GPH850": nc.variables["GPH850"][0][j][i], "CLDFRA_TOTAL": nc.variables["CLDFRA_TOTAL"][0][j][i], "U10M": nc.variables["U10M"][0][j][i], "V10M": nc.variables["V10M"][0][j][i], "DELTA_WSPD10": nc.variables["DELTA_WSPD10"][0][j][i], "DELTA_WDIR10": nc.variables["DELTA_WDIR10"][0][j][i], "DELTA_RAIN": nc.variables["DELTA_RAIN"][0][j][i], "resolution":resolution, "type": typePolygons[k]}) if (not flag): #writer1.writerow({"type": 0}) writer1.writerow({"LONGITUDE":lng, "LATITUDE":lat, "T2C": nc.variables["T2C"][0][j][i], "SLP": nc.variables["SLP"][0][j][i], "WSPD10": nc.variables["WSPD10"][0][j][i], "WDIR10": nc.variables["WDIR10"][0][j][i], "RH2": nc.variables["RH2"][0][j][i], "UH": nc.variables["UH"][0][j][i], "MCAPE": nc.variables["MCAPE"][0][j][i], "TC500": nc.variables["TC500"][0][j][i], "TC850": nc.variables["TC850"][0][j][i], "GPH500": nc.variables["GPH500"][0][j][i], "GPH850": nc.variables["GPH850"][0][j][i], "CLDFRA_TOTAL": nc.variables["CLDFRA_TOTAL"][0][j][i], "U10M": nc.variables["U10M"][0][j][i], "V10M": nc.variables["V10M"][0][j][i], "DELTA_WSPD10": nc.variables["DELTA_WSPD10"][0][j][i], "DELTA_WDIR10": nc.variables["DELTA_WDIR10"][0][j][i], "DELTA_RAIN": nc.variables["DELTA_RAIN"][0][j][i], "resolution":resolution, "type": 0}) print("N. point",count1) #plt.plot(pointX, pointY, 'b,') #plt.show() else: print("No polygon") #print(len(nc.variables['longitude'])) #print(len(nc.variables['latitude'])) for i in range(0, len(nc.dimensions['longitude'])): for j in range(0, len(nc.dimensions['latitude'])): lng = nc.variables["longitude"][i] lat = nc.variables["latitude"][j] count1 = count1 + 1 #writer1.writerow({"type": 0}) writer1.writerow({"LONGITUDE":lng, "LATITUDE":lat, "T2C": nc.variables["T2C"][0][j][i], "SLP": nc.variables["SLP"][0][j][i], "WSPD10": nc.variables["WSPD10"][0][j][i], "WDIR10": nc.variables["WDIR10"][0][j][i], "RH2": nc.variables["RH2"][0][j][i], "UH": nc.variables["UH"][0][j][i], "MCAPE": nc.variables["MCAPE"][0][j][i], "TC500": nc.variables["TC500"][0][j][i], "TC850": nc.variables["TC850"][0][j][i], "GPH500": nc.variables["GPH500"][0][j][i], "GPH850": nc.variables["GPH850"][0][j][i], "CLDFRA_TOTAL": nc.variables["CLDFRA_TOTAL"][0][j][i], "U10M": nc.variables["U10M"][0][j][i], "V10M": nc.variables["V10M"][0][j][i], "DELTA_WSPD10": nc.variables["DELTA_WSPD10"][0][j][i], "DELTA_WDIR10": nc.variables["DELTA_WDIR10"][0][j][i], "DELTA_RAIN": nc.variables["DELTA_RAIN"][0][j][i], "resolution":resolution, "type": 0}) print("N. point",count1) nc.close() managedb.client.close() copyfile(pathCSVFile, pathCSVFileDef) if os.path.exists(pathCSVFile): os.remove(pathCSVFile) else: print("The file does not exist") return True
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/11/29 18:09 # @Author : duanhaobin # @File : douban_book_data_collection.py # @Software: PyCharm # @desc: 豆瓣图书数据采集练习 # 爬虫逻辑:【分页网页url采集】-【数据信息网页url采集】-【数据采集】 import requests import time from bs4 import BeautifulSoup def get_urls(n): ''' 分页网页url采集函数 :param n:页面参数 :return:url列表 ''' urlslst = [] for i in range(n): urlslst.append('https://book.douban.com/tag/%%E7%%94%%B5%%E5%%BD%%B1?start=%i&type=T' % (i * 20)) return urlslst def get_dataurls(ui, d_h, d_c): ''' 数据信息网页url采集 函数 :param ui:分页网址 :param d_h:user_agent :param d_c:cookies信息 :return:数据信息网页url列表 ''' # 访问网页 r = requests.get(url=ui, headers=d_h, cookies=d_c) # 解析网页 soup = BeautifulSoup(r.text, 'lxml') # 找到所有li标签 lis = soup.find('ul', class_='subject-list').findAll('li') li_lst = [] for li in lis: # 构建链接列表 li_lst.append(li.find('a')['href']) return li_lst def get_data(ui, d_h, d_c): ''' 数据采集函数 :param ui:书名url :param d_h:user_agent :param d_c:cookies :return:数据字典 ''' print('进入get_data,ui:', ui) r2 = requests.get(url=ui, headers=dict_h, cookies=dict_c) soup = BeautifulSoup(r2.text, 'lxml') dic = {} dic['书名'] = soup.find('div', id='wrapper').find('h1').text.replace('\n', '') dic['评分'] = soup.find('div', class_='rating_self clearfix').find('strong').text.replace(' ', '') dic['评价人数'] = soup.find('div', class_='rating_sum').find('a').find('span').text infors = soup.find('div', id="info").text.replace(' ', '').split('\n') for i in infors: if ':' in i: dic[i.split(':')[0]] = i.split(':')[1] else: continue return dic if __name__ == "__main__": begin_t = time.time() # 获取分页网址 urllst1 = get_urls(2) # 拼接user_agent dict_h = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/78.0.3904.108 Safari/537.36'} cookies = 'viewed="33440205"; bid=FkeG50F4XvY; gr_user_id=6015c5ac-82f6-4b50-bb85-3c5575d26897; __utmc=30149280; ' \ '__utmz=30149280.1574410772.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ' \ '__utmz=81379588.1574410772.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmc=81379588; ' \ '_vwo_uuid_v2=DF10E7B10E49A5D9F60728C833D04996C|bbcdcfe17d39131c077d26d2ed9db281; ' \ 'dbcl2="169993529:e2JKdBZQZgI"; ck=jwLe; __gads=Test; push_noty_num=0; push_doumail_num=0; ' \ '__utmv=30149280.16999; ll="108288"; __yadk_uid=xoYMePLedf9yf3sEbLPkosdMuq2B4fvU; ap_v=0,' \ '6.0; _pk_ses.100001.3ac3=*; __utma=30149280.625182603.1574410772.1575012018.1575022271.5; ' \ '__utma=81379588.1008532201.1574410772.1575012018.1575022271.5; ' \ '_pk_id.100001.3ac3=06e6cfa033259840.1574410772.5.1575022338.1575012051.; __utmb=30149280.2.10.1575022271; ' \ '__utmb=81379588.2.10.1575022271 ' dict_c = {} # 拼接cookies for i in cookies.split('; '): dict_c[i.split('=')[0]] = i.split('=')[1] urllst2 = [] # 获取数据信息页面网址urllst2 for u in urllst1: try: urllst2.extend(get_dataurls(u, dict_h, dict_c)) print('数据信息网页获取成功,总共获取%i条网页' % len(urllst2)) except: print('数据信息网页获取失败,失败网页:', u) successlst = [] errolst = [] # 采集需求数据 for ui in urllst2: try: successlst.append(get_data(ui, dict_h, dict_c)) print('数据采集成功,总共%i条数据' % len(successlst)) except: errolst.append(ui) print('数据采集失败,失败网址为:', errolst) end_t = time.time() print(successlst) print('数据采集结束,共耗时:%ss' %(str(end_t - begin_t)))
#산술 연산자 : +, =, *, /, //, %, ** #문제 10000초는 몇시간 몇분 몇초인가? s=10000 m=s//60 M=s//60%60 r=s%60 h=m//60 print('{0}시간 {1}분 {2}초,'.format(h,M,r)) #산술연산자 우선순위 : () # 지수** # 곱셈, 나눗셈, 나머지, 몫 # 덧셈, 뺄셈 #할당 연산자 : = #대입 연산자 : +=, -=, *=, /=, //=, %=, **= a=100 a = a + 10 # a += 10 a = a + 10 a = a + 10 sum = 1 sum = sum + 2 # 1+2 sum = sum + 3 # 1+2+3 sum = sum + 4 # 1+2+3+4 sum = sum + 5 # 1+2+3+4+5 b -= 10 #b=b-10 c *= 10 #c=c*10 d /= 10 #d=d/10 e **= 3 #e=e**3 #관계 연산자 : > , < , >=, <=, ==, != : 결과값이 참(True), 거짓(False) 100 > 3 # True a= 100 b= 1001 a > b print(a>b) print(a!=b) #논리 연산자 : and, or, not print('#논리연산자') print(a>b and b==1001) #False print(a>b or b==1001) #True print(not(a>b)) #비트 연산자 : 정수를 2진수로 변환한 수 각각의 비트별로 연산 # & (논리곱), | (논리합), ^(xor) ~(부정not), <<(왼쪽시프트) , >>(오른쪽시프트) print(10 & 3) #1010 & 0011 (2진수곱) -> 0010 print(10 | 3) #1010 | 0011 (2진수합) -> 1011 print(10 ^ 3) #1010 ^ 0011 -> 1001 print(~3) # ~0011 -> 1100 (12) print(10<<1) print(10<<2) print(10<<3) print(10>>1) print(10>>2) print(10>>3) candy= 5000//120 cash=5000%120 print('사탕의 개수는 : {0} 나머지돈은 : {1}원'.format(candy,cash)) print('잔액 : ', format(1235000, ',.0f')) # , 는 자릿수
from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) # nickname = models.CharField(max_length = 50) # I added without DataBase settings # Unless nickname is deleted, it occurs errors when using queryset. title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default = timezone.now) published_date = models.DateTimeField(blank=True, null = True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
# Course: CS261 - Data Structures # Student Name: Jordan Hendricks # Assignment: # Description: class Stack: """ Class implementing STACK ADT. Supported methods are: push, pop, top, is_empty DO NOT CHANGE THIS CLASS IN ANY WAY YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS CLASS IN YOUR SOLUTION """ def __init__(self): """ Initialize empty stack based on Python list """ self._data = [] def push(self, value: object) -> None: """ Add new element on top of the stack """ self._data.append(value) def pop(self) -> object: """ Remove element from top of the stack and return its value """ return self._data.pop() def top(self) -> object: """ Return value of top element without removing from stack """ return self._data[-1] def is_empty(self): """ Return True if the stack is empty, return False otherwise """ return len(self._data) == 0 def __str__(self): """ Return content of the stack as a string (for use with print) """ data_str = [str(i) for i in self._data] return "STACK: { " + ", ".join(data_str) + " }" class Queue: """ Class implementing QUEUE ADT. Supported methods are: enqueue, dequeue, is_empty DO NOT CHANGE THIS CLASS IN ANY WAY YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS CLASS IN YOUR SOLUTION """ def __init__(self): """ Initialize empty queue based on Python list """ self._data = [] def enqueue(self, value: object) -> None: """ Add new element to the end of the queue """ self._data.append(value) def dequeue(self) -> object: """ Remove element from the beginning of the queue and return its value """ return self._data.pop(0) def is_empty(self): """ Return True if the queue is empty, return False otherwise """ return len(self._data) == 0 def __str__(self): """ Return content of the stack as a string (for use with print) """ data_str = [str(i) for i in self._data] return "QUEUE { " + ", ".join(data_str) + " }" class TreeNode: """ Binary Search Tree Node class DO NOT CHANGE THIS CLASS IN ANY WAY """ def __init__(self, value: object) -> None: """ Init new Binary Search Tree DO NOT CHANGE THIS METHOD IN ANY WAY """ self.value = value # to store node's data self.left = None # pointer to root of left subtree self.right = None # pointer to root of right subtree def __str__(self): return str(self.value) class BST: def __init__(self, start_tree=None) -> None: """ Init new Binary Search Tree DO NOT CHANGE THIS METHOD IN ANY WAY """ self.root = None # populate BST with initial values (if provided) # before using this feature, implement add() method if start_tree is not None: for value in start_tree: self.add(value) def __str__(self) -> str: """ Return content of BST in human-readable form using in-order traversal DO NOT CHANGE THIS METHOD IN ANY WAY """ values = [] self._str_helper(self.root, values) return "TREE pre-order { " + ", ".join(values) + " }" def _str_helper(self, cur, values): """ Helper method for __str__. Does pre-order tree traversal DO NOT CHANGE THIS METHOD IN ANY WAY """ # base case if not cur: return # store value of current node values.append(str(cur.value)) # recursive case for left subtree self._str_helper(cur.left, values) # recursive case for right subtree self._str_helper(cur.right, values) # ------------------------------------------------------------------ # def add(self, value: object) -> None: """Adds a new value to the tree""" node = TreeNode(value) if self.root is None: self.root = node return current = self.root while current is not None: # runs until the desired node is reached if value < current.value: if current.left is None: current.left = node return current = current.left elif value >= current.value: if current.right is None: current.right = node return current = current.right def contains(self, value: object) -> bool: """Determines if the binary tree contains the given value""" current = self.root while current is not None: # runs until the value is found if value < current.value: current = current.left elif value >= current.value: if current.value == value: # if the value is found, return True return True current = current.right return False def get_first(self) -> object: """Returns the first value stored at the root node""" if self.root is None: return None return self.root.value def remove_first(self) -> bool: """Removes the root node from the tree""" node = self.root if self.root is None: return False if node.right is None and node.left is None: self.root = None return True if node.left is None and node.right is not None: self.root = node.right return True elif node.right is None and node.left is not None: self.root = node.left return True node = node.right count = 0 address = (self.remove_first_helper(node, count)) count = address[0] node_right = address[1] node_right_left = address[2] if count == 0: self.root.value = node.value self.root.right = None return True node = self.root.right for i in range(count - 1): node = node.left if node_right is not None and node_right_left is not None: node.left = node_right_left node_right_left.right = node_right node_right.left = None elif node_right is not None: node.left = node_right return True def remove_first_helper(self, node, count): """Helps recursively go through the tree to replace root node""" if node.left is not None: count += 1 return self.remove_first_helper(node.left, count) if node.left is None: if node.right is not None: self.root.value = node.value node_right = node.right if node_right.left is not None: return count, node_right, node_right.left return count, node_right, node.left else: return count, None, None def remove(self, value) -> bool: """Removes the first instance of the given value in the binary tree""" node = self.root if node is None: return False if node.value == value: self.remove_first() return True before = self.in_order_traversal() self.remove_helper(node, value) after = self.in_order_traversal() if before.is_empty() is True and after.is_empty() is True: return True before_count = 0 # determine the number of nodes after_count = 0 while before.is_empty() is False: before.dequeue() before_count += 1 while after.is_empty() is False: after.dequeue() after_count += 1 if before_count == after_count: return False return True def remove_helper(self, node, value): """Recursively goes through binary tree to remove a node""" if node is None: return node if value < node.value: # moves left if the value is less than the current node node.left = self.remove_helper(node.left, value) elif value > node.value: # moves right if the value is greater than the current node node.right = self.remove_helper(node.right, value) else: # If the node is found and only has a single child if node.left is None: temp_node = node.right node = None return temp_node # If the node is found and only has a single child elif node.right is None: temp_node = node.left node = None return temp_node temp_node = self.min_val(node.right) node.value = temp_node.value node.right = self.remove_helper(node.right, temp_node.value) return node def min_val(self, node): """Finds the smallest value in a subtree""" while node.left is not None: node = node.left return node def pre_order_traversal(self) -> Queue: """Traverses the binary tree in pre-order""" values = Queue() if self.root is None: return values values.enqueue(self.root) if self.root.left is not None: values = self.pre_order_traversal_helper(self.root.left, values) if self.root.right is not None: values = self.pre_order_traversal_helper(self.root.right, values) return values def pre_order_traversal_helper(self, node, values): """Helps traverse the binary tree recursively""" node_added = False if node.left is not None: values.enqueue(node.value) self.pre_order_traversal_helper(node.left, values) node_added = True if node.right is not None: if node_added is not True: values.enqueue(node.value) self.pre_order_traversal_helper(node.right, values) if node.left is None and node.right is None: values.enqueue(node.value) return values def in_order_traversal(self) -> Queue: """Traverses the binary tree in order""" values = Queue() if self.root is None: return values order = self.in_order_traversal_helper(self.root, values) return order def in_order_traversal_helper(self, node, values): """Helps traverse the binary tree recursively""" if node.left is not None: self.in_order_traversal_helper(node.left, values) values.enqueue(node.value) if node.right is not None: self.in_order_traversal_helper(node.right, values) return values def post_order_traversal(self) -> Queue: """Traverses and returns values in post-order""" values = Queue() if self.root is None: return values if self.root.left is not None: values = self.post_order_traversal_helper(self.root.left, values) if self.root.right is not None: values = self.post_order_traversal_helper(self.root.right, values) values.enqueue(self.root) return values def post_order_traversal_helper(self, node, values): """Helps traverse the binary tree recursively""" if node.left is not None: self.post_order_traversal_helper(node.left, values) if node.right is not None: self.post_order_traversal_helper(node.right, values) values.enqueue(node.value) return values def by_level_traversal(self) -> Queue: """Traverses and returns values in highest level first""" values = Queue() temp_values = Queue() if self.root is None: return values node = self.root values.enqueue(node) temp_values.enqueue(node) # creates temp list so the program can access past nodes while temp_values.is_empty() is False: node = temp_values.dequeue() if node.left is not None: values.enqueue(node.left) temp_values.enqueue(node.left) if node.right is not None: values.enqueue(node.right) temp_values.enqueue(node.right) return values def is_full(self) -> bool: """Determines if the binary tree is full""" return self.is_full_helper(self.root) def is_full_helper(self, node): """Recursively goes through each node to determine a full tree""" if node is None: return True if node.left is None and node.right is None: return True # Both the left and right trees must have full leaves if node.left is not None and node.right is not None: return (self.is_full_helper(node.left) and self.is_full_helper(node.right)) return False def is_complete(self) -> bool: """Determines if the binary tree is complete""" order = self.in_order_traversal() count = 0 while order.is_empty() is False: order.dequeue() count += 1 return self.is_complete_helper(self.root, 0, count) def is_complete_helper(self, node, index, number_nodes): """Recursively goes through each node to determine a complete tree""" if node is None: return True if index >= number_nodes: return False return (self.is_complete_helper(node.left, 2 * index + 1, number_nodes) and self.is_complete_helper(node.right, 2 * index + 2, number_nodes) ) def is_perfect(self) -> bool: """Determines if the tree is perfect""" depth = 0 node = self.root while node is not None: depth += 1 node = node.left node = self.root return self.is_perfect_helper(node, depth, 0) def is_perfect_helper(self, node, depth, level): """Recursively goes through the binary tree to determine if the tree is perfect""" if node is None: return True if node.left is None and node.right is None: return depth == level + 1 if node.left is None or node.right is None: return False return self.is_perfect_helper(node.left, depth, level + 1) and self.is_perfect_helper(node.right, depth, level + 1) def size(self) -> int: """Returns the total number of nodes in the tree""" temp_values = Queue() if self.root is None: return 0 count = 1 node = self.root temp_values.enqueue(node) # creates temp list so the program can access past nodes while temp_values.is_empty() is False: node = temp_values.dequeue() if node.left is not None: temp_values.enqueue(node.left) count += 1 if node.right is not None: temp_values.enqueue(node.right) count += 1 return count def height(self) -> int: """Determines the height of the binary tree""" return self.height_helper(self.root) def height_helper(self, node): """Recursively goes through the binary tree to determine height""" if node is None: return -1 left_height = self.height_helper(node.left) right_height = self.height_helper(node.right) if left_height > right_height: return left_height + 1 else: return right_height + 1 def count_leaves(self) -> int: """Counts the number of leaves in the binary tree""" if self.root is None: return 0 leaves = Queue() leaves = self.count_leaves_helper(self.root, leaves) count = 0 while leaves.is_empty() is False: leaves.dequeue() count += 1 return count def count_leaves_helper(self, node, leaves): """Recursively goes through the binary tree""" if node.left is not None: self.count_leaves_helper(node.left, leaves) if node.right is not None: self.count_leaves_helper(node.right, leaves) if node.left is None and node.right is None: leaves.enqueue(node) return leaves def count_unique(self) -> int: """Counts the number of unique nodes in the tree""" unique = Stack() temp = Stack() in_order = self.in_order_traversal() in_order_stack = Stack() while in_order.is_empty() is False: val = in_order.dequeue() in_order_stack.push(val) while in_order_stack.is_empty() is False: temp_val = in_order_stack.pop() if in_order_stack.is_empty() is False: temp_val2 = in_order_stack.pop() if temp_val == temp_val2: temp.push(temp_val) in_order_stack.push(temp_val2) elif temp.is_empty() is False: temp_val3 = temp.pop() if temp_val == temp_val3: temp.push(temp_val3) temp.push(temp_val) in_order_stack.push(temp_val2) else: unique.push(temp_val) in_order_stack.push(temp_val2) else: unique.push(temp_val) count = 0 while unique.is_empty() is False: unique.pop() count += 1 return count # BASIC TESTING - PDF EXAMPLES # if __name__ == '__main__': # """ add() example #1 """ # print("\nPDF - method add() example 1") # print("----------------------------") # tree = BST() # print(tree) # tree.add(10) # tree.add(15) # tree.add(5) # print(tree) # tree.add(15) # tree.add(15) # print(tree) # tree.add(5) # print(tree) # """ add() example 2 """ # print("\nPDF - method add() example 2") # print("----------------------------") # tree = BST() # tree.add(10) # tree.add(10) # print(tree) # tree.add(-1) # print(tree) # tree.add(5) # print(tree) # tree.add(-1) # print(tree) # """ contains() example 1 """ # print("\nPDF - method contains() example 1") # print("---------------------------------") # tree = BST([10, 5, 15]) # print(tree.contains(15)) # print(tree.contains(-10)) # print(tree.contains(15)) # """ contains() example 2 """ # print("\nPDF - method contains() example 2") # print("---------------------------------") # tree = BST() # print(tree.contains(0)) # """ get_first() example 1 """ # print("\nPDF - method get_first() example 1") # print("----------------------------------") # tree = BST() # print(tree.get_first()) # tree.add(10) # tree.add(15) # tree.add(5) # print(tree.get_first()) # print(tree) # """ remove() example 1 """ # print("\nPDF - method remove() example 1") # print("-------------------------------") # tree = BST([10, 5, 15]) # print(tree.remove(7)) # print(tree.remove(15)) # print(tree.remove(15)) # # """ remove() example 2 """ # print("\nPDF - method remove() example 2") # print("-------------------------------") # tree = BST([10, 20, 5, 15, 17, 7, 12]) # print(tree.remove(20)) # print(tree) # # """ remove() example 3 """ # print("\nPDF - method remove() example 3") # print("-------------------------------") # tree = BST([10, 5, 20, 18, 12, 7, 27, 22, 18, 24, 22, 30]) # print(tree.remove(20)) # print(tree) # comment out the following lines # if you have not yet implemented traversal methods # print(tree.pre_order_traversal()) # print(tree.in_order_traversal()) # print(tree.post_order_traversal()) # print(tree.by_level_traversal()) # """ remove_first() example 1 """ # print("\nPDF - method remove_first() example 1") # print("-------------------------------------") # tree = BST([10, 15, 5]) # print(tree.remove_first()) # print(tree) # # """ remove_first() example 2 """ # print("\nPDF - method remove_first() example 2") # print("-------------------------------------") # tree = BST([10, 20, 5, 15, 17, 7]) # print(tree.remove_first()) # print(tree) # # """ remove_first() example 3 """ # print("\nPDF - method remove_first() example 3") # print("-------------------------------------") # tree = BST([10, 10, -1, 5, -1]) # print(tree.remove_first(), tree) # print(tree.remove_first(), tree) # print(tree.remove_first(), tree) # print(tree.remove_first(), tree) # print(tree.remove_first(), tree) # print(tree.remove_first(), tree) # """ Traversal methods example 1 """ # print("\nPDF - traversal methods example 1") # print("---------------------------------") # tree = BST([10, 20, 5, 15, 17, 7, 12]) # print(tree.pre_order_traversal()) # print(tree.in_order_traversal()) # print(tree.post_order_traversal()) # print(tree.by_level_traversal()) # """ Traversal methods example 2 """ # print("\nPDF - traversal methods example 2") # print("---------------------------------") # tree = BST([10, 10, -1, 5, -1]) # print(tree.pre_order_traversal()) # print(tree.in_order_traversal()) # print(tree.post_order_traversal()) # print(tree.by_level_traversal()) # """ Comprehensive example 1 """ # print("\nComprehensive example 1") # print("-----------------------") # tree = BST() # header = 'Value Size Height Leaves Unique ' # header += 'Complete? Full? Perfect?' # print(header) # print('-' * len(header)) # print(f' N/A {tree.size():6} {tree.height():7} ', # f'{tree.count_leaves():7} {tree.count_unique():8} ', # f'{str(tree.is_complete()):10}', # f'{str(tree.is_full()):7} ', # f'{str(tree.is_perfect())}') # # for value in [10, 5, 3, 15, 12, 8, 20, 1, 4, 9, 7]: # tree.add(value) # print(f'{value:5} {tree.size():6} {tree.height():7} ', # f'{tree.count_leaves():7} {tree.count_unique():8} ', # f'{str(tree.is_complete()):10}', # f'{str(tree.is_full()):7} ', # f'{str(tree.is_perfect())}') # print() # print(tree.pre_order_traversal()) # print(tree.in_order_traversal()) # print(tree.post_order_traversal()) # print(tree.by_level_traversal()) # # """ Comprehensive example 2 """ # print("\nComprehensive example 2") # print("-----------------------") # tree = BST() # header = 'Value Size Height Leaves Unique ' # header += 'Complete? Full? Perfect?' # print(header) # print('-' * len(header)) # print(f'N/A {tree.size():6} {tree.height():7} ', # f'{tree.count_leaves():7} {tree.count_unique():8} ', # f'{str(tree.is_complete()):10}', # f'{str(tree.is_full()):7} ', # f'{str(tree.is_perfect())}') # # for value in 'DATA STRUCTURES': # tree.add(value) # print(f'{value:5} {tree.size():6} {tree.height():7} ', # f'{tree.count_leaves():7} {tree.count_unique():8} ', # f'{str(tree.is_complete()):10}', # f'{str(tree.is_full()):7} ', # f'{str(tree.is_perfect())}') # print('', tree.pre_order_traversal(), tree.in_order_traversal(), # tree.post_order_traversal(), tree.by_level_traversal(), # sep='\n')
#!/usr/bin/env python # -*- coding:utf-8 -*- # !/usr/bin/env python # -*- coding:utf-8 -*- def main(): MAX = 9999999999 N, P = map(int, input().strip().split()) table = list(map(int, input().strip().split())) dp = [MAX] * N for i in range(N - 1, -1, -1): if table[i] == 0: dp[i] = MAX elif table[i] >= N - i: dp[i] = 1 else: left = min(i + 1, N - 1) right = min(i + table[i], N - 1) x = min(dp[left:right + 1]) dp[i] = MAX if x == MAX else x + 1 for i in range(N): if(table[i]==0): continue left = max(0, i - table[i]) right = max(0, i - 1) y = min(dp[left: right + 1]) if y == MAX: continue else: dp[i] = min(dp[i], y + 1) if dp[P - 1] == MAX: print(-1) else: print(dp[P - 1]) # main() while 1: try: main() except: break
# This file is part of spot_motion_monitor. # # Developed for LSST System Integration, Test and Commissioning. # # See the LICENSE file at the top-level directory of this distribution # for details of code ownership. # # Use of this source code is governed by a 3-clause BSD-style # license that can be found in the LICENSE file. from collections import OrderedDict import numpy as np from spot_motion_monitor.camera import BaseCamera from ..config import GaussianCameraConfig __all__ = ['GaussianCamera'] class GaussianCamera(BaseCamera): """This class creates a camera that produces a frame with random Poisson noise and a Gaussian spot placed at random within the frame. Attributes ---------- config : `config.GaussianCameraConfig` The instance containing the camera configuration. counter : int The progress of the oscillation in time. fpsFullFrame : int The Frames per Second rate in full frame mode. fpsRoiFrame : int The Frames per Second rate in ROI frame mode. height : int The pixel height of the CCD. postageStamp : numpy.array The array containing the Gaussian postage stamp. roiSize : int The size of a (square) ROI region in pixels. seed : int The seed for the random number generator. spotSize : int The box size in pixels for the Gaussian spot. width : int The pixel width of the CCD. xAmp : int The amplitude of the x-axis oscillation. xFreq : float The frequency of the x-axis oscillation. xPoint : int The x-coordinate of the Gaussian postage stamp insertion point. xPointOriginal : int The x-coordinate of the original postage stamp insertion point. yAmp : int The amplitude of the y-axis oscillation. yFreq : float The frequency of the y-axis oscillation. yPoint : int The y-coordinate of the Gaussian postage stamp insertion point. yPointOriginal : int The y-coordinate of the original postage stamp insertion point. """ TWO_PI = 2.0 * np.pi seed = None def __init__(self): """Initalize the class. """ super().__init__() self.spotSize = 20 self.height = 480 self.width = 640 self.fpsFullFrame = 24 self.fpsRoiFrame = 40 self.roiSize = 50 self.postageStamp = None self.xPoint = None self.yPoint = None # Parameters for spot oscillation. self.doSpotOscillation = True self.counter = 0 self.xFreq = 1.0 self.xAmp = 10 self.yFreq = 2.0 self.yAmp = 5 self.xPointOriginal = None self.yPointOriginal = None self.config = GaussianCameraConfig() self.modelName = self.name def findInsertionPoint(self): """Determine the Gaussian spot insertion point. """ percentage = 0.2 xRange = percentage * self.width yRange = percentage * self.height # Pick lower left corner for insertion xHalfwidth = self.width / 2 yHalfwidth = self.height / 2 self.xPoint = np.random.randint(xHalfwidth - xRange, xHalfwidth + xRange + 1) self.yPoint = np.random.randint(yHalfwidth - yRange, yHalfwidth + yRange + 1) self.xPointOriginal = self.xPoint self.yPointOriginal = self.yPoint def getCameraInformation(self): """Return the current camera related information. Returns ------- OrderedDict The set of camera information. """ info = OrderedDict() info['Model'] = self.name info['CCD Width (pixels)'] = self.width info['CCD Height (pixels)'] = self.height return info def getConfiguration(self): """Get the current camera configuration. Returns ------- `config.GaussianCameraConfig` The set of current configuration parameters. """ self.config.roiSize = self.roiSize self.config.fpsRoiFrame = self.fpsRoiFrame self.config.fpsFullFrame = self.fpsFullFrame self.config.doSpotOscillation = self.doSpotOscillation self.config.xAmplitude = self.xAmp self.config.xFrequency = self.xFreq self.config.yAmplitude = self.yAmp self.config.yFrequency = self.yFreq return self.config def getFullFrame(self): """Get the full frame from the CCD. Returns ------- numpy.array The current full CCD frame. """ # Create base CCD frame ccd = np.random.poisson(20.0, (self.height, self.width)) if self.doSpotOscillation: self.oscillateSpot() # Merge CCD frame and postage stamp ccd[self.yPoint:self.yPoint + self.postageStamp.shape[1], self.xPoint:self.xPoint + self.postageStamp.shape[0]] += self.postageStamp return ccd def getOffset(self): """Get the offset for ROI mode. Returns ------- (float, float) The x, y pixel positions of the offset for ROI mode. """ # Offset is same for both axes since spot and ROI are square. offset = (self.roiSize - self.spotSize) // 2 xStart = self.xPointOriginal - offset yStart = self.yPointOriginal - offset return (xStart, yStart) def getRoiFrame(self): """Get the ROI frame from the CCD. Returns ------- numpy.array The current ROI CCD frame. """ ccd = self.getFullFrame() xOffset, yOffset = self.getOffset() roi = ccd[yOffset:yOffset + self.roiSize, xOffset:xOffset + self.roiSize] return roi def makePostageStamp(self): """Create the Gaussian spot. """ linear_space = np.linspace(-2, 2, self.spotSize) x, y = np.meshgrid(linear_space, linear_space) d = np.sqrt(x * x + y * y) sigma, mu = 0.5, 0.0 a = 200.0 / (sigma * np.sqrt(2.0 * np.pi)) self.postageStamp = a * np.exp(-((d - mu)**2 / (2.0 * sigma**2))) self.postageStamp = self.postageStamp.astype(np.int64) def oscillateSpot(self): """Calculate the oscillation of the spot. """ self.xPoint = int(self.xPointOriginal + self.xAmp * np.sin(self.TWO_PI * self.xFreq * (self.counter / self.fpsRoiFrame))) self.yPoint = int(self.yPointOriginal + self.yAmp * np.sin(self.TWO_PI * self.yFreq * (self.counter / self.fpsRoiFrame))) self.counter += 1 def resetOffset(self): """Reset the camera offsets back to zero. For the Gaussian camera, this is a no-op. """ pass def setConfiguration(self, config): """Set the comfiguration on the camera. Parameters ---------- config : `config.GaussianCameraConfig` The current configuration. """ self.roiSize = config.roiSize self.fpsRoiFrame = config.fpsRoiFrame self.fpsFullFrame = config.fpsFullFrame self.doSpotOscillation = config.doSpotOscillation self.xFreq = config.xFrequency self.xAmp = config.xAmplitude self.yFreq = config.yFrequency self.yAmp = config.yAmplitude def showFrameStatus(self): """Show frame status from the camera. The Gaussian camera does not use this function since all frames are good. """ pass def shutdown(self): """Handle the shutdown of the camera. """ pass def startup(self): """Handle the startup of the camera. """ np.random.seed(self.seed) self.makePostageStamp() self.findInsertionPoint() def updateOffset(self, centroidX, centroidY): """Update the camera's internal offset values from the provided centroid. For the Gaussian camera, this is a no-op, but helps test the mechanism. Parameters ---------- centroidX : float The x component of the centroid for offset update. centroidY : float The y component of the centroid for offset update. """ pass def waitOnRoi(self): """Wait on information to be updated for ROI mode use. The Gaussian camera does not make use of this currently. """ pass
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from selenium.common.exceptions import WebDriverException from selenium.webdriver.remote.webelement import WebElement class TextBox(WebElement): def __init__(self, textBoxWebElement): super(TextBox, self).__init__(textBoxWebElement.parent, textBoxWebElement.id) self.webElement = textBoxWebElement def enter_text(self, textToBeEntered): try: self.webElement.click() self.webElement.clear() except WebDriverException: pass self.webElement.send_keys(textToBeEntered) return self def is_enabled(self): return self.webElement.is_enabled()
""" Pre-Programming 61 Solution By Teerapat Kraisrisirikul """ def main(): """ Main function """ print(function_1()) print(function_2()) print(function_1()) print(function_2()) print(function_3()) print(function_1()) print(function_2()) print(function_1()) print(function_2()) print(function_1()) print(function_3()) print(function_3()) print(function_3()) print(function_2()) print(function_1()) def function_1(): """ Function #1 """ return "Problem Solving in Information Technology (PSIT)" def function_2(): """ Function #2 """ return "Introduction to Computer Systems (ICS)" def function_3(): """ Function #3 """ return "Information Technology Fundamentals (ITF)" main()
from django.db import models from accounts.models import User, Project class Scrum(models.Model): """ User's scrum report model """ date_created = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) hours = models.CharField(max_length=10) is_edited = models.BooleanField(default=False) def __str__(self): return str(self.id) class Log(models.Model): """ User's log model """ LOG_CHOICES = ( ('1', 'DONE'), ('2', 'WIP') ) log_type = models.CharField(max_length=10, choices=LOG_CHOICES, default='') message = models.TextField() scrum = models.ForeignKey(Scrum, on_delete=models.CASCADE, default='') def __str__(self): return self.message class Issue(models.Model): """ User's issue model """ STATUS_CHOICES = ( ('R', 'Resolved'), ('P', 'Pending'), ('C', 'Closed') ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='P') issue = models.TextField() is_urgent = models.BooleanField(default=False) scrum = models.ForeignKey(Scrum, on_delete=models.CASCADE) deadline = models.DateTimeField(null=True, blank=True) def __str__(self): return self.issue
import dpkt import socket import json import collections as cl import re def main(): # define node f = open ("/root/pcap/cbnoc_node.json") json_data = json.load(f) # read pcap filename = u'/root/pcap/test.pcap' pcr = dpkt.pcap.Reader(open(filename,'rb')) packet_count = 0 flow_list = {} for ts,buf in pcr: packet_count += 1 try: eth = dpkt.ethernet.Ethernet(buf) except: print 'Fail parse FrameNo:', packet_count, '. skipped.' continue if type(eth.data) == dpkt.ip.IP: ip = eth.data src = socket.inet_ntoa(ip.src) dst = socket.inet_ntoa(ip.dst) flow_word = src + "to" + dst if flow_list.has_key(flow_word): flow_list[flow_word] += len(str(buf)) else: flow_list[flow_word] = len(str(buf)) for k,v in flow_list.iteritems(): srcdst = k.split("to") # print srcdst[0],':',srcdst[1], ':', v, '[Byte]' # region region = "CODEBLUE network" # traffic between region srcaddr = intIP(srcdst[0]) dstaddr = intIP(srcdst[1]) if srcaddr in range(intIP('10.1.1.0'),intIP('10.1.1.256')) and not(dstaddr in range(intIP('10.1.1.0'),intIP('10.1.1.256'))): for i in json_data['connections']: if i['source'] == region: # print "a" i['metrics']['normal'] += int(v) if dstaddr in range(intIP('10.1.1.0'),intIP('10.1.1.256')) and not(srcaddr in range(intIP('10.1.1.0'),intIP('10.1.1.256'))): for i in json_data['connections']: if i['target'] == region: print "a" # i['metrics']['normal'] += int(v) # connection for i in json_data['nodes']: if i['name'] == region: # node flag = 0 for j in i['nodes']: if j['name']==srcdst[0]: flag += 1 if j['name']==srcdst[1]: flag += 2 if flag > 2: break if flag==0: # add src and dst i['nodes'].append(mkNode(srcdst[0])) i['nodes'].append(mkNode(srcdst[1])) elif flag==1: i['nodes'].append(mkNode(srcdst[0])) # add src elif flag==2: i['nodes'].append(mkNode(srcdst[1])) # add dst # connection conn1 = {} conn1["source"] = srcdst[0] conn1["target"] = srcdst[1] conn1["metrics"] = ({"normal": v}) conn1["notices"] = () conn1["class"] = "normal" i['connections'].append(conn1) # print(i['connections']) # write JSON wf = open("/root/vizceral-example/dist/sample_data.json","w") json.dump(json_data,wf,indent=4) # end def mkNode(name): node1={} node1["name"] = name node1["node_type"] = "client" node1["class"] = "normal" node1["renderer"] = "focusedChild" return node1 def intIP(ipaddr): i =ipaddr.split(".") j = ((int(i[0])*256+int(i[1]))*256+int(i[2]))*256+int(i[3]) return j if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import xbmc import os import time import shutil import xbmcvfs USERDATA = xbmc.translatePath('special://masterprofile') SMASHINGFOLDER = os.path.join(USERDATA, "smashing") SMASHINGTEMP = os.path.join(USERDATA, "smashing", "smashingtemp") updatefile = os.path.join(SMASHINGTEMP, "miscfiles", "update.txt") # set defaults source = 'not set' target = 'not set' newversion = 'not set' oldversion = 'not set' updateaddonid = 'Addon' fileisold = 'not set' force = 'false' quiet = 'false' invalidtarget = 'false' invalidsource = 'false' age = 1000 # default messages error = 'none' # set default to 'none'; only print if changed error2 = 'none' error3 = 'none' errornotification = 'none' #Makes log easier to follow: def printstar(): print "***************************************************************************************" print "****************************************************************************************" def startaddon(): global thisaddon, source, target, updateaddonid, error, error2 thisaddon = sys.argv[0] printstar() print ('%s has started'% thisaddon) num = len(sys.argv) if num == 1: readupdatefile() else: c = 1 while c < num: check = sys.argv[c] if check[:9] == 'source = ': source = check[9:] source = source.strip() elif check[:7] == 'dest = ': target = check[7:] target = target.strip() elif check[:16] == 'updateaddonid = ': updateaddonid = check[16:] updateaddonid = updateaddonid.strip() elif check == 'choose': chooseupdate() else: error = 'problem in startaddon()' error2 = ('argument not recognised (%s)'% check) errormessage() c = c + 1 checkupdate # errors def errormessage(): global error, error2, errornotification printstar() print ('%s has stopped with an error'% thisaddon) if error in globals(): if not error == 'none': print error if error2 in globals(): if not error2 == 'none': print error2 if error3 in globals(): if not error3 == 'none': print error3 xbmc.executebuiltin('Notification(Problem - check log for details, %s)'% thisaddon) if errornotification in globals(): if not errornotification == 'none': xbmc.sleep(3000) xbmc.executebuiltin('Notification(errornotification)') printstar() cleanup() def removefile(): global error, error2, errornotification print 'running removefile()' print ('DELETEFILE is %s'% DELETEFILE) # delete file # DELETEFILE = the full path of the file to be removed if os.path.exists(DELETEFILE): count = 0 while count < 50: try: os.remove(DELETEFILE) except: pass print ('checking for %s'% DELETEFILE) if not os.path.exists(DELETEFILE): print 'DELETEFILE has been removed' count = count + 50 else: xbmc.sleep(300) print 'Oh no it hasn\'t' count = count + 1 if os.path.exists(DELETEFILE): error = ('Problem with removefile() function in %s.'% thisaddon) error2 = ('Could not delete the file at %s'% DELETEFILE) printstar() errornotification = ('Something went wrong, Could not delete %s'% DELETEFILE) errormessage() else: printstar() print ('%s has deleted %s'% (thisaddon, DELETEFILE)) printstar() # xbmc.executebuiltin('Notification(%s, has been deleted)'% DELETEFILE) xbmc.sleep(300) # remove a folder recursively def removefolder(): global error, error2, errornotification print 'running removefolder()' print ('DELETEFOLDER is %s'% DELETEFOLDER) # delete folder # DELETEFOLDER = the full path of the folder to be removed if os.path.exists(DELETEFOLDER): count = 0 while count < 50: try: shutil.rmtree(DELETEFOLDER) except: pass print ('checking for %s'% DELETEFOLDER) if not os.path.exists(DELETEFOLDER): print 'DELETEFOLDER has been removed' count = count + 50 else: xbmc.sleep(300) print 'Oh no it hasn\'t' count = count + 1 if os.path.exists(DELETEFOLDER): error = ('Problem with removefolder() function in %s.'% thisaddon) error2 = ('Could not delete the folder at %s'% DELETEFOLDER) printstar() errornotification = ('Something went wrong, Could not delete %s'% DELETEFOLDER) errormessage() else: printstar() print ('%s has deleted %s'% (thisaddon, DELETEFOLDER)) printstar() # xbmc.executebuiltin('Notification(%s, has been deleted)'% DELETEFOLDER) xbmc.sleep(300) def oldcopyfolder(): global error, error2, errornotification print 'running copyfolder()' shutil.copytree(source, target) xbmc.sleep(300) if not os.path.isdir(target): error = 'Problem with copyfolder() function' error2 = ('Copyfolder failed (%s to %s)'% (SOURCE, TARGET)) errormessage() def copyfolder(): global error, error2, errornotification, next print 'running copyfolder()' os.mkdir(target) dirs = [] files = [] dirs, files = xbmcvfs.listdir(source) print ('source is: %s'% source) num = len(dirs) print ('num = %d'% num) if num == 0: print 'No subfolders - end of the line' # pass else: c = 0 print 'Subfolders in source are:' while c < num: next = dirs[c] print next targetdir = os.path.join(target, next) if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel2() c = c + 1 num = len(files) print ('num = %d'% num) if num == 0: print 'No files in source' # pass else: c = 0 print 'Files in source are:' while c < num: next = files[c] print next sourcefile = os.path.join(source, next) targetfile = os.path.join(target, next) xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel2(): global next, next2, sourcelevel2, targetlevel2 print 'running copylevel2()' level2files = [] level2dirs = [] sourcelevel2 = os.path.join(source, next) targetlevel2 = os.path.join(target, next) level2dirs, level2files = xbmcvfs.listdir(sourcelevel2) print ('sourcelevel2 is: %s'% sourcelevel2) numlevel2 = len(level2dirs) print ('numlevel2 = %d'% numlevel2) if numlevel2 == 0: print 'No subfolders - end of the line' else: c = 0 print 'Subfolders in sourcelevel2 are:' while c < numlevel2: next2 = level2dirs[c] print next2 targetdir = os.path.join(targetlevel2, next2) if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel3() c = c + 1 numlevel2 = len(level2files) print ('numlevel2 = %d'% numlevel2) if numlevel2 == 0: print 'No files in sourcelevel2' else: c = 0 print 'Files in sourcelevel2 are:' while c < numlevel2: next2 = level2files[c] print next2 sourcefile = os.path.join(sourcelevel2, next2) targetfile = os.path.join(targetlevel2, next2) xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel3(): global next2, next3, sourcelevel3, targetlevel3 print 'running copylevel3()' level3files = [] level3dirs = [] sourcelevel3 = os.path.join(sourcelevel2, next2) targetlevel3 = os.path.join(targetlevel2, next2) level3dirs, level3files = xbmcvfs.listdir(sourcelevel3) print ('sourcelevel3 is: %s'% sourcelevel3) numlevel3 = len(level3dirs) print ('numlevel3 = %d'% numlevel3) if numlevel3 == 0: print 'No subfolders - end of the line' else: c = 0 print 'Subfolders in sourcelevel3 are:' while c < numlevel3: next3 = level3dirs[c] print ('next3 is %s'% next3) targetdir = os.path.join(targetlevel3, next3) if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel4() c = c + 1 numlevel3 = len(level3files) print ('numlevel3 = %d'% numlevel3) if numlevel3 == 0: print 'No files in sourcelevel3' else: c = 0 print 'Files in sourcelevel3 are:' while c < numlevel3: next3 = level3files[c] print ('next3 is %s'% next3) sourcefile = os.path.join(sourcelevel3, next3) print ('copylevel3sourcefile is %s'% sourcefile) targetfile = os.path.join(targetlevel3, next3) print ('copylevel3targetfile is %s'% targetfile) xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel4(): global next3, next4, sourcelevel4, targetlevel4 print 'running copylevel4()' level4files = [] level4dirs = [] sourcelevel4 = os.path.join(sourcelevel3, next3) targetlevel4 = os.path.join(targetlevel3, next3) level4dirs, level4files = xbmcvfs.listdir(sourcelevel4) print ('sourcelevel4 is: %s'% sourcelevel4) numlevel4 = len(level4dirs) if numlevel4 == 0: print 'No subfolders - end of the line' else: c = 0 print 'Subfolders in sourcelevel4 are:' # change 1 number while c < numlevel4: # change 1 number next4 = level4dirs[c] # change 2 numbers print ('next4 is %s'% next4) # change 2 numbers targetdir = os.path.join(targetlevel4, next4) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel5() # change 1 number c = c + 1 numlevel4 = len(level4files) # change 2 numbers print ('numlevel4 = %d'% numlevel4) # change 2 numbers if numlevel4 == 0: print 'No files in sourcelevel4' # change 1 number else: c = 0 print 'Files in sourcelevel4 are:' # change 1 number while c < numlevel4: # change 1 number next4 = level4files[c] # change 2 numbers print ('next4 is %s'% next4) # change 2 numbers sourcefile = os.path.join(sourcelevel4, next4) # change 2 numbers print ('copylevel4sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel4, next4) # change 2 numbers print ('copylevel4targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel5(): # change name global next4, next5, sourcelevel5, targetlevel5 # change 4 numbers print 'running copylevel5()' # change 1 number level5files = [] # change 1 number level5dirs = [] # change 1 number sourcelevel5 = os.path.join(sourcelevel4, next4) # change 3 numbers targetlevel5 = os.path.join(targetlevel4, next4) # change 3 numbers level5dirs, level5files = xbmcvfs.listdir(sourcelevel5) # change 3 numbers # print ('sourcelevel5 is: %s'% sourcelevel5) # change 2 numbers numlevel5 = len(level5dirs) # change 2 numbers # print ('numlevel5 = %d'% numlevel5) # change 2 numbers if numlevel5 == 0: # change 1 number print 'No subfolders - end of the line' else: c = 0 # print 'Subfolders in sourcelevel5 are:' # change 1 number while c < numlevel5: # change 1 number next5 = level5dirs[c] # change 2 numbers # print ('next5 is %s'% next5) # change 2 numbers targetdir = os.path.join(targetlevel5, next5) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel6() # change 1 number c = c + 1 numlevel5 = len(level5files) # change 2 numbers # print ('numlevel5 = %d'% numlevel5) # change 2 numbers if numlevel5 == 0: print 'No files in sourcelevel5' # change 1 number else: c = 0 # print 'Files in sourcelevel5 are:' # change 1 number while c < numlevel5: # change 1 number next5 = level5files[c] # change 2 numbers # print ('next5 is %s'% next5) # change 2 numbers sourcefile = os.path.join(sourcelevel5, next5) # change 2 numbers # print ('copylevel5sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel5, next5) # change 2 numbers # print ('copylevel5targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel6(): # change name global next5, next6, sourcelevel6, targetlevel6 # change 4 numbers print 'running copylevel6()' # change 1 number level6files = [] # change 1 number level6dirs = [] # change 1 number sourcelevel6 = os.path.join(sourcelevel5, next5) # change 3 numbers targetlevel6 = os.path.join(targetlevel5, next5) # change 3 numbers level6dirs, level6files = xbmcvfs.listdir(sourcelevel6) # change 3 numbers # print ('sourcelevel6 is: %s'% sourcelevel6) # change 2 numbers numlevel6 = len(level6dirs) # change 2 numbers # print ('numlevel6 = %d'% numlevel6) # change 2 numbers if numlevel6 == 0: # change 1 number print 'No subfolders - end of the line' else: c = 0 # print 'Subfolders in sourcelevel6 are:' # change 1 number while c < numlevel6: # change 1 number next6 = level6dirs[c] # change 2 numbers # print ('next6 is %s'% next6) # change 2 numbers targetdir = os.path.join(targetlevel6, next6) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel7() # change 1 number c = c + 1 numlevel6 = len(level6files) # change 2 numbers # print ('numlevel6 = %d'% numlevel6) # change 2 numbers if numlevel6 == 0: print 'No files in sourcelevel6' # change 1 number else: c = 0 # print 'Files in sourcelevel6 are:' # change 1 number while c < numlevel6: # change 1 number next6 = level6files[c] # change 2 numbers # print ('next6 is %s'% next6) # change 2 numbers sourcefile = os.path.join(sourcelevel6, next6) # change 2 numbers # print ('copylevel6sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel6, next6) # change 2 numbers # print ('copylevel6targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel7(): # change name global next6, next7, sourcelevel7, targetlevel7 # change 4 numbers print 'running copylevel7()' # change 1 number level7files = [] # change 1 number level7dirs = [] # change 1 number sourcelevel7 = os.path.join(sourcelevel6, next6) # change 3 numbers targetlevel7 = os.path.join(targetlevel6, next6) # change 3 numbers level7dirs, level7files = xbmcvfs.listdir(sourcelevel7) # change 3 numbers # print ('sourcelevel7 is: %s'% sourcelevel7) # change 2 numbers numlevel7 = len(level7dirs) # change 2 numbers # print ('numlevel7 = %d'% numlevel7) # change 2 numbers if numlevel7 == 0: # change 1 number print 'No subfolders - end of the line' else: c = 0 # print 'Subfolders in sourcelevel7 are:' # change 1 number while c < numlevel7: # change 1 number next7 = level7dirs[c] # change 2 numbers # print ('next7 is %s'% next7) # change 2 numbers targetdir = os.path.join(targetlevel7, next7) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel8() # change 1 number c = c + 1 numlevel7 = len(level7files) # change 2 numbers # print ('numlevel7 = %d'% numlevel7) # change 2 numbers if numlevel7 == 0: print 'No files in sourcelevel7' # change 1 number else: c = 0 # print 'Files in sourcelevel7 are:' # change 1 number while c < numlevel7: # change 1 number next7 = level7files[c] # change 2 numbers # print ('next7 is %s'% next7) # change 2 numbers sourcefile = os.path.join(sourcelevel7, next7) # change 2 numbers # print ('copylevel7sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel7, next7) # change 2 numbers # print ('copylevel7targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel8(): # change name global next7, next8, sourcelevel8, targetlevel8 # change 4 numbers print 'running copylevel8()' # change 1 number level8files = [] # change 1 number level8dirs = [] # change 1 number sourcelevel8 = os.path.join(sourcelevel7, next7) # change 3 numbers targetlevel8 = os.path.join(targetlevel7, next7) # change 3 numbers level8dirs, level8files = xbmcvfs.listdir(sourcelevel8) # change 3 numbers # print ('sourcelevel8 is: %s'% sourcelevel8) # change 2 numbers numlevel8 = len(level8dirs) # change 2 numbers # print ('numlevel8 = %d'% numlevel8) # change 2 numbers if numlevel8 == 0: # change 1 number print 'No subfolders - end of the line' else: c = 0 # print 'Subfolders in sourcelevel8 are:' # change 1 number while c < numlevel8: # change 1 number next8 = level8dirs[c] # change 2 numbers # print ('next8 is %s'% next8) # change 2 numbers targetdir = os.path.join(targetlevel8, next8) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel9() # change 1 number c = c + 1 numlevel8 = len(level8files) # change 2 numbers # print ('numlevel8 = %d'% numlevel8) # change 2 numbers if numlevel8 == 0: print 'No files in sourcelevel8' # change 1 number else: c = 0 # print 'Files in sourcelevel8 are:' # change 1 number while c < numlevel8: # change 1 number next8 = level8files[c] # change 2 numbers # print ('next8 is %s'% next8) # change 2 numbers sourcefile = os.path.join(sourcelevel8, next8) # change 2 numbers # print ('copylevel8sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel8, next8) # change 2 numbers # print ('copylevel8targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel9(): # change name global next8, next9, sourcelevel9, targetlevel9 # change 4 numbers print 'running copylevel9()' # change 1 number level9files = [] # change 1 number level9dirs = [] # change 1 number sourcelevel9 = os.path.join(sourcelevel8, next8) # change 3 numbers targetlevel9 = os.path.join(targetlevel8, next8) # change 3 numbers level9dirs, level9files = xbmcvfs.listdir(sourcelevel9) # change 3 numbers # print ('sourcelevel9 is: %s'% sourcelevel9) # change 2 numbers numlevel9 = len(level9dirs) # change 2 numbers # print ('numlevel9 = %d'% numlevel9) # change 2 numbers if numlevel9 == 0: # change 1 number print 'No subfolders - end of the line' else: c = 0 # print 'Subfolders in sourcelevel9 are:' # change 1 number while c < numlevel9: # change 1 number next9 = level9dirs[c] # change 2 numbers # print ('next9 is %s'% next9) # change 2 numbers targetdir = os.path.join(targetlevel9, next9) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel10() # change 1 number c = c + 1 numlevel9 = len(level9files) # change 2 numbers # print ('numlevel9 = %d'% numlevel9) # change 2 numbers if numlevel9 == 0: print 'No files in sourcelevel9' # change 1 number else: c = 0 # print 'Files in sourcelevel9 are:' # change 1 number while c < numlevel9: # change 1 number next9 = level9files[c] # change 2 numbers # print ('next9 is %s'% next9) # change 2 numbers sourcefile = os.path.join(sourcelevel9, next9) # change 2 numbers # print ('copylevel9sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel9, next9) # change 2 numbers # print ('copylevel9targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel10(): # change name global next9, next10, sourcelevel10, targetlevel10 # change 4 numbers print 'running copylevel10()' # change 1 number level10files = [] # change 1 number level10dirs = [] # change 1 number sourcelevel10 = os.path.join(sourcelevel9, next9) # change 3 numbers targetlevel10 = os.path.join(targetlevel9, next9) # change 3 numbers level10dirs, level10files = xbmcvfs.listdir(sourcelevel10) # change 3 numbers # print ('sourcelevel10 is: %s'% sourcelevel10) # change 2 numbers numlevel10 = len(level10dirs) # change 2 numbers # print ('numlevel10 = %d'% numlevel10) # change 2 numbers if numlevel10 == 0: # change 1 number print 'No subfolders - end of the line' else: c = 0 # print 'Subfolders in sourcelevel10 are:' # change 1 number while c < numlevel10: # change 1 number next10 = level10dirs[c] # change 2 numbers # print ('next10 is %s'% next10) # change 2 numbers targetdir = os.path.join(targetlevel10, next10) # change 2 numbers if not os.path.isdir(targetdir): os.mkdir(targetdir) copylevel11() # change 1 number c = c + 1 numlevel10 = len(level10files) # change 2 numbers # print ('numlevel10 = %d'% numlevel10) # change 2 numbers if numlevel10 == 0: print 'No files in sourcelevel10' # change 1 number else: c = 0 # print 'Files in sourcelevel10 are:' # change 1 number while c < numlevel10: # change 1 number next10 = level10files[c] # change 2 numbers # print ('next10 is %s'% next10) # change 2 numbers sourcefile = os.path.join(sourcelevel10, next10) # change 2 numbers # print ('copylevel10sourcefile is %s'% sourcefile) # change 1 number targetfile = os.path.join(targetlevel10, next10) # change 2 numbers # print ('copylevel10targetfile is %s'% targetfile) # change 1 number xbmcvfs.copy(sourcefile, targetfile) # overwrites existing file if present c = c + 1 def copylevel11(): # change 1 number global problem, listproblemfolders, next10, sourcelevel10 # change 2 numbers sourcefoldernotprocessed = os.path.join(sourcelevel10, next10) # change 2 numbers listproblemfolders.append(sourcefoldernotprocessed) print 'running copylevel11' # change 1 number print 'That means not everything has been copied!' problem = 'true' def readupdatefile(): global source, target, force, quiet, oldfile, DELETEFILE print 'running readupdatefile()' # read settings if os.path.isfile(updatefile): f = open(updatefile, "r") lines = f.readlines() f.close() num = len(lines) if num > 0: c = 0 while c < num: check = lines[c] if check[:9] == 'source = ': source = check[9:] source = source.strip() elif check[:7] == 'dest = ': target = check[7:] target = target.strip() elif check[:13] == 'newversion = ': newversion = check[13:] newversion = newversion.strip() elif check[:13] == 'oldversion = ': oldversion = check[13:] oldversion = oldversion.strip() elif check[:16] == 'updateaddonid = ': updateaddonid = check[16:] updateaddonid = updateaddonid.strip() elif check[:5] == 'force': force = 'true' elif check[:5] == 'quiet': force = 'quiet' elif check[:1] == "": pass elif check[:1] == '#': pass c = c + 1 # get time since updatefile was modified: st=os.stat(updatefile) mtime=st.st_mtime now = time.time() age = now - mtime msg = 'file is %d seconds old'% age # print settings print ('source is %s'% source) print ('target is %s'% target) print ('newversion is %s'% newversion) print ('oldversion is %s'% oldversion) print ('updateaddonid is %s'% updateaddonid) print ('force = %s'% force) print ('quiet = %s'% quiet) if not age == 1000: if age < 2: xbmc.sleep(2000) now = time.time() age = now - mtime msg = 'file is %d seconds old'% age print msg xbmc.executebuiltin('Notification(File checked:, %s)'% msg) if age > 10: oldfile = 'true' # DELETEFILE = updatefile # removefile() def checkupdate(): global source, target, force, quiet, age, invalidtarget, invalidsource, DELETEFOLDER print 'running checkupdate' if target == 'not set': chooseaddon() if source == 'not set': choosesource() if not os.path.isdir(target): invalidtarget = 'true' chooseaddon() if not os.path.isdir(source): invalidsource = 'true' choosesource() if age > 10: checkoldupdatefile() DELETEFOLDER = target removefolder() copyfolder() cleanup() def chooseaddon(): global target, invalidtarget print 'running chooseaddon()' def choosesource(): global target, source, invalidsource print 'running choosesource()' def checkoldupdatefile(): global age print 'running checkoldupdatefile()' def chooseupdate(): global source, target, DELETEFOLDER print 'running chooseupdate()' def cleanup(): print 'running cleanup()' # xbmc.executebuiltin('Notification(%s, finished)'% thisaddon) xbmc.executebuiltin('Notification(%s, has been updated)'% updateaddonid) exit() startaddon() readupdatefile() checkupdate()
import pytest from qtpy import PYQT6, PYSIDE6 @pytest.mark.skipif(PYQT6, reason="Not complete in PyQt6") @pytest.mark.skipif(PYSIDE6, reason="Not complete in PySide6") def test_qt3dcore(): """Test the qtpy.Qt3DCore namespace""" Qt3DCore = pytest.importorskip("qtpy.Qt3DCore") assert Qt3DCore.QPropertyValueAddedChange is not None assert Qt3DCore.QSkeletonLoader is not None assert Qt3DCore.QPropertyNodeRemovedChange is not None assert Qt3DCore.QPropertyUpdatedChange is not None assert Qt3DCore.QAspectEngine is not None assert Qt3DCore.QPropertyValueAddedChangeBase is not None assert Qt3DCore.QStaticPropertyValueRemovedChangeBase is not None assert Qt3DCore.QPropertyNodeAddedChange is not None assert Qt3DCore.QDynamicPropertyUpdatedChange is not None assert Qt3DCore.QStaticPropertyUpdatedChangeBase is not None assert Qt3DCore.ChangeFlags is not None assert Qt3DCore.QAbstractAspect is not None assert Qt3DCore.QBackendNode is not None assert Qt3DCore.QTransform is not None assert Qt3DCore.QPropertyUpdatedChangeBase is not None assert Qt3DCore.QNodeId is not None assert Qt3DCore.QJoint is not None assert Qt3DCore.QSceneChange is not None assert Qt3DCore.QNodeIdTypePair is not None assert Qt3DCore.QAbstractSkeleton is not None assert Qt3DCore.QComponentRemovedChange is not None assert Qt3DCore.QComponent is not None assert Qt3DCore.QEntity is not None assert Qt3DCore.QNodeCommand is not None assert Qt3DCore.QNode is not None assert Qt3DCore.QPropertyValueRemovedChange is not None assert Qt3DCore.QPropertyValueRemovedChangeBase is not None assert Qt3DCore.QComponentAddedChange is not None assert Qt3DCore.QNodeCreatedChangeBase is not None assert Qt3DCore.QNodeDestroyedChange is not None assert Qt3DCore.QArmature is not None assert Qt3DCore.QStaticPropertyValueAddedChangeBase is not None assert Qt3DCore.ChangeFlag is not None assert Qt3DCore.QSkeleton is not None
import tempfile import pathlib import asyncio from minikerberos.common.ccache import CCACHE from minikerberos.common.kirbi import Kirbi import pytest import shutil import os from .config import * def test_ccacheroast(): from minikerberos.examples.ccacheroast import ccacheroast ccache = CCACHE() with tempfile.NamedTemporaryFile() as f: for kirbifile in get_testfiles_kirbi(): kirbi = Kirbi.from_file(kirbifile) ccache.add_kirbi(kirbi) ccache.to_file(f.name) ccacheroast(f.name) assert len(ccache.get_hashes()) > 0 # testcases for spnroast @pytest.mark.asyncio async def test_spnroast_base(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, KERBEROS_KERBEROAST_USER, KERBEROS_DOMAIN, f.name) f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 @pytest.mark.asyncio async def test_spnroast_23(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, KERBEROS_KERBEROAST_USER, KERBEROS_DOMAIN, f.name, etypes=23) f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 @pytest.mark.asyncio async def test_spnroast_all(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, KERBEROS_KERBEROAST_USER, KERBEROS_DOMAIN, f.name, etypes='23,17,18') f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 @pytest.mark.asyncio async def test_spnroast_list(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, [KERBEROS_KERBEROAST_USER], KERBEROS_DOMAIN, f.name) f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 @pytest.mark.asyncio async def test_spnroast_file(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile('w') as d: d.write(KERBEROS_KERBEROAST_USER) d.flush() with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, d.name, KERBEROS_DOMAIN, f.name) f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 @pytest.mark.asyncio async def test_spnroast_filedomain(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile('w') as d: d.write(KERBEROS_KERBEROAST_USER + '@' + KERBEROS_DOMAIN) d.flush() with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, d.name, None, f.name) f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 @pytest.mark.asyncio async def test_spnroast_listdomain(): from minikerberos.examples.spnroast import spnroast with tempfile.NamedTemporaryFile() as f: x = await spnroast(KERBEROS_CONN_URL_PW, [KERBEROS_KERBEROAST_USER + '@' + KERBEROS_DOMAIN], KERBEROS_DOMAIN, f.name) f.flush() f.seek(0,0) data = f.read() assert len(data) > 0 def test_kirbi2ccache(): from minikerberos.examples.kirbi2ccache import kirbi2ccache ccache = CCACHE() for kirbifile in get_testfiles_kirbi(): kirbi = Kirbi.from_file(kirbifile) ccache.add_kirbi(kirbi) with tempfile.NamedTemporaryFile() as f: kirbi2ccache(kirbifile, f.name) ccache2 = CCACHE.from_file(f.name) assert len(ccache2.get_hashes()) > 0 @pytest.mark.asyncio async def test_gettgt(): from minikerberos.examples.getTGT import getTGT with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getTGT(KERBEROS_CONN_URL_PW, d.name, f.name) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None @pytest.mark.asyncio async def test_gettgt_nopac(): from minikerberos.examples.getTGT import getTGT with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getTGT(KERBEROS_CONN_URL_PW, d.name, f.name, nopac=True) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None @pytest.mark.asyncio async def test_gettgs(): from minikerberos.examples.getTGS import getTGS with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getTGS(KERBEROS_CONN_URL_PW, KERBEROS_TGS_SPN ,d.name, f.name) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None @pytest.mark.asyncio async def test_getS4U2Self(): from minikerberos.examples.getS4U2self import getS4U2self with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getS4U2self(KERBEROS_CONN_URL_MACHINE, KERBEROS_DELEGATION_SPN_SELF, KERBEROS_DELEGATION_USER_SELF,d.name, f.name) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None @pytest.mark.asyncio async def test_getS4U2Self_ccache(): import os from minikerberos.examples.getS4U2self import getS4U2self from minikerberos.examples.getTGT import getTGT try: await getTGT(KERBEROS_CONN_URL_MACHINE, ccachefile='test.ccache') with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getS4U2self(KERBEROS_CONN_URL_MACHINE_CCACHE, KERBEROS_DELEGATION_SPN_SELF, KERBEROS_DELEGATION_USER_SELF,d.name, f.name) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None finally: os.remove('test.ccache') @pytest.mark.asyncio async def test_getS4U2proxy(): from minikerberos.examples.getS4U2proxy import getS4U2proxy with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getS4U2proxy(KERBEROS_CONN_URL_MACHINE, KERBEROS_DELEGATION_SPN_PROXY, KERBEROS_DELEGATION_USER_PROXY, d.name, f.name) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None @pytest.mark.asyncio async def test_getS4U2proxy_ccache(): import os from minikerberos.examples.getS4U2proxy import getS4U2proxy from minikerberos.examples.getTGT import getTGT try: await getTGT(KERBEROS_CONN_URL_MACHINE, ccachefile='test.ccache') with tempfile.NamedTemporaryFile() as d: with tempfile.NamedTemporaryFile() as f: await getS4U2proxy(KERBEROS_CONN_URL_MACHINE_CCACHE, KERBEROS_DELEGATION_SPN_PROXY, KERBEROS_DELEGATION_USER_PROXY,d.name, f.name) ccache = CCACHE.from_file(f.name) assert len(ccache.get_hashes()) > 0 kirbi = Kirbi.from_file(d.name) assert kirbi.kirbiobj is not None finally: os.remove('test.ccache') @pytest.mark.asyncio async def test_getnt(): from minikerberos.examples.getNT import get_NT #moving certificate to current path... current_file_path = pathlib.Path(__file__).parent.absolute() cert_file_path = current_file_path.joinpath('testdata', 'test.pfx') try: shutil.copy(cert_file_path, 'a.pfx') results = await get_NT(KERBEROS_CONN_URL_PKINIT_PFX) assert len(results) > 0 finally: os.remove('a.pfx') @pytest.mark.asyncio async def test_cve_2022_33679(): from minikerberos.examples.CVE_2022_33679 import exploit with tempfile.NamedTemporaryFile() as f: await exploit(KERBEROS_CONN_URL_ASREP_MD4ARC4, f.name) kirbi = Kirbi.from_file(f.name) assert kirbi.kirbiobj is not None if __name__ == '__main__': asyncio.run(test_spnroast_base())
import numpy as np import mnist #Get data set from import matplotlib.pyplot as plt #Graph import tensorflow as tf import timeit from keras.models import Sequential #ANN architecture from keras.layers import Dense #The layers in the ANN from keras.utils import to_categorical from keras.layers import Activation, Dense from keras.models import Sequential from keras.layers import Dense from keras.datasets import mnist from keras import models from keras import layers from keras.utils import to_categorical #### custom AF #### from keras.layers import Activation from keras import backend as K from keras.utils.generic_utils import get_custom_objects from try_5feb import gunjan_activation get_custom_objects().update({'gunjan_activation': Activation(gunjan_activation)}) (train_images, train_labels), (test_images, test_labels) = mnist.load_data() network = models.Sequential() network.add(layers.Dense(784, activation='tanh', input_shape=(28 * 28,))) network.add(layers.Dense(784, activation='relu', input_shape=(28 * 28,))) network.add(layers.Dense(10, activation='softmax')) network.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # network = models.Sequential() # network.add(layers.Dense(784, activation='relu', input_shape=(28 * 28,))) # network.add(layers.Dense(784, activation='relu', input_shape=(28 * 28,))) # network.add(layers.Dense(10, activation='softmax')) # network.compile(optimizer='adam', # loss='categorical_crossentropy', # metrics=['accuracy']) train_images = train_images.reshape((60000, 28 * 28)) train_images = train_images.astype('float32') / 255 test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) network.fit(train_images, train_labels, epochs=50, batch_size=128) test_loss, test_acc = network.evaluate(test_images, test_labels) plot(train_images, train_labels) print('test_acc:', test_acc, 'test_loss', test_loss)
import json def read_json(path): try: with open(path, 'r') as f: data = json.load(f) return data except FileNotFoundError: return list()
from django.apps import AppConfig class ViewratingsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'viewRatings'
from .base import ( # noqa load_middlewares, ) from .blockchain.base import ( # noqa NoFurtherBlockchainMiddlewares, StopReceiveBallot, BaseBlockchainMiddleware, ) from .consensus.base import ( # noqa NoFurtherConsensusMiddlewares, StopStore, StopBroadcast, BaseConsensusMiddleware, )