import json
import logging
import socket

import survillo.components.servos.micro_servo_sg90 as sg90
import survillo.components.servos.micro_servo_ts90a as ts90a
import survillo.crane.controlled_servo as cs

_IP = '0.0.0.0'
_PORT = 10003
_HORIZONTAL_SERVO_PIN = 17
_VERTICAL_SERVO_PIN = 27

_logger = logging.getLogger(__name__)

class ServoServer:

    def __init__(self, horizontal_servo, vertical_servo):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
            _logger.debug('Server socket created')

            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_socket.bind((_IP, _PORT))
            server_socket.listen(1)

            while True:
                _logger.debug('Server socket waiting for incoming connections')

                client_socket, from_address = server_socket.accept()
                with client_socket:
                    _logger.debug('Connection established with {}'.format(from_address))

                    while True:
                        data = client_socket.recv(1024)

                        if not data:
                            break

                        shutdown = False

                        msg = data.decode('utf-8')
                        for split_msg in msg.strip().split():

                            if not split_msg:
                                _logger.warning('Empty string received from server')
                                continue

                            _logger.debug('Command from client: {}'.format(split_msg))

                            if split_msg == 'q':
                                # Shut down the servos.
                                horizontal_servo.set_position(None)
                                vertical_servo.set_position(None)
                                shutdown = True
                                break

                            try:
                                json_message = json.loads(split_msg)
                            except json.JSONDecodeError as err:
                                _logger.error('Could not json-decode: {}'.format(split_msg))
                                continue

                            position_x = float(json_message.get('px'))
                            position_y = float(json_message.get('py'))
                            if position_x is None or position_y is None:
                                _logger.warning('String does not match expected pattern: {}'.format(split_msg))
                                continue

                            # The horizontal servo is upside down.
                            horizontal_servo.set_position(normalized_position=-position_x)
                            vertical_servo.set_position(normalized_position=position_y)

                        if shutdown:
                            break

                    _logger.debug('Closing client socket')

def main():
    horizontal_servo = cs.ControlledServo(pin=_HORIZONTAL_SERVO_PIN,
                                          min_pulse_width_s=sg90.MIN_PULSE_WIDTH_s,
                                          max_pulse_width_s=sg90.MAX_PULSE_WIDTH_s,
                                          frame_width_s=sg90.FRAME_WIDTH_s,
                                          nominal_max_angle_deg=sg90.MAX_ANGLE_deg,
                                          range_deg=None,
                                          default_angle_deg=0.0)

    vertical_servo = cs.ControlledServo(pin=_VERTICAL_SERVO_PIN,
                                        min_pulse_width_s=ts90a.MIN_PULSE_WIDTH_s,
                                        max_pulse_width_s=ts90a.MAX_PULSE_WIDTH_s,
                                        frame_width_s=ts90a.FRAME_WIDTH_s,
                                        nominal_max_angle_deg=ts90a.MAX_ANGLE_deg,
                                        range_deg=[-90, -60],
                                        default_angle_deg=-90)

    ServoServer(horizontal_servo=horizontal_servo, vertical_servo=vertical_servo)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()


# -*- coding: utf-8 -*-
"""
    femagtools.asm
    ~~~~~~~~~~~~~~

    Reading ASM files

Slots Qr:

  Qr <= 1.25 Qs
  Qr != Qs +/- 2p
  Qr != Qs
  Qr != Qs +/- 1

"""
import pathlib
import logging
import logging.config
import numpy as np
import lmfit

logger = logging.getLogger('femagtools.asm')

def imcur(s, w1, u1, r1, ls1, lh, ls2, r2):
    """return currents i1r, i1i, i2r, i2i"""
    xs1 = w1*ls1
    xh = w1*lh
    x1 = xs1+xh
    xs2 = w1*ls2
    x2 = xs2+xh
    # solve voltage equations for steady state
    A = np.array((
        (r1, -x1, 0, -xh),
        (x1, r1, xh, 0),
        (0, -s*xh, r2, -s*x2),
        (s*xh, 0, s*x2, r2)))
    return np.linalg.solve(A, np.array((u1, 0, 0, 0)))

def torque(p, w1, u1, s, r1, ls1, lh, ls2, r2):
    """return torque"""
    if s == 0:
        return 0
    i2 = imcur(s, w1, u1, r1, ls1, lh, ls2, r2)[2:]
    return 3*p*r2/s/w1*(i2[0]**2 + i2[1]**2)

def fit_current(w1, u1, slip, r1, ls1, lh, i1, cosphi):
    def imcurr(s, ls2, r2):
        return np.array(
            [x + 1j*y
             for x, y in [imcur(sx, w1, u1, r1, ls1, lh, ls2, r2)[:2]
                          for sx in s]])
    model = lmfit.model.Model(imcurr)
    ls2_guess = 0.0
    r2_guess = np.mean(
        [u1/i1x*sx
         for i1x, sx in zip(i1, slip) if abs(i1x) > 1e-6])
    params = model.make_params(r2=r2_guess, ls2=ls2_guess)
    guess = lmfit.models.update_param_vals(params, model.prefix)
    i1c = np.array([x*pf - 1j*x*np.sqrt(1-pf**2)
                    for x, pf in zip(i1, cosphi)])
    r = model.fit(i1c, params=guess, s=slip, verbose=True)
    return r.params['ls2'].value, r.params['r2'].value

valmap = {
    'Stator windings voltage (RMS)[V]': 'u1',
    'Wdgs-connection: 0': 'wdgconn',
    'Nominal frequency': 'f1',
    'Stator phase winding resistamce': 'r1',
    'Stator phase winding resistance': 'r1',
    'Stator phase end-winding reactance': 'xs1',
    'Stator phase winding wires/slot side': 'num_wires',
    'Effect. air gap  length          [mm]': 'lfe',
    'Effect. rotor bar length (+end)  [mm]': 'rbarlen',
    'Number of Phases': 'num_phases',
    'Number of Pole pairs': 'p',
    'Number of Poles simulated': 'p_gen',
    'Number of parallel windings': 'num_par_wdgs',
    'Rotor Lamination                [kg]': 'lamweight',
    'Rotor Conductors                [kg]': 'conweight',
    'MC-File used in calculation': 'mcfile',
    'Losses[W/kg] in MC-File': 'felosscoeff',
    'Max. No. Iterations': 'maxiters',
    'Change of Perm. max %': 'permchg'}

def _read_sections(lines):
    """return list of ASM sections

    sections are either surrounded by lines starting with '[***'
    or by starting with any 'Input data' or 'Simulation Results'
    Args:
      param lines (list) lines of ASM file to read

    Returns:
      list of sections
    """

    section = []
    for line in lines:
        if ('[****' in line or
            'Input data' in line or
                'Simulation Results' in line):
            if section:
                # skip empty lines
                i = 0
                try:
                    while not section[i]:
                        i = i+1
                except IndexError:
                    i = i-1
                yield section[i:]
                section = []
        else:
            section.append(line.strip())
    yield section

def read_input_data(content):
    r = dict()
    for l in content:
        if '=' in l or ':' in l:
            d = '=' if '=' in l else ':'
            k, v = [s.strip() for s in l.split(d)[:2]]
            if k == 'Wdgs-connection: 0':
                c = int(float(l.split()[-1]))
                r[valmap[k]] = ['open', 'star', 'delta'][c]
            else:
                r[valmap[k]] = float(v)
        elif '\t' in l:
            k, v = [s.strip() for s in l.split('\t')[:2]]
            if valmap[k] == 'mcfile':
                r['mcfile'] = v
            else:
                r[valmap[k]] = float(v)

    for k in ('num_phases', 'p', 'p_gen',
              'num_par_wdgs', 'maxiters'):
        if k in r:
            r[k] = int(r[k])
    return r

def read_simulation_results(content):
    unit = 1e3
    resmap = {
        'Torque = P2/(s.omega) [Nm]': 'Tp2',
        'Rotor-Losses P2 [kW]': 'p2',
        'Rotor-Losses P2 [W]': 'p2',
        'Stator FE  Pfe1 [kW]': 'pfe1',
        'Stator FE  Pfe1 [W]': 'pfe1'}
    r = dict(s=[], T=[], u1=[], i1=[], p1=[], cosphi=[],
             f1=[], pfe1=[], p2=[], Tp2=[])
    for l in content:
        if l.startswith('S LIP'):
            if l.find('POWER[W]') > -1:
                unit = 1
                continue
        a = l.split()
        if len(a) == 7:
            for k, v in zip(r.keys(), a):
                r[k].append(float(v))
        elif a:
            a = l.split(':')[-1].split()
            if len(a) == 1:
                try:
                    k = resmap[l.split(':')[0]]
                    r[k].append(float(a[0]))
                except KeyError:
                    logger.warning('Key %s ignored', l.split(':')[0])
    if unit > 1:
        for k in ('p1', 'p2', 'pfe1'):
            r[k] = [x*unit for x in r[k]]
    r['s'] = [s/100 for s in r['s']]
    return r

def parident(w1, u1, i1, cosphi, s, r1, ls1, lh):
    """returns equivalent circuit parameters: r2, ls"""
    logger.info("w1 %s u1 %s i1 %s cosphi %s s %s r1 %s ls1 %s lh %s",
                w1, u1, i1, cosphi, s, r1, ls1, lh)
    ls2, r2 = fit_current(w1, u1, s,
                          r1, ls1, lh, i1, cosphi)

    xi = w1*(ls1+lh - lh**2/(ls2+lh))
    return dict(r2=r2, ls2=ls2, sk=r2/np.sqrt(xi**2 + r1**2))

def read(arg):
    """read asm file

        Args:
          filename or content (list of str) the text lines of the ASM file
    """
    r = {}
    if isinstance(arg, str):
        lines = pathlib.Path(arg).read_text().split('\n')
    elif isinstance(arg, pathlib.Path):
        lines = arg.read_text().split('\n')
    else:
        lines = arg
    for s in _read_sections(lines):
        if not s:
            continue
        title = s[0].split(':')[0].strip()

        if 'FEMAG Classic Version' in title:
            r['version'] = s[0].split(':')[-1].replace(' Version ', '').strip()
        elif 'Project File name' in title:
            r['project'] = s[1].strip()
        elif 'Number of Nodes' in title:
            pass
        elif 'File name' in title:
            r['filename'] = s[0].split(':')[-1].strip()
        elif 'Date' in title:
            d = s[0].split(':')[1].strip().split()
            dd, MM, yy = d[0].split('.')
            hh, mm = ''.join(d[1:-1]).split('.')
            r['date'] = '{}-{}-{}T{:02}:{:02}'.format(
                yy, MM, dd, int(hh), int(mm))
        elif 'Stator windings' in title:
            r.update(read_input_data(s))
        else:
            r.update(read_simulation_results(s))
    r['pcu'] = [3*x**2*r['r1'] for x in r['i1']]
    if r['pfe1']:
        r['pltotal'] = [sum(x) for x in zip(r['pcu'], r['pfe1'], r['p2'])]
    else:
        r['pltotal'] = [sum(x) for x in zip(r['pcu'], r['p2'])]

    w1 = 2*np.pi*r['f1'][0]
    r['ls1'] = r.pop('xs1')/w1
    u1 = r['u1'][0]
    i1 = r['i1']
    cosphi = r['cosphi']
    if r['wdgconn'] == 'star':
        u1 = u1/np.sqrt(3)
    if r['wdgconn'] == 'delta':
        i1 = [x/np.sqrt(3) for x in i1]

    r['lh'] = u1/i1[0]/w1 - r['ls1']
    if len(i1) > 2:
        r.update(parident(w1, u1, i1, cosphi,
                          r['s'], r['r1'], r['ls1'], r['lh']))
    return r

if __name__ == "__main__":
    import sys
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(message)s')
    r = read(sys.argv[1])
    print(r)


from StringIO import StringIO
import unittest

import fooxml

