__author__ = 'Cosmin Basca'

from datetime import datetime, date, time
import new
import re
from urlparse import urlparse
from uuid import uuid4

from surf.namespace import get_namespace, get_namespace_url
from surf.namespace import get_fallback_namespace, SURF
from surf.rdf import BNode, Literal, Namespace, URIRef

pattern_direct = re.compile('^[a-z0-9]{1,}_[a-zA-Z0-9_\-]{1,}$', re.DOTALL)
pattern_inverse = re.compile('^is_[a-z0-9]{1,}_[a-zA-Z0-9_\-]{1,}_of$', re.DOTALL)

def namespace_split(uri):
    """ Same as `uri_split`, but instead of the base of the uri, returns the
    registered `namespace` for this uri

    .. code-block:: python

        >>> print util.namespace_split('http://mynamespace/ns#some_property')
        (rdflib.URIRef('http://mynamespace/ns#'), 'some_property')

    """

    sp = uri.rfind('#') != -1 and '#' or '/'
    base, predicate = uri.rsplit(sp, 1)
    return get_namespace('%s%s' % (base, sp))[1], predicate

def uri_split(uri):
    """ Split the `uri` into base path and remainder,
    the base is everything that comes before the last *#*' or */* including it

    .. code-block:: python

        >>> print util.uri_split('http://mynamespace/ns#some_property')
        ('NS1', 'some_property')

    """

    sp = uri.rfind('#') != -1 and '#' or '/'
    base, predicate = uri.rsplit(sp, 1)
    return get_namespace('%s%s' % (base, sp))[0], predicate

def uri_to_classname(uri):
    '''handy function to convert a `uri` to a Python valid `class name`

    .. code-block:: python

        >>> # prints Ns1some_class, where Ns1 is the namespace (not registered, assigned automatically)
        >>> print util.uri_to_classname('http://mynamespace/ns#some_class')
        Ns1some_class

    '''
    ns_key, predicate = uri_split(uri)
    return '%s%s' % (ns_key.title().replace('-', '_'), predicate)

def attr2rdf(attrname):
    """ Convert an `attribute name` in the form:

    .. code-block:: python

        # direct predicate
        instance1.foaf_name
        # inverse predicate
        instance2.if_foaf_title_of

    to

    .. code-block:: xml

        <!-- direct predicate -->
        <http://xmlns.com/foaf/spec/#term_name>
        <!-- inverse predicate -->
        <http://xmlns.com/foaf/spec/#term_title>

    The function returns two values, the `uri` representation and True if it's
    a direct predicate or False if its an inverse predicate.

    """

    def tordf(attrname):
        prefix, predicate = attrname.split('_', 1)
        ns = get_namespace_url(prefix)
        try:
            return ns[predicate]
        except:
            return None

    if pattern_inverse.match(attrname):
        return  tordf(attrname.replace('is_', '').replace('_of', '')), False
    elif pattern_direct.match(attrname):
        return  tordf(attrname), True
    return None, None

def rdf2attr(uri, direct):
    """ Inverse of `attr2rdf`, return the attribute name,
    given the URI and whether it is `direct` or not.

    .. code-block:: python

        >>> print rdf2attr('http://xmlns.com/foaf/spec/#term_name',True)
        foaf_name
        >>> print rdf2attr('http://xmlns.com/foaf/spec/#term_title',False)
        if_foaf_title_of

    """

    ns, predicate = uri_split(uri)
    attribute = '%s_%s' % (ns.lower(), predicate)
    return direct and attribute or 'is_%s_of' % attribute

def is_attr_direct(attrname):
    """ True if it's a direct `attribute`

    .. code-block:: python

        >>> util.is_attr_direct('foaf_name')
        True
        >>> util.is_attr_direct('is_foaf_name_of')
        False

    """

    return not pattern_inverse.match(attrname)

def uri_to_class(uri):
    '''returns a `class object` from the supplied `uri`, used `uri_to_class` to
    get a valid class name

    .. code-block:: python

        >>> print util.uri_to_class('http://mynamespace/ns#some_class')
        surf.util.Ns1some_class

    '''
    return new.classobj(str(uri_to_classname(uri)), (), {'uri':uri})

def uuid_subject(namespace=None):
    '''the function generates a unique subject in the provided `namespace` based on
    the :meth:`uuid.uuid4()` method,
    If `namespace` is not specified than the default `SURF` namespace is used

    .. code-block:: python

        >>>  print util.uuid_subject(ns.SIOC)
        http://rdfs.org/sioc/ns#1b6ca1d5-41ed-4768-b86a-42185169faff

    '''

    if not namespace:
        namespace = get_fallback_namespace()

    if not isinstance(namespace, Namespace):
        namespace = Namespace(namespace)

    return namespace[str(uuid4())]

DE_CAMEL_CASE_DEFAULT = 2 ** 0
DE_CAMEL_CASE_FORCE_LOWER_CASE = 2 ** 1
pattern = re.compile('([A-Z][A-Z][a-z])|([a-z][A-Z])')

def de_camel_case(camel_case, delim=' ', method=DE_CAMEL_CASE_FORCE_LOWER_CASE):
    '''Adds spaces to a camel case string.  Failure to space out string returns the original string.'''
    if camel_case is None:
        return None
    normalize = lambda s:s
    if (method == DE_CAMEL_CASE_FORCE_LOWER_CASE):
        normalize = lambda s:s.lower()

    return normalize(pattern.sub(lambda m: m.group()[:1] + delim + m.group()[1:], camel_case))

def is_uri(uri):
    '''True if the specified string is a URI reference False otherwise'''
    scheme, netloc, path, params, query, fragment = urlparse(uri)
    if scheme and netloc and path:
        return True
    return False

def pretty_rdf(uri):
    '''Returns a string of the given URI under the form `namespace:symbol`, if `namespace` is registered,
    else returns an empty string'''
    if hasattr(uri, 'subject'):
        uri = uri.subject
    if type(uri) is URIRef:
        NS, symbol = uri_split(uri)
        if unicode(NS).startswith('NS'):
            pretty = symbol
        else:
            pretty = NS.lower() + ':' + symbol
        return pretty
    return ''

def value_to_rdf(value):
    """ Convert the value to an `rdflib` compatible type if appropriate. """

    if type(value) in [str, unicode, basestring, float, int, long, bool, datetime, date, time]:
        return Literal(value)
    elif type(value) in [list, tuple]:
        language = len(value) > 1 and value[1] or None
        datatype = len(value) > 2 and value[2] or None
        return Literal(value[0], lang=language, datatype=datatype)
    elif type(value) is dict:
        val = value.get("value")
        language = value.get("language")
        datatype = value.get("datatype")
        if val:
            return Literal(val, lang=language, datatype=datatype)
        return value
    return value

def json_to_rdflib(obj):
    """Convert a json result entry to an rdfLib type."""
    try:
        type = obj["type"]
    except KeyError:
        raise ValueError("No type specified")

    if type == 'uri':
        return URIRef(obj["value"])
    elif type == 'literal':
        if "xml:lang" in obj:
            return Literal(obj["value"], lang=obj['xml:lang'])
        else:
            return Literal(obj["value"])
    elif type == 'typed-literal':
        return Literal(obj["value"], datatype=URIRef(obj['datatype']))
    elif type == 'bnode':
        return BNode(obj["value"])
    else:
        return None

class single(object):
    """ Descriptor for easy access to attributes with single value. """

    def __init__(self, attr):
        if isinstance(attr, URIRef):
            attr = rdf2attr(attr, True)
        self.attr = attr

    def __get__(self, obj, type=None):
        return getattr(obj, self.attr).first

    def __set__(self, obj, value):
        setattr(obj, self.attr, value)

    def __delete__(self, obj):
        setattr(obj, self.attr, [])


import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from datetime import datetime

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

df = pd.read_csv(
    'crypto10-markets-am.csv')

app.layout = html.Div(children = [
    html.H1(children='How volatile are crypto prices?'),

    html.Div(children='''
        % Change in Prices by Day for Top 10 Cryptocurrencies by Market Cap (2013-2018)

        Hover over the data points to see more details.
        You can click on the currency names on the legends to add/eliminate them from the graph.
    '''),

    # graph 1
    dcc.Graph(
        id='change',
        config = {
            'displaylogo': False
        },
        figure={'data': [go.Scatter(
            x = df[df['name'] == i].date,
            y = df[df['name'] == i]['change%'],
            name=i
        )
        for i in df.name.unique()],

                'layout': go.Layout(
                xaxis={'type': 'date', 'title': 'Date'},
                yaxis={'type': 'linear', 'title': '% Change in Day', 'tickformat': ',.000001%'},
                margin={'l': 100, 'b': 40, 't': 10, 'r': 10},
                legend={'x': 0, 'y': 1},
                hovermode='closest')

        }
        ),

    # graph 2
    #dcc.Graph(
        #id='summary',
        #config = {
            #'displaylogo': False},
        #figure={'data':
                #[dict(type = 'scatter',
                      #x = df['name'],
                      #y = df['change%'],
                      #mode = 'markers',
                      #transforms = [dict(
                      #    type = 'aggregate',
                      #    groups = df['name'].unique(),
                      #    aggregations = [dict(target = 'y', func = 'count', enabled = True),]
                      #)]
                     #)]

               #}
        #),
])

if __name__ == '__main__':
    app.run_server(debug=True)


def get_scores(results):
    scores = {}
    for c in results:
        if c.lower() in scores:
            scores[c.lower()] += 1 if c.islower() else -1
        else:
            scores[c.lower()] = 1 if c.islower() else -1
    return ', '.join(f"{k}:{scores[k]}" for k in sorted(scores, key=scores.get, reverse=True))

input = "EbAAdbBEaBaaBBdAccbeebaec"
print(get_scores(input))


from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

from partners.models import PartnerContactPerson, Partner

# class ContactPersonSerializer(serializers.Serializer):
#     first_name = serializers.CharField(max_length=20)
#     last_name = serializers.CharField(max_length=20)
#     phone = serializers.CharField(max_length=20)

class ContactPersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = PartnerContactPerson
        fields = (
            'id',
            'first_name',
            'last_name',
            'phone',
        )
    def validate(self, attrs):
        print(123)
        return attrs
    def create(self, validated_data):
        print(validated_data)
        print(1)
        instance = PartnerContactPerson(**validated_data)
        # instance.save(commit=False)
        return instance

    # def to_representation(self, instance):
    #     pass
    #
    # def to_internal_value(self, data):
    #     pass

class ContactPersonUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = PartnerContactPerson
        fields = (
            'first_name',
            'last_name',
            'phone',
        )

class AddContactPersonToPartnerCard(serializers.ModelSerializer):
    partner_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = PartnerContactPerson
        fields = (
            'id',
            'partner_id',
            'first_name',
            'last_name',
            'phone',
        )

    def validate(self, attrs):
        partner_id = attrs['partner_id']
        phone = attrs['phone']

        try:
            partner = Partner.objects.prefetch_related('contact_person').get(pk=partner_id)
        except (Partner.DoesNotExist, ValueError, TypeError, OverflowError):
            raise serializers.ValidationError(
                {'partner_id': _('Invalid partner id')},
                code='invalid_partner_id',
            )

        if phone in partner.contact_person.values_list('phone', flat=True):
            raise serializers.ValidationError(
                {'contact_phone': _('Contact with this number exists')},
                code='invalid_contact_phone',
            )
        return attrs

