load(
    "//rules:utils.bzl",
    "ANDROID_TOOLCHAIN_TYPE",
)
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":common.bzl", _common = "common")
load(":java.bzl", _java = "java")

_density_mapping = {
    "ldpi": 120,
    "mdpi": 160,
    "hdpi": 240,
    "xhdpi": 320,
    "xxhdpi": 480,
    "xxxhdpi": 640,
    "tvdpi": 213,
}

def _build(
        ctx,
        out = None,
        modules = [],
        config = None,
        metadata = dict(),
        bundletool = None,
        host_javabase = None):
    args = ctx.actions.args()
    args.add("build-bundle")
    args.add("--output", out)
    if modules:
        args.add_joined("--modules", modules, join_with = ",")
    if config:
        args.add("--config", config)
    for path, f in metadata.items():
        args.add("--metadata-file", "%s:%s" % (path, f.path))

    _java.run(
        ctx = ctx,
        host_javabase = host_javabase,
        executable = bundletool,
        arguments = [args],
        inputs = (
            modules +
            ([config] if config else []) +
            metadata.values()
        ),
        outputs = [out],
        mnemonic = "BuildBundle",
        progress_message = "Building bundle %s" % out.short_path,
    )

def _build_device_json(
        ctx,
        out,
        abis,
        locales,
        density,
        sdk_version):
    json_content = json.encode(struct(
        supportedAbis = abis,
        supportedLocales = locales,
        screenDensity = _density_mapping[density],
        sdkVersion = int(sdk_version),
    ))
    ctx.actions.write(out, json_content)

def _build_sdk_apks(
        ctx,
        out = None,
        aapt2 = None,
        sdk_archive = None,
        sdk_bundle = None,
        debug_key = None,
        bundletool = None,
        host_javabase = None):
    if bool(sdk_archive) == bool(sdk_bundle):
        fail("Exactly one of sdk_archive or sdk_bundle need to be set in %s." % ctx.label.name)
    apks_out = ctx.actions.declare_directory(
        "%s_apks_out" % paths.basename(out.path).replace(".", "_"),
        sibling = out,
    )
    inputs = [debug_key]
    args = ctx.actions.args()
    args.add("build-sdk-apks")
    args.add("--aapt2", aapt2.executable.path)
    if sdk_archive:
        args.add("--sdk-archive", sdk_archive)
        inputs.append(sdk_archive)
    if sdk_bundle:
        args.add("--sdk-bundle", sdk_bundle)
        inputs.append(sdk_bundle)
    args.add("--ks", debug_key)
    args.add("--ks-pass=pass:android")
    args.add("--ks-key-alias=androiddebugkey")
    args.add("--key-pass=pass:android")
    args.add("--output-format=DIRECTORY")
    args.add("--output", apks_out.path)
    _java.run(
        ctx = ctx,
        host_javabase = host_javabase,
        executable = bundletool,
        arguments = [args],
        inputs = inputs,
        tools = [aapt2],
        outputs = [apks_out],
        mnemonic = "BuildSdkApksDir",
        progress_message = "Building SDK APKs directory %s" % apks_out.short_path,
    )

    # Now move standalone APK out of bundletool output dir.
    ctx.actions.run_shell(
        command = """
set -e
APKS_OUT_DIR=%s
DEBUG_APK_PATH=%s

mv "${APKS_OUT_DIR}/standalones/standalone.apk" "${DEBUG_APK_PATH}"
""" % (
            apks_out.path,
            out.path,
        ),
        tools = [],
        arguments = [],
        inputs = [apks_out],
        outputs = [out],
        mnemonic = "ExtractDebugSdkApk",
        progress_message = "Extract debug SDK APK to %s" % out.short_path,
    )

def _build_sdk_bundle(
        ctx,
        out = None,
        module = None,
        sdk_api_descriptors = None,
        sdk_modules_config = None,
        bundletool = None,
        host_javabase = None):
    args = ctx.actions.args()
    args.add("build-sdk-bundle")

    args.add("--sdk-modules-config", sdk_modules_config)
    args.add("--sdk-interface-descriptors", sdk_api_descriptors)
    args.add("--modules", module)
    args.add("--output", out)
    _java.run(
        ctx = ctx,
        host_javabase = host_javabase,
        executable = bundletool,
        arguments = [args],
        inputs = [
            module,
            sdk_api_descriptors,
            sdk_modules_config,
        ],
        outputs = [out],
        mnemonic = "BuildASB",
        progress_message = "Building SDK bundle %s" % out.short_path,
    )

def _build_sdk_module(
        ctx,
        out = None,
        internal_apk = None,
        bundletool_module_builder = None,
        host_javabase = None):
    args = ctx.actions.args()
    args.add("--internal_apk_path", internal_apk)
    args.add("--output_module_path", out)
    ctx.actions.run(
        inputs = [internal_apk],
        outputs = [out],
        executable = bundletool_module_builder,
        arguments = [args],
        mnemonic = "BuildSdkModule",
        progress_message = "Building ASB zip module %s" % out.short_path,
        toolchain = ANDROID_TOOLCHAIN_TYPE,
    )

def _bundle_to_apks(
        ctx,
        out = None,
        bundle = None,
        mode = None,
        system_apk_options = None,
        device_spec = None,
        keystore = None,
        oldest_signer = None,
        lineage = None,
        rotation_min_sdk = None,
        modules = None,
        aapt2 = None,
        bundletool = None,
        host_javabase = None):
    inputs = [bundle]
    args = ctx.actions.args()
    args.add("build-apks")
    args.add("--output", out)
    args.add("--bundle", bundle)
    args.add("--aapt2", aapt2.executable.path)

    if mode:
        args.add("--mode", mode)

    if system_apk_options:
        if mode != "SYSTEM":
            fail("Unexpected system_apk_options specified, requires SYSTEM mode but got %s" % mode)
        args.add_joined("--system-apk-options", system_apk_options, join_with = ",")

    if keystore:
        args.add("--ks", keystore.path)
        args.add("--ks-pass", "pass:android")
        args.add("--ks-key-alias", "AndroidDebugKey")
        inputs.append(keystore)

    if lineage:
        if not oldest_signer:
            fail("Key rotation requires oldest_signer in %s" % ctx.label)
        oldest_signer_properties = _common.create_signer_properties(ctx, oldest_signer)
        args.add("--oldest-signer", oldest_signer_properties.path)
        args.add("--lineage", lineage.short_path)
        inputs.append(oldest_signer_properties)
        inputs.append(oldest_signer)
        inputs.append(lineage)

    if rotation_min_sdk:
        args.add("--rotation-min-sdk-version", rotation_min_sdk)

    if device_spec:
        args.add("--device-spec", device_spec)
        inputs.append(device_spec)

    if modules:
        args.add_joined("--modules", modules, join_with = ",")

    _java.run(
        ctx = ctx,
        host_javabase = host_javabase,
        executable = bundletool,
        arguments = [args],
        inputs = inputs,
        outputs = [out],
        tools = [aapt2],
        mnemonic = "BundleToApks",
        progress_message = "Converting bundle to .apks: %s" % out.short_path,
    )

def _extract_config(
        ctx,
        out = None,
        aab = None,
        bundletool = None,
        host_javabase = None):
    # Need to execute as a shell script as the tool outputs to stdout
    cmd = """
set -e
contents=`%s -jar %s dump config --bundle %s`
echo "$contents" > %s
""" % (
        host_javabase[java_common.JavaRuntimeInfo].java_executable_exec_path,
        bundletool.executable.path,
        aab.path,
        out.path,
    )

    ctx.actions.run_shell(
        inputs = [aab],
        outputs = [out],
        tools = depset([bundletool.executable], transitive = [host_javabase[java_common.JavaRuntimeInfo].files]),
        mnemonic = "ExtractBundleConfig",
        progress_message = "Extract bundle config to %s" % out.short_path,
        command = cmd,
        exec_group = "android_and_java",
    )

def _extract_manifest(
        ctx,
        out = None,
        aab = None,
        module = None,
        xpath = None,
        bundletool = None,
        host_javabase = None):
    # Need to execute as a shell script as the tool outputs to stdout
    extra_flags = []
    if module:
        extra_flags.append("--module " + module)
    if xpath:
        extra_flags.append("--xpath " + xpath)
    cmd = """
set -e
contents=`%s -jar %s dump manifest --bundle %s %s`
echo "$contents" > %s
""" % (
        host_javabase[java_common.JavaRuntimeInfo].java_executable_exec_path,
        bundletool.executable.path,
        aab.path,
        " ".join(extra_flags),
        out.path,
    )

    ctx.actions.run_shell(
        inputs = [aab],
        outputs = [out],
        tools = depset([bundletool.executable], transitive = [host_javabase[java_common.JavaRuntimeInfo].files]),
        mnemonic = "ExtractBundleManifest",
        progress_message = "Extract bundle manifest to %s" % out.short_path,
        command = cmd,
        exec_group = "android_and_java",
    )

def _proto_apk_to_module(
        ctx,
        out = None,
        proto_apk = None,
        runtime_enabled_sdk_config = None,
        bundletool_module_builder = None):
    inputs = [proto_apk]
    args = ctx.actions.args()
    args.add("--internal_apk_path", proto_apk)
    if runtime_enabled_sdk_config:
        args.add("--runtime_enabled_sdk_config_path", runtime_enabled_sdk_config)
        inputs.append(runtime_enabled_sdk_config)

    args.add("--output_module_path", out)
    ctx.actions.run(
        inputs = inputs,
        outputs = [out],
        executable = bundletool_module_builder,
        arguments = [args],
        mnemonic = "BuildAppModule",
        progress_message = "Building AAB zip module %s" % out.short_path,
        toolchain = ANDROID_TOOLCHAIN_TYPE,
    )

