# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed
# under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from copy import deepcopy

import unittest

from _test_utils import AssertMixin

import product.model
import product.util

from model.base import ModelValidationError

class ProductModelTest(unittest.TestCase):
    def setUp(self):
        self.raw_dict = {
            'components':
            [
                # first_component
                {
                    'name': 'example.org/foo/first_component',
                    'version': 'first_version',
                    'dependencies':
                    {
                        'components':
                        [
                            {
                                'name': 'example.org/bar/second_component',
                                'version': 'second_version',
                            }
                        ],
                        'container_images':
                        [
                            {
                                'name': 'first',
                                'version': 'version',
                                'image_reference': 'first_creference:version',
                            }
                        ],
                        'web':
                        [
                            {
                                'name': 'first_web',
                                'version': 'web_version',
                                'url': 'https://example.org',
                            },
                        ],
                        'generic':
                        [
                            {
                                'name': 'generic',
                                'version': 'generic_version',
                            },
                        ],
                    },
                },
                # second_component
                {
                    'name': 'example.org/bar/second_component',
                    'version': 'second_version',
                    'dependencies': None # no dependencies
                }
            ]
        }

    def test_deserialisation_returns_correct_model(self):
        examinee = product.model.ComponentDescriptor.from_dict(raw_dict=self.raw_dict)

        components = list(examinee.components())
        self.assertEqual(len(components), 2)

        first_component = examinee.component(('example.org/foo/first_component', 'first_version'))
        second_component = examinee.component(('example.org/bar/second_component', 'second_version'))

        self.assertEqual(first_component.name(), 'example.org/foo/first_component')
        self.assertEqual(second_component.name(), 'example.org/bar/second_component')

        first_dependencies = first_component.dependencies()
        second_dependencies = second_component.dependencies()

        first_component_deps = list(first_dependencies.components())
        self.assertEqual(len(first_component_deps), 1)
        first_component_dep = first_component_deps[0]

        first_container_deps = list(first_dependencies.container_images())
        self.assertEqual(len(first_container_deps), 1)
        first_container_dep = first_container_deps[0]

        self.assertEqual(first_component_dep.name(), 'example.org/bar/second_component')
        self.assertEqual(first_component_dep.version(), 'second_version')

        self.assertEqual(first_container_dep.image_reference(), 'first_creference:version')

        self.assertEqual(len(list(second_dependencies.components())), 0)
        self.assertEqual(len(list(second_dependencies.container_images())), 0)

        first_web_deps = list(first_dependencies.web_dependencies())
        self.assertEqual(len(first_web_deps), 1)
        first_web_dep = first_web_deps[0]

        self.assertEqual(first_web_dep.name(), 'first_web')
        self.assertEqual(first_web_dep.version(), 'web_version')
        self.assertEqual(first_web_dep.url(), 'https://example.org')

        first_generic_deps = list(first_dependencies.generic_dependencies())
        self.assertEqual(len(first_generic_deps), 1)
        first_generic_dep = first_generic_deps[0]

        self.assertEqual(first_generic_dep.name(), 'generic')
        self.assertEqual(first_generic_dep.version(), 'generic_version')

    def test_merge_identical_products(self):
        left_model = product.model.ComponentDescriptor.from_dict(raw_dict=self.raw_dict)
        right_model = product.model.ComponentDescriptor.from_dict(raw_dict=self.raw_dict)

        merged = product.util.merge_products(left_model, right_model)

        components = list(merged.components())
        self.assertEqual(len(components), 2)

    def test_merge_conflicting_products_should_raise(self):
        left_model = product.model.ComponentDescriptor.from_dict(raw_dict=deepcopy(self.raw_dict))
        right_model = product.model.ComponentDescriptor.from_dict(raw_dict=deepcopy(self.raw_dict))

        # add a new dependency to create a conflicting definition
        container_image_dep = product.model.ContainerImage.create(
                name='container_name',
                version='container_version',
                image_reference='dontcare:sometag',
        )
        first_comp_deps = right_model.component((
                    'example.org/foo/first_component',
                    'first_version')
                ).dependencies()
        first_comp_deps.add_container_image_dependency(container_image_dep)

        with self.assertRaises(ValueError):
            product.util.merge_products(left_model, right_model)

    def test_merge_products(self):
        left_model = product.model.ComponentDescriptor.from_dict(raw_dict={})
        right_model = product.model.ComponentDescriptor.from_dict(raw_dict={})

        left_component1 = product.model.Component.create(name='x/y/lcomp1', version='1')
        right_component1 = product.model.Component.create(name='x/y/rcomp1', version='2')

        left_model.add_component(left_component1)
        right_model.add_component(right_component1)

        merged = product.util.merge_products(left_model, right_model)

        merged_components = list(merged.components())
        self.assertEqual(len(merged_components), 2)

        self.assertIsNotNone(merged.component(('x/y/lcomp1', '1')))
        self.assertIsNotNone(merged.component(('x/y/rcomp1', '2')))

def test_merge_products_with_overwrites():
    left_model = product.model.ComponentDescriptor.from_dict(raw_dict={})
    right_model = product.model.ComponentDescriptor.from_dict(raw_dict={})

    left_component1 = product.model.Component.create(name='x/y/lc1', version='1')
    left_component2 = product.model.Component.create(name='x/y/lc2', version='1')
    image1 = product.model.ContainerImage.create(
        name='image1',
        version='1.2.3',
        image_reference='image:1',
    )

    left_comp_overwrites = left_model.component_overwrite(declaring_component=left_component1)
    left_dep_overwrites = left_comp_overwrites.dependency_overwrite(
        referenced_component=left_component2,
        create_if_absent=True,
    )
    left_dep_overwrites.add_container_image_overwrite(image1)

    merged = product.util.merge_products(left_model, right_model)

    merged_comp_overwrites = merged.component_overwrite(declaring_component=left_component1)
    merged_dep_overwrites = merged_comp_overwrites.dependency_overwrite(
        referenced_component=left_component2,
        create_if_absent=False,
    )

    overwritten_image = merged_dep_overwrites.container_image(name='image1', version='1.2.3')

    assert overwritten_image == image1

    # test merging in inverse order
    merged = product.util.merge_products(right_model, left_model)

    merged_comp_overwrites = merged.component_overwrite(declaring_component=left_component1)
    merged_dep_overwrites = merged_comp_overwrites.dependency_overwrite(
        referenced_component=left_component2,
        create_if_absent=False,
    )

    overwritten_image = merged_dep_overwrites.container_image(name='image1', version='1.2.3')

    assert overwritten_image == image1

class ComponentModelTest(unittest.TestCase, AssertMixin):
    def test_create(self):
        examinee = product.model.Component.create(name='github.com/example/name', version='1.2.3')

        self.assertEqual(examinee.name(), 'github.com/example/name')
        self.assertEqual(examinee.version(), '1.2.3')

    def test_add_dependencies(self):
        examinee = product.model.Component.create(name='github.com/example/name', version='1.2.3')
        deps = examinee.dependencies()
        self.assertEmpty(deps.components())

        component_dep = product.model.ComponentReference.create(
                name='github.com/foo/bar',
                version='2'
        )

        deps.add_component_dependency(component_dep)

        self.assertEqual(tuple(deps.components()), (component_dep,))

class ComponentReferenceModelTest(unittest.TestCase):
    def test_component_name_parsing(self):
        examinee = product.model.ComponentReference.create(name='github.com/org/rname', version='1')

        self.assertEqual(examinee.github_host(), 'github.com')
        self.assertEqual(examinee.github_organisation(), 'org')
        self.assertEqual(examinee.github_repo(), 'rname')

class ComponentNameModelTest(unittest.TestCase):
    def test_validate_component_name(self):
        examinee = product.model.ComponentName.validate_component_name

        invalid_component_names = (
            '',
            'http://github.com/example/example',
            'github.com',
            'github.com/',
            'github.com/foo',
            'github.com/foo/',
            'github.com/foo/bar/x',
        )

        for component_name in invalid_component_names:
            with self.assertRaises(product.model.InvalidComponentReferenceError):
                examinee(component_name)

        # test valid names
        examinee('github.com/example/example')
        examinee('github.com/example/example/')

    def test_from_github_repo_url(self):
        examinee = product.model.ComponentName.from_github_repo_url

        result1 = examinee('https://github.xxx/foo_org/bar_name')
        result2 = examinee('github.xxx/foo_org/bar_name')

        for result in (result1, result2):
            self.assertEqual(result.github_repo(), 'bar_name')
            self.assertEqual(result.github_organisation(), 'foo_org')
            self.assertEqual(result.github_host(), 'github.xxx')
            self.assertEqual(result.github_repo_path(), 'foo_org/bar_name')
            self.assertEqual(result.config_name(), 'github_xxx')

class DependenciesModelTest(unittest.TestCase, AssertMixin):
    def test_ctor(self):
        examinee = product.model.ComponentDependencies(raw_dict={})

        self.assertEmpty(examinee.web_dependencies())
        self.assertEmpty(examinee.generic_dependencies())
        self.assertEmpty(examinee.container_images())
        self.assertEmpty(examinee.components())

    def test_adding_dependencies(self):
        examinee = product.model.ComponentDependencies(raw_dict={})

        ci_dep = product.model.ContainerImage.create(
            name='cn',
            version='cv',
            image_reference='cir:ct',
        )
        comp_dep = product.model.ComponentReference.create(name='h/o/c', version='c')
        web_dep = product.model.WebDependency.create(name='wn', version='wv', url='u')
        gen_dep = product.model.GenericDependency.create(name='gn', version='gv')

        examinee.add_container_image_dependency(ci_dep)
        self.assertEqual((ci_dep,), tuple(examinee.container_images()))

        examinee.add_component_dependency(comp_dep)
        self.assertEqual((comp_dep,), tuple(examinee.components()))

        examinee.add_web_dependency(web_dep)
        self.assertEqual((web_dep,), tuple(examinee.web_dependencies()))

        examinee.add_generic_dependency(gen_dep)
        self.assertEqual((gen_dep,), tuple(examinee.generic_dependencies()))

        # adding the same dependency multiple times must be ignored
        redundant_dep = product.model.GenericDependency.create(name='gn', version='gv')
        self.assertEqual(redundant_dep, gen_dep)
        examinee.add_generic_dependency(redundant_dep)
        self.assertEqual((gen_dep,), tuple(examinee.generic_dependencies()))

