#!/usr/bin/env python
from tools.multiclass_shared import prepare_data

[traindat, label_traindat, testdat, label_testdat] = prepare_data()

parameter_list = [[traindat,testdat,label_traindat,2.1,1,1e-5],[traindat,testdat,label_traindat,2.2,1,1e-5]]

def classifier_multiclassmachine (fm_train_real=traindat,fm_test_real=testdat,label_train_multiclass=label_traindat,width=2.1,C=1,epsilon=1e-5):
	from shogun import MulticlassLabels
	from shogun import KernelMulticlassMachine, MulticlassOneVsRestStrategy
	import shogun as sg

	feats_train=sg.features(fm_train_real)
	feats_test=sg.features(fm_test_real)
	kernel=sg.kernel("GaussianKernel", log_width=width)

	labels=MulticlassLabels(label_train_multiclass)

	classifier = sg.machine("LibSVM", epsilon=epsilon)
	#print labels.get_labels()
	mc_classifier = KernelMulticlassMachine(MulticlassOneVsRestStrategy(),kernel,classifier,labels)
	mc_classifier.train(feats_train)

	kernel.init(feats_train, feats_test)
	out = mc_classifier.apply().get_labels()
	return out

if __name__=='__main__':
	print('MulticlassMachine')
	classifier_multiclassmachine(*parameter_list[0])


import datetime

from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from django.db.models import Sum

from .models import ReadNum
from .models import ReadDetail

def read_statistics_once_read(request, obj):
    ct = ContentType.objects.get_for_model(obj)
    key = '%s_%s_read' % (ct.model, obj.pk)
    if not request.COOKIES.get(key):  # 如果不存在该键值，则执行+1操作
        # 总阅读数+1
        # 利用get_or_create方法，判断是否存在该条记录，存在则返回一个元祖：实例化对象（object）和是否被创建的bool值（created）
        # 不存在，则创建实例化对象，同样返回一个元祖（obj，created）
        readnum, created = ReadNum.objects.get_or_create(content_type=ct, object_id=obj.pk)
        readnum.read_num += 1
        readnum.save()

        # # 上面三个语句，为此注释的优化后代码
        # # 触发该视图函数，对应的文章的阅读数自增1
        # if ReadNum.objects.filter(content_type=ct, object_id=obj.pk).count():
        #     # 存在记录
        #     # 上面已经导入.models.py 中的ReadNum模型
        #     # 下面语句，通过blog=blog关键参数，获取对应的一条记录，并赋值给局部变量readnum
        #     readnum = ReadNum.objects.get(content_type=ct, object_id=obj.pk)
        # else:
        #     # 不存在对应的记录
        #     # 下面语句，通过blog=blog关键参数，实例化创建对应的一条记录，并赋值给局部变量readnum
        #     readnum = ReadNum(content_type=ct, object_id=obj.pk)
        #
        # # 在模型ReadNum 的数据库模型中，无论是否存在该条记录，只要cookies中没有记录，则需要执行阅读数+1操作，并保存
        # readnum.read_num += 1
        # readnum.save()
        ''''''
        # 每天的阅读数
        date = timezone.now().date()
        # if ReadDetail.objects.filter(content_type=ct, object_id=obj.pk, date=date).count():
        #     readDetail = ReadDetail.objects.get(content_type=ct, object_id=obj.pk, date=date)
        # else:
        #     readDetail = ReadDetail(content_type=ct, object_id=obj.pk, date=date)
        readDetail, created = ReadDetail.objects.get_or_create(content_type=ct, object_id=obj.pk, date=date)
        readDetail.read_num += 1
        readDetail.save()
    return key

def get_seven_days_read_data(content_type):
    today = timezone.now().date()  # 获取今天的日期
    read_nums = []  # 保存阅读数
    dates = []  # 保存日期
    for i in range(7, 0, -1):
        # datetime python内置模块，方法timedelta，提供日期差（根据days参数的设置）
        # 下面这条语句，获得最近7天的日期
        date = today - datetime.timedelta(days=i)

        dates.append(date.strftime('%m/%d'))
        read_details = ReadDetail.objects.filter(content_type=content_type, date=date)
        # aggregate聚合函数（对数据库），返回值：字典{'read_num_sum':6}
        result = read_details.aggregate(read_num_sum=Sum('read_num'))
        read_nums.append(result['read_num_sum'] or 0)  # 常用逻辑判断，如果为FALSE，则取0
    return dates, read_nums

def get_today_hot_data(content_type):
    today = timezone.now().date()  # 获取今天的日期
    read_details = ReadDetail.objects.filter(content_type=content_type, date=today).order_by('-read_num')
    return read_details[:7]

def get_yesterday_hot_data(content_type):
    today = timezone.now().date()  # 获取今天的日期
    yesterday = today - datetime.timedelta(days=1)

    read_details = ReadDetail.objects.filter(content_type=content_type, date=yesterday).order_by('-read_num')
    return read_details[:7]


import speech_recognition as sr

def transcribe(AUDIO_FILE):

	# Read the audio file
	r = sr.Recognizer()
	with sr.AudioFile(AUDIO_FILE) as source:
		audio = r.record(source)

	try:
		return r.recognize_sphinx(audio)
	except sr.UnknownValueError:
		return -1
	except sr.RequestError as e:
		return -1


#!usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt
import assignment71 as a71

L = 1
U = 1
mu = 1
T = .1

Ny = 100
dy = L/(Ny-1)
dt = .00001
Nt = round(T/dt + 1)

t = np.zeros(Nt)
y = np.zeros(Ny)
u = np.zeros([Nt,Ny])

for i in range(Ny):
  y[i] = i*dy

i = 1
while (i < Nt):
  t[i] = t[i] + dt
  u[i,:] = a71.couette_flow(u[i-1,:],U,mu,dt,dy)
  u[i,0] = -U
  u[i,Ny-1] = U
  i = i + 1

plt.plot(u[round(Nt/8),:],y,u[round(Nt/4),:],y,u[round(Nt/2),:],y,u[Nt-1,:],y)
plt.show()


import math
import models
import tensorflow as tf
import numpy as np
import utils
from tensorflow import flags
import tensorflow.contrib.slim as slim
FLAGS = flags.FLAGS

class PositionalCnnDeepCombineChainModel(models.BaseModel):
  """Add positional embedding for cnn"""

  def cnn(self,
          model_input,
          l2_penalty=1e-8,
          num_filters = [1024, 1024, 1024],
          filter_sizes = [1,2,3],
          sub_scope="",
          **unused_params):
    max_frames = model_input.get_shape().as_list()[1]
    num_features = model_input.get_shape().as_list()[2]

    shift_inputs = []
    for i in xrange(max(filter_sizes)):
      if i == 0:
        shift_inputs.append(model_input)
      else:
        shift_inputs.append(tf.pad(model_input, paddings=[[0,0],[i,0],[0,0]])[:,:max_frames,:])

    cnn_outputs = []
    for nf, fs in zip(num_filters, filter_sizes):
      sub_input = tf.concat(shift_inputs[:fs], axis=2)
      sub_filter = tf.get_variable(sub_scope+"cnn-filter-len%d"%fs,
                       shape=[num_features*fs, nf], dtype=tf.float32,
                       initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1),
                       regularizer=tf.contrib.layers.l2_regularizer(l2_penalty))
      cnn_outputs.append(tf.einsum("ijk,kl->ijl", sub_input, sub_filter))

    cnn_output = tf.concat(cnn_outputs, axis=2)
    return cnn_output

  def add_positional_embedding(self, model_input, num_frames, l2_penalty=1e-8):
    batch_size, max_frames, num_features = model_input.get_shape().as_list()
    positional_embedding = tf.get_variable("positional_embedding", dtype=tf.float32,
                                shape=[1, max_frames, num_features],
                                initializer=tf.zeros_initializer(),
                                regularizer=tf.contrib.layers.l2_regularizer(l2_penalty))
    mask = tf.sequence_mask(lengths=num_frames, maxlen=max_frames, dtype=tf.float32)
    model_input_with_positional_embedding = tf.einsum("ijk,ij->ijk", model_input + positional_embedding, mask)
    return model_input_with_positional_embedding

  def gated_linear_unit(self, input1, input2):
    return tf.nn.softmax(input1) * input2

  def create_model(self, model_input, vocab_size, num_frames, num_mixtures=None,
                   l2_penalty=1e-8, sub_scope="", original_input=None, **unused_params):
    num_supports = FLAGS.num_supports
    num_layers = FLAGS.deep_chain_layers
    relu_cells = FLAGS.deep_chain_relu_cells
    max_frames = model_input.get_shape().as_list()[1]
    relu_layers = []
    support_predictions = []

    # add positional embedding
    model_input = self.add_positional_embedding(model_input, num_frames, l2_penalty=l2_penalty)

    mask = tf.sequence_mask(lengths=num_frames, maxlen=max_frames, dtype=tf.float32)
    mean_input = tf.einsum("ijk,ij->ik", model_input, mask) \
                      / tf.expand_dims(tf.cast(num_frames, dtype=tf.float32), dim=1)
    mean_relu = slim.fully_connected(
          mean_input,
          relu_cells,
          activation_fn=tf.nn.relu,
          weights_regularizer=slim.l2_regularizer(l2_penalty),
          scope=sub_scope+"mean-relu")
    mean_relu_norm = tf.nn.l2_normalize(mean_relu, dim=1)
    relu_layers.append(mean_relu_norm)

    cnn_output1 = self.cnn(model_input, num_filters=[relu_cells,2*relu_cells,relu_cells], filter_sizes=[1,2,3], sub_scope=sub_scope+"cnn0-output1")
    cnn_output2 = self.cnn(model_input, num_filters=[relu_cells,2*relu_cells,relu_cells], filter_sizes=[1,2,3], sub_scope=sub_scope+"cnn0-output2")
    cnn_output = self.gated_linear_unit(cnn_output1, cnn_output2)

    max_cnn_output = tf.reduce_max(cnn_output, axis=1)
    normalized_cnn_output = tf.nn.l2_normalize(max_cnn_output, dim=1)
    next_input = normalized_cnn_output

    for layer in xrange(num_layers):
      sub_prediction = self.sub_model(next_input, vocab_size, sub_scope=sub_scope+"prediction-%d"%layer)
      support_predictions.append(sub_prediction)

      sub_relu = slim.fully_connected(
          sub_prediction,
          relu_cells,
          activation_fn=tf.nn.relu,
          weights_regularizer=slim.l2_regularizer(l2_penalty),
          scope=sub_scope+"relu-%d"%layer)
      relu_norm = tf.nn.l2_normalize(sub_relu, dim=1)
      relu_layers.append(relu_norm)

      cnn_output1 = self.cnn(model_input, num_filters=[relu_cells,2*relu_cells,relu_cells], filter_sizes=[1,2,3], sub_scope=sub_scope+"cnn%d-output1"%(layer+1))
      cnn_output2 = self.cnn(model_input, num_filters=[relu_cells,2*relu_cells,relu_cells], filter_sizes=[1,2,3], sub_scope=sub_scope+"cnn%d-output2"%(layer+1))
      cnn_output = self.gated_linear_unit(cnn_output1, cnn_output2)

      max_cnn_output = tf.reduce_max(cnn_output, axis=1)
      normalized_cnn_output = tf.nn.l2_normalize(max_cnn_output, dim=1)
      next_input = tf.concat([mean_input, normalized_cnn_output] + relu_layers, axis=1)

    main_predictions = self.sub_model(next_input, vocab_size, sub_scope=sub_scope+"-main")
    support_predictions = tf.concat(support_predictions, axis=1)
    return {"predictions": main_predictions, "support_predictions": support_predictions}

  def sub_model(self, model_input, vocab_size, num_mixtures=None,
                l2_penalty=1e-8, sub_scope="", **unused_params):
    num_mixtures = num_mixtures or FLAGS.moe_num_mixtures

    gate_activations = slim.fully_connected(
        model_input,
        vocab_size * (num_mixtures + 1),
        activation_fn=None,
        biases_initializer=None,
        weights_regularizer=slim.l2_regularizer(l2_penalty),
        scope="gates-"+sub_scope)
    expert_activations = slim.fully_connected(
        model_input,
        vocab_size * num_mixtures,
        activation_fn=None,
        weights_regularizer=slim.l2_regularizer(l2_penalty),
        scope="experts-"+sub_scope)

    gating_distribution = tf.nn.softmax(tf.reshape(
        gate_activations,
        [-1, num_mixtures + 1]))  # (Batch * #Labels) x (num_mixtures + 1)
    expert_distribution = tf.nn.sigmoid(tf.reshape(
        expert_activations,
        [-1, num_mixtures]))  # (Batch * #Labels) x num_mixtures

    final_probabilities_by_class_and_batch = tf.reduce_sum(
        gating_distribution[:, :num_mixtures] * expert_distribution, 1)
    final_probabilities = tf.reshape(final_probabilities_by_class_and_batch,
                                     [-1, vocab_size])
    return final_probabilities

  def get_mask(self, max_frames, num_frames):
    mask_array = []
    for i in xrange(max_frames + 1):
      tmp = [0.0] * max_frames
      for j in xrange(i):
        tmp[j] = 1.0
      mask_array.append(tmp)
    mask_array = np.array(mask_array)
    mask_init = tf.constant_initializer(mask_array)
    mask_emb = tf.get_variable("mask_emb", shape = [max_frames + 1, max_frames],
            dtype = tf.float32, trainable = False, initializer = mask_init)
    mask = tf.nn.embedding_lookup(mask_emb, num_frames)
    return mask


