from __future__ import unicode_literals
#-------------------------------------------------------------------------
#
# Python modules
#
#-------------------------------------------------------------------------
import re

#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from ..lib.date import Date
from ._dateparser import DateParser
from ._datedisplay import DateDisplay
from ._datehandler import register_datehandler

#-------------------------------------------------------------------------
#
# Slovenian parser
#
#-------------------------------------------------------------------------
class DateParserSL(DateParser):
    """
    Converts a text string into a Date object
    """
    month_to_int = DateParser.month_to_int

    month_to_int["januar"] = 1
    month_to_int["januarja"] = 1
    month_to_int["januarjem"] = 1
    month_to_int["jan"] = 1
    month_to_int["i"] = 1

    month_to_int["februar"] = 2
    month_to_int["februarjem"] = 2
    month_to_int["februarja"] = 2
    month_to_int["feb"] = 2
    month_to_int["ii"]  = 2

    month_to_int["mar"] = 3
    month_to_int["marcem"] = 3
    month_to_int["marec"] = 3
    month_to_int["marca"] = 3
    month_to_int["iii"]  = 3

    month_to_int["apr"] = 4
    month_to_int["april"] = 4
    month_to_int["aprilom"] = 4
    month_to_int["aprila"] = 4
    month_to_int["iv"]  = 4

    month_to_int["maj"] = 5
    month_to_int["maja"] = 5
    month_to_int["majem"] = 5
    month_to_int["v"]  = 5

    month_to_int["jun"] = 6
    month_to_int["junij"] = 6
    month_to_int["junijem"] = 6
    month_to_int["junija"] = 6
    month_to_int["vi"]  = 6

    month_to_int["jul"]  = 7
    month_to_int["julij"]  = 7
    month_to_int["julijem"]  = 7
    month_to_int["julija"]  = 7
    month_to_int["vii"]  = 7

    month_to_int["avg"]  = 8
    month_to_int["avgust"]  = 8
    month_to_int["avgustom"]  = 8
    month_to_int["avgusta"]  = 8
    month_to_int["viii"]  = 8

    month_to_int["sep"]  = 9
    month_to_int["sept"]  = 9
    month_to_int["september"]  = 9
    month_to_int["septembrom"]  = 9
    month_to_int["septembra"]  = 9
    month_to_int["ix"]  = 9

    month_to_int["okt"]  = 10
    month_to_int["oktober"]  = 10
    month_to_int["oktobrom"]  = 10
    month_to_int["oktobra"]  = 10
    month_to_int["x"]  = 10

    month_to_int["nov"]  = 11
    month_to_int["november"]  = 11
    month_to_int["novembrom"]  = 11
    month_to_int["novembra"]  = 11
    month_to_int["xi"]  = 11

    month_to_int["dec"]  = 12
    month_to_int["december"]  = 12
    month_to_int["decembrom"]  = 12
    month_to_int["decembra"]  = 12
    month_to_int["xii"]  = 12

    modifier_to_int = {
        'pred'   : Date.MOD_BEFORE,
        'pr.'    : Date.MOD_BEFORE,
        'po'     : Date.MOD_AFTER,
        'okoli'  : Date.MOD_ABOUT,
        'okrog'  : Date.MOD_ABOUT,
        'okr.'   : Date.MOD_ABOUT,
        'ok.'    : Date.MOD_ABOUT,
        'cca.'   : Date.MOD_ABOUT,
        'cca'    : Date.MOD_ABOUT,
        'circa'  : Date.MOD_ABOUT,
        'ca.'    : Date.MOD_ABOUT,
        }

    calendar_to_int = {
        'gregorijanski'  : Date.CAL_GREGORIAN,
        'greg.'          : Date.CAL_GREGORIAN,
        'julijanski'     : Date.CAL_JULIAN,
        'jul.'           : Date.CAL_JULIAN,
        'hebrejski'      : Date.CAL_HEBREW,
        'hebr.'          : Date.CAL_HEBREW,
        'islamski'       : Date.CAL_ISLAMIC,
        'isl.'           : Date.CAL_ISLAMIC,
        'francoski republikanski': Date.CAL_FRENCH,
        'franc.'         : Date.CAL_FRENCH,
        'perzijski'      : Date.CAL_PERSIAN,
        'perz. '         : Date.CAL_PERSIAN,
        'švedski'        : Date.CAL_SWEDISH,
        'šved.'          : Date.CAL_SWEDISH,
        }

    quality_to_int = {
        'približno'   : Date.QUAL_ESTIMATED,
        'pribl.'      : Date.QUAL_ESTIMATED,
        'izračunano'  : Date.QUAL_CALCULATED,
        'izrač.'        : Date.QUAL_CALCULATED,
        }

    bce = ["pred našim štetjem", "pred Kristusom",
           "p.n.š.", "p. n. š.", "pr.Kr.", "pr. Kr."] + DateParser.bce

    def init_strings(self):
        """
        compiles regular expression strings for matching dates
        """
        DateParser.init_strings(self)
        # match 'Day. MONTH year.' format with or without dots
        self._text2 = re.compile('(\d+)?\.?\s*?%s\.?\s*((\d+)(/\d+)?)?\s*\.?$'
                                % self._mon_str, re.IGNORECASE)
        # match Day.Month.Year.
        self._numeric  = re.compile("((\d+)[/\.-])?\s*((\d+)[/\.-])?\s*(\d+)\.?$")

        self._span  = re.compile("od\s+(?P<start>.+)\s+do\s+(?P<stop>.+)",
                                re.IGNORECASE)
        self._range = re.compile(
                            "med\s+(?P<start>.+)\s+in\s+(?P<stop>.+)",
                            re.IGNORECASE)
        self._jtext2 = re.compile('(\d+)?.?\s+?%s\s*((\d+)(/\d+)?)?'\
                                % self._jmon_str, re.IGNORECASE)

#-------------------------------------------------------------------------
#
# Slovenian display
#
#-------------------------------------------------------------------------
class DateDisplaySL(DateDisplay):
    """
    Slovenian language date display class.
    """
    long_months = ( "", "januarja", "februarja", "marca","aprila",
        "maja", "junija", "julija", "avgusta", "septembra",
        "oktobra", "novembra", "decembra"
        )

    short_months = ( "", "jan", "feb", "mar", "apr", "maj", "jun",
        "jul", "avg", "sep", "okt", "nov", "dec"
        )

    calendar = (
        "", "julijanski", "hebrejski",
        "francoski republikanski", "perzijski", "islamski",
        "švedski"
        )

    _mod_str = ("", "pred ", "po ", "okrog ", "", "", "")

    _qual_str = ("", "približno ", "izračunano ")

    _bce_str = "%s p.n.š."

    formats = (
        "ISO (leto-mm-dd)",
        "številčno",
        "dan. mes. leto",
        "dan. mesec leto"
        )
        # this definition must agree with its "_display_gregorian" method

    def _display_gregorian(self, date_val):
        """
        display gregorian calendar date in different format
        """
        # this must agree with its locale-specific "formats" definition
        year = self._slash_year(date_val[2], date_val[3])
        if self.format == 0:
            return self.display_iso(date_val)
        elif self.format == 1:
            # day. month_number. year
            if date_val[3]:
                return self.display_iso(date_val)
            else:
                if date_val[0] == 0 and date_val[1] == 0:
                    value = str(date_val[2])
                else:
                    value = self._tformat.replace('%m', str(date_val[1]))
                    value = value.replace('%d', str(date_val[0]))
                    value = value.replace('%Y', str(date_val[2]))
                    value = value.replace('-', '. ')
        elif self.format == 2:
            # day. month_abbreviation. year
            if date_val[0] == 0:
                if date_val[1] == 0:
                    value = year
                else:
                    value = "%s. %s" % (self.short_months[date_val[1]], year)
            else:
                value = "%d. %s. %s" % (date_val[0],
                                        self.short_months[date_val[1]], year)
        else:
            # day. month_name year
            if date_val[0] == 0:
                if date_val[1] == 0:
                    value = "%s." % year
                else:
                   value = "%s %s" % (self.long_months[date_val[1]], year)
            else:
                value = "%d. %s %s" % (
                  date_val[0],self.long_months[date_val[1]], year)
        if date_val[2] < 0:
            return self._bce_str % value
        else:
            return value

    def display(self, date):
        """
        Return a text string representing the date.
        """
        mod = date.get_modifier()
        cal = date.get_calendar()
        qual = date.get_quality()
        start = date.get_start_date()
        newyear = date.get_new_year()

        qual_str = self._qual_str[qual]

        if mod == Date.MOD_TEXTONLY:
            return date.get_text()
        elif start == Date.EMPTY:
            return ""
        elif mod == Date.MOD_SPAN:
            d_1 = self.display_cal[cal](start)
            d_2 = self.display_cal[cal](date.get_stop_date())
            scal = self.format_extras(cal, newyear)
            return "%sod %s do %s%s" % (qual_str, d_1, d_2, scal)
        elif mod == Date.MOD_RANGE:
            d_1 = self.display_cal[cal](start)
            d_2 = self.display_cal[cal](date.get_stop_date())
            scal = self.format_extras(cal, newyear)
            date_string = "%smed %s in %s%s" % (qual_str, d_1, d_2, scal)
            date_string = date_string.replace("a ","em ") #to correct declination
            date_string = date_string.replace("lem ","lom ")
            date_string = date_string.replace("rem ","rom ")
            date_string = date_string.replace("tem ","tom ")
            return date_string
        else:
            text = self.display_cal[date.get_calendar()](start)
            scal = self.format_extras(cal, newyear)
            date_string = "%s%s%s%s" % (qual_str, self._mod_str[mod], text, scal)
        return date_string