bundletool = struct(
    build = _build,
    build_device_json = _build_device_json,
    build_sdk_apks = _build_sdk_apks,
    build_sdk_bundle = _build_sdk_bundle,
    build_sdk_module = _build_sdk_module,
    bundle_to_apks = _bundle_to_apks,
    extract_config = _extract_config,
    extract_manifest = _extract_manifest,
    proto_apk_to_module = _proto_apk_to_module,
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 00:14:35 2018

@author: liuchuang
"""

import numpy as np

a = np.arange(10)

### 1 通过下标范围产生数组  和原数组共享数据空间
b=a[::-1]  ## 步长为负数 倒序
c=a[3:7]   ### 左开右闭

### 2 通过整数序列 元素选取 每个元素作为下标  获得新数组 不共享空间

d=a[[1,2,3,5]]
a[[1,2,3]]=4,5,6

print(a,b,c,d)

### 3 布尔数组

e = np.arange(3)
f=e[np.array([True,False,True])]
print('\n\n')
print(f)


filename = "Inputs/" + __file__.strip("py") + "txt"
with open(filename, "r") as file:
    data = [line.strip() for line in file.readlines()]

def Part1():
    numVisible = len(data) * 2 + len(data[0]) * 2 - 4

    for i in range(1, len(data) - 1):
        for j in range(1, len(data[i]) - 1):
            tree = int(data[i][j])
            row = data[i]
            col = [data[k][j] for k in range(len(data))]

            if ((tree > int(max(row[:j]))) or
                (tree > int(max(row[j + 1:]))) or
                (tree > int(max(col[:i]))) or
                (tree > int(max(col[i + 1:])))):
                numVisible += 1
                continue

    return numVisible

def Part2():
    bestScore = 0

    for i in range(1, len(data) - 1):
        for j in range(1, len(data[i]) - 1):
            score, north, south, east, west = 0, 0, 0, 0, 0
            tree = int(data[i][j])
            row = data[i]
            col = [data[k][j] for k in range(len(data))]

            for k in range(j - 1, -1, -1):
                west += 1
                if (tree <= int(row[k])):
                    break

            for k in range(j + 1, len(row)):
                east += 1
                if (tree <= int(row[k])):
                    break

            for k in range(i - 1, -1, -1):
                north += 1
                if (tree <= int(col[k])):
                    break

            for k in range(i + 1, len(col)):
                south += 1
                if (tree <= int(col[k])):
                    break

            score = north * south * east * west

            if (score > bestScore):
                bestScore = score

    return bestScore

print(Part1())
print(Part2())


# Definition for a binary tree node.
from collections import deque
class TreeNode:
	def __init__(self, val=0, left=None, right=None):
		self.val = val
		self.left = left
		self.right = right
	def add_left_child(self, value):
		self.left = TreeNode(value)
	def add_right_child(self, value):
		self.right = TreeNode(value)

class Solution:
	def list_to_tree(self, tree_list):
		if len(tree_list) == 0:
			raise Exception('Cannot build an empty tree')
		elif tree_list[0] is None:
			raise Exception('Root cannot be null')
		while tree_list:
			root = TreeNode(tree_list.pop(0))
			curr = root
			curr.add_left_child(tree_list.pop[0])
			curr.add_right_child(tree_list.pop[0])
			if curr.left is not None:
				curr = curr.left
			elif curr.right is not None:
				curr = curr.right

		return root

	def verticalOrder(self, root):
		nodes = {}
        #while root not None:

l = [9, 8]
solution = Solution()
a = solution.list_to_tree(l)
print(a.val)


'''
Created on Feb 13, 2014

@author: theo
'''
import os
from django.core.management.base import BaseCommand, CommandError
from acacia.data.models import Project, ProjectLocatie, MeetLocatie, Datasource, Parameter, Series
from django.conf import settings

class Command(BaseCommand):
    args = ''
    help = 'Deletes unused files from upload area'

    def handle(self, *args, **options):
        # get all files in use
        inuse = ([p.image.path for p in Project.objects.exclude(image='')])
        inuse.extend([l.image.path for l in ProjectLocatie.objects.exclude(image='')])
        inuse.extend([m.image.path for m in MeetLocatie.objects.exclude(image='')])
        inuse.extend([f.filepath() for ds in Datasource.objects.all() for f in ds.sourcefiles.all()])
        inuse.extend([p.thumbpath() for p in Parameter.objects.exclude(thumbnail='')])
        inuse.extend([s.thumbpath() for s in Series.objects.exclude(thumbnail='')])

        count = 0
        for path, folders, files in os.walk(settings.MEDIA_ROOT):
            for f in files:
                name = os.path.join(path,f)
                if not name in inuse:
                    self.stdout.write('Deleting %s\n' % name)
                    try:
                        os.remove(name)
                        count = count+1
                    except Exception as e:
                        self.stdout.write('Error deleting %s: %s\n' % (name,e))
                else:
                    #self.stdout.write('Keeping %s\n' % name)
                    pass

        self.stdout.write('%d files deleted\n' % count)


from django.conf.urls import url

from . import views

from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^login/$', views.authentication, name="authentication"),
    url(r'^logout$', auth_views.logout, {'next_page': '/'}, name="logout", ),
    url(r'^report/$', views.report, name='report'),
    url(r'^reportnivelsalud/$', views.reportnivelsalud, name='reportnivelsalud'),
    url(r'^reportfactorescondicionantes/$', views.reportfactorescondicionantes, name='reportfactorescondicionantes'),
    url(r'^NSr1/$', views.NSr1, name='NSr1'),
    url(r'^NSr2/$', views.NSr2, name='NSr2'),
    url(r'^NSr3/$', views.NSr3, name='NSr3'),
    url(r'^NSr4/$', views.NSr4, name='NSr4'),
    url(r'^NSr5/$', views.NSr5, name='NSr5'),
    url(r'^NSr6/$', views.NSr6, name='NSr6'),
    url(r'^NSr7/$', views.NSr7, name='NSr7'),
    url(r'^NSr8/$', views.NSr8, name='NSr8'),
    url(r'^FCr1/$', views.FCr1, name='FCr1'),
    url(r'^FCr2/$', views.FCr2, name='FCr2'),
    url(r'^FCr3/$', views.FCr3, name='FCr3'),
    url(r'^NSf1/$', views.NSf1, name='NSf1'),
    url(r'^FCf1/$', views.FCf1, name='FCf1'),
    url(r'^ingresar/$', views.ingresardatos, name='ingresar'),

    # url(r'^$', views.login),
    # url(r'^$', views.index, name='index'),
    # url(r'^index/$', views.index, name='index'),
    # url(r'^factorescondicionantes/$', views.factorescondicionantes, name='factorescondicionantes'),

]


class SolapamientoLaberinto:

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

    def verificar(self, posiblePos):
        caminoB = False
        virusB = False
        metaB = False
        dict = self.tablero.dictCuadros
        for piso in dict['camino']:
            (pisoX, pisoY) = (piso.posicion.x, piso.posicion.y)
            if (pisoX, pisoY) == posiblePos:
                caminoB = True
        for virus in dict['virus']:
            (virusX, virusY) = (virus.posicion.x, virus.posicion.y)
            if (virusX, virusY) == posiblePos:
                dict['personaje'].numeroVidas -= 1
                corazon = dict['personaje'].numeroVidas
                dict['vidas'][corazon].lleno = 0
                if dict['personaje'].numeroVidas == 0:
                    for mensaje in dict['mensaje']:
                        if mensaje.getNombre() == 'perdida':
                            mensaje.permitirDibujo(True)
                virusB = True
        (metaX, metaY) = (dict['meta'].posicion.x, dict['meta'].posicion.y)
        if (metaX, metaY) == posiblePos:
            for mensaje in dict['mensaje']:
                if mensaje.getNombre() == 'victoria':
                    mensaje.permitirDibujo(True)
            metaB = True
        return caminoB or virusB or metaB


def IRRIGADOR(ONOFF: str):
    if ONOFF == "ON":
        pins.digital_write_pin(DigitalPin.P0, 1)
    else:
        pins.digital_write_pin(DigitalPin.P0, 0)

def on_bluetooth_connected():
    basic.show_string("C")
bluetooth.on_bluetooth_connected(on_bluetooth_connected)

def on_bluetooth_disconnected():
    basic.show_string("D")
bluetooth.on_bluetooth_disconnected(on_bluetooth_disconnected)

def DECODIFICADOR():
    if led.point(1, 0) and (led.point(2, 0) and (led.point(3, 0) and (led.point(2, 1) and led.point(2, 2)))):
        basic.show_string("TEMPERATURA:")
        basic.show_number(input.temperature())
        basic.clear_screen()
    elif led.point(1, 0) and (led.point(2, 0) and (led.point(2, 1) and (led.point(2, 2) and led.point(3, 2)))):
        basic.show_string("LUMINOSIDADE:")
        basic.show_number(input.light_level())
        basic.clear_screen()
    elif led.point(0, 0) and (led.point(2, 2) and (led.point(0, 4) and (led.point(4, 0) and led.point(4, 4)))):
        basic.show_string("UMIDADE:")
        basic.show_number(UMIDADE)
        basic.clear_screen()
    elif led.point(1, 1) and (led.point(1, 2) and (led.point(2, 3) and (led.point(3, 1) and led.point(3, 2)))):
        IRRIGADOR("ON")
        basic.pause(10000)
        IRRIGADOR("OFF")
        basic.clear_screen()
    elif led.point(2, 2) and (led.point(1, 3) and (led.point(1, 4) and (led.point(3, 3) and led.point(3, 4)))):
        VENTILADOR("ON")
        basic.pause(10000)
        VENTILADOR("OFF")
        basic.clear_screen()
def VENTILADOR(ONOFF2: str):
    if ONOFF2 == "ON":
        pins.digital_write_pin(DigitalPin.P1, 1)
    else:
        pins.digital_write_pin(DigitalPin.P1, 0)
def AUTOMAÇÃO():
    if input.temperature() > 35:
        VENTILADOR("ON")
    else:
        VENTILADOR("OFF")
    if UMIDADE > 60:
        IRRIGADOR("ON")
    else:
        IRRIGADOR("OFF")
UMIDADE = 0
bluetooth.start_led_service()

def on_forever():
    AUTOMAÇÃO()
    DECODIFICADOR()
basic.forever(on_forever)


def solution(s):
    answer = []
    s_li = s.split(" ")
    for i in s_li:

        tmp_li = []
        for j in range(0,len(i)):

            if j % 2 == 0 :
                tmp_li.append(i[j].upper())

            else :
                tmp_li.append(i[j].lower())
        tmp_li="".join(tmp_li)
        answer.append(tmp_li)

    answer=" ".join(answer)
    return answer

프로그래머스/lv1/12930. 이상한 문자 만들기/이상한 문자 만들기.py

이상한 문자 만들기.py


from grt.core import Constants

constants = Constants()

class Intake:
    """
    Intake mechanism, with roller motor, two independent angle
    change motors and 4 (left front/rear, right front/rear) limits
    """
    motor_power = 1

    def __init__(self, roller, achange_left, achange_right,
                 achange_limit_lf, achange_limit_lr,
                 achange_limit_rf, achange_limit_rr):
        self.roller = roller
        self.achange_l = achange_left
        self.achange_r = achange_right
        self.limit_lf = achange_limit_lf
        self.limit_lr = achange_limit_lr
        self.limit_rf = achange_limit_rf
        self.limit_rr = achange_limit_rr
        self.limit_lf.add_listener(self._limit_listener)
        self.limit_lr.add_listener(self._limit_listener)
        self.limit_rf.add_listener(self._limit_listener)
        self.limit_rr.add_listener(self._limit_listener)

    def set_ep(self, power):
        self.roller.Set(power * self.motor_power)

    def start_ep(self):
        self.roller.Set(self.motor_power)

    def stop_ep(self):
        self.roller.Set(0)

    def reverse_ep(self):
        self.roller.Set(-self.motor_power)

    def angle_change(self, power):
        '''
        Set power of angle change. Power > 0 --> forwards.
        '''
        if power > -.5 or power < .5:
            self.achange_l.Set(0)
            self.achange_r.Set(0)

        if power == 0 or\
           power > 0 and not self.limit_lf.pressed or\
           power < 0 and not self.limit_lr.pressed:
            self.achange_l.Set(-power)
        if power == 0 or\
           power > 0 and not self.limit_rf.pressed or\
           power < 0 and not self.limit_rr.pressed:
            self.achange_r.Set(-power)

    def _limit_listener(self, source, state_id, datum):
        if state_id == 'pressed' and datum:
            if source == self.limit_lf and self.achange_l.Get() < 0:
                self.achange_l.Set(0)
            if source == self.limit_lr and self.achange_l.Get() > 0:
                self.achange_l.Set(0)
            if source == self.limit_rf and self.achange_r.Get() < 0:
                self.achange_r.Set(0)
            if source == self.limit_rr and self.achange_r.Get() > 0:
                self.achange_r.Set(0)

class Shooter:
    """
    Shooter mechanism, using winch.
    Pass winch args to constructor.
    """
    SP = constants['SP']
    SC = constants['SC']  # uses a constant offset, instead of an integral term
    LIMIT = constants['SLimit']
    target = 0
    autowinding = False

    def __init__(self, winch_motor, actuator, winch_limit, potentiometer):
        self.winch_motor = winch_motor
        self.actuator = actuator
        self.winch_limit = winch_limit
        self.potentiometer = potentiometer

        constants.add_listener(self._constants_listener)
        #potentiometer.add_listener(self._potentiometer_listener)
        winch_limit.add_listener(self._limit_listener)

    def _potentiometer_listener(self, source, state_id, datum):
        '''
        Stops winding if going too far.
        Controls automatic winding if autowinding is enabled.
        '''
        if state_id == 'angle':
            if datum > self.LIMIT or self.winch_limit.pressed:
                self.winch_stop()
            elif self.autowinding:
                if datum > self.target:  # passed target
                    self.winch_stop()
                else:
                    self.winch_motor.Set(self.SC + self.SP * (self.target - datum))

    def _limit_listener(self, source, state_id, datum):
        '''
        Stops winding if going too far
        '''
        if state_id == 'pressed' and datum:
            self.winch_stop()

    def _constants_listener(self, sensor, state_id, datum):
        if state_id in ('SP', 'SC'):
            self.__dict__[state_id] = datum
        elif state_id == 'SLimit':
            self.LIMIT = datum

    def winch_wind(self, power):
        '''
        Winds the winch. Cancels autowinding when called.
        '''
        self.autowinding = False
        #if power >= 0 and self.potentiometer.angle < self.LIMIT and not self.winch_limit.pressed:
        if power >= 0 and not self.winch_limit.pressed:
            self.winch_motor.Set(-power)

    def winch_stop(self):
        '''
        Stops winding the winch. Cancels autowinding.
        '''
        self.autowinding = False
        self.winch_motor.Set(0)

    def latch(self):
        self.actuator.Set(False)

    def unlatch(self):
        self.actuator.Set(True)

    def set_angle(self, target):
        '''
        Starts automatically winding shooter.
        '''
        self.target = target
        self.autowinding = True

class Defense:
    """
    Defense mechanism, using pneumatic solenoid.
    Pass winch args to constructor.
    """
    def __init__(self, solenoid):
        self.solenoid = solenoid

    def extend(self):
        self.solenoid.Set(True)

    def retract(self):
        self.solenoid.Set(False)


import os
from datetime import date

import dateutil

from src.examples.program.traccar.config.config import Config
from src.examples.program.traccar.config.keys import Keys

class MediaManager:

    _LOGGER = "LoggerFactory.getLogger(MediaManager.class)"

    def __init__(self, config):

        self._path = None

        self._path = config.getString(Keys.MEDIA_PATH)

    def _createFile(self, uniqueId, name):
        filePath = os.O_PATH.get(self._path, uniqueId, name)
        directoryPath = filePath.getParent()
        if directoryPath is not None:
            filePath.createDirectories(directoryPath)
        return filePath.toFile()

    def createFileStream(self, uniqueId, name, extension):
        return "FileOutputStream(self._createFile(uniqueId, name + \".\" + extension))"

    def writeFile(self, uniqueId, buf, extension):
        if self._path is not None:
            size = buf.readableBytes()
            name = (dateutil.formatDate("yyyyMMddHHmmss")).format(date()) + "." + extension
            try:
                with "FileOutputStream(createFile(uniqueId, name))" as output, output.getChannel() as fileChannel:
                    byteBuffer = buf.nioBuffer()
                    written = 0
                    while written < size:
                        written += fileChannel.write(byteBuffer)
                    fileChannel.force(False)
                    return name
            except Exception as e:
                MediaManager._LOGGER.warn("Save media file error", e)
        return None


# Programa simples para testar os sensores

# Importa as bibliotecas
import time
import board
import adafruit_dht
# from board import D18

# Inicialização do dispositivo no pino:
dht_device = adafruit_dht.DHT11(board.D18)
#Para ler do  DHT22
#dht_device = adafruit_dht.DHT22(<pin>)

while True:
    try:
        # Para ler a Temperatura
        temperatura = dht_device.temperature
        # Para ler a umidade
        humidade = dht_device.humidity
        print(f"Temperatura:  {temperatura, :.1f} C    Humididate: {humidade}% ")

    except RuntimeError as error:
        # Se aparecer erros
        print(error.args[0])

    time.sleep(5.0)


import numpy as np
import matplotlib.pyplot as plt

def test_polyreg_univariate():
    '''
        Test polynomial regression
    '''

    # load the data
    filepath = "./test.txt"
    df = pd.read_csv(filepath, header=None)

    X = df[df.columns[:-1]]
    y = df[df.columns[-1]]

    # regression with degree = d
    d = 8
    model = PolynomialRegression(degree=d, tuneLambda=True, regLambdaValues= [ 0.001, 0.003, 0.001])
    model.fit(X, y)

    # output predictions
    xpoints = pd.DataFrame(np.linspace(np.max(X), np.min(X), 100))
    ypoints = model.predict(xpoints)
    # plot curve
    plt.figure()
    plt.plot(X, y, 'rx')
    plt.title('PolyRegression with d = '+str(d))
    plt.plot(xpoints, ypoints, 'b-')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.show()
    print(model.theta)

    #  # # Compute the closed form solution
    # n,d = X.shape
    # X = np.asmatrix(X.to_numpy())
    # X = np.c_[np.ones((n,1)), X]     # Add a row of ones for the bias term
    # y = np.asmatrix(y.to_numpy())

    # y = y.reshape(n,1)
    # thetaClosedForm = inv(X.T*X)*X.T*y
    # print("thetaClosedForm: ", thetaClosedForm.T)

test_polyreg_univariate()


from datetime import date
from typing import List, Optional

from pydantic import BaseModel

class UserBase(BaseModel):
    email: str
    username: str
    tanggal_lahir: date
    alamat: str
    status: Optional[str]
    no_telp: str

class UserUpdate(BaseModel):
    email: Optional[str]
    username: Optional[str]
    tanggal_lahir: Optional[date]
    alamat: Optional[str]
    status: Optional[str]
    no_telp: Optional[str]

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int

    class Config:
        orm_mode = True

class ProductBase(BaseModel):
    nama_product: Optional[str]
    harga: Optional[int]
    deskripsi: Optional[str]
    stok: Optional[int]
    gambar: Optional[str]

class Product(ProductBase):
    product_id: int

    class Config:
        orm_mode = True

class Token(BaseModel):
    access_token: str
    token_type: str

class TokenData(BaseModel):
    username: Optional[str] = None
    email: Optional[str] = None

class MemberBase(BaseModel):
    member_id: int
    poin: int


import requests
from bs4 import BeautifulSoup
import pandas as pd
import pathlib
import datetime

def fetch(which):
    url = 'https://isin.twse.com.tw/isin/C_public.jsp'
    param = dict(
        exchange={'strMode':'2'},
        otc={'strMode':'4'})
    response = requests.get(url, param[which])
    assert response.status_code == 200
    return response.text

def get_html(which):
    print(f'overview GET {which:8} html:', end='\t')
    path = agent.joinpath(which).with_suffix('.html')
    if path.exists():
        print('EXIST', end='\t')
    else:
        print('REQUEST', end='\t')
        text = fetch(which)
        path.write_text(text,encoding='utf8')
    print('SUCCESS!')
    return None

def read_html(which):
    path = agent.joinpath(which).with_suffix('.html')
    text = path.read_text(encoding='utf8')
    soup = BeautifulSoup(text, 'lxml')

    labels = [''.join(t.text.split())
                for t in soup.find_all('b', text=lambda x: x != ' ')]

    table = pd.read_html(text, header=0,converters={})[0]
    table.loc[table['備註'].isin(labels), 'labels'] = labels
    table['labels'] = table['labels'].ffill()
    table = table.loc[~table['備註'].isin(labels)]

    split = table['有價證券代號及名稱'].str.split(expand=True)

    table['ID'] = split[0]

    table['name'] = split.loc[:,1:].fillna('').apply(lambda row: ''.join(row),axis=1)

    table['is_stock'] = table['labels'] == '股票'

    table['industry'] = table['產業別']
    table['market'] = which

    table = table[['ID', 'name', 'is_stock','industry','market']]

    table = table.reset_index(drop=True)
    return table

def html_to_csv(which):
    print(f'PARSE {which:8} html',end='\t')
    path = agent.joinpath(which).with_suffix('.csv')
    table = read_html(which)
    table.to_csv(path.as_posix(),encoding='utf8')
    print('SUCCESS!')
    return table

def read_csv(which):
    path = agent.joinpath(which).with_suffix('.csv')
    if path.exists():
        print(f'{which:8} CSV EXIST!')
        table = pd.read_csv(path.as_posix(),encoding='utf8',dtype={'ID':str},index_col=0)
    else:
        table = html_to_csv(which)
    return table

def merge_csv():
    path = agent.joinpath('merge').with_suffix('.csv')
    exchange = read_csv('exchange')
    otc = read_csv('otc')
    print('MERGE')
    table = exchange.append(otc, ignore_index=False)
    duplicate = table.loc[table.ID.duplicated(False)]
    if not duplicate.empty:
        print('\n','='*25,'合併上市上櫃一覽表時發現重複代碼','='*25)
        display(duplicate)
        assert False, f'duplicate: {duplicate.ID.unique()}'
    table = table.reset_index(drop=True)
    table.to_csv(path.as_posix(),encoding='utf8')
    return table

def read_merge():
    path = agent.joinpath('merge').with_suffix('.csv')
    if path.exists():
        print('MERGE CSV EXIST!')
        table = pd.read_csv(path.as_posix(),encoding='utf8',dtype={'ID':str},index_col=0)
    else:
        table = merge_csv()
    return table

def release():
    release_file = ['*.csv','*.html']
    for file in release_file:
        for item in agent.glob(file):
            item.unlink()

def update():
    print('='*10,str(datetime.date.today()),'='*10)
    get_html('exchange')
    get_html('otc')
    path = depository.joinpath('data.csv')
    new_data = read_merge()
    new_data['status'] = 'new'
    print('UPDATE')
    if path.exists():
        previous_data = pd.read_csv(path.as_posix(),encoding='utf8',dtype={'ID':str}, index_col=0)
        previous_data['status'] = 'data'

        merge_data = previous_data.append(new_data, ignore_index=False)
        merge_data = merge_data.drop_duplicates(subset=['ID','name','is_stock','market'])

        duplicate = merge_data.loc[merge_data.ID.duplicated(False)]
        if not duplicate.empty:
            print('\n','='*25,'一覽表添加新資料時發現內容不重複，但代碼重複的資料','='*25)
            display(duplicate)
            assert False, f'duplicate: {duplicate.ID.unique()}'
    else:
        merge_data = new_data
    merge_data = merge_data.reset_index(drop=True)
    merge_data = merge_data.drop('status',axis=1)
    merge_data.to_csv(path,encoding='utf8')
    print('RELEASE')
    release()
    print('FINISH!')


from gensim.models import KeyedVectors

import image_read as image_read

import pandas as pd
import re
import numpy as np
from ast import literal_eval

'''
This class receives the image,
performs the similarity and recommends the quotes
'''

class QuoteFinder:
    def __init__(self, path):
        self.path = path
        #################### Loading word2vec model
        filename = 'resources/model/glove.6B.50d.txt.word2vec'
        self.word2vec_model = KeyedVectors.load_word2vec_format(filename, binary=False)

    def find_quote(self):
        #################### Loading the quote database
        quote_path = "resources/quote_model/quote_v3_quotes_trained_word2vec.csv"
        quote_df = pd.read_csv(quote_path)

        quote_df['filtered'].replace('', np.nan, inplace=True)
        # print(quote_df[quote_df.isna().any(axis=1)])
        quote_df.dropna(inplace=True)
        quote_df['filtered'] = quote_df['filtered'].apply(lambda x: literal_eval(x))

        #################### Reading google API output and extracting the image annotations
        image_labels = image_read.im_read(self.path)
        # print(image_labels)

        #################### Calculating similarity
        similarity_df = self.__similarity(quote_df, image_labels)

        return similarity_df['Quote'].head(8).tolist()

    def __similarity(self, quote_df, im_filtered):
        if(im_filtered):
            quote_df['new'] = quote_df['filtered'].apply(lambda x: self.word2vec_model.n_similarity(x, im_filtered))
        else:
            print("failed")
        new_quote = quote_df.sort_values(by=['new'], ascending=False)
        return new_quote


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

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.http import HttpResponseRedirect

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'tsune.views.home', name='home'),
    # url(r'^tsune/', include('tsune.foo.urls')),

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

    url(r'^$', lambda x: HttpResponseRedirect('/cardbox/')),  # redirect to /cardbox/
    url(r'^admin/', include(admin.site.urls)),
    url(r'^cardbox/', include('deckglue.deckurls', namespace="deck")),
    url(r'^user/', include('authentication.urls')),
    url(r'^learning/', include('deckglue.learningurls', namespace="learning")),
    url(r'^cardbox/cards/', include('deckglue.cardurls', namespace="card")),
    url(r'^markitup/', include('markitup.urls')),
    url(r'^profile/', include('profiles.urls', namespace="profile")),
    url(r'^inplaceeditform/', include('inplaceeditform.urls')),
    url(r'^upload/', include('upload.urls', namespace="upload")),
    url(r'^comic/', include('comic.urls'))
)


"""
Leetcode 144
Given a binary tree, return the preorder traversal of its nodes' values.
Recursive solution is trivial, could you do it iteratively?
"""

class Node:
    def __init__(self, v):
        self.val = v
        self.left = None
        self.right = None

def preorder_iterative(root):
    stack, res = [], []
    curr = root
    while curr or stack:
        if curr:
            res.append(curr.val)
            stack.append(curr.right)
            stack.append(curr.left)
        curr = stack.pop()
    return res

def preorder_recursive(root):
    res = []
    def helper(node):
        if node:
            res.append(node.val)
            helper(node.left)
            helper(node.right)
    helper(root)
    return res

def test_preorder_iterative():
    A = Node('A')
    B = Node('B')
    C = Node('C')
    D = Node('D')
    E = Node('E')
    F = Node('F')
    G = Node('G')
    H = Node('H')
    I = Node('I')
    F.left = B
    F.right = G
    B.left = A
    B.right = D
    D.left = C
    D.right = E
    G.right = I
    I.left = H
    assert preorder_iterative(F) == ['F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H']
    assert preorder_recursive(F) == ['F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H']


#!/usr/bin/python3
"""
    Module 3-say_my_name.py with the function say_my_name
"""

def say_my_name(first_name, last_name=""):
    """Functions that prints a complete name in a sentence"""
    if type(first_name) is not str:
        raise TypeError('first_name must be a string')
    elif type(last_name) is not str:
        raise TypeError('last_name must be a string')
    print("My name is {} {}".format(first_name, last_name))


# Released under the MIT License. See LICENSE for details.
#
"""Functionality related to managing cloud based assets."""

from __future__ import annotations

from typing import TYPE_CHECKING, Annotated
from dataclasses import dataclass, field
from pathlib import Path
import threading
import urllib.request
import logging
import weakref
import time
import os
import sys

from efro.dataclassio import (
    ioprepped,
    IOAttrs,
    dataclass_from_json,
    dataclass_to_json,
)
import _babase

if TYPE_CHECKING:
    from bacommon.assets import AssetPackageFlavor

@ioprepped
@dataclass
class FileValue:
    """State for an individual file."""

@ioprepped
@dataclass
class State:
    """Holds all persistent state for the asset-manager."""

    files: Annotated[dict[str, FileValue], IOAttrs('files')] = field(
        default_factory=dict
    )

class AssetManager:
    """Wrangles all assets."""

    _state: State

    def __init__(self, rootdir: Path) -> None:
        print('AssetManager()')
        assert isinstance(rootdir, Path)
        self.thread_ident = threading.get_ident()
        self._rootdir = rootdir
        self._started = False
        if not self._rootdir.is_dir():
            raise RuntimeError(f'Provided rootdir does not exist: "{rootdir}"')

        self.load_state()

    def __del__(self) -> None:
        print('~AssetManager()')
        if self._started:
            logging.warning('AssetManager dying in a started state.')

    def launch_gather(
        self,
        packages: list[str],
        flavor: AssetPackageFlavor,
        account_token: str,
    ) -> AssetGather:
        """Spawn an asset-gather operation from this manager."""
        print(
            'would gather',
            packages,
            'and flavor',
            flavor,
            'with token',
            account_token,
        )
        return AssetGather(self)

    def update(self) -> None:
        """Can be called periodically to perform upkeep."""

    def start(self) -> None:
        """Tell the manager to start working.

        This will initiate network activity and other processing.
        """
        if self._started:
            logging.warning('AssetManager.start() called on running manager.')
        self._started = True

    def stop(self) -> None:
        """Tell the manager to stop working.

        All network activity should be ceased before this function returns.
        """
        if not self._started:
            logging.warning('AssetManager.stop() called on stopped manager.')
        self._started = False
        self.save_state()

    @property
    def rootdir(self) -> Path:
        """The root directory for this manager."""
        return self._rootdir

    @property
    def state_path(self) -> Path:
        """The path of the state file."""
        return Path(self._rootdir, 'state')

    def load_state(self) -> None:
        """Loads state from disk. Resets to default state if unable to."""
        print('ASSET-MANAGER LOADING STATE')
        try:
            state_path = self.state_path
            if state_path.exists():
                with open(self.state_path, encoding='utf-8') as infile:
                    self._state = dataclass_from_json(State, infile.read())
                    return
        except Exception:
            logging.exception('Error loading existing AssetManager state')
        self._state = State()

    def save_state(self) -> None:
        """Save state to disk (if possible)."""

        print('ASSET-MANAGER SAVING STATE')
        try:
            with open(self.state_path, 'w', encoding='utf-8') as outfile:
                outfile.write(dataclass_to_json(self._state))
        except Exception:
            logging.exception('Error writing AssetManager state')

class AssetGather:
    """Wrangles a gathering of assets."""

    def __init__(self, manager: AssetManager) -> None:
        assert threading.get_ident() == manager.thread_ident
        self._manager = weakref.ref(manager)
        # self._valid = True
        print('AssetGather()')
        # url = 'https://files.ballistica.net/bombsquad/promo/BSGamePlay.mov'
        # url = 'http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz'
        # fetch_url(url,
        #           filename=Path(manager.rootdir, 'testdl'),
        #           asset_gather=self)
        # print('fetch success')
        thread = threading.Thread(target=self._run)
        thread.run()

    def _run(self) -> None:
        """Run the gather in a background thread."""
        print('hello from gather bg')

        # First, do some sort of.

    # @property
    # def valid(self) -> bool:
    #     """Whether this gather is still valid.

    #     A gather becomes in valid if its originating AssetManager dies.
    #     """
    #     return True

    def __del__(self) -> None:
        print('~AssetGather()')

def fetch_url(url: str, filename: Path, asset_gather: AssetGather) -> None:
    """Fetch a given url to a given filename for a given AssetGather."""
    # pylint: disable=consider-using-with
    import socket

    # We don't want to keep the provided AssetGather alive, but we want
    # to abort if it dies.
    assert isinstance(asset_gather, AssetGather)
    # weak_gather = weakref.ref(asset_gather)

    # Pass a very short timeout to urllib so we have opportunities
    # to cancel even with network blockage.
    req = urllib.request.urlopen(
        urllib.request.Request(
            url, None, {'User-Agent': _babase.user_agent_string()}
        ),
        context=_babase.app.net.sslcontext,
        timeout=1,
    )
    file_size = int(req.headers['Content-Length'])
    print(f'\nDownloading: {filename} Bytes: {file_size:,}')

    def doit() -> None:
        time.sleep(1)
        print('dir', type(req.fp), dir(req.fp))
        print('WOULD DO IT', flush=True)
        # req.close()
        # req.fp.close()

    threading.Thread(target=doit).run()

    with open(filename, 'wb') as outfile:
        file_size_dl = 0

        block_sz = 1024 * 1024 * 1000
        time_outs = 0
        while True:
            try:
                data = req.read(block_sz)
            except ValueError:
                import traceback

                traceback.print_exc()
                print('VALUEERROR', flush=True)
                break
            except socket.timeout:
                print('TIMEOUT', flush=True)
                # File has not had activity in max seconds.
                if time_outs > 3:
                    print('\n\n\nsorry -- try back later')
                    os.unlink(filename)
                    raise
                print(
                    '\nHmmm... little issue... '
                    'I\'ll wait a couple of seconds'
                )
                time.sleep(3)
                time_outs += 1
                continue

            # We reached the end of the download!
            if not data:
                sys.stdout.write('\rDone!\n\n')
                sys.stdout.flush()
                break

            file_size_dl += len(data)
            outfile.write(data)
            percent = file_size_dl * 1.0 / file_size
            status = f'{file_size_dl:20,} Bytes [{percent:.2%}] received'
            sys.stdout.write('\r' + status)
            sys.stdout.flush()
    print('done with', req.fp)


from pyspark import SparkContext
from pyspark.sql import SparkSession

class SparkSpawner:
    @classmethod
    def get_spark(self) -> SparkSession:
        spark_builder = SparkSession.builder.appName('BigDW')\
            .enableHiveSupport() \
            .config("spark.jars.packages","io.delta:delta-core_2.11:0.5.0")  \
            .config("spark.jars.packages", "com.microsoft.sqlserver:mssql-jdbc:7.0.0.jre8,io.delta:delta-core_2.11:0.5.0")
            #.config("hive.metastore.warehouse.dir","d:/AppData/Metastore/")
            #.config("spark.sql.extensions","io.delta.sql.DeltaSparkSessionExtension")
        spark = spark_builder.getOrCreate()

        return spark


import scapy.all as sp
import datetime as dt

class TCPDumpHelper:

    def __init__(self, p):
        self.path = p
        # with Jan 1 1970 as reference, the exp_day is the no of seconds till experiment day
        self.exp_day = 1539388800
        self.ist_hour = 5
        self.ist_mins = 30
        self.Mac_IP_Map = dict()
        self.Mac_IP_Map['e8:4e:06:24:e8:e4'] = "10.10.10.5"
        self.Mac_IP_Map['bc:30:7e:07:97:ce'] = "10.10.10.40"
        self.Mac_IP_Map['00:1b:b1:b1:62:56'] = "10.10.10.50"
        self.Mac_IP_Map['00:80:48:6b:fd:16'] = "10.10.10.70"
        self.Mac_IP_Map['40:b8:9a:f7:42:dd'] = "10.10.10.71"
        self.Mac_IP_Map['00:0b:6b:02:0c:2e'] = "10.10.10.80"
        self.Mac_IP_Map['70:77:81:31:c0:3f'] = "10.10.10.81"
        self.Mac_IP_Map['ac:d1:b8:cf:a4:e1'] = "10.10.10.82"
        self.Mac_IP_Map['00:1b:b1:b1:62:4a'] = "10.10.10.90"
        self.Mac_IP_Map['60:6d:c7:4b:a7:f1'] = "10.10.10.91"
        self.Mac_IP_Map['d8:5d:e2:ab:e2:5f'] = "10.10.10.92"
        self.Mac_IP_Map['00:80:48:6b:fd:17'] = "10.10.10.100"
        self.Mac_IP_Map['10:08:b1:d1:f6:b3'] = "10.10.10.102"

        self.IP_Mac_Map = dict()
        self.IP_Mac_Map["10.10.10.5"] = "e8:4e:06:24:e8:e4"
        self.IP_Mac_Map["10.10.10.10"] = "00:0b:6b:02:0c:f2"
        self.IP_Mac_Map["10.10.10.11"] = ""
        self.IP_Mac_Map["10.10.10.12"] = ""
        self.IP_Mac_Map["10.10.10.20"] = "00:1b:b1:b1:62:4d"
        self.IP_Mac_Map["10.10.10.21"] = "9c:d2:1e:e6:e7:e3"
        self.IP_Mac_Map["10.10.10.22"] = "ac:d1:b8:74:ec:f3"
        self.IP_Mac_Map["10.10.10.30"] = "00:0b:6b:02:0d:61"
        self.IP_Mac_Map["10.10.10.31"] = "00:13:ce:e1:79:cb"
        self.IP_Mac_Map["10.10.10.32"] = "e4:f8:9c:fa:4a:33"
        self.IP_Mac_Map["10.10.10.40"] = " bc:30:7e:07:97:ce"
        self.IP_Mac_Map["10.10.10.41"] = "30:e3:7a:9d:a2:10"
        self.IP_Mac_Map["10.10.10.42"] = "00:13:ce:e1:79:cb"
        self.IP_Mac_Map["10.10.10.50"] = "00:1b:b1:b1:62:56"
        self.IP_Mac_Map["10.10.10.51"] = ""
        self.IP_Mac_Map["10.10.10.52"] = "80:86:f2:df:25:28"
        self.IP_Mac_Map["10.10.10.54"] = "b4:6d:83:22:ec:b4"
        self.IP_Mac_Map["10.10.10.60"] = "00:80:48:6b:fd:15"
        self.IP_Mac_Map["10.10.10.61"] = ""
        self.IP_Mac_Map["10.10.10.62"] = ""
        self.IP_Mac_Map["10.10.10.63"] = "64:5a:04:9d:e9:6a"
        self.IP_Mac_Map["10.10.10.70"] = "00:80:48:6b:fd:16"
        self.IP_Mac_Map["10.10.10.71"] = "40:b8:9a:f7:42:dd"
        self.IP_Mac_Map["10.10.10.72"] = ""
        self.IP_Mac_Map["10.10.10.80"] = "00:0b:6b:02:0c:2e"
        self.IP_Mac_Map["10.10.10.81"] = "70:77:81:31:c0:3f"
        self.IP_Mac_Map["10.10.10.82"] = "ac:d1:b8:cf:a4:e1"
        self.IP_Mac_Map["10.10.10.90"] = "00:1b:b1:b1:62:4a"
        self.IP_Mac_Map["10.10.10.91"] = "60:6d:c7:4b:a7:f1"
        self.IP_Mac_Map["10.10.10.92"] = "d8:5d:e2:ab:e2:5f"
        self.IP_Mac_Map["10.10.10.100"] = "00:80:48:6b:fd:17"
        self.IP_Mac_Map["10.10.10.101"] = ""
        self.IP_Mac_Map["10.10.10.102"] = "10:08:b1:d1:f6:b3"
        self.IP_Mac_Map["10.10.10.110"] = ""
        self.IP_Mac_Map['all'] = "ff:ff:ff:ff:ff:ff"

    def export_signal_strength(self, src_ip, save_path):
        is_all = src_ip == 'all'
        with open(save_path, 'w') as f:
            f.write("Src IP,Transmit Mac, Transmit IP, Dst IP,"
                    "Signal Strength, Time of the day, Raw time (seconds), Micros\n")
            for packet in sp.PcapReader(self.path):
                dels_sec = packet.time - self.exp_day
                dels_mins = dels_sec / 60
                secs = dels_sec % 60
                micro = int((secs - int(secs)) * 10 ** 6)
                secs = int(secs)
                mins = int(dels_mins % 60) + self.ist_mins
                hours = int(dels_mins / 60) + self.ist_hour
                timestamp = dt.datetime(year=2018, month=10, day=13, hour=hours, minute=mins,
                                        second=int(secs), microsecond=micro)
                if packet.haslayer(sp.IP) and packet.haslayer(sp.RadioTap):
                    if packet[sp.Dot11].fields['addr2'] == self.IP_Mac_Map[src_ip] or is_all:
                        f.write(packet[sp.IP].fields['src'] + "," + packet[sp.Dot11].fields['addr2']
                                + "," + src_ip + "," + packet[sp.IP].fields['dst'] + ","
                                + str(packet[sp.RadioTap].fields['dBm_AntSignal']) + "," + str(timestamp) +
                                "," + str(packet.time) + "," + str(int(micro)) + "\n")

    def export_inter_arrival_time(self, save_path):
        old = 0
        with open(save_path, 'w') as f:
            f.write("Time (milli), Time of the day, Raw time (seconds), Micros\n")
            for packet in sp.PcapReader(self.path):
                dels_sec = packet.time - self.exp_day
                dels_mins = dels_sec / 60
                secs = dels_sec % 60
                micro = int((secs - int(secs)) * 10 ** 6)
                secs = int(secs)
                mins = int(dels_mins % 60) + self.ist_mins
                hours = int(dels_mins / 60) + self.ist_hour
                timestamp = dt.datetime(year=2018, month=10, day=13, hour=hours, minute=mins,
                                        second=int(secs), microsecond=micro)

                delta = packet.time - old
                delta = delta * 1000
                old = packet.time
                f.write(str(delta)+","+str(timestamp)+","+str(packet.time) + "," + str(int(micro)) + "\n")

    def export_arrival_rate(self, save_path):
        count = 0
        old_time = 0
        with open(save_path, 'w') as f:
            f.write("Start Time,Rate\n")
            for packet in sp.PcapReader(self.path):
                dels_sec = packet.time - self.exp_day
                dels_mins = dels_sec / 60
                secs = dels_sec % 60
                micro = int((secs - int(secs)) * 10 ** 6)
                secs = int(secs)
                mins = int(dels_mins % 60) + self.ist_mins
                hours = int(dels_mins / 60) + self.ist_hour
                timestamp = dt.datetime(year=2018, month=10, day=13, hour=hours, minute=mins,
                                        second=secs, microsecond=micro)
                if old_time == 0:
                    old_time = timestamp
                    count = 1
                    continue
                else:
                    if (timestamp - old_time) > dt.timedelta(seconds=1):
                        f.write(str(old_time)+","+str(count)+"\n")
                        old_time = timestamp
                        count = 1
                    else:
                        count += 1


"""
https://leetcode.com/problems/sort-array-by-parity/

"""
from typing import List

class Solution:
    def sortArrayByParity(self, A: List[int]) -> List[int]:
        write_p = 0

        for i in range(len(A)):
            if A[i] % 2 == 0:
                A[i], A[write_p] = A[write_p], A[i]
                write_p += 1

        return A


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSlot, QThread, pyqtSignal, QRectF, QRect, QPointF, QLocale
import sys
from collections import OrderedDict
import pyqtgraph as pg
import numpy as np
from easydict import EasyDict as edict

class Viewer2DBasic(QObject):
    sig_double_clicked = pyqtSignal(float, float)

    def __init__(self,parent=None, **kwargs):
        super(Viewer2DBasic,self).__init__()
        #setting the gui
        if parent is None:
            parent=QtWidgets.QWidget()
        self.parent = parent
        self.scaling_options = edict(scaled_xaxis=edict(label="",units=None,offset=0,scaling=1),scaled_yaxis=edict(label="",units=None,offset=0,scaling=1))
        self.setupUI()

    def scale_axis(self,xaxis,yaxis):
        return xaxis*self.scaling_options.scaled_xaxis.scaling+self.scaling_options.scaled_xaxis.offset,yaxis*self.scaling_options.scaled_yaxis.scaling+self.scaling_options.scaled_yaxis.offset

    @pyqtSlot(float,float)
    def double_clicked(self,posx,posy):
        self.sig_double_clicked.emit(posx,posy)

    def setupUI(self):
        vlayout = QtWidgets.QVBoxLayout()
        hsplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)

        self.parent.setLayout(vlayout)
        vlayout.addWidget(hsplitter)
        self.ui = QObject()
        self.image_widget = ImageWidget()
        hsplitter.addWidget(self.image_widget)

        self.scaled_yaxis=AxisItem_Scaled('right')
        self.scaled_xaxis=AxisItem_Scaled('top')
        self.image_widget.plotitem.layout.addItem(self.scaled_xaxis, *(1,1))
        self.image_widget.plotitem.layout.addItem(self.scaled_yaxis, *(2,2))
        self.image_widget.view.sig_double_clicked.connect(self.double_clicked)
        self.scaled_xaxis.linkToView(self.image_widget.view)
        self.scaled_yaxis.linkToView(self.image_widget.view)

        # histograms
        self.histo_widget = QtWidgets.QWidget()
        histo_layout = QtWidgets.QHBoxLayout()
        self.histo_widget.setLayout(histo_layout)
        self.histogram_red = pg.HistogramLUTWidget()
        self.histogram_green = pg.HistogramLUTWidget()
        self.histogram_blue = pg.HistogramLUTWidget()
        Ntick = 3
        colors_red = [(int(r), 0, 0) for r in pg.np.linspace(0, 255, Ntick)]
        colors_green = [(0, int(g), 0) for g in pg.np.linspace(0, 255, Ntick)]
        colors_blue = [(0, 0, int(b)) for b in pg.np.linspace(0, 255, Ntick)]
        cmap_red = pg.ColorMap(pos=pg.np.linspace(0.0, 1.0, Ntick), color=colors_red)
        cmap_green = pg.ColorMap(pos=pg.np.linspace(0.0, 1.0, Ntick), color=colors_green)
        cmap_blue = pg.ColorMap(pos=pg.np.linspace(0.0, 1.0, Ntick), color=colors_blue)
        self.histogram_red.gradient.setColorMap(cmap_red)
        self.histogram_green.gradient.setColorMap(cmap_green)
        self.histogram_blue.gradient.setColorMap(cmap_blue)
        histo_layout.addWidget(self.histogram_red)
        histo_layout.addWidget(self.histogram_green)
        histo_layout.addWidget(self.histogram_blue)

        hsplitter.addWidget(self.histo_widget)

