#!/usr/bin/env python
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import subprocess

import test_env
from lib.device import Device

from host_mock import MockHost

class MockDevice(Device):
    def __init__(self, port=22):
        super(MockDevice, self).__init__(MockHost(), '::1', port)
        self.history = []
        self.toggle = False

    def _ssh(self, cmdline, stdout=subprocess.PIPE):
        """ Overrides Device._ssh to provide canned responses."""
        self.history.append(' '.join(
            self.get_ssh_cmd(['ssh', self._addr] + cmdline)))
        if cmdline[0] == 'cs' and self.toggle:
            response = """
  http.cmx[20963]: fuchsia-pkg://fuchsia.com/http#m
  mock-target1.cmx[7412221]: fuchsia-pkg://fuchsia.com/mock-p
  mock-target2.cmx[7412222]: fuchsia-pkg://fuchsia.com/mock-p
  an-extremely-verbose-target-name[7412223]: fuchsia-pkg://fuchsia.com/mock-p
"""
            self.toggle = False
        elif cmdline[0] == 'cs':
            response = """
  http.cmx[20963]: fuchsia-pkg://fuchsia.com/http#m
  mock-target1.cmx[7412221]: fuchsia-pkg://fuchsia.com/mock-p
  an-extremely-verbose-target-name[7412223]: fuchsia-pkg://fuchsia.com/mock-p
"""
            self.toggle = True
        elif cmdline[0] == 'ls' and cmdline[-1].endswith('corpus'):
            response = """
-rw-r--r--    1 0        0              1796 Mar 19 17:25 feac37187e77ff60222325cf2829e2273e04f2ea
-rw-r--r--    1 0        0               124 Mar 18 22:02 ff415bddb30e9904bccbbd21fb5d4aa9bae9e5a5
"""
        elif cmdline[0] == 'ls':
            response = """
drw-r--r--    2 0        0             13552 Mar 20 01:40 corpus
-rw-r--r--    1 0        0               918 Mar 20 01:40 fuzz-0.log
-rw-r--r--    1 0        0              1337 Mar 20 01:40 crash-deadbeef
-rw-r--r--    1 0        0              1729 Mar 20 01:40 leak-deadfa11
-rw-r--r--    1 0        0             31415 Mar 20 01:40 oom-feedface
"""
        else:
            response = ''
        return subprocess.Popen(
            ['printf', '\'' + response + '\''],
            stdout=stdout,
            stderr=subprocess.STDOUT)

    def _scp(self, srcs, dst):
        """ Overrides Device._scp."""
        self.history.append(' '.join(self.get_ssh_cmd(['scp'] + srcs + [dst])))


from base64 import b64encode

from clld.web.maps import Map, Legend, Layer
from clld.web.util.htmllib import HTML
from clld.lib.svg import icon, data_url

from pofatu.models import ROCKSOURCETYPES

class ArtefactsMap(Map):
    def get_options(self):
        res = Map.get_options(self)
        res['max_zoom'] = 15
        res['base_layer'] = 'OpenTopoMap'
        return res

class SourcesMap(Map):
    def get_options(self):
        res = Map.get_options(self)
        res['max_zoom'] = 15
        res['base_layer'] = 'OpenTopoMap'
        res['info_route'] = 'rocksource_alt'
        res['icons'] = 'div'
        return res

    def get_layers(self):
        for name in ROCKSOURCETYPES:
            yield Layer(
                name,
                name,
                self.req.route_url('rocksources_alt', ext='geojson', _query=dict(type=name)))

    #def get_legends(self):
    #    def make_item(label, color):
    #        return HTML.span(
    #            HTML.img(
    #                width=16,
    #                height=16,
    #                src=data_url(icon('s' + color[1:]))),
    #            HTML.span(label, style='padding-left:5px'),
    #            style='padding-left:5px')
    #    items = [make_item(n, c) for n, c in ROCKSOURCETYPES.items()]
    #    yield Legend(self, 'rock types', items)

def includeme(config):
    config.register_map('languages', ArtefactsMap)
    config.register_map('rocksources', SourcesMap)


#!/usr/bin/env python3

def get_items_with_single_quotes(line):
  if type(line) is str:
    line = line.split(',')
  N = len(line)
  indices = []
  for j in range(N):
    if line[j].count('"')  == 1:
      indices.append( j )
  if indices == []:
    return
  else:
    return indices

def fix_line(line):
  inds = get_items_with_single_quotes(line)
  spline = line.split(',')
  while inds:
    upper = inds.pop()
    lower = inds.pop()
    good_str = ''.join(line.split(',')[lower:upper+1])
    spline = spline[:lower]+ [good_str] + spline[upper:]
  return ','.join(spline)

f = open('Ultrasil_SOI_Inventory.txt','r').readlines()
fixed = open('Ultrasil_SOI_Inventory.fixed.txt','w')
fixed_list = []
for line in f:
  fixed_list.append(fix_line(line))

for line in fixed_list:
  fixed.write(line)

fixed.close()


#!/usr/bin/env python

import xml.etree.ElementTree as ET
from time import sleep

from canari.maltego.entities import IPv4Address
from canari.framework import configure
from common.entities import paThreat
from common import pamod

__author__ = 'bostonlink'
__copyright__ = 'Copyright 2012, Pamalt_canari Project'
__credits__ = []

__license__ = 'GPL'
__version__ = '0.1'
__maintainer__ = 'bostonlink'
__email__ = 'bostonlink@pentest-labs.org'
__status__ = 'Development'

__all__ = [
    'dotransform',
    'onterminate'
]

@configure(
    label='To IP Source [PaloAlto]',
    description='Returns PaloAlto IP source entities associated with the PaloAlto threat',
    uuids=[ 'pamalt_canari.v2.paMaltThreatToIPsrc' ],
    inputs=[ ( 'PaloAlto', paThreat ) ],
    debug=False
)

def dotransform(request, response):

    # Check PAN Authentication AND KEY
    key = pamod.get_login()

    # Create and submit the query to the API and return the jobid
    tid = request.fields['tid']

    query = '(threatid eq %s)' % (tid)
    jobid = pamod.pa_log_query('threat', key, query)
    sleep(5)

    # Loop function to check if the log query job is done
    root = ET.fromstring(pamod.pa_log_get(jobid, key))
    for status in root.findall(".//job/status"):
        while status.text == 'ACT':
            sleep(5)
            root = ET.fromstring(pamod.pa_log_get(jobid, key))
            for status in root.findall(".//job/status"):
                if status.text == 'FIN':
                    break

    # parse the log data and create dictionaries stored in a list for each individual log
    log_list = []
    for entry in root.findall(".//log/logs/entry"):
        entry_dic = {}
        for data in entry:
            entry_dic[data.tag] = data.text

        log_list.append(entry_dic)

    # Create the Maltego Entity
    ip_list = []
    for d in log_list:
        if d['src'] not in ip_list:
            response += IPv4Address(
                d['src'],
                tid=d['tid'],
                ipsrc=d['dst'],
            )
            ip_list.append(d['src'])

    return response


from __future__ import absolute_import
from flask import request
from flask.json import JSONEncoder
import six
from decimal import Decimal
from .util import PrettyDecimal

if six.PY3:
    unicode = str

class IterableEncoder(JSONEncoder):
    def default(self, o):
        try:
            iterator = iter(o)
        except TypeError:
            pass
        else:
            return list(o)
        return super(IterableEncoder, self).default(o)

class PrivateJsonEncoder(JSONEncoder):
    def default(self, o):
        if hasattr(o, '_json'):
            try:
                extended = request.json_extended
            except AttributeError:
                extended = request.args.get('extended', False)
            # request.json_extended can be a dict to set extended mode for only
            # certain types of objects
            if isinstance(extended, dict):
                scope_class = object
                scope_extended = False
                for cls, ext in six.iteritems(extended):
                    if isinstance(o, cls) and issubclass(type(o), scope_class):
                        scope_extended = ext
                        scope_class = cls
                extended = scope_extended
            return o._json(extended)
        return super(PrivateJsonEncoder, self).default(o)

class DecimalEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, PrettyDecimal):
            return o.currency()
        elif isinstance(o, Decimal):
            return unicode(o)
        return super(DecimalEncoder, self).default(o)

# Multiple inheritance FTW
class SRPEncoder(PrivateJsonEncoder, IterableEncoder, DecimalEncoder):
    pass


# -*- coding: cp936 -*-
import urllib
import urllib2
import  re
import  xlwt
import  xlrd

import random
import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

class GetIdNumber():

    @classmethod
    def Idnumber(self):
        url = "http://www.quanshuwang.com/book/0/269/32229420.html"
        request = urllib2.Request(url)
        response = urllib2.urlopen(request)
        a=response.read()
        a=a.decode('gbk')
        # print(a)
        # print(type(a))

        # for i in range(1,10):
        #     a=random.randint(10,20)
        # #     print a
        # pattern = re.compile('\d+')
        # res = re.findall(pattern, a)
        # pattern = re.compile("   &nbsp" +'.*? '+"
")
        reg=r'</script>    (.*?)


"""Views for checking access."""
from django.views.generic import View
from django.shortcuts import render
from granted.managers import user_manager, resource_manager, action_type_manager, access_manager

class CheckAccessView(View):

    def __init__(self):
        """Init Method."""
        self.user_manager = user_manager.UserManager()
        self.resource_manager = resource_manager.ResourceManager()
        self.action_type_manager = action_type_manager.ActionTypeManager()
        self.access_manager = access_manager.AccessManager()
        super(CheckAccessView, self).__init__()

    def get(self, request):
        """Method to get the user, resources and access type for view."""
        """Getting the request params."""
        user_id = request.GET.get('user_id')
        resource_id = request.GET.get('resource_id')
        action_type_id = request.GET.get('action_type_id')
        """Computing the access status."""
        access_status = None
        if user_id and resource_id and action_type_id:
            access_status = self.access_manager.does_user_have_access_for_resource_and_type(
                user_id=user_id, resource_id=resource_id, action_type_id=action_type_id
            )
        """Constructing the payload."""
        payload = {
            'users': self.user_manager.load_chunk(),
            'resources': self.resource_manager.load_chunk(),
            'action_types': self.action_type_manager.load_chunk(),
            'access_status': access_status
        }

        return render(request, 'check_access.html', payload)


# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector

from model.lotto_item import LotteryItem

'''
crawl matches' big data
'''

class Lottery_Spider(scrapy.Spider):
    name = "Lottery_Spider"
    allowed_domains = ["163.com"]
    start_urls = (
        'http://trend.caipiao.163.com/dlt/?periodNumber=100',
    )

    custom_settings = {
        'ITEM_PIPELINES': {'app.lottery_pipelines.LotteryPipeline': 201}
    }

    def load_ball(self, sel):
        item = LotteryItem()
        try:
            lottery_num = str(sel.xpath('./@data-period').extract()[0])
        except:
            lottery_num = "000"
        item["lotteryNum"] = lottery_num
        ballList = sel.xpath('./td[@class!="f_red" and @class!="f_blue"]/text()').extract()
        if len(ballList) == 7:
            item["red1"] = str(ballList[0])
            item["red2"] = str(ballList[1])
            item["red3"] = str(ballList[2])
            item["red4"] = str(ballList[3])
            item["red5"] = str(ballList[4])
            item["blue1"] = str(ballList[5])
            item["blue2"] = str(ballList[6])
        return item

    def parse(self, response):
        sel = Selector(response)
        lottery_balls = sel.xpath('//div[@id="dataWrap"]/table[@id="chartsTable"]/tbody[@id="cpdata"]/tr')
        for sel in lottery_balls:
            item = self.load_ball(sel)
            yield item


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 11:25:57 2019