class RemoveFromPartnerContactsPersonSerializer(serializers.Serializer):
    partner_id = serializers.IntegerField(write_only=True)
    contact_id = serializers.IntegerField(write_only=True)

    def validate(self, attrs):
        partner_id = attrs['partner_id']
        contact_id = attrs['contact_id']

        try:
            partner = Partner.objects.prefetch_related('contact_person').get(pk=partner_id)
        except (Partner.DoesNotExist, ValueError, TypeError, OverflowError):
            raise serializers.ValidationError(
                {'partner_id': _('Invalid partner id')},
                code='invalid_partner_id',
            )

        if not (contact_id in partner.contact_person.values_list('id', flat=True)):
            raise serializers.ValidationError(
                {'contact_id': _('This contact is not on the contact person list')},
                code='invalid_contact_id',
            )
        attrs['partner'] = partner
        return attrs

    def create(self, validated_data):
        PartnerContactPerson.objects.get(pk=validated_data['contact_id']).delete()
        return validated_data['partner']


def solve(a,l,w,h):
    return int(l/a)*int(w/a)*int(h/a)

N,L,W,H=map(int,input().split())

lo = 1
hi = 10**100
epsilon=0.000000001
ans = -1
while hi-lo > epsilon:
    mid = (lo + hi) / 2

    result=solve(mid, L, W, H)

    if result < N:
        hi = mid
    else:
        lo = mid + epsilon

print("%0.13f" % abs(mid))


import matplotlib.pyplot as plt

## Declaramos valores para el eje x
eje_x = ['Python', 'R', 'Node.js', 'PHP'] #unique

## Declaramos valores para el eje y
eje_y = [50,20,35,47] #contador

## Creamos Gráfica
plt.bar(eje_x, eje_y)

## Legenda en el eje y
plt.ylabel('Cantidad de usuarios')

## Legenda en el eje x
plt.xlabel('Lenguajes de programación')

## Título de Gráfica
plt.title('Usuarios de lenguajes de programación')

## Mostramos Gráfica
plt.show()


from aiosqlite import Connection
from typing import Dict, Optional, List
from datetime import datetime

from . import cast_key

class RoomPersistence:
    def __init__(self, db: Connection):
        self.db = db

    async def create_room(self, owner: int, room_code: Optional[str], room_name: str)-> int:
        deactivate_old_rooms = """
            UPDATE room
            SET active = :false
            WHERE owner_id = :owner
        """
        deactivate_old_room_params = {
            "false": False,
            "owner": owner
        }

        create_room = """
            INSERT INTO room (owner_id, active, room_code, room_name)
            VALUES (:owner, :true, :room_code, :room_name)
        """
        create_room_params = {
            "owner": owner,
            "true": True,
            "room_code": room_code,
            "room_name": room_name
        }

        async with self.db.cursor() as cur: # treats the block as a transaction
            await cur.execute(deactivate_old_rooms, deactivate_old_room_params)
            await cur.execute(create_room, create_room_params)
            await self.db.commit()
            return cur.lastrowid

    async def add_user_to_room(self, room_id: int, user_id: int):
        insert = """
            INSERT INTO room_member (room_id, user_id)
            VALUES (:room_id, :user_id)
            ON CONFLICT DO NOTHING
        """

        params = {
            "room_id": room_id,
            "user_id": user_id
        }

        await self.db.execute(insert, params)
        await self.db.commit()

    async def remove_user_from_room(self, room_id: int, user_id: int):
        delete_user = """
            DELETE FROM room_member
            WHERE   user_id = :user_id
                AND room_id = :room_id
        """
        params = {
            "user_id": user_id,
            "room_id": room_id
        }

        await self.db.execute(delete_user, params)
        await self.db.commit()

    async def check_user_in_room(self, user_id: int, room_id: int)-> bool:
        query = """
            SELECT user_id
            FROM room_member
            WHERE   room_member.user_id = :user_id
                AND room_member.room_id = :room_id
            LIMIT 1
        """
        params = {
            "user_id": user_id,
            "room_id": room_id
        }

        cursor = await self.db.execute(query, params)
        result = await cursor.fetchone()
        return bool(result)

    @cast_key("active", bool)
    async def get_room(self, room_id: int)-> Dict:
        query = """
            SELECT room_id, owner_id, active, created_at, room_code, room_name
            FROM room
            WHERE room_id = :room_id
            LIMIT 1
        """
        params = {
            "room_id": room_id
        }

        cursor = await self.db.execute(query, params)
        result = await cursor.fetchone()
        return dict(result) if result else {}

    @cast_key("active", bool)
    async def get_room_by_owner(self, owner_id: int)-> Dict:
        query = """
            SELECT room_id, owner_id, active, created_at, room_code, room_name
            FROM room
            WHERE owner_id = :owner
              AND active = :true
            ORDER BY created_at DESC
            LIMIT 1
        """
        params = {
            "owner": owner_id,
            "true": True
        }

        cursor = await self.db.execute(query, params)
        result = await cursor.fetchone()
        return dict(result) if result else {}

    async def get_joined_rooms_by_user(self, user_id: int)-> List[Dict]:
        query = """
            SELECT room.room_id as room_id, room.owner_id,
                   room.created_at, room.room_name as room_name
            FROM (
                SELECT room.room_id as room_id
                FROM room
                LEFT JOIN room_member ON room_member.room_id = room.room_id
                WHERE room_member.user_id = :user_id AND active = :true
                UNION SELECT room.room_id
                FROM room
                WHERE room.owner_id = :user_id AND active = :true
            ) joined_rooms
            INNER JOIN room ON room.room_id = joined_rooms.room_id
            GROUP BY room.room_id
            ORDER BY created_at DESC
        """
        params = {
            "user_id": user_id,
            "true": True
        }

        cursor = await self.db.execute(query, params)
        return [dict(row) for row in await cursor.fetchall()]

    async def deactivate_room(self, room_id: int):
        deactivate_query = """UPDATE room SET active = :false WHERE room_id = :room_id"""

        params = {
            "false": False,
            "room_id": room_id
        }

        await self.db.execute(deactivate_query, params)
        await self.db.commit()


import asyncio
import json
from rtcbot import Websocket, RTCConnection
import logging
logging.basicConfig(level=logging.DEBUG)

conn = RTCConnection()

async def connect():
    ws = Websocket("https://rtcbot.dev/test1")
    await ws.onReady()
    if ws.error is not None:
        print("Had error", ws.error)
        return
    remoteDescription = await ws.get()
    print("Received Description")
    myDescription = await conn.getLocalDescription(remoteDescription)
    ws.put_nowait(myDescription)

    await ws.close()

    print("Closed socket")

    await conn.onReady()
    if conn.error is not None:
        print("Had conn error", conn.error)
    print("\n\n\nConnection ready!\n\n\n")
    conn.put_nowait("Hello!")

asyncio.ensure_future(connect())
asyncio.get_event_loop().run_forever()


# -*- coding: utf-8 -*-
import setuptools

from autotable import __version__

with open('README.md', 'r') as fh:
    long_description = fh.read()

setuptools.setup(
    name='autotable-YoRyan',
    version=__version__,
    author='Ryan Young',
    author_email='ryan@youngryan.com',
    description='An Open Rails timetable generator that uses GTFS data',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/YoRyan/autotable',
    packages=setuptools.find_packages(),
    classifiers=[
        'Programming Language :: Python :: 3',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: MIT License',
    ],
    python_requires='>=3.7',
    install_requires=[
        'gtfs_kit',
        'more-itertools',
        #'pandas',
        'pyproj',
        'pyyaml',
        'requests',
        'timezonefinder',
    ],
    entry_points={
        'console_scripts': ['autotable=autotable.main:main'],
    },
)


import unittest
from subprocess import Popen, PIPE
import sys
import time
import json
import os
from io import StringIO

TEST_PROJECT_EGG = 'tests/test_project-1.0-py2.7.egg'

@unittest.skip
class RunnerTest(unittest.TestCase):
    def test_run(self):
        env = os.environ.copy()
        env['SCRAPY_EGG'] = TEST_PROJECT_EGG
        p = Popen([sys.executable, '-m', 'scrapydd.utils.runner', 'list'],
                  env=env, stdout=PIPE, stderr=PIPE)
        while p.poll() is None:
            time.sleep(1)
        stdout, stderr = p.communicate()
        output = stdout
        self.assertEqual(output.strip().split(), b'''error_spider
fail_spider
log_spider
sina_news
success_spider
warning_spider'''.split())

    def test_extract_settings(self):
        env = {}
        env['SCRAPY_EGG'] = 'tests/test_project-1.0-py2.7.egg'
        env['SCRAPY_SETTINGS_MODULE'] = 'tests.utils.somesettings'
        p = Popen([sys.executable, '-m', 'scrapydd.utils.runner', 'settings', '--get', 'SOME_SETTING'],
                  env=env, stdout=PIPE)
        while p.poll() is None:
            time.sleep(1)
        stdout, stderr = p.communicate()
        output = stdout
        self.assertEqual(output.strip(), b'TestModule')

    def test_project_settings(self):
        env = {}
        env['SCRAPY_EGG'] = 'tests/test_project-1.0-py2.7.egg'
        p = Popen([sys.executable, '-m', 'scrapydd.utils.runner', 'settings', '--get', 'SOME_SETTING'],
                  env=env, stdout=PIPE)
        while p.poll() is None:
            time.sleep(1)
        stdout, stderr = p.communicate()
        output = stdout
        self.assertEqual(output.strip(), b'1')

    def test_settings_add_middleware(self):
        env = {}
        env['SCRAPY_EGG'] = 'tests/test_project-1.0-py2.7.egg'
        p = Popen([sys.executable, '-m', 'scrapydd.utils.runner', 'settings', '--get', 'SPIDER_MIDDLEWARES'],
                  env=env, stdout=PIPE)
        while p.poll() is None:
            time.sleep(1)
        stdout, stderr = p.communicate()
        settings_spider_middlewares = json.loads(stdout)
        self.assertEqual(1, len(settings_spider_middlewares))
        self.assertEqual(543, settings_spider_middlewares['test_project.middlewares.MyCustomSpiderMiddleware'])

    def test_extract_settings_add_middleware(self):
        env = {}
        env['SCRAPY_EGG'] = 'tests/test_project-1.0-py2.7.egg'
        env['SCRAPY_SETTINGS_MODULE'] = 'tests.utils.somesettings'
        p = Popen([sys.executable, '-m', 'scrapydd.utils.runner', 'settings', '--get', 'SPIDER_MIDDLEWARES'],
                  env=env, stdout=PIPE)
        while p.poll() is None:
            time.sleep(1)
        stdout, stderr = p.communicate()
        settings_spider_middlewares = json.loads(stdout)
        self.assertEqual(2, len(settings_spider_middlewares))
        self.assertEqual(543, settings_spider_middlewares['test_project.middlewares.MyCustomSpiderMiddleware'])
        self.assertEqual(300, settings_spider_middlewares['scrapy.spidermiddlewares.depth.DepthMiddleware'])

class RunnerModuleTest(unittest.TestCase):
    def get_settings_in_process(self, settings, settings_key):
        import optparse
        parser = optparse.OptionParser()

        from scrapy.commands.settings import Command
        from scrapy.crawler import CrawlerProcess

        command = Command()
        command.settings = settings
        command.add_options(parser)
        command.crawler_process = CrawlerProcess(settings)
        opts, args = parser.parse_args(['scrapy', 'settings', '--get',
                                        'BOT_NAME'])
        with Capturing() as output:
            command.run(args, opts)

        return output

    @unittest.skip
    def test_modify_settings_inline(self):
        from scrapydd.utils import runner
        settings = runner.activate_project(TEST_PROJECT_EGG)
        settings.set('BOT_NAME', 'test')

        self.assertEqual(self.get_settings_in_process(settings, 'BOT_NAME'),
                         ['test'])

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio    # free up some memory
        sys.stdout = self._stdout


#!/usr/bin/env python
#
#Izoox.com
#David Scalf
#Izoox Ansible nmap inventory script
#Based on ansible ssh_config discovrery script
#

#standard imports
import argparse
import os.path
import sys

#input imports
import nmap
from libnmap.process import NmapProcess
from libnmap.parser import NmapParser

#output imports
import json
from ansible.module_utils.common._collections_compat import MutableSequence
#import paramiko