class SaxHandlerTest(unittest.TestCase):

    def test_parse(self):
        """ Testing the routes """

        objs = []

        def callback(obj):
            objs.append(obj)

        handler = fooxml.SaxHandler("AttributeLink", callback=callback)
        xml_file = fooxml.xml_file("../samples/SampleAttributeLink.xml", handler)
        xml_file.parse()

        assert len(objs) > 1
        assert type(objs[0]) == dict
        assert objs[0]['AttributeLinkID'] == 'ML0000001057'
        assert objs[0]['ObjectID'] == 'MN0000833164'
        assert objs[0]['PropertyAttributeID'] == 'MA0000000239'
        assert objs[0]['ValueAttributeID'] == '            '
        assert objs[0]['Value'] == 'JoVonn'
        assert objs[0]['Weight'] == '5'
        assert objs[0]['Rank'] == '0'
        assert objs[0]['SortOrder'] == '2'
        assert objs[0]['p_BaseObjectID'] == 'MN0000833164'
        assert objs[0]['Action'] == 'A'

    def test_parse_ampersand(self):
        """
        Test parsing of ampersand characters
        """
        # From http://www.w3schools.com/xml/simple.xml
        xml_fragment = """<?xml version="1.0" encoding="ISO-8859-1"?>
        <!-- Edited by XMLSpy? -->
        <breakfast_menu>
            <food>
                <name>Belgian Waffles & Beer</name>
                <price>$5.95</price>
                <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
                <calories>650</calories>
            </food>
            <food>
                <name>Strawberry Belgian Waffles</name>
                <price>$7.95</price>
                <description>light Belgian waffles covered with strawberries and whipped cream</description>
                <calories>900</calories>
            </food>
        </breakfast_menu>
        """
        stream = StringIO(xml_fragment)
        stream.seek(0)

        objs = []
        def callback(obj):
            objs.append(obj)

        handler = fooxml.SaxHandler("food", callback=callback)
        xml_file = fooxml.xml_file(stream, handler)
        xml_file.parse()

        assert len(objs) > 1
        assert type(objs[0]) == dict
        assert objs[0]['name'] == 'Belgian Waffles & Beer'


import pymongo
import re
from datetime import date, timedelta
# ------------------------------------------
from ToolPack import tools
from KeyGraph_Approach import common_phrases

def split_sentences(doc):
    p_sent_tokenizer = tools.load_pickle("/home/iraklis/PycharmProjects/AllTheNews/Pivot_Files/"
                                         "Classifiers/PunktSentenceTokenizer.pickle")
    sentences = p_sent_tokenizer.sentences_from_text(doc)
    return sentences

# Clean your documents with this method before searching for the noun phrases
def document_cleaning(doc_sentences):
    stop_words = common_phrases.PhraseDetection.load_stopwords()
    documents = list()
    doc_range = list()
    index = 0
    doc_number = 0

    for line in doc_sentences:
        # line_to_lowercase = line.lower()
        clean_line = re.sub('[^A-Za-z0-9]+', ' ', line)     # line_to_lowercase
        documents.append(clean_line)
        index += 1
        doc_range.append(index)
        doc_number += 1

    documents = [doc.strip() for doc in documents]
    clean_documents = list()

    for doc in documents:
        clean_documents.append(' '.join([word for word in doc.split() if word not in stop_words]))

    documents = clean_documents[:]

    return documents

def gather_documents(c_week):
    # Getting data from the mongo database
    client = pymongo.MongoClient()
    # Database name is minedNews
    db = client.all_the_news

    path = "/home/iraklis/PycharmProjects/AllTheNews/KeyGraph_Approach/Week_docs_sentences/"
    week_clean_sents = list()
    with open(path + c_week + '_ids.txt', 'w') as week_file:

        for document in db[c_week].find({}, no_cursor_timeout=True):
            line_sentences = split_sentences(document["text"])
            for sent in line_sentences:
                week_file.write(sent + "\n")
            clean_sent = document_cleaning(line_sentences)
            week_clean_sents.append(clean_sent)
    tools.save_pickle(path + c_week + "sents_of_doc.pickle", week_clean_sents)

def gather_documents_per_day():
    # Getting data from the mongo database
    client = pymongo.MongoClient()
    # Database name is minedNews
    db = client.all_the_news

    path = "/home/iraklis/PycharmProjects/AllTheNews/KeyGraph_Approach/Day_doc_sentences/"
    start_day = date(2016, 1, 4)
    stop_day = date(2017, 1, 1)
    c_day = start_day
    c_week = str(start_day.isocalendar()[0]) + "-" + str(start_day.isocalendar()[1])

    while c_day < stop_day:
        day_clean_sents = list()
        current_date = str(c_day.year) + "-" + str(c_day.month) + "-" + str(c_day.day)
        print(current_date)
        with open(path + current_date + '_ids.txt', 'w') as week_file:
            for document in db[c_week].find({"date": current_date}, no_cursor_timeout=True):
                line_sentences = split_sentences(document["text"])
                for sent in line_sentences:
                    week_file.write(sent + "\n")
                clean_sent = document_cleaning(line_sentences)
                if clean_sent:
                    day_clean_sents.append(clean_sent)
                else:
                    print("Got one on:", current_date, " ", c_week)
                    print(document["_id"])
        c_day += timedelta(1)
        c_week = str(c_day.isocalendar()[0]) + "-" + str(c_day.isocalendar()[1])
        tools.save_pickle(path + current_date + "_sents_of_doc.pickle", day_clean_sents)

if __name__ == "__main__":
    # gather_documents_per_day()
    a = tools.load_pickle("/home/iraklis/PycharmProjects/AllTheNews/KeyGraph_Approach/"
                          "Day_doc_sentences/2016-1-4_sents_of_doc.pickle")
    print()


import math

# convert num to binary sequence
def convert_binary(num):
	bit_seq = []
	while num>0:
		bit_seq.append(num%2)
		num = num//2
	return bit_seq[::-1]
num = 14
print(convert_binary(num))

def add(num1, num2):
	"""
	:type num1: str
	:type num2: str
	:rtype: str
	"""
	if len(num1) > len(num2):
		return multiply(num2, num1)

	result = ''
	carry = 0
	itr1 = len(num1)-1
	itr2 = len(num2)-1
	while itr1>=0 or itr2>=0:
		digit1 = int(num1[itr1]) if itr1>=0 else 0
		digit2 = int(num2[itr2])
		total = digit1 + digit2 + carry
		carry = int(total/10)
		result = str(total%10) + result
		itr1 -= 1
		itr2 -= 1
	return result if carry==0 else str(carry) + result

num1 = '123'
num2 = '456'
print(add(num1, num2))

# with num1, num2 being string, magnitude can exceed integer
def multiply(num1, num2):
	"""
	num1,num2: str
	ret: str
	"""

# long division:
# if curr prefix of de is less than numerator, keep padding 0's
# else
# find denominator/numerator, get remainder
# terminate condition: see some remainder again
# use a set to check if a remainder showed up before
# def fraction2decimal(numerator, denominator):
	#"""
	#numerator: int
	#denominator: int
	#return: string 2/3 = 0.(6)
	#"""
	# remainder = numerator
	# rept = set()
	# result = ''
	# while remainder not in rept:
	# 	if remainder < numerator:
	# 		result += '0'
	# 		denominator *= 10
	# 	else:
	# 		multiple = int(denominator / remainder)
	# 		remainder = denominator - multiple
	# 		result += str(multiple)
	# 		if remainder is 0:
	# 			return '0.' + result[1:]

	# remainder in rept, get the repeating part

# newton's method, find solution of x^2=num
# def sqrt(num):

def addOne(self, bitmap, count_one):
    carry = 1
    reversed_bitmap = bitmap[::-1]
    for ind,bit in enumerate(reversed_bitmap):
        if bit==0:
            reversed_bitmap[ind] = 1
            return reversed_bitmap[::-1], count_one+1
        else:
            if carry==1:
                reversed_bitmap[ind] = 0
                count_one -= 1
    if carry==1:
        count_one += 1
        reversed_bitmap.append(1)
    return reversed_bitmap[::-1], count_one

# lc 338
def countBits(self, num):
    """
    :type num: int
    :rtype: List[int]
    """
    bitmap = [0]
    count_one = 0
    result = [0]
    if num==0:
        return result
    else:
        for i in list(range(num+1))[1:]:
            bitmap, count_one = self.addOne(bitmap, count_one)
            result.append(count_one)
    return result

# breakup to prime numbers: 分解质因数
# def


import numpy as np
from shapely.ops import transform
import os
from tempfile import NamedTemporaryFile
from shapely.geometry import shape, box
from pyveda.utils import from_bounds
import numpy as np
from skimage.draw import polygon
from skimage.io import imread

class NDImageHandler(object):
    _default_dtype = np.float32

    @staticmethod
    def _payload_handler(*args, **kwargs):
        return NDImageHandler._bytes_to_array(*args, **kwargs)

    @staticmethod
    def _on_fail(shape=(3, 256, 256), dtype=np.uint8):
        return np.zeros(shape, dtype=dtype)

    @staticmethod
    def _bytes_to_array(bstring):
        if bstring is None:
            return on_fail()
        try:
            fd = NamedTemporaryFile(prefix='veda', suffix='.tif', delete=False)
            fd.file.write(bstring)
            fd.file.flush()
            fd.close()
            arr = imread(fd.name)
            if len(arr.shape) == 3:
                arr = np.rollaxis(arr, 2, 0)
            else:
                arr = np.expand_dims(arr, axis=0)
        except Exception as e:
            arr = NDImageHandler._on_fail()
        finally:
            fd.close()
            os.remove(fd.name)
        return arr

class BaseLabelHandler(object):
    @staticmethod
    def _get_transform(bounds, height, width):
        return from_bounds(*bounds, width, height)

    @staticmethod
    def _parse_response(res):
        return res['properties']['label']

    @staticmethod
    def _payload_handler(*args, **kwargs):
        raise NotImplementedError

class ClassificationHandler(BaseLabelHandler):
    _default_dtype = np.uint8

    @staticmethod
    def _payload_handler(item, klasses=[], **kwargs):
        payload = ClassificationHandler._parse_response(item)
        return [payload[klass] for klass in klasses]

class SegmentationHandler(BaseLabelHandler):
    _default_dtype = np.float32

    @staticmethod
    def _payload_handler(*args, **kwargs):
        return SegmentationHandler._handle_pixel_payload(*args, **kwargs)

    @staticmethod
    def _handle_pixel_payload(item, klasses=[], out_shape=None, **kwargs):
        payload = SegmentationHandler._parse_response(item)
        if len(out_shape) == 3:
            out_shape = out_shape[-2:]
        out_array = np.zeros(out_shape)
        value = 1
        for klass in klasses:
            shapes = payload[klass]
            try:
                out_array += rasterize(((shape(g), value) for g in shapes), out_shape=out_shape)
            except Exception as e:
                pass
        return out_array

    @staticmethod
    def _handle_geo_payload(item, imshape):
        out_shape = imshape
        if len(imshape) == 3:
            out_shape = imshape[-2:]
        out_array = np.zeros(out_shape)
        value = 1
        for k, features in item['data']['label'].items():
            try:
                out_array += SegmentationHandler._create_mask(features, value, out_shape)
                value += 1
            except Exception as e: # I think this is ValueError from rasterio but need check
                pass
        return out_array

    @staticmethod
    def _create_mask(shapes, value, _shape):
        mask = np.zeros(_shape, dtype=np.uint8)
        for f in shapes:
            coords = f['coordinates'][0]
            r, c = zip(*[(x,y) for x,y in coords])
            rr, cc = polygon(np.array(r), np.array(c))
            mask[rr, cc] = value

class ObjDetectionHandler(BaseLabelHandler):
    _default_dtype = np.float32

    @staticmethod
    def _payload_handler(*args, **kwargs):
        return ObjDetectionHandler._handle_pixel_payload(*args, **kwargs)

    @staticmethod
    def _handle_pixel_payload(item, klasses=[], out_shape=None, **kwargs):
        payload = ObjDetectionHandler._parse_response(item)
        return [payload[klass] for klass in klasses]

    @staticmethod
    def _handle_geo_payload(item, imshape):
        out_shape = imshape
        if len(imshape) == 3:
            out_shape = imshape[-2:]
        xfm = BaseLabelHandler._get_transform(item['data']['bounds'], *out_shape)
        labels = []
        for k, features in item['data']['label'].items():
            class_labels = []
            for i, f in enumerate(features):
                b = shape(f).bounds
                ll, ur = ~xfm * (b[0],b[1]), ~xfm * (b[2],b[3])
                class_labels.append([*ll, *ur])
            labels.append(class_labels)
        return labels