import pygame
from pygame.locals import *

class InputManager:
  def __init__(self, event, renderer):
    self.event = event
    self.renderer = renderer
    self.windowSize = (0,0)
    self.arrowKeys = [False,False,False,False] #up down left right
    self.panSpeed = 0.3
    self.pan = (0,0)

  def update(self):
    xPan, yPan = (0,0)
    x,y = pygame.mouse.get_pos()

    if x < 100:
      xPan = (x-100)/500.0
    elif x > self.windowSize[0]-100:
      xPan = (x-(self.windowSize[0]-100))/500.0

    if y < 100:
      yPan = (y-100)/500.0
    elif y > self.windowSize[1]-100:
      yPan = (y-(self.windowSize[1]-100))/500.0

    if (xPan,yPan) != self.pan:
      self.pan = (xPan,yPan)
      self.event.notify("setPan",(xPan,yPan))

  def setWindowSize(self,size):
    self.windowSize = size

  def registerClick(self, pos, button, down):
    x,y = self.renderer.toGlobalCoord(pos)

    if down and button == 1:
      self.event.notify("leftClick", (x,y))
    elif down and button == 3:
      self.event.notify("rightClick", (x,y))

  def registerKey(self, key, down):
    if down:
      if key == K_UP:
        self.arrowKeys[0] = True
      elif key == K_DOWN:
        self.arrowKeys[1] = True
      elif key == K_LEFT:
        self.arrowKeys[2] = True
      elif key == K_RIGHT:
        self.arrowKeys[3] = True
    else:
      if key == K_UP:
        self.arrowKeys[0] = False
      elif key == K_DOWN:
        self.arrowKeys[1] = False
      elif key == K_LEFT:
        self.arrowKeys[2] = False
      elif key == K_RIGHT:
        self.arrowKeys[3] = False

    xPan = yPan = 0

    if self.arrowKeys[0]: yPan -= self.panSpeed
    if self.arrowKeys[1]: yPan += self.panSpeed
    if self.arrowKeys[2]: xPan -= self.panSpeed
    if self.arrowKeys[3]: xPan += self.panSpeed

    self.event.notify("setPan",(xPan,yPan))


from __future__ import division
__author__ = 'mushahidalam'
import json

class SearchUPC():
    hashtable_upc={}

    def hashfunc(self,str1):
        #hashfunc
        hashvalue=0
        for i in range(0,len(str1)-1):
            hashvalue+=ord(str1[i])
        return hashvalue

    def searchHastable(self,product):
        #Search in Product Name
        len_limit = 12
        try:
            ProdName = product['Product Name'][0].split(' ')
            for key in ProdName:
                if len(key)<len_limit:
                    continue
                if key in self.hashtable_upc:
                    return '['+"'"+key+"'"+']'
        except:
            pass
        #Search in Product short description
        try:
            ProdShortDesc = product['Product Short Description'][0].split(' ')
            # print(ProdShortDesc)
            for key in ProdShortDesc:
                key = key.lower()
                if len(key)<len_limit:
                    continue
                if key in self.hashtable_upc:
                    return '['+"'"+key+"'"+']'
        except:
            pass

        #search in Product Long Description
        try:
            ProdLongDesc = product['Product Long Description'][0].split(' ')
            for key in ProdLongDesc:
                key = key.lower()
                if len(key)<len_limit:
                    continue
                if key in self.hashtable_upc:
                    return '['+"'"+key+"'"+']'
        except:
            # print("parse error")
            pass
        return ''

    def __init__(self):
        #Intialize the Hastable of Possible MPN from dictonary
        for line in open("upc/elec_upc_dic.txt", 'rw+'):
            line = line.rstrip('\n')
            line = line.strip()
            str1 = ''
            for i in range(len(line)-1,0,-1):
                if line[i].isspace() ==False:
                    continue
                else:
                    str1 = line[:i]
                    break
            str1 = str1.replace('\t','')
            str1 = str1.strip()
            hashval = self.hashfunc(str1)
            if str1 not in self.hashtable_upc:
                self.hashtable_upc[str1]= [hashval]
            else:
                # print('Append to same value')
                self.hashtable_upc[str1].append([hashval])

    def dict_init(self,dict_path):
        #Intialize the Hastable of Possible MPN from dictonary
        self.hashtable_upc.clear()
        for line in open(dict_path, 'rw+'):
            line = line.rstrip('\n')
            line = line.strip()
            str1 = ''
            for i in range(len(line)-1,0,-1):
                if line[i].isspace() ==False:
                    continue
                else:
                    str1 = line[:i]
                    break
            str1 = str1.replace('\t','')
            str1 = str1.strip()
            hashval = self.hashfunc(str1)
            if str1 not in self.hashtable_upc:
                self.hashtable_upc[str1]= [hashval]
            else:
                # print('Append to same value')
                self.hashtable_upc[str1].append([hashval])

    def ProbeUPC(self,product,str):
        try:
            result1 = product['Product Short Description'][0].find(str)
        except:
            result1 = -1
        try:
            result2 = product['Product Long Description'][0].find(str)
        except:
            result2 = -1
        try:
            result3 = product['Product Name'][0].find(str)
        except Exception as ex:
            result3 = -1
        if result1!=-1 or result2!=-1 or result3!=-1:
            return True
        else:
            return False

    def search_UPC(self,wal_json,vend_json,*dict_path):
        if len(dict_path) > 0:
            self.dict_init(dict_path[0])
        dict_probe_found_UPC = 0
        mpn_found=0
        found = 0
        count=0
        try:
            UPC_walmart = wal_json['UPC']
        except:
            UPC_walmart =''#not found set it to NULL

        try:
            UPC_vendor = vend_json['UPC']
        except:
            if UPC_walmart=='':
                UPC_vendor = ''
            else:
                #Probe the UPC_walmart in Product short or long Description or Name
                if self.ProbeUPC(vend_json,UPC_walmart[0])== True:
                    UPC_vendor=UPC_walmart
                    mpn_found+=1
                    dict_probe_found_UPC = 1
                else:
                    UPC_vendor=''
        if UPC_walmart=='':
            if UPC_vendor=='':
                count+=1
            else:
                #Probe the UPC_vendor in Product short or long Description & Name
                if self.ProbeUPC(wal_json,UPC_vendor[0])== True:
                    UPC_vendor=UPC_walmart
                    mpn_found+=1
                    dict_probe_found_UPC = 1
                else:
                    UPC_walmart=''

        #search the dictonary
        if UPC_walmart=='':
            UPC_walmart = self.searchHastable(wal_json)
            if UPC_walmart!='':
                found+=1
                dict_probe_found_UPC = 1
                # print('Found in Description Walmart',found,UPC_walmart)
        if UPC_vendor=='':
            UPC_vendor = self.searchHastable(vend_json)
            if UPC_vendor!='':
                found+=1
                dict_probe_found_UPC = 1
                # print('Found in Description Vendor',found,UPC_vendor)
        # print(UPC_walmart[0],UPC_vendor[0])
        if dict_probe_found_UPC == 1:
            confidence = 0.5
        else:
            confidence = 1
        if UPC_walmart=='' and UPC_vendor=='':
            return UPC_walmart,UPC_vendor,confidence
        if UPC_walmart=='':
            return UPC_walmart,UPC_vendor[0],confidence
        elif UPC_vendor=='':
            return UPC_walmart[0],UPC_vendor,confidence
        else:
            return UPC_walmart[0],UPC_vendor[0],confidence


