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

from __future__ import absolute_import
from __future__ import unicode_literals
import mock
from oauth2client.client import AccessTokenCredentials
import unittest

# import Python so we can mock the parts we need to here.
import IPython
import IPython.core.magic

def noop_decorator(func):
  return func

IPython.core.magic.register_line_cell_magic = noop_decorator
IPython.core.magic.register_line_magic = noop_decorator
IPython.core.magic.register_cell_magic = noop_decorator
IPython.get_ipython = mock.Mock()

import google.datalab  # noqa
import google.datalab.bigquery  # noqa
import google.datalab.bigquery.commands  # noqa
import google.datalab.utils.commands  # noqa

class TestCases(unittest.TestCase):

  @mock.patch('google.datalab.utils.commands.notebook_environment')
  @mock.patch('google.datalab.Context.default')
  def test_udf_cell(self, mock_default_context, mock_notebook_environment):
    env = {}
    cell_body = """
    // @param word STRING
    // @param corpus STRING
    // @returns INTEGER
    re = new RegExp(word, 'g');
    return corpus.match(re || []).length;
    """
    mock_default_context.return_value = TestCases._create_context()
    mock_notebook_environment.return_value = env
    google.datalab.bigquery.commands._bigquery._udf_cell({'name': 'count_occurrences',
                                                          'language': 'js'}, cell_body)
    udf = env['count_occurrences']
    self.assertIsNotNone(udf)
    self.assertEquals('count_occurrences', udf._name)
    self.assertEquals('js', udf._language)
    self.assertEquals('INTEGER', udf._return_type)
    self.assertEquals([('word', 'STRING'), ('corpus', 'STRING')], udf._params)
    self.assertEquals([], udf._imports)

  @mock.patch('google.datalab.utils.commands.notebook_environment')
  @mock.patch('google.datalab.Context.default')
  def test_query_cell(self, mock_default_context, mock_notebook_environment):
    env = {}
    mock_default_context.return_value = TestCases._create_context()
    mock_notebook_environment.return_value = env
    IPython.get_ipython().user_ns = env

    # test query creation
    q1_body = 'SELECT * FROM test_table'
    google.datalab.bigquery.commands._bigquery._query_cell({'name': 'q1', 'udfs': None,
                                                            'datasources': None,
                                                            'subqueries': None}, q1_body)
    q1 = env['q1']
    self.assertIsNotNone(q1)
    self.assertEqual(q1.udfs, {})
    self.assertEqual(q1.subqueries, {})
    self.assertEqual(q1_body, q1._sql)
    self.assertEqual(q1_body, q1.sql)

    # test subquery reference and expansion
    q2_body = 'SELECT * FROM q1'
    google.datalab.bigquery.commands._bigquery._query_cell({'name': 'q2', 'udfs': None,
                                                            'datasources': None,
                                                            'subqueries': ['q1']}, q2_body)
    q2 = env['q2']
    self.assertIsNotNone(q2)
    self.assertEqual(q2.udfs, {})
    self.assertEqual({'q1': q1}, q2.subqueries)
    expected_sql = '''\
WITH q1 AS (
  %s
)

%s''' % (q1_body, q2_body)
    self.assertEqual(q2_body, q2._sql)
    self.assertEqual(expected_sql, q2.sql)

  @staticmethod
  def _create_context():
    project_id = 'test'
    creds = AccessTokenCredentials('test_token', 'test_ua')
    return google.datalab.Context(project_id, creds)

  def test_sample_cell(self):
    # TODO(gram): complete this test
    pass

  def test_get_schema(self):
    # TODO(gram): complete this test
    pass

  def test_get_table(self):
    # TODO(gram): complete this test
    pass

  def test_table_viewer(self):
    # TODO(gram): complete this test
    pass


from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import random
from django import template
import time

register = template.Library()

@register.simple_tag(name="random_coin")
def OneCoinSlug():
    random.seed()
    url = 'http://api.coincap.io/v2/assets?limit=100'
    session = Session()
    try:
        response = session.get(url)
        data = json.loads(response.text)
        rank = (data['data'][-1]['rank'])
        coin_number = random.randrange(1,100)
        name = (data['data'][coin_number]['name'])
        id = (data['data'][coin_number]['id'])
    except (ConnectionError, Timeout, TooManyRedirects) as e:
        print(e)
    firstPrice, lastPrice, startTime = GetHistory(id)
    return ("{},,,,{},,,,{},,,,{},,,,{}".format(name, id, firstPrice, lastPrice, startTime))

def GetHistory(id):
    now = time.time()*1000
    nowR = round(now, 0)
    print(now)
    url = "http://api.coincap.io/v2/assets/{}/history?interval=d1&start={}&end={}".format(id, 1281633732000, nowR)
    session = Session()
    try:
        response = session.get(url, allow_redirects=True)
        data = json.loads(response.text)
        array = data.get('data')
        firstPrice = array[0]['priceUsd']
        lastPrice = array[-1]['priceUsd']
        firstTime = array[0]['time']
        priceRound = round(float(firstPrice), 8)
        lastPriceRound = round(float(lastPrice), 8)
    except (ConnectionError, Timeout, TooManyRedirects, TypeError, UnboundLocalError, IndexError) as e:
        print('cyc')
        print(e)
        return ("bug", "bug", "bug")
    return (priceRound, lastPriceRound, firstTime)


N = int(input("Quantos numeros você vai digitar? "))

for i in range(0, N):
    x = int(input("Digite um numero: "))

    if x == 0:
        print("NULO")
    else:
        if x % 2 == 0:
            if x < 0:
                print("PAR NEGATIVO")
            else:
                print("PAR POSITIVO")
        else:
            if x < 0:
                print("IMPAR NEGATIVO")
            else:
                print("IMPAR POSITIVO")


import collections
N = int(input())
S = input()

table = collections.defaultdict(int)
for i in range(N):
    table[S[i]] += 1
ans = 1
mod = 10**9 + 7
alpha = 'abcdefghijklmnopqrstuvwxyz'
for x in alpha:
    ans *= table[x] + 1
    ans %= mod

print((ans-1) % mod)


import pandas as pd, numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

#Import flattened CSV census data into dataframe
df = pd.read_csv('../output/Full_Aviation_Data.csv')

print(df.head())

#Sort out numeric and categorical fields for processing
exclude_vars = ['EventId','AccidentNumber','EventDate','RegistrationNumber','Unnamed: 0','narrative','probable_cause','AirportName','AirportCode','Location','Model','Make','PublicationDate','AirCarrier','Country','Latitude','Longitude']
numeric_vars = list(df._get_numeric_data().columns)
numeric_vars = [field for field in numeric_vars if field not in exclude_vars]
cat_vars = [col for col in df.columns if col not in numeric_vars and col not in exclude_vars]

print("Numeric Vars:  ")
print(numeric_vars)
print("\n")
print("Categorical Vars:  ")
print(cat_vars)

sns.set_style("whitegrid")

#Create one-way frequencies for categorical vars
for cat_var in cat_vars:
	f, ax = plt.subplots(figsize=(12,12))
	plt.title(cat_var+' frequencies')
	sns.countplot(y=cat_var, data=df, color="c")
	plt.savefig('../output/figs/freqs/'+cat_var+'_freqs.png', bbox_inches='tight')
	plt.close()
	print(cat_var + " number of factors: " + str(len(df[cat_var].value_counts())))

#Display by category the relative frequencies by Aircraft Damage
for cat_var in cat_vars:
	f, ax = plt.subplots(figsize=(12,12))
	plt.title(cat_var+' frequencies')
	sns.countplot(y=cat_var, hue="AircraftDamage", data=df)
	plt.savefig('../output/figs/by_aircraft_damage/'+cat_var+'_by_aircraftdamage.png', bbox_inches='tight')
	plt.close()

#Create histograms for numeric vars
for numeric_var in numeric_vars:
	print(numeric_var)
	f, ax = plt.subplots(figsize=(12,12),nrows=3)
	minor=df[df.AircraftDamage == 'Minor']
	substantial=df[df.AircraftDamage == 'Substantial']
	destroyed=df[df.AircraftDamage == 'Destroyed']
	ax[0].title.set_text('Minor: ' + numeric_var+' histogram')
	sns.distplot(minor[numeric_var].dropna(),norm_hist=True,ax=ax[0])
	ax[1].title.set_text('Substantial: ' + numeric_var+' histogram')
	sns.distplot(substantial[numeric_var].dropna(),norm_hist=True,ax=ax[1])
	ax[2].title.set_text('Destroyed: ' + numeric_var+' histogram')
	sns.distplot(minor[numeric_var].dropna(),norm_hist=True,ax=ax[2])
	plt.savefig('../output/figs/histograms/'+numeric_var+'_hist.png', bbox_inches='tight')
	plt.close()


"""
Database administration queries
"""

import psycopg2

from postpy.base import Table, Column, Database, PrimaryKey
from postpy.ddl import compile_qualified_name
from postpy.extensions import install_extension
from postpy.sql import select_dict

def get_user_tables(conn):
    """Retrieve all user tables."""

    query_string = "select schemaname, relname from pg_stat_user_tables;"
    with conn.cursor() as cursor:
        cursor.execute(query_string)
        tables = cursor.fetchall()

    return tables

def get_primary_keys(conn, table: str, schema='public'):
    """Returns primary key columns for a specific table."""

    query = """\
SELECT
  c.constraint_name AS pkey_constraint_name,
  c.column_name     AS column_name
FROM
  information_schema.key_column_usage AS c
  JOIN information_schema.table_constraints AS t
    ON t.constraint_name = c.constraint_name
       AND t.table_catalog = c.table_catalog
       AND t.table_schema = c.table_schema
       AND t.table_name = c.table_name
WHERE t.constraint_type = 'PRIMARY KEY'
  AND c.table_schema=%s
  AND c.table_name=%s
ORDER BY c.ordinal_position"""

    for record in select_dict(conn, query, params=(schema, table)):
        yield record['column_name']