# Chapter-3: Arrays
# Array-Push-Front
# Given an array and an additional value, insert this value at the beginning of the array. Do this without using any built-in array methods

# Built-in array method that can be used for this is "insert" - array.insert(index, val)

# Assuming that the arguments passed are an array and a single additional value
def pushFront(arr, val):
    # This is to set up an array with empty elements having length 1 more than the original
    result = ['' for i in range(0, len(arr)+1)]

    result[0] = val

    for i in range(0, len(arr)):
        result[i+1] = arr[i]

    return result

myArr = [1,2,3,4]
myVal = "First"
print("The original array is {}").format(myArr)
myArr = pushFront(myArr, myVal)
print("The changed array is {}").format(myArr)

# The approach manipulating the array length is not possible in python


import json
import os
import sys
from string import Template

import sublime

from .lib import plistlib

sublime_settings = "Preferences.sublime-settings"
scope_name = "colored.comments.color."
MSG = Template(
    """
Would you like to change your color scheme to '$scheme'?
To permanently disable this prompt, set 'prompt_new_color_scheme'
to false in the Colored Comments settings."""
)

sublime_default_cs = [
    "Mariana.sublime-color-scheme",
    "Celeste.sublime-color-scheme",
    "Monokai.sublime-color-scheme",
    "Breakers.sublime-color-schem",
    "Sixteen.sublime-color-scheme",
]

class ColorManager:
    def __init__(self, new_color_scheme_path, tags, view, settings, regenerate, log):
        self.new_color_scheme_path = new_color_scheme_path
        self.view = view
        self.sublime_pref = None
        self.tags = tags
        self.settings = settings
        self.regenerate = regenerate
        self.log = log
        self.color_scheme = str()
        self.update_preferences = True
        self.awaiting_feedback = False

    def get_update_pref(self):
        return self.update_preferences

    def get_awaiting_feedback(self):
        return self.awaiting_feedback

    def set_awaiting_feedback(self, status):
        self.awaiting_feedback = status

    def _add_colors_to_scheme(self, color_scheme, is_json):
        scheme_rule_key = "rules" if is_json else "settings"
        settings = color_scheme[scheme_rule_key]
        scope_exist = bool()
        updates = bool()

        for tag in self.tags:
            curr_tag = self.tags[tag]
            if not curr_tag.get("color", False):
                continue

            name = _get_color_property("name", curr_tag)
            background = _get_color_property("background", curr_tag)
            foreground = _get_color_property("foreground", curr_tag)
            if False in [name, background, foreground]:
                continue

            scope = "{}{}".format(scope_name, name.lower().replace(" ", "."))

            for setting in settings:
                if "scope" in setting and setting["scope"] == scope:
                    scope_exist = True

            if not scope_exist:
                updates = True
                entry = dict()
                entry["name"] = "[Colored Comments] {}".format(name.title())
                entry["scope"] = scope
                if is_json:
                    entry["foreground"] = foreground
                    entry["background"] = background
                else:
                    entry["settings"] = dict()
                    entry["settings"]["foreground"] = foreground
                    entry["settings"]["background"] = background

                settings.append(entry)
        color_scheme[scheme_rule_key] = settings
        return updates, color_scheme

    def _create_custom_color_scheme_directory(self):
        path = os.path.join(sublime.packages_path(), self.new_color_scheme_path)
        if not os.path.exists(path):
            os.makedirs(path)
        return path

    def create_user_custom_theme(self):
        if self.awaiting_feedback:
            return
        self.awaiting_feedback = True
        if not self.tags:
            self.awaiting_feedback = False
            return

        self.sublime_pref = sublime.load_settings(sublime_settings)
        color_scheme = self.sublime_pref.get("color_scheme")
        if self.regenerate and self.settings.get("old_color_scheme", "") != "":
            color_scheme = self.settings.get("old_color_scheme", "")

        self.settings.set("old_color_scheme", color_scheme)
        sublime.save_settings("colored_comments.sublime-settings")
        cs_base = os.path.basename(color_scheme)

        if cs_base[0:16] != "Colored Comments":
            cs_base = "{}{}".format("Colored Comments-", cs_base)

        custom_color_base = self._create_custom_color_scheme_directory()
        new_cs_absolute = os.path.join(custom_color_base, cs_base)
        self.color_scheme = "{}{}{}{}".format(
            "Packages/", self.new_color_scheme_path, "/", cs_base
        )
        print(self.color_scheme)

        updates, loaded_scheme, is_json = self.load_color_scheme(color_scheme)

        if self.regenerate or updates or color_scheme != self.color_scheme:
            try:
                os.remove(new_cs_absolute)
            except OSError as ex:
                self.log.debug(str(ex))
                pass
            if is_json:
                with open(new_cs_absolute, "w") as outfile:
                    json.dump(loaded_scheme, outfile, indent=4)
            else:
                with open(new_cs_absolute, "wb") as outfile:
                    outfile.write(plistlib.dumps(loaded_scheme))

        if color_scheme != self.color_scheme:
            if sublime.ok_cancel_dialog(
                MSG.substitute(scheme=self.color_scheme), "Confirm"
            ):
                self.sublime_pref.set("color_scheme", self.color_scheme)
                sublime.save_settings("Preferences.sublime-settings")
                self.settings.set("prompt_new_color_scheme", False)
                sublime.save_settings("colored_comments.sublime-settings")
            self.update_preferences = False
            self.awaiting_feedback = False

    def load_color_scheme(self, scheme):
        is_json = bool()
        try:
            if scheme in sublime_default_cs:
                scheme = "{}{}".format("Packages/Color Scheme - Default/", scheme)
            scheme_content = sublime.load_binary_resource(scheme)
        except Exception as ex:
            sublime.error_message(
                " ".join(
                    [
                        "An error occured while reading color",
                        "scheme file. Please check the console",
                        "for details.",
                    ]
                )
            )
            self.log.debug(
                "[Colored Comments]: {} - {}".format(
                    self.load_color_scheme.__name__, ex
                )
            )
            raise
        if scheme.endswith(".sublime-color-scheme"):
            is_json = True
            updates, color_scheme = self._add_colors_to_scheme(
                sublime.decode_value(scheme_content.decode("utf-8")), is_json
            )
        elif scheme.endswith(".tmTheme"):
            updates, color_scheme = self._add_colors_to_scheme(
                plistlib.loads(bytes(scheme_content)), is_json
            )
        else:
            sys.exit(1)
        return updates, color_scheme, is_json

def _get_color_property(property, tags):
    if not tags["color"].get(property, False):
        return False
    return tags["color"][property]


def berekening(n):
    y = 0
    x = 1
    teller = 1
    while teller <= n:
            teller += 1
            y += (-1) ** teller*1/x
            x += 2
    return float(y * 4)

n = float(input("Geef hier het aantal stappen"))
print(berekening(n))


import bezier
import numpy as np
import appendTools
import scalingSkeleton as ss
import math
import makeStandardCircle as mc
import derivativeTools
import makeTriangle as mt

class InputError(Exception):
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

def getPoint(points, pIndex, offset=1):
    return points[(pIndex + offset) % len(points)]

def getBezierCurve(points, pIndex):
    p = [getPoint(points, pIndex, i) for i in range(4)]
    nodes = np.asfortranarray([
        list(map(float, [p[i].x for i in range(4)])),
        list(map(float, [p[i].y for i in range(4)])),
        ])
    return bezier.Curve(nodes, degree=3)

def appendPointByRate(contour, points, rate):
    if points[0].type == points[1].type == 'line':
        appendTools.appendPointRateLine(contour, points[:2], rate)
        return False
    else:
        appendTools.appendPointRate(contour, points, rate)
        return True

def getEdgeSegment(contour):
    edges = {}
    for i in range(len(contour.segments)):
        if contour.segments[i].type == 'line':
            edges[i] = contour.segments[i]
        else:
            nextSegment = contour.segments[(i+1) % len(contour.segments)]
            if nextSegment.type == 'line':
                edges[i] = contour.segments[i]
            # For kiyuk Only...
            elif nextSegment.type == 'curve':
                idx = contour.segments[i].onCurve.index
                if getDegree(contour.points[idx-1], contour.points[idx+1], contour.segments[i].onCurve) >= 10:
                    edges[i] = contour.segments[i]
    return edges

def segToPointIndex(contour, segIndex):
    p = [p for p in contour.segments[segIndex].points if p.type != 'offcurve'][0]
    return contour.points.index(p)

def findNextPoint(points, pIndex, cnt=1):
    for i in range(cnt):
        pIndex += 1
        while points[pIndex].type == 'offcurve':
            pIndex  = (pIndex+1) % len(points)
    return pIndex

def getPointRates(points, start, length):
    conlen = 0
    rates = []
    rates.append(getBezierCurve(points, start).length / length)
    conlen += rates[-1] * length
    while length > conlen:
        start = findNextPoint(points, start)
        rates.append(getBezierCurve(points, start).length / length)
        conlen += rates[-1] * length
    return rates

def applySkeletonAfterDelete(origin, os, oe, skel, ss, se):
    if os > oe:
        oe += len(origin.points)
    if ss > se:
        se += len(skel.points)
    control = 0
    # remove = [origin.points[i] for i in range(os+1, oe) if origin.points[i].type != 'offcurve']
    # while remove:
    #     p = remove.pop()
    #     origin.removeSegment(pToSeg(origin, p), True)
    #     control -= 1
    skelRate = [getBezierCurve(skel.points, i % len(skel.points)).length for i in range(ss, se) if skel.points[i].type != 'offcurve']
    skelLen = sum(skelRate)
    skelRate = list(map(lambda x: x / skelLen, skelRate))
    cnt = 0
    newRate = 0
    for i in range(len(skelRate)-1):
        if cnt:
            newRate = ((skelLen*skelRate[i]) - (skelLen*skelRate[i-1])) / (skelLen - (skelLen*skelRate[i-1]))
        else:
            newRate = skelRate[i]
        appendPointByRate(origin, [origin.points[(findNextPoint(origin.points, os, cnt)+k) % len(origin.points)] for k in range(4)], newRate)
        control += 1
        cnt += 1
        derivativeTools.appendPointByDerivative(origin.points, (os+(cnt*3)) % len(origin.points), origin)
        cnt += 1
        control += 1
    return control

def applySkeleton(origin, os, oe, skel, ss, se):
    if os > oe:
        oe += len(origin.points)
    if ss > se:
        se += len(skel.points)
    temp = 0
    cnt = 0
    comlen = 0
    remove = [origin.points[i] for i in range(os+1, oe) if origin.points[i].type != 'offcurve']
    curIndex = os
    skelRate = [getBezierCurve(skel.points, i % len(skel.points)).length for i in range(ss, se) if skel.points[i].type != 'offcurve']
    skelLen = sum(skelRate)
    skelRate = list(map(lambda x: x / skelLen, skelRate))
    originRate = [getBezierCurve(origin.points, i % len(origin.points)).length for i in range(os, oe) if origin.points[i].type != 'offcurve']
    originLen = sum(originRate)
    originRate = list(map(lambda x: x / originLen, originRate))
    for j in range(len(skelRate)-1):
        curlen = sum(skelRate[:j+1]) * originLen
        while curlen > comlen:
            cnt += 1
            if cnt > 1:
                temp = comlen
            comlen = sum(originRate[:curIndex-os+cnt]) * originLen
        appendPointByRate(origin, [origin.points[(findNextPoint(origin.points, curIndex, cnt-1)+k) % len(origin.points)] for k in range(4)], (curlen-temp) / (comlen-temp))
        originRate = getPointRates(origin.points, os, originLen)
        cnt = 0
        comlen = 0
    while remove:
        p = remove.pop()
        origin.removeSegment(pToSeg(origin, p), True)
        # p.selected = True
        # origin.getParent().removeSelection()