class ImageItem(pg.ImageItem):
    def __init__(self, image=None, **kargs):
        super(ImageItem, self).__init__(image, **kargs)

    def getHistogram(self, bins='auto', step='auto', targetImageSize=200, targetHistogramSize=500, **kwds):
        """Returns x and y arrays containing the histogram values for the current image.
        For an explanation of the return format, see numpy.histogram().

        The *step* argument causes pixels to be skipped when computing the histogram to save time.
        If *step* is 'auto', then a step is chosen such that the analyzed data has
        dimensions roughly *targetImageSize* for each axis.

        The *bins* argument and any extra keyword arguments are passed to
        np.histogram(). If *bins* is 'auto', then a bin number is automatically
        chosen based on the image characteristics:

        * Integer images will have approximately *targetHistogramSize* bins,
          with each bin having an integer width.
        * All other types will have *targetHistogramSize* bins.

        This method is also used when automatically computing levels.
        """
        if self.image is None:
            return None, None
        if step == 'auto':
            step = (int(np.ceil(self.image.shape[0] / targetImageSize)),
                    int(np.ceil(self.image.shape[1] / targetImageSize)))
        if np.isscalar(step):
            step = (step, step)
        stepData = self.image[::step[0], ::step[1]]

        if bins == 'auto':
            try:
                if stepData.dtype.kind in "ui":
                    mn = stepData.min()
                    mx = stepData.max()
                    step = np.ceil((mx - mn) / 500.)
                    bins = np.arange(mn, mx + 1.01 * step, step, dtype=np.int)
                    if len(bins) == 0:
                        bins = [mn, mx]
            except:
                bins = 500
            else:
                bins = 500

        kwds['bins'] = bins
        stepData = stepData[np.isfinite(stepData)]
        hist = np.histogram(stepData, **kwds)

        return hist[1][:-1], hist[0]