def get_column_metadata(conn, table: str, schema='public'):
    """Returns column data following db.Column parameter specification."""
    query = """\
SELECT
  attname as name,
  format_type(atttypid, atttypmod) AS data_type,
  NOT attnotnull AS nullable
FROM pg_catalog.pg_attribute
WHERE attrelid=%s::regclass
  AND attnum > 0 AND NOT attisdropped
ORDER BY attnum;"""

    qualified_name = compile_qualified_name(table, schema=schema)

    for record in select_dict(conn, query, params=(qualified_name,)):
        yield record

def reflect_table(conn, table_name, schema='public'):
    """Reflect basic table attributes."""

    column_meta = list(get_column_metadata(conn, table_name, schema=schema))
    primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema))

    columns = [Column(**column_data) for column_data in column_meta]
    primary_key = PrimaryKey(primary_key_columns)

    return Table(table_name, columns, primary_key, schema=schema)

def reset(db_name):
    """Reset database."""

    conn = psycopg2.connect(database='postgres')
    db = Database(db_name)
    conn.autocommit = True

    with conn.cursor() as cursor:
        cursor.execute(db.drop_statement())
        cursor.execute(db.create_statement())
    conn.close()

def install_extensions(extensions, **connection_parameters):
    """Install Postgres extension if available.

    Notes
    -----
    - superuser is generally required for installing extensions.
    - Currently does not support specific schema.
    """

    from postpy.connections import connect

    conn = connect(**connection_parameters)
    conn.autocommit = True

    for extension in extensions:
        install_extension(conn, extension)


# Complexity
#   Time: O(n)
#   Space: O(n)

class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        v1, v2 = list(map(int, version1.split('.'))), list(map(int, version2.split('.')))

        while len(v1) > 0 and v1[-1] == 0:
            v1.pop()
        while len(v2) > 0 and v2[-1] == 0:
            v2.pop()

        for i in range(max(len(v1), len(v2))):
            if i >= len(v1) and i < len(v2):
                return -1
            elif i < len(v1) and i >= len(v2):
                return 1

            if v1[i] < v2[i]:
                return -1
            elif v1[i] > v2[i]:
                return 1

        return 0

165. Compare Version Numbers/Python/solution1.py


import itertools
import random

class Minesweeper():
    """
    Minesweeper game representation
    """

    def __init__(self, height=8, width=8, mines=8):

        # Set initial width, height, and number of mines
        self.height = height
        self.width = width
        self.mines = set()

        # Initialize an empty field with no mines
        self.board = []
        for i in range(self.height):
            row = []
            for j in range(self.width):
                row.append(False)
            self.board.append(row)

        # Add mines randomly
        while len(self.mines) != mines:
            i = random.randrange(height)
            j = random.randrange(width)
            if not self.board[i][j]:
                self.mines.add((i, j))
                self.board[i][j] = True

        # At first, player has found no mines
        self.mines_found = set()

    def print(self):
        """
        Prints a text-based representation
        of where mines are located.
        """
        for i in range(self.height):
            print("--" * self.width + "-")
            for j in range(self.width):
                if self.board[i][j]:
                    print("|X", end="")
                else:
                    print("| ", end="")
            print("|")
        print("--" * self.width + "-")

    def is_mine(self, cell):
        i, j = cell
        return self.board[i][j]

    def nearby_mines(self, cell):
        """
        Returns the number of mines that are
        within one row and column of a given cell,
        not including the cell itself.
        """

        # Keep count of nearby mines
        count = 0

        # Loop over all cells within one row and column
        for i in range(cell[0] - 1, cell[0] + 2):
            for j in range(cell[1] - 1, cell[1] + 2):

                # Ignore the cell itself
                if (i, j) == cell:
                    continue

                # Update count if cell in bounds and is mine
                if 0 <= i < self.height and 0 <= j < self.width:
                    if self.board[i][j]:
                        count += 1

        return count

    def won(self):
        """
        Checks if all mines have been flagged.
        """
        return self.mines_found == self.mines

class Sentence():
    """
    Logical statement about a Minesweeper game
    A sentence consists of a set of board cells,
    and a count of the number of those cells which are mines.
    """

    def __init__(self, cells, count):
        self.cells = set(cells)
        self.count = count

    def __eq__(self, other):
        return self.cells == other.cells and self.count == other.count

    def __str__(self):
        return f"{self.cells} = {self.count}"

    def known_mines(self):
        """
        Returns the set of all cells in self.cells known to be mines.
        """
        if (len(self.cells) == self.count):
            return self.cells

    def known_safes(self):
        """
        Returns the set of all cells in self.cells known to be safe.
        """
        if(self.count == 0):
            return self.cells

    def mark_mine(self, cell):
        """
        Updates internal knowledge representation given the fact that
        a cell is known to be a mine.
        """
        if(cell in self.cells):
            self.cells.remove(cell)
            self.count -= 1

    def mark_safe(self, cell):
        """
        Updates internal knowledge representation given the fact that
        a cell is known to be safe.
        """
        if(cell in self.cells):
            self.cells.remove(cell)

class MinesweeperAI():
    """
    Minesweeper game player
    """

    def __init__(self, height=8, width=8):

        # Set initial height and width
        self.height = height
        self.width = width

        # Keep track of which cells have been clicked on
        self.moves_made = set()

        # Keep track of cells known to be safe or mines
        self.mines = set()
        self.safes = set()

        # List of sentences about the game known to be true
        self.knowledge = []

    def mark_mine(self, cell):
        """
        Marks a cell as a mine, and updates all knowledge
        to mark that cell as a mine as well.
        """
        self.mines.add(cell)
        for sentence in self.knowledge:
            sentence.mark_mine(cell)

    def mark_safe(self, cell):
        """
        Marks a cell as safe, and updates all knowledge
        to mark that cell as safe as well.
        """
        self.safes.add(cell)
        for sentence in self.knowledge:
            sentence.mark_safe(cell)

    def add_knowledge(self, cell, count):
        """
        Called when the Minesweeper board tells us, for a given
        safe cell, how many neighboring cells have mines in them.

        This function should:
            1) mark the cell as a move that has been made
            2) mark the cell as safe
            3) add a new sentence to the AI's knowledge base
               based on the value of `cell` and `count`
            4) mark any additional cells as safe or as mines
               if it can be concluded based on the AI's knowledge base
            5) add any new sentences to the AI's knowledge base
               if they can be inferred from existing knowledge
        """
        self.moves_made.add(cell)
        self.mark_safe(cell)
        x = cell[0]
        y = cell[1]
        topOfxIsInGird = x-1 >= 0
        bottomOfxIsInGrid = x+1 <= self.width-1
        leftOfyIsInGrid = y-1 >= 0
        rightOfyIsInGrid = y+1 <= self.height-1
        newSentence = set()

        if(topOfxIsInGird):
            # topleft neighbor cell
            if(leftOfyIsInGrid):
                topLeft = (x-1, y-1)
                if(topLeft not in self.mines or topLeft not in self.safes):
                    newSentence.add(topLeft)
            # topMiddle
            topMiddle = (x-1, y)
            if(topMiddle not in self.mines or topMiddle not in self.safes):
                newSentence.add(topMiddle)
            # topRight
            if(rightOfyIsInGrid):
                topRight = (x-1, y+1)
                if(topRight not in self.mines or topRight not in self.safes):
                    newSentence.add(topRight)

        if(bottomOfxIsInGrid):
            # bottomLeft
            if(leftOfyIsInGrid):
                bottomLeft = (x+1, y-1)
                if(bottomLeft not in self.mines or bottomLeft not in self.safes):
                    newSentence.add(bottomLeft)
            # bottomMiddle
            bottomMiddle = (x+1, y)
            if(bottomMiddle not in self.mines or bottomMiddle not in self.safes):
                newSentence.add(bottomMiddle)
            # bottomRight
            if(rightOfyIsInGrid):
                bottomRight = (x+1, y+1)
                if(bottomRight not in self.mines or bottomRight not in self.safes):
                    newSentence.add(bottomRight)

        if(leftOfyIsInGrid):
            centerLeft = (x, y-1)
            if(centerLeft not in self.mines or centerLeft not in self.safes):
                newSentence.add(centerLeft)
        if(rightOfyIsInGrid):
            centerRight = (x, y+1)
            if(centerRight not in self.mines or centerRight not in self.safes):
                newSentence.add(centerRight)

        sentenceToAdd = Sentence(newSentence, count)
        self.knowledge.append(sentenceToAdd)
        # Case where count = length
        mine_cells = []
        for sentence in self.knowledge:
            # print("running")
            if(sentence.known_mines() is not None):
                for cell in sentence.known_mines():
                    mine_cells.append(cell)
            for cell in mine_cells:
                sentence.mark_mine(cell)
                self.mines.add(cell)

        # Case where count is 0
        safe_cells = []
        for sentence in self.knowledge:
            # print("running")
            if(sentence.known_safes() is not None):
                for cell in sentence.known_safes():
                    safe_cells.append(cell)
            for cell in safe_cells:
                sentence.mark_safe(cell)
                self.safes.add(cell)
        for sentence in self.knowledge:
            if(len(sentence.cells) == 0):
                self.knowledge.remove(sentence)

        # Case where we have a subset of another set
        used_cells = []
        repeatedSentence = False
        for sentence1 in self.knowledge:
            for sentence2 in self.knowledge:

                if (sentence1 != sentence2 and len(sentence1.cells) != 0 and len(sentence2.cells) != 0 and sentence1.cells.issubset(sentence2.cells)):

                    for usedCells in used_cells:
                        if(len(sentence1.cells) == len(usedCells) and sentence1.cells.issubset(usedCells)):
                            repeatedSentence = True
                        elif(len(sentence2.cells) == len(usedCells) and sentence2.cells.issubset(usedCells)):
                            repeatedSentence = True

                    if(not repeatedSentence):
                        newSentenceCells = sentence2.cells.difference(
                            sentence1.cells)
                        newCount = sentence2.count - sentence1.count
                        self.knowledge.append(
                            Sentence(newSentenceCells, newCount))
                        used_cells.append(sentence1.cells)
                        used_cells.append(sentence2.cells)

    def make_safe_move(self):
        """
        Returns a safe cell to choose on the Minesweeper board.
        The move must be known to be safe, and not already a move
        that has been made.

        This function may use the knowledge in self.mines, self.safes
        and self.moves_made, but should not modify any of those values.
        """
        for move in self.safes:
            if move not in self.moves_made and move not in self.mines:
                return move

        return None

    def make_random_move(self):
        """
        Returns a move to make on the Minesweeper board.
        Should choose randomly among cells that:
            1) have not already been chosen, and
            2) are not known to be mines
        """
        for i in range(0, self.height):
            for j in range(0, self.width):
                move = (i, j)
                if move not in self.moves_made and move not in self.mines:
                    return move
        return None