def getRemovePoints(start, end, contour):
    removes = [contour.points[i] for i in range(start+1, end) if contour.points[i].type != 'offcurve']
    return removes

def length(a, b):
    return math.sqrt(pow(a[0]-b[0], 2) + pow(a[1]-b[1], 2))

def getDegree(a, b, center):
    t1 = b.x - center.x
    t2 = a.x - center.x
    if not t1:
        t1 += 1
    if not t2:
        t2 += 1
    return abs(math.degrees(math.atan((b.y-center.y)/t1)-math.atan((a.y-center.y)/t2)))

def getPointAngle(points, pIndex):
    cnt1, cnt2 = -1, 1
    while True:
        p = getPoint(points, pIndex, cnt1)
        if p.type == 'offcurve':
            cnt1 -= 1
        else:
            break
    while True:
        p = getPoint(points, pIndex, cnt2)
        if p.type == 'offcurve':
            cnt2 += 1
        else:
            break
    return getDegree(getPoint(points, pIndex, cnt1), getPoint(points, pIndex, cnt2), points[pIndex])

def getFlattestSegment(contour, segIndexes):
    dic = {}
    for i in segIndexes:
        dic[i] = getPointAngle(contour.points, segToPointIndex(contour, i))
    return [k for k, v in dic.items() if min(dic.values()) == v][0]

def getFlatSegment(contour, segIndexes):
    result = []
    for i in segIndexes:
        if getPointAngle(contour.points, segToPointIndex(contour, i)) < 5:
            result.append(i)
    return result

def getRealPoint(segment):
    for p in segment.points:
        if p.type != 'offcurve':
            return p

def pToSeg(contour, point):
    for i in range(len(contour.segments)):
        if point in contour.segments[i].points:
            return contour.segments[i].index

def contourInside(baseContour, subjectContour):
    points = [p.anchor for p in subjectContour.bPoints]
    for p in points:
        if not baseContour.pointInside(p):
            return False
    return True

def setStart(contour):
    p = []
    for s in contour.segments:
        p.append(getRealPoint(s))
    p = list(filter(lambda x: x.y == max(map(lambda y: y.y, p)), p))
    p = list(filter(lambda x: x.x == min(map(lambda y: y.x, p)), p))
    if contour.points[0] != p[0]:
        contour.setStartSegment(pToSeg(contour, p[0])+1)

def setPenPairToOrder(name, padding):
    if padding == 0:
        return name
    temp = ["'penPair':'", "'dependX':'", "'dependY':'"]
    for t in temp:
        if t not in name:
            continue
        index = name.find(t) + len(t)
        penPair = name[index:name.find("'", index)]
        newPenPair = penPair[0] + str(int(penPair[1:-1]) + padding) + penPair[-1]
        name = name.replace(t + penPair, t + newPenPair)
    return name

def applyAttribute(target, skel, padding):
    for i in range(len(skel.segments)):
        sp = skel.points[segToPointIndex(skel, i)]
        tp = target.points[segToPointIndex(target, i)]
        if sp.type != 'offcurve' and tp.type != 'offcurve':
            tp.name = setPenPairToOrder(sp.name, padding)

def applyAttributeSegment(target, targetSegIndex, skel, skelSegIndex, padding):
    for i, j in zip(targetSegIndex, skelSegIndex):
        target.points[segToPointIndex(target, i)].name = setPenPairToOrder(skel.points[segToPointIndex(skel, j)].name, padding)

def applyAttributeAll(ori, skel):
    for o, s in zip(ori.points, skel.points):
        o.name = s.name

def preprocess(contour):
    if not contour._get_clockwise():
        contour.reverse()
    for c in contour.getParent().contours:
        if contour == c:
            continue
        if contourInside(c, contour):
            contour.reverse()
            break
    setStart(contour)

def calculateMiddlePoints(edgeSegmentKeys, length):
    count = 0
    for i in range(len(edgeSegmentKeys)):
        diff = (edgeSegmentKeys[i] - edgeSegmentKeys[i-1]) % length
        if diff > 1:
            count += diff - 1
    return count

def isAllLine(contour):
    for p in contour.points:
        if p.type != 'line':
            return False
    return True

def getPenPair(point):
    try:
        idx = point.name.find("'penPair':")
        if point.name[idx+14].isalpha():
            return point.name[idx+11:idx+15]
        else:
            return point.name[idx+11:idx+14]
    except AttributeError:
        raise InputError(point.getParent().getParent().name + ".glif: contours[" + point.getParent().index + "].points[" + point.index + "]", "It has no penPair attribute")

def getMaxPenPair(contour):
    maxPenPair = 0
    for p in contour.points:
        if p.name is None:
            continue
        maxPenPair = max(maxPenPair, int(getPenPair(p)[1:-1]))
    return maxPenPair

if __name__ == '__main__':
    f = CurrentFont()
    sf = OpenFont("/Users/font/Desktop/WorkSpace_SJ/Projects/CharacterSkeleton/YOON740_skeletons.ufo", False)
    skel = sf.getGlyph('k').contours[0]
    skelEdge = getEdgeSegment(skel)

    # # skel changer
    # skel1 = sf.getGlyph('b').contours[0]
    # skelEdge1 = getEdgeSegment(skel1)
    # skel2 = sf.getGlyph('b').contours[1]
    # skelEdge2 = getEdgeSegment(skel2)
    # skel3 = sf.getGlyph('b').contours[1]
    # skelEdge3 = getEdgeSegment(skel3)
    # skel4 = sf.getGlyph('b').contours[1]
    # skelEdge4 = getEdgeSegment(skel4)
    # skel5 = sf.glyphs[28].contours[0]
    # skelEdge5 = getEdgeSegment(skel5)
    # # skel changer end
    cnt = 0
    setting = False
    for o in f.glyphOrder:
        g = f.getGlyph(o)
        # if int(g.name[3:], 16) >= 0xC544 and int(g.name[3:], 16) <= 0xC78E:

        if g.name == '110f_05':
            setting = True
        if cnt == 1:
            setting = False
        if setting and cnt < 1:
            cnt += 1
            print(g.name)

            # ㅇ일 때
            # mc.makeStandardCircle(*mc.classifyInOutCircle(g[0], g[1]))
            # continue

            # 시옷, 쌍시옷, 지읒, 쌍지읒, 치읒일 때
            # if len(g.contours[0].points) == len(skel1.points):
            #     skel = skel1
            #     skelEdge = skelEdge1
            # elif len(g.contours[0].points) == len(skel2.points):
            #     skel = skel2
            #     skelEdge = skelEdge2
            # if 'g' in skel.getParent().name:
            #     # mt.findAndMake(g)
            #     preprocess(g.contours[0])
            #     applyAttributeAll(g.contours[0], skel)
            #     continue
            # skelSet = 0        # skel changer
            # ss.scaleToTarget(g.contours[0], g.contours[1])     # set skel size to origin
            padding = 0
            for ori in g.contours:
                # # skel changer
                # if skelSet == 0 or skelSet == 1:
                #     skel = skel1
                #     skelEdge = skelEdge1
                # elif skelSet == 2 or skelSet == 3:
                #     if skelSet == 3:
                #         padding = getMaxPenPair(g.contours[0])
                #     else:
                #         padding = 0
                #     skel = skel2
                #     skelEdge = skelEdge2
                # elif skelSet == 2:
                #     padding = 0
                #     skel = skel3
                #     skelEdge = skelEdge3
                # elif skelSet == 3:
                #     padding = 6
                #     skel = skel4
                #     skelEdge = skelEdge4
                # elif skelSet == 4:
                #     skel = skel5
                #     skelEdge = skelEdge5
                # skelSet += 1
                # # skel changer end

                # # To apply all of attribute in skeleton
            # if isAllLine(ori):
                #     oriEdge = getEdgeSegment(ori)
                #     applyAttributeSegment(ori, list(oriEdge.keys()), skel, list(skelEdge.keys()), padding)
                #     # padding += int(len(ori._get_bPoints()) / 2)
                #     continue
                # else:
                #     applyAttributeAll(ori, skel)
                #     continue
                # #

                preprocess(ori)
                oriEdge = getEdgeSegment(ori)
                oriFlat = getFlatSegment(ori, list(oriEdge.keys()))
                while oriFlat:
                    temp = oriFlat.pop()
                    del(oriEdge[temp])
                if len(oriEdge) % 2:
                    del(oriEdge[getFlattestSegment(ori, list(oriEdge.keys()))])
                if isAllLine(ori):
                    applyAttributeSegment(ori, list(oriEdge.keys()), skel, list(skelEdge.keys()), padding)
                    padding += getMaxPenPair(ori)    # int(len(ori._get_bPoints()) / 2)
                    continue
                keyControl = 0
                controlOriEdge = list(oriEdge)

                # For proper operation (get derivative and find opposite side)
                numOfMiddlePoints = calculateMiddlePoints(list(skelEdge.keys()), len(skel.bPoints))

                # remove points
                remove = []
                for i in range(len(oriEdge)):
                    edges = list(oriEdge.keys())
                    if abs(edges[i] - edges[i-1]) != 1:
                        remove += getRemovePoints(segToPointIndex(ori, edges[i-1]), segToPointIndex(ori, edges[i]), ori)
                while remove:
                    p = remove.pop()
                    ori.removeSegment(pToSeg(ori, p), True)
                oriEdge = getEdgeSegment(ori)
                controlOriEdge = list(oriEdge)

                for i in range(len(oriEdge)):
                #     preOriIndex = ori.segments.index(list(oriEdge.values())[i-1])
                #     oriIndex = ori.segments.index(list(oriEdge.values())[i])
                #     preSkelIndex = skel.segments.index(list(skelEdge.values())[i-1])
                #     skelIndex = skel.segments.index(list(skelEdge.values())[i])
                    if numOfMiddlePoints <= 0:
                        break
                    if keyControl:
                        controlOriEdge = [e+keyControl if e >= controlOriEdge[i-1] else e for e in controlOriEdge]
                        preOriIndex = controlOriEdge[i-1]
                        oriIndex = controlOriEdge[i]
                        keyControl = 0
                    else:
                        preOriIndex = controlOriEdge[i-1]
                        oriIndex = controlOriEdge[i]
                    preSkelIndex = list(skelEdge.keys())[i-1]
                    skelIndex = list(skelEdge.keys())[i]
                    # if skeleton's and original's edge gap is different
                    # if (oriIndex-preOriIndex) % len(ori.segments) < (skelIndex-preSkelIndex) % len(skel.segments):
                    if (oriIndex-preOriIndex) % len(ori.segments) != 1 or (skelIndex-preSkelIndex) % len(skel.segments) != 1:
                        # # To append points first before delete origin points
                        # keyControl += applySkeleton(ori, segToPointIndex(ori, preOriIndex), segToPointIndex(ori, oriIndex), skel, segToPointIndex(skel, preSkelIndex), segToPointIndex(skel, skelIndex))
                        # # To delete points first before append points
                        keyControl = applySkeletonAfterDelete(ori, segToPointIndex(ori, preOriIndex), segToPointIndex(ori, oriIndex), skel, segToPointIndex(skel, preSkelIndex), segToPointIndex(skel, skelIndex))
                        numOfMiddlePoints -= 2
                applyAttribute(ori, skel, padding)
                padding += getMaxPenPair(ori)    # int(len(ori._get_bPoints()) / 2)


# uncompyle6 version 3.7.4
# Python bytecode 2.5 (62131)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /usr/lib/python2.5/site-packages/mougeon/gui/hildon/portrait.py
# Compiled at: 2012-03-01 11:28:37
import dbus, dbus.glib, hildon, osso, gettext
_ = gettext.gettext
from mougeon.common import version
version.getInstance().submitRevision('$Revision: 3 $')