#-------------------------------------------------------------------------
#
# Register classes
#
#-------------------------------------------------------------------------
register_datehandler(("sl", "SL", "sl_SI", "slovenščina", "slovenian", "Slovenian",
                 "sl_SI.UTF8", "sl_SI.UTF-8", "sl_SI.utf-8", "sl_SI.utf8"),
                                    DateParserSL, DateDisplaySL)


# -*- coding:utf-8 -*-
from osgeo import gdal
import dill

class PickalableSWIG:
    def __setstate__(self, state):
        self.__init__(*state['args'])

    def __getstate__(self):
        return {'args': self.args}

class PickalableGDALDataset(gdal.Dataset,PickalableSWIG):
    def __init__(self,*args):
        self.args = args

if __name__ == '__main__':
    path = r"G:\武大质检程序样例数据\影像\1自动处理影像异常值\H50G022096\H50G022096.img"
    ds = gdal.Open(path)
    pickleDs = PickalableGDALDataset(ds)
    dill.dumps(pickleDs)


import sys

#启动参数 python3 concatFile143.py data/test.txt data/test1.txt

def main():

	try:
		boylines = []
		startY = input("StartYear:")
		endY = input("EndYear:")
		for i in range(int(startY),int(endY)):
			filenameB = 'BabyNames/'+str(i)+"_BoysNames.txt"

			with open(filenameB) as infile:
				line = infile.readline().strip()
				boylines.append(line)
				print(line)

	except IOError:
		print("获取文件时候出错")
		quit()

	print("-"*20)
	print(boylines)

if __name__ == "__main__":
    main()


# Execute with "py -3 .\roboc.py"
# For OpenClass rooms

import os

import settings
import languages
import game

def main():
    """This function is only useful to not pollute global namespace with variables"""
    if settings.SAVE_FILE_NAME in os.listdir('.'):
        if input(t_.CONTINUE_GAME).strip().upper() == t_.SHORT_YES:
            level_name, position = game.saved_game_data(settings.SAVE_FILE_NAME)
            Game.level = level_name
            Game.level.player_position = position
        else:
            os.unlink(settings.SAVE_FILE_NAME)

    if not Game.level:
        Game.notification(t_.CHOOSE_MAP)
        for i, _ in enumerate(Game.levels):
            Game.notification("[{}] {}".format(i + 1, _.name.replace('.txt', '')))
        Game.level = input("> ")

if __name__ == "__main__":

    t_ = languages.get_language(settings.LANGUAGE)

    with game.Game() as Game:

        if not len(Game.levels):
            raise Game.NoMapsFound

        main()

        Game.level.draw()
        while Game.execute_input(input(t_.GAME_INPUT_PROMPT)):
            Game.level.draw()


from pydoc import cli
from django.shortcuts import render, redirect
from .forms import MedicoFormRegister, ClienteFormRegister, LoginForm, ConsultasForm
from .models import Medico, Cliente, Consulta
from django.contrib.auth import logout

# Create your views here.

def index(request):
	usuario = request.user

	if usuario.is_authenticated:
		if hasattr(usuario, 'medico'):
			consultas2 = Consulta.objects.filter(id_med=usuario.id)
			medico = Medico.objects.get(id=usuario.id)
			if consultas2 != None:
				context = {
					'nome': f'{medico.first_name}  {medico.last_name}',
					'consultas': consultas2,
					'telefone': f'{medico.num_pais} ({medico.num_ddd}) {medico.num_telefone}',
					'cep': medico.cep,
					'endereco': medico.endereco
				}
			else:
				context = {
					'nome': f'{medico.first_name}  {medico.last_name}',
					'telefone': f'{medico.num_pais} ({medico.num_ddd}) {medico.num_telefone}',
					'cep': medico.cep,
					'endereco': medico.endereco
				}
			return render(request, 'home_medico.html', context)
		elif hasattr(usuario, 'cliente'):
			consultas = Consulta.objects.filter(id_cli=usuario.id)
			cliente = Cliente.objects.get(id=usuario.id)
			if consultas != None:
				context = {
					'nome': f'{cliente.first_name}  {cliente.last_name}',
					'consultas': consultas,
					'telefone': f'{cliente.num_pais} ({cliente.num_ddd}) {cliente.num_telefone}',
					'cep': cliente.cep,
					'endereco': cliente.endereco
				}
			else:
				context = {
					'nome': f'{cliente.first_name}  {cliente.last_name}',
					'telefone': f'{cliente.num_pais} ({cliente.num_ddd}) {cliente.num_telefone}',
					'cep': cliente.cep,
					'endereco': cliente.endereco
				}
			return render(request, 'home_cliente.html', context)

	return render(request, 'index.html')

def logout_view(request):
    logout(request)
    return redirect('/')

def login(request):
	formulario = LoginForm(request.POST or None)

	if request.method == 'POST' and formulario.is_valid():
		formulario.login(request)
		return redirect('/')

	context = {
		'form': formulario
	}

	return render(request, 'login.html', context)

def registrar_medico(request):
	formulario = MedicoFormRegister(request.POST or None)

	if request.method == 'POST' and formulario.is_valid():
		formulario.save()
		return redirect('/login/')

	context = {
		'form': formulario
	}

	return render(request, 'registrar_medico.html', context)

def registrar_cliente(request):
	formulario = ClienteFormRegister(request.POST or None)

	if request.method == 'POST' and formulario.is_valid():
		formulario.save()
		return redirect('/login/')

	context = {
		'form': formulario
	}

	return render(request, 'registrar_cliente.html', context)

def registrar_consulta(request):
	cliente = request.user

	if cliente.is_authenticated and hasattr(cliente, 'cliente'):
		formulario = ConsultasForm(request.POST or None)

		if request.method == 'POST' and formulario.is_valid():
			formulario.save(clid=cliente.id)
			return redirect('/')

		context = {
			'form': formulario,
		}

		return render(request, 'registrar_consulta.html', context)
	else:
		return redirect('/')

def aceitar_consulta(request, consulta_id):
	medico = request.user

	if medico.is_authenticated and hasattr(medico, 'medico'):
		consulta = Consulta.objects.get(id=consulta_id)
		if consulta.id_med == medico.id:
			consulta.status = 1
			consulta.save(update_fields=['status'])
		else:
			return redirect('/')
	return redirect('/')