"""
HTML <-> text conversions.
"""
import re

from html.parser import HTMLParser
from re import sub
from sys import stderr
from traceback import print_exc

import os
import string

import codecs

inputfile=r"D:\EigeneDateienMarkus\SkyDrive\Dokumente\Handball\ASR\ArbeitsgruppeSchiedsrichter_SHV\Qualitaetssicherung\Saison16-17\importtool-py\sro_spiele_today.asp.html"
targetfile=r"D:\EigeneDateienMarkus\SkyDrive\Dokumente\Handball\ASR\ArbeitsgruppeSchiedsrichter_SHV\Qualitaetssicherung\Saison16-17\importtool-py\spielplan.csv"

class _DeHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.__text = []

    def handle_data(self, data):
        text = data.strip()
        if len(text) > 0:
            text = sub('[ \t\r\n]+', ' ', text)

            if text =='Sejdaj Samir':
                pass

            self.__text.append(text)
            #self.__text.append(text + ';')

    def handle_starttag(self, tag, attrs):

        if tag=='tr':
            self.__text.append('\n')

##        if tag == 'p':
##            self.__text.append('\n\n')
##        elif tag == 'br':
##            self.__text.append('\n')

    def handle_endtag(self, tag):
        #print("End tag  :", tag)
        pass

        if tag=='td':
            self.__text.append(';')

    def handle_startendtag(self, tag, attrs):
        if tag == 'br':
            self.__text.append('\n\n')

    def text(self):
        #return ''.join(self.__text).strip()
        return ''.join(self.__text)

def dehtml(text):
    try:
        parser = _DeHTMLParser()
        parser.feed(text)
        parser.close()
        return parser.text()
    except:
        print_exc(file=stderr)
        return text

def main():

    #write result
    #f2 = open(targetfile,'w')

    f2 = codecs.open(targetfile, "w", "utf-8")
    f2.write(u'\ufeff')

    if os.path.splitext(inputfile)[1]==".html":
        print("*******************************")
        f = open(inputfile, 'r')
        text=f.read()
        f.close()

        #HTML to text
        parsedtext=dehtml(text)

        #remove blank lines
        parsedtext="".join([s for s in parsedtext.strip().splitlines(True) if s.strip()])

        print(parsedtext)
        print("****************")

        print("Parse Lines")
        lines=parsedtext.splitlines()

        for line in lines:
            print(line)

            if (line== 'Datum;Start;Liga;Spl. Nr.;Team Heim;Team Gast;Halle;SR 1;SR 2;Del 1;Del 2;Insp;'):
                line='Tag;' + line

            if (line == '<!-- //-->' or line.strip(';') == 'Anz. Tage;10 Tage20 Tage30 Tage60 Tage90 Tage120 Tage') or line==';':
                print("falsch:  " + line.strip())
                pass
            else:
                f2.write(line.strip(';'))
                f2.write("\n")

        f2.close

if __name__ == '__main__':
    main()


import requests
from bs4 import BeautifulSoup
from django.shortcuts import render
from .models import Search

# Create your views here.
AMAZONE_URL = 'https://www.amazon.in/s?k={}'
FLIPKART_URL = 'https://www.flipkart.com/search?q={}'

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

def new_search(request):
    search = request.POST.get('search')
    # Search.objects.create(search=search)

    def amazon(search):
        FINAL_AMAZON_URL = AMAZONE_URL.format(
            requests.compat.quote_plus(search))
        response = requests.get(FINAL_AMAZON_URL)
        soup = BeautifulSoup(response.text, features="html.parser")
        search_title = soup.find_all(
            'span', {'class': 'a-size-medium a-color-base a-text-normal'})
        search_price = soup.find_all(
            'span', {'class': 'a-price-whole'})
        search_link = soup.find_all(
            'a', {'class': 'a-link-normal a-text-normal'})
        search_photo = soup.find_all('img', {'class': 's-image'})
        amazon_title = search_title[0].text
        amazon_price = search_price[0].text
        amazon_url = f"https://www.amazon.in{search_link[0].get('href')}"
        amazon_photo = search_photo[0].get('src')
        return {'amazon_title': amazon_title,
                'amazon_price': amazon_price,
                'amazon_url': amazon_url,
                'amazon_photo': amazon_photo}

    def flipkart(search):
        FINAL_FLIPKART_URL = FLIPKART_URL.format(
            requests.compat.quote_plus(search))
        response = requests.get(FINAL_FLIPKART_URL)
        soup = BeautifulSoup(response.text, features="html.parser")
        search_title = soup.find_all(
            'div', {'class': '_4rR01T'})
        search_price = soup.find_all(
            'div', {'class': '_30jeq3 _1_WHN1'})
        search_link = soup.find_all(
            'a', {'class': '_1fQZEK'})
        flipkart_title = search_title[0].text
        flipkart_price = search_price[0].text
        flipkart_url = f"https://www.flipkart.com{search_link[0].get('href')}"
        return {'flipkart_title': flipkart_title,
                'flipkart_price': flipkart_price,
                'flipkart_url': flipkart_url}
    context = {
        'search': search,
    }
    context.update(amazon(search))
    context.update(flipkart(search))
    print(context)
    return render(request, 'home/new_search.html', context)


import multiprocessing
import SUASSystem
import dronekit
from SUASSystem.logging import log
from SUASSystem import GCSSettings
from time import sleep

# Setup logging information
logger_queue = multiprocessing.Queue(-1)
logger_listener_process = multiprocessing.Process(target=SUASSystem.logging.listener_process, args=(
    logger_queue,
    SUASSystem.logging.logger_listener_configurer
))
logger_listener_process.start()
SUASSystem.logging.logger_worker_configurer(logger_queue)
gcs_logger_name = multiprocessing.current_process().name

def gcs_process(sda_status, img_proc_status, interop_position_update_rate):
    manager = multiprocessing.Manager()
    vehicle_state_data = manager.list()
    mission_information_data = manager.list()
    targets_to_submit = manager.list()
    sda_avoid_coords = manager.list()
    location_log = manager.list()

    vehicle = connect_to_vehicle()
    waypoints = download_waypoints(vehicle)

    competition_viewer_process = initialize_competition_viewer_process(vehicle_state_data, mission_information_data)
    img_proc_process = initialize_image_processing_process(img_proc_status, location_log, targets_to_submit)
    sda_process = initialize_sda_process(sda_status, waypoints, sda_avoid_coords, vehicle_state_data, mission_information_data)
    log(gcs_logger_name, "Completed instantiation of all child processes")

    interop_client = SUASSystem.InteropClientConverter(GCSSettings.MSL_ALT, GCSSettings.INTEROP_URL, GCSSettings.INTEROP_USERNAME, GCSSettings.INTEROP_PASSWORD)

    guided_waypoint_location = None
    vehicle_state_data.append(SUASSystem.get_vehicle_state(vehicle, GCSSettings.MSL_ALT))
    while True:
        interop_position_update_rate.value += 1
        vehicle_state_data[0] = SUASSystem.get_vehicle_state(vehicle, GCSSettings.MSL_ALT)

        current_location = SUASSystem.Location(vehicle.location.global_relative_frame.lat, vehicle.location.global_relative_frame.lon, vehicle.location.global_relative_frame.alt)
        print(current_location)
        location_log.append(current_location)
        """if (vehicle.location.global_relative_frame.alt * 3.28084) > GCSSettings.SDA_MIN_ALT and (vehicle.mode.name == "GUIDED" or vehicle.mode.name == "AUTO"):
            log("root", "Avoiding obstacles...")
            vehicle.mode = VehicleMode("GUIDED")
            guided_waypoint_location = sda_avoid_coords[0][0]
            vehicle.simple_goto(guided_waypoint_location.as_global_relative_frame())

        if waypoint_location:
            if vehicle.mode.name == "GUIDED" and has_uav_reached_waypoint(current_location, guided_waypoint_location):
                vehicle.mode = VehicleMode("AUTO")"""

        interop_client.post_telemetry(current_location, vehicle_state_data[0].get_direction())

        sleep(0.1)

def initialize_competition_viewer_process(vehicle_state_data, mission_information_data):
    log(gcs_logger_name, "Instantiating Competition Viewer process")
    competition_viewer_process = multiprocessing.Process(target=SUASSystem.run_competition_viewer_process, args=(
        vehicle_state_data,
        mission_information_data,
    ))
    competition_viewer_process.start()
    log(gcs_logger_name, "Competition Viewer process instantiated")

    return competition_viewer_process

def initialize_sda_process(sda_status, waypoints, sda_avoid_coords, vehicle_state_data, mission_information_data):
    log(gcs_logger_name, "Instantiating SDA process")
    sda_process = multiprocessing.Process(target=SUASSystem.run_sda_process, args=(
        logger_queue,
        waypoints,
        sda_status,
        sda_avoid_coords,
        vehicle_state_data,
        mission_information_data,
    ))
    #sda_process.start()
    log(gcs_logger_name, "SDA process instantiated")

    return sda_process

def initialize_image_processing_process(img_proc_status, location_log, targets_to_submit):
    log(gcs_logger_name, "Instantiating Image Processing process")
    img_proc_process = multiprocessing.Process(target=SUASSystem.run_img_proc_process, args=(
        logger_queue,
        img_proc_status,
        location_log,
        targets_to_submit
    ))
    #img_proc_process.start()
    log(gcs_logger_name, "Image Processing process instantiated")

    return img_proc_process

