'''Reads data files in input folder(home by default, -Gi is flag for passing new one) then calls GDDcalculator.py,
 passes lists of maximum and minimum temperatures also base and upper, takes list of GDD from that and concatenates it
 with associated Data Frame'''
from GDDcalculate import *
import argparse
import pandas as pd
import glob

print("GDD.py starts")
parser = argparse.ArgumentParser(description="Calculating GDD")  # Argument parser for command-line friendly script
parser.add_argument("-tbase", "-b", type=float, default=10, help="Base temperature")  # takes base temperature
parser.add_argument("-tupper", "-u", type=float, default=30, help="Upper temperature")  # takes upper temperature
parser.add_argument("-GDDinfolder", "-Gi", type=str, default="./input/", help="Folder containing GDD input files.")
parser.add_argument("-GDDoutfolder", "-Go", type=str, default="./input/", help="Folder that will keep GDD output files.")

args = parser.parse_args()

for fname in glob.glob(args.GDDinfolder + "*.csv"):  # For loop for .csv files in given input folder
    D = pd.read_csv(fname, header=0)  # skipped rows will change if data frame's shape change###############IMPORTANT
    df = pd.DataFrame(D)
    print(df.columns.values)

    tempmax = df["Max Temp (°C)"]
    tempmin = df["Min Temp (°C)"]  # Data frame's column

    year = list(df['Year'])[1]  # Just so that we can name final file!
    name = list(df['Name'])[1]
    length = len(pd.Series.dropna(tempmin))  # omits None values and gets actual length

    GDD = GDDcalculate(list(tempmin), list(tempmax), args.tbase, args.tupper, length)  # Calls GDD calculator
    df["GDD"] = GDD  # Adds new columnsto Data frame
    df.to_csv(args.GDDoutfolder + str(name)+"_"+str(year)+ ".csv")


from PIL import Image
import os

def Re_size(path):
    iPhone5_WIDTH = 1136
    iPhone5_HEIGHT = 640
    new_path=r"\\new\\"
    name_list=os.listdir(path)
    for name in name_list:
        photo=Image.open(path+name)
        w, h = photo.size
        print(name)
        if w>iPhone5_WIDTH:
            w=iPhone5_WIDTH
            h=h*iPhone5_WIDTH//w
        if h>iPhone5_HEIGHT:
            h=iPhone5_HEIGHT
            w=w*iPhone5_HEIGHT//h
        resize_photo=photo.resize((w,h),Image.ANTIALIAS)# ANTIALIAS滤镜缩放
        resize_photo.save(os.getcwd()+new_path+name)
        print(name)

if __name__ == '__main__':
    Re_size(r".//photos//")


import numpy as np
import pandas as pd
import seaborn as sns

from nninst.backend.tensorflow.attack.common import example_similarity

threshold = 0.5
attack_name = "original"

name = "alexnet_imagenet"
label = "import"
class_to_similarity = {}
for class_id in range(0, 1000, 100):
    similarity = example_similarity(
        name=name,
        threshold=threshold,
        class_id=class_id,
        attack_name=attack_name,
        label=label,
        example_trace_fn=None,
        class_trace_fn=None,
        image_ids=None,
    ).load()
    class_to_similarity[class_id] = similarity

similarity_col = np.concatenate(
    [class_to_similarity[class_id] for class_id in range(0, 1000, 100)]
)
class_col = np.concatenate(
    [
        [str(class_id)] * len(class_to_similarity[class_id])
        for class_id in range(0, 1000, 100)
    ]
)
plot_df = pd.DataFrame({"Similarity": similarity_col, "Class": class_col})
plot_df.info()

ax = sns.boxplot(x="Class", y="Similarity", data=plot_df)
ax.set_ylim(bottom=0, top=1)
fig = ax.get_figure()
# fig.savefig("example_similarity_alexnet_imagenet.pdf", bbox_inches="tight")
fig.savefig("example_similarity_alexnet_imagenet.png", bbox_inches="tight")

summary_df = plot_df.groupby("Class").agg(["mean", "std"]).reset_index()
summary_df.to_csv("example_similarity_alexnet_imagenet.csv", index=False)


import math
import numpy as np

def prime(upto):
    # Return prime numbers

    primes=np.arange(3,upto+1,2)
    isprime=np.ones((upto-1)/2,dtype=bool)
    for factor in primes[:int(math.sqrt(upto))]:
        if isprime[(factor-2)/2]: isprime[(factor*3-2)/2::factor]=0

    return np.insert(primes[isprime],0,2)


import uuid
from django_countries.fields import CountryField

from django.db import models
from django.db.models import Sum
from django.conf import settings

from products.models import Product
from profiles.models import UserProfile

class Order(models.Model):
    """
    * Creates the order in database. Also contains functions to generate a \
    random order number, update the grand total when a line item is added and \
        override save method to set the order number if it has not been set

    \n Returns __str__:
    * the order number
    """
    order_number = models.CharField(max_length=32, null=False, editable=False)
    full_name = models.CharField(max_length=50, null=False, blank=False)
    email = models.EmailField(max_length=254, null=False, blank=False)
    phone_number = models.CharField(max_length=20, null=False, blank=False)
    country = CountryField(blank_label='Country *', null=False, blank=False)
    postcode = models.CharField(max_length=20, null=True, blank=True)
    town_or_city = models.CharField(max_length=40, null=False, blank=False)
    street_address1 = models.CharField(max_length=80, null=False, blank=False)
    street_address2 = models.CharField(max_length=80, null=True, blank=True)
    county = models.CharField(max_length=80, null=True, blank=True)
    date = models.DateTimeField(auto_now_add=True)
    delivery_cost = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        null=False, default=0
    )
    order_total = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        null=False, default=0
    )
    grand_total = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        null=False, default=0
    )
    original_bag = models.TextField(null=False, blank=False, default='')
    stripe_pid = models.CharField(
        max_length=254,
        null=False,
        blank=False,
        default=''
    )
    user_profile = models.ForeignKey(UserProfile,
                                     on_delete=models.SET_NULL,
                                     null=True,
                                     blank=True,
                                     related_name='orders')

    def _generate_order_number(self):
        """
        Generates a random, unique order number using UUID

        \n Returns:
        * the unique number
        """
        return uuid.uuid4().hex.upper()

    def update_total(self):
        """ update_total:

        * Update grand total when a line item is added,
        check if order value requires delivery cost and
        adding delivery if needed.

        \n Args:
        1. self: the order

        \n Saves:
        * saves the updated grand_total
        """
        self.order_total = self.lineitems.aggregate(
            Sum('lineitem_total'))['lineitem_total__sum'] or 0
        if self.order_total < settings.FREE_DELIVERY_THRESHOLD:
            del_per = settings.STANDARD_DELIVERY_PERCENTAGE
            self.delivery_cost = self.order_total * del_per / 100
        else:
            self.delivery_cost = 0
        self.grand_total = self.order_total + self.delivery_cost
        self.save()

    def save(self, *args, **kwargs):
        """ save:

        * Override save method to set the order number
        if it has not been set already.

        \n Args:
        1. self: the order
        2. *args:
        3. **kwargs

        \n Save:
        * saves the order with the arguments
        """
        if not self.order_number:
            self.order_number = self._generate_order_number()
        super().save(*args, **kwargs)

    def __str__(self):
        return self.order_number

class OrderLineItem(models.Model):
    """
    * Creates the order line items. Also contains function to \
         override the save method to set the line-item total

    \n Returns __str__:
    * the sku on order number
    """
    order = models.ForeignKey(
        Order,
        null=False,
        blank=False,
        on_delete=models.CASCADE,
        related_name='lineitems'
    )
    product = models.ForeignKey(
        Product,
        null=False,
        blank=False,
        on_delete=models.CASCADE
    )
    product_size = models.CharField(
        max_length=2,
        null=True,
        blank=True
    )
    quantity = models.IntegerField(
        null=False,
        blank=False,
        default=0
    )
    lineitem_total = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        null=False,
        blank=False,
        editable=False
    )

    def save(self, *args, **kwargs):
        """ save:

    * Override save method to set the line-item total

    \n Args:
    1. self: the order
    2. *args:
    3. **kwargs

    \n Save:
    * saves line-item with args
    """
        self.lineitem_total = self.product.price * self.quantity
        super().save(*args, **kwargs)

    def __str__(self):
        return f'SKU {self.product.sku} on order {self.order.order_number}'


import requests
import urllib.request, urllib.parse, urllib.error
import subprocess
from ha import *

def notify(notificationType, message):
    servers = subprocess.check_output("avahi-browse -tp --resolve _notification._tcp" ,shell=True).decode().split("\n")
    if servers == [""]:
        log("notificationClient", "server not found")
    else:
        for server in servers:
            serverData = server.split(";")
            if len(serverData) > 6:
                host = serverData[6]
                port = serverData[8]
                url = "http://"+host+":"+port+"/notify?eventType="+notificationType+"&message="+urllib.parse.quote(message)
                request = requests.get(url)
                if request.status_code != 200:
                    log("notificationClient", "error", url, request.status_code)
                break


# -*- coding:utf-8 -*-
# @Author         : 江湖一笑
# @Time           : 2020/4/30 8:27
# @Software       : Web-Autotest-Python
# @Python_verison : 3.7
'''
关于动态提示信息的定位
'''
from time import sleep
from selenium import webdriver
import unittest

class Test_Kong(unittest.TestCase):
    '''孔夫子旧书网操作类'''
    @classmethod
    def setUpClass(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(6)
        self.driver.maximize_window()
        self.driver.get('https://login.kongfz.com/')

    @classmethod
    def tearDownClass(self):
        self.driver.quit()

    def setUp(self):
        print('用例执行start：')

    def tearDown(self):
        print('用例执行end：')

    def test_01username_error(self):
        '''用户名不存在测试用例'''
        self.driver.find_element_by_xpath('//input[@id="username"]').send_keys('jinaghuyixiao1')
        sleep(1)
        self.driver.find_element_by_xpath('//input[@id="password"]').send_keys('jianghu1234')
        sleep(10)               # 等待手工输入验证码
        self.driver.find_element_by_xpath('//input[@class="login_submit btn_red_h40"]').click()
        sleep(3)
        # 获取用户名不存在的提示信息
        username_error_info = self.driver.find_element_by_xpath('//label[@id="username-error"]').text
        print(username_error_info)

if __name__ == '__main__':
    unittest.main()

'''
用例执行start：
用户名不存在
用例执行end：
'''

第五章-API高级操作/动态提示文字定位问题示例孔夫子网06.py

动态提示文字定位问题示例孔夫子网06.py


from app.oled import OLED
from app import wifimgr

import machine
import time
import gc

oled = OLED.instance()

try:
  import usocket as socket
except:
  import socket

led = machine.Pin(2, machine.Pin.OUT)

try:
    oled.text("Init AP server...")
    wlan = wifimgr.get_connection()
    if wlan is None:
        oled.text("  Connect failed")
        oled.text("  EXIT!")
        while True:
            pass
except OSError as e:
    print('wifi manager error:\n')
    print(e)
    oled.text("   Exception!")
    while True:
        pass

# Main Code goes here, wlan is a working network.WLAN(STA_IF) instance.

oled.reset()
oled.text("   ESP32 App")
oled.text("ip:" + wifimgr.device_server_ip)
oled.text("")
oled.text(" listening...")

def web_page():

  print('opening webpage')

  gpio_state="OFF"
  if led.value() == 1:
    gpio_state="ON"

  f_html = open('./html/main.html', 'r')
  f_css = open('./css/styles.css', 'r')

  css = f_css.read()
  html = f_html.read()

  if None != html and None != css:
    css = "<style type='text/css'>" + str(css) + "</style>"
    response = html.format(css_styles=css, gpio_state=gpio_state)
    return response
  else:
    return "Unknown Server Exception."

try:
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind(('', 80))
  s.listen(5)
except OSError as e:
  machine.reset()

while True:
  try:
    if gc.mem_free() < 102000:
      gc.collect()
    conn, addr = s.accept()
    conn.settimeout(3.0)

    print('Got a connection from %s' % str(addr))
    oled.textPosV("in:" + str(addr[0]), y=5)

    request = conn.recv(1024)
    conn.settimeout(None)
    request = str(request)

    print('Content = %s' % request)

    led_on = request.find('/?led=on')
    led_off = request.find('/?led=off')
    if led_on == 6:
      print('LED ON')
      oled.textPosV(' cmd: LED ON', y=6)
      led.value(1)
    if led_off == 6:
      print('LED OFF')
      oled.textPosV(' cmd: LED OFF', y=6)
      led.value(0)

    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)
    conn.close()

    time.sleep(3)
    oled.textPosV(" listening...", y=4)
    oled.text("")

  except OSError as e:
    conn.close()
    oled.text('Connection closed')
    print('Connection closed')