class ContainerImageTest(unittest.TestCase):
    def test_validation(self):
        examinee = product.model.ContainerImage.create

        # image references must contain a ':'
        with self.assertRaises(ModelValidationError):
            examinee(name='made_up', version='some_version', image_reference='foo')

        # image_references must contain a tag
        with self.assertRaises(ModelValidationError):
            examinee(name='made_up', version='some_version', image_reference=':bar')

        # image references must contain an image name
        with self.assertRaises(ModelValidationError):
            examinee(name='made_up', version='some_version', image_reference='foo:')


from colored import fg, bg, attr
import numpy as np

#make blank 7x7 block
board = np.zeros(7)

#numbered the same as in the assignment
H = [(0,0), (0,3), (1,0), (1,4), (1,5), (3,2), (3,3), (4,1), (4,4), (4,6), (5,3), (6,0), (6,4), (6,5)]

# https://pypi.org/project/colored/ for color list
# unit list start at 0,0 top left. use coords as if the piece were encapsulated by a rectangle with that coordinate system.
class Piece:
  #rotate 90 degrees counterclockwise
  def rotate90(self, alist):
    for i, item in enumerate(alist):
      (x,y) = item
      tempx = -1 * y
      tempy = x
      alist[i] = (tempx, tempy)
    #return self.zeroup(alist.copy())
    return alist.copy()

  def __init__(self, color, unit_list):
    self.color = color
    self.rotation = [1,1,1,1]
    self.rotation[0] = unit_list.copy()
    self.rotation[1] = self.rotate90(unit_list.copy())
    self.rotation[2] = self.rotate90(self.rotation[1].copy())
    self.rotation[3] = self.rotate90(self.rotation[2].copy())
    self.unit_count = len(self.rotation[0])
    self.is_placed = False
    self.is_out_of_bounds = False

  def printme(self):
    for i in range(4):
      print(self.rotation[i] )
    print('-----------')

def printBoard(A):
  for line in A:
    for item in line:
      if isinstance(item, tuple):
        (block, color) = item
        print('%s%s%i%s' % (fg(color), bg(color), block, attr('reset')), end='')
      else:
        print('%s%s %s' % (fg('white'), bg('white'), attr('reset')), end='')
    print(' ')
  print(' ')

def showCoverage(A):
  for line in A:
    for item in line:
      if item > 1:
        print('%s%s %s' % (fg('gray'), bg('gray'), attr('reset')), end='')
      elif item == 1:
        print('%s%s %s' % (fg('green'), bg('green'), attr('reset')), end='')
      else:
        print('%s%s %s' % (fg('white'), bg('white'), attr('reset')), end='')

hole = Piece('black',[(0,0)])
pieces = [
  Piece('red', [
      (0,0), (0,1),
      (1,0), (1,1), (1,2),
      (2,0), (2,1)
  ]),
  Piece('gold_1', [
      (0,0), (0,1),
             (1,1), (1,2),
                    (2,2)
  ]),
  Piece('green',[
             (0,1), (0,2),
      (1,0), (1,1), (1,2),
             (2,1), (2,2), (2,3)
  ]),
  Piece('dark_cyan', [
      (0,0), (1,0), (2,0), (3,0), (4,0)
  ]),
  Piece('dark_orange', [
      (0,0), (1,0)
  ]),
  Piece('orange_red_1', [
             (0,1),
      (1,0), (1,1),
      (2,0), (2,1),
             (3,1)
  ]),
  Piece('purple_1a', [
      (0,0),
      (1,0), (1,1),
      (2,0), (2,1), (2,2)
  ]),
  Piece('magenta', [
             (0,1),
      (1,0), (1,1), (1,2)
  ]),
  Piece('blue', [
      (0,0), (0,1), (0,2), (0,3),
                    (1,2)
  ])
]

def validLocation(x,y):
  return x >= 0 and x < 7 and y >=0 and y < 7

def placePiece(board, piece, location, rotates):
  for unit in piece.rotation[rotates]:
    (x,y) = unit
    if validLocation(location[0]+x,location[1]+y):
      board[location[0]+x, location[1]+y] += 1
    else:
      piece.is_out_of_bounds = True
  return board

def fitness(board):
  score = 0
  for x in np.nditer(board):
    score += 2**abs(1-x)
  return score

#def findSolution(board, pieces, hole):
 # bestSolution = (board, fitness(board))


import collocation as cl
import numpy as np
import math
from sympy import integrate, symbols, diff, linsolve, cos

k = 14
collocation_points = np.array([-1, -0.75, -0.5, -0.1, 0, 0.1, 0.5, 0.75, 1])
p = 0
two_a = False
power = 2
task = True
x = symbols('x')
a = 0
y = d_y = d2_y = 0

def psi_make(power, task, a_sin, q):
    return cl.d2_y * a_sin + cl.p*cl.d_y + q*cl.y - cl.f(x, power, task)

def cos_func(x, two_a, task):
    if task:
        if two_a:
            return cos(k * x ** 2)
        else:
            return math.cos(k)
    else:
        return 1

def integral_sqr_method():
    cl.n_choice()
    cl.y_creation()
    a_sin = cl.a_func(x, two_a, task)
    q = 1 + x * cos_func(x, two_a, task)
    psi = psi_make(power, task, a_sin, q)
    psi_sqr = psi * psi
    I = integrate(psi_sqr, (x, cl.x_start, cl.x_end))
    equations = list()
    for i in range(collocation_points.shape[0]):
        equations.append(diff(I, cl.a[i]))
    sl = linsolve(equations, cl.a)
    solution = sl.args[0]
    print(solution)
    cl.build_graphics(solution)


from datetime import datetime
class Spy:
    def __init__(self,name,salutation,age,rating):
        self.name=name
        self.salutation=salutation
        self.age=age
        self.rating=rating
        self.chat=[]
        self.is_status=True

class chat_message:
    def __init__(self,text,send_by_me):
        self.text=text
        self.time=datetime.now()
        self.send_by_me=send_by_me

spy=Spy("Swayam","Mr.","23","4.0")


from opencv.cv import *
from opencv.highgui import *
import sys

frame=None
hist_size = 256
range_0=[0,256]
ranges = [ range_0 ]
hist_image=None
hist=None

#hsv image and channels
hsv_image=None
hhsv_image=None
shsv_image=None
vhsv_image=None

def genHist(hist_image,hist_size,hist):
    for i in range(hist_size):
        cvRectangle( hist_image, cvPoint(i*bin_w, hist_image.height),
                     cvPoint((i+1)*bin_w, hist_image.height - cvRound(cvGetReal1D(hist.bins,i))),
                     cvScalarAll(0), -1, 8, 0 );

if __name__ == '__main__':
    cvNamedWindow("histogram",CV_WINDOW_AUTOSIZE)
    cvNamedWindow("image",CV_WINDOW_AUTOSIZE)

    capture=cvCreateFileCapture("/media/My_Passport/Videos/colillas-final2.avi")
    frame=cvQueryFrame(capture)

    #hsv initialization
    hsv_image=cvCloneImage(frame)
    hhsv_image=cvCreateImage(cvGetSize(frame),frame.depth,1)

    #histogram initialization
    hist_image = cvCreateImage(cvSize(320,200), 8, 1);
    hist = cvCreateHist([hist_size], CV_HIST_ARRAY, ranges, 1);

    while(True):
        frame=cvQueryFrame(capture)
        #convert to hsv
        cvCvtColor(frame,hsv_image,CV_RGB2HSV)
        #split channels
        cvSplit(hsv_image,hhsv_image,shsv_image,vhsv_image,None)

        cvCalcHist( hhsv_image, hist, 0, None );

        #get histogram bin width
        min_value, max_value = cvGetMinMaxHistValue( hist );
        cvScale( hist.bins, hist.bins, float(hist_image.height)/max_value, 0 );
        #cvNormalizeHist( hist, 1000 );

        cvSet( hist_image, cvScalarAll(255));
        bin_w = cvRound(float(hist_image.width)/hist_size);

        genHist(hist_image, hist_size, hist)

        cvShowImage("image",frame)
        cvShowImage("histogram",hist_image)
        cvWaitKey()


import tensorflow as tf
import numpy as np

def reduce_median(variable, axis=None):
    """calculate the median of a variable along a given axis."""
    median = tf.contrib.distributions.percentile(
        variable, 50.0, interpolation="lower", axis=axis)
    median += tf.contrib.distributions.percentile(
        variable, 50.0, interpolation="higher", axis=axis)
    return median / 2.

def cumulative_distribution(x):
    return tf.erf(x/2.**.5)

def qfunction(x):
    return 1 - cumulative_distribution(x)

def median_score(target, prediction):
    #error = tf.abs(target - prediction)
    error  = target - prediction
    median = reduce_median(error, axis=0)
    _, var = tf.nn.moments(error, axes=[0])

    x = tf.abs(error - median) / tf.sqrt(var)
    s = qfunction(x)
    return tf.identity(s, name="score")

def mean_score(target, prediction):
    error  = target - prediction
    mean, var = tf.nn.moments(error, axes=[0])

    x = tf.abs(error - mean) / tf.sqrt(var)
    s = qfunction(x)

    return tf.identity(s, name="score")

def mad_score(target, prediction):
    error = target - prediction
    median = reduce_median(error, axis=0)
    dev = tf.abs(error - median)
    mad = reduce_median(dev)
    return tf.identity(dev/mad, name='score')