from dindins.characters.lucy import Lucy
from dindins.characters.juice import Juice
from dindins.objects import *

class Screen(pygame.Surface):
    """Base Screen Object

    This provides the base screen object that other screens inherit off. It itself inherits from the pygame.Surface
    object so it can easily be rendered and interacted by other pygame objects. It includes lists of GUI elements that
    can be rendered, as well as an abstract update method, and a render method. The render method is not to be changed
    by child objects unless for good reason. The update method is to be implemented by the child object.

    Attributes:
        text: List of text to be rendered
        buttons: List of buttons to be rendered
        sprites: pygame.sprite.Group of sprites to be rendered
        dialogue: List of dialogue boxes to be rendered
    """
    def __init__(self):
        """Initiates pygame.Surface and attributes"""
        super().__init__((WIDTH, HEIGHT))
        self.rect = self.get_rect()
        self.rect.center = ((WIDTH / 2, HEIGHT / 2))

        self.text = []
        self.buttons = []
        self.dialogue = []
        self.player = pygame.sprite.GroupSingle()
        self.gameobjects = ObjectsGroup()

    def handle(self, event):
        """Handles events

        This method is to be implemented by the child object. The handler is used to process any events the current
        screen may be interested in. If no events are needed, then the implementation of this method can be omitted.

        Args:
            event: pygame.Event to be handled
        """
        pass

    def update(self):
        """Updates the screen

        This method is to be implemented by the child object. The update method is used to place any code that needs to
        be called once every frame. For example, game logic of holding down a directional key to move the screen
        up/down/left/right. It also indicates that the screen should be updated to a different screen. For example,
        clicking the 'Options' button on the main menu will cause the screen to be updated, no longer rendering the
        main menu but instead the options screen.

        Returns:
            This method must return the screen to be rendered. If no change of screen is needed then return self.
        """
        pass

    def render(self):
        """Renders all gui elements

        Renders each GUI element currently in the attribute lists.
        """
        # Clear screen
        self.fill(BLACK)

        # Text
        for surf, rect in self.text:
            self.blit(surf, rect)

        # Buttons
        for button in self.buttons:
            button.render()
            self.blit(button, button.rect)

        # Game objects
        self.gameobjects.update()
        self.gameobjects.draw(self)

        # Player
        self.player.update()
        self.player.draw(self)

        # Dialogue boxes
        for box in self.dialogue:
            if box.finished:
                self.dialogue.remove(box)
            else:
                box.render()
                self.blit(box, box.rect)

class MainMenu(Screen):
    def __init__(self):
        super().__init__()

        # List of text and buttons
        self.text = []
        self.buttons = []

        # GUI elements
        title = Text.render('Din Dins', RED, (WIDTH / 2, HEIGHT / 8), size=50)
        playbtn = Button('Play', (WIDTH / 2, HEIGHT / 2), action=self._rungame)
        optionsbtn = Button('Options', (WIDTH / 2, HEIGHT / 2 + 110), action=self._options)

        # Add elements to be rendered
        self.text.append(title)
        self.buttons.append(playbtn)
        self.buttons.append(optionsbtn)

        # Flags for displaying other screens
        self.rungame = False
        self.options = False

    def _options(self):
        self.options = True

    def _rungame(self):
        self.rungame = True

    def update(self):
        if self.rungame:
            return GameScreen()
        elif self.options:
            return OptionsMenu()
        else:
            return self

class GameScreen(Screen):
    """In game screen

    This screen handles all interactions and rendering for the DinDins game. The update method is used to move objects
    around the screen to keep the camera centered on the player. The handle method handles in game events such as
    object interaction, pausing/resuming, and hiding.

    Attributes:
        player: pygame.sprite.GroupSingle containing the sprite of the player
        speed: Int describing the movement speed in pixels per frame
        hiding: Boolean indicating if the player is currently hiding
        temp: Variable used to temporarily store any information
        gameobjects: pygame.sprite.Group of every other object in the game
    """
    def __init__(self):
        """Loads initial objects"""
        super().__init__()

        # Add player character
        self.player.add(Lucy())

        # State variables
        self.speed = 3
        self.stamina = StaminaBar((100, 750), 100)
        self.hiding = False
        self.paused = False
        self.temp = None
        self.gameover = False

        self.buttons.append(self.stamina)

        self.objectives = [
            'eat_food',
            'hide_under_bed',
            'go_to_food',
            'avoid_juice',
            'nothing'
        ]

        # Floor
        self.gameobjects.add(
            tileset((590, -226), 10, 7, 'living_floor'),
            tileset((495, 18), 7, 7, 'courtyard_floor', type='tile'),
            tileset((580, 630), 3, 2, 'lobby_floor'),
            tileset((589, 534), 2, 25, 'hallway_floor'),
            tileset((493, 94), 1, 2, 'alcove_floor'),
            tileset((495, 376), 7, 5, 'bedroom_floor', type='carpet')
        )

        # Walls
        self.gameobjects.add(
            tile((600, 210), 11, 875, 'hallway_east', boundingbox=(-1, 438, 5, 438)),  # Hallway east wall
            tile((535, 645), 140, 10, 'lobby_south', boundingbox=(70, 1, 70, 1)),  # Lobby south wall
            tile((470, 595), 10, 100, 'lobby_west', boundingbox=(5, 50, -2, 50)),  # Lobby west wall
            tile((490, 545), 50, 10, 'lobby_north', boundingbox=(25, 19, 5, -18)),   # Lobby north wall
            tile((510, 470), 10, 160, 'hallway_west_lobbytobedroom', boundingbox=(5, 79, -2, 59)),  # Hallway west wall (lobby -> bedroom)
            tile((380, 395), 250, 10, 'bedroom_south', boundingbox=(125, 1, 125, 1)),  # Bedroom south wall
            tile((510, 215), 10, 220, 'hallway_west_bedroomtostudy', boundingbox=(3, 110, -2, 90)),  # Hallway west wall (bedroom -> study)
            tile((380, 195), 250, 10, 'bedroom_north', boundingbox=(125, 19, 125, -18)),  # Bedroom north wall
            tile((260, 295), 10, 200, 'bedroom_west', boundingbox=(5, 100, -2, 100)),  # Bedroom west wall
            tile((480, 110), 50, 10, 'alcove_south', boundingbox=(25, 1, 25, 1)),    # Alcove south wall
            tile((450, 65), 10, 100, 'alcove_west', boundingbox=(5, 50, -2, 50)),  # Alcove west wall
            tile((480, 20), 50, 10, 'alcove_north', boundingbox=(25, 19, 25, -18)),    # Alcove north wall
            tile((510, -100), 10, 250, 'hallway_west_glass', boundingbox=(5, 120, -2, 100)),  # Hallway west wall, looking into courtyard
            tile((385, -220), 250, 10, 'living_south_glass', boundingbox=(125, 1, 125, 1)),   # Living room south wall, looking into courtyard
            tile((259, -219), 11, 502, 'courtyard_kitchen_west', boundingbox=(5, 250, -2, 250)),   # Courtyard and kitchen west wall
            tile((355, 30), 200, 10, 'study_north_glass'),  # Study north wall, looking into courtyard
            tile((435, -465), 355, 10, 'living_north', boundingbox=(178, 19, 178, -18)),     # Living room/kitchen north wall
            tile((610, -345), 10, 250, 'living_east', boundingbox=(-1, 125, 5, 125))      # Living room east wall
        )

        # Doors
        greysurface = pygame.Surface((50, 20))
        greysurface.fill(GREY)
        self.gameobjects.add(
            DialogueBoxObject((560, 645), greysurface, 'Scary people come through this door. I would never dare go out there.', 'front_door'),     # Front door
            DialogueBoxObject((510, 450), pygame.transform.rotate(greysurface, 90), 'My humans litterbox is in there.', 'bathroom_door_hallway'),    # Bathroom door (from hallway)
            DialogueBoxObject((470, 595), pygame.transform.rotate(greysurface, 90), 'I used to sleep in this room, but now it\'s never open.', 'storage_door'),   # Room 1
            DialogueBoxObject((440, 395), greysurface, 'My humans litterbox is in there.', 'bathroom_door_bedroom'),  # Bathroom door (from bedroom)
            DialogueBoxObject((320, 395), greysurface, 'This goes to a courtyard. There was once a trapped bird in there.', 'courtyard_door_bedroom'),   # Bedroom courtyard
            DialogueBoxObject((510, 150), pygame.transform.rotate(greysurface, 90), 'This is where my humans spend most of their time. It\'s only open when they\'re home.', 'study_door'),          # Study
            DialogueBoxObject((325, -485), pygame.image.load(f'{ASSETS}/objects/door.png'), 'Scary sounds come from this door. But my humans also come through here.', 'garage_door')    # Garage
        )

        # Other objects
        self.gameobjects.add(
            BaseObject((425, -270), pygame.image.load(f'{ASSETS}/objects/rug2.png'), 'table_rug'),
            HideObject((425, -285), pygame.image.load(f'{ASSETS}/objects/table.png'), 'table', boundingbox=(28, 22, 28, 10)),
            BaseObject((340, 200), pygame.image.load(f'{ASSETS}/objects/dresser.png'), 'dresser1', boundingbox=(7, 18, 8, 1)),
            BaseObject((440, 200), pygame.image.load(f'{ASSETS}/objects/dresser.png'), 'dresser2', boundingbox=(6, 18, 7, 1)),
            BaseObject((585, -385), pygame.image.load(f'{ASSETS}/objects/tv.png'), 'tv', boundingbox=(18, 64)),
            BaseObject((375, -410), pygame.image.load(f'{ASSETS}/objects/bench1.png'), 'bench1', boundingbox=(7, 56, 5, 35)),
            BaseObject((278, -410), pygame.image.load(f'{ASSETS}/objects/bench2.png'), 'bench2', boundingbox=(7, 56, 5, 35)),
            BaseObject((325, -390), pygame.image.load(f'{ASSETS}/objects/rug1.png'), 'kitchen_rug'),
            BaseObject((518, -375), pygame.image.load(f'{ASSETS}/objects/rug3.png'), 'living_rug'),
            BaseObject((519, -380), pygame.image.load(f'{ASSETS}/objects/coffee_table.png'), 'coffee_table',  boundingbox=(10, 26, 5, 6)),
            BaseObject((585, -460), pygame.image.load(f'{ASSETS}/objects/lamp.png'), 'lamp', boundingbox='image'),
            BaseObject((585, -315), pygame.image.load(f'{ASSETS}/objects/plant.png'), 'plant', boundingbox=(20, 10)),
            BaseObject((455, -385), pygame.image.load(f'{ASSETS}/objects/couch.png'), 'couch', boundingbox=(7, 40, 10, 20)),
            BaseObject((283, 280), pygame.image.load(f'{ASSETS}/objects/wardrobe.png'), 'wardrobe', boundingbox=(18, 48, 5, 30)),
        )

        # Objective objects
        self.gameobjects.add(
            Bowls(self.objectives),
            Bed(self.objectives),
        )

        # Shift objects for initial positioning
        for object in self.gameobjects.sprites():
            object.move(-50, 800)

    def _collide(self):
        for object in self.gameobjects.colliders():
            if self.player.sprite.rect.colliderect(object.boundingbox):
                return True

    def _trigger(self):
        for object in self.gameobjects.triggerables():
            if self.player.sprite.rect.colliderect(object.rect):
                object.trigger()

    def handle(self, event):
        """Handles in game events

        This method handles all events in game. This includes pressing the space bar to interact with objects,
        pausing/resuming, and hiding.

        Args:
            event: pygame.Event object to handle
        """
        # Space to interact with objects
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Regular interaction
                if not self.paused and not self.hiding:
                    for object in self.gameobjects.interactables():
                        # Allows for interaction with collidable objects
                        if pygame.sprite.collide_rect_ratio(1.25)(self.player.sprite, object):
                            object.interact()

                # Stop hiding
                elif self.hiding and not self.paused:
                    # Resume player
                    self.player.sprite.pause = False
                    self.hiding = False
                    self.speed = 3

                    # Revert objects using saved offset
                    for object in self.gameobjects.sprites():
                        object.move(-1 * self.temp[0],  -1 * self.temp[1])

        # Pause the game
        elif event.type == PAUSE:
            self.paused = True
            self.speed = 0
            self.player.sprite.pause = True

            # Pause Juice if she is in game
            juice = self.gameobjects.get('juice')
            if juice:
                juice.pause = True

        # Resume the game
        elif event.type == RESUME:
            self.paused = False
            self.speed = 3
            # Only show the player if they are not hiding
            if not self.hiding:
                self.player.sprite.pause = False

            # Resume Juice if she is in game
            juice = self.gameobjects.get('juice')
            if juice:
                juice.pause = False

        # Hide
        # Hiding pauses only the player (not NPCs), and makes the player sprite transparent.
        elif event.type == HIDE:
            # Pause player
            self.player.sprite.pause = True
            self.speed = 0
            self.hiding = True

            # Make player transparent
            self.player.sprite.image = pygame.image.load(f'{ASSETS}/terrain/transparent.png')

            # If move is set to false then move camera to center of hiding object
            if not event.move:
                # Get player and object coordinates
                object = event.object.rect.center
                pos = self.player.sprite.rect.center

                # Calculate and save offset so we can revert when not hiding
                x = pos[0] - object[0]
                y = pos[1] - object[1]
                self.temp = (x, y)

                # Move objects
                for object in self.gameobjects.sprites():
                    object.move(x, y)

        # Render given objects
        elif event.type == RENDER:
            for object in event.objects:
                if type(object) == DialogueBox:
                    self.dialogue.append(object)
                    pygame.event.post(pygame.event.Event(PAUSE, {}))
                else:
                    self.gameobjects.add(object)

        # Objective completed
        elif event.type == OBJECTIVE:
            self.objectives.remove(event.objective)

            if self.objectives[0] == 'go_to_food':
                self.gameobjects.add(SpawnTrigger(
                    (660, 500),
                    pygame.image.load(f'{ASSETS}/terrain/transparent.png'),
                    'juice_trigger',
                    Juice((510, -200)),
                    DialogueBox('Oh no, it\'s Juice! She always bullies me when the humans leave. I better avoid her.', (WIDTH / 2, HEIGHT * .8))
                ))

        elif event.type == GAME_OVER:
            self.gameover = True

    def update(self):
        """Updates the screen

        To keep the 'camera' centered on Lucy, we move the objects on the screen instead of the Lucy sprite. So we
        update rect x and y coordinates when the directional keys are pressed to achieve this.

        Returns:
            The screen to be rendered
        """
        speed_x = 0
        speed_y = 0

        # Movement
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            speed_x = self.speed
        if keystate[pygame.K_RIGHT]:
            speed_x = self.speed * -1
        if keystate[pygame.K_UP]:
            speed_y = self.speed
        if keystate[pygame.K_DOWN]:
            speed_y = self.speed * -1

        # Sprinting
        # If Lucy runs out of stamina, she will be blocked until her stamina is full again.
        if keystate[pygame.K_LSHIFT] and not self.stamina.blocked:
            self.player.sprite.rate = 6
            speed_x *= 2
            speed_y *= 2
            self.stamina.stamina -= 1
            # Block sprinting if no stamina remaining
            if self.stamina.stamina == 0:
                self.stamina.blocked = True
        else:
            # Regain stamina when not sprinting
            if self.stamina.stamina < 100:
                self.stamina.stamina += 1
            # Unblock sprinting if full stamina
            else:
                self.stamina.blocked = False
            self.player.sprite.rate = 2

        # Shift all objects on x axis
        for object in self.gameobjects.sprites():
            object.move(speed_x, 0)

        # Reset objects if collision occurred
        if self._collide():
            for object in self.gameobjects.sprites():
                object.move(-1 * speed_x, 0)

        # Shift all objects on y axis
        for object in self.gameobjects.sprites():
            object.move(0, speed_y)

        # Reset objects if collision occurred
        if self._collide():
            for object in self.gameobjects.sprites():
                object.move(0, -1 * speed_y)

        # Check triggers
        self._trigger()

        return self if not self.gameover else OptionsMenu()