'''Based on https://github.com/google-research/dads'''

from gym.spaces import Tuple, Discrete, Dict
import logging
import numpy as np
import tree
from collections import defaultdict

import ray
from ray.rllib.agents.qmix.mixers import VDNMixer, QMixer
from ray.rllib.agents.qmix.model import RNNModel, _get_size
from ray.rllib.agents.ppo.ppo_torch_policy import ppo_surrogate_loss, vf_preds_fetches, ValueNetworkMixin, kl_and_loss_stats
from ray.rllib.env.multi_agent_env import ENV_STATE
from ray.rllib.env.wrappers.group_agents_wrapper import GROUP_REWARDS
from ray.rllib.evaluation.metrics import LEARNER_STATS_KEY
from ray.rllib.evaluation.postprocessing import compute_gae_for_sample_batch, \
    Postprocessing
from ray.rllib.models.torch.torch_action_dist import TorchCategorical
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.torch_policy import TorchPolicy
from ray.rllib.policy.rnn_sequencing import chop_into_sequences
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.models.catalog import ModelCatalog
from ray.rllib.models.modelv2 import _unpack_obs, restore_original_dimensions
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.annotations import override
from ray.rllib.utils.torch_ops import apply_grad_clipping, \
    convert_to_torch_tensor, explained_variance, sequence_mask, \
    convert_to_non_torch_type
from ray.rllib.agents.custom_ppo.skill_dynamics_model import SkillDynamics
from ray.rllib.agents.custom_ppo.model import PPODADSAgent
from ray.rllib.execution.rollout_ops import StandardizeFields
from ray.rllib.utils.sgd import minibatches, standardize

# Torch must be installed.
torch, nn = try_import_torch(error=True)

logger = logging.getLogger(__name__)