def negar_consulta(request, consulta_id):
	medico = request.user

	if medico.is_authenticated and hasattr(medico, 'medico'):
		consulta = Consulta.objects.get(id=consulta_id)
		if consulta.id_med == medico.id:
			consulta.status = 2
			consulta.save(update_fields=['status'])
		else:
			return redirect('/')
	return redirect('/')


import ase.io, os.path
from utilities import relax_config, run_root, rescale_to_relaxed_bulk, evaluate
import ase.build
import numpy as np
import spglib

def do_one_antisite_pair(bulk_supercell, bulk_supercell_pe, i1, i2, tol=1.0e-2):
    assert bulk_supercell.numbers[i1] != bulk_supercell.numbers[i2]

    # do unrelaxed (without perturbations)
    antisite = bulk_supercell.copy()
    Z1, Z2 = antisite.numbers[[i1, i2]]
    antisite.numbers[i1] = Z2
    antisite.numbers[i2] = Z1

    label = "ind_%d_Z_%d_ind_%d_Z_%d" % (i1, Z1, i2, Z2)
    unrelaxed_filename=run_root+"-%s-unrelaxed.xyz" % label
    ase.io.write(os.path.join("..", unrelaxed_filename), antisite, format='extxyz')
    evaluate(antisite)
    unrelaxed_antisite_pe = antisite.get_potential_energy()

    antisite = relax_config(antisite, relax_pos=True, relax_cell=False, tol=tol, save_traj=True,
        config_label=label, from_base_model=True, save_config=True, try_restart=True)
    relaxed_filename=run_root+"-%s-relaxed.xyz" % label
    ase.io.write(os.path.join("..", relaxed_filename), antisite, format='extxyz')

    # already has calculator from relax_configs
    antisite_pe = antisite.get_potential_energy()
    Ef0 = unrelaxed_antisite_pe - bulk_supercell_pe
    Ef = antisite_pe - bulk_supercell_pe
    print("got antisite", label, "cell energy", antisite_pe, "n_atoms", len(antisite))
    print("got bulk energy", bulk_supercell_pe)
    return ( label, unrelaxed_filename, Ef0, relaxed_filename, Ef, Z1, Z2 )

def do_farthest_inequiv_pairs(test_dir, tol=1.0e-2):
    print("doing do_farthest_antisite_pairs")
    bulk_supercell = ase.io.read(os.path.join(test_dir, "bulk_supercell.xyz"), format="extxyz")
    print("got bulk_supercell ", len(bulk_supercell))

    bulk = rescale_to_relaxed_bulk(bulk_supercell)
    # relax bulk supercell positions in case it's only approximate (as it must be for different models), but stick
    # to relaxed bulk's lattice constants as set by rescale_to_relaxed_bulk
    bulk_supercell = relax_config(bulk_supercell, relax_pos=True, relax_cell=False, tol=tol, save_traj=True,
        config_label="rescaled_bulk", from_base_model=True, save_config=True)

    ase.io.write(os.path.join("..", run_root+"-rescaled-bulk.xyz"),  bulk_supercell, format='extxyz')

    print("got bulk primitive cell ", bulk.get_cell())
    print("got rescaled bulk_supercell cell ", bulk_supercell.get_cell())

    if 'arb_supercell' in bulk_supercell.info:
        print("making bulk supercell from", bulk_supercell.info['arb_supercell'].reshape((3,3)))
        bulk_supersupercell = ase.build.make_supercell(bulk_supercell, bulk_supercell.info['arb_supercell'].reshape((3,3)))
        print("got supersupercell with ", len(bulk_supersupercell), "atoms, cell\n", bulk_supersupercell.get_cell())

        bulk_supersupercell.info.update(bulk_supercell.info)
        bulk_supercell = bulk_supersupercell

    sym_data = spglib.get_symmetry_dataset(bulk_supercell, symprec=0.01)
    equiv_at = set([tuple(iZ) for iZ in zip(sym_data["equivalent_atoms"], bulk_supercell.numbers)])

    # print("equiv_at", equiv_at)

    antisite_list = []
    for i1, Z1 in equiv_at:
        for i2_proto, Z2 in equiv_at:
            if Z1 <= Z2:
                continue
            # print("check i", i1, i2_proto, "Z", Z1, Z2)

            i2s = np.where(sym_data["equivalent_atoms"] == i2_proto)[0]
            i2_dists = bulk_supercell.get_distances(i1, i2s, mic=True)
            farthest_ind = np.argmax(i2_dists)
            i2 = i2s[farthest_ind]

            antisite_list.append((i1, i2))

    # print("antisite_list", antisite_list) ##

    evaluate(bulk_supercell)
    bulk_supercell_pe = bulk_supercell.get_potential_energy()
    properties = { "bulk_struct_test" : bulk_supercell.info["bulk_struct_test"], "bulk_E_per_atom" : bulk_supercell_pe / len(bulk_supercell), "defects" : {} }

    for i1, i2 in antisite_list:
        (label, unrelaxed_filename, Ef0, relaxed_filename, Ef, Z1, Z2) = do_one_antisite_pair(bulk_supercell, bulk_supercell_pe, i1, i2, tol)

        properties["defects"][label] = { 'Ef0' : Ef0, 'Ef' : Ef, 'unrelaxed_filename' : unrelaxed_filename, 'relaxed_filename' : relaxed_filename,
            'atom_inds' : (int(i1), int(i2)), 'Zs' : (int(Z1), int(Z2)) }

    print("returning properties", properties)
    return properties


# %load ../code/student_code_ind4.py
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import math
import random
import glob
import os
import numpy as np

import cv2
import numbers
import collections

import torch
from torch.utils import data

from utils import resize_image, load_image

# default list of interpolations
_DEFAULT_INTERPOLATIONS = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]

#################################################################################
# These are helper functions or functions for demonstration
# You won't need to modify them
#################################################################################

class Compose(object):
  """Composes several transforms together.

  Args:
      transforms (list of ``Transform`` objects): list of transforms to compose.

  Example:
      >>> Compose([
      >>>     Scale(320),
      >>>     RandomSizedCrop(224),
      >>> ])
  """
  def __init__(self, transforms):
    self.transforms = transforms

  def __call__(self, img):
    for t in self.transforms:
      img = t(img)
    return img

  def __repr__(self):
    repr_str = ""
    for t in self.transforms:
      repr_str += t.__repr__() + '\n'
    return repr_str

class RandomHorizontalFlip(object):
  """Horizontally flip the given numpy array randomly
     (with a probability of 0.5).
  """
  def __call__(self, img):
    """
    Args:
        img (numpy array): Image to be flipped.

    Returns:
        numpy array: Randomly flipped image
    """
    if random.random() < 0.5:
      img = cv2.flip(img, 1)
      return img
    return img

  def __repr__(self):
    return "Random Horizontal Flip"

#################################################################################
# You will need to fill in the missing code in these classes
#################################################################################
class Scale(object):
  """Rescale the input numpy array to the given size.

  Args:
      size (sequence or int): Desired output size. If size is a sequence like
          (w, h), output size will be matched to this. If size is an int,
          smaller edge of the image will be matched to this number.
          i.e, if height > width, then image will be rescaled to
          (size, size * height / width)

      interpolations (list of int, optional): Desired interpolation.
      Default is ``CV2.INTER_NEAREST|CV2.INTER_LINEAR|CV2.INTER_CUBIC``
      Pass None during testing: always use CV2.INTER_LINEAR
  """
  def __init__(self, size, interpolations=_DEFAULT_INTERPOLATIONS):
    assert (isinstance(size, int)
            or (isinstance(size, collections.Iterable)
                and len(size) == 2)
           )
    self.size = size
    # use bilinear if interpolation is not specified
    if interpolations is None:
      interpolations = [cv2.INTER_LINEAR]
    assert isinstance(interpolations, collections.Iterable)
    self.interpolations = interpolations

  def __call__(self, img):
    """
    Args:
        img (numpy array): Image to be scaled.

    Returns:
        numpy array: Rescaled image
    """
    # sample interpolation method
    interpolation = random.sample(self.interpolations, 1)[0]

    # scale the image
    if isinstance(self.size, int):
      h, w, c = img.shape
      ratio = self.size/min(h,w)
      img = resize_image(img, (int(w*ratio),int(h*ratio)), interpolation)
      return img
    else:
      img = resize_image(img, self.size, interpolation)
      return img

  def __repr__(self):
    if isinstance(self.size, int):
      target_size = (self.size, self.size)
    else:
      target_size = self.size
    return "Scale [Exact Size ({:d}, {:d})]".format(target_size[0], target_size[1])