class FremantleRotation(object):
    """thp's screen rotation for Maemo 5

Simply instantiate an object of this class and let it auto-rotate
your StackableWindows depending on the device orientation.

If you need to relayout a window, connect to its "configure-event"
signal and measure the ratio of width/height and relayout for that.

You can set the mode for rotation to AUTOMATIC (default), NEVER or
ALWAYS with the set_mode() method.
"""
    (AUTOMATIC, NEVER, ALWAYS) = range(3)
    MODE_CAPTIONS = (
     _('Automatic'), _('Landscape'), _('Portrait'))
    (_PORTRAIT, _LANDSCAPE) = ('portrait', 'landscape')
    _ENABLE_ACCEL = 'req_accelerometer_enable'
    _DISABLE_ACCEL = 'req_accelerometer_disable'
    _MCE_SERVICE = 'com.nokia.mce'
    _MCE_REQUEST_PATH = '/com/nokia/mce/request'
    _MCE_REQUEST_IF = 'com.nokia.mce.request'
    KBD_SLIDER = '/sys/devices/platform/gpio-switch/slide/state'
    _KBD_OPEN = 'open'
    _KBD_CLOSED = 'closed'

    def __init__(self, app_name, main_window=None, version='1.0', mode=0):
        """Create a new rotation manager

app_name ... The name of your application (for osso.Context)
main_window ... The root window (optional, hildon.StackableWindow)
version ... The version of your application (optional, string)
mode ... Initial mode for this manager (default: AUTOMATIC)
"""
        self._orientation = None
        self._main_window = main_window
        self._stack = hildon.WindowStack.get_default()
        self._mode = -1
        self._last_dbus_orientation = None
        self._keyboard_state = self._get_keyboard_state()
        app_id = ('-').join((app_name, self.__class__.__name__))
        self._osso_context = osso.Context(app_id, version, False)
        program = hildon.Program.get_instance()
        program.connect('notify::is-topmost', self._on_topmost_changed)
        system_bus = dbus.Bus.get_system()
        system_bus.add_signal_receiver(self._on_orientation_signal, signal_name='sig_device_orientation_ind', dbus_interface='com.nokia.mce.signal', path='/com/nokia/mce/signal')
        system_bus.add_signal_receiver(self._on_keyboard_signal, signal_name='Condition', dbus_interface='org.freedesktop.Hal.Device', path='/org/freedesktop/Hal/devices/platform_slide')
        self.set_mode(mode)
        return

    def get_mode(self):
        """Get the currently-set rotation mode

This will return one of three values: AUTOMATIC, ALWAYS or NEVER.
"""
        return self._mode

    def set_mode(self, new_mode):
        """Set the rotation mode

You can set the rotation mode to AUTOMATIC (use hardware rotation
info), ALWAYS (force portrait) and NEVER (force landscape).
"""
        if new_mode not in (self.AUTOMATIC, self.ALWAYS, self.NEVER):
            raise ValueError('Unknown rotation mode')
        if self._mode != new_mode:
            if self._mode == self.AUTOMATIC:
                self._last_dbus_orientation = self._orientation
                self._send_mce_request(self._DISABLE_ACCEL)
            if new_mode == self.NEVER:
                self._orientation_changed(self._LANDSCAPE)
            elif new_mode == self.ALWAYS and self._keyboard_state != self._KBD_OPEN:
                self._orientation_changed(self._PORTRAIT)
            elif new_mode == self.AUTOMATIC:
                self._orientation_changed(self._last_dbus_orientation)
                self._send_mce_request(self._ENABLE_ACCEL)
            self._mode = new_mode

    def _send_mce_request(self, request):
        rpc = osso.Rpc(self._osso_context)
        rpc.rpc_run(self._MCE_SERVICE, self._MCE_REQUEST_PATH, self._MCE_REQUEST_IF, request, use_system_bus=True)

    def _on_topmost_changed(self, program, property_spec):
        if self._mode == self.AUTOMATIC:
            if program.get_is_topmost():
                self._send_mce_request(self._ENABLE_ACCEL)
            else:
                self._send_mce_request(self._DISABLE_ACCEL)

    def _get_main_window(self):
        if self._main_window:
            return self._main_window
        else:
            windows = self._stack.get_windows()
            if windows:
                return windows[(-1)]
            else:
                return
        return

    def _orientation_changed(self, orientation):
        if self._orientation == orientation:
            return
        flags = 0
        if orientation != self._LANDSCAPE:
            flags |= hildon.PORTRAIT_MODE_SUPPORT
        if orientation == self._PORTRAIT:
            flags |= hildon.PORTRAIT_MODE_REQUEST
        window = self._get_main_window()
        if window is not None:
            hildon.hildon_gtk_window_set_portrait_flags(window, flags)
        self._orientation = orientation
        return

    def _get_keyboard_state(self):
        try:
            return open(self.KBD_SLIDER).read().strip()
        except IOError:
            return self._KBD_CLOSED

    def _keyboard_state_changed(self):
        state = self._get_keyboard_state()
        if state == self._KBD_OPEN:
            self._orientation_changed(self._LANDSCAPE)
        elif state == self._KBD_CLOSED:
            if self._mode == self.AUTOMATIC:
                self._orientation_changed(self._last_dbus_orientation)
            elif self._mode == self.ALWAYS:
                self._orientation_changed(self._PORTRAIT)
        self._keyboard_state = state

    def _on_keyboard_signal(self, condition, button_name):
        if condition == 'ButtonPressed' and button_name == 'cover':
            self._keyboard_state_changed()

    def _on_orientation_signal(self, orientation, stand, face, x, y, z):
        if orientation in (self._PORTRAIT, self._LANDSCAPE):
            if self._mode == self.AUTOMATIC and self._keyboard_state != self._KBD_OPEN:
                self._orientation_changed(orientation)
            self._last_dbus_orientation = orientation


class A():
    def __init__(self):
        self.lisst=[]
        self.strinng=""
    def g(self):
    	while(True):
    		self.strinng=str(input("Enter : "))
    		self.lisst.append(self.strinng.upper())
    		self.p=int(input("(1/0)? "))
    		if (self.p)==0:
    			break
    def sc(self):
        print(self.lisst)

t=A()
t.g()
t.sc()


import os
import time
import subprocess

def filho():
    print('\nA new child %d' % os.getpid())
    j=0;
    while( j<3 ):
    	time.sleep(10)
    	newpid = os.fork()
    	if newpid == 0:
    		filho()
    	else:
    		print("Processo %d dobrou." % os.getpid())
    	j=j+1

 	#print("O processo %d vai morrer." % os.getpid()) queria enteder pq ta dando erro nisso
    os.kill(os.getpid(), 9)

def pai():
	while True:
		subprocess.call(["ps -ef"], shell = True)
		criar = input("Deseja criar processos? ('s' para sim, 'n' para não)\n")
		if criar == 's':
			numProce = int(input("Digite a quantidade de processos a serem criados: \n"))
			while numProce != 0:
				newpid = os.fork()
				if newpid == 0:
					filho()
				else:
					pids = (os.getpid(), newpid)
					print("pai: %d, Filho: %d" % pids)
					time.sleep(0.1)
				numProce = numProce-1
		encerrar = input("Deseja encerrar algum processo? ('s' para sim/ 'n' para não\n")
		if encerrar == 's':
			numPid = int(input("Digite o Pid do processo a ser encerrado: \n"))
			if numPid == os.getpid():
				print("O processo pai vai morrer!")
				time.sleep(3)
				subprocess.call(["killall -9 python3 unidade1.py"], shell = True)
			os.kill(numPid, 9)
			print("O processo %d foi morto!" % numPid)

pai()


#!/bin/python

import os

HTML_FILE = 'index.html'
BEGIN_TAG = '<!-- ## BEGIN %s ## -->'
END_TAG = '<!-- ## END %s ## -->'

SCRIPT_DIRECTIVE = 'AUTO SCRIPT'
STYLE_DIRECTIVE = 'AUTO STYLE'
CONTROLLER_DIRECTIVE = 'AUTO CONTROLLER'
INIT_DIRECTIVE = 'AUTO INIT'

def file_includer(line_fmt, extensions=None, explicit=None, ignore=None, directory=None):
	if extensions is None:
		extensions = []
	if explicit is None:
		explicit = []
	if ignore is None:
		ignore = []
	def includer():
		script_file = os.path.realpath(__file__)
		script_dir = os.path.dirname(script_file)
		root = None
		dir_and_fname = None
		if directory is None:
			root = script_dir
			dir_and_fname = lambda fn: fn
		else:
			root = os.path.join(script_dir, directory)
			dir_and_fname = lambda fn: os.path.join(directory, fn)
		script_names = []
		for fname in os.listdir(root):
			if any(i in fname for i in ignore):
				continue
			if any(e in fname for e in explicit):
				script_names.append(line_fmt(dir_and_fname(fname)))
				continue
			if any(fname.endswith(ext) for ext in extensions):
				script_names.append(line_fmt(dir_and_fname(fname)))
				continue
		return script_names
	return includer

def script_line_fmt(fname):
	return '  <script type="module" src="%s"></script>\n' % fname

def style_line_fmt(fname):
	return '  <link rel="stylesheet" type="text/css" href="%s"></link>\n' % fname

script_processor = file_includer(
	script_line_fmt,
	extensions=['.js'],
	ignore=['template', 'controller', 'init'],
	directory='build'
)

controller_processor = file_includer(
	script_line_fmt,
	explicit=['controller.js'],
	directory='build'
)

init_processor = file_includer(
	script_line_fmt,
	explicit=['init.js'],
	directory='build'
)

style_processor = file_includer(
	style_line_fmt,
	extensions=['.css']
)

def process_directive(source_file, directive_name, processor):
	with open(source_file, 'r') as src:
		src_lines = src.readlines()
	begin_line = None
	end_line = None
	begin_tag = BEGIN_TAG % directive_name
	end_tag = END_TAG % directive_name
	for i, line in enumerate(src_lines):
		if begin_tag in line:
			assert begin_line is None
			begin_line = i
		if end_tag in line:
			assert end_line is None
			end_line = i
	src_lines[begin_line + 1:end_line] = processor()
	with open(source_file, 'w') as src:
		for line in src_lines:
			src.write(line)

def main():
	process_directive(HTML_FILE, SCRIPT_DIRECTIVE, script_processor)
	process_directive(HTML_FILE, STYLE_DIRECTIVE, style_processor)
	process_directive(HTML_FILE, CONTROLLER_DIRECTIVE, controller_processor)
	process_directive(HTML_FILE, INIT_DIRECTIVE, init_processor)

if __name__ == '__main__':
	main()


import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import mobilenet_v2
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverListener

class MyListener(CheckpointSaverListener):
    def begin(self):
        print(".")

    def end(self, session, global_step_value):
        print("_")

if __name__ == '__main__':
    base_path = "../../../data"
    output_path = "../../../output"
    images_dir = "%s/flower_photos" % base_path

    #####################
    # Data Generator
    #####################

    # Before do this, please add new classes at the end of ImageNetLabels.txt. each class per line
    # classes: daisy、dandelion、roses、sunflowers、tulips
    labels_path = "ImageNetLabels.txt"
    imagenet_labels = np.array(open(labels_path).read().splitlines())[1:].tolist()  # drop first line 'background'

    print(len(imagenet_labels), imagenet_labels)

    train_datagen = ImageDataGenerator(preprocessing_function=mobilenet_v2.preprocess_input,
                                       validation_split=0.2)
    train_generator = train_datagen.flow_from_directory(images_dir, target_size=(224, 224),
                                                        color_mode='rgb', batch_size=32, shuffle=True,
                                                        classes=imagenet_labels, class_mode='sparse',
                                                        subset='training')
    validation_generator = train_datagen.flow_from_directory(images_dir, target_size=(224, 224),
                                                             color_mode='rgb', batch_size=32, shuffle=True,
                                                             classes=imagenet_labels, class_mode='sparse',
                                                             subset='validation')

    ###################
    # Define transfer learning model
    ###################

    base_model = mobilenet_v2.MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
    base_model.trainable = False

    keras_model = keras.Sequential([
        base_model,
        keras.layers.GlobalAveragePooling2D(),
        keras.layers.Dense(1024, activation='relu'),
        keras.layers.Dense(512, activation='relu'),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(5, activation='softmax')
    ])
    keras_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metric='accuracy')

    ###################
    # Use tensorflow estimator
    ###################

    # Multi GPUs
    strategy = tf.contrib.distribute.MirroredStrategy()
    config = tf.estimator.RunConfig(train_distribute=strategy)

    est_model = keras.estimator.model_to_estimator(keras_model=keras_model, config=config)

    train_x = []
    train_y = []
    for inputs_batch, labels_batch in validation_generator:
        train_x.append(inputs_batch)
        train_y.append(labels_batch)

    train_input_fn = tf.estimator.inputs.numpy_input_fn(x=train_x, y=train_y, num_epochs=1, shuffle=False)

    my_listener = MyListener()

    # To train, we call Estimator's train function:
    est_model.train(input_fn=train_input_fn, steps=5, saving_listeners=my_listener)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from apps.coxtactoe import tictactoe as ttt