class ImageWidget(pg.GraphicsLayoutWidget):
    """this gives a layout to add imageitems.
    """
    def __init__(self, parent = None):
        QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates))
        super(ImageWidget, self).__init__(parent)
        self.setupUI()

    def setupUI(self):
        layout = QtWidgets.QGridLayout()
        #set viewer area
        self.scene_obj = self.scene()
        self.view = View_cust()
        self.plotitem = pg.PlotItem(viewBox=self.view)
        self.plotItem = self.plotitem #for backcompatibility
        self.plotitem.vb.setAspectLocked(lock=True, ratio=1)
        self.setCentralItem(self.plotitem)

class View_cust(pg.ViewBox):
    """Custom ViewBox used to enable other properties compared to parent class: pg.ViewBox

    """
    sig_double_clicked = pyqtSignal(float, float)

    def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False,
                 enableMenu=True, name=None, invertX=False):
        super(View_cust, self).__init__(parent, border, lockAspect, enableMouse, invertY, enableMenu, name,
                                        invertX)

    def mouseClickEvent(self, ev):
        if ev.button() == QtCore.Qt.RightButton and self.menuEnabled():
            ev.accept()
            self.raiseContextMenu(ev)
        if ev.double():
            pos = self.mapToView(ev.pos())
            self.sig_double_clicked.emit(pos.x(), pos.y())