def connect_to_vehicle():
    log(gcs_logger_name, "Connecting to UAV on: %s" % GCSSettings.UAV_CONNECTION_STRING)
    vehicle = dronekit.connect(GCSSettings.UAV_CONNECTION_STRING, wait_ready=True)
    vehicle.wait_ready('autopilot_version')
    log(gcs_logger_name, "Connected to UAV on: %s" % GCSSettings.UAV_CONNECTION_STRING)
    SUASSystem.logging.log_vehicle_state(vehicle, gcs_logger_name)

    return vehicle

def download_waypoints(vehicle):
    log(gcs_logger_name, "Downloading waypoints from UAV on: %s" % GCSSettings.UAV_CONNECTION_STRING)
    waypoints = vehicle.commands
    waypoints.download()
    waypoints.wait_ready()
    log(gcs_logger_name, "Waypoints successfully downloaded from UAV on: %s" % GCSSettings.UAV_CONNECTION_STRING)

    return waypoints

def has_uav_reached_waypoint(current_location, waypoint_location, threshold_dist=2):
    dx, dy, dz = SUASSystem.haversine(waypoint_location, current_location)
    euclidean_dist = (dx**2 + dy**2 + dz**2)**0.5

    if euclidean_dist < threshold_dist:
        return True

    return False


# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: Idealis Consulting
#    Copyright (c) 2016 Idealis Consulting S.A. (http://www.idealisconsulting.com)
#    All Rights Reserved
#
#    WARNING: This program as such is intended to be used by professional
#    programmers who take the whole responsibility of assessing all potential
#    consequences resulting from its eventual inadequacies and bugs.
#    End users who are looking for a ready-to-use solution with commercial
#    guarantees and support are strongly advised to contact a Free Software
#    Service Company.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from psycopg2 import OperationalError

from odoo import api, models, fields, _
from odoo.exceptions import ValidationError
from odoo.tools import config, float_compare

class UnvcStockQuant(models.Model):
    _inherit = "stock.quant"

    @api.constrains('product_id', 'quantity')
    def check_negative_qty(self):
        """
        Rewrite the standard method, this way we can have negative stock on product for which the category of the unit of measure allows it.
        """
        p = self.env['decimal.precision'].precision_get(
            'Product Unit of Measure')
        check_negative_qty = (
            (config['test_enable'] and
             self.env.context.get('test_stock_no_negative')) or
            not config['test_enable']
        )
        if not check_negative_qty:
            return

        for quant in self:
            ###########################################
            ########### CHANGES happens here ##########
            ###########################################
            disallowed_by_product = \
                not quant.product_id.allow_negative_stock \
                and not quant.product_id.categ_id.allow_negative_stock \
                and not quant.product_id.uom_id.category_id.allow_negative_stock
            ###########################################
            ###########################################
            disallowed_by_location = not quant.location_id.allow_negative_stock
            if (
                float_compare(quant.quantity, 0, precision_digits=p) == -1 and
                quant.product_id.type == 'product' and
                quant.location_id.usage in ['internal', 'transit'] and
                (disallowed_by_product or disallowed_by_location)
            ):
                msg_add = ''
                if quant.lot_id:
                    # Now find a quant we can compensate the negative quants
                    #  with some untracked quants.
                    untracked_qty = quant._get_available_quantity(
                        quant.product_id, quant.location_id, lot_id=False,
                        strict=True)
                    if float_compare(abs(quant.quantity),
                                     untracked_qty, precision_digits=p) < 1:
                        return True
                    msg_add = _(" lot '%s'") % quant.lot_id.display_name
                raise ValidationError(_(
                    "You cannot validate this stock operation because the "
                    "stock level of the product '%s'%s would become negative "
                    "(%s) on the stock location '%s' and negative stock is "
                    "not allowed for this product and/or location.") % (
                        quant.product_id.name, msg_add, quant.quantity,
                        quant.location_id.complete_name))

    @api.model
    def _update_available_quantity(self, product_id, location_id, quantity, lot_id=None, package_id=None, owner_id=None,
                                   in_date=None):
        """
        Delete every negative stock quant! We don't want to keep track of them. Since negative consumption is allow only for meter
        and length it means that in reality we are at zero (negative stock only exist because of measure error on the field).
        """
        available_qty, in_date = super(UnvcStockQuant, self)._update_available_quantity(
            product_id, location_id, quantity, lot_id, package_id, owner_id, in_date)
        self = self.sudo()
        quants = self._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id,
                              strict=True)
        quants = quants.filtered(lambda quant: quant.quantity < 0)
        for quant in quants:
            try:
                with self._cr.savepoint():
                    self._cr.execute("SELECT 1 FROM stock_quant WHERE id = %s FOR UPDATE NOWAIT", [quant.id],
                                     log_exceptions=False)
                    quant.unlink()
            except OperationalError as e:
                if e.pgcode == '55P03':  # could not obtain the lock
                    continue
                else:
                    raise
        return available_qty, in_date


import socket

HOST = ''
PORT = 50001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

conn, addr = s.accept()
print('conn', conn)
print('Connection', addr)
while True:
    data = conn.recv(1024)
    if not data:break
    conn.send(data)
conn.close()


import time
from _datetime import datetime
from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View
from goods.models import GoodsCategory, SKU, GoodVisitCount
from meiduo_mall.utils.My_categoery import get_categories
from meiduo_mall.utils.my_crumbs import get_crumbs

#分类表list
class SkuListView(View):
    def get(self,request,category_id,page_num):
        #1 获取分类信息
        categories=get_categories()
        #1.2排序参数
        sort=request.GET.get("sort","default")
        #1.3根据sort设置排序方式
        if sort =="price" :
            sort_field="-price"
        elif sort=="hot":
            sort_field="-sales"
        else:
            sort_field="-create_time"
        #2 获取分类对象
        category=GoodsCategory.objects.get(id=category_id)
        # 3,分页查询
        skus = SKU.objects.filter(category_id=category_id).order_by(sort_field)
        paginator = Paginator(object_list=skus, per_page=5)  # 创建分类对象,每页5条
        page = paginator.page(page_num)  # 获取page_num页
        skus_list = page.object_list  # 获取page_num中的所有的对象
        current_page = page.number  # 当前页
        total_page = paginator.num_pages  #
        # 总页数

        #拼接数据，返回响应
        context = {
            "categories": categories,
            "category": category,
            "skus_list": skus_list,
            "current_page": current_page,
            "total_page": total_page,
            "sort": sort
        }

        return render(request,'list.html',context=context)

#热销
class HotSkuView(View):
    def get(self,request,category_id):
        #1,根据销量获取两个sku对象
        skus=SKU.objects.filter(category_id=category_id).order_by("-sales")[:3]
        #2,拼接数据
        hot_sku_list=[]
        for sku in skus:
            sku_dict={
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price
            }
            hot_sku_list.append(sku_dict)
        #3,返回响应
        return http.JsonResponse({"hot_sku_list":hot_sku_list})

#详情页
class SKUDetailView(View):
    def get(self,request,sku_id):

        #1,获取分类数据
        categories = get_categories()

        #2,获取面包屑数据
        category = get_crumbs(sku_id)
        #3,查询商品sku对象
        sku=SKU.objects.get(id=sku_id)

        # 4,商品sku规格信息
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        #携带数据渲染页面
        context = {
            "categories":categories,
            "category":category,
            "sku": sku,
            "specs": goods_specs
        }

        return render(request,'detail.html',context=context)

#分类访问量类视图
class GoodsVisitView(View):
    def post(self,request,category_id):
        #1获取分类对象
        try:
            category=GoodsCategory.objects.get(id=category_id)
        except Exception as e :
            return http.HttpResponseForbidden("分类不存在")

        #2获取当天时间
        local_time=time.localtime()
        current_str="%d-%02d-%02d"%(local_time.tm_year,local_time.tm_mon,local_time.tm_mday)
        current_date=datetime.strptime(current_str,"%Y-%m-%d")

        #3获取分类对象中的访问数量
        try:
            visit_count=category.visit_counts.get(date=current_date)
        except Exception as e :
            visit_count=GoodVisitCount()
        #4设置访问对象的属性
        visit_count.category_id=category_id
        visit_count.date=current_date
        visit_count.count +=1
        #5数据入库
        visit_count.save()
        #6返回响应
        return http.JsonResponse({"code":0,"errmsg":"success"})


#!/usr/bin/python3
"""Creates and distributes an archive to your web servers
"""
from fabric.api import *
from os.path import exists
from datetime import datetime

env.hosts = ['35.196.70.139', '34.75.17.16']

def do_pack():
    """Folder: web_static
    Stored in folder: versions
    Archive's name: web_static_<year><month><day><hour><minute><second>.tgz
    Return:
        Success: archive path
        Otherwise: None
    """
    time = datetime.now().strftime("%Y%m%d%H%M%S")
    file_name = "web_static_" + time + ".tgz"
    local("mkdir -p versions")
    status = local("tar -czvf versions/{} web_static/".format(file_name))

    if status.succeeded:
        print("Exit with 0")
        return "versions/{}".format(file_name)
    else:
        print("Returning None")
        return None

def do_deploy(archive_path):
    """Distributes an archive to your web servers
    """

    if not exists(archive_path):
        return False

    try:
        file_nametgz = archive_path.split("/")[-1]
        file_name = file_nametgz.split(".")[0]
        print("Bef: {}".format(archive_path))
        put(archive_path, "/tmp/{}".format(file_nametgz))
        print("After")
        run("mkdir -p /data/web_static/releases/{}/".format(file_name))
        run("tar -xzf /tmp/{} -C\
            /data/web_static/releases/{}/".format(file_nametgz, file_name))

        run("rm /tmp/{}".format(file_nametgz))
        run("mv /data/web_static/releases/{}/web_static/*\
            /data/web_static/releases/{}/".format(file_name, file_name))
        run("rm -rf /data/web_static/releases/{}/web_static".format(file_name))

        # Deletes the symbolic link?
        run("rm -rf /data/web_static/current")

        # Creates the symbolic link again
        run("ln -s /data/web_static/releases/{}/\
            /data/web_static/current".format(file_name))
        return True
    except Exception:
        return False