from apps.coxtactoe.ai import MinMaxPlayer, X, O

__docformat__ = 'restructuredtext en'

def test_minmax_player_as_x():
    """Has MinMaxPlayer play 1000 games as X. Opponent's play is random.
    """
    ai = MinMaxPlayer(X)
    ai.play()

def test_minmax_player_as_o():
    """Has MinMaxPlayer play 1000 games as O. Opponent's play is random.
    """
    ai = MinMaxPlayer(O)
    ai.player = X  # let X go first
    ai.play()

def test_minmax_player_api():
    """Tests :class:`MinMaxPlayer` interface for playing when state is external
    """
    board = ttt.Board()
    board.place(X, 0)
    ai = MinMaxPlayer(O, board)
    ai_move = ai.get_best_move()
    board.place(O, ai_move)


shopping = []
while True:
    new_item = input("Please enter the next item, or type END to finish: ")
    if new_item == "END":
        print(shopping)
        print("thank you")
        break
    else:
      shopping.append(new_item)
      continue


from typing import Tuple
import pandas as pd
from pathlib import Path
import json
import argparse

import pickle
import logging
import lightgbm as lgb
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from evaluation import uAUC

logger = logging.getLogger('lgb_new')

from pandarallel import pandarallel

pandarallel.initialize()

ORIGINAL_ROOT = Path('../data/wechat_algo_data1')
TG_FEATURE_ROOT = Path('../tg_feature')
TG_FEATURE_CONFIG = TG_FEATURE_ROOT / 'feature_config.json'
TG_FEATURE_USER = TG_FEATURE_ROOT / 'userid_breakdown_scale.csv'
TG_FEATURE_FEED = TG_FEATURE_ROOT / 'feedid_breakdown_scale.csv'
LGB_FEATURE_ROOT = Path('../lgb_feature')
LGB_OUT_OFFLINE_ROOT = Path('../lgb_out_offline')
LGB_OUT_ONLINE_ROOT = Path('../lgb_out_online')
LGB_TRAIN_OFFLINE = LGB_FEATURE_ROOT / 'train_offline.csv'
LGB_TEST_OFFLINE = LGB_FEATURE_ROOT / 'test_offline.csv'
LGB_TRAIN_ONLINE = LGB_FEATURE_ROOT / 'train_online.csv'
LGB_TEST_ONLINE = LGB_FEATURE_ROOT / 'test_online.csv'
LGB_TRAIN_OFFLINE_PKL = LGB_FEATURE_ROOT / 'train_offline.pkl'
LGB_TEST_OFFLINE_PKL = LGB_FEATURE_ROOT / 'test_offline.pkl'
LGB_TRAIN_ONLINE_PKL = LGB_FEATURE_ROOT / 'train_online.pkl'
LGB_TEST_ONLINE_PKL = LGB_FEATURE_ROOT / 'test_online.pkl'
ACTION_LIST_ALL = ["read_comment", "like", "click_avatar",  "forward", "comment", "follow", "favorite"]
ACTION_LIST_PRE = ["read_comment", "like", "click_avatar",  "forward"]
FEA_FEED = 'feedid,authorid,videoplayseconds,bgm_song_id,bgm_singer_id'.split(',')
ACTION_WEIGHT = { 'read_comment': 4, 'like': 3, 'click_avatar': 2, 'forward': 1 }

LGB_PARAMS = {
    'boosting_type': 'gbdt',
    'objective': 'binary',
    'metric': 'auc',
    'max_depth': -1,
    'num_leaves': 31,
    'learning_rate': 0.25,
    'feature_fraction': 0.9,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': 0,
    'random_state': 42,
    'n_jobs': -1,
    'force_col_wise': True,
    # 'two_round': True
}

def init_logging():
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.FileHandler("debug.log"), logging.StreamHandler()],
    )

def get_original_data(with_feedinfo: bool) -> Tuple[pd.DataFrame, pd.DataFrame]:
    logger.info('getting original data')
    user_action = pd.read_csv(ORIGINAL_ROOT / 'user_action.csv')
    test_a = pd.read_csv(ORIGINAL_ROOT / 'test_a.csv')

    with open(TG_FEATURE_ROOT / 'userid_map.pkl', 'rb') as f:
        userid_map = pickle.load(f)

    with open(TG_FEATURE_ROOT / 'feedid_map.pkl', 'rb') as f:
        feedid_map = pickle.load(f)

    # merge feed info
    feed_info = pd.read_csv(ORIGINAL_ROOT / 'feed_info.csv')[FEA_FEED]
    if with_feedinfo:
        user_action = user_action.merge(feed_info, how='left', on='feedid')
        test_a = test_a.merge(feed_info, how='left', on='feedid')

    user_action['userid'] = user_action['userid'].parallel_apply(lambda x: userid_map[x])
    user_action['feedid'] = user_action['feedid'].parallel_apply(lambda x: feedid_map[x])
    test_a['userid'] = test_a['userid'].parallel_apply(lambda x: userid_map[x])
    test_a['feedid'] = test_a['feedid'].parallel_apply(lambda x: feedid_map[x])

    return user_action, test_a

def prepare_tg_dense_features() -> Tuple[pd.DataFrame, pd.DataFrame]:
    with open(TG_FEATURE_CONFIG, 'r') as f:
        feature_config = json.load(f)

    logger.info('preparing tg dense features')

    user_dense_feature_names = { **(feature_config['user_breakdown']), **(feature_config['duration_breakdown']) }
    user_dense_feature_names = user_dense_feature_names.keys()
    user_dense_feature_names = [x.replace('{}', '.*') for x in user_dense_feature_names] + ['userid', 'date_']

    feed_dense_feature_names = { **(feature_config['feed_breakdown']), **(feature_config['device_breakdown']) }
    feed_dense_feature_names = feed_dense_feature_names.keys()
    feed_dense_feature_names = [x.replace('{}', '.*') for x in feed_dense_feature_names] + ['feedid', 'date_']

    user_dense_features = pd.read_csv(TG_FEATURE_USER)
    user_dense_features = user_dense_features.filter(user_dense_features)

    feed_dense_features = pd.read_csv(TG_FEATURE_FEED)
    feed_dense_features = feed_dense_features.filter(feed_dense_features)

    return user_dense_features, feed_dense_features

def prepare_train_test_data(user_action: pd.DataFrame, test_a: pd.DataFrame, user_dense_features: pd.DataFrame, feed_dense_features: pd.DataFrame):
    train_offline = user_action[(user_action['date_'] < 14) & (user_action['date_'] >= 7)]
    test_offline = user_action[user_action['date_'] == 14]
    # user_dense_features_14 = user_dense_features[user_dense_features['date_'] == 14]
    # feed_dense_features_14 = feed_dense_features[feed_dense_features['date_'] == 14]
    train_offline = train_offline.merge(user_dense_features, how='left', on=['userid', 'date_'])
    train_offline = train_offline.merge(feed_dense_features, how='left', on=['feedid', 'date_'])
    test_offline = test_offline.merge(user_dense_features, how='left', on=['userid', 'date_'])
    test_offline = test_offline.merge(feed_dense_features, how='left', on=['feedid', 'date_'])

    logger.info('writing train&test offline data, train shape: {}, test shape: {}'.format(train_offline.shape, test_offline.shape))
    train_offline.to_pickle(LGB_TRAIN_OFFLINE_PKL)
    test_offline.to_pickle(LGB_TEST_OFFLINE_PKL)

    user_dense_features_15 = user_dense_features[user_dense_features['date_'] == 15]
    feed_dense_features_15 = feed_dense_features[feed_dense_features['date_'] == 15]
    # last week
    train_online = user_action[(user_action['date_'] <= 14) & (user_action['date_'] > 7)]  # all data
    train_online = train_online.merge(user_dense_features, how='left', on=['userid', 'date_'])
    train_online = train_online.merge(feed_dense_features, how='left', on=['feedid', 'date_'])

    test_online = test_a.merge(user_dense_features_15, how='left', on=['userid'])
    test_online = test_online.merge(feed_dense_features_15, how='left', on=['feedid'])

    logger.info('writing train&test online data, train shape: {}, test shape: {}'.format(train_online.shape, test_online.shape))
    train_online.to_pickle(LGB_TRAIN_ONLINE_PKL)
    test_online.to_pickle(LGB_TEST_ONLINE_PKL)

def offline_train(phases: str):
    # load train data
    # label = 'read_comment'
    # for label in ACTION_LIST_PRE:
    phases = phases.split(',')
    logger.info('loading offline train&test data')
    train_on = pd.read_pickle(LGB_TRAIN_OFFLINE_PKL)
    test_on = pd.read_pickle(LGB_TEST_OFFLINE_PKL)
    aucs = {}
    boost_round = {}
    for label in phases:
        logger.info('-------------------------')
        logger.info('PHASE: {}'.format(label))
        logger.info('-------------------------')
        # only read_comment for now
        ACTION_LIST = ACTION_LIST_ALL.copy()
        ACTION_LIST.remove(label)
        train_on_phase = train_on.drop(['date_', 'play', 'stay'] + ACTION_LIST, axis=1)
        y_train_on = train_on_phase[label]
        x_train_on = train_on_phase.drop(label, axis=1)

        test_on_phase = test_on.drop(['date_', 'play', 'stay'] + ACTION_LIST, axis=1)
        y_test_on = test_on_phase[label]
        x_test_on = test_on_phase.drop(label, axis=1)

        logger.info('getting train & val dataset')

        ul = x_test_on['userid'].tolist()
        dtrain = lgb.Dataset(x_train_on, label=y_train_on)
        dval = lgb.Dataset(x_test_on, label=y_test_on)

        logger.info('going to train')
        lgb_model = lgb.train(
            LGB_PARAMS,
            dtrain,
            num_boost_round=10000,
            valid_sets=[dval],
            early_stopping_rounds=50,
            verbose_eval=50,
        )

        pred = lgb_model.predict(x_test_on, num_iteration=lgb_model.best_iteration)
        logger.info('best iteration: {}, best score: {}'.format(lgb_model.best_iteration, lgb_model.best_score))
        v = uAUC(y_test_on.tolist(), pred.tolist(), ul)
        logger.info('uAUC: {}'.format(v))
        aucs[label] = v
        boost_round[label] = lgb_model.best_iteration

        logger.debug('features: {}'.format(x_train_on.columns.tolist()))
        importance_split = lgb_model.feature_importance('split')
        logger.debug('feature importance split: {}'.format(importance_split))
        importance_gain = lgb_model.feature_importance('gain')
        logger.debug('feature importance gain: {}'.format(importance_gain))

        logger.info('save them to file')
        str = 'features: {}\nfeature importance (split): {}\nfeature importance (gain): {}\n\n'.format(
            x_train_on.columns.tolist(), importance_split, importance_gain
        )

        xobj = { x[0]: {'split': x[1], 'gain': x[2] } for x in list(zip(x_train_on.columns.tolist(), importance_split, importance_gain)) }

        with open(LGB_OUT_OFFLINE_ROOT / 'feature_importance_{}.txt'.format(label), 'w', encoding='utf8') as f:
            f.write(str)
            f.flush()

        with open(LGB_OUT_OFFLINE_ROOT / 'feature_importance_{}.json'.format(label), 'w', encoding='utf8') as f:
            f.write("{}".format(xobj).replace("'", '"'))
            f.flush()

        logger.info('saving model: {}'.format(label))
        # cannot use PosixPath as parameter to 'save_model'
        lgb_model.save_model((LGB_OUT_OFFLINE_ROOT / 'lgb_{}.lgb_model'.format(label)).as_posix())
        lgb.plot_importance(lgb_model, figsize=(30, 180)).figure.savefig(LGB_OUT_OFFLINE_ROOT / 'lgb_importance_{}.png'.format(label))

    # calculate uAUC
    numerator = 0
    denominator = 0
    for label in phases:
        numerator += ACTION_WEIGHT[label] * aucs[label]
        denominator += ACTION_WEIGHT[label]

    logger.info('offline uAUC calculated: {}'.format(numerator / denominator))

    # save boost_round
    with open(LGB_OUT_OFFLINE_ROOT / 'boost_round.json', 'w', encoding='utf8') as f:
        json.dump(boost_round, f)

    pass