class OptionsMenu(Screen):
    def __init__(self):
        super().__init__()

    def update(self):
        return self

class DinDins:
    """Main loop

    This class contains the entry point and main loop of the game.

    Attributes:
        running: Boolean indicating if the game is running
        rootdisplay: pygame.display, the main window
        clock: pygame.time.Clock for setting FPS
    """
    def __init__(self):
        """Initialises game"""
        # Init pygame and set running to true
        pygame.init()
        self.running = True

        # Build root display
        self._rootdisplay = pygame.display.set_mode((WIDTH, HEIGHT))

        # Set up clock
        self._clock = pygame.time.Clock()

    def _cleanup(self):
        """Cleans up and quits pygame"""
        pygame.quit()
        exit(0)

    def _handle(self, event, screen):
        """Event handler

        The DinDins event handler processes events that concern the application as a whole, such as closing the game.
        Otherwise it passes the event to the current screens handler.

        Args:
            event: pygame.event.Event to handle
            screen: Screen to pass event to
        """
        if event.type == pygame.QUIT:
            self.running = False
        else:
            screen.handle(event)

    def _render(self, screen):
        """Renders the screen

        Args:
            screen: Screen to be rendered
        """
        screen.render()
        self._rootdisplay.blit(screen, (0, 0))

        pygame.display.flip()

    def run(self):
        """Main game loop"""
        screen = MainMenu()
        while self.running:
            # Handlers
            self._clock.tick(FPS)
            for event in pygame.event.get():
                self._handle(event, screen)

            screen = screen.update()
            self._render(screen)

        self._cleanup()

if __name__ == '__main__':
    game = DinDins()
    game.run()


#! /usr/bin/env python3

"""
llfi-profile takes a profiling executable and executes it

Prerequisites:
  1. 'input.yaml' contains appropriate options for LLFI and must be in the
     current working directory.
  2. You need to be in the parent directory of the PROF_EXE to invoke
     llfi-profile. This is to make it easier for LLFI to track the outputs
     generated by PROF_EXE.
  3. llfi-profile only checks recursively in the current directory for possible
     outputs. If your output is not under current directory, you need to store
     that output by yourself.
  4. You need to put input files (if any) in the current working directory.
"""

# This script profiles the program to produce llfi.stat.prof.txt

import sys
import yaml
import os
import time
import subprocess
import shutil
import argparse

prog = os.path.basename(sys.argv[0])

basedir = os.getcwd()

def usage(msg = None):
  retval = 0
  if msg is not None:
    retval = 1
    msg = "ERROR: " + msg
    print(msg, file=sys.stderr)
  print(__doc__ % globals(), file=sys.stderr)
  sys.exit(retval)

def help():
  parser = initParser()
  parser.print_help()

def initParser():
  parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    prog='llfi profile',
    epilog=__doc__,
  )
  parser.add_argument('PROF_EXE', help='instrumented executable')
  parser.add_argument('EXE_ARGS', nargs='*',
                      help='arguments to PROF_EXE used during profiling')
  return parser

def parseArgs(parser, args):
  options = parser.parse_args(args)
  options.PROF_EXE = os.path.realpath(options.PROF_EXE)
  if os.path.dirname(os.path.dirname(options.PROF_EXE)) != basedir:
    usage("You need to invoke llfi-inject at the parent directory of PROF_EXE")

  # remove the directory prefix for input files, this is to make it easier for the program
  # to take a snapshot
  for index, opt in enumerate(options.EXE_ARGS):
    if os.path.isfile(opt):
      if os.path.realpath(os.path.dirname(opt)) != basedir:
        usage("File %s passed through option is not under current directory" % opt)
      else:
        options.EXE_ARGS[index] = os.path.basename(opt)

  return options

def checkInputYaml(prof_exe):
  #Check for input.yaml's presence
  yamldir = os.path.dirname(os.path.dirname(prof_exe))
  try:
    f = open(os.path.join(yamldir, 'input.yaml'), 'r')
  except:
    usage("No input.yaml file in the parent directory of profiling executable")
    exit(1)

  #Check for input.yaml's correct formmating
  try:
    doc = yaml.load(f)
    f.close()
  except:
    usage("input.yaml is not formatted in proper YAML (reminder: use spaces, not tabs)")
    exit(1)