class AxisItem_Scaled(pg.AxisItem):
    """
    Subclass of pg.AxisItem enabling scaling of the tick values with respect to the linked viewbox
    """

    def __init__(self, orientation, scaling=1, offset=0, pen=None, linkView=None, parent=None, maxTickLength=-5,
                 showValues=True):
        """
        ==============  ===============================================================
        **Arguments:**
        orientation     one of 'left', 'right', 'top', or 'bottom'
        scaling         multiplicative coeff applied to the ticks
        offset          offset applied to the ticks after scaling
        maxTickLength   (px) maximum length of ticks to draw. Negative values draw
                        into the plot, positive values draw outward.
        linkView        (ViewBox) causes the range of values displayed in the axis
                        to be linked to the visible range of a ViewBox.
        showValues      (bool) Whether to display values adjacent to ticks
        pen             (QPen) Pen used when drawing ticks.
        ==============  ===============================================================
        """
        pg.AxisItem.__init__(self, orientation, pen, linkView, parent, maxTickLength, showValues)
        self.scaling = scaling
        self.offset = offset

    def linkedViewChanged(self, view, newRange=None):
        if self.orientation in ['right', 'left']:
            if newRange is None:
                newRange = [pos * self.scaling + self.offset for pos in view.viewRange()[1]]
            else:
                newRange = [pos * self.scaling + self.offset for pos in newRange]

            if view.yInverted():
                self.setRange(*newRange[::-1])
            else:
                self.setRange(*newRange)
        else:
            if newRange is None:
                newRange = [pos * self.scaling + self.offset for pos in view.viewRange()[0]]
            else:
                newRange = [pos * self.scaling + self.offset for pos in newRange]
            if view.xInverted():
                self.setRange(*newRange[::-1])
            else:
                self.setRange(*newRange)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    form = QtWidgets.QWidget()
    prog = Viewer2DBasic(form)

    form.show()
    sys.exit(app.exec_())