nm = nmap.PortScanner()
nm.nmap.PortScanner()
nm.scan()

def get_config():
    if not os.path.isfile(os.path.expanduser(SSH_CONF)):
        return {}
    with open(os.path.expanduser(SSH_CONF)) as f:
        cfg = paramiko.SSHConfig()
        cfg.parse(f)
        ret_dict = {}
        for d in cfg._config:
            if isinstance(d['host'], MutableSequence):
                alias = d['host'][0]
            else:
                alias = d['host']
            if ('?' in alias) or ('*' in alias):
                continue
            _copy = dict(d)
            del _copy['host']
            if 'config' in _copy:
                ret_dict[alias] = _copy['config']
            else:
                ret_dict[alias] = _copy
        return ret_dict

def print_list():
    cfg = get_config()
    meta = {'hostvars': {}}
    for alias, attributes in cfg.items():
        tmp_dict = {}
        for ssh_opt, ans_opt in _ssh_to_ansible:
            if ssh_opt in attributes:
                # If the attribute is a list, just take the first element.
                # Private key is returned in a list for some reason.
                attr = attributes[ssh_opt]
                if isinstance(attr, MutableSequence):
                    attr = attr[0]
                tmp_dict[ans_opt] = attr
        if tmp_dict:
            meta['hostvars'][alias] = tmp_dict

    print(json.dumps({_key: list(set(meta['hostvars'].keys())), '_meta': meta}))

def print_host(host):
    cfg = get_config()
    print(json.dumps(cfg[host]))

def get_args(args_list):
    parser = argparse.ArgumentParser(
        description='ansible inventory script parsing .ssh/config')
    mutex_group = parser.add_mutually_exclusive_group(required=True)
    help_list = 'list all hosts from .ssh/config inventory'
    mutex_group.add_argument('--list', action='store_true', help=help_list)
    help_host = 'display variables for a host'
    mutex_group.add_argument('--host', help=help_host)
    return parser.parse_args(args_list)

def main(args_list):

    args = get_args(args_list)
    if args.list:
        print_list()
    if args.host:
        print_host(args.host)

if __name__ == '__main__':
    main(sys.argv[1:])


from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import UserPassesTestMixin
from django.urls import reverse, reverse_lazy
from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView

from photo.forms import SearchForm, PhotoForm
from photo.models import Photo

User = get_user_model()

from django.contrib.auth import get_user_model

class IndexView(ListView):
    template_name = 'index.html'
    model = Photo
    context_object_name = 'photos'
    paginate_by = 4
    paginate_orphans = 1

    def get(self, request, *args, **kwargs):
        self.form = self.get_search_form()
        self.search_value = self.get_search_value()
        return super().get(request, *args, **kwargs)

    def get_search_form(self):
        return SearchForm(self.request.GET)

    def get_search_value(self):
        if self.form.is_valid():
            return self.form.cleaned_data['search']
        return None

    def get_queryset(self):
        queryset = super().get_queryset()
        search_value = self.get_search_value()
        if search_value:
            users = get_user_model().objects.filter(username__icontains=search_value)
            queryset = queryset.filter(author__in=users)
        return queryset

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        context['form'] = self.form
        context['search_value'] = self.search_value
        return context

class AddPhotoView(CreateView):
    model = Photo
    fields = ['signature', 'image']
    template_name = 'add_photo.html'

    def form_valid(self, form):
        photo = form.save(commit=False)
        photo.author = self.request.user
        photo.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('index')

class PhotoUpdateView(UserPassesTestMixin, UpdateView):
    template_name = 'update.html'
    form_class = PhotoForm
    model = Photo
    context_object_name = 'photo'

    def get_success_url(self):
        return reverse('details', kwargs={'pk': self.object.pk})

    def test_func(self):
        user = self.request.user
        photo = self.get_object()
        return self.request.user.has_perm('photo.change_photo') or user == photo.author

class PhotoDetail(DetailView):
    template_name = 'detail.html'
    model = Photo
    context_object_name = 'photo'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

class PhotoDeleteView(UserPassesTestMixin, DeleteView):
    template_name = 'confirm_delete.html'
    context_object_name = 'photo'
    model = Photo

    success_url = reverse_lazy('index')

    def test_func(self):
        user = self.request.user
        photo = self.get_object()
        return self.request.user.has_perm('photo.delete_photo') or user == photo.author


n = int(input())
times = list(map(int, input().split()))

times.sort()

answer = list()
answer.append(times[0])

for i in range(1, n):
    answer.append(answer[-1]+times[i])

print(sum(answer))


import subprocess
import sys

TR = 1 # 10
FR = [
1,
2,
3,
4,
5
]

MODES = [
"trinity",
"materialized"
]

CMD = "mx --dy /compiler,js/graal-nodejs --cp-sfx ../../mxbuild/dists/jdk1.8/morpheusdsl.jar  --jdk jvmci node --polyglot morpheus.js ./benchparams/synthesized_logRegJS.json logisticRegression 5000 results_javascript %s T %s %s"

for fr in FR:
    for m in MODES:
        print("RUNNING: ", "TR=",TR, "FR=",fr)
        COMMAND = CMD % (m, TR, fr)
        print(COMMAND)
        pipe = subprocess.Popen(COMMAND, shell=True)
        pipe.wait()


#! /usr/bin/env python3

import datetime
import sched
import threading
import time

import RPi.GPIO as GPIO
import pygame
from twilio.rest import TwilioRestClient

chan_list = []

def send_text(account_sid, auth_token, my_number, event_start):
    twilio_client = TwilioRestClient(account_sid, auth_token)
    twilio_number = '+12403033631'
    date = str(datetime.datetime.fromtimestamp(event_start))
    body = 'There will be a viewable satellite event on: ' + date
    message = twilio_client.messages.create(body=body, from_=twilio_number, to=my_number)

def beep(stop_event):
    pygame.mixer.init()
    pygame.mixer.music.load('notification.mp3')
    while not stop_event.is_set():
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            continue

def flash_led(stop_event):
    while not stop_event.is_set():
        GPIO.output(chan_list, (True, True, True))
        time.sleep(1)
        GPIO.output(chan_list, (False, False, False))
        time.sleep(1)
    GPIO.output(chan_list, (False, False, False))

def start_alerts(event_time):
    stop_event = threading.Event()

    t_beep = threading.Thread(target=beep, kwargs={"stop_event": stop_event})
    t_beep.start()
    t_led = threading.Thread(target=flash_led, kwargs={"stop_event": stop_event})
    t_led.start()

    # sleep until the event if the event hasn't happened, else end
    if event_time - time.time() > 0:
        time.sleep(event_time - time.time())

    stop_event.set()
    t_beep.join()
    t_led.join()

def event_scheduler(account_sid, auth_token, my_number, events):
    # Set pin mode to the numbers you can read off the pi
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    # Set up channel list
    global chan_list
    chan_list = [13, 19, 26]  # 13 red, 19 green, 26 blue
    GPIO.setup(chan_list, GPIO.OUT)

    s = sched.scheduler(time.time, time.sleep)
    for event in events:
        # the alerts are scheduled 15min before the event
        alert_time = event['start'] - datetime.timedelta(seconds=900).total_seconds()

        print('Scheduled event for', datetime.datetime.fromtimestamp(alert_time))
        print('Event will occur in', datetime.timedelta(seconds=alert_time - time.time()), '\n')

        # schedule the sms alert
        s.enterabs(time=alert_time, action=send_text, priority=1,
                   kwargs={'account_sid': account_sid, 'auth_token': auth_token, 'my_number': my_number,
                           'event_start': event['start']})
        # schedule the led/audio alerts
        s.enterabs(time=alert_time, action=start_alerts, priority=1, kwargs={'event_time': event['start']})
    s.run(blocking=True)

    GPIO.cleanup(chan_list)


from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams
from pdfminer.layout import LTFigure
from pdfminer.layout import LTRect
from pdfminer.layout import LTTextBoxHorizontal
from pdfminer.layout import LTTextLineHorizontal
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfdevice import PDFDevice
import sys

# open a PDF file
if len(sys.argv) < 2:
    pdf_name = "test.pdf"
else:
    pdf_name = sys.argv[1]

document = open(pdf_name, 'rb')

# create a PDF resource manager object that stores shared resources
rsrcmgr = PDFResourceManager()
laparams = LAParams()
# create a PDF device object
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
# create a PDF interpreter object
interpreter = PDFPageInterpreter(rsrcmgr, device)

# process each page contained in the document
last_y = -1
line_txt = ""
for page in PDFPage.get_pages(document):
    interpreter.process_page(page)
    layout = device.get_result()
    for element in layout:
        if isinstance(element, LTTextBoxHorizontal):
            print("N1 {}".format(element.get_text()))
        elif isinstance(element, LTFigure):
            pass
        elif isinstance(element, LTRect):
            pass
        elif isinstance(element, LTTextLineHorizontal):
            x0,x1 = element.bbox[0], element.bbox[1]
            y0,y1,txt = element.bbox[2], element.bbox[3], element.get_text().strip('\n')
            #print("N3 {} {} {} {} '{}'".format(x0, x1, y0, y1, txt))
            if last_y == -1:
                line_txt = txt
            elif abs(y1 - last_y) < 1e-6:
                line_txt = line_txt + txt
            else:
                print("N2 {}".format(line_txt))
                line_txt = txt

            last_y = y1
        else:
            print("Ned {}".format(type(element).__name__))


import os

FILE_NAME = "data.txt"

def load_file(file_path):
    with open(file_path, "r") as file:
        lines = file.readlines()
        return [[v.strip().split(" ") for v in line.strip().split("|")] for line in lines]

def decode(signals):
    signals = [set(signal) for signal in signals]
    encoding = [None] * 10
    display = [None] * 7
    encoding[1] = set(next(signal for signal in signals if len(signal) == 2))
    encoding[4] = set(next(signal for signal in signals if len(signal) == 4))
    encoding[7] = set(next(signal for signal in signals if len(signal) == 3))
    encoding[8] = set(next(signal for signal in signals if len(signal) == 7))

    display[0] = encoding[7].difference(encoding[1])
    len_six = [signal for signal in signals if len(signal) == 6]
    cf = encoding[7].difference(display[0])
    encoding[6] = next(signal for signal in len_six if len(cf.difference(signal)) != 0)
    len_six.remove(encoding[6])
    display[2] = encoding[8].difference(encoding[6])
    display[5] = cf.difference(display[2])
    bd = encoding[4].difference(encoding[1])
    encoding[0] = next(signal for signal in len_six if len(bd.difference(signal)) != 0)
    display[3] = encoding[8].difference(encoding[0])
    display[1] = bd.difference(display[3])
    len_six.remove(encoding[0])
    encoding[9] = next(iter(len_six))
    display[4] = encoding[8].difference(encoding[9])
    display[6] = encoding[8].difference({d for v in display if v is not None for d in v })
    encoding[2] = [ ] # a, c, d, f, g
    return encoding

if __name__ == "__main__":
    file_path = os.path.join(os.path.dirname(__file__), FILE_NAME)
    data = load_file(file_path)
    # print(sum(1 for d in data for val in d[1] if len(val) in [2, 3, 4, 7]))

    for display in data:
        signals, output = display
        encoding = decode(signals)
        print(encoding)
        exit()


from typing import AnyStr
import requests
from app.core import configuration

class RecipesWebService:
    BASE_URL = configuration.APP_WS_RECIPES_URL
    SECRET = configuration.APP_WS_RECIPES_SECRET

    @classmethod
    def search_recipe(cls, search: str|None):
        headers = {"Authorization": f"Bearer {cls.SECRET}"}
        page_number = 0
        n_per_page = 5
        if search is None:
            # Get 1 Random
            n_per_page = 1
        params = dict(
            q=search,
            page_number=page_number,
            n_per_page=n_per_page
        )
        resp = requests.get(f"{cls.BASE_URL}/api/recipe/skill", headers=headers, params=params)
        if (resp.status_code == 200):
            data = resp.json()
            return data
        else:
            return None