class RandomSizedCrop(object):
  """Crop the given numpy array to random area and aspect ratio.

  A crop of random area of the original size and a random aspect ratio
  of the original aspect ratio is made. This crop is finally resized to given size.
  This is widely used as data augmentation for training image classification models

  Args:
      size (sequence or int): size of target image. If size is a sequence like
          (w, h), output size will be matched to this. If size is an int,
          output size will be (size, size).
      interpolations (list of int, optional): Desired interpolation.
      Default is ``CV2.INTER_NEAREST|CV2.INTER_LINEAR|CV2.INTER_CUBIC``
      area_range (list of int): range of the areas to sample from
      ratio_range (list of int): range of aspect ratio to sample from
      num_trials (int): number of sampling trials
  """

  def __init__(self, size, interpolations=_DEFAULT_INTERPOLATIONS,
               area_range=(0.25, 1.0), ratio_range=(0.8, 1.2), num_trials=10):
    self.size = size
    if interpolations is None:
      interpolations = [cv2.INTER_LINEAR]
    assert isinstance(interpolations, collections.Iterable)
    self.interpolations = interpolations
    self.num_trials = int(num_trials)
    self.area_range = area_range
    self.ratio_range = ratio_range

  def __call__(self, img):
    # sample interpolation method
    interpolation = random.sample(self.interpolations, 1)[0]

    for attempt in range(self.num_trials):

      # sample target area / aspect ratio from area range and ratio range
      area = img.shape[0] * img.shape[1]
      target_area = random.uniform(self.area_range[0], self.area_range[1]) * area
      aspect_ratio = random.uniform(self.ratio_range[0], self.ratio_range[1])

      #################################################################################
      # Fill in the code here
      #################################################################################
      # compute the width and height
      # note that there are two possibilities
      # crop the image and resize to output size

      # h*w = (w*aspect_ratio)*w = target_area
      hw_list = []
      width = (target_area/aspect_ratio)**0.5
      height = width*aspect_ratio
      height, width = int(height), int(width)

      # two possibilities:
      hw_list = [(height, width), (width,height)]
      for h, w in hw_list:
        # find a suitable crop area and aspect_ratio
        if h < img.shape[0] and w < img.shape[1]:
          randX = random.sample(range(0, img.shape[0]-h), 1)[0]
          randY = random.sample(range(0, img.shape[1]-w), 1)[0]
          if isinstance(self.size, int):
            img = resize_image(img[randX:(randX+h), randY:(randY+w)],
                                (self.size, self.size),
                                interpolation)
          else:
            img = resize_image(img[randX:(randX+h), randY:(randY+w)],
                                self.size,
                                interpolation)
          return img

    # Fall back
    if isinstance(self.size, int):
      im_scale = Scale(self.size, interpolations=self.interpolations)
      img = im_scale(img)
      #################################################################################
      # Fill in the code here
      #################################################################################
      # with a square sized output, the default is to crop the patch in the center
      # (after all trials fail)
      imgH, imgW = img.shape[0], img.shape[1]
      if imgH > imgW:
        offset = imgH - imgW
        img = img[offset//2:-(offset-offset//2),:]
      else:
        offset = imgW - imgH
        img = img[:, offset//2:-(offset-offset//2)]
      return img
    else:
      # with a pre-specified output size, the default crop is the image itself
      im_scale = Scale(self.size, interpolations=self.interpolations)
      img = im_scale(img)
      return img

  def __repr__(self):
    if isinstance(self.size, int):
      target_size = (self.size, self.size)
    else:
      target_size = self.size
    return "Random Crop" + \
           "[Size ({:d}, {:d}); Area {:.2f} - {:.2f}%; Ratio {:.2f} - {:.2f}%]".format(
            target_size[0], target_size[1],
            self.area_range[0], self.area_range[1],
            self.ratio_range[0], self.ratio_range[1])

class RandomColor(object):
  """Perturb color channels of a given image
  Sample alpha in the range of (-r, r) and multiply 1 + alpha to a color channel.
  The sampling is done independently for each channel.

  Args:
      color_range (float): range of color jitter ratio (-r ~ +r) max r = 1.0
  """
  def __init__(self, color_range):
    self.color_range = color_range

  def __call__(self, img):
    #################################################################################
    # Fill in the code here
    #################################################################################
    for c in range(img.shape[2]):
      alpha = random.uniform(-self.color_range, self.color_range)
      for i in range(img.shape[0]):
        for j in range(img.shape[1]):
          img[i,j,c]= np.clip(img[i,j,c]*(1+alpha), 0, 255).astype(np.uint8)
    return img

  def __repr__(self):
    return "Random Color [Range {:.2f} - {:.2f}%]".format(
            1-self.color_range, 1+self.color_range)

class FastRandomColor(RandomColor):
  """
  A fast implementation of RandomColor using pre-calculated lookup table.
  """
  def __init__(self, color_range):
    super().__init__(color_range)

  def __call__(self, img):
    for c in range(img.shape[2]):
      alpha = random.uniform(-self.color_range, self.color_range)
      color_dict = {}
      for i in range(256):
        color_dict[i] = np.clip(i*(1+alpha), 0, 255).astype(np.uint8)
      for i in range(img.shape[0]):
        for j in range(img.shape[1]):
          img[i,j,c]=color_dict[img[i,j,c]]
    return img

class FasterRandomColor(RandomColor):
  """
  A faster implementation of RandomColor using matrix calculations.
  """
  def __init__(self, color_range):
    super().__init__(color_range)

  def __call__(self, img):
    for c in range(img.shape[2]):
      alpha = random.uniform(-self.color_range, self.color_range)
      img[:,:,c] = np.clip(img[:,:,c].astype(float)*(1+alpha), 0, 255).astype(np.uint8)
    return img

class RandomRotate(object):
  """Rotate the given numpy array (around the image center) by a random degree.

  Args:
      degree_range (float): range of degree (-d ~ +d)
  """
  def __init__(self, degree_range, interpolations=_DEFAULT_INTERPOLATIONS):
    self.degree_range = degree_range
    if interpolations is None:
      interpolations = [cv2.INTER_LINEAR]
    assert isinstance(interpolations, collections.Iterable)
    self.interpolations = interpolations

  def __call__(self, img):
    # sample interpolation method
    interpolation = random.sample(self.interpolations, 1)[0]
    # sample rotation
    degree = random.uniform(-self.degree_range, self.degree_range)
    # ignore small rotations
    if np.abs(degree) <= 1.0:
      return img

    #################################################################################
    # Fill in the code here (Done)
    #################################################################################
    # get the max rectangular within the rotated image

    # 2D rotation matrix
    M = cv2.getRotationMatrix2D((img.shape[1]//2, img.shape[0]//2), degree,1)
    img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))

    # to find the max rectangular
    opt = 0
    # to work in grayscale
    arr = np.mean(img,axis=2)

    # loop over each row
    for y in range(arr.shape[0]):
      # find the nonzero elements with min-index and max-index
      index = np.where(arr[y,:]>0)[0]
      xmin, xmax = min(index), max(index)
      width = xmax - xmin

      # find heights
      height = min(max(np.where(arr[y:, xmin]>0)[0]), max(np.where(arr[y:, xmax]>0)[0]))
      area = height*width
      if area > opt:
        opt = area
        r, c, h, w = y, xmin, height, width
    return img[r:(r+h), c:(c+w)]

  def __repr__(self):
    return "Random Rotation [Range {:.2f} - {:.2f} Degree]".format(
            -self.degree_range, self.degree_range)

#################################################################################
# Additional helper functions
#################################################################################
class ToTensor(object):
  """Convert a ``numpy.ndarray`` image to tensor.
  Converts a numpy.ndarray (H x W x C) image in the range
  [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
  """
  def __call__(self, img):
    assert isinstance(img, np.ndarray)
    # convert image to tensor
    assert (img.ndim > 1) and (img.ndim <= 3)
    if img.ndim == 2:
      img = img[:, :, None]
      tensor_img = torch.from_numpy(np.ascontiguousarray(
        img.transpose((2, 0, 1))))
    if img.ndim == 3:
      tensor_img = torch.from_numpy(np.ascontiguousarray(
        img.transpose((2, 0, 1))))
    # backward compatibility
    if isinstance(tensor_img, torch.ByteTensor):
      return tensor_img.float().div(255.0)
    else:
      return tensor_img

class SimpleDataset(data.Dataset):
  """
  A simple dataset
  """
  def __init__(self, root_folder, file_ext, transforms=None):
    # root folder, split
    self.root_folder = root_folder
    self.transforms = transforms
    self.file_ext = file_ext

    # load all labels
    file_list = glob.glob(os.path.join(root_folder, '*.{:s}'.format(file_ext)))
    self.file_list = file_list

  def __len__(self):
    return len(self.file_list)

  def __getitem__(self, index):
    # load img and label (from file name)
    filename = self.file_list[index]
    img = load_image(filename)
    label = os.path.basename(filename)
    label = label.rstrip('.{:s}'.format(self.file_ext))
    # apply data augmentation
    if self.transforms is not None:
      img  = self.transforms(img)
    return img, label


class Optimizer:
    def __init__(self, automata):
        self.automata = automata
        self.nodes = []
        self.edges = []
        self.states = []

    def edges_from(self, node):
        for edge in self.automata.edges:
            if edge[0] == node:
                yield edge

    def move_from(self, node, state):
        for edge in self.edges_from(node):
            if edge[2] == state:
                yield edge[1]

    def possible_moves(self, nodes):
        states = []
        for node in nodes:
            for edge in self.edges_from(node):
                if edge[2] not in states and not edge[2] == "":
                    states.append(edge[2])
        return states

    def e(self, nodes=[], stop=True):
        _nodes = list(nodes)
        for node in nodes:
            for _node in self.move_from(node, ""):
                if _node not in _nodes:
                    _nodes.append(_node)
                    _nodes = self.e(_nodes)
        return _nodes

    def move(self, nodes, state):
        _nodes = []
        for node in nodes:
            for _node in self.move_from(node, state):
                if _node not in _nodes:
                    _nodes.append(_node)
        return _nodes

    def get_state_index(self, state):
        state.sort()
        i = 0
        for _state in self.states:
            if _state == state:
                return i
            i = i + 1
        return -1

    def put_state(self, state):
        state.sort()
        if self.get_state_index(state) < 0:
            self.states.append(state)
            self.nodes.append(len(self.nodes))

    def expand(self, t):
        for state in self.possible_moves(t):
            ts = self.move(t, state)
            tn = self.e(ts)
            search = self.get_state_index(tn)
            self.put_state(tn)
            origin = self.get_state_index(t)
            destiny = self.get_state_index(tn)
            self.edges.append([origin, destiny, state])
            if search < 0:
                self.expand(tn)

    def optimize(self):
        t0 = self.e([self.automata.nodes[0]])
        self.put_state(t0)
        self.expand(t0)
        return self

    def get_dict(self):
        return {"nodes": self.nodes, "edges": self.edges}

def optimize(automata):
    return Optimizer(automata).optimize()


from tkinter import *
#!I am going to scrap the making dropdown menus because they can be really complicated.
#*Instead, I can make entry boxes for everything and check the values

root = Tk()
black_list =[]

def check(a,b, c, d):

    if checker2.get() in black_list:
        print("lol")
    elif checker1.get() in my_list:
        black_list.append(checker1.get())
        print(black_list)

my_list = ['1','2','3']

checker1 = StringVar()
checker1.trace_add('write', lambda: check("a", "b", "c", checker1))
#*Trace add is not really working the best
checker2=StringVar()
checker2.trace_add('write', lambda: check("a", "b", "c", checker2))

a = Entry(root, textvariable=checker1)
a.grid(row=0, column=0)

b = Entry(root, textvariable=checker2)
b.grid(row=1, column=0)

mainloop()


from sys import stdin

input = stdin.readline

filtered_words = []
word = input().strip()
divisor_count = 0

for i in range(len(word)):
    ascii_num = ord(word[i])
    if ascii_num >= 48 and ascii_num <= 57:
        filtered_words.append(word[i])

nums = int(''.join(filtered_words))

for i in range(1, nums+1):
    if nums % i == 0:
        divisor_count += 1

print(nums)
print(divisor_count)

파이썬 알고리즘 강의/Ch3/숫자만 추출.py


import json
import random

separator_length = 50

print("Игра начинается")

def load_question():
    while True:
        user_choice = input("Выберите на каком языке хотите играть:\nРусский/Russian/1\nАнглийский/English/2\n"
                            "Для выхода из игры используйте: Выход\Стоп\Stop\Exit\n-->> ").lower()
        english_game = ["english", "английский", "2"]
        russian_game = ["russian", "русский", "1"]
        stop_game = ["stop", "стоп", "выход", "exit"]
        list_questions = []
        if user_choice in russian_game:
            with open("tasks_russian.json", encoding="utf-8") as file:
                questions_list = json.load(file)
                random.shuffle(questions_list)
                for number, keys in enumerate(questions_list):
                    list_questions.append(
                        Question(keys['questions'], keys['difficulty'], keys['answer'], number)
                    )
                return list_questions
        elif user_choice in english_game:
            with open("tasks_english.json", encoding="utf-8") as file:
                questions_list = json.load(file)
                random.shuffle(questions_list)
                for number, keys in enumerate(questions_list):
                    list_questions.append(
                        Question(keys['questions'], keys['difficulty'], keys['answer'], number)
                    )
                return list_questions
        elif user_choice in stop_game:
            quit()
        else:
            print("В меня не запрограммировали такой язык")

class Question:
    def __init__(self, question, difficulty, right_answer, number):
        self.question = question
        self.difficulty = int(difficulty)
        self.right_answer = right_answer
        self.number = number

        self.is_asked = False
        self.user_answer = None
        self.score = self.difficulty * 10

    def get_points(self):
        return self.score

    def is_correct(self):
        return self.user_answer == self.right_answer

    def build_question(self):
        return f"Вопрос {self.number + 1}:\nСложность: {self.difficulty}/5\n{self.question}"

    def build_feedback(self):
        if self.is_correct():
            return f"Ответ верный, вы заработали {self.score} баллов\n" \
                   f"{('-' * separator_length)}"
        return f"Ответ неверный, верный ответ {self.right_answer}\n" \
               f"{('-' * separator_length)}"

def statistics(questions):
    total_score = 0
    right_answer = 0

    for user_question in questions:
        if user_question.is_correct():
            total_score += user_question.score
            right_answer += 1
    print(f"отвечено правильно на {right_answer} вопросов из {len(questions)}\n"
          f"Заработано {total_score} баллов")

if __name__ == "__main__":
    QUESTIONS = load_question()

    for question in QUESTIONS:
        print(question.build_question())
        user_answer = input("-->")

        question.user_answer = user_answer.title()
        question.is_asked = True

        print(question.build_feedback())

print("Вот и всё!")
statistics(QUESTIONS)


from functools import reduce
from src.utility.file import read_lines

PAIRS = {
    '(': ')',
    '{': '}',
    '<': '>',
    '[': ']'
}
OPENING_CHARS = PAIRS.keys()

def solve_part_1(inputFile):
    input_data = read_lines(inputFile)
    error_score = {
        ')': 3,
        ']': 57,
        '}': 1197,
        '>': 25137,
    }

    total_score = 0
    for line in input_data:
        close_queue = []
        for char in line:
            if char in OPENING_CHARS:
                closer = PAIRS[char]
                # char is opening, adding closer to queue
                close_queue.append(closer)
                continue
            else:
                if close_queue[-1] == char:
                    close_queue.pop()
                else:
                    total_score += error_score[char]
                    break

    return total_score

def solve_part_2(inputFile):
    input_data = read_lines(inputFile)

    error_score = {
        ')': 1,
        ']': 2,
        '}': 3,
        '>': 4,
    }

    scores = []
    for line in input_data:
        close_queue = []
        for char in line:
            if char in OPENING_CHARS:
                closer = PAIRS[char]
                # char is opening, adding closer to queue
                close_queue.append(closer)
                continue
            else:
                # char is closer, checking if next in queue
                if close_queue[-1] == char:
                    # char is closing and next is in queue - remove from queue
                    close_queue.pop()
                else:
                    # char is closing but not expected next - corrupt line
                    close_queue = []
                    break

        line_score = reduce(lambda x, y: x * 5 + error_score[y], close_queue[::-1], 0)
        if (line_score > 0):
            scores.append(line_score)

    # return "middle" score
    return sorted(scores)[len(scores) // 2]

def solve(part=1, example=False):
    fileName = "input.txt" if not example else "example.txt"
    filePath = f"src/year_2021/day_10/{fileName}"

    if part == 1:
        return solve_part_1(filePath)
    elif part == 2:
        return solve_part_2(filePath)
    else:
        raise ValueError(f'There is no part {part}')


"""Common configure functions for snmp"""

# Python
import logging

# Unicon
from unicon.core.errors import SubCommandFailure

# Steps
from pyats.aetest.steps import Steps

# Genie
from genie.conf.base import Interface

log = logging.getLogger(__name__)

def configure_snmp(device,community_string, access_type):
    """ Configures the snmp on device
        Args:
            device ('obj'): device to use
            community_string ('str'): community_string
            access_type ('str') : type of Access
        Returns:
            None
        Raises:
            SubCommandFailure
    """
    log.debug("Configuring snmp on device {device}".format(device=device))

    try:
        device.configure("snmp-server community {community_string} {access_type}".format(
            community_string=community_string,access_type=access_type))
    except SubCommandFailure as e:
        raise SubCommandFailure("Could not configure snmp. Error:\n{error}".format(error=e))

def unconfigure_snmp(device,community_string):
    """ Unconfigures the snmp on device
        Args:
            device ('obj'): device to use
            community_string ('str'): community_string
        Returns:
            None
        Raises:
            SubCommandFailure
    """
    log.debug("Configuring snmp on device {device}".format(device=device))

    try:
        device.configure("no snmp-server community {community_string}".format(community_string=community_string))
    except SubCommandFailure as e:
        raise SubCommandFailure("Could not unconfigure snmp. Error:\n{error}".format(error=e))


#!/xde

import xde_world_manager as xwm
import xde_robot_loader  as xrl
import xde_resources     as xr
import lgsm
import time

##### AGENTS
dt = 0.01
wm = xwm.WorldManager()
wm.createAllAgents(dt, lmd_max=.5)
wm.resizeWindow("mainWindow",  640, 480, 1000, 50)

##### ROBOT
rname = "robot"
robotWorld = xrl.createWorldFromUrdfFile("resources/Robot3T.xml", rname, [0,0,0,1,0,0,0], True, 0.001, 0.001, use_collada_color=False)
wm.addWorld(robotWorld)
robot = wm.phy.s.GVM.Robot(rname)
robot.enableGravity(False)
N = robot.getJointSpaceDim()

dynModel = xrl.getDynamicModelFromWorld(robotWorld)

##### OBSTACLES
sphereWorld = xrl.createWorldFromUrdfFile("resources/sphere.xml", "sphere1", [1.,.8,.5,1,0,0,0], True, 0.001, 0.001)
wm.addWorld(sphereWorld)

##### SET INTERACTION
wm.ms.setContactLawForMaterialPair("material.metal", "material.concrete", 1, 1.5)
robot.enableContactWithRobot("sphere1", True)
#wm.contact.showContacts([(rname+"."+b,"sphere1.sphere") for b in ["link_x", "link_y", "link_z"]]) # to display contact

##### CTRL
import xde_isir_controller  as xic
ctrl = xic.ISIRController(dynModel, rname, wm.phy, wm.icsync, "qld", True)
ctrl.controller.takeIntoAccountGravity(False)
#jointConst  = ctrl.add_constraint( xic.JointLimitConstraint(ctrl.getModel(), .2) )

contConst   = ctrl.add_constraint( xic.ContactAvoidanceConstraint(ctrl.getModel(), .2, 0.2) )
contConstUpdater = ctrl.add_updater(xic.ContactAvoidanceConstraintUpdater(contConst, ctrl.getModel(), wm.phy))
contConstUpdater.add_contactAvoidance("sphere1.sphere", "robot.link_x")
contConstUpdater.add_contactAvoidance("sphere1.sphere", "robot.link_y")
contConstUpdater.add_contactAvoidance("sphere1.sphere", "robot.link_z")

#gposdes = lgsm.zeros(N)
#gposdes[1] = 1.2
#gveldes = lgsm.zeros(N)
fTask = ctrl.createFrameTask("frametask", "robot.link_z", lgsm.Displacement(), w=1., kp=5.)
fTask.setPosition(lgsm.Displacement(1.,.8,.5,1,0,0,0))

##### OBSERVERS
jpobs = ctrl.add_updater(xic.observers.JointVelocitiesObserver(ctrl.getModel()))

###### SIMULATE
ctrl.s.start()

wm.startAgents()
wm.phy.s.agent.triggerUpdate()

time.sleep(10.)

wm.stopAgents()
ctrl.s.stop()

##### RESULTS
import pylab as pl

jpos = jpobs.get_record()
pl.plot(jpos)
pl.show()


from collections import defaultdict

class Graph:
   def __init__(self,vertex):
       self.vertex=vertex
       self.graph=defaultdict(list)

   def addedges(self,u,v):
       self.graph[u].append(v)

   def util(self,u,color):
       color[u]="grey"
       for i in self.graph[u]:
          if color[i]=="white":
             if self.util(i,color):
                return True
          elif color[i]=="grey":
               return True
       color[u]="black"
       return False

   def iscyclic(self):
      color=["white"]*self.vertex
      for i in range(self.vertex):
          if color[i]=="white":
             if self.util(i,color):
                print(color)
                return True
      print(color)
      return False

if __name__=="__main__":
   graph=Graph(4)
   graph.addedges(0,2)
   graph.addedges(2,0)
   graph.addedges(0,1)
   graph.addedges(1,2)
   graph.addedges(2,3)
   print(graph.iscyclic())


import numpy as np
from . import Sudoku_Generator as SdkGen

EMPTY = 0
VALID = 1
INVALID = 2
FIXED = 3

TESTING = False
if __name__ == "__main__":
    test_dir = './test_board.txt'
else:
    test_dir = './gameplay/test_board.txt'

class SudokuSystem:

    def __init__(self):
        self.number_grid = np.zeros((9, 9), dtype=np.uint8)
        self.cell_status = np.zeros((9, 9), dtype=np.uint8)
        self.scribbles = np.zeros((9, 9), dtype='<U9')
        self.offending_cells = []
        for i in range(9):
            row = []
            for j in range(9):
                row.append([])
            self.offending_cells.append(row)

    def clear_grid(self):
        self.number_grid[:] = 0
        self.cell_status[:] = FIXED
        self.scribbles[:] = ''
        for i in range(9):
            for j in range(9):
                while self.offending_cells[i][j]:
                    self.offending_cells[i][j].pop()

    def replace_cell_number(self, row, col, val):
        prev_val = self.number_grid[row, col]
        self.number_grid[row, col] = int(val)
        self.invalid_cell_check(row, col, prev_val)
        if val == 0:
            self.change_cell_status(row, col, EMPTY)

    def clear_scribble(self, row, col):
        self.scribbles[row, col] = ''

    def toggle_scribble(self, row, col, val):
        if val in self.scribbles[row, col]:
            self.scribbles[row, col] = self.scribbles[row, col].replace(val, '')
        else:
            self.scribbles[row, col] += val

    def get_cell_number(self, row, col):
        return self.number_grid[row, col]

    def change_cell_status(self, row, col, new_status):
        if not self.cell_status[row, col] == FIXED:
            self.cell_status[row, col] = new_status

    def get_cell_status(self, row, col):
        return self.cell_status[row, col]

    def completion_check(self):
        if np.all(np.logical_or(self.cell_status == VALID, self.cell_status == FIXED)):
            self.cell_status[:] = FIXED
            return True
        else:
            return False

    def invalid_cell_check(self, row, col, prev_num):
        val_check = self.number_grid[row, col]

        if not prev_num == val_check or val_check == 0:
            while self.offending_cells[row][col]:
                r, c = self.offending_cells[row][col].pop()
                try:
                    self.offending_cells[r][c].remove((row, col))
                except ValueError:
                    print('No such cell found')
                if not self.offending_cells[r][c]:
                    self.change_cell_status(r, c, VALID)

        if not val_check == 0:

            row_check = np.where(self.number_grid[row, :] == val_check)[0]
            col_check = np.where(self.number_grid[:, col] == val_check)[0]
            local_grid_row = int(row / 3) * 3
            local_grid_col = int(col / 3) * 3
            local_grid_check_row, local_grid_check_col = np.where(
                self.number_grid[local_grid_row:local_grid_row + 3, local_grid_col:local_grid_col + 3] == val_check)

            if len(row_check) == 1 and len(col_check) == 1 and len(local_grid_check_row) == 1:
                self.cell_status[row, col] = VALID
            else:
                self.cell_status[row, col] = INVALID
                bad_cells = []
                if not len(row_check) == 1:
                    for c in row_check:
                        if not c == col:
                            bad_cells.append((row, c))
                            self.offending_cells[row][c].append((row, col))
                            self.change_cell_status(row, c, INVALID)
                if not len(col_check) == 1:
                    for r in col_check:
                        if not r == row:
                            bad_cells.append((r, col))
                            self.offending_cells[r][col].append((row, col))
                            self.change_cell_status(r, col, INVALID)
                if not len(local_grid_check_row) == 1:
                    for r, c in zip(local_grid_check_row + local_grid_row, local_grid_check_col + local_grid_col):
                        if not (c == col or r == row):
                            bad_cells.append((r, c))
                            self.offending_cells[r][c].append((row, col))
                            self.change_cell_status(r, c, INVALID)

                self.offending_cells[row][col] = bad_cells

    def generate_test_board(self, difficulty):
        self.clear_grid()
        try:
            with open(test_dir, 'r') as f:
                lines = f.readlines()

            values = []
            for line in lines:
                values.append([int(val) for val in line.strip('\n').split(',')])

            self.number_grid[:] = values
            self.cell_status[:] = FIXED
            row, col = np.where(self.number_grid == 0)

            for r, c in zip(row, col):
                self.cell_status[r, c] = EMPTY
        except Exception as e:
            print(e)
            print('Something went wrong loading the test file. Generating a random board instead')
            self.generate_random_board(difficulty)

    def generate_random_board(self, difficulty):
        self.clear_grid()
        self.number_grid[:] = SdkGen.generate_sudoku_puzzle(difficulty)
        row, col = np.where(self.number_grid == 0)

        for r, c in zip(row, col):
            self.cell_status[r, c] = EMPTY


def solution(m, n, puddles):
    answer = 0
    dp = [[0] * m for _ in range(n)]

    dp[0][0] = 1
    puddles = list(map(tuple, puddles))
    puddles = set(puddles)

    for i in range(n):
        for j in range(m):
            if i == 0:
                if j == 0:
                    continue
                elif (j+1, i+1)not in puddles:
                    dp[i][j] = dp[i][j - 1]
            elif (j+1, i+1) not in puddles:
                dp[i][j] = dp[i - 1][j]
                if j > 0:
                    dp[i][j] = (dp[i][j] + dp[i][j-1])%1000000007

    return dp[-1][-1]


#!/usr/bin/env python

import sys, unittest, time, re

sys.path.append('..')
import common.monotesting as mono
from winformsTestCase import winformsTestCase

class WinForms_ControlInspector426259Test(winformsTestCase):
    testcaseid = 426259
    command = 'ControlInspector'
    message = 'Inspect the SWF.Button control\n1. Click on the File / Windows Forms\n2. Select System.Windows.Forms.Button\n3. Click Ok\n4. Move mouse over the new button control that was created'

if __name__ == "__main__":
    mono.monotesting_main()

# vim:ts=4:expandtab:


import dask
import numpy as np
import pandas as pd
import pytest

import cudf
import dask.dataframe as dd

@pytest.mark.parametrize("by", ["a", "b"])
@pytest.mark.parametrize("nelem", [10, 100, 1000])
@pytest.mark.parametrize("nparts", [1, 2, 5, 10])
def test_sort_values(nelem, nparts, by):
    df = cudf.DataFrame()
    df["a"] = np.ascontiguousarray(np.arange(nelem)[::-1])
    df["b"] = np.arange(100, nelem + 100)
    ddf = dd.from_pandas(df, npartitions=nparts)

    with dask.config.set(scheduler="single-threaded"):
        got = ddf.sort_values(by=by).compute().to_pandas()
    expect = df.sort_values(by=by).to_pandas().reset_index(drop=True)
    pd.util.testing.assert_frame_equal(got, expect)

def test_sort_values_binned():
    np.random.seed(43)
    nelem = 100
    nparts = 5
    by = "a"
    df = cudf.DataFrame()
    df["a"] = np.random.randint(1, 5, nelem)
    ddf = dd.from_pandas(df, npartitions=nparts)

    parts = ddf.sort_values_binned(by=by).to_delayed()
    part_uniques = []
    for i, p in enumerate(parts):
        part = dask.compute(p)[0]
        part_uniques.append(set(part.a.unique()))

    # Partitions do not have intersecting keys
    for i in range(len(part_uniques)):
        for j in range(i + 1, len(part_uniques)):
            assert not (
                part_uniques[i] & part_uniques[j]
            ), "should have empty intersection"

def test_sort_binned_meta():
    df = cudf.DataFrame([("a", [0, 1, 2, 3, 4]), ("b", [5, 6, 7, 7, 8])])
    ddf = dd.from_pandas(df, npartitions=2).persist()

    ddf.sort_values_binned(by="b")


# https://programmers.co.kr/learn/courses/30/lessons/12940

def solution(n, m):
    answer = [0, n * m]
    while n != 0:
        r = m % n
        m = n
        n = r
    answer[0] = m
    answer[1] //= m
    return answer

최대공약수와 최소공배수.py


#! /usr/bin/env python3

# This is a stripped down version used as a backend for running a modified      ###
# regrtest from the host                                                        ###
                                                                                ###
"""
Script to run Python regression tests.

Run this script with -h or --help for documentation.
"""

import importlib
import io
import os
import sys
import tempfile
import time
import traceback
import unittest

# Some times __path__ and __file__ are not absolute (e.g. while running from
# Lib/) and, if we change the CWD to run the tests in a temporary dir, some
# imports might fail.  This affects only the modules imported before os.chdir().
# These modules are searched first in sys.path[0] (so '' -- the CWD) and if
# they are found in the CWD their __file__ and __path__ will be relative (this
# happens before the chdir).  All the modules imported after the chdir, are
# not found in the CWD, and since the other paths in sys.path[1:] are absolute
# (site.py absolutize them), the __file__ and __path__ will be absolute too.
# Therefore it is necessary to absolutize manually the __file__ and __path__ of
# the packages to prevent later imports to fail when the CWD is different.
for module in sys.modules.values():
    if hasattr(module, '__path__'):
        module.__path__ = [os.path.abspath(path) for path in module.__path__]
    if hasattr(module, '__file__'):
        module.__file__ = os.path.abspath(module.__file__)

# Test result constants.
PASSED = 1
FAILED = 0
ENV_CHANGED = -1
SKIPPED = -2
RESOURCE_DENIED = -3
INTERRUPTED = -4
CHILD_ERROR = -5   # error in a child process

from test import support

RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network',
                  'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui')

TEMPDIR = tempfile.gettempdir()                                                 ###
TEMPDIR = os.path.abspath(TEMPDIR)

def findtests(testdir=None, stdtests=None, nottests=None):                      ### All parameters are filled by the host
    """Return a list of all applicable test modules."""
    testdir = findtestdir(testdir)
    names = os.listdir(testdir)
    tests = []
    others = set(stdtests) | nottests
    for name in names:
        mod, ext = os.path.splitext(name)
        if mod[:5] == "test_" and ext in (".mpy", ".py", "") and mod not in others:  ###
            tests.append(mod)
    return stdtests + sorted(tests)

def runtest(test, verbose, quiet,
            huntrleaks=False, use_resources=None,
            output_on_failure=False, failfast=False, match_tests=None,
            timeout=None):
    """Run a single test.

    test -- the name of the test
    verbose -- if true, print more messages
    quiet -- if true, don't print 'skipped' messages (probably redundant)
    huntrleaks -- run multiple times to test for leaks; requires a debug
                  build; a triple corresponding to -R's three arguments
    use_resources -- list of extra resources to use
    output_on_failure -- if true, display test output on failure
    timeout -- dump the traceback and exit if a test takes more than
               timeout seconds
    failfast, match_tests -- See regrtest command-line flags for these.

    Returns the tuple result, test_time, where result is one of the constants:
        INTERRUPTED      KeyboardInterrupt when run under -j
        RESOURCE_DENIED  test skipped because resource denied
        SKIPPED          test skipped for some other reason
        ENV_CHANGED      test failed because it changed the execution environment
        FAILED           test failed
        PASSED           test passed
    """

    if use_resources is not None:
        support.use_resources = use_resources
    use_timeout = (timeout is not None)
    if use_timeout:
        faulthandler.dump_traceback_later(timeout, exit=True)
    try:
        support.match_tests = match_tests
        if failfast:
            support.failfast = True
        if output_on_failure:
            raise NotImplementedError("stdout can't be redirected")             ###
        else:
            support.verbose = verbose  # Tell tests to be moderately quiet
            result = runtest_inner(test, verbose, quiet, huntrleaks,
                                   display_failure=not verbose)
        return result
    finally:
        cleanup_test_droppings(test, verbose)

# Unit tests are supposed to leave the execution environment unchanged
# once they complete.  But sometimes tests have bugs, especially when
# tests fail, and the changes to environment go on to mess up other
# tests.  This can cause issues with buildbot stability, since tests
# are run in random order and so problems may appear to come and go.
# There are a few things we can save and restore to mitigate this, and
# the following context manager handles this task.

class saved_test_environment:
    """Save bits of the test environment and restore them at block exit.

        with saved_test_environment(testname, verbose, quiet):
            #stuff

    Unless quiet is True, a warning is printed to stderr if any of
    the saved items was changed by the test.  The attribute 'changed'
    is initially False, but is set to True if a change is detected.

    If verbose is more than 1, the before and after state of changed
    items is also printed.
    """

    changed = False

    def __init__(self, testname, verbose=0, quiet=False):
        self.testname = testname
        self.verbose = verbose
        self.quiet = quiet

    # To add things to save and restore, add a name XXX to the resources list
    # and add corresponding get_XXX/restore_XXX functions.  get_XXX should
    # return the value to be saved and compared against a second call to the
    # get function when test execution completes.  restore_XXX should accept
    # the saved value and restore the resource using it.  It will be called if
    # and only if a change in the value is detected.
    #
    # Note: XXX will have any '.' replaced with '_' characters when determining
    # the corresponding method names.

    resources = ('cwd',                                                         ###
                 'os.environ',                                                  ###
                 'files',                                                       ###
                )                                                               ###

    def get_cwd(self):
        return os.getcwd()
    def restore_cwd(self, saved_cwd):
        os.chdir(saved_cwd)

    def get_os_environ(self):
        return id(os.environ), os.environ, dict(os.environ)
    def restore_os_environ(self, saved_environ):
        os.environ = saved_environ[1]
        os.environ.clear()
        os.environ.update(saved_environ[2])

    def get_files(self):
        return sorted(fn + ('/' if os.path.isdir(fn) else '')
                      for fn in os.listdir())
    def restore_files(self, saved_value):
        fn = support.TESTFN
        if fn not in saved_value and (fn + '/') not in saved_value:
            if os.path.isfile(fn):
                support.unlink(fn)
            elif os.path.isdir(fn):
                support.rmtree(fn)

    def resource_info(self):
        for name in self.resources:
            method_suffix = name.replace('.', '_')
            get_name = 'get_' + method_suffix
            restore_name = 'restore_' + method_suffix
            yield name, getattr(self, get_name), getattr(self, restore_name)

    def __enter__(self):
        self.saved_values = dict((name, get()) for name, get, restore
                                                   in self.resource_info())
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        saved_values = self.saved_values
        del self.saved_values
        for name, get, restore in self.resource_info():
            current = get()
            original = saved_values.pop(name)
            # Check for changes to the resource's value
            if current != original:
                self.changed = True
                restore(original)
                if not self.quiet:
                    print("Warning -- {} was modified by {}".format(
                                                 name, self.testname),
                                                 file=sys.stderr)
                    if self.verbose > 1:
                        print("  Before: {}\n  After:  {} ".format(
                                                  original, current),
                                                  file=sys.stderr)
        return False

def runtest_inner(test, verbose, quiet,
                  huntrleaks=False, display_failure=True):
    support.unload(test)

    test_time = 0.0
    try:
        if test.startswith('test.'):
            abstest = test
        else:
            # Always import it from the test package
            abstest = 'test.' + test
        with saved_test_environment(test, verbose, quiet) as environment:
            import gc                                                           ###
            if not quiet:                                                       ###
                before = gc.mem_free()                                          ###
            start_time = time.time()
            the_module = importlib.import_module(abstest)
            if not quiet:                                                       ###
                after = gc.mem_free()                                           ###
                print('Loading module mem_free: before=%.1fkB, after=%.1fkB' % (before / 1024, after / 1024))  ###
            # If the test has a test_main, that will run the appropriate
            # tests.  If not, use normal unittest test loading.
            test_runner = getattr(the_module, "test_main", None)
            if test_runner is None:
                def test_runner():
                    loader = unittest.TestLoader()
                    tests = loader.loadTestsFromModule(the_module)
                    support.run_unittest(tests)
            test_runner()
            test_time = time.time() - start_time
    except support.ResourceDenied as msg:
        if not quiet:
            print(test, "skipped --", msg)
        return RESOURCE_DENIED, test_time
    except unittest.SkipTest as msg:
        if not quiet:
            print(test, "skipped --", msg)
        return SKIPPED, test_time
    except KeyboardInterrupt:
        raise
    except support.TestFailed as msg:
        if display_failure:
            print("test", test, "failed --", msg, file=sys.stderr)
        else:
            print("test", test, "failed", file=sys.stderr)
        return FAILED, test_time
    except MemoryError as msg:                                                  ###
        if not quiet:                                                           ###
            print(test, "Out of memory --", msg, file=sys.stderr)               ###
            return FAILED, test_time                                            ###
        else:                                                                   ###
            raise                                                               ### Let host print message since stdout is not displayed
    except BaseException as msg:                                                ### Why doesn't traceback.format_exc() work?
        print("test", test, "crashed --", msg, file=sys.stderr)
        return FAILED, test_time
    else:
        if environment.changed:
            return ENV_CHANGED, test_time
        return PASSED, test_time

def cleanup_test_droppings(testname, verbose):
    import shutil
    import stat
    import gc

    # First kill any dangling references to open files etc.
    # This can also issue some ResourceWarnings which would otherwise get
    # triggered during the following test run, and possibly produce failures.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print("%r left behind %s %r" % (testname, kind, name))
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception as msg:
            print(("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)

def findtestdir(path=None):
    return path or os.path.dirname(__file__) or os.curdir