def sliding_score(labels, prediction, small_window, large_window, nr_prev_frames):

    error = tf.abs(labels - prediction)
    error = tf.reduce_mean(error, axis=[1,2])

    index = tf.constant(0)
    shape = [labels.shape[0].value - nr_prev_frames,]
    scores = tf.zeros(shape)

    def cond(i, error, scores):
        return i < shape[0]

    def body(i, error, scores):
        # index at ith prediction (i+nr_prev_frames'th label)
        j = i + nr_prev_frames
        sw_error = error[j:j+small_window]
        lw_error = error[j-large_window:j+small_window]
        mu, var = tf.nn.moments(lw_error, axes=[0])
        sw_mu = tf.reduce_mean(sw_error, axis=0)
        x = tf.abs(mu - sw_mu) / tf.sqrt(var)
        s = qfunction(x)

        shape = scores.shape
        scores = tf.concat([scores[:i], [s], scores[i+1:]], axis=0)
        scores.set_shape(shape)
        return i+1, error, scores

    _, _, scores = tf.while_loop(cond, body, [index, error, scores])
    return tf.identity(scores, name='score')


#!/usr/bin/python3

from cyaron import IO, randint
from random import random
from math import sqrt, log2

_N = [5, 100000, 3000, 3000, 100000]
_T = [5, 5, 5, 8, 10]