# This entity describes the Minimum Entropy Increment Algorithm (MEI) for Clustering highly correlated channels
#   in the discretized spectrum of interest for our Cognitive Radio Research.
# Author: Bharath Keshavamurthy
# Organization: School of Electrical and Computer Engineering, Purdue University, West Lafayette, IN.
# Copyright (c) 2019. All Rights Reserved.

# Using the same notations as in the reference paper...
# Reference: M Gao, et. al., "Fast Spectrum Sensing: A Combination of Channel Correlation and Markov Model", 2014.

# The imports
import numpy
from collections import namedtuple

# This class describes the Minimum Entropy Increment Clustering Algorithm (MEI) designed to bypass some of the
#   limitations and drawbacks of the Greedy Clustering Algorithm (GC).
class MinimumEntropyIncrementAlgorithm(object):

    # The number of channels $N$ in the discretized spectrum of interest
    NUMBER_OF_CHANNELS = 18

    # The number of episodes $M$ of SU sensing/interaction with the radio environment
    NUMBER_OF_EPISODES = 1000

    # The number of clusters $T$ mandated by our evaluation framework constraints
    NUMBER_OF_CLUSTERS = 6

    # The initialization sequence
    def __init__(self):
        print('[INFO] MinimumEntropyIncrementAlgorithm Initialization: Bringing things up...')
        # The start probabilities a.k.a steady-state probabilities of the spatial and temporal Markov chains
        self.start_probabilities = {0: 0.4,
                                    1: 0.6
                                    }
        # The transition probabilities of both the spatial and the temporal Markov chains
        self.transition_probabilities = {0: {0: 0.7,
                                             1: 0.3
                                             },
                                         1: {0: 0.2,
                                             1: 0.8
                                             }
                                         }
        # The true PU occupancy states over these $M$ episodes
        self.true_pu_occupancy_states = self.get_true_pu_occupancy_states()
        # Construct the channel correlation matrix using the XNOR operation
        self.channel_correlation_matrix = self.get_channel_correlation_matrix()
        # The set $G$ which will contain the set of clusters at the end of this MEI algorithm
        self.g = [k for k in range(self.NUMBER_OF_CHANNELS)]
        # The set $D$ which will contain the set of Detected Channels (DCs) corresponding to the clusters in $G$
        #   at the end of this MEI algorithm
        self.d = [k for k in range(self.NUMBER_OF_CHANNELS)]
        # The output structure/format of the MPEG evaluation routine
        self.mpeg_output_format = namedtuple('MPEG_ROUTINE_OUTPUT',
                                             ['mpeg', 'd'])
        # The output structure/format of the MEI algorithm
        self.mei_output_format = namedtuple('MEI_OUTPUT',
                                            ['G', 'D'])

    # Simulate the occupancy behavior of the incumbents over these $M$ episodes
    def get_true_pu_occupancy_states(self):
        # The output to be returned
        pu_occupancy_states = []
        state = 1
        # The occupancy of band-0 and time-0 $X_{0}(0)$
        if numpy.random.random_sample() > self.start_probabilities[1]:
            state = 0
        pu_occupancy_states.append([state])
        # The occupancy of band-0 across all the episodes $X_{0}(m),\ \forall m \in \{1, 2, 3, \dots, M\}$
        for episode in range(1, self.NUMBER_OF_EPISODES):
            random_sample = numpy.random.random_sample()
            if state == 0 and random_sample < self.transition_probabilities[0][1]:
                state = 1
            elif state == 0 and random_sample > self.transition_probabilities[0][1]:
                state = 0
            elif state == 1 and random_sample < self.transition_probabilities[1][0]:
                state = 0
            else:
                state = 1
            pu_occupancy_states[0].append(state)
        # Get the appropriate previous state cell in the output N x M matrix
        state = pu_occupancy_states[0][0]
        # The occupancy of all the bands in episode-0 $X_{n}(0),\ \forall n \in \{1, 2, 3, \dots, N\}$
        for channel in range(1, self.NUMBER_OF_CHANNELS):
            random_sample = numpy.random.random_sample()
            if state == 0 and random_sample < self.transition_probabilities[0][1]:
                state = 1
            elif state == 0 and random_sample > self.transition_probabilities[0][1]:
                state = 0
            elif state == 1 and random_sample < self.transition_probabilities[1][0]:
                state = 0
            else:
                state = 1
            pu_occupancy_states.append([state])
        # Go through the rest of the N x M matrix using both the spatial Markov chain statistics and the temporal
        #   Markov chain statistics
        # $X_{n}(m),\ \forall n \in \{1, 2, 3, \dots, N\}\ and\ m \in \{1, 2, 3, \dots, M\}$
        for channel in range(1, self.NUMBER_OF_CHANNELS):
            for episode in range(1, self.NUMBER_OF_EPISODES):
                random_sample = numpy.random.random_sample()
                previous_spatial_state = pu_occupancy_states[channel - 1][episode]
                previous_temporal_state = pu_occupancy_states[channel][episode - 1]
                occupied_probability = \
                    self.transition_probabilities[previous_spatial_state][1] * \
                    self.transition_probabilities[previous_temporal_state][1]
                if random_sample < occupied_probability:
                    state = 1
                else:
                    state = 0
                pu_occupancy_states[channel].append(state)
        return pu_occupancy_states

    # Construct the channel correlation matrix $A$ using the XNOR operation
    def get_channel_correlation_matrix(self):
        # Setting up the output to the returned
        correlation_matrix = []
        for channel in range(self.NUMBER_OF_CHANNELS):
            correlation_matrix.append([])
        # Row index: Channel $i$
        for i in range(self.NUMBER_OF_CHANNELS):
            # Column index: Channel $j$
            for j in range(self.NUMBER_OF_CHANNELS):
                correlation_sum = 0
                # Episode iterator $m$
                for m in range(self.NUMBER_OF_EPISODES):
                    if self.true_pu_occupancy_states[i][m] == self.true_pu_occupancy_states[j][m]:
                        correlation_sum += 1
                correlation_matrix[i].append(correlation_sum / self.NUMBER_OF_EPISODES)
        return correlation_matrix

    # Calculate the Minimum Prediction Entropy of the given Group (MPEG)
    def calculate_mpeg(self, g_k):
        # The internal evaluation members are initialized here
        peg_gk = 0
        mpeg_gk = 1e100
        d_k = None
        for c_i in g_k:
            for c_j in range(self.NUMBER_OF_CHANNELS):
                # $j \neq i$ in the summation
                if c_j == c_i:
                    continue
                # $H(c_{j}|c_{i}) = -rho_{ij} \log(\rho_{ij}) - (1 - \rho_{ij}) log(1 - \rho_{ij})$
                peg_gk += (-1 *
                           self.channel_correlation_matrix[c_i][c_j] *
                           numpy.log(self.channel_correlation_matrix[c_i][c_j])
                           ) + \
                          (-1 *
                           (1 - self.channel_correlation_matrix[c_i][c_j]) *
                           numpy.log(1 - self.channel_correlation_matrix[c_i][c_j])
                           )
            # $MPEG(g_{k})$ evaluation and subsequent inference of $d_{k}$
            if peg_gk < mpeg_gk:
                mpeg_gk = peg_gk
                d_k = c_i
        return self.mpeg_output_format(mpeg=mpeg_gk,
                                       d=d_k)

    # The core algorithm: Minimum Entropy Increment (MEI)
    # We'll follow the same exact MEI algorithm as laid down in the reference work...
    def cluster(self):
        # The internal members are initialized here
        mei = 1e100
        gi_min = None
        gj_min = None
        gnew_min = None
        di_min = None
        dj_min = None
        dnew_min = None
        # while $|G| > T$
        while len(self.g) > self.NUMBER_OF_CLUSTERS:
            for g_i in self.g:
                # $MPEG(g_{i})$ and $d_{i}$
                mpeg_output = self.calculate_mpeg(g_i)
                mpeg_gi = mpeg_output.mpeg
                d_i = mpeg_output.d
                for g_j in self.g:
                    # $MPEG(g_{j})$ and $d_{j}$
                    mpeg_output = self.calculate_mpeg(g_j)
                    mpeg_gj = mpeg_output.mpeg
                    d_j = mpeg_output.d
                    # Reduce the consumption of sensing by merging these two channel groups
                    g_new = g_i + g_j
                    # $MPEG(g_{new})$ and $d_{new}$
                    mpeg_output = self.calculate_mpeg(g_new)
                    mpeg_gnew = mpeg_output.mpeg
                    d_new = mpeg_output.d
                    # The entropy increment as a result of the merging
                    ei = mpeg_gnew - mpeg_gi - mpeg_gj
                    # MEI evaluation and subsequent inference of the merged group with the smallest entropy increment
                    if ei < mei:
                        mei = ei
                        gi_min = g_i
                        gj_min = g_j
                        gnew_min = g_new
                        di_min = d_i
                        dj_min = d_j
                        dnew_min = d_new
            # $G \leftarrow G - g_{i} - g_{j} + g_{new}$
            self.g.remove(gi_min)
            self.g.remove(gj_min)
            self.g.append(gnew_min)
            # $D \leftarrow D - d_{i} - d_{j} + d_{new}$
            self.d.remove(di_min)
            self.d.remove(dj_min)
            self.d.append(dnew_min)
        # Return the output in the prescribed format in case an external entity needs it...
        return self.mei_output_format(G=self.g,
                                      D=self.d)

    # The termination sequence
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('[INFO] MinimumEntropyIncrementAlgorithm Termination: Tearing things down...')
        # Nothing to do...

# Run Trigger
if __name__ == '__main__':
    print('[INFO] MinimumEntropyIncrementAlgorithm main: Triggering the Minimum Entropy Increment Algorithm...')
    agent = MinimumEntropyIncrementAlgorithm()
    clustered_output = agent.cluster()
    print('[INFO] MinimumEntropyIncrementAlgorithm main: The set of grouped channels is - {}'.format(
        str(clustered_output.G))
    )
    print('[INFO] MinimumEntropyIncrementAlgorithm main: The set of corresponding DCs is - {}'.format(
        str(clustered_output.D))
    )


import time
import cueBeamCore2
import copy
import math
import pickle

estimated_worker_performance = 300000.0  # rays/second
intended_worker_time = 0.3  # seconds

world = cueBeamCore2.CueBeamWorld()
world.rxPlane.set_nxnynz(1, 1024, 1024)
world.rxPlane.clear_pressurefield()
current_ray_count = world.get_ray_count()

need_workers = int(math.ceil(current_ray_count / ( estimated_worker_performance * intended_worker_time)))
each_worker_does_y_lines = math.ceil(world.rxPlane.ny / need_workers)
print("going for {} workers doing {} lines each".format(need_workers, each_worker_does_y_lines))

# update the world ny size based on the lines done
world.rxPlane.ny = int(need_workers * each_worker_does_y_lines)
world.rxPlane.clear_pressurefield()

elements_vectorized_local = []
for idxElement in range(0, len(world.elements) - 1):
    elements_vectorized_local.extend(
                                    [world.elements[idxElement].x,
                                     world.elements[idxElement].y,
                                     world.elements[idxElement].z,
                                     world.elements[idxElement].amplitude,
                                     world.elements[idxElement].phase,
                                     0.0
                                     ])

handles = []
time_start = time.clock()
for idx_worker in range(need_workers):
    y_line_n = idx_worker * each_worker_does_y_lines  # starts correctly at zero - unlike in matlab!
    y_line_y = world.rxPlane.y0 + world.rxPlane.dy * y_line_n
    handles.append({
        'received': False,
        'y_line_y': y_line_y,
        'y_line_n': y_line_n,
        'async_handle': cueBeamCore2.beamsim_instant.delay(  # note: generates and issues the remote call right here.
            k=world.wavenumber,
            x0=world.rxPlane.x0,
            y0=y_line_y,
            z0=world.rxPlane.z0,
            nx=world.rxPlane.nx,
            ny=each_worker_does_y_lines,
            nz=world.rxPlane.nz,
            dx=world.rxPlane.dx,
            dy=world.rxPlane.dy,
            dz=world.rxPlane.dz,
            elements_vectorized=elements_vectorized_local)
    })