import solution
from sortedcontainers import SortedList
import bisect

class Solution(solution.Solution):
    def solve(self, test_input=None):
        nums, k, t = test_input
        return self.containsNearbyAlmostDuplicate(list(nums), k, t)

    def containsNearbyAlmostDuplicate(self, nums, k, t):
        """
        :type nums: List[int]
        :type k: int
        :type t: int
        :rtype: bool
        """
        # O(N)
        if t < 0 or k < 0:
            return False
        all_buckets = {}
        bucket_size = t + 1  # 桶的大小设成t+1更加方便
        for i in range(len(nums)):
            bucket_num = nums[i] // bucket_size  # 放入哪个桶

            if bucket_num in all_buckets:  # 桶中已经有元素了
                return True

            all_buckets[bucket_num] = nums[i]  # 把nums[i]放入桶中

            if (bucket_num - 1) in all_buckets and abs(all_buckets[bucket_num - 1] - nums[i]) <= t:  # 检查前一个桶
                return True

            if (bucket_num + 1) in all_buckets and abs(all_buckets[bucket_num + 1] - nums[i]) <= t:  # 检查后一个桶
                return True

            # 如果不构成返回条件，那么当i >= k 的时候就要删除旧桶了，以维持桶中的元素索引跟下一个i+1索引只差不超过k
            if i >= k:
                all_buckets.pop(nums[i - k] // bucket_size)

        return False

        # # O(N logk)
        # window = SortedList()
        # for i in range(len(nums)):
        #     # len(window) == k
        #     if i > k:
        #         window.remove(nums[i - 1 - k])
        #     window.add(nums[i])
        #     idx = bisect.bisect_left(window, nums[i])
        #     if idx > 0 and abs(window[idx] - window[idx-1]) <= t:
        #         return True
        #     if idx < len(window) - 1 and abs(window[idx+1] - window[idx]) <= t:
        #         return True
        # return False


from django.test import TestCase

from core.models import User, ActivityPeriod
from core.views import get_user_data_by_id, get_all_user_data, get_user_activity_details

class UserTestCase(TestCase):

    def test_user(self):
        with self.assertRaises(User.DoesNotExist):
            user_1 = User.objects.get(id="W07QCRPA4")
            user_1_expected_output = '{"id": "W07QCRPA4", "real_name": "Glinda Southgood", "tz": "Asia/Kolkata"}'
            self.assertEquals(user_1.__str__(), user_1_expected_output)
        with self.assertRaises(User.DoesNotExist):
            User.objects.get(id="W07QCSQA6")

class ViewTestCase(TestCase):

    def test_get_user_data_by_id(self):
        user_1_id = "W07QCSQA6"
        self.assertEquals(get_user_data_by_id(user_1_id), None)

    def test_get_all(self):
        user_1_id = "W07QCSQA6"
        self.assertEquals(get_all_user_data(), None)

    def test_get_user_activity_details(self):
        user_1 = None
        self.assertEquals(get_user_activity_details(user_1), [])


from __future__ import absolute_import

from flask import current_app

from .builder import JenkinsBuilder

class JenkinsGenericBuilder(JenkinsBuilder):
    def __init__(self, master_urls=None, *args, **kwargs):
        self.script = kwargs.pop('script')
        self.cluster = kwargs.pop('cluster')
        self.path = kwargs.pop('path', '')
        self.workspace = kwargs.pop('workspace', '')

        if not master_urls:
            # if we haven't specified master urls, lets try to take the default
            # for this given cluster
            master_urls = current_app.config['JENKINS_CLUSTERS'].get(self.cluster)

        super(JenkinsGenericBuilder, self).__init__(master_urls, *args, **kwargs)

    def get_job_parameters(self, job, script=None, target_id=None, path=None):
        params = super(JenkinsGenericBuilder, self).get_job_parameters(
            job, target_id=target_id)

        if path is None:
            path = self.path

        if script is None:
            script = self.script

        project = job.project
        repository = project.repository

        vcs = repository.get_vcs()
        if vcs:
            repo_url = vcs.remote_url
        else:
            repo_url = repository.url

        params.extend([
            {'name': 'CHANGES_PID', 'value': project.slug},
            {'name': 'REPO_URL', 'value': repo_url},
            {'name': 'SCRIPT', 'value': script},
            {'name': 'REPO_VCS', 'value': repository.backend.name},
            {'name': 'CLUSTER', 'value': self.cluster},
            {'name': 'WORK_PATH', 'value': path},
            {'name': 'C_WORKSPACE', 'value': self.workspace},
        ])

        return params


from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

# print report
coffee_machine = CoffeeMaker()
money_machine = MoneyMachine()
menu_items = Menu()

machine_is_on = True

while machine_is_on:
    order = menu_items.get_items()
    # prompt user to make an order
    user_choice = str(input(f'What would you like? ({menu_items.get_items()}): ')).lower()

    try:
        if user_choice == "off":
            machine_is_on = False
        elif user_choice == "report":
            coffee_machine.report()
            money_machine.report()
        else:

            # find the drink
            drink = menu_items.find_drink(user_choice)
            if coffee_machine.is_resource_sufficient(drink):
                # process payments
                if money_machine.make_payment(drink.cost):
                    coffee_machine.make_coffee(drink)
    except AttributeError:
        print("Sorry wrong entry. Please try again!!")
        continue


import matplotlib.pyplot as plt
import numpy as np

from fluids.fittings import entrance_rounded, entrance_rounded_methods

rcs = np.linspace(0,0.4, 1000)
for method in entrance_rounded_methods:
    Ks = [entrance_rounded(Di=1.0, rc=rc, method=method) for rc in rcs]
    plt.plot(rcs, Ks, label=method)
plt.legend()
plt.title('Comparison of available methods for rounded flush entrances to pipes')
plt.xlabel('rc/Di')
plt.ylabel('K')
#plt.show()


import cv2
import os

for root, dirs, files in os.walk('pai/1/'):
    # print(root)
    # print(dirs)
    # print(files)
    if (files):
        for item in files:
            img = cv2.imread(os.path.join('pai/1', item))
            rows, cols = img.shape[:2]
            M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 15, 1.2)
            dst = cv2.warpAffine(img, M, (cols, rows))
            cv2.imwrite('pai/11/' + item + '_warp.jpg', dst)


import gym
import numpy as np
from stable_baselines3.common.env_checker import check_env
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3 import DQN

env = gym.make('navi_env:navi-env-v0')

train = True
new_train = True
model_name = "distance_matters"
steps = 10000

class TensorboardCallback(BaseCallback):

    def __init__(self, verbose=0):
        super(TensorboardCallback, self).__init__(verbose)

if train:
    if new_train:
        model = DQN(
            "MultiInputPolicy",
            env,
            learning_rate = 0.0003,
            buffer_size=1024,
            learning_starts = 0,
            target_update_interval=3000,
            exploration_final_eps=0,
            exploration_fraction=0.95,
            verbose=1,
            tensorboard_log="F:/navi_dqn/tensor/manhattan_end")

        model.learn(
            total_timesteps=steps,
            callback = TensorboardCallback(),
            log_interval=4,
            tb_log_name=model_name)

        model.save(model_name)

    else:
        model = DQN.load(model_name)
        model.set_env(env)

        model.learn(
            total_timesteps=steps,
            callback = TensorboardCallback(),
            log_interval=4,
            tb_log_name=model_name)

        model.save(model_name)

else:
    model = DQN.load(model_name)
    model.set_env(env)

    obs = env.reset()
    while True:
        action, _states = model.predict(obs, deterministic=True)
        obs, reward, done, info = env.step(action)
        env.render()
        if done:
          obs = env.reset()


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error,mean_squared_error
from keras.models import Model,Sequential
from keras.layers import Dense,Activation

df = pd.read_excel('AL_WIND_07_12.xlsx')

df['Time'] = df['DateTime'].dt.hour

df = df.drop(['DateTime'],axis=1)

Y = df['Power generated by system | (kW)']
X = df.drop(['Power generated by system | (kW)'],axis=1)

X_train,X_test,Y_train,Y_test = train_test_split(X,Y, test_size=0.33, random_state=42)

def basemodel():
	model = Sequential()
	model.add(Dense(12,input_dim=5,activation='relu'))
	model.add(Dense(12,activation='relu'))
	model.add(Dense(1,activation='linear'))
	model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae'])
	return model

regr = basemodel()

regr.fit(X_train,Y_train,batch_size=32,epochs=400,shuffle=True)
predictions = regr.predict(X_test)
df0=pd.DataFrame(predictions)
df0[df0 < 0] = 0
df['NN_predictions'] = df0
df.to_csv('NN_wind_predictions.csv')

print(mean_absolute_error(predictions,Y_test))
print(np.sqrt(mean_squared_error(predictions,Y_test)))

Zindi Africa/Wind Power predictions/lineareg.py


from __future__ import absolute_import

import datetime
import json
import os
import requests

import simpy
from celery.utils.log import get_task_logger