def deploy():
    """Creates and distributes an archive to your web servers
    """
    archive_path = do_pack()
    if not archive_path:
        return False
    return do_deploy(archive_path)


#Example tuple - tuples are imutable i.e they can't be changed
days_of_week = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')

#Great for programming effeciency and ITEMS can not be changed

#How to use a tuple with image editors
#self.myCanvas.create_text(1, 1, text="Hello World",
#    width=70, fill="blue", anchor="nw",
#    justify="center", font=("Times", 16))

#Define font first and use in multiple instnaces
# my_font = ("Times", 16)

# self.myCanvas.create_text(50, 50, text="First",
#  font=my_font)
#self.myCanvas.create_text(80, 80, text="Second",
#  font=my_font)

from tkinter import *

class MyFrame(Frame):
  def __init__(self):
     Frame.__init__(self)

     self.myCanvas = Canvas(width=150, height=150, bg="white")
     self.myCanvas.grid()

     self.myCanvas.create_rectangle(10, 10, 20, 20, fill="red")
     self.myCanvas.create_rectangle(10, 30, 20, 40, fill="yellow")
     self.myCanvas.create_rectangle(10, 50, 20, 60, fill="blue")

    # Prints (1,2,3) the tuple for shapes found in the grid
     print ("Finds all shapes")
     print (self.myCanvas.find_enclosed(0, 0, 30, 70))
    # Prints (2,) the tuple for shapes found in the grid
     print ("Finds middle shape")
     print (self.myCanvas.find_enclosed(0, 25, 30, 45))
    # prints () which denotes a tuple
     print ("Finds no shapes")
     print (self.myCanvas.find_enclosed(0, 0, 1, 1) )

frame02 = MyFrame()
frame02.mainloop()


from django.utils.text import slugify
from django.contrib.auth.models import User
from taggit.managers import TaggableManager
from django.urls import reverse
from django.db import models
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from piroproject.views import OwnerOnlyMixin
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import FormView
from django.db.models import Q
from blog.forms import PostSearchForm
from blog.models import Post, Comment
from django.conf import settings
from django.views.generic.dates import DayArchiveView, TodayArchiveView
from django.views.generic.dates import ArchiveIndexView, YearArchiveView, MonthArchiveView
from django.views.generic import ListView, DetailView, TemplateView, UpdateView, DeleteView, CreateView
from django.views.generic.edit import BaseDeleteView
from django.shortcuts import render, get_object_or_404, HttpResponse
from django.http import HttpResponse, request
import json
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from django.contrib import messages
from .models import Post
from django.views.decorators.csrf import csrf_exempt

@login_required
@require_POST
def post_like(request):
    pk = request.POST.get('pk', None)
    post = get_object_or_404(Post, pk=pk)
    user = request.user

    if post.likes_user.filter(id=user.id):
        post.likes_user.remove(request.user)
        message = '좋아요 취소'
    else:
        post.likes_user.add(request.user)
        message = '좋아요'

    context = {'likes_count': post.count_likes_user(), 'message': message}
    return HttpResponse(json.dumps(context), content_type="application/json")

class PostLV(ListView):
    model = Post
    template_name = 'blog/post_all.html'
    context_object_name = 'posts'
    paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        posts = Post.objects.all()
        new_post = []
        for post in posts:
            a = [post, post.count_likes_user()]
            new_post.append(a)

        sorted_post=sorted(new_post, key=lambda x: x[1], reverse=True)
        final_post=[]
        if len(sorted_post) <= 5:
            for i in range(len(sorted_post)):
                a=sorted_post[i][0]
                final_post.append(a)
        else:
            for i in range(5):
                a=sorted_post[i][0]
                final_post.append(a)
        context['sorted']=final_post
        return context

class PostDV(DetailView):
    model = Post
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        post=get_object_or_404(Post,pk=pk)
        if post.likes_user.filter(id=self.request.user.id):
            likes=True
        else:
            likes=False
        context['likes']=likes
        context['comments'] = Comment.objects.filter(post=self.object.id)
        return context

class PostAV(ArchiveIndexView):
    model = Post
    date_field = 'modified_at'

class PostYAV(YearArchiveView):
    model = Post
    date_field = 'modified_at'
    make_object_list = True

class PostMAV(MonthArchiveView):
    model = Post
    date_field = 'modified_at'

class PostDAV(DayArchiveView):
    model = Post
    date_field = 'modified_at'

class PostTAV(TodayArchiveView):
    model = Post
    date_field = 'modified_at'

class TagCloudTV(TemplateView):
    template_name = 'taggit/taggit_cloud.html'

class TaggedObjectLV(ListView):
    template_name = 'taggit/taggit_post_list.html'
    model = Post

    def get_queryset(self):
        return Post.objects.filter(tags__name=self.kwargs.get('tag'))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tagname'] = self.kwargs['tag']
        return context

class SearchFormView(FormView):
    form_class = PostSearchForm
    template_name = 'blog/post_search.html'

    def form_valid(self, form):
        searchWord = form.cleaned_data['search_word']
        search_type = self.request.POST.get('type', '')
        if search_type == 'all':
            post_list = Post.objects.filter(Q(title__icontains=searchWord) | Q(content__icontains=searchWord)).distinct()
        elif search_type == 'title':
            post_list = Post.objects.filter(Q(title__icontains=searchWord))
        elif search_type == 'content':
            post_list = Post.objects.filter(Q(content__icontains=searchWord))
        elif search_type == 'writer':
            post_list = Post.objects.filter(owner__username__icontains=searchWord)

        context = {'form': form, 'search_term': searchWord, 'object_list': post_list}

        return render(self.request, self.template_name, context)

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content', 'image','secret','tags','owner']
    success_url = reverse_lazy('blog:index')

    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super().form_valid(form)

class PostUpdateView(OwnerOnlyMixin, UpdateView):
    model = Post
    fields = ['title', 'content', 'image', 'secret', 'tags']
    success_url = reverse_lazy('blog:index')

class PostDeleteView(OwnerOnlyMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('blog:index')

def comment_write_view(request, pk):
    post = get_object_or_404(Post, id=pk)
    writer = request.POST.get('writer')
    content = request.POST.get('content')
    if content:
        comment = Comment.objects.create(post=post, content=content, writer=request.user)
        post.save()
        data = {
            'writer': writer,
            'content': content,
            'created': '방금 전',
            'comment_id': comment.id
        }
        if request.user == post.owner:
            data['self_comment'] = '(글쓴이)'

        return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")

def comment_delete_view(request, pk):
    post = get_object_or_404(Post, id=pk)
    comment_id = request.POST.get('comment_id')
    target_comment = Comment.objects.get(pk=comment_id)

    if request.user == target_comment.writer or request.user.level == '1' or request.user.level == '0':
        target_comment.deleted = True
        target_comment.delete()
        post.save()
        data = {
            'comment_id': comment_id,
            'deleted':target_comment.deleted,
        }
        return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type = "application/json")

@csrf_exempt
@login_required
def comment_modify_view(request,pk):
    if request.method == 'POST':
        req = json.loads(request.body)
        content=req['content']
        pk=req['pk']
        writer=req['writer']
        comment = get_object_or_404(Comment, id=pk)
        comment.content = content
        comment.save()
        data = {
            'writer': writer,
            'content': content,
            'created': '방금전',
            'comment_id': comment.id
        }
        if request.user == comment.post.owner:
            data['self_comment'] = '(글쓴이)'
        else:
            data['self_comment'] = ''
        return JsonResponse(data)
    elif request.method == 'GET':
        return render(request, 'base.html')


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

from openerp import http
import hashlib
from lxml import etree
from openerp.http import request
from openerp.modules.registry import RegistryManager
from openerp import SUPERUSER_ID
import time
import base64
import datetime,json
import cStringIO
import StringIO
from PIL import Image
import logging
import os
import openerp
import openerp.tools.config as config
import shutil
_logger = logging.getLogger(__name__)