items_to_receive = need_workers
while items_to_receive > 0:
    time.sleep(0.05)
    for idx_worker in range(need_workers):
        if not(handles[idx_worker]['received']):
            if handles[idx_worker]['async_handle'].ready():
                idx1 = handles[idx_worker]['y_line_n']
                idx2 = idx1+each_worker_does_y_lines
                data_in = pickle.loads(handles[idx_worker]['async_handle'].result)
                world.rxPlane.pressurefield[idx1:idx2, :] = data_in
                handles[idx_worker]['received'] = True
                items_to_receive -= 1
time_end = time.clock()
cueBeamCore2.do_plot_abs(world)
overall_performance = world.get_ray_count() / (time_end - time_start)
print("made {:06.2f} k rays/sec".format(overall_performance/1.0e3))


# 057 faça programa que leia o sexo de uma pessoa, caso alguem digite errado peça a digitaçao até ter o valor correto

sexo = input('Qual o seu sexo [M/F}? ').upper()
while sexo != 'M' and sexo != 'F':
    print('Por favor! Digite M se masculino ou F se feminino!')
    sexo = input('Qual o seu sexo [M/F}? ').upper()
print('Seu sexo é {}.'.format(sexo))

# 058 melhore o desafio 28 só que agora o usuário vai tentar até acertar

from random import randint
comp = randint(0, 10)
user = int(input('Tente acertar o número de 0 a 10 que o computador está pensando: '))
tent = 1
while user != comp:
    user = int(input('Tente novamente: '))
    tent = tent + 1
print('Parabéns! Você acertou em {} tentativas. O número pensado pelo computador é mesmo {}.'.format(tent, comp))

# 059 crie um programa que leia 2 valores e mostre um menu na tela: somar, multiplocar, numero >, novo n, sair

n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
opcao = int(input('''Você deseja:
[ 1 ] SOMAR
[ 2 ] MULTIPLCAR
[ 3 ] INFORMAR O NÚMERO MAIOR
[ 4 ] DIGITAR NOVOS NÚMEROS
[ 5 ] SAIR
'''))
while opcao == 0 or opcao > 5:
    opcao = int(input('Digite uma opção válida: '))
    while 0 < opcao < 5:
        if opcao == 1:
            print('A soma entre {} e {} é igual a {}.'.format(n1, n2, n1 + n2))
            opcao = int(input('O que deseja fazer agora? '))
        elif opcao == 2:
            print('O produto entre {} e {} é igual a {}.'.format(n1, n2, n1 * n2))
            opcao = int(input('O que deseja fazer agora? '))
        elif opcao == 3:
            if n1 > n2:
                print('{} é maior que {}.'.format(n1, n2))
                opcao = int(input('O que deseja fazer agora? '))
            elif n1 == n2:
                print('{} é igual que {}.'.format(n1, n2))
                opcao = int(input('O que deseja fazer agora? '))
            else:
                print('{} é maior que {}.'.format(n2, n1))
                opcao = int(input('O que deseja fazer agora? '))
        if opcao == 4:
            n1 = int(input('Digite um número: '))
            n2 = int(input('Digite outro número: '))
            opcao = int(input('O que deseja fazer agora? '))
print('Programa encerrado!')

# 060 faça um programa que leia um numero qualquer e mostre seu fatorial

n = int(input('Digite o número que deseja saber seu fatorial: '))
n0 = n
c = n - 1
while c != 0:
    n = n * c
    c = c - 1
print('Fatorial de {} é {}.'.format(n0, n))

# 061 refaça o exercicio 51 usando while (lendo PA com primeiro termo e razao mostrar os 10 primeiros termos)

n = int(input('Digite o primeiro termo de sua PA: '))
r = int(input('Digite a razão de sua PA: '))
c = 0
print('Sua PA é igual a:')
while c != 10:
    if c < 9:
        print(n, end=', ')
    else:
        print(n + r)
    n = n + r
    c = c + 1

# 062 melhore o desafio anterior perguntando se o usuário quer que mostre mais termos e pare quando o usuário pedir

n = int(input('Digite o primeiro termo de sua PA: '))
r = int(input('Digite a razão de sua PA: '))
c = 0
print('Sua PA é igual a:')
while c != 10:
    if c < 9:
        print(n, end=', ')
    else:
        print(n + r)
    n = n + r
    c = c + 1
mais = int(input('Você quer ver mais quando quantos termos? '))
while mais > 0 and c != 10 + mais:
    if c < 9 + mais:
        print(n, end=', ')
    else:
        print(n + r)
    n = n + r
    if c == 9 + mais:
        mais = mais + int(input('Mais quantos termos? '))
    c = c + 1

# 063 escreva um programa que leia um numero inteiro n e mostre os n primeiros numeros da sequencia de fibonacci

n = int(input('Quantos termos da sequência de Fibonacci deseja ver? '))
fib1 = 0
fib2 = 1
c = 1
while c < n:
    if fib1 == 0:
        print(fib2, end='-> ')
    print(fib2 + fib1, end='-> ')
    fib = fib1 + fib2
    fib1 = fib2
    fib2 = fib
    c = c + 1
print(' Acabou!')

# 064 crie um programa que leia varios numeros inteiros e pare quando for digitado 999
# no final mostre a soma dos numeros inteiros (-999) e quantos foram digitados

n = int(input('Digite um número inteiro: '))
c = 0
n1 = 0
s = n
while n1 != 999:
    n1 = int(input('Digite outro número inteiro (999 para sair): '))
    s = s + n1
    c = c + 1
print('Foram digitados {} números e a soma deles é igual a {}.'.format(c, s - 999))

# 065 crie um programa que leia varios numeros inteiros pelo teclado
# no final mostre a média, qual o valor maior, qual o menor e se o usuário quer o não continuar

n = int(input('Digite um número: '))
c = 1
sair = 'S'
min = n
max = n
m = 0
while sair == 'S':
    n1 = int(input('Digite outro valor: '))
    c = c + 1
    if c == 2:
        m = (n + n1) / c
    else:
        m = ((m * (c - 1)) + n1) / c
    print('A média é {}.'.format(m))
    if n1 > max:
        max = n1
    print('{} é o maior valor digitado.'.format(max))
    if n1 < min:
        min = n1
    print('{} é o menor valor digitado.'.format(min))
    n = n1
    sair = input('Deseja continuar [S/N]? ').upper()


server = dict()
server['ip'] = '127.0.0.1'
ORACLE_BASE = "/opt/oracle"
dbname = 'AsdE'
db_ins_name = 'lite1'
OUTPUT_DIR = "/tmp/faq."

str1 = ("scp {ip}:{oracle_base}/diag/rdbms/{dbname}/"
        "{db_ins_name}/trace/alert_{db_ins_name}.log {output_dir}/").format(
    ip=server['ip'],
    oracle_base=ORACLE_BASE,
    dbname=dbname.lower(),
    db_ins_name=db_ins_name,
    output_dir=OUTPUT_DIR)

str2 = 'scp ' + server['ip'] + ':' + ORACLE_BASE + '/diag/rdbms/' + \
    dbname.lower() + '/' + db_ins_name + \
    '/trace/alert_' + db_ins_name + '.log ' + OUTPUT_DIR + '/'

print(str1)
print(str2)

print("123",
      "sad"
      "qwe",
      """123
      456
      789
      """)


import argparse
import logging

import PIL
import torch

from . import datasets, decoder, network, transforms, visualizer

LOG = logging.getLogger(__name__)

class Predictor:
    """Convenience class to predict from various inputs with a common configuration."""

    batch_size = 1  #: batch size
    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')  #: device
    fast_rescaling = True  #: fast rescaling
    loader_workers = None  #: loader workers
    long_edge = None  #: long edge

    def __init__(self, checkpoint=None, head_metas=None, *,
                 json_data=False,
                 visualize_image=False,
                 visualize_processed_image=False):
        if checkpoint is not None:
            network.Factory.checkpoint = checkpoint
        self.json_data = json_data
        self.visualize_image = visualize_image
        self.visualize_processed_image = visualize_processed_image

        self.model_cpu, _ = network.Factory().factory(head_metas=head_metas)
        self.model = self.model_cpu.to(self.device)
        if self.device.type == 'cuda' and torch.cuda.device_count() > 1:
            LOG.info('Using multiple GPUs: %d', torch.cuda.device_count())
            self.model = torch.nn.DataParallel(self.model)
            self.model.base_net = self.model_cpu.base_net
            self.model.head_nets = self.model_cpu.head_nets

        self.preprocess = self._preprocess_factory()
        self.processor = decoder.factory(self.model_cpu.head_metas)

        self.last_decoder_time = 0.0
        self.last_nn_time = 0.0
        self.total_nn_time = 0.0
        self.total_decoder_time = 0.0
        self.total_images = 0

        LOG.info('neural network device: %s (CUDA available: %s, count: %d)',
                 self.device, torch.cuda.is_available(), torch.cuda.device_count())

    @classmethod
    def cli(cls, parser: argparse.ArgumentParser, *,
            skip_batch_size=False, skip_loader_workers=False):
        """Add command line arguments.

        When using this class together with datasets (e.g. in eval),
        skip the cli arguments for batch size and loader workers as those
        will be provided via the datasets module.
        """
        group = parser.add_argument_group('Predictor')

        if not skip_batch_size:
            group.add_argument('--batch-size', default=cls.batch_size, type=int,
                               help='processing batch size')

        if not skip_loader_workers:
            group.add_argument('--loader-workers', default=cls.loader_workers, type=int,
                               help='number of workers for data loading')

        group.add_argument('--long-edge', default=cls.long_edge, type=int,
                           help='rescale the long side of the image (aspect ratio maintained)')
        group.add_argument('--precise-rescaling', dest='fast_rescaling',
                           default=True, action='store_false',
                           help='use more exact image rescaling (requires scipy)')

    @classmethod
    def configure(cls, args: argparse.Namespace):
        """Configure from command line parser."""
        cls.batch_size = args.batch_size
        cls.device = args.device
        cls.fast_rescaling = args.fast_rescaling
        cls.loader_workers = args.loader_workers
        cls.long_edge = args.long_edge

    def _preprocess_factory(self):
        rescale_t = None
        if self.long_edge:
            rescale_t = transforms.RescaleAbsolute(self.long_edge, fast=self.fast_rescaling)

        pad_t = None
        if self.batch_size > 1:
            assert self.long_edge, '--long-edge must be provided for batch size > 1'
            pad_t = transforms.CenterPad(self.long_edge)
        else:
            pad_t = transforms.CenterPadTight(16)

        return transforms.Compose([
            transforms.NormalizeAnnotations(),
            rescale_t,
            pad_t,
            transforms.EVAL_TRANSFORM,
        ])

    def dataset(self, data):
        """Predict from a dataset."""
        loader_workers = self.loader_workers
        if loader_workers is None:
            loader_workers = self.batch_size if len(data) > 1 else 0

        dataloader = torch.utils.data.DataLoader(
            data, batch_size=self.batch_size, shuffle=False,
            pin_memory=self.device.type != 'cpu',
            num_workers=loader_workers,
            collate_fn=datasets.collate_images_anns_meta)

        yield from self.dataloader(dataloader)

    def enumerated_dataloader(self, enumerated_dataloader):
        """Predict from an enumerated dataloader."""
        for batch_i, item in enumerated_dataloader:
            if len(item) == 3:
                processed_image_batch, gt_anns_batch, meta_batch = item
                image_batch = [None for _ in processed_image_batch]
            elif len(item) == 4:
                image_batch, processed_image_batch, gt_anns_batch, meta_batch = item
            if self.visualize_processed_image:
                visualizer.Base.processed_image(processed_image_batch[0])

            pred_batch = self.processor.batch(self.model, processed_image_batch, device=self.device)
            self.last_decoder_time = self.processor.last_decoder_time
            self.last_nn_time = self.processor.last_nn_time
            self.total_decoder_time += self.processor.last_decoder_time
            self.total_nn_time += self.processor.last_nn_time
            self.total_images += len(processed_image_batch)

            # un-batch
            for image, pred, gt_anns, meta in \
                    zip(image_batch, pred_batch, gt_anns_batch, meta_batch):
                LOG.info('batch %d: %s', batch_i, meta.get('file_name', 'no-file-name'))

                # load the original image if necessary
                if self.visualize_image:
                    visualizer.Base.image(image, meta=meta)

                pred = [ann.inverse_transform(meta) for ann in pred]
                gt_anns = [ann.inverse_transform(meta) for ann in gt_anns]

                if self.json_data:
                    pred = [ann.json_data() for ann in pred]

                yield pred, gt_anns, meta

    def dataloader(self, dataloader):
        """Predict from a dataloader."""
        yield from self.enumerated_dataloader(enumerate(dataloader))

    def image(self, file_name):
        """Predict from an image file name."""
        return next(iter(self.images([file_name])))

    def images(self, file_names, **kwargs):
        """Predict from image file names."""
        data = datasets.ImageList(
            file_names, preprocess=self.preprocess, with_raw_image=True)
        yield from self.dataset(data, **kwargs)

    def pil_image(self, image):
        """Predict from a Pillow image."""
        return next(iter(self.pil_images([image])))

    def pil_images(self, pil_images, **kwargs):
        """Predict from Pillow images."""
        data = datasets.PilImageList(
            pil_images, preprocess=self.preprocess, with_raw_image=True)
        yield from self.dataset(data, **kwargs)

    def numpy_image(self, image):
        """Predict from a numpy image."""
        return next(iter(self.numpy_images([image])))

    def numpy_images(self, numpy_images, **kwargs):
        """Predict from numpy images."""
        data = datasets.NumpyImageList(
            numpy_images, preprocess=self.preprocess, with_raw_image=True)
        yield from self.dataset(data, **kwargs)

    def image_file(self, file_pointer):
        """Predict from an opened image file pointer."""
        pil_image = PIL.Image.open(file_pointer).convert('RGB')
        return self.pil_image(pil_image)