def online_train(runid: str):
    logger.info('loading online train&test data')
    train_on = pd.read_pickle(LGB_TRAIN_ONLINE_PKL)
    test_on = pd.read_pickle(LGB_TEST_ONLINE_PKL)

    submit = pd.read_csv(ORIGINAL_ROOT / 'test_a.csv')
    for label in ACTION_LIST_PRE:
        logger.info('-------------------------')
        logger.info('PHASE: {}'.format(label))
        logger.info('-------------------------')
        # only read_comment for now
        ACTION_LIST = ACTION_LIST_ALL.copy()
        ACTION_LIST.remove(label)
        train_on_phase = train_on.drop(['date_', 'play', 'stay'] + ACTION_LIST, axis=1)
        y_train_on = train_on_phase[label]
        x_train_on = train_on_phase.drop(label, axis=1)

        # no label in test
        # test_on_phase = test_on.drop(['date_', 'play', 'stay'] + ACTION_LIST, axis=1)
        # y_test_on = test_on_phase[label]
        # x_test_on = test_on_phase.drop(label, axis=1)
        x_test_on = test_on
        x_test_on = x_test_on[x_train_on.columns]

        logger.info('getting train & val dataset')

        ul = x_test_on['userid'].tolist()
        dtrain = lgb.Dataset(x_train_on, label=y_train_on)
        # dval = dtrain

        logger.info('loading best boost round when offline train')
        with open(LGB_OUT_OFFLINE_ROOT / 'boost_round.json', 'r', encoding='utf8') as f:
            boost_round = json.load(f)

        logger.info('going to train')
        lgb_model = lgb.train(
            LGB_PARAMS,
            dtrain,
            num_boost_round=boost_round[label],
            valid_sets=[dtrain],
            early_stopping_rounds=50,
            verbose_eval=50,
        )

        pred = lgb_model.predict(x_test_on, num_iteration=lgb_model.best_iteration)
        submit[label] = pred
        logger.info('best iteration: {}, best score: {}'.format(lgb_model.best_iteration, lgb_model.best_score))
        # there's no label for online predict
        # v = uAUC(y_test_on.tolist(), pred.tolist(), ul)
        # logger.info('uAUC: {}'.format(v))

        logger.debug('features: {}'.format(x_train_on.columns.tolist()))
        importance_split = lgb_model.feature_importance('split')
        logger.debug('feature importance split: {}'.format(importance_split))
        importance_gain = lgb_model.feature_importance('gain')
        logger.debug('feature importance gain: {}'.format(importance_gain))

        logger.info('save them to file')
        str = 'features: {}\nfeature importance (split): {}\nfeature importance (gain): {}\n\n'.format(
            x_train_on.columns.tolist(), importance_split, importance_gain
        )

        xobj = { x[0]: {'split': x[1], 'gain': x[2] } for x in list(zip(x_train_on.columns.tolist(), importance_split, importance_gain)) }

        with open(LGB_OUT_ONLINE_ROOT / 'feature_importance_{}_{}.txt'.format(label, runid), 'w', encoding='utf8') as f:
            f.write(str)
            f.flush()

        with open(LGB_OUT_ONLINE_ROOT / 'feature_importance_{}_{}.json'.format(label, runid), 'w', encoding='utf8') as f:
            f.write("{}".format(xobj).replace("'", '"'))
            f.flush()

        logger.info('saving model: {}'.format(label))
        lgb_model.save_model((LGB_OUT_ONLINE_ROOT / 'lgb_{}_{}.lgb_model'.format(label, runid)).as_posix())
        lgb.plot_importance(lgb_model, figsize=(30, 180)).figure.savefig(LGB_OUT_ONLINE_ROOT / 'lgb_importance_{}_{}.png'.format(label, runid))

    # save submit
    submit.to_csv(LGB_OUT_ONLINE_ROOT / 'submit_lgb_{}.csv'.format(runid), index=False)
    pass

def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser()
    p.add_argument('--mode', type=str, choices=['process', 'offline_train', 'online_train'])
    p.add_argument('--phase', type=str)
    p.add_argument('--with_feedinfo', action='store_true')
    p.add_argument('--runid', type=str)
    return p.parse_args()

def main():
    init_logging()
    args = vars(parse_args())
    if args['mode'] == 'process':
        user_action, test_a = get_original_data(args['with_feedinfo'])
        user_dense_features, feed_dense_features = prepare_tg_dense_features()
        prepare_train_test_data(user_action, test_a, user_dense_features, feed_dense_features)
    elif args['mode'] == 'offline_train':
        offline_train(args['phase'])
    elif args['mode'] == 'online_train':
        online_train(args['runid'])
    pass

if __name__ == '__main__':
    main()


# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt

''' Define a Bandit class which has the following parameters
@param numArm : number of actions in the K-armed bandit problem
@param epsilon : Set the epsilon value for epsilon-greedy action selection. Default value is 0.0
@param temperature : Set the temperature parameter of softmax action selection. Default value is 1.0
@param epsilonGreedy : Flag to select that action-selection is based on epsilon-greedy algorithm. Default value is False
@param softmax : Flag to select that action-selection is based on the softmax algorithm. Defalut value is False
@param ucb : Flag to select that action-selection is based on the softmax algorithm. Default value is False
@param initial_estimate : Setting the initial estimates for estimates all the arms
@param trueReward : Setting the true reward for the all arms
'''

class Bandit:
    # Constructor function to initialise the parameters for the bandit instantiation
    def __init__(self, numArm = 10, epsilon = 0.0, temperature = 1.0, epsilonGreedy = False, softmax = False, ucb =
    False, initial_estimate = 0.0, trueReward = 0.0):
        # Initialisation of parameters
        self.numArm = numArm
        self.epsilon = epsilon
        self.temperature = temperature
        self.time = 0
        self.averageReward = 0
        self.epsilonGreedy = epsilonGreedy
        self.softmax = softmax
        self.ucb = ucb
        self.armIndices = np.arange(self.numArm)
        self.qTrue = trueReward * np.ones(self.numArm) # True rewards for each action
        self.qEst = initial_estimate *  np.ones(self.numArm) # Estimate of the reward for each action
        self.actionCount = np.zeros(self.numArm) # Action Selection count
        # Get the true rewards for each action
        for i in range(0,self.numArm):
            self.qTrue[i] = self.qTrue[i] + np.random.randn()
        self.bestAction = np.argmax(self.qTrue)

    # Function to choose the action based on what algorithm is being followed
    def chooseAction(self):
        if self.epsilonGreedy == True:
            armToPlay = np.random.randint(0,self.numArm) # Choose a random action
            # With probability greater than epsilon, choose the action greedily
            if np.random.random() > self.epsilon:
                armToPlay = np.argmax(self.qEst)
            return armToPlay

        if self.softmax == True:
            expo_val = np.exp(self.qEst / self.temperature)
            prob_val = expo_val / np.sum(expo_val) # Get the probability distribution to be sampled from
            rnd = np.random.random() # Sample a random number
            # Use the CDF method to sample from the Gibbs distribution
            for i,w in enumerate(prob_val):
                rnd -= w
                if rnd < 0:
                    return i
            return 0

        if self.ucb == True:
            # play each action once at first
            if(np.count_nonzero(self.actionCount) < self.numArm):
                return np.argmin(self.actionCount)
            # after having played each arm once, choose action greedily using the upper confidence bound
            return np.argmax(self.qEst + np.sqrt(np.log(self.time + 1) / (np.asarray(self.actionCount) + 1)))

    # Function to get the reward on playing the action, increment the count of action and update the estimate of that action
    def getReward(self,action):
        reward = np.random.randn() + self.qTrue[action]
        self.time += 1
        self.averageReward = (self.time - 1.0) / self.time * self.averageReward + reward / self.time # keep a running average of the reward
        self.actionCount[action] += 1 # increase the action count
        self.qEst[action] += 1.0 / self.actionCount[action] * (reward - self.qEst[action]) # update the estimate of the action
        return reward


from django.shortcuts import render, redirect
from .forms import RegisterForm
from .models import User, Profile

def home(request):
    return render(request, 'app1/index.html')

# Register
def register(request):
    form = RegisterForm
    if request.method == 'POST':
        form = form(request.POST)
        if form.is_valid():
            form.save()
            return redirect('app1:login')
    return render(request, 'app1/register.html', {'forms': form})

# Profile View
def profile(request, id=None):
    context = {}
    try:
        user = User.objects.get(id=id)
        user = Profile.objects.get(user__email=user)
        context['userprofile'] = user
    except User.DoesNotExist:
        error = 'This User Does Not Exist'
        return render(request, 'page404.html', {'error': error})
    return render(request, 'app1/profile.html', context)

# Delete User
def delete_user(request, id=None):
    if 'delete_user' in request.POST and id is not None:
        User.objects.get(id=id).delete()
    return redirect('app1:register')

UserApp/More than three users/project/app1/views.py


from flask import Flask, jsonify, render_template, make_response
import csv

app = Flask(__name__)

# results = [{'state':'Arizona', 'district': '1', 'cand1': 'A', 'cand2': 'B', 'party1':'dem', 'party2': 'rep','pred': 0.7, 'time': 0}, {'state':'Massachusetts', 'district': '1', 'cand1': 'A', 'cand2': 'B', 'party1':'dem', 'party2': 'rep','pred': 0.25, 'time': 0}]

with open('FakeData-Sheet1.csv') as f:
     reader = csv.DictReader(f)
     data = list(reader)

results = []
assert len(data)% 2 == 0
party = {"R": "rep", "D": "dem"}
color = {"Republican": 1, "Democratic": 0}
for i in range(0, int(len(data)), 2):
     # print(data[i]["State"], "H")
     # print(data[i+1]["State"], "H")
     # print(data[i]["State"]==data[i+1]["State"])
     # assert data[i]["State"] == data[i+1]["State"]
     # assert data[i]["District"] == data[i+1]["District"]
     entry = {}
     entry["pred1"] = float(data[i]["Prob Winning"])
     entry["pred2"] = float(data[i+1]["Prob Winning"])
     entry["party1"] = party[data[i]["Party"]]
     entry["cand1"] = data[i]["Candidate"]
     entry["party2"] = party[data[i+1]["Party"]]
     entry["cand2"] = data[i+1]["Candidate"]
     entry["state"] = data[i]["State"].rstrip()
     entry["district"] = data[i]["District"]
     results.append(entry)

affiliations = {}
with open('States-by-Affiliation-Sheet1.csv') as f:
     reader = csv.reader(f)
     for row in reader:
          affiliation = row[1].split()
          # if len(affiliation) == 1:
          # print(row[0].rstrip())
          if affiliation[0] in color:
               affiliations[row[0].rstrip()] = color[affiliation[0]]
          else:
               affiliations[row[0].rstrip()] = 0.5
          # else:

timedata = []
times = ['2019-12-07', '2019-11-07', '2019-10-07', '2019-09-07', '2019-08-07']