@author: yolandatiao
"""

########## Collect count files ##########
# Author: Huitian (Yolanda) Diao
# Apr 30, 2019
# Dependencies:
# - HTseq-count output count files
# - DEseq2

########## Import ##########
import os
import csv
import glob
from astropy.io import ascii

########## Self defined functions ##########
def CompileTables(wkDir, outName, colN):
    filelist=[]
    for root, dirs, files in os.walk(wkDir):
        for file in files:
            if not file.startswith("._"):
                if file.endswith("GN.csv"):
                    filelist.append(os.path.join(root, file))
    fnames = [x.split("/")[-1].replace(".csv", "").replace("_addGN", "") for x in filelist]
    print(fnames)

    with open(outName, "w") as fout:
        wfout = csv.writer(fout, delimiter=",")
        header = ["transcript", "gene_name"] + fnames
        wfout.writerow(header)
        #print(header)
        finlist = []
        rfinlist = []
        for x in range(0, len(filelist)):
            finlist.append(open(filelist[x], "r"))
        for x in range(0, len(filelist)):
            rfinlist.append(csv.reader(finlist[x], delimiter=","))
        for x in range(0, len(filelist)):
            #print(x)
            next(rfinlist[x])
        for row in rfinlist[0]:
            newrow = [row[0], row[7], row[colN]]
            for x in range(1, len(filelist)):
                newrow.append(next(rfinlist[x])[colN])
            wfout.writerow(newrow)

def fltTables(fileList, sltFile, cutoff, direction, apdx):
    keepRows = []
    totalRowN = 0
    with open(sltFile, "r") as fin:
        rfin = csv.reader(fin, delimiter=",")
        next(rfin)
        rowN = 0
        for row in rfin:
            rowN += 1
            rowNumbers = row[1:]
            rowNumbers = [float(x) for x in rowNumbers if x!="NA"]
            if rowNumbers != []:
                if direction == "more":
                    if max(rowNumbers) >= cutoff:
                        keepRows.append(rowN)
                elif direction == "less":
                    if min(rowNumbers) <= cutoff:
                        keepRows.append(rowN)
                elif direction == "abs_more":
                    rowNumbers = [abs(x) for x in rowNumbers]
                    if max(rowNumbers) >= cutoff:
                        keepRows.append(rowN)
        totalRowN = rowN
    for f in fileList:
        outName = f.replace(".csv", "_%s-c%s.csv"%(apdx, cutoff))
        with open(f, "r") as fin:
            with open(outName, "w") as fout:
                rfin = csv.reader(fin, delimiter=",")
                wfout = csv.writer(fout, delimiter=",")
                wfout.writerow(next(rfin))
                rowN = 0
                for row in rfin:
                    rowN += 1
                    if rowN in keepRows:
                        wfout.writerow(row)
    print("Total row number: %s" %totalRowN)
    print("Kept row number: %s" %len(keepRows))
    print("Kept percentage: %s percent" %str(float(len(keepRows))/totalRowN*100))

def fltDEseqOut(fileX, log2fcC, pvalC, padjC, updn):
    outName = fileX.replace(".csv", "_log2fc-c%s-%s_pval-c%s_padj-c%s.csv"%(log2fcC, updn, pvalC, padjC))
    with open(fileX, "r") as fin:
        with open(outName, "w") as fout:
            rfin = csv.reader(fin, delimiter=",")
            wfout = csv.writer(fout, delimiter=",")
            wfout.writerow(next(rfin))
            for row in rfin:
                nu_row = row
                if row[2] == "NA":
                    nu_row[2] = 0
                if row[5] == "NA":
                    nu_row[5] = 1
                if row[6] == "NA":
                    nu_row[6] = 1
                if log2fcC == "NA" or (log2fcC != "NA" and updn == "up" and float(nu_row[2]) > log2fcC) or (log2fcC != "NA" and updn == "dn" and float(nu_row[2]) < log2fcC):
                    if pvalC == "NA" or (pvalC != "NA" and float(nu_row[5]) <= pvalC):
                        if padjC == "NA" or (padjC != "NA" and float(nu_row[6]) <= padjC):
                            wfout.writerow(row)

########## Main ##########
###----- Compile DE-seq2 results
wk_dir = "/Volumes/Yolanda/Exp337CD25KONascent/3_DE-seq/1_compiled"
os.chdir(wk_dir)

DEseq2out_dir = "/Volumes/Yolanda/Exp337CD25KONascent/3_DE-seq/0.1_original_GN/dupr"
CompileTables(DEseq2out_dir, "dupr_DEseq_pval.csv", 5)
CompileTables(DEseq2out_dir, "dupr_DEseq_padj.csv", 6)
CompileTables(DEseq2out_dir, "dupr_DEseq_log2fc.csv", 2)
CompileTables(DEseq2out_dir, "dupr_DEseq_baseMean.csv", 1)

DEseq2out_dir = "/Volumes/Yolanda/Exp337CD25KONascent/3_DE-seq/0.1_original_GN/nondupr"
CompileTables(DEseq2out_dir, "nondupr_DEseq_pval.csv", 5)
CompileTables(DEseq2out_dir, "nondupr_DEseq_padj.csv", 6)
CompileTables(DEseq2out_dir, "nondupr_DEseq_log2fc.csv", 2)
CompileTables(DEseq2out_dir, "nondupr_DEseq_baseMean.csv", 1)

###----- Filter Compiled outputs
wk_dir = "/Volumes/EXP337/Exp337CD25KONascent/3_DE-seq/1_Compiled_out"
os.chdir(wk_dir)

file_list = ["DEseq_baseMean.csv", "DEseq_log2fc.csv", "DEseq_padj.csv", "DEseq_pval.csv"]
fltTables(file_list, "DEseq_padj.csv", 0.05, "less", "padj")

file_list = ["DEseq_baseMean.csv", "DEseq_log2fc.csv", "DEseq_padj.csv", "DEseq_pval.csv"]
fltTables(file_list, "DEseq_pval.csv", 0.05, "less", "pval")

file_list = ["DEseq_baseMean.csv", "DEseq_log2fc.csv", "DEseq_padj.csv", "DEseq_pval.csv"]
fltTables(file_list, "DEseq_log2fc.csv", 1, "abs_more", "log2fc")

file_list = ["DEseq_baseMean.csv", "DEseq_log2fc.csv", "DEseq_padj.csv", "DEseq_pval.csv"]
fltTables(file_list, "DEseq_log2fc.csv", 2, "abs_more", "log2fc")

file_list = ["DEseq_baseMean_log2fc-c1.csv", "DEseq_log2fc_log2fc-c1.csv",
             "DEseq_padj_log2fc-c1.csv", "DEseq_pval_log2fc-c1.csv"]
fltTables(file_list,  "DEseq_pval_log2fc-c1.csv", 0.05, "less", "log2fc")

###----- Filter each file
wk_dir = "/Volumes/EXP337/Exp337CD25KONascent/3_DE-seq/DEseq2_out"
os.chdir(wk_dir)

for file in glob.glob("*h.csv"):
    fltDEseqOut(file, 0, 0.05, "NA", "up")
    fltDEseqOut(file, 0, 0.05, "NA", "dn")
    fltDEseqOut(file, 0, "NA", 0.05, "up")
    fltDEseqOut(file, 0, "NA", 0.05, "dn")


from django import forms
class ContactForm(forms.Form):
    name = forms.CharField(label="Nombre", required=True, widget=forms.TextInput(
        attrs={'class':'form-control', 'placeholder':'Escribe tu msnsaje'}
    ), min_length=3, max_length=100)
    email = forms.EmailField(label="Email", required=True, widget=forms.EmailInput(
        attrs={'class':'form-control', 'placeholder':'Escribe tu msnsaje'}
    ), min_length=3, max_length=100)
    content = forms.CharField(label="contenido", required=True, widget=forms.Textarea(
        attrs={'class':'form-control', 'row': 3, 'placeholder':'Escribe tu msnsaje'}
    ), min_length=10, max_length=1000)

    fecha = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=forms.DateTimeInput(attrs={
            'class': 'form-control datetimepicker-input',
            'data-target': '#datetimepicker1'
        }))


# -*- coding: utf-8 -*-
#:-------------------------------------------------------------------------------------------------------------
#:
#:
#:								     Equi-biaxial Computation
#:
#:
#:--------------------------------------------------------------------------------------------------------------

# Defining elasticity and deleting plasticity

elastic = Elastic( eType = 'orthotropic')
'''
plastic = Plastic( pType = 'none')
mdb = material_config(mdb, elastic, plastic)

# Set random elastic computation

EquTest = Test( name = 'EL_Rand', test_type = 'Equ', loading_type =  loading_type)
EquTest.setEqu( loading = F_random )

Equ_EL_Rand_JobName = EL_Compute(mdb, EquTest, EL_Job, alpha, odbSrc)

KI, KII, Keq  = K_nominaux_Extraction(odbSrc, Equ_EL_Rand_JobName)

# Set normalized elastic computation

F_norm = F_random * sqrt(1000) / KI
print 'F normalized = ', F_norm

EquTest = Test( name = 'EL_Norm', test_type = 'Equ', loading_type =  loading_type)
EquTest.loading = F_norm

Equ_EL_Norm_JobName = EL_Compute(mdb, EquTest, EL_Job, alpha, odbSrc)

KI, KII, Keq  = K_nominaux_Extraction(odbSrc, Equ_EL_Norm_JobName)

# Defining plasticity
'''
plastic = Plastic(pType = 'combined-hardening')
mdb = material_config(mdb, elastic, plastic)
'''
# Set monotonic plastic computation

EquTest = Test( name = 'PL', test_type = 'Equ', loading_type =  loading_type)
EquTest.setEqu( loading = F_norm , Kmin = Kmin_Equ, Kmax = Kmax_Equ)

Equ_Mon_PL_JobName, Kmin_Equ, Kmax_Equ = PL_Compute(mdb, EquTest, PL_Mon_Job, alpha, odbSrc)
'''

# Set cyclic plastic computation

F_norm = Job.Equ.EL.Norm_Force

EquTest = Test( name = 'PL', test_type = 'Equ', loading_type =  loading_type)
EquTest.setEqu( loading = F_norm , Kmin = Kmin_Equ, Kmax = Kmax_Equ)

Equ_Cyc_PL_JobName = Cyclic_Computation(mdb, EquTest, PL_Cyc_Job, alpha, odbSrc)

# Saving Job parameters:
'''
Job.Equ.EL.Name = Equ_EL_Norm_JobName
Job.Equ.EL.Norm_Force = F_norm
Job.Equ.PL.MonName = Equ_Mon_PL_JobName
'''
Job.Equ.PL.CycName = Equ_Cyc_PL_JobName
Job.Equ.PL.CycForce = F_norm
Job.Equ.PL.CycKmin = Kmin_Equ
Job.Equ.PL.CycKmax = Kmax_Equ


import setuptools

with open('README.md') as f:
    long_description = f.read()

setuptools.setup(
    name='yapdfminer',
    use_scm_version=True,
    description='PDF parser and analyzer',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/eladkehat/yapdfminer',
    author='Elad Kehat',
    author_email='eladkehat@gmail.com',
    license='MIT',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.7',
        'Topic :: Text Processing',
    ],
    keywords=[
        'pdf',
        'pdf parser',
        'pdf converter',
        'layout analysis',
        'text mining',
    ],
    packages=setuptools.find_packages(exclude=['cmaprsrc', 'docs', 'samples', 'tests']),
    include_package_data=True,
    python_requires='>=3.7',
    install_requires=[
        'chardet ~= 3.0',
        'Pillow ~= 6.0',
        'pycryptodome ~= 3.8',
        'sortedcontainers ~= 2.1',
    ],
    setup_requires=['setuptools_scm'],
    scripts=[
        'tools/pdf2txt.py',
        'tools/dumppdf.py',
        'tools/latin2ascii.py',
    ]
)


import subprocess

import os

from core.utils.Executor import _convert_subprocess_cmd, pidof

def check_environment() -> bool:
    __opam_env__ = [
        'CAML_LD_LIBRARY_PATH',
        'MANPATH',
        'PERL5LIB',
        'OCAML_TOPLEVEL_PATH',
        'PATH'
    ]

    for var in __opam_env__:
        if not os.environ.get(var, None):
            return False

    PATH = os.environ.get('PATH')

    try:
        OCAML_VERSION = subprocess.check_output(
           _convert_subprocess_cmd('ocaml -vnum')
        ).decode('utf-8').strip()

    except subprocess.CalledProcessError:
        return False

    for path in PATH.split(':'):
        if path.endswith(
            os.path.join('.opam', 'system', 'bin')
        ) or path.endswith(
            os.path.join('.opam', OCAML_VERSION, 'bin')
        ):
            return True

def check_mirage() -> bool:
    try:
        subprocess.check_output(
            _convert_subprocess_cmd('which mirage')
        )

    except subprocess.CalledProcessError:
        return False
    else:
        return True

def check_redis_server() -> bool:
    try:
        pidof('redis-server')

    except subprocess.CalledProcessError as e:
        return False
    else:
        return True

def check_redis_queue() -> bool:
    try:
        out = subprocess.check_output(
            _convert_subprocess_cmd('rq info')
        ).decode('utf-8')

    except FileNotFoundError as e:
        return False
    else:
        if '0 workers' in out:
            return False

        return True

def is_root() -> bool:
    # Get the effective user id
    if os.geteuid() == 0:
        return True
    else:
        return False


from typing import Union
from typing import Optional
from datetime import datetime

from numpy import ndarray

def get_l2_chunk_children(
    graph_id: int, chunk_id: int, timestamp: datetime, flatten: Optional[bool] = False
) -> Union[ndarray, dict]:
    from numpy import array
    from numpy import uint64
    from pychunkedgraph.graph.attributes import Hierarchy
    from ..utils import get_cg

    cg = get_cg(graph_id)
    chunk_id = uint64(chunk_id)
    chunk_layer = cg.get_chunk_layer(chunk_id)
    assert chunk_layer == 2, f"Chunk layer must be 2, got {chunk_layer}"

    rr_chunk = cg.range_read_chunk(
        chunk_id, properties=Hierarchy.Child, time_stamp=timestamp
    )

    if flatten:
        l2_chunk_array = []
        for l2 in rr_chunk:
            svs = rr_chunk[l2][0].value
            for sv in svs:
                l2_chunk_array.extend([l2, sv])
        return array(l2_chunk_array)
    else:
        l2_chunk_dict = {}
        for k in rr_chunk:
            l2_chunk_dict[k] = rr_chunk[k][0].value
        return l2_chunk_dict


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

from Libs.FrameHandle.TimerItemBase import TimerItemBase;

'''
@brief 倒计时定时器
'''

class DaoJiShiTimer(TimerItemBase):

    def __init__(self):
        super(DaoJiShiTimer, self).__init__();

        self.mTypeId = "DaoJiShiTimer";

    def setTotalTime(self, value):
        super(DaoJiShiTimer, self).setTotalTime(value);
        self.m_curRunTime = value;

    def getRunTime(self):
        return self.m_totalTime - self.m_curRunTime;

    # 如果要获取剩余的倒计时时间，使用 getLeftCallTime
    def getLeftRunTime(self):
        return self.m_curRunTime;

    def OnTimer(self, delta):
        if (self.m_disposed):
            return;

        self.m_curRunTime -= delta;
        if(self.m_curRunTime < 0):
            self.m_curRunTime = 0;

        self.m_intervalLeftTime += delta;

        if (self.m_bInfineLoop):
            self.checkAndDisp();
        else:
            if (self.m_curRunTime <= 0):
                self.disposeAndDisp();
            else:
                self.checkAndDisp();

    def reset(self):
        self.m_curRunTime = self.m_totalTime;
        self.m_curCallTime = 0;
        self.m_intervalLeftTime = 0;
        self.m_disposed = False;


# -*- coding: utf-8 -*-
"""Functions to sample sktime datasets.