################################################################################
def config(profiling_exe):
  global inputdir, outputdir, baselinedir, errordir
  # config
  llfi_dir = os.path.dirname(profiling_exe)

  inputdir = os.path.join(llfi_dir, "prog_input")
  outputdir = os.path.join(llfi_dir, "prog_output")
  baselinedir = os.path.join(llfi_dir, "baseline")
  errordir = os.path.join(llfi_dir, "error_output")

  if not os.path.isdir(outputdir):
    os.mkdir(outputdir)
  if not os.path.isdir(baselinedir):
    os.mkdir(baselinedir)
  if not os.path.isdir(errordir):
    os.mkdir(errordir)
  if not os.path.isdir(inputdir):
    os.mkdir(inputdir)

################################################################################
def execute(execlist):
  global outputfile
  print('\t' + ' '.join(execlist))
  #get state of directory
  dirSnapshot()
  p = subprocess.Popen(execlist, stdout = subprocess.PIPE)
  elapsetime = 0
  while True:
    elapsetime += 1
    time.sleep(1)
    #print p.poll()
    if p.poll() is not None:
      moveOutput()
      print("\t program finish", p.returncode)
      print("\t time taken", elapsetime,"\n")
      outputFile = open(outputfile, "wb")
      outputFile.write(p.communicate()[0])
      outputFile.close()
      replenishInput() #for cases where program deletes input or alters them each run
      #inputFile.close()
      return p.returncode

################################################################################
def storeInputFiles(exe_args):
  global inputList
  inputList=[]
  for opt in exe_args:
    if os.path.isfile(opt):#stores all files in inputList and copy over to inputdir
      shutil.copy2(opt, os.path.join(inputdir, opt))
      inputList.append(opt)

################################################################################
def replenishInput():#TODO make condition to skip this if input is present
  for each in inputList:
    if not os.path.isfile(each):#copy deleted inputfiles back to basedir
      shutil.copy2(os.path.join(inputdir, each), each)

################################################################################
def moveOutput():
  #move all newly created files that are not "llfi.stat.prof.txt" < -- since this is a product of profiling
  newfiles = [_file for _file in os.listdir(".")]
  for each in newfiles:
    if each not in dirBefore and each != "llfi.stat.prof.txt":
      fileSize = os.stat(each).st_size
      if fileSize == 0 and each.startswith("llfi"):
        #empty library output, can delete
        print(each + " is going to be deleted for having size of " + str(fileSize))
        os.remove(each)
      else:
        flds = each.split(".")
        newName = '.'.join(flds[0:-1])
        newName+='.prof.'+flds[-1]
        os.rename(each, os.path.join(baselinedir, newName))

################################################################################
def dirSnapshot():
  #snapshot of directory before each execute() is performed
  global dirBefore
  dirBefore = [_file for _file in os.listdir(".")]

################################################################################
def run(args):
  global outputfile

  parser = initParser()
  options = parseArgs(parser, args)

  checkInputYaml(options.PROF_EXE)
  config(options.PROF_EXE)

  storeInputFiles(options.EXE_ARGS)
  # baseline
  outputfile = os.path.join(baselinedir, "golden_std_output")
  execlist = [options.PROF_EXE]
  execlist.extend(options.EXE_ARGS)

  return execute(execlist)

################################################################################

if __name__=="__main__":
  if len(sys.argv) == 1:
    help()
    exit(1)
  exit(run(sys.argv[1:]))


from time import perf_counter_ns
from argparse import ArgumentParser
import random

"""
QuickSelect is a very similar algorithm to QuickSort as both of them are Divide&Conquer algorithms and
both of them use Partition to divide the array.

The code contains two functions:

Partition: (Same as in QuickSort) This function take an array (a) and two integers for the beginning and the end of the array (l, r)
and choose the last element of the array as a pivot, then it sorts the array putting the pivot in the right place, so that all the elements that are smaller than the pivot on left of it and all elements that are larger than the pivot on the right of it, then returns the index of the pivot.

kthlargest: It takes an array (a) and an integer (k) and returns the k'th largest element of the array by
splitting the array using Partition and calling itself
recuresivly with the suitable argument (subarray and modified k).
"""

def partition(lst, start, end):
    pivot_val = lst[end]
    i = start - 1
    for j in range(start, end):
        if lst[j] <= pivot_val:
            i += 1
            lst[i], lst[j] = lst[j], lst[i]
    lst[i + 1], lst[end] = lst[end], lst[i + 1]
    return i + 1

def partition2(lst, start, end, pivot):
    pivot_val = lst[pivot]
    lst[pivot], lst[end] = lst[end], lst[pivot]
    i = start - 1
    for j in range(start, end):
        if lst[j] > pivot_val:
            i += 1
            lst[j], lst[i] = lst[i], lst[j]
    lst[i+1], lst[end] = lst[end], lst[i+1]
    return i+1

def quickSelect(lst, start, end, k):
    if start == end:
        return lst[start]

    pivot_point = random.randint(start, end)
    pivot_index = partition(lst, start, end, pivot_point)

    if pivot_index == k:
        return lst[k]
    elif k < pivot_index:
        return quickSelect(lst,     start,              pivot_index-1,   k)
    else:
        return quickSelect(lst,     pivot_index+1,      end,             k)

def findKthLargest(lst, k):
    return quickSelect(lst, 0, len(lst)-1, k-1)

#####################################################################

def partition(lst, start, end):
    pivot_val = lst[end]
    i = start - 1
    for j in range(start, end):
        if lst[j] <= pivot_val:
            i += 1
            lst[i], lst[j] = lst[j], lst[i]
    lst[i + 1], lst[end] = lst[end], lst[i + 1]
    return i + 1

def kthlargest(lst, k):
    left = 0
    right = len(lst) - 1
    # choosing a pivot and saving its index
    pivot = partition(lst, left, right)
    if pivot == right - k + 1:  # if the choosen pivot is the correct elemnt, then return it
        result = lst[pivot]
    elif pivot > right - k + 1:  # if the element we are looking for is in the left part to the pivot then call 'kthlargest' on that part after modifing k
        result = kthlargest(lst[:pivot], k - (right - pivot + 1))
    else:  # if the element we are looking for is in the left part to the pivot then call 'kthlargest' on that part
        result = kthlargest(lst[pivot + 1:right + 1], k)

    return result


import datetime
import json
import time

from Core.models import FicheTravail, Voiture, Client
from Core.auth import login_required
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

from Core.auth import need_permissions
from Core.models import Utilise

@login_required(login_url='login')
@need_permissions('access_cards_history')
def main(request):
    return render(request, "Fiches/fiches.html", build_main_list_data())

def bool_to_json(b):
    if b:
        return 'true'
    else:
        return 'false'

def build_main_list_data(filter=Q()):

    filter = filter & Q(etat=True) & Q(cloture=True)
    fiches = FicheTravail.objects.filter(filter).order_by('num_fiche')

    fdata = {'fiches': []}

    for fiche in fiches:
        tdata = []

        for tache in fiche.tache_set.all():

            pdata = []
            utilise = Utilise.objects.filter(Q(tache_id=tache.id))

            for u in utilise:

                if not u.piece.freeze:
                    pdata.append({
                        'id': u.piece.id,
                        'reference': u.piece.reference,
                        'libelle': u.piece.libelle,
                        'quantite': u.nombre,
                        'prix_vente': u.piece.prix_vente,
                        'entree': datetime.datetime.fromtimestamp(u.piece.date_entree_stock).strftime('%d-%m-%Y'),
                        'emplacement': u.piece.emplacement,
                        'alerte': u.piece.alerte,
                    })

            tdata.append({
                'id': tache.id,
                'date_heure_debut': datetime.datetime.fromtimestamp(tache.date_heure_debut).strftime("%d-%m-%Y  %H:%M:%S"),
                'temps': time.strftime('%H:%M:%S', time.gmtime(tache.temps)),
                'code_tache': tache.code_tache,
                'etat': bool_to_json(tache.etat),
                'pieces': pdata
            })

        voiture = Voiture.objects.filter(Q(id=fiche.voiture_id)).first()
        v = {
            'id': voiture.id,
            'num_chassis': voiture.num_chassis,
            'marque': voiture.marque,
            'modele': voiture.modele,
            'num_imma': voiture.num_immatricu,
            'annee_imma': voiture.annee_immatricu,
            'kilometrage': voiture.kilometrage
        }

        client = Client.objects.filter(Q(num_cli=voiture.client_id)).first()
        c = {
            'id': client.num_cli,
            'nom': client.nom,
            'prenom': client.prenom,
            'email': client.email,
            'telephone': client.num_tel,
            'gsm': client.num_gsm,
            'tva': client.num_tva,
            'adresse': client.adresse.adresse,
            'cp': client.adresse.cp,
            'ville': client.adresse.ville,
            'pays': client.adresse.pays,
        }

        fdata['fiches'].append({
            'id': fiche.num_fiche,
            'date_realisation': datetime.datetime.fromtimestamp(fiche.date_realisation).strftime('%d-%m-%Y'),
            'type': fiche.type,
            'etat': bool_to_json(fiche.etat),
            'taches': tdata,
            'client': c,
            'voiture': v
        })

    return fdata