class DADSPPOPolicy(TorchPolicy):
    def __init__(self, obs_space, action_space, config):

        # update policy attr for loss calculation
        self.framework = config['framework'] = 'torch'
        self.kl_coeff = config['kl_coeff']
        self.kl_target = config['kl_target']
        self.entropy_coeff = config['entropy_coeff']
        self.cur_lr = config['lr']
        # setup ._value() for gae computation
        self.setup_value(config)
        self.dist_class, logit_dim = ModelCatalog.get_action_dist(
                    action_space, config["model"], framework='torch')

        self.model = PPODADSAgent(obs_space, action_space, logit_dim,
                                  config['model'], name='ppo_dads_agent')

        super().__init__(obs_space, action_space, config,
                         model=self.model,
                         loss=None, # we calculate the loss inside learn_on_batch
                         action_distribution_class=self.dist_class
                         )
        # Merge Model's view requirements into Policy's.
        self.view_requirements.update(self.model.view_requirements)
        # Perform test runs through postprocessing- and loss functions.
        self._initialize_loss_from_dummy_batch(
            auto_remove_unneeded_view_reqs=True,
            stats_fn=None,
        )
        self.ppo_opt = torch.optim.Adam(self.model.parameters(), lr=self.config["lr"])
        self.minibatch_size = config['sgd_minibatch_size']
        self.ppo_epochs = config['ppo_epochs']
        self.dynamics_epochs = config['dynamics_epochs']
        self.use_dynamics = config['use_dynamics']
        # create dynamics model
        if self.use_dynamics:
            self.dynamics = SkillDynamics(self.config)
            self.dynamics_opt = torch.optim.Adam(self.dynamics.parameters(), lr=self.config["dynamics_lr"])

    @override(TorchPolicy)
    def postprocess_trajectory(self,
                                   sample_batch,
                                   other_agent_batches=None,
                                   episode=None):
        return sample_batch

    @override(TorchPolicy)
    def compute_actions_from_input_dict(self,
                                        input_dict,
                                        explore=None,
                                        timestep=None,
                                        episodes=None,
                                        **kwargs):

        explore = explore if explore is not None else self.config["explore"]
        with torch.no_grad():
            input_dict = self._lazy_tensor_dict(input_dict)
            # state_batches for RNN
            state_batches = [
                input_dict[k] for k in input_dict.keys() if "state_in" in k[:8]
            ]
            seq_lens = np.array([1] * len(input_dict["obs"])) if state_batches else None
            dist_inputs, state_out = self.model(input_dict, state_batches, seq_lens)
            action_dist = self.dist_class(dist_inputs, self.model)
            # Get the exploration action from the forward results.
            actions, logp = \
                self.exploration.get_exploration_action(
                    action_distribution=action_dist,
                    timestep=timestep,
                    explore=explore)
            # add extra info to the trajectory
            extra_info = {}
            # get values from the critic after doing inference for the actions
            extra_info[SampleBatch.VF_PREDS] = self.model.value_function()
            # Action-dist inputs.
            if dist_inputs is not None:
                extra_info[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs

            # Action-logp and action-prob.
            if logp is not None:
                extra_info[SampleBatch.ACTION_PROB] = \
                    torch.exp(logp.float())
                extra_info[SampleBatch.ACTION_LOGP] = logp

            # Update our global timestep by the batch size.
            self.global_timestep += len(input_dict[SampleBatch.CUR_OBS])

            return convert_to_non_torch_type((actions, state_out, extra_info))

    @override(TorchPolicy)
    def learn_on_batch(self, train_batch):
        # print(type(train_batch))
        # Turn the values into tensors
        # train_batch_tensor = self._lazy_tensor_dict(train_batch)
        # train_batch_tensor = train_batch_tensor
        # restore_original_dimensions()
        # print(train_batch_tensor.keys())
        # update the skill dynamics

        # Set Model to train mode.
        if self.model:
            self.model.train()
        if self.dynamics:
            self.dynamics.train()

        stats = defaultdict(int)
        if self.use_dynamics:
            c = 0
            for ep in range(self.dynamics_epochs):
                for mb in minibatches(train_batch, self.minibatch_size): # minibatches(train_batch.copy(), self.minibatch_size)
                    c += 1
                    mb["is_training"] = True
                    minibatch = self._lazy_tensor_dict(mb)

                    obs = _unpack_obs(minibatch['obs'],
                                        self.model.options['orig_obs_space'],torch)
                    next_obs = _unpack_obs(minibatch['new_obs'],
                                        self.model.options['orig_obs_space'],torch)
                    dynamics_obs = obs['dynamics_obs']
                    next_dynamics_obs = next_obs['dynamics_obs'] - obs['dynamics_obs']
                    z = obs['z']

                    log_prob = self.dynamics.get_log_prob(dynamics_obs,z,next_dynamics_obs,training=True)
                    dynamics_loss = -torch.mean(log_prob)
                    orth_loss = self.dynamics.orthogonal_regularization()
                    l2_loss = self.dynamics.l2_regularization()
                    if self.config['dynamics_orth_reg']:
                        dynamics_loss += orth_loss
                    if self.config['dynamics_l2_reg'] and not self.config['dynamics_spectral_norm']:
                        dynamics_loss += l2_loss
                    self.dynamics_opt.zero_grad()
                    dynamics_loss.backward()
                    if self.config['grad_clip']:
                        grad_norm = nn.utils.clip_grad_norm_(
                            self.dynamics.parameters(), self.config['grad_clip'])
                    self.dynamics_opt.step()
                    stats['dynamics_loss'] += dynamics_loss.item()
                    stats['orth_loss'] += orth_loss.item()
                    stats['l2_loss'] += l2_loss.item()
            stats['dynamics_loss'] /= c
            stats['orth_loss'] /= c
            stats['l2_loss'] /= c

            self.dynamics.eval()
            # compute intrinsic reward
            with torch.no_grad():
                batch = self._lazy_tensor_dict(train_batch)
                obs = _unpack_obs(batch['obs'],
                                        self.model.options['orig_obs_space'],torch)
                next_obs = _unpack_obs(batch['new_obs'],
                                    self.model.options['orig_obs_space'],torch)
                z = obs['z']
                dynamics_obs = obs['dynamics_obs']
                next_dynamics_obs = next_obs['dynamics_obs'] - obs['dynamics_obs']

                dads_reward, info = self.dynamics.compute_reward(dynamics_obs,z,next_dynamics_obs)
                dads_reward = self.config['dads_reward_scale'] * dads_reward.numpy()
                # # replace the reward column in train_batch
                # print(train_batch['rewards'].shape)
                train_batch['rewards'] = dads_reward
                stats['avg_dads_reward'] = dads_reward.mean()
                stats['num_skills_higher_prob'] = info['num_higher_prob']

        # calculate GAE for dads reward here?
        trajs = train_batch.split_by_episode()
        processed_trajs = []
        for traj in trajs:
            processed_trajs.append(compute_gae_for_sample_batch(self,traj))
        batch = SampleBatch.concat_samples(processed_trajs)

        # train_batch = compute_gae_for_sample_batch(self, self._lazy_numpy_dict(train_batch))
        # train_batch = self._lazy_tensor_dict(train_batch)
        # update agent using RL algo
        # split to minibatches
        c = 0
        for ep in range(self.ppo_epochs):
            # batch.shuffle()
            for mb in minibatches(batch, self.minibatch_size):
                c += 1
                mb["is_training"] = True
                # minibatch = mb.copy()
                mb['advantages'] = standardize(mb['advantages'])
                minibatch = self._lazy_tensor_dict(mb)
                # compute the loss
                loss_out = ppo_surrogate_loss(self,self.model,self.dist_class,minibatch)
                # compute gradient
                self.ppo_opt.zero_grad()
                # the learning_rate is already used in ppo_surrogate_loss
                loss_out.backward()
                # grad norm
                if self.config['grad_clip']:
                    grad_norm = nn.utils.clip_grad_norm_(
                        self.model.parameters(), self.config['grad_clip'])
                self.ppo_opt.step()
                # log stats
                stats['ppo_loss'] += loss_out.item()
        stats['ppo_loss'] /= c
        # add more info about the loss
        stats.update(kl_and_loss_stats(self, train_batch))

                #  {
                #     "loss": loss_out.item(),
                #     'test': 1
                #     # "grad_norm": grad_norm
                #     # if isinstance(grad_norm, float) else grad_norm.item(),
                # }
        return {LEARNER_STATS_KEY: stats}

    def setup_value(self, config):
        # When doing GAE, we need the value function estimate on the
        # observation.
        if config["use_gae"]:
            # Input dict is provided to us automatically via the Model's
            # requirements. It's a single-timestep (last one in trajectory)
            # input_dict.
            if config["_use_trajectory_view_api"]:
                def value(**input_dict):
                    model_out, _ = self.model.from_batch(
                        convert_to_torch_tensor(input_dict, self.device),
                        is_training=False)
                    # [0] = remove the batch dim.
                    return self.model.value_function()[0]
        else:
            def value(*args, **kwargs):
                return 0.0

        self._value = value


import sys

def check(mid):
    max_s=min_s=score[0]
    cnt=1
    for i in range(1,n):
        max_s=max(max_s,score[i])
        min_s=min(min_s,score[i])
        if max_s-min_s>mid:
            cnt+=1
            max_s=score[i]
            min_s=score[i]
    return cnt

n,m=map(int, sys.stdin.readline().split())
score=list(map(int, sys.stdin.readline().split()))

l=0
r=max(score)
answer=0
while l<=r:
    mid=(l+r)//2
    if check(mid)<=m:
        r=mid-1
        answer=mid
    else:
        l=mid+1
print(answer)


def sol():
    n = int(input())
    a = []
    for _ in range(n):
        a.append([int(x) for x in input().split()])
    if n == 2: return [a[0][1] // 2] * 2
    b = [ (a[0][1] + a[0][2] - a[1][2]) // 2 ]
    for i in range(1, n):
        b.append(a[0][i] - b[0])
    return b

# drive code
print(*sol())


# -*- coding: utf-8 -*-

from FirrSequence import FirrSequence
import Toolbox
from pylab import *
from matplotlib.ticker import MultipleLocator

#-------------Latex Style--------------
rc('font',**{'family':'serif','serif':['Computer Modern'],'size':'14'})
rc('text', usetex=True)
#--------------------------------------

rc('xtick',labelsize=20)
rc('ytick',labelsize=20)
#--------------------------------------

"""LR Tech BB emissivity"""
em = loadtxt("../Params/emissivity.dat")
emiss_wls = em[:,0]
emiss = em[:,1]

illuminated = list(loadtxt("../Params/illuminated_pixels_193.txt"))
non_illuminated = list(loadtxt("../Params/non_illuminated_pixels_193.txt"))

seq = "/media/quentin/LACIE SHARE/FIRR_measurements/LR-TECH/SET2/2015-07-30_21-53-21.0718"
npos = 10
sequence = FirrSequence(seq,npos,seq,detector=3)

filters = ["F0007"]
k = 5 # filter position

sequence.organized(spav="all",non_ill=0)
all_tms = sequence.all_tms
all_mean = sequence.all_mean

i_abb1 = searchsorted(sequence.temp_tms,all_tms[k,0])
Tamb1 = sequence.temp_abb[i_abb1]                # exact ABB temperature at measurement
i_hbb = searchsorted(sequence.temp_tms,all_tms[k,1])
Thot = sequence.temp_hbb[i_hbb]                  # exact HBB temperature at measurement
Tpma1 = sequence.temp_pm[i_abb1]                 # pointing mirror temperature at ABB measurement
Tpmh = sequence.temp_pm[i_hbb]                   # pointing mirror temperature at HBB measurement
tamb1 = all_tms[k,0]
thot = all_tms[k,1]-tamb1
tscene = all_tms[k,2:,None]-tamb1
amb1 = all_mean[k,0,:]
hot = all_mean[k,1,:]
scene = all_mean[k,2:,:]

Tamb2 = Tamb1
Tpma2 = Tpma1
tamb2 = tamb1
amb2 = amb1

G,B0,rad_scene,bt = Toolbox.get_calib(amb1,hot,scene,amb2,thot,tscene,tamb2,Tamb1,Thot,Tamb2,filters[0],emiss_wls,emiss,Tpma1,Tpmh,Tpma2)
new_G = zeros([4800])
new_B0 = zeros([4800])

new_G[illuminated] = G[illuminated]
new_B0[illuminated] = B0[illuminated]
new_B0[non_illuminated] = B0[non_illuminated]

fig,(ax1,ax2) = subplots(1,2,figsize=(13,5))
fig.subplots_adjust(bottom=0.05,left=0.05,right=0.95,hspace=0.15)

cs1 = ax1.imshow(reshape(new_G,(60,80)),vmin=-29,vmax=-26.5,cmap=cm.gist_rainbow,interpolation='none')
cs1.cmap.set_under('w')
cs1.cmap.set_over('w')
spacing = 1 # This can be your user specified spacing.
minorLocator = MultipleLocator(spacing)
# Set minor tick locations.
ax1.yaxis.set_minor_locator(minorLocator)
ax1.xaxis.set_minor_locator(minorLocator)
# Set grid to use minor tick locations.
ax1.grid(which = 'minor',linestyle="-",alpha=0.25)
ax1.set_title(r"Gain (counts~W$^{-1}$~m$^{2}$~sr)",size=20)
colorbar(cs1,shrink=0.7,ax = ax1)

cs2 = ax2.imshow(reshape(new_B0,(60,80)),vmin = 29500,vmax=34500,cmap=cm.gist_rainbow,interpolation='none')
cs2.cmap.set_under('w')
cs2.cmap.set_over('w')
spacing = 1 # This can be your user specified spacing.
minorLocator = MultipleLocator(spacing)
# Set minor tick locations.
ax2.yaxis.set_minor_locator(minorLocator)
ax2.xaxis.set_minor_locator(minorLocator)
# Set grid to use minor tick locations.
ax2.grid(which = 'minor',linestyle="-",alpha=0.25)
ax2.set_title(r"Background signal (counts)",size=20)
colorbar(cs2,shrink=0.7,ax = ax2)

fig.savefig("/home/quentin/Papiers/FIRR_AMT/Figures/Background_spatial.pdf",dpi=300,format="pdf")

show()


import sys
import traceback
import datetime
import logging

class Frame(object):

    def __init__(self, tb):
        self.tb = tb
        frame = tb.tb_frame
        self.locals = {}
        self.locals.update(frame.f_locals)

    def print_path(self):
        return traceback.format_tb(self.tb, limit=1)[0]

    def print_local(self):
        return "\n".join(["%s=%s" % (k, self.dump_value(self.locals[k])) for k in self.locals])

    def dump_value(self, v):
        try:
            return str(v)
        except:
            return "value can not serilizable"

def get_debug_detail(e, log_it=True):
    """
    生成日志相关描述信息
    :param e: Exception
    :param log_it:是否写入日志模块
    :return:
    """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    frames = []
    tb = exc_traceback
    frames.append(tb.tb_frame)
    detail = "system error -Exception:\n%s\n\ndetail info is:\n" % e
    while tb.tb_next:
        tb = tb.tb_next
        fm = Frame(tb)
        detail += fm.print_path()
        detail += "\nlocals variables:\n"
        detail += fm.print_local()
        detail += "\n" + "-" * 100 + "\n"
    if log_it:
        logging.error(detail)
    return detail
if __name__ == '__main__':
    try:
        1/0
    except Exception as e:
        get_debug_detail(e)


from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.opengl as gl
import numpy as np
import sys
import math

"""
Simple examples demonstrating the use of GLMeshItem.

"""

QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseDesktopOpenGL)
app = QtGui.QApplication([])

w = gl.GLViewWidget()
w.show()
w.setWindowTitle('pyqtgraph example: GLMeshItem')
w.setCameraPosition(distance=40)

g = gl.GLGridItem()
g.scale(2, 2, 1)
w.addItem(g)

R = 10
r=10

phi_rng = np.linspace(0, 2*math.pi, 15)
theta_rng = np.linspace(0, math.pi, 15)

for phi in phi_rng:
    for theta in theta_rng:
        x = r * math.sin(theta) * math.cos(phi)
        y = r * math.sin(theta) * math.sin(phi)
        z = r * math.cos(theta)
        d = 0.5
        x2 = (r + d) * math.sin(theta) * math.cos(phi)
        y2 = (r + d) * math.sin(theta) * math.sin(phi)
        z2 = (r + d) * math.cos(theta)
        pts = np.array([[x, y, z], [x2, y2, z2]])
        ptss = np.array([[x, y, z], [0, 0, 0]])
        plt = gl.GLLinePlotItem(pos=pts, width = 4, color=pg.glColor(200, 200, 0))
        pltt = gl.GLLinePlotItem(pos=ptss, color=pg.glColor(255, 255, 255))
        w.addItem(plt)
        w.addItem(pltt)

sys.exit(app.exec_())  # Запускаем цикл обработки событий


import numpy as np

from lib.envs.gridworld import GridWorld

def value_iteration(env, discount_factor=1.0, theta=0.00001):
    """
        Value Iteration Algorithm.

        Args:
            env: OpenAI env. env.P represents the transition probabilities of the environment.
                env.P[s][a] is a list of transition tuples (prob, next_state, reward, done).
                env.nS is a number of states in the environment.
                env.nA is a number of actions in the environment.
            theta: We stop evaluation once our value function change is less than theta for all states.
            discount_factor: Gamma discount factor.

        Returns:
            A tuple (policy, V) of the optimal policy and the optimal value function.
        """

    V = np.zeros(env.nS)

    while True:
        delta = -float('inf')

        for s in range(env.nS):
            v = V[s]
            max_v = -float('inf')

            for a in range(env.nA):
                current_v = 0.0
                for prob, s_prime, reward, is_done in env.P[s][a]:
                    current_v += prob * (reward + discount_factor * V[s_prime])
                max_v = max(max_v, current_v)

            V[s] = max_v
            delta = max(delta, abs(v - V[s]))

        if delta < theta:
            break

    policy = np.zeros((env.nS, env.nA))

    for s in range(env.nS):
        count = 0
        prob_a = []
        for a in range(env.nA):
            current_v = 0.0
            for prob, s_prime, reward, is_done in env.P[s][a]:
                current_v += prob * (reward + discount_factor * V[s_prime])

            if np.isclose([V[s]], [current_v])[0]:
                count += 1
                prob_a.append(1.0)
            else:
                prob_a.append(0.0)

        policy[s] = np.array(prob_a) / count

    return policy, V

if __name__ == '__main__':
    env = GridWorld()

    policy, v = value_iteration(env)

    print("Policy Probability Distribution:")
    print(policy)
    print("")

    print("Reshaped Grid Policy (0=up, 1=right, 2=down, 3=left):")
    print(np.reshape(np.argmax(policy, axis=1), env.shape))
    print("")

    print("Value Function:")
    print(v)
    print("")

    print("Reshaped Grid Value Function:")
    print(v.reshape(env.shape))
    print("")

    expected_v = np.array([0, -1, -2, -3, -1, -2, -3, -2, -2, -3, -2, -1, -3, -2, -1, 0])
    np.testing.assert_array_almost_equal(v, expected_v, decimal=2)


#Author:Chris.chen
import re,time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

def get_auctionitemdict(auctionitemdict):
    main_url = "http://www.sothebys.com"
    url = 'http://www.sothebys.com/content/sothebys/en/auctions/2018/important-americana-n09805.html'
    browser = webdriver.Firefox()
    browser.implicitly_wait(3)
    browser.get(url)
    # cookie = browser.get_cookies()
    source_code = browser.page_source
    # print(source_code)
    items = re.search("ECAT.lot\['\d+'\].*",source_code).group()
    item = items.split(';ECAT.lot')
    # print(item)
    num = 0
    for i in item:
        if num > 5:
            break
        # print(i)
        itemdictstr = re.sub("ECAT.lot", '', i, count=1)
        itemdictstr = re.sub("\['\d+'\]=", '', itemdictstr, count=1)
        itemdictstr = re.sub("false", "'false'", itemdictstr)
        itemdictstr = re.sub("true", "'true'", itemdictstr).strip()
        itemdictstr = re.sub("};", "}", itemdictstr).strip()
        # print(itemdictstr)
        # print(type(eval(itemdictstr)))
        itemdict = eval(itemdictstr)
        #拍品编号
        lotnum = itemdict['id']
        #拍品标题
        title = itemdict['guaranteeLine']
        #拍品最低估价
        lowest = itemdict['lowEst']
        # 拍品最高估价
        highest = itemdict['highEst']
        #币种
        currency = itemdict['currency']
        # 拍品地址
        itemurl = re.sub('#conditionsOfSaleModal', '', main_url + itemdict['condRep'])
        #打开拍品链接
        browser.get(itemurl)
        # print(browser.page_source)
        #拍品描述
        soup = BeautifulSoup(browser.page_source,'html5lib')
        itemdes = soup.find_all('div', {'class', 'lotdetail-description-text'})[0].text.strip()

        print(itemdict)
        print('lotnum: ',itemdict['id'])
        print('title: ', itemdict['guaranteeLine'])
        print('itemdes: ',itemdes)
        print('itemurl: ',re.sub('#conditionsOfSaleModal','',main_url+itemdict['condRep']))
        print('itemimageurl: ',main_url + itemdict['image'])
        print('lowest: ',itemdict['lowEst'])
        print('highest: ',itemdict['highEst'])
        print('currency: ',itemdict['currency'])

        auctionitemdict[lotnum] = [title,itemdes,lowest,highest,currency,itemurl]
        # browser.back()
        num += 1
        time.sleep(1)

    return auctionitemdict

    # action = ActionChains(browser).move_to_element(element)
    #
    # while True:
    #     browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")
    #     try:
    #         target = browser.find_element_by_xpath('/html/body/div[2]/div[2]/div[3]/section[2]/article[191]/div[2]/h1')
    #         break
    #     except NoSuchElementException as e:
    #         pass

    # EnAuctionList = browser.find_elements_by_xpath('/html/body/div[2]/div[2]/div[3]/section[2]/article/div[2]/h4[2]/a')
    # for i in EnAuctionList:
    #     # i.click()
    #     action = ActionChains(browser)
    #     action.move_to_element(i)
    #     action.click(i)
    #     action.perform()
    #     # img_url = i.get_attribute('src')
    # browser.close()

auctionitemdict={}
get_auctionitemdict(auctionitemdict)
print(sorted(auctionitemdict.items()))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
Created By  : Nguyen Huu Kim - huukim98@gmail.com
Created Date: May 5, 2021 3:04pm GMT+0700
Project : AkaOCR core
_____________________________________________________________________________

This file contains function to convert from data source of Cocotext to desire groundtruth format
_____________________________________________________________________________

Refer API from https://github.com/bgshih/coco-text (coco_text.py)
Cocotext just has annot for train set only, split train/test/eval by yourself

Data source:
    #refer: https://vision.cornell.edu/se3/coco-text-2/
    #annot: https://vision.cornell.edu/se3/wp-content/uploads/2019/05/COCO_Text.zip
    #image
            http://images.cocodataset.org/zips/train2014.zip
            http://images.cocodataset.org/zips/val2014.zip
            http://images.cocodataset.org/zips/test2014.zip
"""

import coco_text
import shutil
import json
import os
import argparse
from tqdm import tqdm
from pathlib import Path

subset = ['train','test', 'val']

def convert(src_path, annot_path, des_path):
    ct = coco_text.COCO_Text(annot_path)
    print(ct.info())
    for ss in subset:
        des_img_path = os.path.join(des_path, ss, 'images')
        des_jsn_path = os.path.join(des_path, ss, 'annotations')
        #remove old if exist for clean data
        if os.path.exists(des_img_path) and os.path.isdir(des_img_path):
            shutil.rmtree(des_img_path)
        if os.path.exists(des_jsn_path) and os.path.isdir(des_jsn_path):
            shutil.rmtree(des_jsn_path)
        #create folder output if not exist
        Path(des_img_path).mkdir(parents=True, exist_ok=True)
        Path(des_jsn_path).mkdir(parents=True, exist_ok=True)

        if ss == 'train':
            imgs = ct.getImgIds(imgIds=ct.train)
        elif ss == 'test':
            imgs = ct.getImgIds(imgIds=ct.test)
        else:
            imgs = ct.getImgIds(imgIds=ct.val)

        img_item = {}

        for img in tqdm(imgs):
            annIds = ct.getAnnIds(imgIds=img)
            anns = ct.loadAnns(annIds)
            img_prop = ct.loadImgs(img)

            img_item["file"] = img_prop[0]["file_name"]
            img_item["width"] = img_prop[0]["width"]
            img_item["height"] = img_prop[0]["height"]
            img_item["depth"] = 1
            words = []
            for ann in anns:
                word = {}
                if 'utf8_string' in list(ann.keys()):
                    left, top, width, height = ann['bbox']
                    x1, y1 = left, top
                    x2, y2 = x1+width, y1
                    x3, y3 = x2, y2+height
                    x4, y4 = x3-width, y3

                    #append word
                    word["text"] = ann['utf8_string']
                    word["x1"] = round(x1,1)
                    word["y1"] = round(y1,1)
                    word["x2"] = round(x2,1)
                    word["y2"] = round(y2,1)
                    word["x3"] = round(x3,1)
                    word["y3"] = round(y3,1)
                    word["x4"] = round(x4,1)
                    word["y4"] = round(y4,1)
                    word["char"] = []
                    words.append(word)

            img_item["words"] = words
            src_img = os.path.join(src_path, img_item["file"])
            des_img = os.path.join(des_img_path, img_item["file"])
            des_jsn = os.path.join(des_jsn_path, img_item["file"][:img_item["file"].rfind('.')]+'.json')

            shutil.copyfile(src_img, des_img)
            with open(des_jsn, 'w') as js:
                json.dump(img_item, js, indent=4)

        print("Done convert set, check at: ", des_img_path)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--src_path', required=True, help='path to source data path')
    parser.add_argument('--annot_path', required=True, help='path to annot (.json) file of cocotext')
    parser.add_argument('--des_path', required=True, help='path to destination output path (contain images and annotations subfolder)')

    opt = parser.parse_args()
    convert(src_path=opt.src_path, annot_path=opt.annot_path, des_path=opt.des_path)

if __name__ == '__main__':
    main()

#src_path='D:/kimnh3/dataset/ocr/raw_download/cocotext/2014/train2014'
#annot_path='D:/kimnh3/dataset/ocr/raw_download/cocotext/annot-text/COCO_Text/COCO_Text.json'
#des_path='D:/kimnh3/dataset/ocr/converted/cocotext/'


import collections
class Solution:
    def wordSubsets(self, A, B):
        """
        :type A: List[str]
        :type B: List[str]
        :rtype: List[str]
        """
        bMaxCount = collections.Counter()
        for b in B:
            bMaxCount |= collections.Counter(b)

        universals = []
        for a in A:
            aCount = collections.Counter(a)
            if all(aCount[bLetter] >= bMaxCount[bLetter] for bLetter in bMaxCount):
                universals.append(a)

        return universals

print(Solution().wordSubsets(["amazon","apple","facebook","google","leetcode"], ["ec","oc","ceo"]))


#!/usr/bin/env python

# Test the reflex dictionary usage in PyROOT to
# instantiate and configure the overlap removal tool(s).

# Setup libs
from ROOT import gROOT
gROOT.SetBatch()
gROOT.Macro('$ROOTCOREDIR/scripts/load_packages.C')

# Import using the PyROOT bindings and reflex dictionary
from ROOT import OverlapRemovalTool

# Configure the tool(s)
orTool = OverlapRemovalTool('OverlapRemovalTool')
orTool.setProperty('OverlapLabel', 'overlaps')
orTool.setProperty(bool)('LinkOverlapObjects', True)

#Initialize the tool(s)
orTool.initialize()


import datetime
from collections import OrderedDict

from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.db.models import ProtectedError
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render

from appTienda.formularios import Articulo_form
from appTienda.models import Articulo, Unidad, Prenda_precio_compra, Prenda_precio_venta, Tipo_articulo
from appTienda.views.controller import borrar_sessiones

#Listado de articulo
def listado(request, pagina, orden):
    pagina = 1
    # Guardo sessiones
    request.session['articulo_pagina'] = pagina
    request.session['articulo_orden'] = orden
    borrar_sessiones(request, 'articulo_pagina', 'articulo_orden', 'articulo_numero', 'aritculo_busqueda', 'articulo_opcion')
    # Si hay mensajes para mostrar
    if 'msjlista' in request.session:
        mensaje = request.session["msjlista"]
        del request.session['msjlista']
    else:
        mensaje = ''
    # Funcionalidad
    if request.method == "POST":
        busqueda = str(request.POST.get('busqueda'))
        opcion = str(request.POST.get('opcion_busqueda'))
        request.session['articulo_busqueda'] = busqueda
        request.session['articulo_opcion'] = opcion
    else:
        if 'articulo_busqueda' not in request.session:
            busqueda = ''
        else:
            busqueda = request.session['articulo_busqueda']
        if 'articulo_opcion' not in request.session:
            opcion = ''
        else:
            opcion = request.session['articulo_opcion']
    if len(busqueda) != 0:
        if opcion == 'codigo':
            lista = Articulo.objects.filter(codigo__icontains=busqueda).order_by(orden)
        elif opcion == 'descripcion':
            lista = Articulo.objects.filter(descripcion__icontains=busqueda).order_by(orden)
        elif opcion == 'categoria':
            lista = Articulo.objects.filter(Q(categoria__codigo__icontains=busqueda)
                                            | Q(categoria__nombre__icontains=busqueda)).order_by(orden)
    else:
        if opcion == 'valuar':
            lista = Articulo.objects.filter(estado__estado__icontains='Valuar').order_by(orden)
        elif opcion == 'stock':
            lista = Articulo.objects.filter(estado__estado__icontains='Stock').order_by(orden)
        elif opcion == 'venta':
            lista = Articulo.objects.filter(estado__estado__icontains='Venta').order_by(orden)
        elif opcion == 'vendido':
            lista = Articulo.objects.filter(estado__estado__icontains='Vendido').order_by(orden)
        else:
            lista = Articulo.objects.all().order_by(orden)
    busqueda = ''
    opciones = OrderedDict([
        ('descripcion', 'Descripción'), ('codigo', 'Código'),
        ('categoria', 'Categoría'),
        ('venta', 'Venta'), ('vendido', 'Vendido'),
        ('valuar', 'Valuar'), ('stock', 'Stock'),
    ])
    campos = OrderedDict([
        ('codigo', 'Código'), ('descripcion', 'Descripción'),
        ('precio_compra', 'Precio compra'),
        ('precio_venta', 'Precio venta'), ('estado', 'Estado')
    ])
    ctx = {'articulo_lista': lista,
           'mensaje': mensaje,
           'busqueda': busqueda,
           'seleccionado': opcion,
           'pagina': pagina,
           'orden': orden,
           'campos': campos,
           'opciones': opciones,
           }
    return render(request,'mantenimientos/articulo/lista.html', ctx)

# Alta de articulo
def alta(request):
    pagina = str(request.session['articulo_pagina'])
    orden = str(request.session['articulo_orden'])
    if request.method == "POST":
        form = Articulo_form(request.POST)
        #form_precio = Prenda_precio_form(request.POST)
        if form.is_valid():
            nuevo = Articulo()
            nuevo.categoria = form.cleaned_data['categoria']
            nuevo.codigo = form.cleaned_data['codigo']
            nuevo.color = form.cleaned_data['color']
            nuevo.talle = form.cleaned_data['talle']
            nuevo.descripcion = form.cleaned_data['descripcion']
            nuevo.stock = form.cleaned_data['stock']
            nuevo.ultima_compra = form.cleaned_data['ultima_compra']
            nuevo.precio_compra = form.cleaned_data['precio_compra']
            nuevo.precio_venta = form.cleaned_data['precio_venta']
            nuevo.unidad = Unidad.objects.get(id=1)
            nuevo.tipo = Tipo_articulo.objects.get(id=1)
            nuevo.evaluar_estado()
            if nuevo.estado is not None:
                if nuevo.estado.estado == 'Valuar':
                    mensaje = "Se guardo satifactoriamente. Falta valuar"
                if nuevo.estado.estado == 'Stock':
                    mensaje = "Se guardo satifactoriamente. Faltan detalles"
                if nuevo.estado.estado == 'Venta':
                    mensaje = "Se guardo satifactoriamente. Listo para venta"
                nuevo.save()
                form = Articulo_form()
            else:
                mensaje = "Revisar campos vacios"
            #form_precio = Prenda_precio_form()
        else:
            mensaje = "Revisar errores antes de continuar"
        ctx = {'form': form, 'mensaje': mensaje, 'pagina': pagina, 'orden': orden}
        return render(request,'mantenimientos/articulo/alta.html', ctx)
    else:
        form = Articulo_form()
        form.ultima_compra = datetime.datetime.now()
        ctx = {'form': form, 'pagina': pagina, 'orden': orden}
        return render(request,'mantenimientos/articulo/alta.html', ctx)

def modificacion(request, articulo_id):
    pagina = str(request.session['articulo_pagina'])
    orden = str(request.session['articulo_orden'])
    articulo_mod = Articulo.objects.get(id=articulo_id)
    datos_inicial = {'codigo': articulo_mod.codigo,
                     'categoria': articulo_mod.categoria,
                     'color': articulo_mod.color,
                     'talle': articulo_mod.talle,
                     'descripcion': articulo_mod.descripcion,
                     'stock': articulo_mod.stock,
                     'unidad': articulo_mod.unidad,
                     'ultima_compra': articulo_mod.ultima_compra,
                     'precio_compra': articulo_mod.precio_compra,
                     'precio_venta': articulo_mod.precio_venta,
                     'tipo_iva': articulo_mod.tipo_iva,
                     'tipo': articulo_mod.tipo,
                     'estado': articulo_mod.estado,
                     }
    if request.method == 'POST':
        form = Articulo_form(request.POST, instance=articulo_mod)
        if form.is_valid():
            articulo_mod.codigo = form.cleaned_data['codigo']
            articulo_mod.categoria = form.cleaned_data['categoria']
            articulo_mod.color = form.cleaned_data['color']
            articulo_mod.talle = form.cleaned_data['talle']
            articulo_mod.descripcion = form.cleaned_data['descripcion']
            articulo_mod.precio_compra = form.cleaned_data['precio_compra']
            articulo_mod.precio_venta = form.cleaned_data['precio_venta']
            articulo_mod.evaluar_estado()
            if articulo_mod.estado is not None:
                if articulo_mod.estado.estado == 'Valuar':
                    request.session['msjlista'] = str(articulo_mod.codigo)+" Se modifico satifactoriamente. Falta valuar"
                if articulo_mod.estado.estado == 'Stock':
                    request.session['msjlista'] = str(articulo_mod.codigo)+" Se modifico satifactoriamente. Faltan detalles"
                if articulo_mod.estado.estado == 'Venta':
                    request.session['msjlista'] = str(articulo_mod.codigo)+" Se modifico satifactoriamente. Listo para venta"
                articulo_mod.save()
                return HttpResponseRedirect('/articulo/pagina/' + pagina + '/orden/' + orden)
            else:
                mensaje = "Revisar campos vacios"
        else:
            mensaje = 'Corregir errores antes de continuar'
        ctx = {'form': form, 'pagina': pagina, 'orden': orden, 'mensaje': mensaje }
    if request.method == 'GET':
        form = Articulo_form(initial=datos_inicial)
        ctx = { 'form': form, 'pagina': pagina, 'orden': orden }
    return render(request, 'mantenimientos/articulo/modificacion.html', ctx)

def baja(request, articulo_id):
    pagina = str(request.session['articulo_pagina'])
    orden = str(request.session['articulo_orden'])
    articulo_baja = Articulo.objects.get(id=articulo_id)
    if request.method == 'POST':
        try:
            baja = Articulo()
            baja.id = articulo_id
            baja.delete()
            request.session['msjlista'] = 'Se elimino correctamente'
            return HttpResponseRedirect('/articulo/pagina/' + pagina + '/orden/' + orden)
        except ProtectedError:
            mensaje = 'No se pudo eliminar'
            ctx = {'articulo': articulo_baja, 'pagina': pagina, 'orden': orden,
                   'mensaje': mensaje}
    else:
        ctx = {'articulo': articulo_baja, 'pagina': pagina, 'orden': orden}
    return render(request, 'mantenimientos/articulo/baja.html', ctx)

def detalle(request, articulo_id):
    pagina = str(request.session['articulo_pagina'])
    orden = str(request.session['articulo_orden'])
    articulo = Articulo.objects.get(id=articulo_id)
    form = Articulo_form(instance=articulo)
    ctx = {'form': form, 'pagina': pagina, 'orden': orden}
    return render(request, 'mantenimientos/articulo/detalle.html', ctx)


import numpy as np
import pygame

class Pipe:
    def __init__(self,info,special=None):
        self.info = info
        self.spacing = 150
        self.top = np.random.uniform(0.1*self.info["height"],0.7*self.info["height"])  #np.random.random()*self.info["height"]/2
        self.bottom = self.info["height"] - (self.top + self.spacing) #np.random.random()*self.info["height"]/2
        self.x = self.info["width"]
        self.w = 40
        self.speed = 1
        self.highlight = False
        if self.info["generation_count"] % 2 == 0:
            self.colour = (255,255,255)
        else:
            self.colour = (200,200,200)
        if special:
            self.colour = (128,128,128)

    def show(self):
        if self.highlight:
            colour = (255,0,0)
        else:
            colour = self.colour

        pygame.draw.rect(self.info["screen"], colour, [self.x,0,self.w,self.top])
        pygame.draw.rect(self.info["screen"], colour, [self.x,self.info["height"]-self.bottom,self.w,self.bottom])

    def update(self):
        self.x -= self.speed

    def offscreen(self):
        return self.x < -self.w

    def hits(self,bird):
        if (bird.y < self.top) or (bird.y > self.info["height"] - self.bottom ):
            if (bird.x > self.x) and (bird.x < self.x + self.w):
                self.highlight = True
                return True
            else:
                self.highlight = False
                return False
        else:
            self.highlight = False
            return False


def nextGap(gap):
    gap = (gap * 10)//13
    if gap < 1:
        return 1
    return gap
def combSort(arr):
    n = len(arr)
    gap = n
    swapped = True
    while gap !=1 or swapped:
        gap = nextGap(gap)
        swapped = False
        for i in range(0, n-gap):
            if arr[i] > arr[i + gap]:
                arr[i], arr[i + gap]=arr[i + gap], arr[i]
                swapped = True
size = int(input())
arr = [int(x) for x in input().split()]
combSort(arr)
unsupportable = 0
for x in arr:
    if x == arr[0]:
        unsupportable += 1
    else:
        break
for x in reversed(arr):
    if x == arr[len(arr)-1]:
        unsupportable += 1
    else:
        break
print(size-unsupportable if size-unsupportable >= 0 else 0)


# Copyright (c) 2013 - 2016 Huawei Technologies Co., Ltd.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
"""
Volume api for FusionStorage systems.
"""

import os
import re
import six

from oslo_log import log as logging

from cinder.i18n import _LE
from cinder import utils

LOG = logging.getLogger(__name__)
fsc_conf_file = "/etc/cinder/volumes/fsc_conf"
fsc_cli = "fsc_cli"
fsc_ip = []
fsc_port = '10519'
manage_ip = "127.0.0.1"
CMD_BIN = fsc_cli

volume_info = {
    'result': '',
    'vol_name': '',
    'father_name': '',
    'status': '',
    'vol_size': '',
    'real_size': '',
    'pool_id': '',
    'create_time': ''}

snap_info = {
    'result': '',
    'snap_name': '',
    'father_name': '',
    'status': '',
    'snap_size': '',
    'real_size': '',
    'pool_id': '',
    'delete_priority': '',
    'create_time': ''}

pool_info = {
    'result': '',
    'pool_id': '',
    'total_capacity': '',
    'used_capacity': '',
    'alloc_capacity': ''}

class FSPythonApi(object):

    def __init__(self):
        LOG.debug("FSPythonApi init.")
        self.get_ip_port()
        self.res_idx = len('result=')

    def get_ip_port(self):
        LOG.debug("File fsc_conf_file is %s.", fsc_conf_file)
        if os.path.exists(fsc_conf_file):
            try:
                fsc_file = open(fsc_conf_file, 'r')
                full_txt = fsc_file.readlines()
                LOG.debug("Full_txt is %s.", full_txt)
                for line in full_txt:
                    if re.search('^vbs_url=', line):
                        tmp_vbs_url = line[8:]
                        return re.split(',', tmp_vbs_url)
            except Exception as e:
                LOG.debug("Get fsc ip failed, error=%s.", e)
            finally:
                fsc_file.close()
        else:
            LOG.debug("Fsc conf file not exist, file_name=%s.", fsc_conf_file)

    def get_manage_ip(self):
        LOG.debug("File fsc_conf_file is %s.", fsc_conf_file)
        if os.path.exists(fsc_conf_file):
            try:
                fsc_file = open(fsc_conf_file, 'r')
                full_txt = fsc_file.readlines()
                for line in full_txt:
                    if re.search('^manage_ip=', line):
                        manage_ip = line[len('manage_ip='):]
                        manage_ip = manage_ip.strip('\n')
                        return manage_ip
            except Exception as e:
                LOG.debug("Get manage ip failed, error=%s.", e)
            finally:
                fsc_file.close()
        else:
            LOG.debug("Fsc conf file not exist, file_name=%s.", fsc_conf_file)

    def get_dsw_manage_ip(self):
        return manage_ip

    def start_execute_cmd(self, cmd, full_result_flag):
        fsc_ip = self.get_ip_port()
        manage_ip = self.get_manage_ip()
        ip_num = len(fsc_ip)

        LOG.debug("fsc_ip is %s", fsc_ip)

        if ip_num <= 0:
            return None

        if ip_num > 3:
            ip_num = 3

        exec_result = ''
        result = ''
        if full_result_flag:
            for ip in fsc_ip:
                cmd_args = [CMD_BIN, '--manage_ip', manage_ip.replace(
                    '\n', ''), '--ip', ip.replace('\n', '')] + cmd.split()
                LOG.debug("Dsware cmd_args is %s.", cmd_args)

                exec_result, err = utils.execute(*cmd_args, run_as_root=True)
                exec_result = exec_result.split('\n')
                LOG.debug("Result is %s.", exec_result)
                if exec_result:
                    for line in exec_result:
                        if re.search('^result=0', line):
                            return exec_result
                        elif re.search('^result=50150007', line):
                            return 'result=0'
                        elif re.search('^result=50150008', line):
                            return 'result=0'
                        elif re.search('^result=50', line):
                            return exec_result
            return exec_result
        else:
            for ip in fsc_ip:
                cmd_args = [CMD_BIN, '--manage_ip', manage_ip.replace(
                    '\n', ''), '--ip', ip.replace('\n', '')] + cmd.split()
                LOG.debug("Dsware cmd_args is %s.", cmd_args)

                exec_result, err = utils.execute(*cmd_args, run_as_root=True)
                LOG.debug("Result is %s.", exec_result)
                exec_result = exec_result.split('\n')
                if exec_result:
                    for line in exec_result:
                        if re.search('^result=', line):
                            result = line
                            if re.search('^result=0', line):
                                return line
                            elif re.search('^result=50150007', line):
                                return 'result=0'
                            elif re.search('^result=50150008', line):
                                return 'result=0'
                            elif re.search('^result=50', line):
                                return line
            return result

    def create_volume(self, vol_name, pool_id, vol_size, thin_flag):
        cmd = '--op createVolume' + ' ' + '--volName' + ' ' + six.text_type(
            vol_name) + ' ' + '--poolId' + ' ' + six.text_type(
            pool_id) + ' ' + '--volSize' + ' ' + six.text_type(
            vol_size) + ' ' + '--thinFlag' + ' ' + six.text_type(thin_flag)

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def extend_volume(self, vol_name, new_vol_size):
        cmd = ''
        cmd = '--op expandVolume' + ' ' + '--volName' + ' ' + six.text_type(
            vol_name) + ' ' + '--volSize' + ' ' + six.text_type(new_vol_size)

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def create_volume_from_snap(self, vol_name, vol_size, snap_name):
        cmd = ('--op createVolumeFromSnap' + ' ') + (
            '--volName' + ' ') + six.text_type(
            vol_name) + ' ' + '--snapNameSrc' + ' ' + six.text_type(
            snap_name) + ' ' + '--volSize' + ' ' + six.text_type(vol_size)

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def create_fullvol_from_snap(self, vol_name, snap_name):
        cmd = ('--op createFullVolumeFromSnap' + ' ') + (
            '--volName' + ' ') + six.text_type(
            vol_name) + ' ' + '--snapName' + ' ' + six.text_type(snap_name)

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def create_volume_from_volume(self, vol_name, vol_size, src_vol_name):
        retcode = 1
        tmp_snap_name = six.text_type(vol_name) + '_tmp_snap'

        retcode = self.create_snapshot(tmp_snap_name, src_vol_name, 0)
        if 0 != retcode:
            return retcode

        retcode = self.create_volume(vol_name, 0, vol_size, 0)
        if 0 != retcode:
            self.delete_snapshot(tmp_snap_name)
            return retcode

        retcode = self.create_fullvol_from_snap(vol_name, tmp_snap_name)
        if 0 != retcode:
            self.delete_snapshot(tmp_snap_name)
            self.delete_volume(vol_name)
            return retcode

        return 0

    def create_clone_volume_from_volume(self, vol_name,
                                        vol_size, src_vol_name):
        retcode = 1
        tmp_snap_name = six.text_type(src_vol_name) + '_DT_clnoe_snap'

        retcode = self.create_snapshot(tmp_snap_name, src_vol_name, 0)
        if 0 != retcode:
            return retcode

        retcode = self.create_volume_from_snap(
            vol_name, vol_size, tmp_snap_name)
        if 0 != retcode:
            return retcode

        return 0

    def volume_info_analyze(self, vol_info):
        local_volume_info = volume_info

        if not vol_info:
            local_volume_info['result'] = 1
            return local_volume_info

        local_volume_info['result'] = 0

        vol_info_list = []
        vol_info_list = re.split(',', vol_info)
        for line in vol_info_list:
            line = line.replace('\n', '')
            if re.search('^vol_name=', line):
                local_volume_info['vol_name'] = line[len('vol_name='):]
            elif re.search('^father_name=', line):
                local_volume_info['father_name'] = line[len('father_name='):]
            elif re.search('^status=', line):
                local_volume_info['status'] = line[len('status='):]
            elif re.search('^vol_size=', line):
                local_volume_info['vol_size'] = line[len('vol_size='):]
            elif re.search('^real_size=', line):
                local_volume_info['real_size'] = line[len('real_size='):]
            elif re.search('^pool_id=', line):
                local_volume_info['pool_id'] = line[len('pool_id='):]
            elif re.search('^create_time=', line):
                local_volume_info['create_time'] = line[len('create_time='):]
            else:
                LOG.error(_LE("Analyze key not exist, key=%s."),
                          six.text_type(line))
        return local_volume_info

    def query_volume(self, vol_name):
        tmp_volume_info = volume_info
        cmd = '--op queryVolume' + ' ' + '--volName' + ' ' + vol_name

        exec_result = self.start_execute_cmd(cmd, 1)
        if exec_result:
            for line in exec_result:
                if re.search('^result=', line):
                    if not re.search('^result=0', line):
                        tmp_volume_info['result'] = line[self.res_idx:]
                        return tmp_volume_info
                    for line in exec_result:
                        if re.search('^vol_name=' + vol_name, line):
                            tmp_volume_info = self.volume_info_analyze(line)
                            if six.text_type(0) == tmp_volume_info['status']:
                                tmp_snap_name = six.text_type(
                                    vol_name) + '_tmp_snap'
                                self.delete_snapshot(tmp_snap_name)
                            return tmp_volume_info

        tmp_volume_info['result'] = 1
        return tmp_volume_info

    def delete_volume(self, vol_name):
        cmd = '--op deleteVolume' + ' ' + '--volName' + ' ' + vol_name

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def create_snapshot(self, snap_name, vol_name, smart_flag):
        cmd = '--op createSnapshot' + ' ' + '--volName' + ' ' + six.text_type(
            vol_name) + ' ' + '--snapName' + ' ' + six.text_type(
            snap_name) + ' ' + '--smartFlag' + ' ' + six.text_type(smart_flag)

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def snap_info_analyze(self, info):
        local_snap_info = snap_info.copy()

        if not info:
            local_snap_info['result'] = 1
            return local_snap_info

        local_snap_info['result'] = 0

        snap_info_list = []
        snap_info_list = re.split(',', info)
        for line in snap_info_list:
            line = line.replace('\n', '')
            if re.search('^snap_name=', line):
                local_snap_info['snap_name'] = line[len('snap_name='):]
            elif re.search('^father_name=', line):
                local_snap_info['father_name'] = line[len('father_name='):]
            elif re.search('^status=', line):
                local_snap_info['status'] = line[len('status='):]
            elif re.search('^snap_size=', line):
                local_snap_info['snap_size'] = line[len('snap_size='):]
            elif re.search('^real_size=', line):
                local_snap_info['real_size'] = line[len('real_size='):]
            elif re.search('^pool_id=', line):
                local_snap_info['pool_id'] = line[len('pool_id='):]
            elif re.search('^delete_priority=', line):
                local_snap_info['delete_priority'] = line[
                    len('delete_priority='):]
            elif re.search('^create_time=', line):
                local_snap_info['create_time'] = line[len('create_time='):]
            else:
                LOG.error(_LE("Analyze key not exist, key=%s."),
                          line)

        return local_snap_info

    def query_snap(self, snap_name):
        tmp_snap_info = snap_info.copy()
        cmd = '--op querySnapshot' + ' ' + '--snapName' + ' ' + snap_name

        exec_result = self.start_execute_cmd(cmd, 1)
        if exec_result:
            for line in exec_result:
                if re.search('^result=', line):
                    if not re.search('^result=0', line):
                        tmp_snap_info['result'] = line[self.res_idx:]
                        return tmp_snap_info
                    for line in exec_result:
                        if re.search('^snap_name=' + snap_name, line):
                            tmp_snap_info = self.snap_info_analyze(line)
                            return tmp_snap_info

        tmp_snap_info['result'] = 1
        return tmp_snap_info

    def delete_snapshot(self, snap_name):
        cmd = '--op deleteSnapshot' + ' ' + '--snapName' + ' ' + snap_name

        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            if re.search('^result=0', exec_result):
                return 0
            else:
                return exec_result[self.res_idx:]
        else:
            return 1

    def pool_info_analyze(self, info):
        local_pool_info = pool_info.copy()

        if not info:
            local_pool_info['result'] = 1
            return local_pool_info

        local_pool_info['result'] = 0

        pool_info_list = []
        pool_info_list = re.split(',', info)
        for line in pool_info_list:
            line = line.replace('\n', '')
            if re.search('^pool_id=', line):
                local_pool_info['pool_id'] = line[len('pool_id='):]
            elif re.search('^total_capacity=', line):
                local_pool_info['total_capacity'] = line[
                    len('total_capacity='):]
            elif re.search('^used_capacity=', line):
                local_pool_info['used_capacity'] = line[len('used_capacity='):]
            elif re.search('^alloc_capacity=', line):
                local_pool_info['alloc_capacity'] = line[
                    len('alloc_capacity='):]
            else:
                LOG.error(_LE("Analyze key not exist, key=%s."),
                          six.text_type(line))
        return local_pool_info

    def query_pool_info(self, pool_id):
        tmp_pool_info = pool_info.copy()
        cmd = '--op queryPoolInfo' + ' ' + '--poolId' + ' ' + six.text_type(
            pool_id)
        LOG.debug("Pool id is %s.", pool_id)
        exec_result = self.start_execute_cmd(cmd, 1)
        if exec_result:
            for line in exec_result:
                if re.search('^result=', line):
                    if not re.search('^result=0', line):
                        tmp_pool_info['result'] = line[self.res_idx:]
                        return tmp_pool_info
                    for line in exec_result:
                        if re.search('^pool_id=' + six.text_type(pool_id),
                                     line):
                            tmp_pool_info = self.pool_info_analyze(line)
                            return tmp_pool_info

        tmp_pool_info['result'] = 1
        return tmp_pool_info

    def query_pool_type(self, pool_type):
        pool_list = []
        tmp_pool_info = {}
        result = 0
        cmd = ''
        cmd = '--op queryPoolType --poolType' + ' ' + pool_type
        LOG.debug("Query poolType: %s.", pool_type)
        exec_result = self.start_execute_cmd(cmd, 1)
        if exec_result:
            for line in exec_result:
                line = line.replace('\n', '')
                if re.search('^result=', line):
                    if not re.search('^result=0', line):
                        result = int(line[self.res_idx:])
                        break
                    for one_line in exec_result:
                        if re.search('^pool_id=', one_line):
                            tmp_pool_info = self.pool_info_analyze(one_line)
                            pool_list.append(tmp_pool_info)
                    break
        return (result, pool_list)

    def query_dsware_version(self):
        retcode = 2
        cmd = '--op getDSwareIdentifier'
        exec_result = self.start_execute_cmd(cmd, 0)
        if exec_result:
            # New version.
            if re.search('^result=0', exec_result):
                retcode = 0
            # Old version.
            elif re.search('^result=50500001', exec_result):
                retcode = 1
            # Failed!
            else:
                retcode = exec_result[self.res_idx:]
        return retcode


import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile

import time

def getms():
  return int(round(time.time() * 1000))

sess = tf.Session(config=
    tf.ConfigProto(inter_op_parallelism_threads=1,
                   intra_op_parallelism_threads=1,
                   device_count = {"GPU": 0}))
'''
sess = tf.Session()
'''
with gfile.FastGFile("mnist_frozen_model.pb", "rb") as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    sess.graph.as_default()
    tf.import_graph_def(graph_def, name='')

sess.run(tf.global_variables_initializer())

# Show all op
for op in sess.graph.get_operations():
   print(op.name,op.values())

x = sess.graph.get_tensor_by_name("input:0")
softmax = sess.graph.get_tensor_by_name("softmax:0")
for i in range(100000):
  batch_xs = np.random.random_sample((1, 28, 28, 1))
  print(batch_xs.shape)
  start = getms()
  out = sess.run(softmax, feed_dict={x: batch_xs})
  print(out)
  print("forward...... " + str(getms() - start) + " ms")


import pandas as pd
import numpy as np
import random
from sklearn.datasets import load_iris

from sklearn.feature_selection import SelectKBest,SelectPercentile, SelectFpr,SelectFdr,GenericUnivariateSelect,chi2,f_regression

p_num = 1

def put_anomaly(x,i_max = 5):
    for i in range(i_max):
        random_index = random.randint(0,149)
        random_column = random.randint(0,3)
        x[random_index,random_column] = x[random_index,random_column] + random.randint(1,5)
        x[0,:] = 6
    return x

x, y = load_iris(return_X_y=True)
x_new  = put_anomaly(x)
#x_new = x

data = pd.DataFrame(data = x_new)
data['label'] = y

#Feature Selection - Filter Methods - Univariate feature selection
# Chi squared test - SelectKBest
x_chi = SelectKBest(chi2, k=2).fit_transform(x, y)

# Chi squared test - SelectPercentile
x_chi = SelectPercentile(chi2, percentile=2).fit_transform(x, y)

# Chi squared test - SelectFpr
x_chi = SelectFpr(chi2, alpha=0.001).fit_transform(x, y)

# Chi squared test - SelectFdr
x_chi = SelectFdr(chi2, alpha=0.001).fit_transform(x, y)

# Chi squared test - GenericUnivariateSelect - mode : {‘percentile’, ‘k_best’, ‘fpr’, ‘fdr’, ‘fwe’}
transformer = GenericUnivariateSelect(chi2, 'k_best', param=2)
x_chi = transformer.fit_transform(x, y)

#These objects take as input a scoring function that returns univariate scores and p-values (or only scores for SelectKBest and SelectPercentile):

#For regression: f_regression, mutual_info_regression
#For classification: chi2, f_classif, mutual_info_classif

#Chi squared test - GenericUnivariateSelect - for regression
transformer = GenericUnivariateSelect(chi2, 'k_best', param=2)
transformer.score_func(x,y)
x_chi = transformer.fit_transform(x, y)

24.4.19/סקריפטים/Feature Selection Algorithms _ Filter Methods.py


message='GUVF VF ZL FRPERG ZRFFNTR.'

ALFAVIT='ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for key in range(len(ALFAVIT)):
    translated=''
    for symbol in message:
        if symbol in ALFAVIT:
            num=ALFAVIT.find(symbol)
            num=num-key
            if num < 0:
                num=num+len(ALFAVIT)
            translated+=ALFAVIT[num]
        else:
            translated+=symbol
    print('Key#%s:%s'%(key,translated))


#!/usr/bin/env python
import rospy
import std_msgs
import time

def talker():
    pub = rospy.Publisher('Direction', std_msgs.msg.String, queue_size=10)
    pub2 = rospy.Publisher('Speed', std_msgs.msg.Float32, queue_size=10)
    rospy.init_node('arduino_sender')

    #pub.publish('forward')
    time.sleep(1)
    pub2.publish(0)

talker()


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
     url(r'^$', 'apps.compraventa.views.index', name='index'),
     url(r'^productos', 'apps.compraventa.views.productos', name='productos'),
     url(r'^categorias', 'apps.compraventa.views.categorias', name='categorias'),
     url(r'^vcategorias', 'apps.compraventa.views.vercategorias', name='vercategorias'),

    # url(r'^compraventa/', include('compraventa.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)


# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

"""
fused operator dsl function: fused_relu_grad_bn_update_grad
ResNet50 fused computation. 216 in XLA patterns
"""
from __future__ import absolute_import
import akg.topi as topi
import akg.utils as utils
from tests.common.test_op.resnet.fused_pattern_grad import relu_grad, bn_gamma_grad, bn_beta_grad

def fused_relu_grad_bn_update_grad(data_sum, in_bn, head_active, in_active, layout='NHWC',
                                    out_dtype="float32", target=utils.CUDA):

    if layout != 'NHWC' and layout!= "NCHW":
        raise NotImplementedError(
            'Layout not supported {} '.format(layout))

    inter_dtype = "float32"
    relugrad = relu_grad(head_active, in_active)
    relugrad_cast = topi.cast(relugrad, inter_dtype)
    inbn_cast = topi.cast(in_bn, inter_dtype)

    bn_gamma_ad = bn_gamma_grad(relugrad_cast, inbn_cast, data_sum, layout)
    bn_beta_ad = bn_beta_grad(relugrad_cast, layout)

    if bn_gamma_ad.dtype != out_dtype:
        bn_gamma_ad = topi.cast(bn_gamma_ad, out_dtype)
    if bn_beta_ad.dtype != out_dtype:
        bn_beta_ad = topi.cast(bn_beta_ad, out_dtype)

    return [bn_gamma_ad, bn_beta_ad]


from django.core.validators import EmailValidator
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from .models import (Brand, Catalogue, Client, Entry, Exit, Product, Provider,
                     Purchase, Sale)

class BrandSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Brand
        fields = (
            'pk',
            'name'
        )

class CatalogueSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Catalogue
        fields = (
            'pk',
            'name'
        )

class ProductSerializer(serializers.HyperlinkedModelSerializer):

    brand = serializers.SlugRelatedField(queryset=Brand.objects.all(),
		slug_field='name', required=True, error_messages = {
            'does_not_exist': _("Brand with name {value} doesn't exit"),
        }
    )
    catalogue = serializers.SlugRelatedField(queryset=Catalogue.objects.all(),
		slug_field='name', required=True, error_messages = {
            'does_not_exist': _("Catalogue with name {value} doesn't exit"),
        }
    )

    code = serializers.CharField(max_length=80 , validators=[
        UniqueValidator(
            queryset=Product.objects.all(),
            message = _("Product code is unique")
        )],
    )

    class Meta:
        model = Product
        fields = (
            'pk',
            'name',
            'code',
            'details',
            'sale_price',
            'purchase_price',
            'brand',
            'catalogue',
            'stock')

    def validate_sale_price(self, data):
        if data <= 0:
            raise serializers.ValidationError(
                _("Price must be a positive number")
            )
        return data

    def validate_purchase_price(self, data):
        if data <= 0:
            raise serializers.ValidationError(
                _("Price must be a positive number")
            )
        return data

    def validate_stock(self, data):
        if data < 0:
            raise serializers.ValidationError(
                _("Product stock can't be negative")
            )
        return data

class ProviderSerializer(serializers.ModelSerializer):

    email = serializers.CharField(max_length=80 ,validators=[
        UniqueValidator(
            queryset=Provider.objects.all(),
            message = _('provider with this email already exists.')
        ),
        EmailValidator()
        ],
        allow_blank = True
    )

    class Meta:
        model = Provider
        fields = (
            'pk',
            'name',
            'phone',
            'email')

class SaleSerializer(serializers.ModelSerializer):

    product = serializers.SlugRelatedField(queryset=Product.objects.all(),
		slug_field='code', required=True, error_messages = {
            'does_not_exist': _("Product with code {value} doesn't exit"),
        }
    )

    sold = serializers.ReadOnlyField(
        source='get_amount_sold'
    )

    exit = serializers.SlugRelatedField(queryset=Exit.objects.all(),
		slug_field='pk', required=True, error_messages = {
            'does_not_exist': _("Exit with id {value} doesn't exit"),
        }
    )

    class Meta:
        model = Sale
        fields = (
            'pk',
            'exit',
            'product',
            'amount',
            'unit_price',
            'sold',
        )

    def validate_amount(self, amount):
        if amount < 0:
            raise serializers.ValidationError(
                _("Amount must be a positive number")
            )
        return amount

    def validate(self, data):

        curr_amount = self.instance.amount if self.instance else 0

        if self.instance:
            curr_product = self.instance.product
        else:
            curr_product = data['product']

        amount = data['amount']

        curr_stock = curr_product.stock

        if curr_amount + curr_stock - amount < 0:
            raise serializers.ValidationError(
                _("There is not enough stock for this product")
            )

        return data

class PurchaseSerializer(serializers.ModelSerializer):

    product = serializers.SlugRelatedField(queryset=Product.objects.all(),
		slug_field='code', required=True, error_messages = {
            'does_not_exist': _("Product with code {value} doesn't exit"),
        }
    )

    spent = serializers.ReadOnlyField(
        source='get_amount_spent'
    )

    entry = serializers.SlugRelatedField(queryset=Entry.objects.all(),
		slug_field='pk', required=True, error_messages = {
            'does_not_exist': _("Entry with id {value} doesn't exit"),
        }
    )

    class Meta:
        model = Purchase
        fields = (
            'pk',
            'entry',
            'product',
            'amount',
            'unit_price',
            'spent',
        )

    def validate_amount(self, amount):
        if amount < 0:
            raise serializers.ValidationError(
                _("Amount must be a positive number")
            )
        return amount

class ExitSerializer(serializers.HyperlinkedModelSerializer):

    user = serializers.ReadOnlyField(source='user.username')
    exit_sales = SaleSerializer(many=True, read_only=True)

    units_sold = serializers.ReadOnlyField(
        source='get_units_sold'
    )

    total_sold = serializers.ReadOnlyField(
        source='total_amount_sold'
    )

    client = serializers.SlugRelatedField(queryset=Client.objects.all(),
		slug_field='tice', required=False, allow_null=True, error_messages = {
            'does_not_exist': _("Client with name {value} doesn't exit"),
        }
    )

    class Meta:
        model = Exit
        fields = (
            'pk',
            'created_date',
            'user',
            'client',
            'units_sold',
            'total_sold',
            'exit_sales'
        )
        read_only_fields = ('created_date', 'user')

class EntrySerializer(serializers.HyperlinkedModelSerializer):

    user = serializers.ReadOnlyField(source='user.username')
    provider = serializers.SlugRelatedField(queryset=Provider.objects.all(),
		slug_field='name', required=True, error_messages = {
            'does_not_exist': _("Provider with name {value} doesn't exit"),
        }
    )
    entry_purchases = PurchaseSerializer(many=True, read_only=True)

    units_bought = serializers.ReadOnlyField(
        source='get_units_bought'
    )

    total_spent = serializers.ReadOnlyField(
        source='total_amount_spent'
    )

    class Meta:
        model = Entry
        fields = (
            'pk',
            'created_date',
            'user',
            'provider',
            'units_bought',
            'total_spent',
            'entry_purchases'
        )
        read_only_fields = ('created_date', 'user')

class ClientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Client
        fields = (
            'pk',
            'name',
            'phone',
            'tice',
        )


# WITHOUT static results

from util import path

from examples.vikoData_7rooms_vol2.exampleCrownstones.SimulatorCrownstone_cluster_neighbors_staticResults import SimulatorCrownstone
from examples.vikoData_7rooms_vol2.exampleInteractionModules.TrainingAndTesting import TrainingAndTesting
from simulator import SimulationGui, JsonFileStore, Simulator

#second room layout
mapData = JsonFileStore('./vikoData_7rooms_vol2/maps/officesExample.json').getData()
config = JsonFileStore('./vikoData_7rooms_vol2/maps/config.json').getData()
rooms = JsonFileStore('./vikoData_7rooms_vol2/maps/roomOverlay.json').getData()
userModule = JsonFileStore('./vikoData_7rooms_vol2/maps/userData.json').getData()

# #7 nodes, 1 per room
# testCS = SimulatorCrownstone(1, 4, 11)
# testCS.debugPrint = True
# simulatorCrownstones = [
# 	#room7
# 	testCS,
# 	#room6
# 	SimulatorCrownstone(2, 6, 7),
#   	#room1
#   	SimulatorCrownstone(3, 4, 3),
#   	#room3
# 	SimulatorCrownstone(4, 12, 4),
# 	#room2
# 	SimulatorCrownstone(5, 8, 5),
# 	#room5
# 	SimulatorCrownstone(6, 12, 8),
# 	#room4
# 	SimulatorCrownstone(7, 14, 10),
# ]

# #13 nodes
# simulatorCrownstones = [
# 	#room7
# 	SimulatorCrownstone(1, 5, 11),
# 	#room6
# 	SimulatorCrownstone(2, 6, 7),
#   	#room1
#   	SimulatorCrownstone(3, 4, 1),
#   	#room3
# 	SimulatorCrownstone(4, 12, 4),
# 	#room2
# 	SimulatorCrownstone(5, 6, 5),
# 	#room5
# 	SimulatorCrownstone(6, 11, 7),
# 	#room4
# 	SimulatorCrownstone(7, 15, 11),
# 	SimulatorCrownstone(8, 2, 8),
# 	SimulatorCrownstone(9, 15, 1),
# 	SimulatorCrownstone(10, 14, 8),
# 	SimulatorCrownstone(11, 2, 4),
# 	SimulatorCrownstone(12, 9, 8),
#  	SimulatorCrownstone(13, 2, 8),
# ]

#28 nodes
simulatorCrownstones = [
	SimulatorCrownstone(1, 9, 10), # X, Y positions in meters relative to zeroPoint on Map
	SimulatorCrownstone(2, 7, 12), # X, Y positions in meters relative to zeroPoint on Map
	SimulatorCrownstone(3, 6, 7), # X, Y positions in meters relative to zeroPoint on Map
    SimulatorCrownstone(4, 15, 5),
    SimulatorCrownstone(5, 1, 1),
    SimulatorCrownstone(6, 7, 2),
    SimulatorCrownstone(7, 9, 1),
	SimulatorCrownstone(8, 12, 4),
	SimulatorCrownstone(9, 16, 1),
	SimulatorCrownstone(10, 9, 4),
	SimulatorCrownstone(11, 6, 5),
	SimulatorCrownstone(12, 9, 8),
	SimulatorCrownstone(13, 2, 8),
	SimulatorCrownstone(14, 3, 5),
	SimulatorCrownstone(15, 1, 11),
	SimulatorCrownstone(16, 16, 7),
	SimulatorCrownstone(17, 11, 11),
	SimulatorCrownstone(18, 11, 7),
	SimulatorCrownstone(19, 14, 10),
	SimulatorCrownstone(20, 16, 11),
	SimulatorCrownstone(21, 13, 8),
	SimulatorCrownstone(22, 11, 1),
	SimulatorCrownstone(23, 7, 9),
	SimulatorCrownstone(24, 1, 4),
	SimulatorCrownstone(25, 14, 3),
	SimulatorCrownstone(26, 4, 10),
	SimulatorCrownstone(27, 4, 3),
	SimulatorCrownstone(28, 5, 1)
]

# create a custom interaction module
interactionModule = TrainingAndTesting("Victoria")

a = SimulationGui()
a.loadMap(mapData)
a.loadSimulatorCrownstones(simulatorCrownstones)
a.loadUserData(userModule)
a.loadConfig(config)
a.loadRooms(rooms)

b = Simulator()
b.loadInteractionModule(interactionModule)
b.loadCrownstones(simulatorCrownstones)
b.loadConfig(config)
a.loadSimulator(b)# this will load the user module into the simulator as a broadcaster.

# a.run()
# a.startSimulation(1270)

# running without gui interaction:
a.initScreen()
a.render(a.screen)
a.calculateGroundTruthMap()
a.getStaticResults(True)

# print("truth map", a.groundTruthMap)
# print("result map", a.resultMap)

#compare result map with ground Truth map
d1 = a.groundTruthMap
d2 = a.resultMap
counter = 0
correct = 0
for k1, v1 in d1.items():
    if k1 in d2:
        for v2 in d2[k1]:
            for ck in v1.keys():
                if ck in d2[k1]:
                    if (d1[k1][ck]!=None):
                        counter += 1
                        if (d1[k1][ck] == d2[k1][ck]):
                            correct += 1
accuracy = correct/counter * 100
print('Accuracy: ' + repr(accuracy) + '%')

# #create a map where the most accurate prediction among all crownstones will be saved
# c_map = {}
# conf_map = {}
# for x in range (85, 735, 10):
#     c_map[x] = {}
#     conf_map[x] = {}
#     for y in range(85, 855, 10):
#         c_map[x][y] = None
#         conf_map[x][y] = None
#
# count = 0
# for stone in simulatorCrownstones:
#     a.resultMap = stone.Map
#     a.render(a.screen)
#     #take the drawing of the result map of each crownstone
#     #a.makeScreenshot("cs_" + str(count) + "_ttl_4.png")
#     count += 1
#     d1 = a.groundTruthMap
#     d2 = a.resultMap
#     d3 = stone.confidence_Map
#     counter = 0
#     correct = 0
#     for k1, v1 in d1.items():
#         if k1 in d2:
#             for v2 in d2[k1]:
#                 for ck in v1.keys():
#                     if ck in d2[k1]:
#                         #I don't take into account the None labels (where no room corresponds) in the ground truth map
#                         if (d1[k1][ck] != None):
#                             counter += 1
#                             #I compare the label of each result map of every crownstone with the label in ground truth map. I don't take into account the
#                             #none values where the room is not in the range of crownstone so it cannot make a room prediction.
#                             if (d1[k1][ck]==d2[k1][ck]) and (d2[k1][ck] != None) :
#                                 correct += 1
#                                 c_map[k1][ck] = d1[k1][ck]
#                                 if (conf_map[k1][ck]== None):
#                                     conf_map[k1][ck] = d3[k1][ck]
#                                 else:
#                                     if (conf_map[k1][ck]<d3[k1][ck]):
#                                         conf_map[k1][ck] = d3[k1][ck]
#     if (correct != 0):
#         accuracy = correct/counter * 100
#         print ("cs_" + str(count) + 'Accuracy_total: ' + repr(accuracy) + '%')
#
# # the accuracy is not exactly the same for all the crownstones because of the radio map. When the radio map is constructed and the training
# # phase goes from one label_room to another there are some data that are still to be relayed as far as TTL = 4
# #
# # print ("conf_map", conf_map)
# # print(simulatorCrownstones[0].Map)
# # print (simulatorCrownstones[0].confidence_Map)
# # the accuracy regarding the c_map that has all the best predictions of all crownstones
# correct_1 = 0
# d1 = a.groundTruthMap
# d2 = c_map
# counter_1 = 0
# for k1, v1 in d1.items():
#     if k1 in d2:
#         for v2 in d2[k1]:
#             for ck in v1.keys():
#                 if ck in d2[k1]:
#                     if (d1[k1][ck]!= None):
#                         counter_1 += 1
#                         if (d1[k1][ck]==d2[k1][ck] and d2[k1][ck]!=None):
#                             correct_1 += 1
# Accuracy_cmap = correct_1/counter_1 * 100
# #print ("Combined result map", c_map)
# print ('Accuracy_cmap: ' + repr(Accuracy_cmap) + '%')


#方法一
###############################################################
def get_names(x = []) :
	L = []
	while True:
		name = input("請輸入學生姓名:")
		if not name:
			break
		L.append(name)
	x.extend(L) # 追加列表
	x[:] = L    # 切片賦值
	return L

names = get_names()
print(names)

# 方式2
###############################################################
def get_names(L = []) :
	while True:
		name = input("請輸入學生姓名:")
		if not name:
			break
		L.append(name)
	return L

n = []
get_names(n)
print(n)


#!/usr/bin/env python
# -*- python -*-
# -*- coding: utf-8 -*-

#
# Copyright 2011-2018 Red Hat, Inc.
#   This copyrighted material is made available to anyone wishing to use,
#  modify, copy, or redistribute it subject to the terms and conditions of
#  the GNU General Public License v.2.
#
#   This application is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   General Public License for more details.
#
# Authors:
#   Guy Streeter <guy.streeter@gmail.com>
#

from __future__ import print_function
import sys
import os
import subprocess

from setuptools import Command, setup
from distutils.command.build import build
from distutils.extension import Extension
from Cython.Distutils import build_ext

if sys.version_info[0] == 3:
    _package_name = 'python3-hwloc'
else:
    _package_name = 'python2-hwloc'

__author = 'Guy Streeter <guy.streeter@gmail.com>'
__author_email = 'guy.streeter@gmail.com'
__license = 'GPLv2+'
__description = 'python bindings for hwloc'
__version = '2.3.5.0.1.11.5'
__URL = 'https://gitlab.com/guystreeter/python-hwloc'
__classifiers = [
    'Environment :: Other Environment',
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
    'Operating System :: POSIX :: Linux',
    'Programming Language :: Python',
    'Topic :: System :: Systems Administration',
    ]

with open('README.rst') as rfile:
    __long_description = rfile.read()

datadir = os.environ.get('DATADIR', 'share')
docdir = os.path.join(datadir, 'doc', _package_name)
licdir = os.environ.get('LICENSEDIR',
                        os.path.join(datadir, 'doc', _package_name))

data_files = [
    (licdir, ['COPYING',
              'LICENSE',
              ]),
    (docdir, ['doc/hwloc-hello.py',
              'doc/guide.md',
              'doc/guide.html',
              ]),
]

class build_doc(Command):
    description = 'build guide.pdf and guide.html'
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        try:
            subprocess.call(
                ['/usr/bin/pandoc', '-o', 'doc/guide.html', 'doc/guide.md'])
            subprocess.call(
                ['/usr/bin/pandoc', '-o', 'doc/guide.pdf', '--toc', '-V',
                 'fontfamily:utopia', 'doc/guide.md'])
        except:
            print(
                'pandoc and texlive are required to build documentation',
                file=sys.stderr)

class all_build(build):
    sub_commands = [
        ('build_ext', None),
        ] + build.sub_commands

setup(
    name=_package_name,
    version=__version,
    description=__description,
    author=__author,
    author_email=__author_email,
    license=__license,
    classifiers=__classifiers,
    long_description=__long_description,
    url=__URL,
    packages=['hwloc'],
    data_files=data_files,
    cmdclass={
        'build': all_build,
        'build_doc': build_doc,
        'build_ext': build_ext,
        },
    ext_modules=[
        Extension(
            'hwloc.chwloc',
                ['chwloc.pyx'],
            libraries=['hwloc']),
        Extension(
            'hwloc.linuxsched',
            ['linuxsched.pyx'])])