Used in experiments to get deterministic resamples.
"""

import numpy as np
import pandas as pd
import sklearn.utils

def stratified_resample(X_train, y_train, X_test, y_test, random_state):
    """Stratified resample data without replacement using a random state.

    Reproducable resampling. Combines train and test, resamples to get the same class
    distribution, then returns new train and test.

    Parameters
    ----------
    X_train : pd.DataFrame
        train data attributes in sktime pandas format.
    y_train : np.array
        train data class labels.
    X_test : pd.DataFrame
        test data attributes in sktime pandas format.
    y_test : np.array
        test data class labes as np array.
    random_state : int
        seed to enable reproducable resamples
    Returns
    -------
    new train and test attributes and class labels.
    """
    all_labels = np.concatenate((y_train, y_test), axis=None)
    all_data = pd.concat([X_train, X_test])
    random_state = sklearn.utils.check_random_state(random_state)
    # count class occurrences
    unique_train, counts_train = np.unique(y_train, return_counts=True)
    unique_test, counts_test = np.unique(y_test, return_counts=True)
    assert list(unique_train) == list(
        unique_test
    )  # haven't built functionality to deal with classes that exist in
    # test but not in train
    # prepare outputs
    X_train = pd.DataFrame()
    y_train = np.array([])
    X_test = pd.DataFrame()
    y_test = np.array([])
    # for each class
    for label_index in range(0, len(unique_train)):
        # derive how many instances of this class from the counts
        num_instances = counts_train[label_index]
        # get the indices of all instances with this class label
        label = unique_train[label_index]
        indices = np.where(all_labels == label)[0]
        # shuffle them
        random_state.shuffle(indices)
        # take the first lot of instances for train, remainder for test
        train_indices = indices[0:num_instances]
        test_indices = indices[num_instances:]
        del indices  # just to make sure it's not used!
        # extract data from corresponding indices
        train_instances = all_data.iloc[train_indices, :]
        test_instances = all_data.iloc[test_indices, :]
        train_labels = all_labels[train_indices]
        test_labels = all_labels[test_indices]
        # concat onto current data from previous loop iterations
        X_train = pd.concat([X_train, train_instances])
        X_test = pd.concat([X_test, test_instances])
        y_train = np.concatenate([y_train, train_labels], axis=None)
        y_test = np.concatenate([y_test, test_labels], axis=None)
    # get the counts of the new train and test resample
    unique_train_new, counts_train_new = np.unique(y_train, return_counts=True)
    unique_test_new, counts_test_new = np.unique(y_test, return_counts=True)
    # make sure they match the original distribution of data
    assert list(counts_train_new) == list(counts_train)
    assert list(counts_test_new) == list(counts_test)
    return X_train, y_train, X_test, y_test


# multiple players

import unittest

from game import Game

class TestFeatureThree(unittest.TestCase):
        def test_play_order(self):
                game = Game()
                game.new_game(2)
                order = game.playorder() # order is an iterable that can be given to, for example, itertools.cycle
                self.assertEqual(len(order), 2)
                self.assertIn(0, order)
                self.assertIn(1, order)


"""

CS228: Human Computer Interaction

Deliverable 5: Drawing skeletons of hands with pyGame and LeapMotion