for T in range(5):
    for t in range(_T[T]):
        print('processing', T + 1, t + 1)
        data = IO(file_prefix='', data_id='%d-%d' % (T + 1, t + 1))

        n = randint(_N[T] * 8 // 10, _N[T])
        if t:
            n = n // 2 * 2

        s = ''
        x = n // 2 * 2
        if t & 1:
            step = int(sqrt(n))
        else:
            step = n - int(log2(n))
        step = max(step, 2)
        while x:
            r = min(step, x)
            l = randint(max(2, r // 2), r) // 2
            s += '0' * l + '1' * l
            x -= l * 2

        if T == 1:
            s = list(s)
            s[randint(0, n - 1)] = '?'
            s = ''.join(s)
        elif T == 2:
            s = '?' * n
        else:
            p = 0.5 * t / (_T[T] - 1) + 0.45
            start = int(randint(50000, 80000) / 100000 * t / (_T[T] - 1) * n)
            ss = '?' * start
            for ch in s[start:]:
                if random() <= p:
                    ss += '?'
                else:
                    ss += ch
            s = ss

        data.input_writeln(s)
        data.output_gen('./10001')
        data.close()

Online Judges/BunnyOJ/BunnyOJ 10001 Easy sequence/data/maker.py


import psycopg2
import config
import os

def start(self):
    conn = psycopg2.connect( ("host=%s port=%s dbname=%s user=%s password=%s") % (config.dbhost, config.dbport, config.dbname, config.dbuser, config.dbpassword) )
    cur = conn.cursor()

    sql = """SELECT user_id,album_id FROM albums
            WHERE delete = TRUE
    """
    cur.execute(sql)
    records = cur.fetchall()
    conn.commit()
    if ( len(records) == 0 ):
        self.oprint("{remove_albums} No albums marked to remove")
        return
    sql = """DELETE FROM albums
            WHERE delete = TRUE
    """
    cur.execute(sql)
    conn.commit()
    len_rec = len(records)
    users = []
    albums = []
    for i in range(len_rec):
        users.append(records[i][0])
        albums.append(records[i][1])
    for i in range(len_rec):
        self.oprint("{remove_albums} Remove album from Database | User_ID: "+str(users[i])+" | Album_ID: "+str(albums[i]))
    for i in range(len(records)):
        user_id = str(records[i][0])
        album_id = str(records[i][1])
        sql = """SELECT name FROM images
                WHERE user_id = """+user_id+""" AND album_id = """+album_id+"""
        """
        cur.execute(sql)
        rec_images = cur.fetchall()
        conn.commit()
        sql = """DELETE FROM images
                WHERE user_id = """+user_id+""" AND album_id = """+album_id+"""
        """
        cur.execute(sql)
        conn.commit()
        if ( len(rec_images) == 0 ):
            self.oprint("{remove_albums} (Empty album) | (User_ID: "+user_id+" | Album_ID "+album_id+") doesn't contain images to remove")
            continue
        self.oprint("{remove_albums} All images from (User_ID: "+user_id+" | Album_ID: "+album_id+") removed from Database")
        for k in range(len(rec_images)):
            name = rec_images[k][0]
            for path_dir in ['i','p','s']:
                image_path = config.site_location+path_dir+'/'+user_id+'/'+name+'.jpg'
                os.remove(image_path)
            self.oprint("{remove_albums} (User_ID: "+user_id+" | Album_ID: "+album_id+" ) Removed image from HDD: " + name)
    self.oprint("{remove_albums} It took %s to remove Albums" % self.time_spent())
    cur.close()


import random
import time

# World Variables ------------------
_5Stars = [
    "Keqing",
    "Mona",
    "Qiqi",
    "Jean",
    "Diluc",
    "Amos Bow",
    "Skyward Harp",
    "Lost Prayer To The Sacred Winds",
    "Skyward Atlas",
    "Primordial Jade Winged-Spear",
    "Skyward Spine",
    "Wolf's Gravestone",
    "Skyward Pride",
    "Skyward Blade",
    "Aquila Favonia",
]
_4Stars = [
    "Sucrose",
    "Chongyun",
    "Noelle",
    "Bennett",
    "Fischl",
    "Ningguang",
    "Xingqiu",
    "Beidou",
    "Xiangling",
    "Amber",
    "Razor",
    "Kaeya",
    "Barbara",
    "Lisa",
    "Rust",
    "Sacrificial Bow",
    "The Stringless",
    "Favonius Warbow",
    "Eye Of Perception",
    "Sacrificial Fragments",
    "The Widsithv",
    "Favonius Codex",
    "Favonius Lance",
    "Dragon's Bane",
    "Rainslasher",
    "Sacrificial Greatsword",
    "The Bell",
    "Favonius Greatsword",
    "Lions Roar",
    "Sacrificial Sword",
    "The Flute",
    "Favonius Sword",
]
_3Stars = [
    "Slingshot",
    "Sharpshooter's Oath",
    "Raven Bow",
    "Emerald Orb",
    "Thrilling Tales Of Dragon Slayers",
    "Magic Guide",
    "Black Tassel",
    "Debate Club",
    "Bloodtainted Greatsword",
    "Ferrous Shadow",
    "Skyrider Sword",
    "Harbinger Of Dawn",
    "Cool Steel",
]

inventory = {
    "5Stars": ["MC"],
    "4Stars": [],
    "3Stars": [],
}

global pulls_since_5
pulls_since_5 = 0
global pulls_since_4
pulls_since_4 = 0

# Functions -------------------------
def starAnimation(stuffGot):
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
    time.sleep(0.25)
    print("`")
    time.sleep(0.25)
    print('  `')
    time.sleep(0.25)
    print('    `')
    time.sleep(0.25)
    print('      `')
    time.sleep(0.25)
    print('       `   *  ')
    time.sleep(0.25)
    print('     * (    #    ) *         ')
    time.sleep(0.25)
    print('      *(   #***#   )*      ')
    time.sleep(0.25)
    print('        * (  # ) *        ')
    time.sleep(0.25)
    print('            *           ')
    time.sleep(0.25)
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print()

    print("---- Pulled ----")
    for stuff in stuffGot:
        print(stuff)

def getPull(rarity):
    if rarity == 5:
        l = len(_5Stars) -1
        num = random.randint(0,l)
        pull = _5Stars[num]
        inventory["5Stars"].append(pull)
        return pull +" **"
    elif rarity == 4:
        l = len(_4Stars) -1
        num = random.randint(0,l)
        pull = _4Stars[num]
        inventory["4Stars"].append(pull)
        return pull + " *"
    else:
        l = len(_3Stars) -1
        num = random.randint(0,l)
        pull = _3Stars[num]
        inventory["3Stars"].append(pull)
        return pull

def makeWish(ammount):
    stuffGot = [];
    animation = False
    global pulls_since_5
    global pulls_since_4

    for val in range(0,ammount):
        if pulls_since_5 >= 89:
            stuffGot.append(getPull(5))
            animation = True
            pulls_since_5  = 0
            pulls_since_4  = 0
        elif pulls_since_4 >= 9:
            stuffGot.append(getPull(4))
            animation = True
            pulls_since_5 += 1
            pulls_since_4  = 0
        else:
            num = random.randint(0,1000)
            if num >= 994:
                stuffGot.append(getPull(5))
                animation = True
                pulls_since_5  = 0
            elif num < 994 and num >= 943:
                stuffGot.append(getPull(4))
                animation = True
                pulls_since_5 += 1
                pulls_since_4  = 0
            else :
                stuffGot.append(getPull(3))
                pulls_since_4 += 1
                pulls_since_5 += 1

    if animation:
        starAnimation(stuffGot)
    else:
        print("---- Pulled ----")
        for stuff in stuffGot:
            print(stuff)
    start()

def start():
    print("--------------------------------------------")
    userInput = input()
    try:
        if int(userInput) >0:#<= 10:
            makeWish(int(userInput))
    except:
        if userInput.lower() == 'inventory':
            print("~~ 5 Stars ~~\n")
            for x in inventory['5Stars']:
                print(x)
            print("~~ 4 Stars ~~\n")
            for x in inventory['4Stars']:
                print(x)
            #print("~~ Junk ~~\n")
            #for x in inventory['3Stars']:
            #    print(x)
            start()
        elif userInput.lower() == 'q':
            quit()
        else:
            print("Dumbbutt do it right")
            start()

# Start -----------------------------
print()
print("Welcome let me explain how to use this program :)")
print("Simply type the number of pulls you wish to make (10 max) \nor type 'Inventory' to see your inventory")
print("Thats all there is to know! Have Fun!! ")
print()
start()


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

import sys
import time

STYLE = {
        'fore': {
                'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
                'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37,
        },
        'back': {
                'black': 40, 'red': 41, 'green': 42, 'yellow': 43,
                'blue': 44, 'purple': 45, 'cyan': 46, 'white': 47,
        },
        'mode': {
                'bold': 1, 'underline': 4, 'blink': 5, 'invert': 7,
        },
        'default': {
                'end': 0,
        }
}

def useStyle(string, mode='', fore='', back=''):
    mode = '%s' % STYLE['mode'][mode] if STYLE['mode'].has_key(mode) else ''
    fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else ''
    back = '%s' % STYLE['back'][back] if STYLE['back'].has_key(back) else ''
    style = ';'.join([s for s in [mode, fore, back] if s])
    style = '\033[%sm' % style if style else ''
    end = '\033[%sm' % STYLE['default']['end'] if style else ''

    return '%s%s%s' % (style, string, end)

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

    return int(cr[1]), int(cr[0])

terminal_width, terminal_hight = getTerminalSize()

def updateTerminalSize():
    global terminal_width
    global terminal_hight
    terminal_width, terminal_hight = getTerminalSize()

# 清除屏幕
def clearScreen():
    sys.stdout.write("\033[2J")

# 清除从光标到行尾的内容
def clearLine():
    sys.stdout.write("\033[K")

# 光标复位
def resetCursor():
    sys.stdout.write("\033[H")

# 光标保存
def saveCursor():
    sys.stdout.write("\033[s")

# 光标恢复
def recoverCursor():
    sys.stdout.write("\033[u")

# 光标隐藏
def hideCursor():
    sys.stdout.write("\033[?25l")

# 光标显示
def showCursor():
    sys.stdout.write("\033[?25h")

# 定位光标
def moveCursor(x, y):
    sys.stdout.write("\033[%d;%dH" % (y, x))

# 上移光标
def moveupCursor(y):
    sys.stdout.write("\033[%dA" % y)

# 下移光标
def movedownCursor(y):
    sys.stdout.write("\033[%dB" % y)

# 左移光标
def moveleftCursor(x):
    sys.stdout.write("\033[%dD" % x)

# 右移光标
def moverightCursor(x):
    sys.stdout.write("\033[%dC" % x)

def printString(x, y, string, mode='', fore='', back='', flush=True):
    moveCursor(x, y)
    str_style = useStyle(string, mode, fore, back)
    sys.stdout.write(str_style)
    if flush:
        sys.stdout.flush()

def printString_Center(num_line, string, mode='', fore='', back='', flush=True):
    moveCursor(1, num_line)
    length = len(string)
    x = terminal_width//2 - length//2 + 1
    # printString(x, 2, "x = %d, num_line = %d" % (x, num_line))
    printString(x, num_line, string, mode, fore, back, flush)

def printHLine(x, y, length, ch, mode='', fore='', back='', flush=True):
    printString(x, y, ch*length, mode, fore, back, flush)

def printVLine(x, y, hight, ch, mode='', fore='', back='', flush=True):
    for i in range(hight):
        printString(x, y+i, ch, mode, fore, back, flush)

def printRectangle(x1, y1, x2, y2, ch, mode='', fore='', back='', flush=True):
    printHLine(x1, y1, x2-x1+1, ch, mode, fore, back, False)
    printVLine(x1, y1+1, y2-y1, ch, mode, fore, back, False)
    printHLine(x1, y2, x2-x1+1, ch, mode, fore, back, False)
    printVLine(x2, y1+1, y2-y1, ch, mode, fore, back, False)
    if flush:
        sys.stdout.flush()

def printSolidRectangle(x1, y1, x2, y2, ch, mode='', fore='', back='', flush=True):
    width = x2-x1+1
    for y in range(y1, y2+1):
        printHLine(x1, y, width, ch, mode, fore, back, False)
    if flush:
        sys.stdout.flush()

def printRectangle_Amend(x1, y1, x2, y2, ch, mode='', fore='', back='', flush=True):
    printHLine(x1, y1, x2-x1+1, ch, mode, fore, back, False)
    printVLine(x1, y1+1, y2-y1, ch, mode, fore, back, False)
    printVLine(x1+1, y1+1, y2-y1, ch, mode, fore, back, False)
    printHLine(x1, y2, x2-x1+1, ch, mode, fore, back, False)
    printVLine(x2-1, y1+1, y2-y1, ch, mode, fore, back, False)
    printVLine(x2, y1+1, y2-y1, ch, mode, fore, back, False)
    if flush:
        sys.stdout.flush()

class OverScolling(object):
    def __init__(self, x1, y1, x2, y2, mode='', fore='', back='', table_width=8):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.mode = mode
        self.fore = fore
        self.back = back
        self.width = x2 - x1 + 1
        self.hight = y2 - y1 + 1
        self.table_width = table_width
        # self.cur_line = y1
        self.str_list = []
        self.str_list.append(('', 0))
        self.setCanvas()
        # print "width = %d, hight = %d" % (self.width, self.hight)

    def setCanvas(self):
        printSolidRectangle(self.x1, self.y1, self.x2, self.y2, ' ', \
            self.mode, self.fore, self.back)

    def __addString_base(self, string):
        self.str_list.append((string, len(string)))
        if len(self.str_list) - 1 > self.hight:
            self.str_list = self.str_list[1:]
        for i in range(self.hight):
            if len(self.str_list) - 1 <= i:
                break
            diff = 0 if self.str_list[i][1] <= self.str_list[i+1][1] \
                        else self.str_list[i][1] - self.str_list[i+1][1]
            string = self.str_list[i+1][0] + ' ' * diff
            printString(self.x1, self.y1+i, string, self.mode, self.fore, self.back, False)
        moveCursor(self.x1+self.str_list[-1][1], self.y1+len(self.str_list)-1-1)
        sys.stdout.flush()

    def addToList(self, l, i, v):
        if i < len(l):
            l[i] = v
        else:
            l.append(v)
        return l

    def handleBRT(self, string):
        l = []
        i = 0
        for c in string:
            if c == '\b':
                if i > 0:
                    i -= 1
            elif c == '\r':
                i = 0
            elif c == '\t':
                i = (i//self.table_width + 1) * self.table_width
                for n in range(len(l), i):
                    l.append(' ')
            else:
                l = self.addToList(l, i, c)
                i += 1
        return ''.join(l)

    def handleIgnore(self, string):
        l = string.split("\f")
        string = '\\f'.join(l)
        l = string.split("\v")
        string = '\\v'.join(l)
        return string

    def splitStringByLength(self, string, length):
        res = []
        num = len(string) // length
        for i in range(num):
            res.append(string[length*i:length*(i+1)])
        res.append(string[length*num:])
        return res

    def handleString(self, string, length):
        res = []
        string_n = string.split('\n')
        for s in string_n:
            s = self.handleBRT(s)
            s = self.handleIgnore(s)
            s = self.splitStringByLength(s, length)
            res += s
        return res

    def addString(self, string):
        strings = self.handleString(string, self.width)
        for s in strings:
            self.__addString_base(s)

class OverScollingCenter(OverScolling):
    def __init__(self, num_line, width, hight, mode='', fore='', back='', table_width=8):
        self.num_line = num_line
        self.width = width if terminal_width > width else terminal_width
        self.hight = hight if terminal_hight > hight else terminal_hight
        self.mode = mode
        self.fore = fore
        self.back = back
        self.x1 = terminal_width//2 - self.width//2 + 1
        self.x2 = self.x1 + self.width - 1
        self.y1 = self.num_line
        self.y2 = self.y1 + self.hight - 1
        super(OverScollingCenter, self).__init__(self.x1, self.y1, self.x2, self.y2, \
            self.mode, self.fore, self.back, table_width)

def test():
    clearScreen()
    moveCursor(1, 1)
    printString_Center(1, "Scolling Test")
    # printRectangle(2, 2, 20, 10, ' ', mode='blink', fore='white', back='white')
    # printSolidRectangle(2, 10, 20, 20, ' ', mode='blink', fore='white', back='white')
    # print getTerminalSize()
    # scroll = OverScolling(2, 5, 50, 7, mode='', fore='green', back='black')
    scroll = OverScollingCenter(3, terminal_width-10, 15, mode='', fore='red', back='white')
    scroll1 = OverScolling(3, 21, terminal_width//2-2, 30, mode='bold', fore='whilte', back='green')
    scroll2 = OverScolling(terminal_width//2+2, 21, terminal_width-2, 30, mode='underline', fore='whilte', back='green')
    import time
    import random
    import sys
    cur_f = open(sys.argv[0], 'r')
    for i in range(100):
        # string = '#' * random.randint(0, 100) + '[%d]' % (i+1)
        string = cur_f.readline()[:-1]
        string1 = '$' * random.randint(0, 100) + '[%d]' % (i+1)
        string2 = '%' * random.randint(0, 100) + '[%d]' % (i+1)
        scroll.addString(string)
        scroll1.addString(string1)
        scroll2.addString(string2)
        time.sleep(0.5)
    cur_f.close()
    moveCursor(1, terminal_hight)

if __name__ == '__main__':
    test()


import json
import time

def get_result(version="020000"):
    with open('out/basic/00/answer/test-'+version+".json", 'r') as f:
        json_content = json.load(f)
        return json_content

if __name__ == "__main__":
    start_time = time.time()

    result = get_result()

    result_scores = result["scores"]
    print(len(list(result_scores.keys())))
    print(len(list(result.keys())))

    counter = 0
    for key, val in result.items():
        if key != "scores":
            print(key)
            print(val)
            print(result_scores[key])
            print("\n\n")
            counter += 1

        if counter > 3:
            break

    print("Program execution time")
    print(time.time() - start_time)


#!/usr/bin/env python
from collections import namedtuple
import pytest
import jip
import jip.cluster as cl

@pytest.mark.parametrize("name", [
    'jip.cluster.Slurm',
    'jip.cluster.PBS',
    'jip.cluster.LSF',
    'jip.cluster.SGE',
])
def test_loading_internal_implementations(name):
    assert cl.get(name) is not None

def test_cluster_not_found():
    with pytest.raises(cl.ClusterImplementationError):
        cl.get('unknown')

def test_cluster_name_none():
    jip.config.config['cluster'] = None
    with pytest.raises(cl.ClusterImplementationError):
        cl.get(None)

@pytest.mark.parametrize("name,term", [
    ('jip.cluster.Slurm', '%j'),
    ('jip.cluster.PBS', '$PBS_JOBID'),
    ('jip.cluster.LSF', '%J'),
    ('jip.cluster.SGE', '$JOB_ID'),
])
def test_resolving_log_file_names(name, term):
    Job = namedtuple('Job', 'job_id')
    j = Job(1)
    cluster = cl.get(name)
    assert cluster.resolve_log(j, "log-%s" % term) == "log-1"

def test_sge_threads_pe_loading():
    jip.config.config['sge'] = {
        "threads_pe": 'threads'
    }
    sge = cl.SGE()
    assert sge.threads_pe == 'threads'


import os
from . import utils_func

    # # List of django_q models
    # task_list = django_q.models.Task.objects
    # success_list = django_q.models.Success.objects
    # failure_list = django_q.models.Failure.objects
    # ormqs_list = django_q.models.OrmQ.objects
    # # All objects in each django_q models
    # tasks_all = task_list.all()
    # success_all = success_list.all()
    # failure_all = failure_list.all()
    # ormq_all = ormqs_list.all()
    # print("!!!!!!!!!tasks_all: ", tasks_all)
    # print(len(tasks_all))
    # print("!!!!!!!!!success_all: ", success_all)
    # print(len(success_all))
    # print("!!!!!!!!!failure_all: ", failure_all)
    # print(len(failure_all))
    # print("!!!!!!!!!ormq_all: ", ormq_all)
    # print(len(ormq_all))
    #
    #
    # # Check whether in success_list (task is established and succeed)
    # success_select = success_list.filter(name = new_task_name)
    # print("success_select: ", success_select)
    # # Check whether in failer_list (task is established and failed)
    # failure_select = failure_list.filter(name = new_task_name)
    # print("failure_select: ", failure_select)
    #
    # # Check whether in queue list (task is not created)
    # queue_select = [o for o in ormq_all if o.name() == new_task_name]
    # print("queue_select: ", queue_select)
    #
    # print("!!!!!!!!!success_select: ", success_select)
    # print("!!!!!!!!!failure_select: ", failure_select)
    # print("!!!!!!!!!queue_select: ", queue_select)
    #
    # # Target : check whether the running jobs is in which status
    # # 1. Still in Queue
    # # 2. Running
    # # 3. Success
    # # 4. Failed
    # # ** It will not be in the Schedule list ~
    # if len(success_select) == 1:
    #     return "Success"
    # if len(success_select) == 0:
    #     print("length failure_select is zero!!")
    #
    # if len(failure_select) == 1:
    #     return "Failure"
    # if len(failure_select) == 0:
    #     print("length failure_select is zero!!")
    #
    # if len(queue_select) == 1:
    #     return "Queue"
    # if len(queue_select) == 0:
    #     print("length queue_select is zero!!")
    #
    # if len(success_select) == 0 and len(failure_select) == 0 and len(queue_select) == 0 :
    #     return "None"

    # print("ormq_select: ", ormq_select)

    # args, func, group, hook, id, kwargs, name, result, started, stopped, success
    # print("@@@ tasks_all args: ", tasks_all[0].args)
    # print("@@@ tasks_all func: ", tasks_all[0].func)
    # print("@@@ tasks_all group: ", tasks_all[0].group)
    # print("@@@ tasks_all hook: ", tasks_all[0].hook)
    # print("@@@ tasks_all id: ", tasks_all[0].id)
    # print("@@@ tasks_all kwargs: ", tasks_all[0].kwargs)
    # print("@@@ tasks_all name: ", tasks_all[0].name)
    # print("@@@ tasks_all result: ", tasks_all[0].result)
    # print("@@@ tasks_all started: ", tasks_all[0].started)
    # print("@@@ tasks_all stopped: ", tasks_all[0].stopped)
    # print("@@@ tasks_all success: ", tasks_all[0].success)
    #
    # print("@@@ success_all", success_all)
    # print("@@@ failure_all", failure_all)
    # print("@@@ ormq_all", ormq_all)
    # print("@@@ ormq_all", ormq_all[0].id)
    # print("@@@ ormq_all", ormq_all[0].name())
    # print("@@@ ormq_all", ormq_all[0].task_id())
    #
    # print("@@@ ormq_all", ormq_all[0].key)
    # print("@@@ ormq_all", ormq_all[0].lock)
    # print("@@@ ormq_all", ormq_all[0].payload)

def Whole_check_reference_based_results(url_base_dir, base_dir, sample_list):
    samples_all_info = {}
    for sample_name in sample_list:
        url_sample_base_dir = os.path.join(url_base_dir, sample_name)
        samples_all_info[sample_name] = {}
        one_sample_all_info = {}
        sample_datadir = os.path.join(base_dir, sample_name)
        ## Checking files
        ## Reference-based file checking!!
        Step_1_check_first_qc = utils_func.Step_1_check_first_qc(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_1_check_first_qc"] = Step_1_check_first_qc[0]
        Step_1_check_trimming_qc = utils_func.Step_1_check_trimming_qc(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_1_check_trimming_qc"] = Step_1_check_trimming_qc[0]
        Step_1_check_second_qc = utils_func.Step_1_check_second_qc(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_1_check_second_qc"] = Step_1_check_second_qc[0]
        Step_2_check_reference_based_bwa_sam = utils_func.Step_2_check_reference_based_bwa_sam(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_2_check_reference_based_bwa_sam"] = Step_2_check_reference_based_bwa_sam[0]
        Step_2_check_reference_based_bwa_report_txt = utils_func.Step_2_check_reference_based_bwa_report_txt(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_2_check_reference_based_bwa_report_txt"] = Step_2_check_reference_based_bwa_report_txt[0]
        Step_3_check_reference_based_samtools_fixmate_bam = utils_func.Step_3_check_reference_based_samtools_fixmate_bam(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_3_check_reference_based_samtools_fixmate_bam"] = Step_3_check_reference_based_samtools_fixmate_bam[0]
        Step_3_check_reference_based_samtools_sorted_bam = utils_func.Step_3_check_reference_based_samtools_sorted_bam(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_3_check_reference_based_samtools_sorted_bam"] = Step_3_check_reference_based_samtools_sorted_bam[0]
        Step_4_check_reference_based_bcftools_vcf = utils_func.Step_4_check_reference_based_bcftools_vcf(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_4_check_reference_based_bcftools_vcf"] = Step_4_check_reference_based_bcftools_vcf[0]
        Step_4_check_reference_based_bcftools_vcf_revise = utils_func.Step_4_check_reference_based_bcftools_vcf_revise(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_4_check_reference_based_bcftools_vcf_revise"] = Step_4_check_reference_based_bcftools_vcf_revise[0]
        Step_5_check_reference_based_snpeff_vcf_annotation = utils_func.Step_5_check_reference_based_snpeff_vcf_annotation(url_sample_base_dir, sample_datadir, sample_name)
        one_sample_all_info["Step_5_check_reference_based_snpeff_vcf_annotation"] = Step_5_check_reference_based_snpeff_vcf_annotation[0]
        samples_all_info[sample_name] = one_sample_all_info
    sample_checker_list = []
    for sample_key, sample_check_info in samples_all_info.items():
        ans = all(value == True for value in sample_check_info.values())
        sample_checker_list.append(ans)
    #This is for checking everything is fine~~~
    # sample_checker_list.append(False)
    overall_sample_result_checker = all(item == True for item in sample_checker_list)
    return (overall_sample_result_checker, samples_all_info)


#coding:utf-8
import unittest
class AssertResult(unittest.TestCase):
    #比较实际返回值与期望返回值
    def __init__(self):
        super(AssertResult, self).__init__()
        self.result = 1
    def compareDict(self, dict1, dict2):
        try:
            for key1, value1 in dict1.items():
                if not isinstance(value1, dict):
                    if self.assertresult(value1, dict2[key1]):
                        self.result *= 1
                    else:
                        print("{}不等于{}".format(value1, dict2[key1]))
                        self.result *= 0
                        #break
                else:
                    self.compareDict(value1, dict2[key1])
        except (AttributeError, KeyError) as e:
            print(e)
            print(dict1)
            print(dict2)
            self.result = 0
        return self.result

    def assertresult(self, res, exp_res):
        try:
            self.assertEqual(res, exp_res)
            print("pass")
            return True
        except Exception  as e:
            print("fail")
            print(e)
            return False
if __name__ == "__main__" and __package__ is None:
    __package__ = "assert_results"

if __name__ == "__main__":
    dict1 = {"content": {"sourceUrl": "as","location": "lt" },"active": True}
    dict2 = {"data": None, "err": 0, "msg": "success"}
    dict3 = {"data": None, "err": 0, "msg": "success"}
    dict4 = {"content": {"sourceUrl": "as", "location": "lt"}, "active": True}
    print(AssertResult().compareDict(dict1, dict2))


import MH_game_mechanics as mhgm
import re
import time

def main():
    """
    Play Let's Make a Deal! as made famous in the Monty Hall problem.
    """
    game = mhgm.Game()

    run_intro(game)
    first_round(game)
    montys_intervention(game)
    second_round(game)
    final_reveal(game)

def run_intro(game):
    """
     - Welcome message + presentation of doors.
    """
    print("\nWelcome to Let's Make a Deal!\n")
    input("(Press enter to continue...)\n")
    print("In front of you are 3 doors: ")
    list_remaining_doors(game, revealed=False)
    input("...\n")
    print("\nBehind one of the doors is a brand new car! Behind the others are goats...")
    input("...\n")

def first_round(game):
    """
     - Player prompted to select door.
     - game updated.
    """
    player_choice_1 = get_first_choice(game.door_nums)
    game.update_player_choice(player_choice_1)
    input("...\n")

def montys_intervention(game):
    """
     - Monty selects doors to open, revealing booby prizes. Leaves players first choice
    and one other door unopened.
     - game updated.
    """
    print("Monty has offered to open one of the remaining doors!\n")
    available = game.get_selectable_doors("prize", "chosen")
    while len(game.get_selectable_doors("montys_choice")) > 2:
        montys_choice = game.update_monty_choice(available)
        print(f'He opens Door #{montys_choice} and reveals a goat!')
        available.remove(montys_choice)
    input("...\n")

def second_round(game):
    """
     - Player prompted to stick with original choice or switch to the other option.
     - game updated.
    """
    print(f'There remain two unopened doors: ')
    list_remaining_doors(game, "montys_choice")
    old_choice = game.query_player_choice()
    new_choice = input("\nWould you like to stick or twist? ")
    while not re.fullmatch(r"stick|twist", new_choice, re.IGNORECASE):
        new_choice = input(f"Enter 'stick' to stick with Door {old_choice} or 'twist' to change: ")
    player_choice_2 = stick_or_twist(old_choice, new_choice, game)
    game.update_player_choice(player_choice_2)
    print()

def final_reveal(game):
    """
    - Dramatic final prize reveal.
    """
    print("You won", end='', flush=True)
    time.sleep(0.5)
    print(".", end='', flush=True)
    time.sleep(0.5)
    print(".", end='', flush=True)
    time.sleep(0.5)
    print(". ", end='', flush=True)
    time.sleep(0.5)
    if game.check_player_won():
        print("a car!", end='', flush=True)
    else:
        print("a goat!", end='', flush=True)
    time.sleep(1)
    print('\n')

def list_remaining_doors(game, *ignore_list, revealed=False):
    """
    Takes list of ignore criteria and prints doors available for selection.
    revealed option reveals prize for debug purposes.
    """
    for door_num in game.get_selectable_doors(*ignore_list):
        print(f" - Door #{door_num}", end='')
        if revealed:
            print(f": {game.doors[door_num]['prize']}")
        else:
            # print new line if prize not appended
            print()

def get_first_choice(door_nums):
    """
    Takes
    """
    while True:
        try:
            choice = int(input("Choose a door # to open: "))
        except ValueError:
            print("Please enter a digit only.")
            continue
        else:
            if choice in door_nums:
                print(f'You chose Door #{choice}!')
                return choice
            else:
                print(f"{choice} isn't an available door!")

def stick_or_twist(old_choice, new_choice, game):
    """
    Takes old_choice (int) and new_choice (str).
    Returns door choice as int based on player's choice.
    """
    if new_choice.lower() == "stick":
        return old_choice

    twist = game.get_selectable_doors("montys_choice", "chosen")[0]
    return twist

if __name__ == '__main__':
    main()


def loop_merge_sort(l1,l2):
    tmp = []
    while len(l1)>0 and len(l2)>0:
        if l1[0] <l2[0]:
            tmp.append(l1[0])
            del l1[0]
        else:
            tmp.append(l2[0])
            del l2[0]
    print(tmp)

36.两个有序列表，l1,l2，对这两个列表进行合并不可使用extend.py

36.两个有序列表，l1,l2，对这两个列表进行合并不可使用extend.py


"""
Django settings for kanri project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('KANRI_SECRET_KEY')
AUSPOST_KEY = os.environ.get('KANRI_AUSPOST_KEY')
POSTMARK_API_KEY = os.environ.get('KANRI_POSTMARK_KEY')
POSTMARK_SENDER = os.environ.get('KANRI_POSTMARK_SENDER')

DEBUG = bool(os.environ.get('KANRI_DEBUG', ''))
TEMPLATE_DEBUG = DEBUG

# Application definition
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'kanri_template_tags',
    'dashboard',
    'attendance',
    'mentors',
    'ninjas',
    'planner',
    'accounts',
    'jobs',
    'rewards',
    'south',
    'lockout',
    'reversion',
    'bootstrap3'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'lockout.middleware.LockoutMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'kanri.urls'
WSGI_APPLICATION = 'kanri.wsgi.application'

# Try to config Heroku database (if we're on Heroku)
import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config()

if len(DATABASES['default']) == 0:
    # We aren't on Heroku, configure local db.
    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-au'
TIME_ZONE = 'Australia/Perth'
USE_I18N = True
USE_L10N = True
USE_TZ = True

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates').replace('\\','/'),
)

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

AUTH_USER_MODEL = 'accounts.KanriUser'

# Postmark Emails
EMAIL_BACKEND = 'postmark.backends.PostmarkBackend'

# Proxy stuff
USE_X_FORWARDED_HOST = True

# Customised django.contrib.messages for bootstrap
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.ERROR: 'danger',
}


from django.db import models
import uuid
from django.db import migrations, models
from django.contrib.auth.models import User
# Create your models here.
#1. create a model tname time seriesdata
#2. make sure it have the fields  (datetime,low,high,open,close,volumefrom,volumeto)
#3.make sure run python manage make migration
#4. pyhon manage.py migrate

#thats all

class TimeSeriesDatum(models.Model):

        date = models.DateTimeField()
        low =  models.FloatField()
        high =  models.FloatField()
        open =  models.FloatField()
        close =  models.FloatField()
        volume_from = models.FloatField()
        volume_to = models.FloatField()

        def __int__(self):
            return  int(self.datetime) + int(self.low) + int(self.high) + int(self.open) + int(self.close) + int(self.volume_from) + int(self.volume_to)


# -*- coding=UTF-8 -*-
"""Asset notify.  """

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import io
import logging
import os
import time
import webbrowser
from tempfile import mkstemp

import nuke
import pendulum
from jinja2 import Environment, FileSystemLoader

import callback
from nuketools import utf8
from wlf.codectools import get_encoded as e
from wlf.codectools import get_unicode as u
from wlf.decorators import run_with_clock

from . import core
from .monitor import FootagesMonitor

LOGGER = logging.getLogger(__name__)

def warn_missing_frames(assets=None, show_ok=False):
    """Show missing frames to user
        assets (any, optional): Defaults to None.
            object contains assets, None mean all Assets.
        show_ok (bool, optional): Defaults to False.
            If show message for no missing frames.
    """

    if assets is None:
        assets = FootagesMonitor.all()
    else:
        assets = FootagesMonitor(assets)

    result = assets.missing_frames_dict()
    if not result:
        if show_ok:
            nuke.message(utf8('没有发现缺帧素材'))
    elif len(result) < 10:
        if nuke.GUI:
            nuke.message(utf8(result.as_html().replace('\n', '')))
        else:
            LOGGER.warning(result)
    else:
        # Use html to display.
        fd, name = mkstemp('.html', text=True)
        with io.open(fd, 'w') as f:
            f.write(result.as_html())
        webbrowser.open(name)

SHOWED_WARNING = []

def throtted_warning(msg):
    """Only show each warning message once.  """

    msg = u(msg)
    if msg not in SHOWED_WARNING:
        nuke.warning(utf8(msg))
        SHOWED_WARNING.append(msg)

def reset_warning_history():
    """Forget showed warning.  """

    del SHOWED_WARNING[:]

def warn_mtime(show_ok=False, since=None):
    """Show footage that mtime newer than script mtime. """

    LOGGER.debug('Check warn_mtime')

    try:
        script_name = nuke.scriptName()
    except RuntimeError:
        if show_ok:
            nuke.message(utf8('文件未保存'))
        return
    script_mtime = os.path.getmtime(e(script_name))
    since = since or script_mtime

    @run_with_clock('检查素材修改日期')
    def _get_mtime_info():
        ret = {}
        for n in nuke.allNodes('Read', nuke.Root()):
            try:
                mtime = time.mktime(time.strptime(
                    n.metadata('input/mtime'), '%Y-%m-%d %H:%M:%S'))
            except TypeError:
                continue
            if mtime > since:
                ret[nuke.filename(n)] = mtime
                ftime = time.strftime('%m-%d %H:%M:%S', time.localtime(mtime))
                throtted_warning(
                    '{}: [new footage]{}'.format(u(n.name()), ftime))
        return ret

    newer_footages = _get_mtime_info()

    if not (show_ok or newer_footages):
        return

    env = Environment(loader=FileSystemLoader(core.TEMPLATES_DIR))
    template = env.get_template('mtime.html')
    data = [(k, pendulum.from_timestamp(v).diff_for_humans())
            for k, v in newer_footages.items()]
    msg = template.render(script_name=script_name,
                          script_mtime=pendulum.from_timestamp(
                              script_mtime).diff_for_humans(),
                          data=data)
    nuke.message(utf8(msg))

def setup():
    pendulum.set_locale('zh')
    callback.CALLBACKS_ON_SCRIPT_LOAD.append(reset_warning_history)
    callback.CALLBACKS_ON_SCRIPT_LOAD.append(warn_missing_frames)
    callback.CALLBACKS_ON_SCRIPT_LOAD.append(warn_mtime)
    callback.CALLBACKS_ON_SCRIPT_SAVE.append(warn_missing_frames)


from ctypes import *

'''
#define BLAKE3_VERSION_STRING "0.3.7"
#define BLAKE3_KEY_LEN 32
#define BLAKE3_OUT_LEN 8
#define BLAKE3_BLOCK_LEN 8
#define BLAKE3_CHUNK_LEN 32
#define BLAKE3_MAX_DEPTH 4
#define BLAKE3_MAX_SIMD_DEGREE 16

typedef struct {
  uint32_t cv[8];
  uint64_t chunk_counter;
  uint8_t buf[BLAKE3_BLOCK_LEN];
  uint8_t buf_len;
  uint8_t blocks_compressed;
  uint8_t flags;
} blake3_chunk_state;

typedef struct {
  uint32_t key[8];
  blake3_chunk_state chunk;
  uint8_t cv_stack_len;
  uint8_t cv_stack[(BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN];
} blake3_hasher;
'''
BLAKE3_VERSION_STRING="0.3.7"
BLAKE3_KEY_LEN=32
BLAKE3_OUT_LEN=8
BLAKE3_BLOCK_LEN=8
BLAKE3_CHUNK_LEN=32
BLAKE3_MAX_DEPTH=4
BLAKE3_MAX_SIMD_DEGREE=16

class blake3_chunk_stack(Structure):
    _fields_ = [("cv", c_uint * 8),
                ("chunk_counter", c_ulonglong),
                ("buf", c_ubyte * BLAKE3_BLOCK_LEN),
                ("buf_len", c_ubyte),
                ("blocks_compressed", c_ubyte),
                ("flags", c_ubyte)]

class blake3_hasher(Structure):
	_fields_ = [("key", c_uint * 8),
                ("chunk", blake3_chunk_stack),
                ("cv_stack_len", c_ubyte),
                ("cv_stack", c_ubyte * (BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN),]

blake3 = CDLL("./libblake3.so")

def blake3_hasher_init():
    instance = blake3_hasher()
    blake3.blake3_hasher_init(byref(instance))
    return instance

def blake3_hasher_update(self, value, length):
    value = (c_byte * length)(value)
    blake3.blake3_hasher_update(byref(self), byref(value), length)
    return self

def blake3_hasher_finalize(self, length):
    value = c_ulonglong()
    blake3.blake3_hasher_finalize(byref(self), byref(value), length)
    return value

a = blake3_hasher_init()
blake3_hasher_update(a, 0x332, 1)
res = blake3_hasher_finalize(a, 8)
print(res)


import os, sys, asyncio, logging, subprocess, math
import time
from picamera import PiCamera

DEFAULT_RESOLUTION = (800,600)
HIGH_RESOLUTION = (1024,768)

class Camera:
    name = ""
    path_to_last_photo = ""
    logger = logging.getLogger(__name__)
    image_output_path = ""

    def __init__(self,name="Base",rotation=None,orientation=None):
        self.name = name
        self.image_output_path = "/home/pi/Code/hangoutsbot/"
        self.rotation = rotation
        self.orientation = orientation

    def take_picture(self, filename):
        self.path_to_last_photo = self.get_image_filepath(filename)

    def upload_last_picture(self, bot, event):
        image_data = open(self.path_to_last_photo,'rb')
        filename = os.path.basename(self.path_to_last_photo)

        self.logger.debug("uploading {} from {}".format(filename, self.path_to_last_photo))

        photo_id = yield from bot._client.upload_image(image_data, filename=filename)
        self.logger.info("Photo id in method: " + photo_id)

        image_data.close
        yield from bot.coro_send_message(event.conv.id_, "", image_id=photo_id)

    def get_image_filepath(self,filename):
        return "{0}/{1}".format(self.image_output_path,filename)

    def enhance(self):
        return

class PiCam(Camera):
    enhance_counter = 0

    def __init__(self, name="PiCam"):
        super(PiCam, self).__init__(name="PiCam",rotation=90,orientation="w")

    #@asyncio.coroutine
    def take_picture(self, filename="picam_image.jpg", enhance=False):
        with PiCamera(resolution=DEFAULT_RESOLUTION) as cam_api:
            cam_api.rotation = self.rotation
            cam_api.vflip = True
            cam_api.hflip = True

            if enhance is True:
                self.enhance_counter = self.enhance_counter + 1
                cam_api.resolution = HIGH_RESOLUTION
                enhance_factor = 1/(math.pow(2, self.enhance_counter))
                cam_api.zoom = (0.0,0.0,enhance_factor,enhance_factor)
                #cam_api.zoom = (cam_api.resolution.width/2,cam_api.resolution.height/2,enhance_factor,enhance_factor)
            else:
                self.enhance_counter = 0
                cam_api.resolution = DEFAULT_RESOLUTION

            cam_api.capture(self.get_image_filepath(filename))
        super(PiCam, self).take_picture(filename)

    def set_rotation(self, rotation):
        self.rotation = rotation

class WebCam(Camera):
    def __init__(self, name="WebCam"):
        super(WebCam, self).__init__(name="WebCam")

    #@asyncio.coroutine
    def take_picture(self, filename="webcam_image.jpg"):
        subprocess.call(['/usr/bin/fswebcam','-r','640x480',self.get_image_filepath(filename)])
        super(WebCam, self).take_picture(filename)

class AllCams(Camera):
    _picam = PiCam()
    _webcam = WebCam()

    def __init__(self, name="AllCams"):
        super(AllCams, self).__init__(name="AllCams")

    def take_picture(self):
        self._picam.take_picture()
        self._webcam.take_picture()

    def upload_last_picture(self, bot, event):
        yield from self._picam.upload_last_picture(bot, event)
        yield from self._webcam.upload_last_picture(bot, event)


# Creates a pipeline that listens to Pub/Sub topic messages streamed from Oracle db and processes them
from __future__ import absolute_import

from google.cloud import bigquery
from google.cloud import pubsub_v1
import apache_beam as beam
import apache_beam.options.pipeline_options as opt
import apache_beam.transforms.window as window # Not used

# Constants
PROJECT    = "organic-palace-306416"
TOPIC      = "BQTopic"
SUBSCRIPTION = "BQTopic-sub"
DATASET    = "test"
TABLE_NAME = "Employee"

# Transformations
class createDict (beam.DoFn):
    def process (self, element):
        columns = ['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME', 'EMAIL', 'JOB_ID', 'SALARY']
        values = element.split (b',') # Convert string to list
        col_val = dict (zip (columns, values)) # Merge the two lists and generate a dictionary
        print (col_val)
        return [col_val]

class upSalaries10pct (beam.DoFn): # Salary rise
    def process (self, element):
        salary = float (element ['SALARY'])
        salary = salary + salary * 0.1
        element ['SALARY'] = salary

        return [element]

class convertToByte (beam.DoFn):
    def process (self, element):
        b_element = bytes (element, 'utf-8') # When streaming, data must be a byte stream
        return [b_element]

#data = 1, 'Greg', 'Nichols', 'Greg@tx.com',1000, 34000

# Program entry point
def run ():
    # Get the Pub/Sub topic object
    topic_name = 'projects/{project_id}/topics/{topic}'.format(project_id = PROJECT, topic = TOPIC)
    subscription_name = 'projects/{project_id}/subscriptions/{subscription}'.format (project_id = PROJECT, subscription = SUBSCRIPTION)
    publisher = pubsub_v1.PublisherClient () # Creates a publisher client
    topic_path = publisher.topic_path (PROJECT, TOPIC) # Creates a fully qualified topic path. Same as previous row

    for i in range (1, 1000001, 1):
        msg = f"{i}, 'Csacsi', 'Bacsi', 'csacso@hotmail.com', 111, 50000"
        msg = bytes (msg, 'utf-8')
        publisher.publish (topic_name, msg)

    # Build and run the pipeline
    pipeline_options = opt.PipelineOptions ()
    pipeline_options.view_as (opt.StandardOptions).streaming = True # Set options first
    google_cloud_options = pipeline_options.view_as (opt.GoogleCloudOptions)
    google_cloud_options.project = PROJECT
    google_cloud_options.job_name = 'myjobx2'
    google_cloud_options.staging_location = 'gs://csacsi/staging'
    google_cloud_options.temp_location = 'gs://csacsi/temp'
    google_cloud_options.region = 'europe-west2'
    workerOptions = pipeline_options.view_as (opt.WorkerOptions)
    workerOptions.num_workers = 3
    pipeline_options.view_as (opt.StandardOptions).runner = 'DataflowRunner'

    with beam.Pipeline (options=pipeline_options) as pcoll: # Creates a pipeline

        messages = pcoll | "Read from pubSub" >> beam.io.ReadFromPubSub (subscription=subscription_name, id_label='message_id') # Read the pubsub topic into a PCollection (creates the pipeline)

        # PCollection: immutable, elements are of same type, no random access. Can be bounded or stream. Windows are used with timestamps
        # Transforms: ParDo, Combine, composite: combines core transforms
        ''' [Final Output PCollection] = ([Initial Input PCollection] | [First Transform] | [Second Transform] | [Third Transform]) '''

        dict_rows = messages | "Convert to dict" >> beam.ParDo (createDict ())

        rows_to_insert = dict_rows | "Up salaries by 10%" >> beam.ParDo (upSalaries10pct ())

        #byte_stream = rows | "Convert to byte" >> beam.ParDo (convertToByte ())

        rows_to_insert | beam.io.WriteToBigQuery (table   = TABLE_NAME,
                                                  dataset = DATASET,
                                                  project = PROJECT,
                                                  schema  = ("EMPLOYEE_ID:INTEGER,"
                                                             "FIRST_NAME:STRING,"
                                                             "LAST_NAME:STRING,"
                                                             "EMAIL:STRING,"
                                                             "JOB_ID:INTEGER,"
                                                             "SALARY:INTEGER"),
                                                  create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, # Creates table if does not exist CREATE_IF_NEEDED
                                                  write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND, # Could be WRITE_TRUNCATE
                                                  ignore_insert_ids = True)

# **************************************************** End of code ********************************************************

# Alternative solution using the subscribers callback to write to BigQuery - not using beam/DataFlow
def subscriber_fn (project, subscription_name):
    subscriber = pubsub.SubscriberClient ()
    subscription_path = subscriber.subscription_path(project, subscription_name)

    def callback(message): # When a message is received it is processed and acknowledged here
        print('Received message: {}'.format(message))
        write2BQ (message.data)
        message.ack ()

    subscription = subscriber.subscribe (subscription_path, callback=callback)
    print('Listening for messages on {}'.format(subscription_path))

    future = subscription.open (callback) # Program blocks shere and waits for published messages
    try:
        future.result()
    except Exception as e:
        print('Listening for messages on {} threw an Exception: {}'.format(subscription_name, e))
        raise

# Write to BigQuery
def write2BQ (dataset_id, table_id, message):
    client = bigquery.Client () # Instantiate BigQuery client

    # Get dataset details
    dataset_ref = client.dataset (dataset_id)
    table_ref = dataset_ref.table(table_id)
    table = client.get_table(table_ref)

    errors = client.insert_rows (table, message) # Stream writing

    if not errors:
        print('Messages loaded into {}:{}'.format (dataset_id, table_id))
    else:
        print('Errors:')
        for error in errors:
            print(error)

# Starts here if executed as script
if __name__ == '__main__':
  run ()


import random
import math
import os
from coep_package.latex import latex
from coep_package.csv_module import putInCsv, database_fn

signs = ['+', '-', '*', '/']

expression2 = ''
inter_solution2 = ''
inter_solution2_2 = ''
solution2 = ''
solution2_2 = ''
calc_ans2 = ''
eval_expression = ''
correctIndex = ''
allOptions = []
wrong_Options = []
soln_print = ''

def generateExpressionBracket1():
    var1 = random.randint(-150, 150)
    var2 = random.randint(1, 150)
    var3 = random.randint(-150, 150)
    symbol1 = signs[random.randint(0,3)]
    symbol2 = signs[random.randint(0,3)]
    if var1 < 0:
        var1 = '(' + str(var1) + ')'
    if var3 < 0:
        var3 = '(' + str(var3) + ')'

    expression1 = '(' + str(var1) + ' ' + symbol1 + ' ' + str(var2) + ' ' + symbol2 + ' ' + str(var3) + ')'
    calc_ans1 = str(round(eval(expression1), 2))
    ans = None
    soln1 = None
    soln2 = None
    if symbol1 in '*/':
        ans = round(eval(str(var1) + ' ' + symbol1 + ' ' + str(var2)), 2)
        soln1 = str(var1) + ' ' + symbol1 + ' ' + str(var2)
    else:
        ans = round(eval(str(var2) + ' ' + symbol2 + ' ' + str(var3)), 2)
        soln2 = str(var2) + ' ' + symbol2 + ' ' + str(var3)

    solution1 = ''
    if soln2 == None:
        soln2 = symbol2 + ' ' + str(var3)
        solution1 = '(' + str(ans) + ' ' + soln2 + ')'
    else:
        soln1 =  str(var1) + ' ' + symbol1
        solution1 = '(' + soln1 + ' ' + str(ans) + ')'
    return expression1, solution1, calc_ans1

def generateExpressionBracket2():
    var3 = random.randint(1, 150)
    var4 = random.randint(-150, 150)
    var5 = random.randint(1, 150)
    expression1, solution1, calc_ans1 = generateExpressionBracket1()
    symbol1 = signs[random.randint(0,3)]
    symbol2 = signs[random.randint(0,3)]
    symbol3 = signs[random.randint(0,3)]

    if var4 < 0:
        var4 = '(' + str(var4) + ')'

    expression2 = '[' + expression1 + ' ' + symbol1 + ' ' + str(var3) + ' ' + symbol2 + ' ' + str(var4) + ']' + ' ' + symbol3 + ' ' + str(var5)
    eval_expression = '(' + expression1 + ' ' + symbol1 + ' ' + str(var3) + ' ' + symbol2 + ' ' + str(var4) + ')' + ' ' + symbol3 + ' ' + str(var5)
    calc_ans2 = round(eval(eval_expression), 2)
    ans = None
    soln1 = None
    soln2 = None

    inter_solution2 = '[' + solution1 + ' ' + symbol1 + ' ' + str(var3) + ' ' + symbol2 + ' ' + str(var4) + ']' + ' ' + symbol3 + ' ' + str(var5)
    inter_solution2_2 = '[' + calc_ans1 + ' ' + symbol1 + ' ' + str(var3) + ' ' + symbol2 + ' ' + str(var4) + ']' + ' ' + symbol3 + ' ' + str(var5)
    if symbol1 in '*/':
        ans = round(eval(str(calc_ans1) + ' ' + symbol1 + ' ' + str(var3)), 2)
        soln1 = symbol2 + ' ' + str(var4)
    elif symbol2 in '*/':
        ans = round(eval(str(var3) + ' ' + symbol2 + ' ' + str(var4)), 2)
        soln2 = str(calc_ans1) + ' ' + symbol1
    else:
        ans = round(eval(str(calc_ans1) + ' ' + symbol1 + ' ' + str(var3)), 2)
        soln1 = symbol2 + ' ' + str(var4)

    solution2 = ''
    if soln2 == None:
        soln2 = symbol2 + ' ' + str(var4)
        solution2 = '[' + str(ans) + ' ' + soln2 + ']' + ' ' + symbol3 + ' ' + str(var5)
        eval_exp = str(ans) + ' ' + soln2
    else:
        soln1 =  str(calc_ans1) + ' ' + symbol1
        solution2 = '[' + soln1 + ' ' + str(ans) + ']' + ' ' + symbol3 + ' ' + str(var5)
        eval_exp = soln1 + ' ' + str(ans)

    solution2_2 = str(round(eval(eval_exp), 2)) + ' ' + symbol3 + ' ' + str(var5)

    calc_ans2 = round(eval(solution2_2), 2)

    expression2 = expression2.replace('*', '\\times')
    inter_solution2 = inter_solution2.replace('*', '\\times')
    inter_solution2_2 = inter_solution2_2.replace('*', '\\times')
    solution2 = solution2.replace('*', '\\times')
    solution2_2 = solution2_2.replace('*', '\\times')

    return expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression

def solution(expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression, correctIndex, allOptions, wrong_Options):

    for i in range(0, 4):
        if i+1 != int(correctIndex):
            allOptions[i] = latex(allOptions[i])

    return f"= {latex(expression2)}
\n= {latex(inter_solution2)}
\n= {latex(inter_solution2_2)}
\n= {latex(solution2)}
\n= {latex(solution2_2)}
\n= {latex(calc_ans2)}
\nTherefore option {latex(correctIndex)} is right selection"

def question(expression2):
    return(f"Solve the given expression and round the decimal place up to 2 digits at each step\n{expression2}")

def options(calc_ans2, eval_expression):
    allOptions = []
    allOptions.append(calc_ans2)

    wrong_options_expression1 = eval_expression.replace('+', '*')
    allOptions.append(round(eval(wrong_options_expression1), 2) + random.randint(1, 4))

    wrong_options_expression2 = eval_expression.replace('/', '-')
    allOptions.append(round(eval(wrong_options_expression2), 2) + random.randint(1, 4))

    wrong_options_expression3 = eval_expression.replace('*', '/')
    allOptions.append(round(eval(wrong_options_expression3), 2) + random.randint(1, 4))

    wrong_options = []
    random.shuffle(allOptions)
    correctIndex = None
    wrong_options = []
    for i in range(1, 5):
        if allOptions[i-1] == calc_ans2:
            correctIndex = i
            latex(allOptions[i-1])
        else:
            wrong_options.append(latex(allOptions[i-1]))

    return correctIndex, allOptions, wrong_options

def changeValues():
    global expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression

    expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression = generateExpressionBracket2()

    correctIndex, allOptions, wrong_Options= options(calc_ans2, eval_expression)

    expression2 = expression2.replace('/', '\div')
    inter_solution2 = inter_solution2.replace('/', '\div')
    inter_solution2_2 = inter_solution2_2.replace('/', '\div')
    solution2 = solution2.replace('/', '\div')
    solution2_2 = solution2_2.replace('/', '\div')

    soln_print = solution(expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression, correctIndex, allOptions, wrong_Options)

    expression2 = latex(expression2)
    calc_ans2 = latex(calc_ans2)

    return expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression, correctIndex, allOptions, wrong_Options, soln_print

def main_function():
    expression2, inter_solution2, inter_solution2_2, solution2, solution2_2, calc_ans2, eval_expression, correctIndex, allOptions, wrong_Options, soln_print = changeValues()

    Question = question(expression2)
    Corr_op = calc_ans2
    wrong_op1, wrong_op2, wrong_op3 = wrong_Options
    Solution = soln_print

    database_dict= database_fn(
        Question_Type='text',
        Answer_Type='text',
        Topic_Number='030302',
        Variation='v1',
        Question=Question,
        Correct_Answer_1=Corr_op,
        Wrong_Answer_1=wrong_op1,
        Wrong_Answer_2=wrong_op2,
        Wrong_Answer_3=wrong_op3,
        ContributorMail = '2019yash.kumthekar@ves.ac.in',
        Solution_text=Solution
    )
    return database_dict

putInCsv(
    Topic_Number='030302',
    Number_Of_Iterations=5,
    Main_Function=main_function,
    Filename='v1_3.py',
    Create_Textfile=True,
    Remove_Duplicates=True
)


class Solution:
	def maxProduct(self,ar, n):
	    maxV=ar[0]
	    minV=ar[0]
	    maxP=ar[0]
	    for i in range(1,n):
	        if ar[i]<0:
	            maxV,minV=minV,maxV
	        minV=min(ar[i],ar[i]*minV)
	        maxV=max(ar[i],ar[i]*maxV)

	        maxP=max(maxP,maxV)
	    return maxP

s=Solution()
ar=[3,-6,-10,0,2]
ans=s.maxProduct(ar,len(ar))
print(ans)