@login_required(login_url='login')
def search_card(request):
    if request.is_ajax() and request.method == 'POST':
        value = request.POST['value'].lower()

        print(value)
        if value == "all":
            sfw = None
        else:
            values = value.split(' ')

            # Split values for date
            if len(values) == 1 and '/' in values[0]:
                values = values[0].split("/")
            elif len(values) == 1 and '-' in values[0]:
                values = values[0].split("-")

            # Try date match
            try:
                if len(values) == 1 and values[0].isdigit():
                    sfw = Q(date_realisation__year=values[0]) | Q(date_realisation__month=values[0]) | Q(
                        date_realisation__day=values[0])
                    return HttpResponse(json.dumps(
                        build_main_list_data(sfw)
                    ))

                elif len(values) == 2 and values[0].isdigit() and values[1].isdigit():
                    sfw = Q(date_realisation__year=values[0]) & Q(date_realisation__month=values[1])
                    sfw = sfw | Q(date_realisation__year=values[1]) & Q(date_realisation__month=values[0])

                    return HttpResponse(json.dumps(
                        build_main_list_data(sfw)
                    ))
                elif len(values) == 3 and values[0].isdigit() and values[1].isdigit() and values[2].isdigit():
                    sfw = Q(date_realisation__year=values[0]) & Q(date_realisation__month=values[1]) & Q(
                        date_realisation__day=values[2])
                    sfw = sfw | Q(date_realisation__day=values[0]) & Q(date_realisation__month=values[1]) & Q(
                        date_realisation__year=values[2])

                    return HttpResponse(json.dumps(
                        build_main_list_data(sfw)
                    ))
                else:
                    raise Exception
            except Exception:
                # Match for car
                sfw = Q(voiture__num_chassis__icontains=value) | Q(voiture__marque__icontains=value) | \
                      Q(voiture__modele__icontains=value) | Q(voiture__num_immatricu__icontains=value)

                # Check for name AND last name of the owner of the car concerned by the card
                if len(values) == 2:
                    sfw = sfw | Q(voiture__client__nom__icontains=values[0]) & Q(
                        voiture__client__prenom__icontains=values[1])
                    sfw = sfw | Q(voiture__client__nom__icontains=values[1]) & Q(
                        voiture__client__prenom__icontains=values[0])
                # Check for name OR last name of the owner of the car concerned by the card
                else:
                    sfw = sfw | Q(voiture__client__nom__icontains=value) | Q(voiture__client__prenom__icontains=value)

                return HttpResponse(json.dumps(
                    build_main_list_data(sfw)
                ))

        return HttpResponse(json.dumps(
            build_main_list_data()
        ))
    else:
        return HttpResponse(status=400)


import socketio #to install dependency with pip, use - pip install "python-socketio[client]"
import datetime
import time

from subprocess import check_output

server_address = "localhost" # insert server IP address here
#server_port = 5000
server_port = 80

sio = socketio.Client()

@sio.event
def connect():
    print("[ INFO ] Incoming connection from something...?")

@sio.event
def connect_error():
    print("[ INFO ] Failed to connect.")

@sio.event
def disconnect():
    print("[ INFO ] Disconnected from the server.")

print('[ INFO ] Connecting to server http://{}:{}...'.format(
    server_address, server_port))

def get_ip_addr():
    return check_output(['hostname', '-I']).decode().rstrip()

server_connected = False

def ping_server():
    global server_connected
    print('Sending ping request to server...')
    sio.emit(
        'PING_FROM_CLIENT',
        {
            'picam_ip': get_ip_addr()
        },
        namespace='/client')
    server_connected = False

@sio.on('PING_FROM_SERVER', namespace='/client')
def ping_response(message):
    global server_connected
    print('Ping response received: ' + message['server_ip'])
    server_connected = True

sio.connect(
    'http://{}:{}'.format(server_address, server_port),
    transports=['websocket'],
    namespaces=['/client']
)

while True:
    ping_server()
    time.sleep(5)


from psiturk.experiment import validate, load_experiment, get_validation_fields
from psiturk.utils import find_directories
import pandas
import json

myexperiments = find_directories("../")
output_file = os.path.abspath("../index.html")
data_folder = os.path.abspath("../.data")

# Let's make a dataframe of valid experiments
fields = [f[0] for f in get_validation_fields()]
valid = pandas.DataFrame(columns=fields)

# Make a table of experiment information
for candidate in myexperiments:
    if validate(candidate):
        experiment = load_experiment(candidate)[0]
        for field in experiment.keys():
            values = experiment[field]
            # Join lists with a comma
            if isinstance(values,list):
                values = ",".join(values)
            valid.loc[experiment["tag"],field] = values

# First prepare rendered table
table = valid.to_html(index=None,classes="table table-striped table-bordered")
table = table.replace('class="dataframe',' id="chart" class="dataframe')

# Read in template
template = "".join(open("index.html","rb").readlines())
template = template.replace("[[SUB_TABLE_SUB]]",table)
filey = open(output_file,"wb")
filey.writelines(template)
filey.close()

# Function to save pretty json file
def save_pretty_json(outfile,myjson):
    filey = open(outfile,'wb')
    filey.write(json.dumps(myjson, sort_keys=True,indent=4, separators=(',', ': ')))
    filey.close()

# Finally, save other versions of updated metadata for people to use
save_pretty_json("%s/psiturk-experiments.json" %(data_folder),json.loads(valid.to_json(orient="records")))
valid.to_csv("%s/psiturk-experiments.tsv" %(data_folder),sep="\t",index=None)
valid.to_pickle("%s/psiturk-experiments.pkl" %(data_folder))


from datetime import datetime, timedelta
import socket
import json
from playsound import playsound
import platform
import os

current = ['north korea', 'kim jong un', 'cohen', 'ZTE']

if platform.node() == 'DESKTOP-PH13SCF':
    comp_path = 'C:\\Users\\SAHIL\\Dropbox\\'
elif os.name == 'posix':
    comp_path = '/Users/Sahil/Dropbox/'
else:
    comp_path = 'C:\\Users\\Trader\\Dropbox\\'

def get_time():
    utc_minus_8hr = datetime.utcnow() - timedelta(hours=4)
    current_time = utc_minus_8hr.strftime('%I:%M:%S')
    return current_time

def send_data(item1, item2, item3, item4):
    clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientsocket.connect(('localhost', 8089))
    item1 = '\033[4m' + item1 + '\033[0m'
    raw_data = {'source': item1, 'text': item2, 'time': item3, 'link': item4}
    json_data = json.dumps(raw_data)
    clientsocket.send(json_data.encode())

def play_sound(name):
    path1 = comp_path + 'sound_files\\'
    path2 = name
    path = path1 + path2
    playsound(path)

def write_file(tickers, source, time, text, code):
    f = open(comp_path + 'tweets.txt', 'a')
    data_raw = {'tickers': tickers, 'source': source, 'time': time, 'text': text, 'code': code}
    data_json = json.dumps(data_raw)
    f.write(data_json + '\n')
    f.close()


#
# -----------------------------------------------------------------------------
#                     The CodeChecker Infrastructure
#   This file is distributed under the University of Illinois Open Source
#   License. See LICENSE.TXT for details.
# -----------------------------------------------------------------------------