"""

import os
import shutil

from Del05 import Capture_Hands

def make_directory(pathway):
    try:
        shutil.rmtree(pathway)
        os.makedirs(pathway)
    except OSError:
        if not os.path.isdir(pathway):
            raise

make_directory("userData")

Hand_Captue_Class = Capture_Hands()
print("Initializing Hand Capture: Please engage the LeapMotion Device")
Hand_Captue_Class.Run_Forever()
print("Hand capture session has ended")


from flask import request
from flask_restful import Resource
from database import db

class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Role: {name}>'.format(name=self.name)

class RoleList(Resource):
    def get(self):
        roles = Role.query.all()
        role_info_list = []
        for role in roles:
            role_info = dict()

            role_info['id'] = role.id
            role_info['name'] = role.name

            role_info_list.append(role_info)

        return {'roles': role_info_list}

    def post(self):
        role = Role(
            name=request.form.get('name')
        )
        db.session.add(role)
        db.session.commit()
        return {
            "id": role.id,
        }


#!/usr/bin/python3

import math
import cmath

a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))

x1 = x2 = 0

if a == 0:
    if b == 0:
        x1 = x2 = - c
    else:
        x1 = x2 = -c / b
else:
    d = b**2 - 4*a*c
    if d < 0:
        x1 = (- b + 0j * cmath.sqrt(d)) / (2 * a)
        x2 = (- b - 0j * cmath.sqrt(d)) / (2 * a)
    elif d > 0:
        x1 = (-b + math.sqrt(d)) / (2 * a)
        x2 = (-b - math.sqrt(d)) / (2 * a)
    else:
        x1 = x2 = -b / (2 * a)

print("x1: " + str(x1))
print("x2: " + str(x2))


import pytest
from affordable_leggins.leggins_list import find_size

AVAILABLE_SIZES = ["XXS", "XS", "S", "M", "L", "XL", "XXL"]

@pytest.mark.vcr()
def test_find_size():
    leggin_id = "12068050"
    assert find_size(leggin_id) == AVAILABLE_SIZES

@pytest.mark.vcr()
def test_find_one_limited_size():
    leggin_other_id = "12605008"
    assert find_size(leggin_other_id) == ["L", "XXL"]

@pytest.mark.vcr()
def test_find_no_size():
    leggin_id = "0"
    assert find_size(leggin_id) is None


from random import randint
def Quickselect(lst,left,right,K):
    if(left==right):
        return(lst[left])
    pos=partition(lst,left,right)
    if(pos==K-1):
        return(lst[pos])
    elif(pos>=K):
        return(Quickselect(lst,left,pos-1,K))
    return(Quickselect(lst,pos+1,right,K))
def partition(lst,left,right):
    pivot=lst[right]
    i=left
    for j in range(left,right):
        if(lst[j]<pivot):
            lst[j],lst[i]=lst[i],lst[j]
            i+=1
    lst[right],lst[i]=lst[i],lst[right]
    return(i)
def main():
    lst=[]
    for _ in range(10):
        lst.append(randint(1,100))
    #lst=list(map(int,input().split()))
    K=int(input())
    print(Quickselect(lst,0,len(lst)-1,K))
main()


import requests, re, json, urllib

def cat():
    url = 'http://random.cat/meow'
    r = requests.get(url)
    x = json.loads(r.text)
    link = x['file']
    ext = link.split('.')[-1]
    extreturn = 'kot.' + ext
    urllib.urlretrieve(link, extreturn)
    return extreturn


from django.conf import settings
from django.contrib import admin
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.urlresolvers import reverse, NoReverseMatch
from django.db.models import Model
from django.template import (Context, Node, TextNode, NodeList, FilterExpression,
    Template, TemplateSyntaxError)
from django.template.defaultfilters import truncatewords_html
from django.template.loader import get_template, Template
from django.template.loader_tags import BlockNode
from django.utils.html import strip_tags
from django.utils.safestring import mark_safe
from django.utils.simplejson import loads
from django.utils.text import capfirst
from mezzanine import template
from mezzanine.clevercss import convert as ccss_convert
from mezzanine.core.forms import get_edit_form
from mezzanine.utils.html import decode_entities
from mezzanine.utils.urls import admin_url
from mezzanine.utils.views import is_editable
from urllib import urlopen, urlencode
from uuid import uuid4
import os

register = template.Library()

@register.render_tag
def set_short_url_for(context, token):
    """
    Sets the ``short_url`` attribute of the given model using the bit.ly
    credentials if they have been specified and saves it.
    """
    obj = context[token.split_contents()[1]]
    request = context["request"]
    if getattr(obj, "short_url") is None:
        obj.short_url = request.build_absolute_uri(request.path)
        settings = context["request"].settings
        args = {
            "login": settings.BLOG_BITLY_USER,
            "apiKey": settings.BLOG_BITLY_KEY,
            "longUrl": obj.short_url,
        }
        if args["login"] and args["apiKey"]:
            url = "http://api.bit.ly/v3/shorten?%s" % urlencode(args)
            response = loads(urlopen(url).read())
            if response["status_code"] == 200:
                obj.short_url = response["data"]["url"]
                obj.save()
    return ""

@register.to_end_tag
def metablock(context, nodelist):
    """
    Remove HTML tags, entities and superfluous characters from meta blocks.
    """
    parsed = nodelist.render(context)
    parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",")
    return strip_tags(decode_entities(parsed))

@register.inclusion_tag("includes/pagination.html", takes_context=True)
def pagination_for(context, current_page):
    """
    Include the pagination template and data for persisting querystring in
    pagination links.
    """
    querystring = context["request"].GET.copy()
    if "page" in querystring:
        del querystring["page"]
    querystring = querystring.urlencode()
    return {"current_page": current_page, "querystring": querystring}

@register.simple_tag
def thumbnail(image_url, width, height):
    """
    Given the url to an image, resizes the image using the given width and
    height on the first time it is requested, and returns the url to the new
    resized image. if width or height are zero then original ratio is
    maintained.
    """

    image_url = unicode(image_url)
    image_path = os.path.join(settings.MEDIA_ROOT, image_url)
    image_dir, image_name = os.path.split(image_path)
    thumb_name = "%s-%sx%s.jpg" % (os.path.splitext(image_name)[0], width, height)
    thumb_path = os.path.join(image_dir, thumb_name)
    thumb_url = "%s/%s" % (os.path.dirname(image_url), thumb_name)

    # abort if thumbnail exists, original image doesn't exist, invalid width or
    # height are given, or PIL not installed
    if not image_url:
        return ""
    if os.path.exists(thumb_path):
        return thumb_url
    try:
        width = int(width)
        height = int(height)
    except ValueError:
        return image_url
    if not os.path.exists(image_path) or (width == 0 and height == 0):
        return image_url
    try:
        from PIL import Image, ImageOps
    except ImportError:
        return image_url

    # open image, determine ratio if required and resize/crop/save
    image = Image.open(image_path)
    if width == 0:
        width = image.size[0] * height / image.size[1]
    elif height == 0:
        height = image.size[1] * width / image.size[0]
    if image.mode not in ("L", "RGB"):
        image = image.convert("RGB")
    try:
        image = ImageOps.fit(image, (width, height), Image.ANTIALIAS).save(
            thumb_path, "JPEG", quality=100)
    except:
        return image_url
    return thumb_url

@register.inclusion_tag("admin/includes/editable_loader.html", takes_context=True)
def editable_loader(context):
    """
    Set up the required JS/CSS for the in-line editing toolbar and controls.
    """
    t = get_template("admin/includes/editable_toolbar.html")
    context["REDIRECT_FIELD_NAME"] = REDIRECT_FIELD_NAME
    context["toolbar"] = t.render(Context(context))
    return context

@register.to_end_tag
def editable(context, nodelist, token):
    """
    Add the required HTML to the parsed content for in-line editing, such as
    the icon and edit form if the object is deemed to be editable - either it
    has an ``editable`` method which returns True, or the logged in user has
    change permissions for the model.
    """
    def parse_field(field):
        field = field.split(".")
        obj = context[field.pop(0)]
        attr = field.pop()
        while field:
            obj = getattr(obj, field.pop(0))
        return obj, attr

    fields = [parse_field(f) for f in token.split_contents()[1:]]
    if fields:
        fields = [f for f in fields if len(f) == 2 and f[0] is fields[0][0]]
    parsed = nodelist.render(context)
    if not parsed.strip():
        parsed = "".join([unicode(getattr(*field)) for field in fields])
    if fields:
        obj = fields[0][0]
        if isinstance(obj, Model) and is_editable(obj, context["request"]):
            field_names = ",".join([f[1] for f in fields])
            context["form"] = get_edit_form(obj, field_names)
            context["original"] = parsed
            context["uuid"] = uuid4()
            t = get_template("admin/includes/editable_form.html")
            return t.render(Context(context))
    return parsed

@register.simple_tag
def try_url(url_name):
    """
    Mimics Django's ``url`` template tag but fails silently. Used for urls
    in admin templates as these urls won't resolve when admin tests are
    running.
    """
    try:
        url = reverse(url_name)
    except NoReverseMatch:
        return ""
    return url

def admin_app_list(request):
    """
    Adopted from ``django.contrib.admin.sites.AdminSite.index``. Returns a
    list of lists of models grouped and ordered according to
    ``request.settings.ADMIN_MENU_ORDER``. Called from the
    ``admin_dropdown_menu`` template tag as well as the ``app_list``
    dashboard widget.
    """
    app_dict = {}
    menu_order = [(x[0], list(x[1])) for x in request.settings.ADMIN_MENU_ORDER]
    found_items = set()
    for (model, model_admin) in admin.site._registry.items():
        opts = model._meta
        in_menu = not hasattr(model_admin, "in_menu") or model_admin.in_menu()
        if in_menu and request.user.has_module_perms(opts.app_label):
            perms = model_admin.get_model_perms(request)
            admin_url_name = ""
            if perms["change"]:
                admin_url_name = "changelist"
            elif perms["add"]:
                admin_url_name = "add"
            if admin_url_name:
                model_label = "%s.%s" % (opts.app_label, opts.object_name)
                for (name, items) in menu_order:
                    try:
                        index = list(items).index(model_label)
                    except ValueError:
                        pass
                    else:
                        found_items.add(model_label)
                        app_title = name
                        break
                else:
                    index = None
                    app_title = opts.app_label
                model_dict = {
                    "index": index,
                    "perms": model_admin.get_model_perms(request),
                    "name": capfirst(model._meta.verbose_name_plural),
                    "admin_url": admin_url(model, admin_url_name),
                }
                app_title = app_title.title()
                if app_title in app_dict:
                    app_dict[app_title]["models"].append(model_dict)
                else:
                    try:
                        titles = [x[0] for x in
                            request.settings.ADMIN_MENU_ORDER]
                        index = titles.index(app_title)
                    except ValueError:
                        index = None
                    app_dict[app_title] = {
                        "index": index,
                        "name": app_title,
                        "models": [model_dict],
                    }

    for (i, (name, items)) in enumerate(menu_order):
        for unfound_item in set(items) - found_items:
            if isinstance(unfound_item, (list, tuple)):
                item_name, item_url = unfound_item[0], try_url(unfound_item[1])
                if item_url:
                    if name not in app_dict:
                        app_dict[name] = {
                            "index": i,
                            "name": name,
                            "models": [],
                        }
                    app_dict[name]["models"].append({
                        "index": items.index(unfound_item),
                        "perms": {"custom": True},
                        "name": item_name,
                        "admin_url": item_url,
                    })

    app_list = app_dict.values()
    sort = lambda x: x["name"] if x["index"] is None else x["index"]
    for app in app_list:
        app["models"].sort(key=sort)
    app_list.sort(key=sort)
    return app_list

@register.inclusion_tag("admin/includes/dropdown_menu.html", takes_context=True)
def admin_dropdown_menu(context):
    """
    Renders the app list for the admin dropdown menu navigation.
    """
    context["dropdown_menu_app_list"] = admin_app_list(context["request"])
    return context

@register.inclusion_tag("admin/includes/app_list.html", takes_context=True)
def app_list(context):
    """
    Renders the app list for the admin dashboard widget.
    """
    context["dashboard_app_list"] = admin_app_list(context["request"])
    return context

@register.inclusion_tag("admin/includes/recent_actions.html", takes_context=True)
def recent_actions(context):
    """
    Renders the recent actions list for the admin dashboard widget.
    """
    return context

@register.render_tag
def dashboard_column(context, token):
    """
    Takes an index for retrieving the sequence of template tags from
    ``request.settings.DASHBOARD_TAGS`` to render into the admin dashboard.
    """
    column_index = int(token.split_contents()[1])
    output = []
    for tag in context["request"].settings.DASHBOARD_TAGS[column_index]:
        try:
            t = Template("{%% load %s %%}{%% %s %%}" % tuple(tag.split(".")))
            output.append(t.render(Context(context)))
        except TemplateSyntaxError:
            pass
    return "".join(output)

@register.simple_context_tag
def render(context, *args):
    """
    Renders the arguments as a template themselves. This allows for treating
    text obtained from the model as template code.
      {% render page.content %}
    """
    if len(args) == 1:
        return Template(args[0], 'render').render(context)
    bits = []
    for arg in args:
        bits.append(Template(arg, 'render').render(context))
    return mark_safe(u''.join(bits))

@register.simple_context_tag
def rendersummary(context, *args):
    """
    Renders the arguments as a template themselves. This allows for treating
    text obtained from the model as template code.
      {% render page.content %}
    """
    if len(args) == 1:
        return Template(args[0], 'rendersummary').render(context)
    bits = []
    for arg in args:
        bits.append(Template(arg, 'rendersummary').render(context))
    summary = mark_safe(u''.join(bits))
    for end in ("
", "
", "
", "
", "\n", ". "):
        if end in summary:
            summary = summary.split(end)[0] + end
    summary = truncatewords_html(summary, 100)
    return summary

BLOCK_MEDIAS = '__medias__'

class MediasNode(BlockNode):
    def render(self, context):
        context['medias'] = {}
        super(MediasNode, self).render(context)
        return u''

@register.tag
def medias(parser, token):
    bits = token.contents.split()
    if len(bits) != 1:
        raise TemplateSyntaxError("'%s' tag does not take any arguments" % bits[0])
    try:
        if BLOCK_MEDIAS in parser.__loaded_blocks:
            raise TemplateSyntaxError("'%s' tag appears more than once" % bits[0])
        parser.__loaded_blocks.append(BLOCK_MEDIAS)
    except AttributeError: # parser.__loaded_blocks isn't a list yet
        parser.__loaded_blocks = [BLOCK_MEDIAS]
    return MediasNode(BLOCK_MEDIAS, NodeList())

class MediaNode(Node):
    def __init__(self, type, nodelist):
        self.type = type
        self.nodelist = nodelist

    def render(self, context):
        if isinstance(self.type, FilterExpression):
            self.type = self.type.resolve(context)
        value = self.nodelist.render(context)
        medias = context['medias']
        values = medias.get(self.type)
        if values is None:
            medias[self.type] = [value]
        else:
            if value not in values:
                values.append(value)
        return u''

@register.tag
def media(parser, token):
    bits = token.split_contents()
    if bits[0] == 'media':
        if len(bits) != 2:
            raise TemplateSyntaxError("'media' takes one argument (type)")
        type = parser.compile_filter(bits[1])
    else:
        if len(bits) != 1:
            raise TemplateSyntaxError("'%s' does not take arguments" % bits[0])
        type = bits[0]
    nodelist = parser.parse(('end' + bits[0],))
    parser.delete_first_token()
    node = MediaNode(type, nodelist)
    try:
        block = parser.__medias_block
        block.nodelist.append(node)
        return TextNode('')
    except AttributeError:
        pass
    try:
        if BLOCK_MEDIAS in parser.__loaded_blocks:
            return node
        parser.__loaded_blocks.append(BLOCK_MEDIAS)
    except AttributeError:
        parser.__loaded_blocks = [BLOCK_MEDIAS]
    nodelist = NodeList()
    nodelist.contains_nontext = True
    nodelist.append(parser.create_variable_node(parser.compile_filter('block.super')))
    nodelist.append(node)
    block = BlockNode(BLOCK_MEDIAS, nodelist)
    parser.__medias_block = block
    return block

@register.to_end_tag
def ccss(context, nodelist):
    return mark_safe(ccss_convert(nodelist.render(context)))


from collections import defaultdict
from typing import List

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        if endWord not in wordList:
            return 0
        length = len(beginWord)

        dic = defaultdict(set)

        for word in wordList:
            for i in range(length):
                dic[word[:i] + "*" + word[i + 1:]].add(word)

        word_level = {beginWord: 0}
        queue = [beginWord]
        while queue:
            cur = queue.pop(0)
            for i in range(length):
                for word in dic[cur[:i] + "*" + cur[i + 1:]]:
                    if word not in word_level:
                        word_level[word] = word_level[cur] + 1
                        queue.append(word)

                    if word == endWord:
                        return word_level[word] + 1

        return 0

class Solution1(object):
    def __init__(self):
        self.length = 0
        self.dic = defaultdict(set)

    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        if endWord not in wordList:
            return 0
        self.length = len(beginWord)
        for word in wordList:
            for i in range(self.length):
                self.dic[word[:i] + "*" + word[i + 1:]].add(word)

        queue_begin = [(beginWord, 1)]
        queue_end = [(endWord, 1)]
        visited_begin = {beginWord: 1}
        visited_end = {endWord: 1}

        while queue_begin and queue_end:
            ans = self.visit(queue_begin, visited_begin, visited_end)
            if ans:
                return ans
            ans = self.visit(queue_end, visited_end, visited_begin)
            if ans:
                return ans
        return 0

    def visit(self, queue, visited, other_visited):
        cur, level = queue.pop(0)
        for i in range(self.length):
            pattern = cur[:i] + "*" + cur[i + 1:]
            for word in self.dic[pattern]:
                if word in other_visited:
                    return level + other_visited[word]
                if word not in visited:
                    visited[word] = level + 1
                    queue.append((word, level + 1))
        return None

class Solution3:
    def __init__(self):
        self.length = 0
        self.dic = defaultdict(set)

    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        if endWord not in wordList:
            return 0
        self.length = len(beginWord)

        for word in wordList:
            for i in range(self.length):
                self.dic[word[:i] + "*" + word[i + 1:]].add(word)

        word_level_begin = {beginWord: 0}
        queue_begin = [beginWord]

        word_level_end = {endWord: 0}
        queue_end = [endWord]
        while queue_begin and queue_end:
            ans = self.visit(queue_begin, word_level_begin, word_level_end)
            if ans:
                return ans
            ans = self.visit(queue_end, word_level_end, word_level_begin)
            if ans:
                return ans

        return 0

    def visit(self, queue, word_level, other_word_level):
        cur = queue.pop(0)
        for i in range(self.length):
            for word in self.dic[cur[:i] + "*" + cur[i + 1:]]:
                if word not in word_level:
                    word_level[word] = word_level[cur] + 1
                    queue.append(word)
                if word in other_word_level:
                    return word_level[word] + other_word_level[word] + 1
        return None

if __name__ == '__main__':
    beginWord = "hit"
    endWord = "cog"
    wordList = ["hot", "dot", "dog", "lot", "log", "cog"]

    print(Solution3().ladderLength(beginWord, endWord, wordList))


# -*- coding: utf-8 -*-
import numpy as np
from .CalcuDescriptors import CalcuDescriptors
from .AdjacentTensor import AdjacentTensor
from .Fingerprint import Fingerprint
from .VertexMatrix import VertexMatrix
from .Atom_Bond import Atom, Bond
from scipy.sparse import coo_matrix

def PadAdjMat(A1, A2):
    node_num1 = A1.shape[0]
    node_num2 = A2.shape[0]
    pad_A = []
    for i in range(A1.shape[1]):
        adj1_pad = np.pad(A1[:,i,:], ((0, 0), (0, node_num2)), 'constant', constant_values=(0))
        adj2_pad = np.pad(A2[:,i,:], ((0, 0), (node_num1, 0)), 'constant', constant_values=(0))
        pad_A.append(np.concatenate((adj1_pad, adj2_pad), axis=0))
    return np.array(Pad_A)

def combine(l1, l2):
    l = []
    if l1==[] or l2==[]:
        return l
    else:
        for i in l1:
            for j in l2:
                l.append([i, j])
        return l

def AdjMatOfInterMolecularInteraction(NodeNumber, interactions):
    interaction_mat = np.zeros([NodeNumber,1,NodeNumber])
    for act in interactions:
        interaction_mat[act[0],0,act[1]] = 1
        interaction_mat[act[1],0,act[0]] = 1
    return interaction_mat

class Cocrystal(object):

    def __init__(self, coformer1, coformer2):
        self.coformer1 = coformer1
        self.coformer2 = coformer2
        self.node_num1 = len(coformer1.atoms)
        self.node_num2 = len(coformer2.atoms)
        self.NodeNumber = self.node_num1+self.node_num2
        self.name = coformer1.molname+'&'+coformer2.molname

    @property
    def AdjacentTensor(self):
        return AdjacentTensor(self.get_nodes, self.get_edges, self.NodeNumber)

    @property
    def VertexMatrix(self):
        return VertexMatrix(self.get_nodes)

    @property
    def get_nodes(self):
        self.nodes = {}
        for atom_ix1 in self.coformer1.atoms:
            self.nodes.setdefault(atom_ix1, self.coformer1.atoms[atom_ix1])
        for atom_ix2 in self.coformer2.atoms:
            self.nodes.setdefault(atom_ix2+self.node_num1, self.coformer2.atoms[atom_ix2])
        return self.nodes

    @property
    def get_edges(self):
        edges = {}
        edges1 = self.coformer1.get_edges
        for k1 in edges1:
            edges.setdefault(k1, edges1[k1])
        edges2 = self.coformer2.get_edges
        for k2 in edges2:
            edges.setdefault((k2[0]+self.node_num1,k2[1]+self.node_num1), edges2[k2])
        return edges

    def descriptors(self, includeSandP=True, charge_model='eem2015bm'):
        desc1 = self.coformer1.descriptors(includeSandP=includeSandP, charge_model=charge_model)
        desc2 = self.coformer2.descriptors(includeSandP=includeSandP, charge_model=charge_model)
        return np.append(desc1, desc2, axis=0)

    def Fingerprints(self, fp_type='ecfp', **kwargs):
        '''
        fp_type should be one of  the fp set {'avalon', 'ecfp', 'maccs', 'rdkit'} and is case insensitive.
        '''
        fp1_ins = Fingerprint(self.coformer1.rdkit_mol)
        fp2_ins = Fingerprint(self.coformer2.rdkit_mol)
        FP_funcs = {}
        FP_funcs['avalon'] = [getattr(fp1_ins, 'AvalonFP'),getattr(fp2_ins, 'AvalonFP')]
        FP_funcs['ecfp'] = [getattr(fp1_ins, 'ECFP'),getattr(fp2_ins, 'ECFP')]
        FP_funcs['maccs'] = [getattr(fp1_ins, 'MACCSkeysFP'),getattr(fp2_ins, 'MACCSkeysFP')]
        FP_funcs['rdkit'] = [getattr(fp1_ins, 'RDKitFP'),getattr(fp2_ins, 'RDKitFP')]
        fp1 = FP_funcs[fp_type.lower()][0](**kwargs)
        fp2 = FP_funcs[fp_type.lower()][1](**kwargs)
        return np.append(fp1, fp2, axis=0)

    @property
    def possible_hbonds(self):
        # process data for graph-CNN
        d1 = self.coformer1.hbond_donors
        Hs1 = []
        for h1 in d1.values():
            Hs1 = Hs1 + h1
        a1 = self.coformer1.hbond_acceptors

        d2 = self.coformer2.hbond_donors
        Hs2 = []
        for h2 in d2.values():
            Hs2 = Hs2 + h2
        Hs2 = list(np.array(Hs2)+self.node_num1)
        a2 = list(np.array(self.coformer2.hbond_acceptors)+self.node_num1)
        return combine(Hs1,a2) + combine(Hs2,a1)

    @property
    def possible_interaction(self):
        CHs_1 = self.coformer1.get_CHs
        CHs_2 = self.coformer2.get_CHs
        CHs_2 = list(np.array(CHs_2)+self.node_num1)

        A_1 = self.coformer1.hbond_acceptors
        A_2 = list(np.array(self.coformer2.hbond_acceptors)+self.node_num1)

        C_H_A = combine(CHs_1, A_2) + combine(CHs_2, A_1)
        return C_H_A

    @property
    def possible_pipi_stack(self):
        aromatic1 = self.coformer1.aromatic_atoms
        aromatic2 = list(np.array(self.coformer2.aromatic_atoms)+self.node_num1)
        pipi_stack = combine(aromatic1,aromatic2)
        return pipi_stack

    def InteractionTensor(self, hbond=True, pipi_stack=False, contact=False):
        if hbond==False and pipi_stack==False and contact==False:
            return None
        interactions = []
        if hbond:
            hb_adj = AdjMatOfInterMolecularInteraction(self.NodeNumber, self.possible_hbonds)
            interactions.append(hb_adj)
        if pipi_stack:
            pipi_adj = AdjMatOfInterMolecularInteraction(self.NodeNumber, self.possible_pipi_stack)
            interactions.append(pipi_adj)
        if contact:
            contact_adj = AdjMatOfInterMolecularInteraction(self.NodeNumber, self.possible_interaction)
            interactions.append(contact_adj)
        return np.concatenate(interactions, axis=1)

    def CCGraphTensor(self, t_type='OnlyCovalentBond', hbond=True, pipi_stack=False, contact=False):
        t_type_set = {'allfeature','allfeaturebin','isringandconjugated','onlycovalentbond',
                      'withbinbistancematrix','withbondlenth','withdistancematrix'}
        t_type = t_type.lower()
        if t_type not in t_type_set:
            raise ValueError('t_type is case insensitive and should be one of the list :{}'.format(str(list(t_type_set))))
        CCG_ins = AdjacentTensor(self.get_nodes, self.get_edges, self.NodeNumber)
        methods = [i for i in dir(CCG_ins) if '__' not in i]
        methods_dict = {}
        for method in methods:
            methods_dict[method.lower()] = getattr(CCG_ins, method)
        CCG = methods_dict[t_type]()
        t_interaction = self.InteractionTensor(hbond=hbond, pipi_stack=pipi_stack, contact=contact)
        if t_interaction is None:
            return CCG
        else:
            return np.append(CCG, t_interaction, axis=1)

    def COO_CCGraphTensor(self, **kwargs):
        CCG = self.CCGraphTensor(**kwargs)
        coo_CCG = coo_matrix(CCG.sum(axis=1))
        edge_index = [coo_CCG.row, coo_CCG.col]
        edge_attr = CCG[edge_index[0],:,edge_index[1]]
        return edge_index, edge_attr


#-------------------------------------------------------------------------------
# Name:        PyMon_ClientInWindow
# Purpose:     Program to have an easy interface with the embedded monitor
#
# Author:      Legros
#
# Created:     21/03/2021
# Copyright:   (c) Legros 2021
# License:     Private Property
#-------------------------------------------------------------------------------

# graphic interface library
from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext
import tkinter as tk

#For Time stamping of log ========================> Should be deleted or kept to timestamp measurements
from datetime import datetime

#used for delay (in main only)
import time

#used to display a popup telling the file is cleared
import pymsgbox

#queue are used to give access to the message received from network
# (more than only printing on the monitor
from multiprocessing import Queue
queue_in = Queue()

#used for network interface
from threading import Thread
import socket

# ================ > should be deleted
import logging

# ================ > should be deleted
import sys

# ================ > should be deleted
import json

#import regular expression tool to analyse ZIOT response
import re

#import logger object
from PyMon_Logger import Logger

#import result window to show measurements
from PyMon_ResultWindow_V4 import ResultWindow

#import Configuration tools (graphic and saved configuration
from PyMon_ConfigFile import *
# create object to share graph configuration
cg = ConfigGraph()
cf = ConfigFile()
CF_ETHERNET_SECTION="Ethernet"

root = Tk()
root.title('PyMon CLient (ZIOT)')
root.geometry('{}x{}'.format(1300, 550))

left_frame = Frame(root,highlightbackground=cg.WIN_HIGH_LIGHT, highlightthickness=1,
                    bg=cg.LABEL_BACKGROUND, width=160, height=50, pady=3)
left_frame.grid(row=0, column=0, sticky="nw")

# create all of the main containers
root.grid_columnconfigure(1, weight=1)
root.grid_rowconfigure(0, weight=1)

Right_frame = Frame(root, bg=cg.WIN_BACKGROUND,
                    highlightbackground=cg.WIN_HIGH_LIGHT, highlightthickness=1,
                    width=300, height=50, pady=3)
Right_frame.grid(row=0, column=1,sticky="nsew")
Right_frame.grid_columnconfigure(0, weight=1)
Right_frame.grid_rowconfigure(1, weight=1)

# create the widgets for right frame
# =====================================

#create and place logger object
Log_frame = Frame(Right_frame,highlightbackground=cg.WIN_HIGH_LIGHT, highlightthickness=1,
                            bg=cg.LABEL_BACKGROUND, height=50, pady=3)
Log_frame.grid(row=0,column=0,padx = 10, columnspan=2, sticky="w")
logger = Logger(Log_frame, "Monitor")

# Output Trace Window
# --------------------
output_area = scrolledtext.ScrolledText(Right_frame,
                                      width = 70,
                                      height = 10,
                                      bg = cg.TRACE_BACKGROUND,
                                      font = ("Courier",10))

output_area.grid(row=1, column=0, columnspan =2, pady = 15, padx = 10, sticky="nsew")
output_area.grid_columnconfigure(0, weight=1)
output_area.grid_rowconfigure(0, weight=1)

# input enter Window
# --------------------
IP_label = Label(Right_frame, fg = cg.WIN_FOREGROUND, bg = cg.WIN_BACKGROUND, text='Manual command :')
IP_label.grid(row=3, column=0,pady = 0, padx = 10, sticky="nw")

def input_area_enter(event):
#    global LogComm
    CmdLine = input_area.get(1.0, END) # input cmd from read
    CmdLine = CmdLine.replace("\n","") # supress \n for start of line
    input_area.delete(1.0,END)         # delete input zone
    # Output cmd to TRACE
##    output_send("{"+CmdLine+"}", MSG_TYPE_SEND)
    output_queue.put_nowait(("{"+CmdLine+"}", MSG_TYPE_SEND))

    MyTCP_SendToServer(CmdLine)

input_area = scrolledtext.ScrolledText(Right_frame,
                                      width = 50,
                                      height = 2,
                                      bg = cg.CMD_BACKGROUND,
                                      foreground='blue',
                                      font = ("Courier",10))

input_area.grid(row=4, column=0, pady = 10, padx = 10, sticky="ew",)
input_area.grid_columnconfigure(0, weight=1)
input_area.bind('<Return>',input_area_enter)

MSG_TYPE_ACTION  = 0
MSG_TYPE_SEND    = 1
MSG_TYPE_RECEIVE = 2

# Output cmd to TRACE
def output_send(msg, msg_type):
    logger.save(msg)               #log the cmd received
    if msg_type==MSG_TYPE_ACTION:
        output_area.configure(state ='normal')
        output_area. insert(END,"#"+msg+'\n','ACTION_COLOR')
        output_area.tag_config('ACTION_COLOR', foreground='green')
        output_area.see("end")
        output_area.configure(state ='disabled')
    elif msg_type==MSG_TYPE_SEND:
        output_area.configure(state ='normal')
        output_area. insert(END,"> "+msg+'\n','SEND_COLOR')
        output_area.tag_config('SEND_COLOR', foreground='blue')
        output_area.see("end")
        output_area.configure(state ='disabled')
    elif msg_type==MSG_TYPE_RECEIVE:
        output_area.configure(state ='normal')
        output_area. insert(END,msg+'\n','RECEIVE_COLOR')
        output_area.tag_config('RECEIVE_COLOR', foreground='black')
        output_area.see("end")
        output_area.configure(state ='disabled')
    else:
        output_area.configure(state ='normal')
        output_area. insert(END,msg+'\n','ERROR_COLOR')
        output_area.tag_config('ERROR_COLOR', foreground='grey')
        output_area.see("end")
        output_area.configure(state ='disabled')

## =============================================================
## =============================================================
## =============================================================

output_queue = Queue()

def output_pull_queue():
    while (1):
        msg, msg_type =output_queue.get(block=True, timeout=None)
        output_send(msg,msg_type)

Thread_output = Thread(target = output_pull_queue, args =())
Thread_output.start()

output_queue.put_nowait(("Mon message de sortie",MSG_TYPE_ACTION))

## =============================================================
## =============================================================
## =============================================================

# --------------- TCP client mamagement -------------------

ClientState = 0
#client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def ProcessReveivedMsg(client):
    try:
##        output_send('in ProcessReveivedMsg()',MSG_TYPE_ACTION)
        output_queue.put_nowait(('in ProcessReveivedMsg()',MSG_TYPE_ACTION))

        while 1:
            MyFrame = client.recv(1024)
            if not MyFrame:
##                output_send('Client quit',MSG_TYPE_ACTION)
                output_queue.put_nowait(('Client quit',MSG_TYPE_ACTION))
                break #quit while
            else:
                #convert the "byte" received to a string
                FrameStr = MyFrame.decode('UTF-8')
                rameStr = FrameStr.replace("\n","") # supress \n for start of line
                #FrameStr = FrameStr.replace("\r","") # supress \r for start of line

                #filter received string with just empty string
                #(an empty string always follow a string...)
                if (len(FrameStr)!=0):
                    #display the received msg
##                    output_send(FrameStr,MSG_TYPE_RECEIVE)
                    output_queue.put_nowait((FrameStr,MSG_TYPE_RECEIVE))
                    #push reception to the queue_in
                    queue_in.put_nowait(FrameStr)

    except:
        MyEnd = 0
        # except is used to catch the error when client.rev is waiting a message
        # and client is closed by client.close()

def MyTcpClient(in_q):
    ii=0
    ClientState = 0
    ServerRequest = 0
    while 1:
        #Check if a command is received from main task
        if in_q.empty()==False:
            ServerRequest = in_q.get()

        #if server is disabled, check if it has to be launched
        if ClientState==0:
            if (ServerRequest==1):  # Request server connexion
                # bind socket to server IP and Port
                Port = int(Port_StrVar.get())
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                client.connect((IP_StrVar.get(),int(Port_StrVar.get())))
                txt='Connection to '+IP_StrVar.get()+', port='+Port_StrVar.get()
##                output_send(txt,MSG_TYPE_ACTION)
                output_queue.put_nowait((txt,MSG_TYPE_ACTION))
                ClientState = 1

        #if server is enabled, check if it has to be stoped
        if ClientState==1:
            if (ServerRequest==0):  # Request server connexion
##                output_send('Disconnect',MSG_TYPE_ACTION)
                output_queue.put_nowait(('Disconnect',MSG_TYPE_ACTION))
                client.close()
                #note : This will cause "ProcessReveivedMsg" exception
##                Thread_ProcessReveivedMsg.join()
                ClientState = 0

        time.sleep(1)
        ii += 1
##        output_send(str(ii),MSG_TYPE_SEND)
        output_queue.put_nowait((str(ii),MSG_TYPE_SEND))

##        if(ClientState==1):
##            client.send(('hello +'+str(ii)).encode())

##Thread_MyTcpClient = Thread(target = MyTcpClient, args =(q, ))
##Thread_MyTcpClient.start()

def MyTCP_ConnectToServer():
    global ClientState
    global client
    #manage client connection to the server
    Port = int(Port_StrVar.get())
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        #client connection to server
        client.connect((IP_StrVar.get(),int(Port_StrVar.get())))
        txt='Connection to '+IP_StrVar.get()+', port='+Port_StrVar.get()
        output_queue.put_nowait((txt,MSG_TYPE_ACTION))
        ClientState = 1
        #Launch thread to receive data
        Thread_ProcessReveivedMsg = Thread(target = ProcessReveivedMsg, args =(client, ))
        Thread_ProcessReveivedMsg.start()
        output_queue.put_nowait(('Receiving thread is started',MSG_TYPE_ACTION))

        #widget management
        ConnStatus_txt.set("Connected")
        ConnStatus_label.config(fg="green", font='Helvetica 11 bold')

    except:
        output_queue.put_nowait(("Server refuse connection",MSG_TYPE_ACTION))
        ClientState = 0
        #widget management
        ConnStatus_txt.set("Disconnected")
        ConnStatus_label.config(fg="black", font='Helvetica 10')

def MyTCP_DisConnectToServer():
    global ClientState
    global client
    try:
        #manage client connection to the server
        output_queue.put_nowait(('Disconnect',MSG_TYPE_ACTION))
        client.close()
        #note : This will cause "ProcessReveivedMsg" exception
        Thread_ProcessReveivedMsg.join()
        ClientState = 0
    except:
        ClientState = 0
    #manage widget
    ConnStatus==0
    ConnStatus_txt.set("Disconnected")
    ConnStatus_label.config(fg="black", font='Helvetica 10')

def MyTCP_SendToServer(strMessage):
    global ClientState
    global client
    if(ClientState==1):
        try:
            client.send(strMessage.encode())
        except:
            output_queue.put_nowait(("Can't send to Server",MSG_TYPE_ACTION))
            MyTCP_DisConnectToServer()
    else:
        output_queue.put_nowait(("Connect to Server before to send message.",MSG_TYPE_ACTION))

# -------------- Connexion widget --------------------

def changeConnStatus():
    global ClientState
    if ClientState==0:
        MyTCP_ConnectToServer()
    elif ClientState==1:

        MyTCP_DisConnectToServer()
    else: #Default state
        ConnStatus_txt.set("----")
        ConnStatus_label.config(fg="black", font='Helvetica 10 bold')
        ClientState==0

# ---------- Popup Window for Rf Measurement -------------

def ZIOT_SendReceive(msg, MaxDelay_ms):
    # if a message has to be sent.
    if msg!=None:
        output_queue.put_nowait((msg, MSG_TYPE_SEND))
        MyTCP_SendToServer(msg)
    # wait reception of a message with a max delay.
    # return None if no message is received before delay.
    try:
        response = queue_in.get(block=True, timeout=MaxDelay_ms/1000)
    except:
        response = None
    return response

def Rf_create(save):

    #analyse response with regular expression
    ##   /RF\s*:\s*([0-9]*\.[0-9]*)/gm
    # First regular expression to identify line "RF    : 3135.10742 Ohm"
    p_line = re.compile('RF\s*:\s*([0-9]*\.[0-9]*)')
    # second regular expression to identify line "3135.10742"
    p_val  = re.compile('[0-9]*\.[0-9]*')

    #create result window
    rWin = ResultWindow(root)

    #empty reception queue
    while queue_in.empty()==False:
        queue_in.get_nowait()

    #repeat 10 Rf estimation
    for i in range(1,100):
        print("=========== "+str(i)+" ===========")
        #send command 'S2' to request Rf measurement.
        response = ZIOT_SendReceive('S2', 2000)
        if response==None:
            output_queue.put_nowait(("Response expected, not received", MSG_TYPE_SEND))
            return
        if (save):
            response = ZIOT_SendReceive('1', 3000)
        else:
            response = ZIOT_SendReceive('0', 3000)

        while response!=None:
            m = p_line.search(response)
            if m!=None:
                #print(m)
                #print(m.group())
                m = p_val.search(response)
                if m!=None:
                    #print(m)
                    print(m.group())
                    rWin.AddResult(float(m.group()),"Ω")

            #ask for next answer.
            response = ZIOT_SendReceive(None, 1000)

## pour récuperer la valeur de resistance dans : T1[Z,|Z|,RF,Lm], T2[|U|,U_RMS]  : 23.65427  + 270.62933 j : 271.66110 : 3119.93384 Ohm : 0.02370 H : 0.15680 V : 0.45808 V
#  /T1\[Z,\|Z\|,RF,Lm\], T2\[\|U\|,U_RMS\] (\d|\s|\.|\+|j)*:(\d|\s|\.|\+|j)*:(\d|\s|\.|\+|j)*: ([0-9]*\.[0-9]*)/gm

def Rf_createSave():
    Rf_create(True)

def Rf_createNotSave():
    Rf_create(False)

# ---------- Manage IP settings -------------

#Load settings in configuration file
ADDRESS = cf.take(CF_ETHERNET_SECTION,"addrIPv4","192.168.1.11")
MASK    = cf.take(CF_ETHERNET_SECTION,"maskIPv4","255.25.0.0")
PORT    = cf.take(CF_ETHERNET_SECTION,"portIPv4",4101)

#callback to save settings in configuration file when Entry is modified
def IP_StrVar_modified(*args):
    cf.put(CF_ETHERNET_SECTION,"addrIPv4",IP_StrVar.get())
def MASK_StrVar_modified(*args):
    cf.put(CF_ETHERNET_SECTION,"maskIPv4",MASK_StrVar.get())
def Port_StrVar_modified(*args):
    try:
        cf.put(CF_ETHERNET_SECTION,"portIPv4",int(Port_StrVar.get()))
    except:
        cf.put(CF_ETHERNET_SECTION,"portIPv4",4101)
# -------------- IP widget --------------------

NetworkTitle_label = Label(left_frame, text='Network',background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
IP_StrVar   = StringVar(left_frame, value=ADDRESS)
IP_StrVar.trace_add("write",IP_StrVar_modified)
IP_label    = Label(left_frame, text='IP address :',background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
IP_entry    = Entry(left_frame, textvariable = IP_StrVar, width = cg.ENTRY_DEF_WIDTH, background=cg.ENTRY_COLOR);

MASK_StrVar = StringVar(left_frame, value=MASK)
MASK_StrVar.trace_add("write",MASK_StrVar_modified)
MASK_label  = Label(left_frame, text='IP mask : ',background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
MASK_entry  = Entry(left_frame, textvariable = MASK_StrVar, width = cg.ENTRY_DEF_WIDTH, background=cg.ENTRY_COLOR)

Port_StrVar = StringVar(left_frame, value=str(PORT))
Port_StrVar.trace_add("write",Port_StrVar_modified)
Port_label  =  Label(left_frame, text='IP port : ',background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
Port_entry  =  Entry(left_frame, textvariable = Port_StrVar, width = cg.ENTRY_DEF_WIDTH, background=cg.ENTRY_COLOR);

NetworkTitle_label.config(font='Helvetica 10 bold')
ConnStatus_txt = StringVar()
ConnStatus_label = Label(left_frame, textvariable=ConnStatus_txt,background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
ConnStatus_txt.set("----")
ConnStatus_label.config(fg="black", font='Helvetica 10 bold')
ConnStatus = 1
Conn_bouton = Button(left_frame, text="Connect", width = cg.BUTTON_DEF_WIDTH, command=changeConnStatus)
Conn_bouton["fg"] = "black"

##entry_L = Entry(Right_frame, background="orange")

# layout the widgets in the top frame
NetworkTitle_label.grid(row=0, column=0, columnspan =2, padx=10,pady=10)
Conn_bouton.grid(row=1, column=0)
ConnStatus_label.grid(row=1, column=1)
IP_label.grid(row=4, column=0)
IP_entry.grid(row=4, column=1, padx=5)
MASK_label.grid(row=5, column=0)
MASK_entry.grid(row=5, column=1, padx=5)
Port_label.grid(row=6, column=0)
Port_entry.grid(row=6, column=1, padx=5)

# -------------- Config Widget --------------------

def save_Settings():
    ...

def Load_Settings():
    ...

ConfTitle_label    = Label(left_frame, text='Configuration',background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
Load_bouton        = Button(left_frame, text="Load JSON", width = cg.BUTTON_DEF_WIDTH, command=Load_Settings)
Load_bouton["fg"]  = "black"
Save_bouton        = Button(left_frame, text="Save JSON", width = cg.BUTTON_DEF_WIDTH, command=save_Settings)
Load_bouton["fg"]  = "black"

ConfTitle_label.config(font='Helvetica 10 bold')

ConfTitle_label.grid(row=7, column=0, columnspan =2, pady=10)
Load_bouton.grid(row=8, column=0, padx=10)
Save_bouton.grid(row=8, column=1, padx=10)

# -------------- Measure Rf --------------------
MeasRfTitle_label    = Label(left_frame, text='Measure Rf',background = cg.LABEL_BACKGROUND, fg = cg.LABEL_FOREGROUND)
MeasRfTitle_label.config(font='Helvetica 10 bold')
MeasRfTitle_label.grid(row=9, column=0, columnspan =2, pady=10)

MeasRf_bouton        = Button(left_frame, text="Start", width = cg.BUTTON_DEF_WIDTH, command=Rf_createNotSave)
MeasRf_bouton["fg"]  = "black"
MeasRf_bouton.grid(row=10, column=0, padx=10)

SaveRf_bouton        = Button(left_frame, text="Start & Save", width = cg.BUTTON_DEF_WIDTH, command=Rf_createSave)
SaveRf_bouton["fg"]  = "black"
SaveRf_bouton.grid(row=10, column=1, padx=10)

# Placing cursor in the text area
output_area.focus()

root.mainloop()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('add/', views.addtodo, name='add'),
    path('complete/<int:todo_pk>/', views.complete, name='complete'),
    path('delcompleted/', views.delcompleted, name='delcompleted'),
    path('delall/', views.delall, name='delall'),
    path('register/', views.register, name='register'),
]


#!/usr/bin/python3

import os
import datetime
import json

from collections import OrderedDict
from subprocess import check_output

class Interface:
    def __init__(self):
        self.path = os.environ['HOME_DIR']

    def IP(self, interface):
        output = check_output(f'ifconfig {interface}', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if('inet6' in line):
                pass
            elif('inet' in line):
                line = line.strip().split()
                ip = line[1]
#                print(ip)
                return(ip)

    def MTU(self, interface):
        i = 0
        output = check_output(f'ifconfig {interface}', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if(i == 0):
                i += 1
                line = line.strip().split()
                mtu = line[3]
#                print(mtu)
                return(mtu)

    def MAC(self, interface):
        output = check_output(f'ifconfig {interface}', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if('ether' in line):
                line = line.strip().split()
                mac = line[1]
#                print(mac)
                return(mac)

    def Netmask(self, interface):
        output = check_output(f'ifconfig {interface}', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if('inet6' in line):
                pass
            elif('netmask' in line):
                line = line.strip().split()
                netmask = line[3]
#                print(netmask)
                return(netmask)

    def Broadcast(self, interface):
        output = check_output(f'ifconfig {interface}', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if('inet6' in line):
                pass
            elif('broadcast' in line):
                line = line.strip().split()
                broadcast = line[5]
#                print(broadcast)
                return(broadcast)

    def DefaultGateway(self):
        output = check_output('ip route', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if('default' in line):
                dfg = line.split()[2]

                return dfg

    def IPtoMAC(self, ipa):
        output = check_output('arp -n', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if (line and line.split()[0] == ipa):
                ipa_mac = line.split()[2]
                break
        else:
            ipa_mac = None

        return ipa_mac

    def Bandwidth(self):
        intstat = {}
        with open('{}/data/interface_speed.json'.format(self.path), 'r') as speed:
            bandwidth = json.load(speed)
        for key, value in bandwidth.items():
            intstat[key] = [round(int(value[0])*8/1024, 2), round(int(value[1])*8/1024, 2)]

#        print(intstat)
        return intstat

    def WANSubnet(self, interface, dfg):
        masks = [0, 128, 192, 224, 240, 248, 250]
        hosts = [254, 126, 62, 30, 14, 6, 2]
        ip_range = set()

        output = check_output(f'ifconfig {interface}', shell=True).decode()
        output = output.splitlines(8)
        for line in output:
            if('inet' in line):
                line = line.strip().split()
                ip = line[1]
                netmask = line[3]
                break

        ip = ip.split('.')
        dfg = dfg.split('.')
        netmask = netmask.split('.')
        network = f'{ip[0]}.{ip[1]}.{ip[2]}'
        for i, mask in enumerate(masks):
            if (int(netmask[3]) == mask):
                usable_ips = [int(dfg[3])+1, int(dfg[3])+hosts[i]]

        for ip in range(usable_ips[0], usable_ips[1]):
            ip_range.add(f'{network}.{ip}')
#                print(ip)
        return(ip_range)


films = {
    "Finding Dory": {"ID": "1", "Age": 4, "Seats": 20, "AvailableSeats": 20},
    "Bourne": {"ID": "2", "Age": 18, "Seats": 20, "AvailableSeats": 20},
    "Tarzan": {"ID": "3", "Age": 15, "Seats": 35, "AvailableSeats": 35},
    "Ghost Busters": {"ID": "4", "Age": 12, "Seats": 50, "AvailableSeats": 50}
}

films_id_map = {
    "1": "Finding Dory",
    "2": "Bourne",
    "3": "Tarzan",
    "4": "Ghost Busters"
}

# give access to admin by check pwd and username
# automate film edit, add, remove

print(type(films))
while True:
    # automate this menu by convert dictionary to list, then iterate list items

    for key in films_id_map:
        print(key + '.', films_id_map[key])

    print("\n")

    choice = input("What film would you like to watch?\n>>> ").strip()

    while not (choice == "1" or choice == "2" or choice == "3" or choice == "4"):
        choice = input("Not available, please choose again\n>>> ")

    film_name = films_id_map[choice]
    age_limit = films[film_name]["Age"]
    available_seat = films[film_name]["AvailableSeats"]
    if available_seat == 0:
        print("We are sold out, sorry! Please choose another film.")
    else:
        user_age = input("How old are you?\n>>> ").strip()
        while user_age == "":
            user_age = input("How old are you?\n>>> ").strip()
        user_age = int(user_age)
        if user_age >= age_limit:
            seat_condition = "{} seats are available, how many would like to book?\n>>> ".format(available_seat)
            book_seat = input(seat_condition).strip()
            while book_seat == "":
                book_seat = input(seat_condition).strip()
            book_seat = int(book_seat)
            while book_seat > available_seat or book_seat <= 0:
                book_seat = int(input("Sorry, bad number, choose again\n>>> ").strip())
            print("Take your cola and pop corn, film is about to start")
            films[film_name]["AvailableSeats"] = available_seat - book_seat
        else:
            print("Sorry kiddo, you are too young for this")


import sys

argc = len(sys.argv)
if argc > 2:
    print("Error")
else:
    try:
        nbr = sys.argv[1]
        nbr = int(nbr)
        if nbr == 0:
            print("I'm a zero")
        else:
            result = nbr % 2
            if result:
                print("I'm odd")
            else:
                print("I'm even")
    except TypeError:
        print("Error")
    except IndexError:
        print("")


"""
A website domain like "discuss.leetcode.com"
consists of various subdomains. At the top level, we have "com",
at the next level, we have "leetcode.com", and at the lowest level,
"discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com",
we will also visit the parent domains "leetcode.com" and "com" implicitly.