import asyncio
import random

async def one(x):
    await asyncio.sleep(random.randint(1, 3))
    return print(x)

async def main():
    lst = [x for x in range(10)]
    lst_tasks = []
    for x in lst:
        task = asyncio.create_task(one(x))
        lst_tasks.append(task)
    await asyncio.gather(*lst_tasks)

asyncio.run(main())


from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
import rsrc_rc
import cmath
import math

class ColorWidget(QtGui.QWidget):
    """
    ColorWidget class
    @author Sebastian Treu

    ColorWidget is a QWidget that manages the selection of RGBA colors with ColorWheel class and a QSlider.

    Everytiime a color has been choosen, it will trigger a colorChanged() signal. It also shows in a QLabel
    the custom color choosen and also being selecting.
    """

    # colorChanged() signal used to indicate color selection.
    colorChanged = QtCore.pyqtSignal(QtGui.QColor)

    def __init__(self, parent = None):
        super(ColorWidget, self).__init__(parent)
        self.colorWheel   = ColorWidget.ColorWheel(self)
        self.colorDisplay = QLabel(self)
        self.alphaSlider  = QSlider(self)
        self.color = self.colorWheel.getColor()
        self.configureAlphaSlider()
        self.configureColorDisplay()
        self.configureLayout()
        self.configureSignals()

    def configureColorDisplay(self):
        """ Sets the displayed color label properties. """
        self.colorDisplay.setAutoFillBackground(True)
        self.colorDisplay.setStyleSheet("QLabel { background-color: rgb(100, 20, 200);")

    def configureLayout(self):
        """ Configures the layout of this widget. """
        colorLabel = QtGui.QLabel("Selected Color:")
        alphaLabel = QtGui.QLabel("Transparency:")
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.formLayout       = QtGui.QFormLayout()
        self.layout           = QtGui.QVBoxLayout(self)
        self.horizontalLayout.addWidget(self.colorWheel)
        self.formLayout.setLabelAlignment(QtCore.Qt.AlignRight)
        self.formLayout.setHorizontalSpacing(22)
        self.formLayout.setVerticalSpacing(9)
        self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, alphaLabel)
        self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.alphaSlider)
        self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, colorLabel)
        self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.colorDisplay)
        self.formLayout.setHorizontalSpacing(22)
        self.layout.addLayout(self.horizontalLayout)
        self.layout.addLayout(self.formLayout)
        self.layout.setContentsMargins(9, 0, 9, 5)

    def configureAlphaSlider(self):
        """ Sets the transparency slider properties. """
        self.alphaSlider.setOrientation(QtCore.Qt.Horizontal)
        self.alphaSlider.setRange(0, 255)
        self.alphaSlider.setSingleStep(1)
        self.alphaSlider.setTracking(True)
        self.alphaSlider.setValue(255)

    def configureSignals(self):
        """ Sets the appropiate signal management. """
        self.alphaSlider.valueChanged.connect(self.alphaIsChanging)
        self.alphaSlider.sliderReleased.connect(self.alphaChanged)
        self.colorWheel.colorIsAdjusting.connect(self.setDisplayLabelBackground)
        self.colorWheel.colorChanged.connect(self.arrangeColor)

    def setColor(self, color):
        self.color = color
        self.color.setAlpha(self.alphaSlider.value())

    def arrangeColor(self, color):
        self.setColor(color)
        self.colorChanged.emit(self.color)

    def setDisplayLabelBackground(self, color):
        self.setColor(color)
        values = "{r}, {g}, {b}, {a}".format(r = self.color.red(),
                                             g = self.color.green(),
                                             b = self.color.blue(),
                                             a = self.alphaSlider.value()
                                             )
        self.colorDisplay.setStyleSheet("QLabel { background-color: rgba("+values+"); }")
        self.colorDisplay.setToolTip(self.color.name()+hex(self.color.alpha())[2:])

    def alphaChanged(self):
        self.color.setAlpha(self.alphaSlider.value())
        self.colorChanged.emit(self.color)

    def alphaIsChanging(self, alpha):
        self.alpha = alpha
        self.setDisplayLabelBackground(self.color)
        if self.alphaSlider.isSliderDown() is False:
            self.color.setAlpha(self.alphaSlider.value())
            self.colorChanged.emit(self.color)

    class ColorWheel(QtGui.QFrame):
        """
        ColorWheel class.
	@author Sebastian Treu

        ColorWheel is a QFrame displaying a wheel with a color range and, a square box with a gradient of the
        wheel selected color. This class only manages the selection of OPAQUE colors, that is, RGB colors
        with an alpha value of 255.

        When a new color is definetily choosen, it will fire colorChanged() signal. When a color is being
        choosen, it will fire a colorIsAdjusting() signal.
	"""

        __pyqtSignals__ = ("colorChanged(QColor)", "colorIsAdjusting(QColor)")

        OuterWheelRadius = 94
        InnerWheelRadius = 74
        RestrictedRadius = InnerWheelRadius + (OuterWheelRadius - InnerWheelRadius) / 2
        WheelWidth = WheelHeight = 195
        MaskWidth  = MaskHeight  = 101
        MaskX = MaskY = 47
        MarkerXOffset = MarkerYOffset = 8
        NoAreaDrag    = 0
        MaskAreaDrag  = 1
        WheelAreaDrag = 2

        def __init__(self, parent = None):
            super(ColorWidget.ColorWheel, self).__init__(parent)
            self.wheelImage  = QtGui.QImage(":/images/resources/images/wheel.png")
            self.wheelPixmap = QtGui.QPixmap.fromImage(self.wheelImage)
            self.maskImage   = QtGui.QImage(":/images/resources/images/mask.png")
            self.maskPixmap  = QtGui.QPixmap.fromImage(self.maskImage)
            self.whatever    = QtGui.QPixmap(self.maskPixmap.width(), self.maskPixmap.height())
            self.marker      = QtGui.QPixmap(":/images/resources/images/marker.png")
            self.setMinimumSize(self.WheelWidth, self.WheelHeight)
            self.setMaximumSize(self.WheelWidth, self.WheelHeight)
            self.xOrigin = self.yOrigin = self.WheelWidth / 2
            self.wheelMarkerX  = self.xOrigin
            self.wheelMarkerY  = self.yOrigin - self.RestrictedRadius
            self.maskMarkerX = self.maskMarkerY = self.xOrigin
            self.maskBounds = QtCore.QRect(self.MaskX, self.MaskY, self.MaskWidth, self.MaskHeight)
            self.gradient = QColor(self.wheelImage.pixel(self.maskMarkerX, self.maskMarkerY))
            self.dragging = self.NoAreaDrag
            self.color = QColor()
            self.mousePressEvent(QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress,
                                                   QtCore.QPoint(self.wheelMarkerX,
                                                                 self.wheelMarkerY
                                                                 ),
                                                   QtCore.Qt.LeftButton,
                                                   QtCore.Qt.LeftButton,
                                                   QtCore.Qt.NoModifier
                                                   )
                                 )
            self.colorChanged.emit(self.color)

        # A simple getter function
        def getColor(self):
            return self.color

        # Do the painting in the paint event
        def paintEvent(self, event):
            offScreen = QPainter()
            offScreen.begin(self.whatever)
            offScreen.fillRect(0, 0, self.MaskWidth, self.MaskHeight, self.gradient)
            offScreen.drawPixmap(0, 0, self.maskPixmap)
            offScreen.end()
            onScreen = QPainter()
            onScreen.begin(self)
            onScreen.drawPixmap(0, 0, self.wheelPixmap)
            onScreen.drawPixmap(self.MaskX, self.MaskY, self.whatever)
            onScreen.drawPixmap(self.wheelMarkerX - self.MarkerXOffset, self.wheelMarkerY - self.MarkerYOffset, self.marker)
            onScreen.drawPixmap(self.maskMarkerX - self.MarkerXOffset, self.maskMarkerY - self.MarkerYOffset, self.marker)
            onScreen.end()
            if self.dragging:
                self.grabColor()
                self.colorIsAdjusting.emit(self.color)

        #
        def grabColor(self):
            #grabbedImage = QtGui.QPixmap.grabWindow(self.winId(), self.MaskX, self.MaskY, self.MaskWidth, self.MaskHeight).toImage()
            grabbedImage = self.whatever.toImage()
            color = QColor(grabbedImage.pixel(self.maskMarkerX - self.MaskX, self.maskMarkerY - self.MaskY))
            self.color = QColor(color.red(), color.green(), color.blue())

        # Initiate the drag event if we are using the left mouse button and set the correct coordinates
        # for the mask and wheel markers respectively
        def mousePressEvent(self, event):
            x = event.x()
            y = event.y()
            if (event.button() == QtCore.Qt.LeftButton):
                if self.maskBounds.contains(x, y):
                    self.dragging = self.MaskAreaDrag
                    point = self.setMaskMarkerPoint(x, y)
                else:
                    point = self.setWheelMarkerPoint(x, y)
                    self.gradient = QColor(self.wheelImage.pixel(point[0], point[1]))
                    self.dragging = self.WheelAreaDrag
            self.update()

        # If we are dragging, update the coordinates
        def mouseMoveEvent(self, event):
            x = event.x()
            y = event.y()
            if self.dragging == self.MaskAreaDrag and self.maskBounds.contains(x, y):
                point = self.setMaskMarkerPoint(x, y)
            elif self.dragging == self.WheelAreaDrag:
                point = self.setWheelMarkerPoint(x, y)
                self.gradient = QColor(self.wheelImage.pixel(point[0], point[1]))
            self.update()

        # The release event will set the dragging flag to 0
        def mouseReleaseEvent(self, event):
            self.dragging = self.NoAreaDrag
            self.grabColor()
            self.colorChanged.emit(self.color)

        # Helper function that sets the current wheel marker coordinates
        def setWheelMarkerPoint(self, x, y):
            iNumber = -(self.xOrigin - x) + (y - self.yOrigin) * 1j
            angle = cmath.phase(iNumber)
            point = cmath.rect(self.RestrictedRadius, angle + math.pi)
            self.wheelMarkerX = self.xOrigin - point.real
            self.wheelMarkerY = self.yOrigin - point.imag
            return (self.wheelMarkerX, self.wheelMarkerY)

        # Helper function that sets the current mask marker coordinates
        def setMaskMarkerPoint(self, x, y):
            self.maskMarkerX = x
            self.maskMarkerY = y
            return (x,y)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    main = QtGui.QMainWindow()
    color = ColorWidget(main)
    main.setCentralWidget(color)
    main.show()
    sys.exit(app.exec_())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 14 10:57:42 2021