from DLP.celery import app
from DLP.settings import BASE_DIR
from dlp.apis.api_weather import can_fly, ALLOW
from dlp.file_manager.file_manager import get_site_url, \
    get_temperature_availability, has_temperature_availability, \
    get_temperature_restriction
from dlp.galaxy_comunication.galaxy_comunication import send_kmls
from dlp.kml_manager.kml_generator import create_transports_list, \
    create_packages_list, create_delivers
from dlp.models import Package, LogisticCenter, Drone, Transport, StyleURL
from dlp.routes_manager.routes_generator import get_drone_steps, Point

logger = get_task_logger(__name__)
KML_TMP_FOLDER = os.path.join(BASE_DIR + "/dlp/static/kmls/tmp/")
POSITION_URL = get_site_url() + "receive_position"

# Package Stiles id
PENDING_STYLE = 1
SENDING_STYLE = 2
SENT_STYLE = 3

class DroneTransport(object):
    def __init__(self, env, positions, id_transport):
        self.id_transport = id_transport
        self.env = env
        self.positions = positions
        # Start the run process everytime an instance is created.
        self.action = self.env.process(self.run())

    def run(self):
        logger.info(POSITION_URL)
        for position in self.positions:
            yield self.env.process(self.send_data(1.0, position))
        self.positions.reverse()
        yield self.env.timeout(1.0)
        for position in self.positions:
            yield self.env.process(self.send_data(1.0, position))

    def send_data(self, duration, position):
        print('sending data...')
        requests.post(POSITION_URL,
                      data={'id_transport': self.id_transport,
                            'lat': position['lat'], 'lng': position['lng'],
                            'alt': position['alt']})
        yield self.env.timeout(duration)

@app.task(name="tasks.manage_all_packets")
def manage_all_packets():
    logger.info("Searching for packages pending to send")
    create_transports_list()
    create_packages_list()
    create_delivers()
    send_kmls()
    packages = Package.objects.filter(status=Package.PackageStatus.PENDING)
    for package in packages:
        drones_availability(package)

def drones_availability(package):
    droppoint = package.drop_point
    city = droppoint.logistic_center.city
    if not has_temperature_availability(city.name):
        can_fly(city.name, city.lat, city.lng)
    if get_temperature_availability(
            city.name) == ALLOW or get_temperature_restriction() == False:
        lc = LogisticCenter.objects.get(id=droppoint.logistic_center_id)
        drones = Drone.objects.filter(
            logistic_center_id=droppoint.logistic_center_id,
            status=Drone.DroneStatus.WAITING)
        for drone in drones:
            package.status = Package.PackageStatus.SENDING
            package.style_url = StyleURL.objects.get(id=SENDING_STYLE)
            package.save()
            drone.status = Drone.DroneStatus.DELIVERING
            drone.save()
            city = droppoint.logistic_center.city
            origin = Point(lc.lat, lc.lng, lc.alt)
            destiny = Point(droppoint.lat, droppoint.lng, droppoint.alt)
            positions = get_drone_steps(origin, destiny, city)
            json_pos = json.dumps([ob.__dict__ for ob in positions])
            transport = create_transport(package, drone, lc,
                                         len(positions) * 2)
            send_package.delay(drone.id, package.id, transport.id, json_pos)
            break
    else:
        logger.info("Weather inestable in {city}".format(city=city.name))

def create_transport(package, drone, lc, max_steps):
    transport = Transport(package=package, drone=drone, logistic_center=lc,
                          max_steps=max_steps)
    transport.save()
    return transport

@app.task()
def send_package(drone_id, package_id, transport_id, json_pos):
    logger.info("Packet " + str(package_id) + " will be sent by drone " +
                str(drone_id))
    env_go = simpy.rt.RealtimeEnvironment(initial_time=0, factor=1.5,
                                          strict=False)
    positions = json.loads(json_pos)
    dronetransport_g = DroneTransport(env_go, positions, transport_id)
    env_go.run(until=dronetransport_g.action)
    final_transport(drone_id, package_id, transport_id)

def final_transport(drone_id, package_id, transport_id):
    package = Package.objects.get(id=package_id)
    package.status = Package.PackageStatus.SENT
    package.style_url = StyleURL.objects.get(id=SENT_STYLE)
    package.date_delivered = datetime.datetime.now()
    package.save()
    transport = Transport.objects.get(id=transport_id)
    transport.status = Transport.TransportStatus.FINISHED
    transport.save()
    drone = Drone.objects.get(id=drone_id)
    drone.status = Drone.DroneStatus.WAITING
    drone.save()
    delete_kml(transport_id)

def delete_kml(transport_id):
    os.remove(KML_TMP_FOLDER + "Transport{}.kml".format(transport_id))


# coding: utf-8

"""
    SnapTrade

    Connect brokerage accounts to your app for live positions and trading

    The version of the OpenAPI document: 1.0.0
    Contact: api@snaptrade.com
    Created by: https://snaptrade.com/
"""

from datetime import date, datetime  # noqa: F401
import decimal  # noqa: F401
import functools  # noqa: F401
import io  # noqa: F401
import re  # noqa: F401
import typing  # noqa: F401
import typing_extensions  # noqa: F401
import uuid  # noqa: F401

import frozendict  # noqa: F401

from snaptrade_client import schemas  # noqa: F401

class Status(
    schemas.DictSchema
):
    """
    This class is auto generated by Konfig (https://konfigthis.com)

    Status of API
    """

    class MetaOapg:

        class properties:
            version = schemas.IntSchema
            timestamp = schemas.StrSchema
            online = schemas.BoolSchema
            __annotations__ = {
                "version": version,
                "timestamp": timestamp,
                "online": online,
            }
        additional_properties = schemas.AnyTypeSchema

    @typing.overload
    def __getitem__(self, name: typing_extensions.Literal["version"]) -> MetaOapg.properties.version: ...

    @typing.overload
    def __getitem__(self, name: typing_extensions.Literal["timestamp"]) -> MetaOapg.properties.timestamp: ...

    @typing.overload
    def __getitem__(self, name: typing_extensions.Literal["online"]) -> MetaOapg.properties.online: ...

    @typing.overload
    def __getitem__(self, name: str) -> MetaOapg.additional_properties: ...

    def __getitem__(self, name: typing.Union[typing_extensions.Literal["version"], typing_extensions.Literal["timestamp"], typing_extensions.Literal["online"], str, ]):
        # dict_instance[name] accessor
        return super().__getitem__(name)

    @typing.overload
    def get_item_oapg(self, name: typing_extensions.Literal["version"]) -> typing.Union[MetaOapg.properties.version, schemas.Unset]: ...

    @typing.overload
    def get_item_oapg(self, name: typing_extensions.Literal["timestamp"]) -> typing.Union[MetaOapg.properties.timestamp, schemas.Unset]: ...

    @typing.overload
    def get_item_oapg(self, name: typing_extensions.Literal["online"]) -> typing.Union[MetaOapg.properties.online, schemas.Unset]: ...

    @typing.overload
    def get_item_oapg(self, name: str) -> typing.Union[MetaOapg.additional_properties, schemas.Unset]: ...

    def get_item_oapg(self, name: typing.Union[typing_extensions.Literal["version"], typing_extensions.Literal["timestamp"], typing_extensions.Literal["online"], str, ]):
        return super().get_item_oapg(name)

    def __new__(
        cls,
        *args: typing.Union[dict, frozendict.frozendict, ],
        version: typing.Union[MetaOapg.properties.version, decimal.Decimal, int, schemas.Unset] = schemas.unset,
        timestamp: typing.Union[MetaOapg.properties.timestamp, str, schemas.Unset] = schemas.unset,
        online: typing.Union[MetaOapg.properties.online, bool, schemas.Unset] = schemas.unset,
        _configuration: typing.Optional[schemas.Configuration] = None,
        **kwargs: typing.Union[MetaOapg.additional_properties, dict, frozendict.frozendict, str, date, datetime, uuid.UUID, int, float, decimal.Decimal, bool, None, list, tuple, bytes, io.FileIO, io.BufferedReader, ],
    ) -> 'Status':
        return super().__new__(
            cls,
            *args,
            version=version,
            timestamp=timestamp,
            online=online,
            _configuration=_configuration,
            **kwargs,
        )


import argparse

from ccc_client.dcs.DcsRunner import DcsRunner
from ccc_client.utils import print_API_response

def run(args):
    runner = DcsRunner(args.host, args.port, args.authToken)
    for i in args.cccId:
        r = runner.create_link(args.setId, i)
        print_API_response(r)

parser = argparse.ArgumentParser(
    description='Assign one or more resources to a set'
)
parser.set_defaults(runner=run)
parser.add_argument(
    '--setId', '-p',
    required=True,
    type=str,
    help='CCC_ID of new or existing set'
)
parser.add_argument(
    '--cccId', '-c',
    type=str,
    nargs='+',
    help='CCC_ID(s) of data to be assigned to set'
)


class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) == 1: return True
        if nums[0] == 0: return False
        target = len(nums) - 1
        state = [0] * target
        state[0] = nums[0]
        for i in range(1, len(state)):
            state[i] = max(state[i-1]-1, nums[i])
            if state[i] == 0: return False
        return True


from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import speech
import imaplib

fromadd = "mmanibalan2@gmail.com"

def send():
    speech.voice("To whom")
    a = speech.speech()
    print("done")
    speech.voice("mail")
    body = speech.speech()
    print("done")
    msg = MIMEMultipart()
    msg["From"] = fromadd
    msg["To"] = a
    msg["Subject"]="Senf by manibalan"
    msg.attach(MIMEText(body,"plain"))
    mail = msg.as_string()
    server = smtplib.SMTP("smtp.gmail.com","587")
    server.ehlo()
    server.starttls()
    server.login(fromadd,"findmeufuck")
    server.sendmail(fromadd,a,mail)
    server.quit()

def read_email_from_gmail():
    try:
        mail = imaplib.IMAP4_SSL("imap.gmail.com","993")
        mail.login(fromadd,'findmeufuck')
        mail.select('inbox')

        type, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])

        for i in range(latest_email_id,first_email_id, -1):
            typ, data = mail.fetch(i, '(RFC822)' )

            for response_part in data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    email_subject = msg['subject']
                    email_from = msg['from']
                    print ('From : ' + email_from + '\n')
                    print ('Subject : ' + email_subject + '\n')

    except Exception as e:
        print (str(e))
if __name__ == "__main__":
    read_email_from_gmail()


import logging
import os
import termcolor

# Success log level
SUCCESS = 25

def configure_logging(level=logging.INFO, use_color=True):
    """
    Configure te global logging settings.
    """

    override_level = os.environ.get('S2EENV_LOG_LEVEL', None)
    if override_level:
        level = logging.getLevelName(override_level)

    # Add a 'SUCCESS' level to the logger
    logging.addLevelName(SUCCESS, 'SUCCESS')
    logging.Logger.success = success

    # Configure colored logging
    logger = logging.getLogger()
    logger.setLevel(level)

    # Overwrite any existing handlers
    if logger.handlers:
        logger.handlers = []

    colored_handler = logging.StreamHandler()
    colored_handler.setFormatter(ColoredFormatter(use_color=use_color))
    logger.addHandler(colored_handler)

# pylint: disable=protected-access
def success(self, msg, *args, **kwargs):
    if self.isEnabledFor(SUCCESS):
        self._log(SUCCESS, msg, args, **kwargs)

def log_to_file(log_file):
    """
    Switches logging to a file.
    The file contains color codes and can be viewed with less -r.
    """
    fileh = logging.FileHandler(log_file, 'w')
    fileh.setFormatter(ColoredFormatter())

    # Reset the root logger in order to replace the default console one
    log = logging.getLogger()
    for hdlr in log.handlers:
        log.removeHandler(hdlr)
    log.addHandler(fileh)