Now, call a "count-paired domain" to be a count (representing the number of
visits this domain received), followed by a space, followed by the address.
An example of a count-paired domain might be "9001 discuss.leetcode.com".

We are given a list cpdomains of count-paired domains. We would like
a list of count-paired domains, (in the same format as the input,
and in any order), that explicitly counts the number of visits to each subdomain.

Example 1:
Input:
["9001 discuss.leetcode.com"]
Output:
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Explanation:
We only have one website domain: "discuss.leetcode.com". As discussed above,
the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.

Example 2:
Input:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation:
We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and
"wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times,
"com" 900 + 50 + 1 = 951 times, and "org" 5 times.

Notes:

The length of cpdomains will not exceed 100.
The length of each domain name will not exceed 100.
Each address will have either 1 or 2 "." characters.
The input count in any count-paired domain will not exceed 10000.
The answer output can be returned in any order.

"""

class Solution:
    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
        if cpdomains == []:
            return []
        else:
            domains = []
            for i in range(len(cpdomains)):
                d_  = Domain(cpdomains[i])
                domains.append(d_)
                temp = self.parse(d_)
                domains.extend(self.parse(d_))

            ret_dom =[]
            ret_dom.append(domains[0])
            for i in range(1,len(domains)):
                for j in range(len(ret_dom)):
                    if domains[i].domain == ret_dom[j].domain:
                        ret_dom[j].num +=domains[i].num
                        break
                    if j == len(ret_dom)-1:
                        ret_dom.append(domains[i])
            ret = []
            for i in range(len(ret_dom)):
                ret.append(str(ret_dom[i].num) + ' ' + ret_dom[i].domain)
        return ret

    def parse(self, domain_):
        ret =[]
        for i in range(len(domain_.d_parts)-1):
            str_ = ""
            for j in range(i+1,len(domain_.d_parts)-1):
                str_ = str_ + domain_.d_parts[j] + '.'
            str_ = str_ + domain_.d_parts[-1] #add the last
            str_ = str(domain_.num) + " " + str_
            d_ = Domain(str_)
            ret.append(d_)
        return ret

class Domain:
    def __init__(self,domain_):
        try:
            self.num = int(domain_.split(' ')[0])
            self.domain = domain_.split(' ')[1]
            self.d_parts = self.domain.split('.')

        except:
            self.num = -1
            self.domain  = ""
            self.d_parts = []


#print("========")
#print("Listas")
#print("========\n")

#demo_list = [1, "hello", 1.34, [1, 2, 3]]
#numbers_list = list((1, 2, 3, 4))

#print(demo_list)
#print(numbers_list)
#print(type(numbers_list))

#print("\n========")
#print("Lista con rangos")
#print("========\n")

#prueba_rango = list(range(1, 11))
#print(prueba_rango)

#print("\n========")
#print("Pruebas con listas")
#print("========\n")

#colors = ['green', 'blue', 'red']
#colors += ['yellow']
#print(colors)
#print('green' in colors)
#colors[0] = 'black'
#print(colors)
#colors.append('violet')
#colors.extend(['violet', 'white'])
#colors.insert(-1, 'violet')
#colors.insert(len(colors), 'violet')
#print(colors)
#colors.remove('red')
#colors.pop(1)
#colors.clear()
#colors.sort(reverse=True)
#print(colors.index('blue'))

#print("\n========")
#print("Tuples")
#print("========\n")

#x = (1, 2, 3, 4, 5, 6)
#y = tuple((1, 2, 3))
#z = (9,)
#print(dir(tuple))
#print(x[5])
#NO PUEDES AÑADIR MAS VALORES COMO CON LAS LISTAS
#location = {
    #(35.125, 39.365):"Tokio",
    #(20.125, 150.365):"Nueva York"
    #}
#print(location)

#print("\n========")
#print("SET")
#print("========\n")

#colors = {'green', 'blue', 'red'}
#colors.add('white')
#colors.remove('red')
#colors.clear()
#del colors
#print(colors)

#print("\n========")
#print("Diccionario")
#print("========\n")

#product = {
    #"name":"book",
    #"quantity" :"3",
    #"price": 5.99
    #}
#print(product)

person = {
    'nombre': 'Luis',
    'apellido': 'Alayo',
    'edad': 30
    }
#print(person.items())
#del person
#person.clear()
print(person)


from typing import List
import os
import glob
import asyncio
import csv
from hashlib import sha1
from pathlib import Path
from collections import defaultdict
from dataclasses import dataclass
import click
from pyppeteer import launch
from PIL import Image
from jinja2 import Template

@dataclass(frozen=True)
class Product():
    name: str
    url: str
    categories: List[str]
    description: str
    tags: List[str]

    @property
    def image_name(self):
        return sha1(self.url.encode('utf-8')).hexdigest()

def load_products_csv() -> List[Product]:
    products = []
    def parse_list(list_str: str) -> List[str]:
        return [s.strip() for s in list_str.split('+')]
    with open('data/data.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        next(csv_reader)
        for row in csv_reader:
            p = Product(
                name=row[0],
                url=row[1],
                categories=parse_list(row[2]),
                description=row[3],
                tags=parse_list(row[4])
            )
            products.append(p)
    return products

async def capture_screenshots(websites: List[str]) -> None:
    browser = await launch()
    page = await browser.newPage()
    await page.setViewport({'width': 1200, 'height': 800})
    for website in websites:
        filename = sha1(website.encode('utf-8')).hexdigest()
        if not os.path.exists(f'processing/screenshots/{filename}.png'):
            await page.goto(website)
            await page.screenshot({'path': f'processing/screenshots/{filename}.png'})
    await browser.close()

def resize_all_screenshots() -> None:
    size = 600, 400
    for filepath in glob.glob("processing/screenshots/*.png"):
        im = Image.open(filepath)
        im.thumbnail(size)
        name = os.path.basename(filepath)
        im.save('processing/screenshot_thumbnails/' + name, 'PNG')

@click.group()
def cli():
    pass

@cli.command()
def generate():
    click.echo("Generating...")
    products: List[Product] = load_products_csv()
    categories = defaultdict(list)
    for product in products:
        for category in product.categories:
            categories[category].append(product)
    urls = [p.url for p in products]
    asyncio.get_event_loop().run_until_complete(capture_screenshots(urls))
    resize_all_screenshots()
    with open(Path('templates/index.htm')) as template_file:
        template = Template(template_file.read())
        with open(Path('index.html'), 'w') as index_file:
            index_file.write(template.render(categories=categories, category_keys=sorted(categories.keys())))

if __name__ == "__main__":
    cli()


# -*- coding: utf-8 -*-
"""Tests for utility functions in tmux."""

import re

import pytest

from libtmux.common import has_required_tmux_version, which, session_check_name, is_version
from libtmux.exc import LibTmuxException, BadSessionName

version_regex = re.compile(r'[0-9]\.[0-9]')

def test_no_arg_uses_tmux_version():
    """Test the :meth:`has_required_tmux_version`."""
    result = has_required_tmux_version()
    assert version_regex.match(result) is not None

def test_ignores_letter_versions():
    """Ignore letters such as 1.8b.

    See ticket https://github.com/tony/tmuxp/issues/55.

    In version 0.1.7 this is adjusted to use LooseVersion, in order to
    allow letters.

    """
    result = has_required_tmux_version('1.9a')
    assert version_regex.match(result) is not None

    result = has_required_tmux_version('1.8a')
    assert result == r'1.8'

    # Should not throw
    assert type(is_version('1.8'))  is bool
    assert type(is_version('1.8a')) is bool
    assert type(is_version('1.9a')) is bool

def test_error_version_less_1_7():
    with pytest.raises(LibTmuxException) as excinfo:
        has_required_tmux_version('1.7')
        excinfo.match(r'tmuxp only supports')

    with pytest.raises(LibTmuxException) as excinfo:
        has_required_tmux_version('1.6a')

        excinfo.match(r'tmuxp only supports')

    has_required_tmux_version('1.9a')

def test_which_no_tmuxp_found(monkeypatch):
    monkeypatch.setenv("PATH", "/")
    which('tmuxp')
    which('tmuxp', '/')

@pytest.mark.parametrize("session_name,raises,exc_msg_regex", [
    ('', True, 'may not be empty'),
    (None, True, 'may not be empty'),
    ("my great session.", True, 'may not contain periods'),
    ("name: great session", True, 'may not contain colons'),
    ("new great session", False, None),
    ("ajf8a3fa83fads,,,a", False, None),
])
def test_session_check_name(session_name, raises, exc_msg_regex):
    if raises:
        with pytest.raises(BadSessionName) as exc_info:
            session_check_name(session_name)
        assert exc_info.match(exc_msg_regex)
    else:
        session_check_name(session_name)


import re

from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from sesc.items import SescItem
from sesc.utils import get_type_from_imgurl, get_age_range_from_imgurl

class SescspSpider(CrawlSpider):
    name = 'sescsp'
    allowed_domains = ['sescsp.org.br']
    start_urls = ['http://www.sescsp.org.br/sesc/programa_new/busca.cfm?unidade_id=16']

    rules = (
        Rule(SgmlLinkExtractor(allow=r'page=')),
        Rule(
            SgmlLinkExtractor(
                allow=r'programacao_id',
                restrict_xpaths=[
                    '//*[@id="box"][not(preceding-sibling::*[1][@id=prog])]//*[@class="tit"]',
                    '//*[@id="box"][not(preceding-sibling::*[1][@id=prog])]//*[@class="tit2"]'
                ]),
            callback='parse_event',
            follow=True),
    )

    def parse_event(self, response):
        hxs = HtmlXPathSelector(response)
        i = SescItem()
        i['name'] = hxs.select('string(//*[@class="tit"])').extract()[0]
        i['event_type'] = get_type_from_imgurl(hxs.select('string(//*[@class="tit"]/parent::td/preceding-sibling::td[1]//img/@src)').extract()[0])
        i['superEvent'] = hxs.select('string(//img[@src=images/estrela.gif]/following-sibling::span)').extract()[0]
        #i['subEvent'] =
        #i['performes'] =
        i['startDate'] = hxs.select('string(//*[@class="data"])').extract()[0]
        #i['Duration'] =
        #i['endDate'] =
        i['location'] = hxs.select('string(//*[@class="local"])').extract()[0]
        i['price'] = hxs.select('string(//*[@class="preco"])').extract()[0]
        i['age_range'] = get_age_range_from_imgurl(hxs.select('string(//img/@src[contains(., "selos")])').extract()[0])
        i['description'] = hxs.select('string(//*[@class="txtinfo"])').extract()[0]
        return i


from django.conf.urls import url
from django.contrib import admin

from .views import(
    list_cliente,
    create_cliente,
    update_cliente,
    delete_cliente,
    detail_cliente,
)
app_name = 'cliente'

urlpatterns = [
    url(r'^$',list_cliente, name='list'),
    url(r'^criar/$',create_cliente),
    url(r'^(?P<id>\d+)/$',detail_cliente, name='detail'),
    url(r'^(?P<id>\d+)/editar/$',update_cliente, name='update'),
    url(r'^(?P<id>\d+)/deletar/$',delete_cliente),
]