""" Test review status functionality."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import logging
import os
import unittest

from codeCheckerDBAccess_v6.ttypes import ReviewStatus

from libtest import env
from libtest.thrift_client_to_db import get_all_run_results

class TestReviewStatus(unittest.TestCase):

    _ccClient = None

    def setUp(self):
        test_workspace = os.environ['TEST_WORKSPACE']

        test_class = self.__class__.__name__
        print('Running ' + test_class + ' tests in ' + test_workspace)

        self._testproject_data = env.setup_test_proj_cfg(test_workspace)
        self.assertIsNotNone(self._testproject_data)

        self._cc_client = env.setup_viewer_client(test_workspace)
        self.assertIsNotNone(self._cc_client)

        # Get the run names which belong to this test.
        run_names = env.get_run_names(test_workspace)

        runs = self._cc_client.getRunData(None, None, 0, None)

        test_runs = [run for run in runs if run.name in run_names]

        self.assertEqual(len(test_runs), 1,
                         'There should be only one run for this test.')
        self._runid = test_runs[0].runId

    def test_multiple_change_review_status(self):
        """
        Test changing review status of the same bug.
        """
        runid = self._runid
        logging.debug('Get all run results from the db for runid: ' +
                      str(runid))

        run_results = get_all_run_results(self._cc_client, runid)
        self.assertIsNotNone(run_results)
        self.assertNotEqual(len(run_results), 0)

        bug = run_results[0]

        # Change review status to confirmed bug.
        review_comment = 'This is really a bug'
        status = ReviewStatus.CONFIRMED
        success = self._cc_client.changeReviewStatus(
            bug.reportId, status, review_comment)

        self.assertTrue(success)
        logging.debug('Bug review status changed successfully')

        report = self._cc_client.getReport(bug.reportId)
        self.assertEqual(report.reviewData.comment, review_comment)
        self.assertEqual(report.reviewData.status, status)

        # Try to change review status back to unreviewed.
        status = ReviewStatus.UNREVIEWED
        success = self._cc_client.changeReviewStatus(
            bug.reportId,
            status,
            u'')

        self.assertTrue(success)
        logging.debug("Bug review status changed successfully")

        report = self._cc_client.getReport(bug.reportId)
        self.assertEqual(report.reviewData.comment, '')
        self.assertEqual(report.reviewData.status, status)

        # Change review status to false positive.
        review_comment = 'This is not a bug'
        status = ReviewStatus.FALSE_POSITIVE
        success = self._cc_client.changeReviewStatus(
            bug.reportId, status, review_comment)

        self.assertTrue(success)
        logging.debug('Bug review status changed successfully')

        report = self._cc_client.getReport(bug.reportId)
        self.assertEqual(report.reviewData.comment, review_comment)
        self.assertEqual(report.reviewData.status, status)

        # Change review status to intentional.
        review_comment = u''
        status = ReviewStatus.INTENTIONAL
        success = self._cc_client.changeReviewStatus(
            bug.reportId, status, review_comment)

        self.assertTrue(success)
        logging.debug('Bug review status changed successfully')

        report = self._cc_client.getReport(bug.reportId)
        self.assertEqual(report.reviewData.comment, review_comment)
        self.assertEqual(report.reviewData.status, status)


#!/usr/bin/env python

# location:
# /home/production/python/relay_1_on.py

import sys
import RPi.GPIO as GPIO

GPIO.setwarnings(False)

# using GPIO 4 as the relay 1 output
# chan_list not necessary but helpful if multiple channels are intialized

chan_list = [4]

GPIO.setmode(GPIO.BCM)
GPIO.setup(chan_list, GPIO.OUT)

# GPIO.output(channel, 0 = on 1 = off)
GPIO.output(4, 0)

#EOF


from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt

cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target,
stratify=cancer.target, random_state=42)

lr001 = LogisticRegression(C=0.01).fit(X_train, y_train)
print("logistics regression with C=0.01")
print("training set score: %f" % lr001.score(X_train, y_train))
print("test set score: %f" % lr001.score(X_test, y_test))

lr = LogisticRegression().fit(X_train, y_train)
print("logistics regression with C=1")
print("training set score: %f" % lr.score(X_train, y_train))
print("test set score: %f" % lr.score(X_test, y_test))

lr100 = LogisticRegression(C=100).fit(X_train, y_train)
print("logistics regression with C=100")
print("training set score: %f" % lr100.score(X_train, y_train))
print("test set score: %f" % lr100.score(X_test, y_test))

plt.plot(lr.coef_.T, 'o', label="C=1")
plt.plot(lr100.coef_.T, 'o', label="C=100")
plt.plot(lr001.coef_.T, 'o', label="C=0.001")
plt.xticks(range(cancer.data.shape[1]), cancer.feature_names, rotation=90)
plt.ylim(-5, 5)
plt.legend()
plt.show()


import matplotlib.patches as patches
from scipy.constants import g,pi
import numpy as np
import matplotlib.pyplot as plt

π = pi

# drag coeeficient divided by mass
B2oMass = 4.0E-5 # 1/m

# the time step
Δt = 0.01 # s

# initial velocity
v0 = 500 # m/s

# guess for angle
θ = np.radians(20.0) # radians

# angle step
dθ = 0.01 # radians

# Iterate the Euler equations for the positions, only storing the x and y
# coordinates until we have a 'hit'
# hint: check out the docs for numpy.append and consider using while loops

xmin,xmax = 13.5E3,13.55E3
x = np.array([0.0])
while not (xmin < x[-1] < xmax):
    x = np.array([0.0])
    y = np.array([0.0])
    θ += dθ
    vx = v0 * np.cos(θ)
    vy = v0 * np.sin(θ)

    while y[-1] >= 0.0:
        v = np.sqrt(vx**2 + vy**2)
        vx -= B2oMass * v * vx * Δt
        vy -= g*Δt + B2oMass * v * vy * Δt
        x = np.append(x,x[-1] + vx*Δt)
        y = np.append(y,y[-1] + vy*Δt)

    if x[-1] > xmax:
        print('Too Far!')
        break

# Plot the resulting trajectory
ax1 = plt.subplot(111)
ax1.plot(x/1.0E3,y/1.0E3,'-',label='θ = %4.2f˚'%np.degrees(θ))
ax1.add_patch(patches.Rectangle((13.5, 0.0),0.05,0.05,facecolor='#39FF14',edgecolor='None',zorder=10))

# set the x and y labels and a title
plt.xlabel('x [km]')
plt.ylabel('y [km]')
plt.legend()
plt.grid(True)
plt.title('Cannon Shell Trajectory')

# Only show positive y-coordinates
plt.axis(ymin=0.0)
plt.show()


import logging
from typing import Dict

logger = logging.getLogger(__name__)

def new_event(event_data: Dict[str, any]) -> "Event":
    if event_data["type"] == "item":
        return Item(event_data)
    elif event_data["type"] == "gold":
        return Gold(event_data)
    elif event_data["type"] == "healthTimes":
        return HealthTimes(event_data)
    elif event_data["type"] == "nothing":
        return Nothing(event_data)
    elif event_data["type"] == "magicStone":
        return MagicStone(event_data)
    elif event_data["type"] == "command":
        return Command(event_data)
    else:
        logger.error("Item missing type filed.")

class Event(object):
    """
    Represents a item.
    """

    def __init__(self, event_data: Dict[str, any]):
        logger.info(f"Event made")
        logger.debug(str(event_data))
        self.value = event_data["value"]
        self.type = event_data["type"]
        self.message = event_data["message"]

        self.kwargs = event_data["kwargs"]

    def activate(self, player):
        """
        The action taken when the item is used.

        :param player: The player that the event happend to
        """
        logger.warning(f"event used the default event.trigger, this should not happened.")

class Item(Event):
    def activate(self, player):
        for _ in "_"*self.kwargs["amount"]:
            item = player.game_data.get_item(self.value)
            player.inventory.add_item(item)

class Gold(Event):
    def activate(self, player):
        player.gold += self.value

class HealthTimes(Event):
    def activate(self, player):
        player.health *= self.value
        player.health = min(player.health, 40)

class Nothing(Event):
    def activate(self, player):
        pass

class MagicStone(Event):
    def activate(self, player):
        if player.inventory.count_item(self.kwargs["item"]) >= 1:
            self.message = self.kwargs["new_message"]
            player.gold += self.value

class Command(Event):
    def activate(self, player):
        pass


import datetime

from django.core.management import BaseCommand
from django.db.models import Q

from apps.enrollment.courses.models.semester import Semester, Freeday, ChangedDay
from apps.enrollment.courses.models.term import Term as CoursesTerm
from apps.schedule.models.term import Term as ScheduleTerm
from apps.schedule.models.event import Event

class Command(BaseCommand):

    def handle(self, *args, **options):
        semester = Semester.objects.get_next()
        Event.objects.filter(course__semester=semester, type=3).delete()
        freedays = Freeday.objects.filter(Q(day__gte=semester.lectures_beginning),
                                          Q(day__lte=semester.lectures_ending))\
            .values_list('day', flat=True)
        changed = ChangedDay.objects.filter(Q(day__gte=semester.lectures_beginning), Q(
            day__lte=semester.lectures_ending)).values_list('day', 'weekday')
        terms = CoursesTerm.objects.filter(
            group__course__semester=semester).select_related(
            'group', 'group__course', 'group__course__entity')
        days = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: []}

        day = semester.lectures_beginning

        while day <= semester.lectures_ending:

            if day in freedays:
                day = day + datetime.timedelta(days=1)
                continue

            weekday = day.weekday()

            for d in changed:
                if d[0] == day:
                    weekday = int(d[1]) - 1
                    break

            days[weekday].append(day)

            day = day + datetime.timedelta(days=1)

        for t in terms:
            ev = Event.objects.get_or_create(
                group=t.group,
                course=t.group.course,
                title=t.group.course.entity.get_short_name(),
                type='3',
                visible=True,
                status='1',
                author=t.group.teacher.user)[0]

            for room in t.classrooms.all():
                for day in days[int(t.dayOfWeek) - 1]:
                    minute = t.start_time.minute
                    if minute == 0:
                        minute = 15
                    ScheduleTerm.objects.get_or_create(
                        event=ev,
                        day=day,
                        start=t.start_time,
                        end=t.end_time,
                        room=room)


from DoublyLinkedList import DoubleLinkedList
from DoublyLinkedList import DoubleNode
from DoublyLinkedList import NodePointer

def remove_node(list, node):
	# No nodes can be deleted from an empty list.
	if list.is_empty():
		return False

	# Start checking the head node.
	pointer = NodePointer(list.head)

	# First check if the head element is the node because a NodePointer object
	# can not delete head or tail nodes.
	if pointer.node == node:
		list.remove_first()
		return True

	# Delete the first instance of the supplied node.
	while pointer.has_next():
		pointer.next()
		if pointer.node == node:
			pointer.delete()
			return True

	# At this point, there is only the tail node to check.
	if pointer.node == node:
		list.remove_last()
		return True

	# If we still have not returned, then we could not delete the node since it
	# does not exist in this list.
	return False

def main():
	node_A = DoubleNode("A")
	node_B = DoubleNode("B")
	node_C = DoubleNode("C")
	node_D = DoubleNode("D")
	node_E = DoubleNode("E")
	node_F = DoubleNode("F")
	node_G = DoubleNode("G")
	node_H = DoubleNode("H")
	node_list = [node_A, node_B, node_C, node_D, node_E, node_F, node_G, node_H]
	test_list = DoubleLinkedList(node_list)

	print(test_list)
	print(remove_node(test_list, node_A))
	print(remove_node(test_list, node_E))
	print(remove_node(test_list, node_H))
	print(test_list)

	test_list.clear()
	print(test_list)
	print(remove_node(test_list, node_F))

if __name__ == "__main__":
	main()


import stripe

from ..models.gateway import Gateway

from ..models.money import Money
from ..models.account import Account
from ..models.card import Card

from ..models.exceptions import MissingGatewayOptionsException

class Stripe(Gateway):
    def __init__(self, options: dict) -> None:
        if options is None:
            options = {}

        if 'api_key' not in options:
            raise MissingGatewayOptionsException

        stripe.api_key = options['api_key']

    def charge(self, money: Money, token: str, account: Account, card: Card, options: dict) -> dict:
        try:
            if options is None:
                options = {}

            if token is None:
                # Create the token
                token = stripe.Token.create(
                    card={
                        'number': card.number,
                        'exp_month': card.month,
                        'exp_year': card.year,
                        'cvc': card.cvc,
                    },
                )

            # Charge the token
            return self.response(
                stripe.Charge.create(
                    amount=money.cents,
                    currency=money.currency,
                    source=token,
                    capture=options.get('capture', True),
                )
            )
        except stripe.error.StripeError as error:
            body = error.json_body
            err = body.get('error', {})

            return self.response({
                'error': err.get('code'),
                'message': err.get('message'),
                'response': err,
            })

    def authorize(self, money: Money, token: str, account: Account, card: Card, options: dict) -> dict:
        if options is None:
            options = {}

        # Set capture to false to run an authorize transaction
        options.capture = False

        return self.charge(money, token, account, card, options)

    def void(self, charge_id: str, options: dict = None) -> dict:
        return self.refund(charge_id)

    def refund(self, charge_id: str, money: Money = None, options: dict = None) -> dict:
        args = {'charge': charge_id}

        if money is not None:
            args['amount'] = money.cents

        try:
            return self.response(
                stripe.Refund.create(**args)
            )
        except stripe.error.StripeError as error:
            body = error.json_body
            err = body.get('error', {})

            return self.response({
                'error': err.get('code'),
                'message': err.get('message'),
                'response': err,
            })

    def response(self, result: dict) -> dict:
        if 'error' not in result:
            return {
                'id': result.get('id', None),
            }

        error = self.translate_error(result['error'])

        return {
            'error': error,
            'message': Stripe.get_error_message(error),
            'gateway_error': result['error'],
            'gateway_message': result['message'],
            'gateway_response': result['response'],
        }

    @staticmethod
    def translate_error(error: str) -> str:
        errors = {
            'account_country_invalid_address': 'invalid_avs',
            'amount_too_large': 'invalid_amount',
            'amount_too_small': 'invalid_amount',
            'api_key_expired': 'authentication_error',
            'card_declined': 'declined',
            'charge_already_refunded': 'transaction_already_refunded',
            'charge_disputed': 'disputed',
            'expired_card': 'expired_card',
            'incorrect_address': 'invalid_avs',
            'incorrect_cvc': 'invalid_cvc',
            'incorrect_number': 'invalid_card',
            'incorrect_zip': 'invalid_avs',
            'invalid_card_type': 'invalid_card',
            'invalid_charge_amount': 'invalid_amount',
            'invalid_cvc': 'invalid_cvc',
            'invalid_expiry_month': 'invalid_expiration',
            'invalid_expiry_year': 'invalid_expiration',
            'invalid_number': 'invalid_card',
            'postal_code_invalid': 'invalid_avs',
            'secret_key_required': 'authentication_error',
            'token_already_used': 'invalid_token',
            'token_in_use': 'invalid_token',
        }

        return errors.get(error, 'unknown_error')


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

import time
import logging
from HbaseTools import HbaseLogInfoTask
from RedisTools import RedisYyTools
from elasticsearch import Elasticsearch,helpers
from conf import ES_LOG_ADDR,COUNT_NUM

logging.basicConfig(filename='log/log_info.log',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(module)s :%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p', level=logging.INFO)

class LogInsertInfo(object):

    def __init__(self):
        self.hbase_con = HbaseLogInfoTask()
        self.redis_con = RedisYyTools()
        self.es = Elasticsearch(ES_LOG_ADDR)

    def es_ping(self):
        if not self.es.ping():
            self.es = Elasticsearch(ES_LOG_ADDR,timeout=30)

    def run(self):
        action_list = []
        count = 0
        start = int(time.time())
        cunzai = 0
        while True:
            rowkey = self.redis_con.get_yy_nb_rowkey("es:log:insert:info")
            if rowkey == None:
                if len(action_list) > 0:
                    logging.warning("重复存入elasticsearch当中%d条数据" % cunzai)
                    cunzai = 0
                    self.commit(action_list)
                    action_list.clear()
                    start = int(time.time())
                    count = 0
                time.sleep(5)
                continue
            if len(rowkey) > 500:
                log_info = "id：%s长度超过500" %rowkey
                logging.warning(log_info)
                continue
            boo = self.es.exists("log_info","sino",rowkey)
            if boo:
                cunzai = cunzai + 1
                map = self.hbase_con.getResultByRowkey("log_info", rowkey)
                if not map:
                    continue
                action_list.append({
                    "_op_type":"update",
                    "_index": "log_info",
                    "_type": "sino",
                    "_id": rowkey,
                    "doc": map,
                })
            else:
                map = self.hbase_con.getResultByRowkey("log_info", rowkey)
                if not map:
                    continue
                action_list.append({
                    "_index": "log_info",
                    "_type": "sino",
                    "_id": rowkey,
                    "_source": map,
                })
            end = int(time.time())
            count = count + 1
            if count > COUNT_NUM or (end - start) > 30:
                self.es_ping()
                logging.warning("重复存入elasticsearch当中%d条数据" % cunzai)
                cunzai = 0
                if len(action_list) > 0:
                    self.commit(action_list)
                start = int(time.time())
                action_list.clear()
                count = 0

    def commit(self,action_list):
        try:
            helpers.bulk(self.es, action_list)
        except Exception as e:
            log_info = "index:log_info,\terror:" + str(e)
            logging.error(log_info)
            helpers.bulk(self.es, action_list)
        logging.warning("提交成功：%d条数据" % len(action_list))

if __name__=="__main__":
    logInsertInfo = LogInsertInfo()
    logInsertInfo.run()


from conans import ConanFile, CMake, tools
import os, shutil

class OpenImageIOConan(ConanFile):
    name = "openimageio"
    description = "OpenImageIO is a library for reading and writing images, and a bunch of related classes, utilities, and applications." \
                  "There is a particular emphasis on formats and functionality used in professional, large-scale animation and visual effects work for film."
    topics = ("conan", "vfx", "image", "picture")
    license = "BSD-3-Clause"
    homepage = "http://www.openimageio.org/"
    url = "https://github.com/conan-io/conan-center-index"
    settings = "os", "compiler", "build_type", "arch"
    generators = "cmake", "cmake_find_package"
    exports_sources = ["CMakeLists.txt", "patches/*"]
    short_paths = True

    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "with_dicom": [True, False],
        "with_raw": [True, False]
    }

    default_options = {
        "shared": False,
        "fPIC": True,
        "with_dicom": False, # Heavy dependency, disabled by default
        "with_raw": False # libraw is available under CDDL-1.0 or LGPL-2.1, for this reason it is disabled by default
    }

    _cmake = None

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake

        self._cmake = CMake(self)

        # CMake options
        self._cmake.definitions["OIIO_BUILD_TOOLS"] = True
        self._cmake.definitions["OIIO_BUILD_TESTS"] = False
        self._cmake.definitions["BUILD_DOCS"] = False
        self._cmake.definitions["INSTALL_DOCS"] = False
        self._cmake.definitions["INSTALL_FONTS"] = False
        self._cmake.definitions["INSTALL_CMAKE_HELPER"] = False
        self._cmake.definitions["EMBEDPLUGINS"] = True
        self._cmake.definitions["USE_PYTHON"] = False
        self._cmake.definitions["USE_EXTERNAL_PUGIXML"] = True

        # Set "USE_<PKG>" variables for disabled plugins to False.
        # If these variables are not set, the package will be built
        # when required library is found, even if it is not provided
        # by Conan.
        self._cmake.definitions["USE_JPEGTURBO"] = False
        self._cmake.definitions["USE_JPEG"] = True
        self._cmake.definitions["USE_HDF5"] = False
        self._cmake.definitions["USE_OPENCOLORIO"] = True
        self._cmake.definitions["USE_OPENCV"] = False
        self._cmake.definitions["USE_TBB"] = False
        self._cmake.definitions["USE_DCMTK"] = self.options.with_dicom
        self._cmake.definitions["USE_FFMPEG"] = False
        self._cmake.definitions["USE_FIELD3D"] = False
        self._cmake.definitions["USE_GIF"] = True
        self._cmake.definitions["USE_LIBHEIF"] = False
        self._cmake.definitions["USE_LIBRAW"] = self.options.with_raw
        self._cmake.definitions["USE_OPENVDB"] = False
        self._cmake.definitions["USE_PTEX"] = False
        self._cmake.definitions["USE_R3DSDK"] = False
        self._cmake.definitions["USE_NUKE"] = False
        self._cmake.definitions["USE_OPENGL"] = False
        self._cmake.definitions["USE_QT"] = False
        self._cmake.definitions["USE_QT5"] = False

        self._cmake.configure()
        return self._cmake

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        if self.options.shared:
            del self.options.fPIC

    def requirements(self):
        self.requires("openexr/2.5.2")
        self.requires("libtiff/4.1.0")
        self.requires("fmt/7.0.3")
        self.requires("boost/1.74.0")
        self.requires("tsl-robin-map/0.6.3")
        self.requires("pugixml/1.10")
        self.requires("libsquish/1.15")
        self.requires("libpng/1.6.37")
        self.requires("libwebp/1.1.0")
        self.requires("openjpeg/2.3.1")
        self.requires("giflib/5.2.1")
        self.requires("freetype/2.10.2")
        self.requires("opencolorio/1.1.1")
        self.requires("libjpeg/9d")

        if self.options.with_dicom:
            self.requires("dcmtk/3.6.5")

        if self.options.with_raw:
            self.requires("libraw/0.20.0")

    def source(self):
        tools.get(**self.conan_data["sources"][self.version])
        os.rename("oiio-Release-{}".format(self.version), self._source_subfolder)

    def _patch_sources(self):
         for patch in self.conan_data.get("patches", {}).get(self.version, []):
            tools.patch(**patch)

    def build(self):
        self._patch_sources()

        cmake = self._configure_cmake()
        cmake.build()

    def package(self):
        cmake = self._configure_cmake()
        cmake.install()

        tools.rmdir(os.path.join(self.package_folder, "include", "OpenImageIO", "fmt"))
        tools.rmdir(os.path.join(self.package_folder, "lib", "cmake"))
        tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))
        tools.rmdir(os.path.join(self.package_folder, "share"))

        self.copy("LICENSE.md", src=self._source_subfolder, dst="licenses")

    def package_info(self):
        self.cpp_info.names["cmake_find_package"] = "OpenImageIO"
        self.cpp_info.names["cmake_find_package_multi"] = "OpenImageIO"
        self.cpp_info.names['pkg_config'] = 'OpenImageIO'

        self.cpp_info.libs = tools.collect_libs(self)

        if self.settings.os == "Linux":
            self.cpp_info.system_libs.append("dl")

        if not self.options.shared:
            self.cpp_info.defines.append("OIIO_STATIC_DEFINE")


import PyNAU7802
import smbus2

RPI_I2C_BUS = 1

# Create the bus
bus = smbus2.SMBus(RPI_I2C_BUS)

# Create the scale and initialize it
scale = PyNAU7802.NAU7802()
if scale.begin(bus):
    print("Connected!\n")
else:
    print("Can't find the scale, exiting...\n")
    exit()

# Calculate the zero offset
print("Calculating the zero offset...")
scale.calculateZeroOffset()
print("The zero offset is: {0}\n".format(scale.getZeroOffset()))

print("Put a known mass on the scale.")
cal = float(input("Mass in kg? "))

# Calculate the calibration factor
print("Calculating the calibration factor...")
scale.calculateCalibrationFactor(cal)
print("The calibration factor is : {0:0.3f}\n".format(scale.getCalibrationFactor()))

input("Press [Enter] to measure a mass. ")
print("Mass is {0.0.3f} kg".format(scale.getWeight()))


"""167. Two Sum II - Input array is sorted
Easy

2714

737

Add to List

Share
Given an array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.

Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]

Constraints:

2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution."""

class Solution:
    def twosum(self, numbers: list[int], target: int) -> list[int]:
        start = 0
        end = len(numbers) - 1
        while numbers[start] <= target:
            if numbers[start] + numbers[end] == target:
                return [start + 1, end + 1]
            if numbers[start] + numbers[end] < target:
                start += 1
            else:
                end -= 1

my_numbers = [2, 7, 11, 15]
my_target = 9
solution = Solution()
print(solution.twosum(my_numbers, my_target))
#  This solution worked, but timed out. Let's make it more efficient.