class ColoredFormatter(logging.Formatter):
    """
    Prints log messages in color.
    """

    # Maps log levels to colors
    LOG_COLOR_MAP = {
        'WARNING': 'yellow',
        'ERROR': 'red',
        'SUCCESS': 'green',
    }

    def __init__(self, use_color=True):
        super().__init__(fmt='%(levelname)s: [%(name)s] %(message)s')

        self._use_color = use_color

    def format(self, record):
        if self._use_color:
            color = ColoredFormatter.LOG_COLOR_MAP.get(record.levelname)

            if color:
                record.levelname = termcolor.colored(record.levelname, color)
                record.name = termcolor.colored(record.name, color)
                record.msg = termcolor.colored(record.msg, color)

        return super().format(record)


import requests
#设置代理
proxy = {
    'http':'218.65.254.114',
    'https':'175.148.72.52:1133'
}
url = 'https://httpbin.org/get'
response = requests.get(url,proxies=proxy)
print(response.status_code)
print(response.text)
#使用私密代理
# proxy = {
#     'http':''
# }


from SIZR import *
from scitools.std import PiecewiseConstant # using this to shorten
                                           # implementation of E, alpha and beta
problem = ProblemSIZR(S0=60,I0=0,Z0=1,R0=0,
                      E     = PiecewiseConstant(domain=[0,33],
                              data=[(0, 20), (4, 2), (28, 0)]),T=33,
                      alpha = PiecewiseConstant(domain=[0,33],
                              data=[(0, 0), (4, 0.0016), (28, 0.0006)]),
                      beta  = PiecewiseConstant(domain=[0,33],
                              data=[(0, 0.03), (4, 0.0012), (28, 0)]),
                      dS = lambda t: 0 if t < 28 else 0.0067,
                      dI = lambda t: 0.014 if 4 <= t <= 28 else 0,p=1)

solver = SolverSIZR(problem,0.1) # SIZR file is used to solve this task, as it accepts parameters as functions
solver.solve()
solver.plot()

"""
[Command: python -u /home/simen/python/Project/Night_of_the_Living_Dead.py]
[Finished in 2.313s]
"""


a = int(input())
a =[int(i) for i in input().split()]
a =[0, 0]
for i in range(l - 2, - 1, - 1):
	if(a[i]== 0):
		a.append(a[i])
	else :
		a.append(a[i])
ans = 0
for i in range(len(a)):
	if(a[i]== 0):
		count = count + 1
	else :
		j = a[i]
print(ans)


def pc(num, total):
	if num == 0: return '0%'
	if num == total: return '100%'

	s = "%.1f%%" % (100.0 * num / total)
	if s == '0.0%':
		return '<0.1%'
	elif s == '100.0%':
		return '99.9%'
	else:
		return s

def fc(num):
	return "{:,}".format(int(num))

def int2str(num):
	sbl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	base = len(sbl)

	ret = ''
	num, rem = divmod(num, base)
	while num:
		ret = sbl[rem] + ret
		num, rem = divmod(num, base)

	return sbl[rem] + ret


import tkinter as tk
import os
import tkinter.ttk as ttk
from board import MainBoard, SettingBoard, open_setting
import tkinter.font as tkFont
import webbrowser

from logic import get_map_path, get_setting

from constants import *

MAP_PATH = get_map_path()
size, cr = get_setting(JSON_NAME)

win = tk.Tk()
win.title("ra3 map browser")

if ICON_PATH and os.path.exists(ICON_PATH):
    win.iconbitmap(ICON_PATH)

win.resizable(width=False, height=False)

def_font = tk.font.nametofont("TkDefaultFont")
font_1 = def_font.copy()
font_1.config(size=20)

vars ={
    "page_index" : tk.StringVar(win, "1"),
    "nums_count" : tk.IntVar(win, 0),
    "show_info" : tk.StringVar(win, ""),
    # for frame 2
    "map_path" : tk.StringVar(win, value=MAP_PATH),
    "setting_info" : tk.StringVar(win, value=""),

    "search_word": tk.StringVar(win, value=""),
    "kind_selector": tk.StringVar(win, value=SUGGEST[0]),

    "search_val": ""
}

main_board = MainBoard(win)
main_board.pack()

gvars = {}

setting_board = SettingBoard(win)
setting_board.set_vars(vars)

gvars["sb"] = setting_board
gvars["mb"] = main_board

def view_author(event=None):
    webbrowser.open("https://space.bilibili.com/149259132")

def view_project(event=None):
    webbrowser.open("https://github.com/BigShuang/ra3-map-browser")

if True:
# try:
    main_board.set_setting(map_path=MAP_PATH, size=size, cr=cr, font_1=font_1)
    main_board.set_vars_main(vars)
    main_board.init()

    menu = tk.Menu(win)
    win.config(menu=menu)

    menu.add_cascade(label="设置", command=lambda : open_setting(gvars))
    menu.add_separator()
    menu.add_cascade(label="查看作者", command=view_author)
    menu.add_cascade(label="查看项目", command=view_project)

# except Exception as e:
#     print(e)
#     vars["show_info"].set(str(e))

win.mainloop()


from typing import Set, List
import argparse
import itertools
import numpy as np
import cv2
import os

ALLOWED_EXT = [".jpg", ".JPG", ".png", ".PNG", ".jpeg", ".JPEG"]
AVAILABLE_ALGORITHMS = ["dhash", "humming"]

def read_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("folder", help="Path to a folder with images")
    parser.add_argument("--remove", default=0, type=int, help="Remove duplicates or not. Expected 0 or 1")
    parser.add_argument("--algorithm", default="dhash", type=str, help="Available algorithms: dhash, humming")
    parser.add_argument("--humming_thresh", type=float, default=10, help="Humming distance threshold")
    return parser.parse_args()

def calculate_dhash(image: np.ndarray, hash_size: int = 8) -> int:
    """
    Creates a numerical representation of an input image by calculating relative horizontal gradient between
    adjacent pixels and then converting it into a hash.
    Images with the same numerical representation are considered duplicates
    :param image:
    :param hash_size:
    :return:
    """
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # Convert to gray so we do not need to compare pixel values across all 3 channels
    resized_image = cv2.resize(gray_image, dsize=(hash_size + 1, hash_size))
    difference_image = resized_image[:, 1:] > resized_image[:, :-1]

    return sum([2 ** i for i, v in enumerate(difference_image.flatten()) if v])

def collect_image_paths(folder: str, paths: list) -> list:
    assert os.path.isdir(folder), "Argument folder is not a folder but a file"
    for file in os.listdir(folder):
        path_to_file = os.path.join(folder, file)
        if any(file.endswith(ext) for ext in ALLOWED_EXT):
            paths.append(path_to_file)
        elif os.path.isdir(path_to_file):
            collect_image_paths(path_to_file, paths)

    return paths

def calculate_hamming_distance(hash_1: int, hash_2: int) -> bin:
    return bin(int(hash_1) ^ int(hash_2)).count("1")

def convert_hash(hash_) -> int:
    return int(np.array(hash_, dtype="float64"))

def visualise_similar_images(paths: Set[str], thumbnail_size: int = 400) -> None:
    if len(paths) > 4:
        thumbnail_size = 200

    print("\nPATHS OF SIMILAR/IDENTICAL IMAGES:")
    duplicate_images = None
    for path in paths:
        print(path)
        try:
            image = cv2.imread(path)
        except Exception as e:
            print(f"Failed to open {path} while handling duplicates. Error: {e}. Skipped")
            continue
        image = cv2.resize(image, (thumbnail_size, thumbnail_size))
        # Concat images for visualisation purposes
        if duplicate_images is None:
            duplicate_images = image
        else:
            duplicate_images = np.hstack([duplicate_images, image])
    cv2.imshow("Duplicated images", duplicate_images)
    cv2.waitKey(0)

    return

def generate_hashes_for_images(paths_to_images: List[str], algorithm: str = "dhash") -> dict:
    hashes = dict()
    print("Calculating hashes...")
    for i, path_to_image in enumerate(paths_to_images):
        print(f"Processing: {i} / {len(paths_to_images)}")
        try:
            image = cv2.imread(path_to_image)
        except Exception as e:
            print(f"Failed to open: {path_to_image}. Error: {e}. Image skipped")
            continue

        if algorithm == "dhash":
            hash_ = calculate_dhash(image)
        else:
            hash_ = convert_hash(calculate_dhash(image))

        # Get a list of all image paths for the calculated hash if any. Else, returns an empty list
        paths = hashes.get(hash_, list())
        paths.append(path_to_image)
        hashes[hash_] = paths

    return hashes

def run_dhash_algorithm(args) -> None:
    paths_to_images = list()
    paths_to_images = collect_image_paths(args.folder, paths_to_images)
    hashes = generate_hashes_for_images(paths_to_images, "dhash")
    # Handle duplicates
    for hash_, paths in hashes.items():
        if not len(paths) > 1:
            continue
        if not args.remove:
            visualise_similar_images(paths)
        else:
            for path in paths[1:]:
                os.remove(path)

    return

def run_humming_algorithm(args) -> None:
    paths_to_images = list()
    paths_to_images = collect_image_paths(args.folder, paths_to_images)
    paths_of_similar_images = set()
    hashes = generate_hashes_for_images(paths_to_images, "humming")

    #TODO: Review how you store duplicates. How they are stored together! Wrong
    #      You need to assemble similar images together, so you can delete and leave only 1
    #      Using dict with hashes of similar imgs as keys might work

    for hash_, paths in hashes.items():
        if len(paths) > 1:
            paths_of_similar_images.update(set(paths))

    #Check for similar images: humming distance between hashes within the threshold
    for k1, k2 in itertools.combinations(hashes, 2):
        if calculate_hamming_distance(k1, k2) <= args.humming_thresh:
            paths_of_similar_images.update(set(hashes[k1]))
            paths_of_similar_images.update(set(hashes[k2]))

    if args.remove:
        for path in paths_of_similar_images[1:]:
            os.remove(path)
    else:
        if len(paths_of_similar_images) > 1:
            visualise_similar_images(paths_of_similar_images)
        else:
            print("\nNo similar images to visualise")

    return

def main() -> None:
    args = read_args()
    assert os.path.isdir(args.folder), "Wrong input. Folder expected."
    assert args.humming_thresh >= 0, "Wrong value of hummning distance provided"
    assert args.algorithm.lower().strip() in AVAILABLE_ALGORITHMS, \
                                        "Wrong algorithm requested. Available: dhash, humming"
    if args.algorithm.lower().strip() == "dhash":
        run_dhash_algorithm(args)
    elif args.algorithm.lower().strip() == "humming":
        run_humming_algorithm(args)

    return

if __name__ == "__main__":
    main()


import numpy as np
import cv2

#calling and storing the file for face recognition
face_cascade=cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')

cap=cv2.VideoCapture(0)

while True:
    ret,frame=cap.read()
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)#cascade works on gray

    #faces stores coodinates values of all the face in this particular frame
    faces=face_cascade.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=5)#scalefactor=accuracy

    #x and y denotes the bottom and left axis face
    #w andh denotess width and height

    for(x,y,w,h) in faces:
        #print(x,y,w,h)
        roi_gray=gray[y:y+h , x:x+w]#storing the face part of grey frame

        #saving the face part
        img_item="my_image.png"
        cv2.imwrite( img_item,roi_gray)

        #drwaing rectangle
        color=(200,156,200) #in BGR
        stroke=2;
        end_cord_x=x+w;
        end_cord_y=y+h;
        cv2.rectangle(frame,(x,y),(end_cord_x,end_cord_y),color,stroke)

    cv2.imshow('frame',frame)

    if(cv2.waitKey(20) & 0xFF==ord('q')):
        break
cap.release()
cv2.destroyAllWindows()