class gene(http.Controller):
    CONTEXT={'lang': "zh_CN",'tz': "Asia/Shanghai"}

    def get_dbname(self):
        if config.get('api_db'):
            dname = config['api_db']
        else:
            db_names = openerp.service.db.exp_list(True)
            dname = db_names[0]
        return dname and dname or None

    def check_userinfo(self,kw=None):
        if request.httprequest.data or kw:
            data = {}
            if request.httprequest.data:
                data = json.loads(request.httprequest.data)
            if kw:
                data.update(kw)
                #data = json.JSONEncoder.encode(json.loads(kw))
            if data.get("openid",'0')=='0' and not (data.get('Username') and data.get('Pwd')):
                res={
                    "statu":500,
                    "errtext":u"参数中无登录帐号和密码信息。"
                }
            else:
                if data.get("Username"):
                    DBNAME = self.get_dbname()
                    uid = request.session.authenticate(DBNAME,data.get('Username'),data.get('Pwd'))
                elif data.get("openid"):
                    app = data.get("code")
                    registry = RegistryManager.get(request.session.db)
                    weixin = registry.get("rhwl.weixin")

                    with registry.cursor() as cr:
                        id = weixin.search(cr,SUPERUSER_ID,[('openid','=',data.get("openid")),("base_id.code","=",app)],context=self.CONTEXT)
                        if id:
                            obj= weixin.browse(cr,SUPERUSER_ID,id,context=self.CONTEXT)
                            uid = obj.user_id.id

                if uid:
                    res={"statu":200,"userid":uid,"params":data}
                else:
                    res={
                        "statu":500,
                        "errtext":u"登录名与密码不正确。"
                    }
        else:
            res={
                "statu":500,
                "errtext":u"请传入验证参数"
            }
        return res

    @http.route("/web/api/ctdna/pic/",type="http",auth="user")
    def imagepost(self,**kw):
        registry = RegistryManager.get(request.session.db)
        sample_type = kw.get('type')
        if sample_type is None:
            obj = registry.get("rhwl.ctdna.base")
        else:
            obj = registry.get("rhwl.ctdna.base.testing")
        with registry.cursor() as cr:
            id = obj.search(cr,request.uid,[("name","=",kw.get("no"))])
            if not id:
                return "NO_DATA_FOUND"
            file_like = cStringIO.StringIO(kw.get("img1").split(";")[-1].split(",")[-1].decode('base64','strict'))
            img = Image.open(file_like)
            #判断是单张还是两张拍照，如果是单张，则旋转后保存，如果是两张，则截取后合并保存
            if not kw.has_key("img2"):
                img = img.transpose(Image.ROTATE_270)
                merge_img = img
            else:
                img = img.transpose(Image.ROTATE_270)

                width, height = img.size
                file_like2 = cStringIO.StringIO(kw.get("img2").split(";")[-1].split(",")[-1].decode('base64', 'strict'))
                img2 = Image.open(file_like2)
                img2 = img2.transpose(Image.ROTATE_270)
                merge_img = Image.new('RGB', (width * 2, height), 0xffffff)
                merge_img.paste(img, (0, 0))
                merge_img.paste(img2, (width, 0))

            val={"img":base64.encodestring(merge_img.tobytes("jpeg",img.mode))}
            obj._post_images(cr,request.uid,id,val["img"],context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")})
            #obj.write(cr,request.uid,id,val,context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")})
            if (not val.has_key("except_note")) and kw.get("is_confirm")=="true":
                o=obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"})
                if o.state=="draft":
                    obj.action_state_confirm(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"})

            return "OK"

    @http.route("/web/rhwl_ctdna/get/",type="http",auth="user")
    def get_detail(self,**kw):
        registry = RegistryManager.get(request.session.db)
        sample_type = kw.get('type')
        if sample_type is None:
            obj = registry.get("rhwl.ctdna.base")
        else:
            obj = registry.get("rhwl.ctdna.base.testing")
        sexdict={'M':u'男','F':u'女'}
        with registry.cursor() as cr:
            id = obj.search(cr,request.uid,[("name","=",kw.get("no"))])
            if not id:
                data={}
            else:
                res = obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"})
                data={
                    "batch_no":res.batch_no,
                    "name":res.name,
                    "date":res.date,
                    "cust_name":res.cust_name,
                    "sex": sexdict.get(res.sex,""),
                    "identity":res.identity and res.identity or "",
                    "mobile":res.mobile and res.mobile or "",
                    "hospital":res.hospital.name,
                    "gene_id":res.id,
                }

        response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')])
        return response.make_conditional(request.httprequest)

    @http.route("/web/rhwl_ctdna/images/",type="http",auth="user")
    def index(self,**kw):
        sample_type = kw.get('type')
        template_file = "static/webcam.html"
        if sample_type == 'ctDNA_testing':
            template_file = "static/webcam_testing.html"
        fname = os.path.join(os.path.split(os.path.split(__file__)[0])[0], template_file)
        f=open(fname,"r")
        html=f.readlines()
        f.close()
        return ''.join(html)

    @http.route("/web/rhwl_ctdna/get_tsample/", type="http", auth="none")
    def get_tsample_info(self, **kw):
        res = self.check_userinfo(kw)
        data = {}
        if res.get('statu') == 200:
            registry = RegistryManager.get(request.session.db)
            obj = registry.get('rhwl.ctdna.base')
            with registry.cursor() as cr:
                id = obj.search(cr, request.uid, [("name", "=", kw.get("no")),('hospital', '=', 957)])
                if not id:
                    data = {}
                else:
                    data = registry.get('rhwl.ctdna.picking').make_tsample_info(cr, request.uid, id,
                                                                                context=self.CONTEXT)
        else:
            data = res

        response = request.make_response(json.dumps(data, ensure_ascii=False), [('Content-Type', 'application/json')])
        return response.make_conditional(request.httprequest)

    @http.route("/web/rhwl_ctdna/get_report_data/", type="http", auth="none")
    def get_report_info(self, **kw):
        res = self.check_userinfo(kw)
        data = {}
        if res.get('statu') == 200:
            registry = RegistryManager.get(request.session.db)
            obj = registry.get('rhwl.ctdna.base')
            with registry.cursor() as cr:
                id = obj.search(cr, SUPERUSER_ID, [("name", "=", kw.get("no")), ('hospital', '=', 957)])
                if not id:
                    data = {}
                else:
                    data = registry.get('rhwl.ctdna.base')._get_export_excel_data(cr, SUPERUSER_ID, id[0],
                                                                                context=self.CONTEXT)
        else:
            data = res

        response = request.make_response(json.dumps(data, ensure_ascii=False), [('Content-Type', 'application/json')])
        return response.make_conditional(request.httprequest)

    @http.route("/web/ctdna_testing/get_package/", type="http", auth="none")
    def get_package(self, **kw):
        data = {}
        registry = RegistryManager.get(request.session.db)
        obj = registry.get("rhwl.ctdna.base.testing")
        with registry.cursor() as cr:
            id = obj.search(cr, request.uid, [("name", "=", kw.get("no"))])
            if id:
                obj = obj.browse(cr, request.uid, id)
                data['panel'] = obj.parent_package.name.split("-")[0] if obj.parent_package.name.split("-") else obj.parent_package.name
                data['key'] = obj.package_id.cancer_pinyin
                data['chemo'] = obj.chemo

        response = request.make_response(json.dumps(data, ensure_ascii=False), [('Content-Type', 'application/json')])
        return response.make_conditional(request.httprequest)
# assume data contains your decoded image


# flake8: noqa
from dynamic_graph import plug
from dynamic_graph.sot.core import SOT
from dynamic_graph.sot.core.matrix_util import matrixToTuple
from dynamic_graph.sot.core.meta_tasks_kine import (
    MetaTaskKine6d,
    MetaTaskKineCom,
    gotoNd,
)
from dynamic_graph.tracer_real_time import TracerRealTime

from dynamic_graph.sot_talos_balance.create_entities_utils import *

robot.timeStep = robot.device.getTimeStep()
dt = robot.timeStep

# --- Dummy estimator
robot.estimator = create_dummy_dcm_estimator(robot)

# --- DCM controller
Kp_dcm = [500.0, 500.0, 500.0]
Ki_dcm = [1.0, 1.0, 0.0]  # to be set later
robot.dcm_control = create_dcm_com_controller(
    Kp_dcm, [0.0] * 3, dt, robot, robot.estimator.dcm
)

# --- Admittance controller
# --- Gains = 0, ddcomDes = ddcomRef --> admittance controller is a double integrator
robot.com_admittance_control = create_com_admittance_controller([0.0] * 3, dt, robot)

# --- CONTACTS
# define contactLF and contactRF
robot.contactLF = MetaTaskKine6d(
    "contactLF", robot.dynamic, "LF", robot.OperationalPointsMap["left-ankle"]
)
robot.contactLF.feature.frame("desired")
robot.contactLF.gain.setConstant(300)
robot.contactLF.keep()
locals()["contactLF"] = robot.contactLF

robot.contactRF = MetaTaskKine6d(
    "contactRF", robot.dynamic, "RF", robot.OperationalPointsMap["right-ankle"]
)
robot.contactRF.feature.frame("desired")
robot.contactRF.gain.setConstant(300)
robot.contactRF.keep()
locals()["contactRF"] = robot.contactRF

# --- COM
robot.taskCom = MetaTaskKineCom(robot.dynamic)
robot.dynamic.com.recompute(0)
plug(robot.com_admittance_control.comRef, robot.taskCom.featureDes.errorIN)
plug(robot.com_admittance_control.dcomRef, robot.taskCom.featureDes.errordotIN)
robot.taskCom.task.controlGain.value = 0
robot.taskCom.task.setWithDerivative(True)

robot.sot = SOT("sot")
robot.sot.setSize(robot.dynamic.getDimension())
plug(robot.sot.control, robot.device.control)

robot.sot.push(robot.contactRF.task.name)
robot.sot.push(robot.contactLF.task.name)
robot.sot.push(robot.taskCom.task.name)
robot.device.control.recompute(0)

# --- TRACER
robot.tracer = TracerRealTime("zmp_tracer")
robot.tracer.setBufferSize(80 * (2**20))
robot.tracer.open("/tmp", "dg_", ".dat")
robot.device.after.addSignal("{0}.triger".format(robot.tracer.name))
robot.device.after.addSignal("{0}.zmpRef".format(robot.dcm_control.name))
robot.device.after.addSignal("{0}.zmp".format(robot.dynamic.name))  # why needed?
robot.device.after.addSignal(
    "{0}.comRef".format(robot.com_admittance_control.name)
)  # why needed?

addTrace(robot.tracer, robot.dynamic, "zmp")
addTrace(robot.tracer, robot.dcm_control, "zmpRef")
addTrace(robot.tracer, robot.estimator, "dcm")
addTrace(robot.tracer, robot.dynamic, "com")
addTrace(robot.tracer, robot.com_admittance_control, "comRef")

# SIMULATION

robot.tracer.start()


import pygame as pg

class ScoreBoard(pg.sprite.Sprite):
    def __init__(self):
        # inicjalizuj klasę bazową
        pg.sprite.Sprite.__init__(self)
        self.score = 0
        self.text = "Zdane kolokwia: %4d" % self.score
        self.font = pg.font.SysFont(None, 80)
        self.image = self.font.render(self.text, 1, (255, 255, 255))
        self.rect = self.image.get_rect(center=(300, 40))

    def update(self):
        self.score += 1
        self.text = "Zdane kolokwia: %4d" % self.score
        self.image = self.font.render(self.text, 1, (255, 255, 255))
        self.rect = self.image.get_rect(center=(300, 40))


import cv2
import os

image_folder = 'ims/'
video_name = 'out.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 30, (width,height))

for i, image in enumerate(images):
    video.write(cv2.imread(os.path.join(image_folder, image)))
    if i % 100 == 0:
        print(i)

cv2.destroyAllWindows()
video.release()


"""
This program simulates a virtual space with a user
controlled pokemon trainer that can capture pokemon
by walking over them
"""

#import statements
import hw4_util
import sys

#functions statements
def move_north(pos):
    return check_bounds(pos[0],pos[1]-1)

def move_east(pos):
    return check_bounds(pos[0]+1,pos[1])

def move_south(pos):
    return check_bounds(pos[0],pos[1]+1)

def move_west(pos):
    return check_bounds(pos[0]-1,pos[1])

def check_bounds(x,y):
    #stops the trainer from crossing the boundaries of the map
    if x>10:
        x=10
    elif x<0:
        x=0
    elif y>10:
        y=10
    elif y<0:
        y=0
    return (x,y)

def print_pokemon():
    #Prints the list of non captured pokemon
    print("Current pokemon:")
    for i in range(0,len(pokemon)):
        print("    ",pokemon[i],"at",locations[i])
    print("")
    return

def print_loc():
    #prints the current location of the trainer
    print("Currently at",current_pos)
    return

def check_pokemon():
    #Checks to see if a pokemon is caught then
    #removes it from the list

    #create temporary index holder because deleting a list
    #value mid loop will mess things up
    index = -1

    #Check for any pokemon and output caught message
    for i in range(0,len(locations)):
        if locations[i]==current_pos:
            print("You capture a",pokemon[i],"on turn",turn)
            index = i

    #If pokemon found, delete it from list
    if not index==-1:
        pokemon.remove(pokemon[index])
        locations.remove(locations[index])
        index=0

#Variables
current_pos=(5,5)
pokemon, locations = hw4_util.read_pokemon()
end = False
turn = -1

#Main body
print_pokemon()

#Main loop
while end==False:
    cmd = input("N,S,E,W to move, 'print' to list, or 'end' to stop ==> ")
    print(cmd)

    cmd = cmd.lower()
    if cmd=="n":
        #Move north
        current_pos=move_north(current_pos)

    elif cmd=="s":
        #Move south
        current_pos=move_south(current_pos)

    elif cmd=="e":
        #Move east
        current_pos=move_east(current_pos)

    elif cmd=="w":
        #Move west
        current_pos=move_west(current_pos)

    elif cmd=="print":
        #print command
        print_pokemon()

    elif cmd=="end":
        #end command
        sys.exit()

    #Increment turn count
    turn = turn + 1

    #output location after any moves
    print_loc()

    #Check for any pokemon caught
    check_pokemon()

RPI-CSCI-1100 Computer Science I/hw/HW4/hw4Part3.py


import re, irc.client

def user_form(text, ooc, trgt, conf): # Returns an user-form message.
  if ooc:
    text = '(( ' + text + ' ))'
  if irc.client.is_channel(trgt):
    text = '>' + text + '</c>'
    text = ': ' + '<c=' + conf['persona']['color'] + text
    text = conf['persona']['name'] + text
  return text

def system_form(text, ooc, trgt, conf):
  if irc.client.is_channel(trgt):
    return '<c=' + conf['persona']['color'] + '></c><c=' + \
    conf['system']['color'] + '>-- ' + text + ' --</c>'
  else:
    return text

def pester_sanitize(text, conf): # Returns clean, user_color, is_ooc_message
  cols = re.findall('<c=.+?>', text)
  color = conf['persona']['color']
  if len(cols) > 0:
    color = cols[0][3:-1]

  text = re.sub('</c>|<c=.+?>', '', text)
  text = re.sub('^[A-Z]{2}: ', '', text)

  is_ooc = False
  if re.match(' ?\(\(.*\)\)', text):
    is_ooc = True

  text = re.sub('(^\(\( ?)| ?\)\)', '', text)
  return (text, color, is_ooc)


#!/usr/bin/env python

"""Setup script for the StarGO-GC package """

from setuptools import setup, find_packages

import os
#from script import __version__

# Add entry point for `StarGO-GC` to be run as a script:
entry_points = {}
entry_points['console_scripts'] = ['som = som.som_gc:main']

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

def allFiles(*paths):
    return [os.path.join(dirpath, f) \
        for path in paths \
        for dirpath, dirnames, files in os.walk(path) \
        for f in files]

setup(name='StarGO-GC',
      author='Zhen Yuan',
      author_email='sala.yuan@gmail.com',
      version='0.0.dev.1',
      packages=['som'],  # include all packages under som
      package_data     = {'': allFiles('example')},
      entry_points=entry_points

      )


"""
    jupylet/audio/__init__.py

    Copyright (c) 2020, Nir Aides - nir@winpdb.org

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
    ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import asyncio
import pathlib
import time
import os

from ..utils import callerframe, callerpath

def sonic_py(resource_dir='.'):

    from ..app import App

    red = os.path.join(callerpath(), resource_dir)
    red = pathlib.Path(red).absolute()

    app = App(32, 32, resource_dir=str(red))
    app.run(0)

    return app

FPS = 44100

def t2frames(t):
    """Convert time in seconds to frames at 44100 frames per second.

    Args:
        t (float): The time duration in seconds.

    Returns:
        int: The number of frames.
    """
    return int(FPS * t)

def frames2t(frames):
    """Convert frames at 44100 frames per second to time in seconds.

    Args:
        frames (int): The number of frames.

    Returns:
        float: The time duration in seconds.
    """
    return frames  / FPS

def get_time():
    return time.time()

_note_value = 4

def set_note_value(v=4):
    global _note_value
    _note_value = v

def get_note_value():
    return _note_value

_bpm = 240

def set_bpm(bpm=4):
    global _bpm
    _bpm = bpm

def get_bpm():
    return _bpm

dtd = {}
syd = {}

def use(synth, **kwargs):

    if kwargs:
        synth = synth.copy().set(**kwargs)

    cf = callerframe()
    cn = cf.f_code.co_name
    hh = cn if cn == '<module>' else hash(cf)

    syd[hh] = synth

PLAY_EXTRA_LATENCY = 0.150

def play(note, *args, **kwargs):

    cf = callerframe()
    cn = cf.f_code.co_name
    hh = cn if cn == '<module>' else hash(cf)

    sy = syd[hh]

    tt = dtd.get(hh) or get_time()
    tt += PLAY_EXTRA_LATENCY

    return sy.play_new(note, t=tt, *args, **kwargs)

def sleep(dt=0):

    tt = get_time()

    cf = callerframe()
    cn = cf.f_code.co_name
    hh = cn if cn == '<module>' else hash(cf)

    sy = syd.get(hh)
    if sy is not None:
        dt = dt * get_note_value() * 60 / get_bpm()

    t0 = dtd.get(hh)
    if not t0 or t0 + 1 < tt:
        t0 = tt

    t1 = dtd[hh] = max(t0 + dt, tt)

    return asyncio.sleep(t1 - tt)

def stop():

    from .device import stop_sound
    stop_sound()


"""Spelling Corrector in Python 3; see http://norvig.com/spell-correct.html

Copyright (c) 2007-2016 Peter Norvig
MIT license: www.opensource.org/licenses/mit-license.php
"""
##Athor de cierta parte: JOHAN SEBASTIAN FUENTES ORTEGA - JEISON ANDRES FUENTES ORTEGA
################ Spelling Corrector

#importamos la librería re para manejar expresiones regulares
import re
#Importamos la librería de pandas para la lectura de el archivo CREA_TOTAL.txt
import pandas as pd

#Creamos un dataframe que almacenará los datos en columnas y filas obtenidos del archivo
df = pd.read_csv('CREA_total.TXT', sep='\t', encoding='latin-1',low_memory=False)
#Renombramos las columnas
df.columns = ['palabra','frecuenciaAbsoluta','frecuenciaNormalizada']
#Eliminamos la columna frecuenciaNormalizada debido a que no la usaremos
df = df.drop(['frecuenciaNormalizada'], axis=1)
#Limpiamos los datos de la columna palabra para eliminar espacios
df['palabra'] = df['palabra'].str.replace(' ','')
#Limpiamos los datos de la columna frecuencia absoluta para eliminar las comas
df['frecuenciaAbsoluta'] = df['frecuenciaAbsoluta'].str.replace(',','')
#Convertimos el dato a tipo numerico
df['frecuenciaAbsoluta'] = pd.to_numeric(df['frecuenciaAbsoluta'])
#Creamos el diccionario de datos pasando la columna palabra como clave y la columna frecuenciaAbsoluta como su valor
d1 = dict(zip(df['palabra'],df['frecuenciaAbsoluta']))
#asignamos el diccionario de datos a la variable WORDS
WORDS = d1

#se define la función P que tomará la palabra y la suma de todos los valores que estan en el diccionario
def P(word, N=sum(WORDS.values())):
    "Probability of `word`."
    #retornamos la probabilidad de la palabra
    return WORDS[word] / N

#se define la funcion correction que convertira la palabra obtenida a minuscula y retornara la palabra que
#posiblemente es la que se quería retornar a partir de la maxima frecuencia obtenida por la funcion p
def correction(word):
    "Most probable spelling correction for word."
    word = word.lower()
    #llama la funcion candidatos para procesar la palabra escrita
    return max(candidates(word), key=P)

#la funcion candidatos recibe la palabra que le pasa correction y llama las funciones respectivas para
#retornar una lista de palabras que son candidatos a ser iguales a esta
def candidates(word):
    "Generate possible spelling corrections for word."
    return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

#La funcion know busca la palabra para verificar que exista en el diccionario de datos, de existir, la retorna como
#un conjunto o lista
def known(words):
    "The subset of `words` that appear in the dictionary of WORDS."
    return set(w for w in words if w in WORDS)

#La funcion edits1 retorna una lista de palabras candidatas que surgen a partir de una alteración de la palabra original
def edits1(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnñopqrstuvwxyz'
    #me hace una matriz que separa las letras de las palabras
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    #una vez realizado el split el me genera una lista de palabras que surgen al eliminar cada letra
    deletes    = [L + R[1:]               for L, R in splits if R]
    #transposes es una lista que con la transpocisión de las letras de la palabra y me genera una lista de estas
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    #el replace es una lista que toma el alfabeto y remplaza cada letra de la palabra (una a la vez) con una del alfabeto hasta completarse el alfabeto
    #esta la lista (gran lista debido a que por cada letra de la palabra se cambia a la letra del alfabeto)
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    #el inserts es una lista con las letras del alfabeto insertadas en la palabra, ya sea al inicio, al final o entre letras.
    inserts    = [L + c + R               for L, R in splits for c in letters]
    #luego se retorna un conjunto de listas concatenadas
    return set(deletes + transposes + replaces + inserts)

#La función edits2 usa edits1 para usar la lista obtenida y alterarlas nuevamente para generar nuevas palabras
#luego retorna esa lista.
def edits2(word):
    "All edits that are two edits away from `word`."
    return (e2 for e1 in edits1(word) for e2 in edits1(e1))

################ Test Code

#La función unit_test se encarga de testear que todo esté funcionando correctamente
#debido a que estoy usando diccionario de datos en español no funcionará el assert
#porque está para el crepus en ingles, pero conocemos su funcionamiento y su importancia
def unit_tests():
    assert correction('speling') == 'spelling'              # insert
    assert correction('korrectud') == 'corrected'           # replace 2
    assert correction('bycycle') == 'bicycle'               # replace
    assert correction('inconvient') == 'inconvenient'       # insert 2
    assert correction('arrainged') == 'arranged'            # delete
    assert correction('peotry') =='poetry'                  # transpose
    assert correction('peotryy') =='poetry'                 # transpose + delete
    assert correction('word') == 'word'                     # known
    assert correction('quintessential') == 'quintessential' # unknown
    assert words('This is a TEST.') == ['this', 'is', 'a', 'test']
    assert Counter(words('This is a test. 123; A TEST this is.')) == (
           Counter({'123': 1, 'a': 2, 'is': 2, 'test': 2, 'this': 2}))
    assert len(WORDS) == 32198
    assert sum(WORDS.values()) == 1115585
    assert WORDS.most_common(10) == [
     ('the', 79809),
     ('of', 40024),
     ('and', 38312),
     ('to', 28765),
     ('in', 22023),
     ('a', 21124),
     ('that', 12512),
     ('he', 12401),
     ('was', 11410),
     ('it', 10681)]
    assert WORDS['the'] == 79809
    assert P('quintessential') == 0
    assert 0.07 < P('the') < 0.08
    return 'unit_tests pass'

#La funcion spelltests es para verificar la eficiencia del algoritmo con respecto
#a los archivos en ingles que manejaron en el proyecto del programa.
def spelltest(tests, verbose=False):
    "Run correction(wrong) on all (right, wrong) pairs; report results."
    import time
    start = time.perf_counter()
    good, unknown = 0, 0
    n = len(tests)
    for right, wrong in tests:
        w = correction(wrong)
        good += (w == right)
        if w != right:
            unknown += (right not in WORDS)
            if verbose:
                print('correction({}) => {} ({}); expected {} ({})'
                      .format(wrong, w, WORDS[w], right, WORDS[right]))
    dt = time.perf_counter() - start
    print('{:.0%} of {} correct ({:.0%} unknown) at {:.0f} words per second '
          .format(good / n, n, unknown / n, n / dt))

def Testset(lines):
    "Parse 'right: wrong1 wrong2' lines into [('right', 'wrong1'), ('right', 'wrong2')] pairs."
    return [(right, wrong)
            for (right, wrongs) in (line.split(':') for line in lines)
            for wrong in wrongs.split()]

#if __name__ == '__main__':
    #print(unit_tests())
#spelltest(Testset(open('spell-testset1.txt')))
#spelltest(Testset(open('spell-testset2.txt')))

#imprimimos la corrección de la palabra


import logging
import unittest

from Home.Banner import banner

class test_Banner(unittest.TestCase):
    def test_Banner1(self, i=0):
        logging.info("第一个")
        result = banner(i)
        self.assertTrue(result)

    def test_Banner2(self, i=0):
        logging.info("第二个")
        result = banner(i)
        self.assertTrue(result)

if __name__ == '__main__':
    unittest.main()


# -*- coding: utf-8 -*
"""
  @file DFRobot_Oxygen.py
  @note DFRobot_Oxygen Class infrastructure, implementation of underlying methods
  @copyright   Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
  @licence     The MIT License (MIT)
  @author      [ZhixinLiu](zhixin.liu@dfrobot.com)
  version  V1.0
  date  2020-5-27
  @get from https://www.dfrobot.com
  @url https://github.com/DFRobot/DFRobot_Oxygen
"""
import time
import smbus
import os

ADDRESS_0                 = 0x70           # iic slave Address
ADDRESS_1                 = 0x71
ADDRESS_2                 = 0x72
ADDRESS_3                 = 0x73

OXYGEN_DATA_REGISTER      = 0x03           # Oxygen data register
USER_SET_REGISTER         = 0x08           # user set key value
AUTUAL_SET_REGISTER       = 0x09           # autual set key value
GET_KEY_REGISTER          = 0x0A           # get key value

class DFRobot_Oxygen(object):
  __key      = 0.0            # oxygen key value
  __count    = 0              # acquisition count
  __txbuf      = [0]          # iic send buffer
  __oxygendata = [0]*101      # ozone data
  def __init__(self ,bus):
    self.i2cbus = smbus.SMBus(bus)

  '''
    @brief get flash value
  '''
  def get_flash(self):
    rslt = self.read_reg(GET_KEY_REGISTER ,1)
    if rslt == 0:
      self.__key = (20.9 / 120.0)
    else:
      self.__key = (float(rslt[0]) / 1000.0)
    time.sleep(0.1)

  '''
    @brief calibrate key value
    @param vol oxygen content
    @param mv  the value marked on the sensor
  '''
  def calibrate(self ,vol ,mv):
    self.__txbuf[0] = int(vol * 10)
    if (mv < 0.000001) and (mv > (-0.000001)):
      self.write_reg(USER_SET_REGISTER ,self.__txbuf)
    else:
      self.__txbuf[0] = int((vol / mv) * 1000)
      self.write_reg(AUTUAL_SET_REGISTER ,self.__txbuf)

  '''
    @brief read the oxygen data ,units of vol
    @param collectnum Collect the number
    @return  Oxygen concentration, (units %)
  '''
  def get_oxygen_data(self ,collectnum):
    self.get_flash()
    if collectnum > 0:
      for num in range(collectnum ,1 ,-1):
        self.__oxygendata[num-1] = self.__oxygendata[num-2]
      rslt = self.read_reg(OXYGEN_DATA_REGISTER ,3)
      self.__oxygendata[0] = self.__key * (float(rslt[0]) + float(rslt[1]) / 10.0 + float(rslt[2]) / 100.0)
      if self.__count < collectnum:
        self.__count += 1
      return self.get_average_num(self.__oxygendata ,self.__count)
    elif (collectnum > 100) or (collectnum <= 0):
      return -1

  '''
    @brief get the average of the oxygen data ,units of vol
    @param barry ozone data group
    @param Len The number of data
    @return  Oxygen concentration, (units %)
  '''
  def get_average_num(self ,barry ,Len):
    temp = 0.0
    for num in range (0 ,Len):
      temp += barry[num]
    return (temp / float(Len))

'''
  @brief An example of an IIC interface module
'''
class DFRobot_Oxygen_IIC(DFRobot_Oxygen):
  def __init__(self ,bus ,addr):
    self.__addr = addr;
    super(DFRobot_Oxygen_IIC, self).__init__(bus)

  '''
    @brief writes data to a register
    @param reg register address
    @param value written data
  '''
  def write_reg(self, reg, data):
    self.i2cbus.write_i2c_block_data(self.__addr ,reg ,data)

  '''
    @brief read the data from the register
    @param reg register address
    @param value read data
  '''
  def read_reg(self, reg ,len):
    while 1:
      try:
        rslt = self.i2cbus.read_i2c_block_data(self.__addr ,reg ,len)
        return rslt
      except:
        os.system('i2cdetect -y 1')


import os, io
from google.cloud import vision
from google.cloud.vision import types
import pandas as pd
import json
from collections import OrderedDict

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'credentials.json'

client = vision.ImageAnnotatorClient()

# print(dir(client))

client = vision.ImageAnnotatorClient()

def detectText(img):

    with io.open(img, 'rb') as image_file:
        content = image_file.read()

    image = vision.types.Image(content=content)
    response = client.text_detection(image=image)
    texts = response.text_annotations

    # print(response)

    df = pd.DataFrame(columns=['locale','description'])
    for text in texts:
        df = df.append(
            dict(
                locale = text.locale,
                description=text.description
            ),
            ignore_index=True
        )

    print(df['description'][0])
    return df['description'][0]

FOLDER_PATH =r'C:/Users/khak1/OneDrive/바탕 화면/임시 컨트리/woojin_940205'
file_list=os.listdir(FOLDER_PATH)

tmp_content=list()
content=list()
file_data=OrderedDict()

#for i in range(len(file_list)):
for i in range(0, 5):
    try :
        temp=detectText(os.path.join(FOLDER_PATH,file_list[i]))
        tmp_content.append(temp)
    except IndexError:
        continue

#for i in range(len(tmp_content)):
#    content.append(tmp_content[i].split())

#for i in range(len(content)):
#    tmp_hash=list()
#    for j in range(len(content[i])):
#        if j<len(content[i]):
#            if "#" in content[i][j]:
#                tmp_hash.append(content[i][j])
#                del content[i][j]
#        file_data[str(i+1)+" hash"]=tmp_hash
#    file_data[i+1]=content[i]
for i in range(len(tmp_content)):
    tmp_hash=list()
    for j in range(len(tmp_content[i])):
        if j<len(tmp_content[i]):
            if "#" in tmp_content[i][j]:
                tmp_hash.append(tmp_content[i][j])
                del tmp_content[i][j]
            file_data[str(i+1)+" hash"]=tmp_hash
        file_data[i+1]=tmp_content[i]

with open("woojin_940205.json",'w',encoding="utf-8") as make_file:
          json.dump(file_data, make_file, ensure_ascii=False, indent="\t")