@author: liang
"""

import pandas as pd
import requests

def get_data_redis(curse_redis, id_list, id_name):

    #####get data from redis
    dta = curse_redis.mget(id_list)
#    columns_list = list(eval(dta[0]).keys())
    columns_list = eval(curse_redis.get('COLUMNS'))
    data_array = []
    for item in dta:

        if item != None:
            value_list = list(eval(item).values())
        else:
            value_list = [None] * len(columns_list)

        data_array.append(value_list)
    result_df = pd.DataFrame(data_array, columns = columns_list)
    result_df[id_name] = id_list
    return result_df

def get_item_api(itemid_list):

    data_array = []

    url = "http://test"
    data = '{"key":"value"}'
    res = requests.post(url=url,data=data)
    columns_list = list(res.text.keys())

    for item_id in itemid_list:
        data = '{"key":"value"}'
        #字符串格式
        res = requests.post(url=url,data=data)
        print(res.text)
        value_list = list(res.text.values())
        data_array.append(value_list)

    itemdf = pd.DataFrame(data_array, columns= columns_list)
    itemdf['item_id'] = itemid_list

    return itemdf

if __name__ == "__main__":

    import redis
    pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
    redis_curse = redis.Redis(connection_pool=pool)

    sample = {"user_list":['60b4cdc47789d200098dc87d', '60b4cc777789d200098dc879'],  "item_list":["BTC","TRX","TUSD","BTT","DAI","BNB","TEL","SNX","DCR","LTC","DOT","SNT","XLM","DEGO","ETC","ETH","KNC","VET","DRGN","SOLVE","ROOBEE","AION","CRPT","RBTC","AERGO","TRTL","IOTX","OPEN","VIDT","TOKO","KICK","UTK","KAT" ]}

    itemid_list = sample['item_list']

    item_df = get_data_redis(redis_curse, itemid_list, 'item_id')


#!/usr/bin/python3

# python3 ohlc_4.py [ticker]
# return outf0

import sys, requests, time
import urllib.request
from datetime import timedelta,datetime
from bs4 import BeautifulSoup

ticker = sys.argv[1]
outf0  = sys.argv[2]
index  = int(sys.argv[3])

row0 = ""
row1 = ""
# https://www.tpex.org.tw/web/stock/aftertrading/daily_trading_info/st43_print.php?l=zh-tw&d=111/08&stkno=3105&s=0,asc,0
url = 'https://www.tpex.org.tw/web/stock/aftertrading/daily_trading_info/st43_print.php?l=zh-tw' + \
    '&d=' + str(int(datetime.today().strftime("%Y"))-1911)+'/'+datetime.today().strftime("%m") + \
    '&stkno='+ticker+'&s=0,asc,0'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table_body = soup.find('tbody')
if ( table_body is not None ):
    i = 0
    for tr in soup.findAll('tr')[2:]:
        tds = tr.findAll('td')
        if ( 9 == len(tds) ) :
            row0 =  row0 + tds[0].text.strip() + ":"
            row1 = row1 + str(float(tds[6].text.strip().replace(',', ''))) + ":"
    row0 = "ticker/date:"+row0[:-1]+"\n"
    row1 = ticker+":"+row1[:-1]+"\n"
    with open(outf0, 'a') as outfile:
        if ( index <= 1 ):
            outfile.write(row0)
        outfile.write(row1)
    outfile.close()
else:
    print("no data for " + ticker)

sys.exit(0)


#importing modules
import pandas as pd
from openpyxl import load_workbook
pd.options.mode.chained_assignment = None

wb = load_workbook('/.../analytics-22158-credit.xlsx')
creditSheet = wb.active

#cleaing credit card data
unwantedM = " 00:00:00"
unwantedY = "2020-"
dash = '-'
#01/12/2011
#DD/MM/YYYY
#cleaning columns A, C
for i in range(273):
    if type(creditSheet.cell(row= i+1 , column = 3).value) == str:
        creditSheet.cell(row= i+1 , column = 3).value = float(creditSheet.cell(row= i+1 , column = 3).value.strip(' CR'))

    if unwantedM and unwantedY and dash in str(creditSheet.cell(row= i+1 , column = 1).value):
        creditSheet.cell(row= i+1 , column = 1).value = str(creditSheet.cell(row= i+1 , column = 1).value).replace(unwantedY,'')
        creditSheet.cell(row= i+1 , column = 1).value = str(creditSheet.cell(row= i+1 , column = 1).value).replace(unwantedM,'')
        creditSheet.cell(row= i+1 , column = 1).value = str(creditSheet.cell(row= i+1 , column = 1).value).replace(dash,'/')

#adding year 2019
for j in range(224):
    creditSheet.cell(row= j+1 , column = 1).value = str(creditSheet.cell(row= j+1 , column = 1).value) + "/2019"

#adding year 2020
for k in range(272):
    if "/2019" not in str(creditSheet.cell(row= k+1 , column = 1).value):
        creditSheet.cell(row= k+1 , column = 1).value = str(creditSheet.cell(row= k+1 , column = 1).value) + "/2020"

wb.save('/.../analytics-22158-credit.xlsx')

df = pd.read_excel('/.../analytics-22158-credit.xlsx')

def find_clean_tran(tran):
    all_clean_transaction = {
        "Masked Bank Transaction" : "TOTAL FUEL Gas Station",
        "Masked Bank Transaction" : "EL EZABY",
        "Masked Bank Transaction" : "H&M-CAIRO FESTIVAL",
        "Masked Bank Transaction" : "AMERICAN EAGLE OUTFIT",
        "Masked Bank Transaction" : "CARREFOUR",
        "Masked Bank Transaction" : "MASTER EXPRESS",
        "Masked Bank Transaction" : "Spotify",
        "Masked Bank Transaction" : "EL EZABY",
        "Masked Bank Transaction" : "IKEA",
        "Masked Bank Transaction" : "HOLMES BURGERS",
        "Masked Bank Transaction" : "AMZN"
    }

    clean_transaction = all_clean_transaction[tran]

    return clean_transaction

for i in range(len(df['Transaction'])):
    df['Transaction'].loc[i] = find_clean_tran(df['Transaction'].loc[i])

df.to_csv(r'/.../analytics-22158-credit.csv', index = False)

#cleaing debit card data
df = pd.read_csv('/.../analytics-22158-debit.csv')
def get_date(date):
    date_by_day = date[0:2]
    search_key = date[2:5]

    months = {
        # 27/06/2019
        # 02Jun19
        "Jun" : "/06/2019",
        "Jul" : "/07/2019",
        "Aug" : "/08/2019",
        "Sep" : "/09/2019",
        "Oct" : "/10/2019",
        "Nov" : "/11/2019",
        "Dec" : "/12/2019",
        "Jan" : "/01/2020",
        "Feb" : "/02/2020",
        "Mar" : "/03/2020"
    }
    for key, val in months.items():
            if search_key in key:
                clean_date = date_by_day + val
                return clean_date
    # res = [val for key, val in months.items() search_key for search_key in search_keys if search_key in key]
    # print(res)

def find_clean_tran(tran):
    transaction_lst = [
        "PAPA JOHNS",
        "Uber",
        "Spotify",
        "WITHDRAWAL",
        "myfawry",
        "PIZZAHUT",
        "Swvl",
        "Other",
        "EMARATMISR",
        "Go Bus",
        "STARBUCKS",
        "HEART ATTACK",
        "DUKES",
        "IKEA",
        "CARREFOUR",
        "KFC",
        "RADIOSHACK",
        "CILANTRO",
        "EGYPTRAILWAYS",
        "MCDONALD"
    ]
    for i in range(len(transaction_lst)):
        if transaction_lst[i] in tran:
            return transaction_lst[i]

idx = df[df['Transaction'].str.contains('SALARY|Internet Transfer|OPENING|CLOSING|DEPOSIT', na=False)]
idx_list = list(idx.index)
# df = df.drop(df.index[idx_list])
df = df.dropna()

for i in range(len(df)):
    #df['Transaction'].loc[i] = find_clean_tran(df['Transaction'].loc[i])
    print(df['Date'].loc[i])
    #df['Date'].loc[i] = get_date(df['Date'].loc[i])

df.to_csv(r'/.../analytics-22158-debit.csv', index = False)


import click

from .output import (
    write_wass_test_output_bed,
    write_apa_site_bed,
)
from .d3pendr import run_d3pendr

@click.command()
@click.option('-t', '--treatment-fns', required=True, multiple=True)
@click.option('-c', '--control-fns', required=True, multiple=True)
@click.option('-o', '--output-prefix', required=True)
@click.option('--write-apa-sites/--no-apa-sites', required=False, default=True)
@click.option('-a', '--annotation-gtf-fn', required=True)
@click.option('--read-strand', type=click.Choice(['same', 'opposite', 'unstranded']), default='same')
@click.option('--read-end', type=click.Choice(['3', '5']), default='3')
@click.option('--paired-end-read', type=click.Choice(['1', '2', 'both', 'single']), default='single')
@click.option('--min-read-overlap', default=0.2)
@click.option('--min-reads-per-rep', default=5)
@click.option('--extend-gene-five-prime', default=0)
@click.option('--use-5utr/--ignore-5utr', default=True)
@click.option('--extend-gene-three-prime', default=0)
@click.option('--use-locus-tag/--use-gene-id-tag', default=False)
@click.option('--max-terminal-intron-size', default=100_000)
@click.option('--min-terminal-exon-size', default=30)
@click.option('--bootstraps', default=999)
@click.option('--threshold', default=0.05)
@click.option('--use-gamma-model/--no-model', default=True)
@click.option('--test-homogeneity/--no-test-homogeneity', default=False)
@click.option('--tpe-cluster-sigma', default=15)
@click.option('--min-tpe-reads', default=5)
@click.option('--min-tpe-fractional-change', default=0.1)
@click.option('-p', '--processes', default=4)
def d3pendr(treatment_fns, control_fns,
            output_prefix, write_apa_sites,
            annotation_gtf_fn,
            read_strand, read_end, paired_end_read,
            min_read_overlap, min_reads_per_rep,
            extend_gene_five_prime, use_5utr,
            extend_gene_three_prime,
            use_locus_tag,
            max_terminal_intron_size, min_terminal_exon_size,
            bootstraps, threshold, use_gamma_model, test_homogeneity,
            tpe_cluster_sigma, min_tpe_reads, min_tpe_fractional_change,
            processes):
    '''
    d3pendr: Differential 3' End analysis of Nanopore Direct RNAs

    Identifies differential polyadenylation events in either an
    annotation dependent manner, using
    a permutation test of Wasserstein distance between 3' end
    distributions and a KS test.

    Outputs bed6 format with extra columns.
    '''

    results, apa_sites = run_d3pendr(
        annotation_gtf_fn,
        treatment_fns, control_fns,
        read_strand, read_end, paired_end_read,
        min_read_overlap, min_reads_per_rep,
        extend_gene_five_prime, use_5utr,
        extend_gene_three_prime,
        use_locus_tag,
        max_terminal_intron_size, min_terminal_exon_size,
        bootstraps, threshold,
        use_gamma_model, test_homogeneity,
        write_apa_sites,
        tpe_cluster_sigma, min_tpe_reads, min_tpe_fractional_change,
        processes
    )
    output_bed = f'{output_prefix}.apa_results.bed'
    write_wass_test_output_bed(output_bed, results)
    if write_apa_sites:
        apa_site_bed = f'{output_prefix}.apa_sites.bed'
        write_apa_site_bed(apa_site_bed, apa_sites)

if __name__ == '__main__':
    d3pendr()


import json
import os
from base64 import b64encode

import requests
from django.core.files.base import ContentFile
from django.shortcuts import render

def wkhtmltopdf(check):
    url = f"http://{os.environ['WKHTMLTODPF_HOST']}:{os.environ['WKHTMLTODPF_PORT']}/"
    context = {
        'check': check,
    }
    byte_content = render(None, f'{check.type}_check.html',
                          context=context, content_type='application/json').content
    base64_bytes = b64encode(byte_content)
    base64_string = base64_bytes.decode('utf-8')
    data = {
        'contents': base64_string,
    }
    headers = {
        'Content-Type': 'application/json',
    }
    response = requests.post(url, data=json.dumps(data), headers=headers)
    check.status = 'printed'
    check.pdf_file.save(f'{check.order["id"]}_{check.type}.pdf', ContentFile(response.content))
    check.save()


#!/usr/bin/env python3

import argparse
from datetime import datetime
from pathlib import Path

import measuretf as mtf
import measuretf.timecode

def sync_folders(paths, start_datetime=None, end_datetime=None):
    """Create timestamps and sync to time."""
    if not isinstance(paths, list):
        paths = [paths]

    paths = [Path(path) for path in paths]

    for folder_name in paths:
        folder_index = int(folder_name.stem[-1])
        timecode = mtf.timecode.tc2tstamp(folder_name)

        if start_datetime is None or end_datetime is None:
            start_datetime = timecode[0][0]
            end_datetime = timecode[-1][0]

        print(
            "Using start and end times:",
            start_datetime.isoformat(),
            end_datetime.isoformat(),
        )
        mtf.timecode.sync_folder_to_timestamps(
            folder_name,
            start_datetime,
            end_datetime,
            out_folder=folder_name.parent / f"synced_{folder_index}",
            n_jobs=2,
        )

if __name__ == "__main__":

    # Instantiate the parser
    parser = argparse.ArgumentParser(description="Sync wav files in folder to timecode")

    # Optional positional argument
    parser.add_argument(
        "paths", type=str, nargs="+", help="At least one path to folder"
    )

    # Optional positional argument
    parser.add_argument(
        "-s",
        "--start_datetime",
        type=str,
        help="Start datetime as isoformat string, e.g. '2019-07-04T12:12:47'",
    )

    # Optional positional argument
    parser.add_argument(
        "-e",
        "--end_datetime",
        type=str,
        help="End datetime as isoformat string, e.g. '2019-07-04T12:12:47'",
    )

    args = parser.parse_args()

    try:
        print(args.start_datetime)
        start_datetime = args.start_datetime
        if start_datetime is not None:
            start_datetime = datetime.fromisoformat(start_datetime)

        end_datetime = args.end_datetime
        if end_datetime is not None:
            end_datetime = datetime.fromisoformat(args.end_datetime)
    except Exception as e:
        parser.error(str(e))

    sync_folders(args.paths, start_datetime, end_datetime)


import json

def json_decoder(js):
    return json.loads(js)

def checker(user_input):
    buses_id = {}
    stop_names_all = {}
    start_stops = []
    finnish_stops = []
    transfer_stops = []
    stop_names_wrong = []
    o_stops = []
    for each_o_stop in user_input:
        if each_o_stop['stop_type'] == 'O':
            o_stops.append(each_o_stop['stop_name'])
    for each_dict in user_input:
        buses_id[each_dict['bus_id']] = ''
        stop_names_all[each_dict['stop_name']] = ''
        if each_dict['stop_type'] == 'S':
            start_stops.append(each_dict['stop_name'])
        if each_dict['stop_type'] == 'F':
            finnish_stops.append(each_dict['stop_name'])
    for stop in stop_names_all.keys():
        content = []
        for each_stop in user_input:
            if stop == each_stop['stop_name']:
                content.append(each_stop['stop_type'])
        stop_names_all[stop] = content
    for trans_stop in stop_names_all.keys():
        if len(stop_names_all[trans_stop]) > 1:
            transfer_stops.append(trans_stop)
    for stop in o_stops:
        if stop in transfer_stops or stop in finnish_stops or stop in start_stops:
            stop_names_wrong.append(stop)

    if stop_names_wrong:
        print('On demand stop test:')
        print('Wrong stop types: ', sorted(stop_names_wrong))
    else:
        print('On demand stop test:')
        print('OK')

def printer(result):
    pass

printer(checker(json_decoder(input())))


'''
Created on Mar 29, 2012

@author: mpelko
'''

class NeuronSynapse(object):
    """
    The template class for any Neuron synapse.
    """
    def __init__(self):
        self.name = "Template"
        self.strength = 0.
        self.delay = 0.
        self.synapse_for_neuron = None
        self.location = None
        self.section_name = None

    def attach(self, location, section):
        assert False, "Not inplemented"


import copy

class Crates:
    def __init__(self, num_stacks, stack_pth):
        self.stacks = [[] for i in range(num_stacks)]
        with open(stack_pth) as f:
            for line in f:
                row = line.strip().split("]")
                i = 0
                for stack in row:
                    if len(stack) > 1:
                        n_spaces = int(len(stack[:-2]) / 4)
                        i += n_spaces
                        crate = stack[-1]
                        self.stacks[i] += [crate]
                        i += 1

    def move_one(self, moves_pth):
        stacks = copy.deepcopy(self.stacks)
        with open(moves_pth) as f:
            for line in f.readlines():
                cmds = line.strip().split(' ')
                move = int(cmds[1])
                off = int(cmds[3]) - 1
                onto = int(cmds[5]) - 1

                for m in range(move):
                    stacks[onto].insert(0, stacks[off].pop(0))

        print("Top stacks move one: ", end='')
        for stack in stacks:
            print(stack[0], end='')
        print()

    def move_all(self, moves_pth):
        stacks = copy.deepcopy(self.stacks)
        with open(moves_pth) as f:
            for line in f.readlines():
                cmds = line.strip().split(' ')
                move = int(cmds[1])
                off = int(cmds[3]) - 1
                onto = int(cmds[5]) - 1

                stacks[onto] = stacks[off][0:move] + stacks[onto]
                stacks[off] = stacks[off][move:]

        print("Top stacks move all: ", end='')
        for stack in stacks:
            print(stack[0], end='')
        print()


import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from matplotlib import pyplot as plt
import numpy as np

import random

from dataset import get_data

X_train = get_data('dataset')
X_train = torch.from_numpy(X_train)
X_dataset = TensorDataset(X_train)
X_dataloader = DataLoader(X_dataset, batch_size=64, shuffle=True)

lcode = 64

device = "cpu"

class VAE(nn.Module):
    def __init__(self):
        super().__init__()
        self.shrink = nn.Sequential(
            nn.Conv2d(3, 16, (3, 3),  padding=1),
            nn.MaxPool2d((2, 2)),
            nn.ReLU(),
            nn.Conv2d(16, 64, (3, 3), padding=1),
            nn.MaxPool2d((2, 2)),
            nn.ReLU(),
            nn.Flatten(),
            nn.Linear(64*8*8, 64*8),
            nn.ReLU()
        )
        self.mean = nn.Linear(64*8, lcode)
        self.logvar = nn.Linear(64*8, lcode)
        self.decode = nn.Sequential(
            nn.Linear(lcode, 64*8),
            nn.ReLU(),
            nn.Linear(64*8, 64*8*8),
            nn.ReLU(),
            nn.Unflatten(1, (64, 8, 8)),
            nn.ConvTranspose2d(64, 16, (3, 3), stride=2, padding=1),
            nn.ReLU(),
            nn.ConvTranspose2d(16, 3, (4, 4), stride=2),
            nn.Sigmoid()
        )

    def sample(self, mean, logvar):
        return mean + torch.exp(logvar / 2) * torch.randn_like(mean)

    def encode(self, x):
        y = self.shrink(x)
        return self.sample(self.mean(y), self.logvar(y))

    def forward(self, x):
        y = self.shrink(x)
        m = self.mean(y)
        v = self.logvar(y)
        return (m, v, self.decode(self.sample(m, v)))

model = VAE().to(device)
print(model)

def kl_std(mean, logvar):
    return torch.sum(torch.exp(logvar) + mean * mean - 1 - logvar)

mse = nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=5e-6, momentum=0.9)

def train(model, optimizer, beta):
    size = len(X_dataloader.dataset)
    model.train()
    for batch, X in enumerate(X_dataloader):
        X = X[0].to(device)

        (mean, logvar, img) = model(X)
        loss_mse = mse(img, X)
        loss_kl = kl_std(mean, logvar)
        loss = loss_mse + beta * loss_kl

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

def test(model):
    size = len(X_dataloader.dataset)
    num_batches = len(X_dataloader)
    model.eval()
    test_loss_mse, test_loss_kl, correct = 0, 0, 0
    with torch.no_grad():
        for X in X_dataloader:
            X = X[0].to(device)
            (mean, logvar, img) = model(X)
            test_loss_mse += mse(img, X).item()
            test_loss_kl += kl_std(mean, logvar).item()
    test_loss_mse /= num_batches
    test_loss_kl /= num_batches
    correct /= size
    print(f"Test Error: \n Avg MSE loss: {test_loss_mse:>8f} \n Avg KL loss: {test_loss_kl:>8f} \n")

epochs = 800
ncycle = 2 # see "Cyclical Annealing Schedule: A Simple Approach to Mitigating KL Vanishing"
def beta_of(t):
    n = epochs / (2 * ncycle)
    i = t / n
    if i % 2 == 0:
        return i / n
    else:
        return 1

for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train(model, optimizer, beta_of(t))
    test(model)
print("Done!")

def show(rgb):
    img = np.empty([32, 32, 3])
    for i in range(32):
        for j in range(32):
            for k in range(3):
                img[i, j, k] = rgb[k, i, j]
    plt.axis('off')
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img)

def gen(code):
    with torch.no_grad():
        show(model.decode(code).numpy()[0])

def compare(i):
    show(X_dataset[i][0])
    gen(model.encode(torch.unsqueeze(X_dataset[i][0], 0)))

def fake():
    gen(torch.randn([1, lcode]))

for i in range(8*8):
    plt.subplot(8, 8, i+1)
    fake()
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

for i in range(32):
    t = random.randint(a=0, b=len(X_train) - 1)
    plt.subplot(8, 8, 2 * i + 1)
    show(X_dataset[t][0])
    plt.subplot(8, 8, 2 * i + 2)
    gen(model.encode(torch.unsqueeze(X_dataset[t][0], 0)))
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

for i in range(8):
    t1 = random.randint(a=0, b=len(X_train) - 1)
    t2 = random.randint(a=0, b=len(X_train) - 1)
    c1 = model.encode(torch.unsqueeze(X_dataset[t1][0], 0))
    c2 = model.encode(torch.unsqueeze(X_dataset[t2][0], 0))
    for a in range(11):
        plt.subplot(8, 11, i * 11 + a + 1)
        a /= 10
        gen(a * c1 + (1 - a) * c2)
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()