with open('{}.csv'.format(times[0])) as f:
     reader = csv.DictReader(f)
     reader = list(reader)
     for entry in reader:
          entry["party"] = party[entry["party"]]
     #      for time in times:
     #           entry["time"] = time
     #           entry["prob"] = entry[time]
     #           timedata.append(entry)
     # print(reader)
     # for i in range(0, int(len(reader)), 2):
     #      entry = {}
     #      entry['party'] = party[reader[i]['party']]
     #      entry['state'] = reader[i]['state']
     #      entry['district'] = reader[i]['district']

     #      print(entry)
          # for time in times:
          #      timedata.append()
          # pass

results = []
assert len(reader)% 2 == 0
for i in range(0, int(len(reader)), 2):
     # print(data[i]["State"], "H")
     # print(data[i+1]["State"], "H")
     # print(data[i]["State"]==data[i+1]["State"])
     # assert data[i]["State"] == data[i+1]["State"]
     # assert data[i]["District"] == data[i+1]["District"]
     entry = {}
     entry["pred1"] = float(reader[i][times[0]]) if reader[i]["party"] == "dem" else 1-float(reader[i][times[0]])
     entry["pred2"] = float(reader[i+1][times[0]]) if reader[i+1]["party"] == "dem" else 1-float(reader[i+1][times[0]])
     entry["party1"] = reader[i]["party"]
     entry["cand1"] = reader[i]["person"]
     entry["party2"] = reader[i+1]["party"]
     entry["cand2"] = reader[i+1]["person"]
     entry["state"] = reader[i]["state"].rstrip()
     entry["district"] = reader[i]["district"]
     results.append(entry)

@app.route('/', methods = ['GET'])
def home():
     return make_response(jsonify({'results':results, 'affiliations': affiliations, 'timedata': reader, 'times': times}), 200)

@app.route('/a', methods = ['GET'])
def page():
     return render_template('/visualization.html')

if __name__== '__main__':
     app.jinja_env.auto_reload = True
     app.config['TEMPLATES_AUTO_RELOAD'] = True
     # app.config['TEMPLATES_AUTO_RELOAD'] = True
     app.config['STATIC_AUTO_RELOAD'] = True
     app.run(debug=True, extra_files=['/static','/templates'])


from django.conf.urls import patterns, url

from timetable import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^compose/(?P<timetable_id>\w+)$', views.timetable_compose, name='timetable_compose'),

    url(r'render_course_list/$', views.render_course_list, name='render_course_list'),
    url(r'render_calendar/$', views.render_calendar, name='render_calendar'),
    url(r'assign_lesson/$', views.assign_lesson, name='assign_lesson'),
)


import tkinter as tk
from  tkinter import ttk  #导入内部包
from Code import Find
from Code import ShowTable
FindWeek=0				#当前的周数
FindDay=0				#查询的日期
FindCourse=0			#查询的课

path=".\Background\Back.png"			#背景图片路径

#主窗口的启动
Win=tk.Tk()
Win.title("实验室无课表查询")			#title文字
Win.minsize(900,500)					#窗口大小控制
Win.maxsize(900,500)

#背景图片的展示
canvas = tk.Canvas(Win,width=900,height=500)
canvas.pack(expand = 'YES', fill = 'both')
image = tk.PhotoImage(file = path)
canvas.create_image(0,0,image = image, anchor = 'nw')

#三个滑块选项：初始化以及展示
WeekScale=tk.Scale(Win,from_=0,to=24,label="选择查询的周",orient="horizontal")
DayScale=tk.Scale(Win,from_=0,to=7,label="选择查询的星期",orient="horizontal")
CourseScale=tk.Scale(Win,from_=0,to=5,label="选择查询的节数",orient="horizontal")
WeekScale.place(x=10,y=5)
DayScale.place(x=160,y=5)
CourseScale.place(x=310,y=5)
Table=ttk.Treeview(Win)#表格

def Print(Day,StuNameList,StuNumList,StuClassList):

#对于每天的查询
	if(Day==0):								#当查询一周的情况的时候
		print("a")
	else:
		#Table=
		ShowTable.ShowDay(Table,Day,StuNameList,StuNumList,StuClassList)
		Table.place(x=100,y=150)

def Click():		#按钮的点击事件						核心处理事件

	FindWeek=WeekScale.get()
	FindDay=DayScale.get()
	FindCourse=CourseScale.get()

	StuNameList,StuNumList,StuClassList,Error=Find.Find(FindWeek,"ALL")

	Print(FindDay,StuNameList,StuNumList,StuClassList)

#确定按钮的初始化和展示
Button=tk.Button(Win,text="查询",command=Click)
Button.place(x=460,y=40)

Win.mainloop()


import random

def simulation(len):
    alphabet = 'abcdefghijklmnopqrstuvwxyz '
    string = ''
    for i in range(len):
        string += alphabet[random.randrange(27)]
    return string

def compare(current, target):
    num = sum([1 for i in range(len(target)) if current[i] == target[i]]) / len(target)
    return num

def generator(string):
    num = 0
    iter = 0
    best = simulation(len(string))
    while num != 1:
        current = simulation(len(string))
        num = compare(current, string)
        if num > compare(best, string):
            best = current
        iter += 1
        if iter % 100000 == 0:
            print(compare(best, string))
    return iter

print(generator('methinks it is like a weasel'))


# NAME：ChengYu
# DATE：20200405-1
# FUNC：字典查找网络全部元素
# QSTN：网络个数不能过大，否则会爆内存；
#       更改了“网”的定义：包含所有互通元素的集合，未检测bug，官方用例pass
#       eye是网眼个数估计值，不准确，但能确定网络是否只有一个环
#       输出成txt文件,修改bug：无网眼时返回1节点-》返回空

import numpy as np
import time
import Global9

#列表转字典(lst:被转换数据，dic:输出字典，n:数据总行数)
def Lst2Dic(lst:[]):
    dic={}
    n = lst.shape[0]
    for i in range(n):
        if lst[i][0] not in dic:
            dic[lst[i][0]] = [lst[i][1]]
        else:
            dic[lst[i][0]] += [lst[i][1]]
    return dic

#查找网络（dic：要查找的字典，ID，开始查询的位置）
def Find_Net(dic:{},ID:int):
    # 查找链(dic:要查找的字典,ID:查找字典中的ID，tmp:传入一个含ID的列表贮存链,RES：保存网络用于迭代的传入，eye:网孔数量)
    def Find_chain(dic: {}, ID: int):
        if (ID in dic):         #判断传进来的字典里有没有
            n = len(dic[ID])  # ID1发送的用户有多少
            # 递归结束条件：ID不在字典中，链超过7
            for ID0 in dic[ID]:  # 遍历ID1发送的用户
                if len(Global9.chain)-1 <= 100:  # 如果链的长度不超标（不起限制作用）
                    if ID0 in dic:  # 如果此用户作为发送人在字典中存在
                        if (ID0 not in Global9.chain[:-1] and ID0 not in Global9.net):  # 如果没闭合成环
                            Global9.chain += [ID0]  # 存在缓存里
                            Find_chain(dic, ID0)  # 递归

                        else: #闭合成环了

                            Global9.net += Global9.chain  # 把这个数组接到后面
                            Global9.eye += 1  # 网孔加一
                            Global9.chain = []  # 删除tmp保存的环，就是转移到RES里面，然后存新环了

                    else:  # 链断了
                        continue
                else:  # 超出n个了
                    continue

            if len(Global9.chain)!=0:#全遍子树历完了还没有就删除这个父节点
                del Global9.chain[-1]
            return

        else:
            return
####################################################

    Global9.eye=0
    Global9.net=[]
    Global9.chain=[ID]
    Find_chain(dic, ID)
    return Global9.net,Global9.eye

#求网络总和（net:网络）
def Net_Sum(Net:[]):
    return [sum(Net)]

#判断是否合法（net:网络，find：已经找到的网络和）[P.S.这个判断方式十分粗暴，就是判断网络节点总和相等就判定查找过]
def IsIllegal(net:[],find:[],eye:int):
    a=sum(net)
    b=len(net)
    if (a in find) or (b<=2) or (eye==1 and b>7) :
        return 1#不合法
    else:
        return 0#合法

#读取数据（path:路径）
def Read_Data(path:str):

    dataset = np.array(np.genfromtxt(path, delimiter=',', dtype=int))
    dic=Lst2Dic(dataset[:, :-1])
    # print(dic)
    return dic

#由于网络相互不接触，删掉也没关系(dic：所有测试数据，net：查找出的网络）
def Delet(dic:{},net:[]):
    for ID in net:
        del dic[ID]
    return dic

#对接函数（dic:查找的字典,ls：网络列表）
def Connect(dic:{},ls:[]):
    res=[]
    for ID0 in ls:
        for ID1 in dic[ID0]:
            if ID1 in ls:
                res.append([ID0,ID1])
    return res

#网络查找接口函数（dic：查找的字典）
def FIND_NET(dic:{}):
    res=[[]]
    net, eye = Find_Net(dic, ID)  # 查找网
    if len(net) != 0:  # 如果成网络了
        res = Connect(dic, net)
    else:  # 节点没有网络连接
        del dic[ID]  # 删掉节点
    for ID0 in net:  #删掉网络节点
        del dic[ID0]
    return res,eye

def WRITE_TXT(ls:[],path:str):
    fh = open(path, 'w', encoding='utf-8')
    for STREAM in ls:
        fh.write(str(STREAM[0]) + ',' + str(STREAM[1]) + ',' + '0' + '\n')
    fh.close()

if __name__=='__main__':

    start1 = time.perf_counter()
    ########################################################################
    # FUN:提取网络保存成文件
    # COPYRIGHT@CY
    ########################################################################
    Global9.dic = Read_Data("../dataset/test_data.txt")# 读取文件保存成字典

    net, eye = Find_Net(Global9.dic, 9)  # 查找网

    fh = open('res_cy.txt', 'w', encoding='utf-8')
    while (len(Global9.dic) != 0):
        for ID in Global9.dic:
            net,eye=FIND_NET(Global9.dic)
            if (len(net)!=1):
                print(eye,net)
                for STREAM in net:
                    fh.write(str(STREAM[0]) + ',' + str(STREAM[1]) + ',' + '0' + '\n')
            break
    fh.close()

    #########################################################################
    # FUN:
    # COPYRIGHT@
    #########################################################################

    end1 = time.perf_counter()
    print("final is in : %s Seconds " % (end1 - start1))


from gi.repository import Gtk, GtkSource
class Status:
  def __init__(self):
    self.connect('view-created', lambda _, view:
        view.connect('draw', self.draw_status))
    self.connect('key-pressed', lambda _:
        self.current_view.queue_draw())

    self.command_prefix = []
    self.connect('key-handler-reset', lambda w: self.command_prefix.clear())
    self.connect('key-handler-prefix', lambda w, c: self.command_prefix.append(c))

  def draw_status(self, view, cr):
    rect = view.get_allocation()
    cr.select_font_face('Times')
    cr.set_font_size(256)
    cr.set_source_rgb(0.2, 0.2, 0.2)
    cr.move_to(rect.width / 3, rect.height / 2)
    # operation_mode
    if self.operation_mode == self.COMMAND:
        cr.show_text('C')
    # command
    cr.set_font_size(128)
    t = ''.join(self.command_prefix)
    if self.n != 0: t = str(self.n) + t
    cr.show_text(t)
    # selection_mode
    cr.move_to(rect.width / 3 + 50, rect.height / 2 - 50)
    if self.selection_mode == self.CHAR:
        cr.show_text('c')
    elif self.selection_mode == self.LINE:
        cr.show_text('l')
    elif self.selection_mode == self.RECT:
        cr.show_text('r')
    # current column
    buf = view.get_buffer()
    cursor_rect = view.get_iter_location(buf.get_iter_at_mark(buf.get_insert()))
    cr.set_source_rgb(0, 0.5, 0)
    cr.set_line_width(2)
    x, _ = view.buffer_to_window_coords(Gtk.TextWindowType.WIDGET, cursor_rect.x, 0)
    cr.move_to(x, 0)
    cr.line_to(x, rect.height)
    cr.stroke()