# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        ptr = new = None
        current = head

        while current is not None:
            ptr = current
            current = current.next
            ptr.next = new
            new = ptr

        head = new

        return head


from logger import decorator
import os

nested_list2 = [
    [['a'], 'b', 'c'],
    ['d', 'e', 'f', 'h', False],
    [[1, [2]], None],
]
path = os.path.abspath('logs.txt')

@decorator(path)
def hard_generator(main_list):
    for lists in main_list:
        if isinstance(lists, list):
            for lis in hard_generator(lists):
                yield lis
        else:
            yield lists

if __name__ == '__main__':
    for item in hard_generator(nested_list2):
        print(item)


#!/usr/bin/env python
import sys
import re

# Import dummy data
import intentmap
import objectlist
import identifiers
import determinants

# Dictionary generation and management
class DictionaryHandler:
	def __init__(self):
		self.intents = intentmap.intents
		self.objects = objectlist.objects
		self.identifiers = identifiers.identifiers
		self.determinants = determinants.determinants
		self.corpus = []

	def generateCorpus(self):
		for (intents,synonyms) in self.intents.iteritems():
			for s in synonyms:
				for o in self.objects:
					self.corpus.append(s + " " + o)

	# Checks a whole sentence for first value in a
	# list of values for each key in a dictionary,
	# returns a tuple of key and the rest of the string
	def checkDictionary(self,string,dictionary):
		strings = string.lower().split()
		strings.reverse()
		returnStrings = []
		for s in strings:
			for (key,values) in dictionary.iteritems():
				for v in values:
					if (s == v):
						return key," ".join(returnStrings)
			returnStrings.insert(0,s)
		return "none", " ".join(returnStrings)

	# Checks the first word of string against a list
	# Returns a tuple of the word and the rest of the
	# string if found, otherwise, the first element
	# of the tuple is "None"
	def checkList(self,string,list):
		strings = string.lower().split()
		for l in list:
			if (strings[0] == l):
				strings.pop(0)
				return l, " ".join(strings)
		return "none"," ".join(strings)

	# Calls word parsing functions to classify each word
	def parseSentence(self,string):
		intent	= self.checkDictionary(string,self.intents)
		id		= self.checkList(intent[1],self.identifiers)
		det		= self.checkDictionary(id[1],self.determinants)
		object	= self.checkList(det[1],self.objects)
		return intent[0],id[0],det[0],object[0]

	def makeMessage(self,string):
		s = self.parseSentence(string)
		i = "Intent		: " + s[0] + "\n"
		o = "Object		: " + s[3] + "\n"
		r = "Recipient	: " + s[1] + "\n"
		c = "Count		: " + s[2] + "\n"
		return i + o + r + c

# Main function
if __name__ == "__main__":
	s = DictionaryHandler()
	print(s.makeMessage("I WOULD LIKE YOU TO PLEASE GO AND GET ME A SODA"))
	print(s.makeMessage("CAN YOU GET DAVID A SODA PLEASE"))
	print(s.makeMessage("IS THERE ANY CHANCE THAT YOU CAN FIND PAUL SOME PEPSI"))

# Notes for phrase parsing
"""
The structure of a sentence as we are attempting to understand it will be as such:

Ext			= Extraneous
Name		= A person's name
D			= Determinant
ID			= Identifier
V			= Verb
N			= Noun
P			= Preposition
NP			= Noun phrase = (D)(N)
PP			= Prepositional phrase = (P)(NP)
VP			= Verb phrase = (Ext)(V)

Sentence	= (VP)(ID?)(NP?)(PP?)

The justification is that all robot commands are essentially simple imperatives, so all words before a VP should be understood as extraneous.

Example 1:

	"GO GET ME A COKE"

	VP = GO GET
	ID = ME
	NP = A COKE

	->

	V  = GET
	ID = ME
	D  = A
	N  = COKE

Verbs are mapped to Intents, nouns are mapped to objects, identifiers are mapped to names, and prepositions are mapped to object metadata. In the above example, we can think of the mapping structure as such:

	GET ME A COKE -> intent(subject,object,metadata) -> retrieve(me,coke,null)

Example 2:

	"GO GET DAVID A COKE FROM THE FRIDGE"

	VP = GO GET
	ID = DAVID
	NP = A COKE
	PP = FROM THE FRIDGE

	->

	V  = GET
	ID = DAVID
	D  = A
	N  = COKE
	P  = FROM
	D  = THE
	N  = FRIDGE

	-> retrieve(david,coke,location:fridge)

Note: this is all conceptual at the moment, much thanks to David Marino for helping out with the linguistic analysis. Also, no sentence will include more than one prepositional phrase at the moment.

"""


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

class SA():
    def __init__(self,L,k,first_temperature,last_temperature,city_num,distance_matrix):
        self.L=L
        self.k=k
        self.first_temperature=first_temperature
        self.last_temperature=last_temperature
        self.current_temperature=self.first_temperature
        self.fitness=1e4
        self.city_num=city_num
        self.individual=np.random.permutation(self.city_num)
        self.distance_matrix=distance_matrix
        self.history_fitness=[]

    def fitness_calculation(self):
        temp=0
        for i in range(self.city_num-1):
            start=self.individual[i]
            end=self.individual[i+1]
            temp+=self.distance_matrix[start,end]
        start=self.individual[0]
        end=self.individual[-1]
        temp+=self.distance_matrix[end,start]
        self.fitness=temp

    def temp_fitness_calculation(self,individual_temp):
        temp=0
        for i in range(self.city_num-1):
            start=individual_temp[i]
            end=individual_temp[i+1]
            temp+=self.distance_matrix[start,end]
        start=individual_temp[0]
        end=individual_temp[-1]
        temp+=self.distance_matrix[end,start]
        return temp

    def isothermal_process(self):
        for i in range(self.L):
            temp1=np.random.randint(self.city_num)
            temp2=np.random.randint(self.city_num)
            start=min(temp1,temp2)
            end=max(temp1,temp2)
            #print('start',start)
            #print('end',end)
            individual_temp=self.individual.copy()
            #print('individual_temp',individual_temp)
            #print('individual_temp[end-1:start-1:-1]',individual_temp[end-1:start-1:-1])
            #print('individual_temp[start:end]',individual_temp[start:end])
            if end!=0:#避免0为末端索引引起的倒序空集
                if start!=0:#避免0为起始索引使倒序产生空集
                    individual_temp[start:end]=individual_temp[end-1:start-1:-1]
                else:
                    individual_temp[start:end] = individual_temp[end - 1::-1]

            temp_fitness=self.temp_fitness_calculation(individual_temp)
            self.fitness_calculation()
            if self.fitness>temp_fitness:
                self.individual=individual_temp
            else:
                if (np.e)**(-(temp_fitness-self.fitness)/self.current_temperature)>np.random.rand():
                    self.individual=individual_temp

    def temperature_fall_process(self):
        while self.current_temperature>self.last_temperature:
            self.isothermal_process()
            self.current_temperature*=self.k
            self.history_fitness.append(self.fitness)

data=pd.read_excel('data_generation.xlsx')
x=data['x']
y=data['y']

distance_matrix=np.zeros((len(x),len(y)))
for i in range(len(x)):
    for j in range(len(y)):
        distance_matrix[i, j] = ((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2) ** 0.5

test=SA(L=1000,k=0.99,first_temperature=100,last_temperature=0.1,city_num=30,distance_matrix=distance_matrix)
test.temperature_fall_process()

plt.figure()
for i in range(len(test.individual)-1):
    start=test.individual[i]
    end=test.individual[i+1]
    plt.scatter([x[start],x[end]],[y[start],y[end]])
    plt.plot([x[start],x[end]],[y[start],y[end]])
start=test.individual[0];end=test.individual[-1]
plt.scatter([x[start],x[end]],[y[start],y[end]])
plt.plot([x[start],x[end]],[y[start],y[end]])
plt.show()

plt.figure()
plt.plot(test.history_fitness)
plt.show()

print('最短路径',test.individual)
print('最短距离',test.fitness)


#!/usr/bin/env python
import numpy
import scipy.stats
import functions.regression as regression

'''
Compute the correlation coefficient for the x-values in x_values and y-values
in y_values.
'''

def run(x_values, y_values, y_errors):
    '''
    -----------
    Parameters:
    -----------
    x_values: (numpy.ndarray) a 1-dimensional numpy array of x-values
    y_values: (numpy.ndarray) a 1-dimensional numpy array of y-values, where
        for each i=1,2,...,n x_values[i] is paired with y_values[i].
    y_errors: (numpy.ndarray or None) the uncertainties (standard deviation) associated with each value
    -----------------
    Function
    -----------------
    Compute the pearson correlation coefficient and print to stdout.
    '''
    m, sigma_m, b, sigma_b, r, p = regression.linear(x_values, y_values, y_errors)

    msg = '''
--------------------------------------------------------------------------------
Calculation of correlation coefficient for specified x-values and specified
y-values
--------------------------------------------------------------------------------
pearson correlation coefficient (r): {:.04e}'''.format(r)
    print(msg)
    return


#!/usr/bin/python3.4
# -*- coding=utf-8 -*-

from ftplib import FTP
import multiprocessing

def anonymous_ftp(hostname,timeout=1):
	try:
		connection = FTP(hostname, timeout=timeout)
		connection.login('anonymous', '1@2.net')
		connection.quit()
		return [1, hostname]

	except Exception as e:
		return [0, hostname]

def anonymous_scan(network):
	import ipaddress
	net = ipaddress.ip_network(network)
	pool=multiprocessing.Pool(processes=100)
	result = []
	for ip in net:
		result.append(pool.apply_async(anonymous_ftp, (str(ip),)))
	#pool.close()
	#pool.join()
	for res in result:
		if res.get()[0] == 1:
			print(res.get()[1] + '为匿名FTP')

if __name__ == '__main__':
	anonymous_scan('202.100.1.0/24')


import pandas as pd
from argparse import Namespace
from hamplicons.main import main

class TestClass:
	def test_version(self):
		"""
		Purpose it to remind myself to update version
		"""
		with open('pyproject.toml') as f:
			for line in f.read():
				if line.startswith("version"):
					assert line.endswith("4.2.0")
					break

	def test_defaults(self, tmp_path):
		"""
		test basic functionality

		:param tmp_path:
		:return:
		"""
		args = Namespace(
			t=8, log_level='INFO', targets_fasta='tests/data/targets.fa', data_directory='tests/data',
			data_directory_recursive=False, skip_merging=False, deactivate_relaxed_matching=False, hamming_distance=4,
			o=tmp_path, output_formats='xlsx', convert_to_wells=False, plate_layout=[8, 12]
		)
		main(args)
		files = set([x.name for x in tmp_path.glob("*")])
		assert {"hamp_out.log", "hamp_out.merged", "hamp_out.xlsx"} == files
		assert pd.read_excel(tmp_path / "hamp_out.xlsx").equals(pd.read_excel("tests/output/hamp_out.xlsx"))


import json
import os
import sys
from argparse import Namespace

import pytest

# need this so the raptor unit tests can find raptor/raptor classes
here = os.path.abspath(os.path.dirname(__file__))
raptor_dir = os.path.join(os.path.dirname(here), "raptor")
sys.path.insert(0, raptor_dir)

from browsertime import Browsertime
from perftest import Perftest
from webextension import WebExtensionFirefox

@pytest.fixture
def options(request):
    opts = {
        "app": "firefox",
        "binary": "path/to/dummy/browser",
        "browsertime_visualmetrics": False,
        "extra_prefs": {},
    }

    if hasattr(request.module, "OPTIONS"):
        opts.update(request.module.OPTIONS)
    return opts

@pytest.fixture
def browsertime_options(options):
    options["browsertime_node"] = "browsertime_node"
    options["browsertime_browsertimejs"] = "browsertime_browsertimejs"
    options["browsertime_ffmpeg"] = "browsertime_ffmpeg"
    options["browsertime_geckodriver"] = "browsertime_geckodriver"
    options["browsertime_chromedriver"] = "browsertime_chromedriver"
    options["browsertime_video"] = "browsertime_video"
    options["browsertime_visualmetrics"] = "browsertime_visualmetrics"
    options["browsertime_no_ffwindowrecorder"] = "browsertime_no_ffwindowrecorder"
    return options

@pytest.fixture
def raptor(options):
    return WebExtensionFirefox(**options)

@pytest.fixture
def mock_test():
    return {
        "name": "raptor-firefox-tp6",
        "test_url": "/dummy/url",
        "secondary_url": "/dummy/url-2",
    }

@pytest.fixture(scope="session")
def get_prefs():
    def _inner(browser):
        import raptor

        prefs_dir = os.path.join(raptor.__file__, "preferences")
        with open(os.path.join(prefs_dir, "{}.json".format(browser)), "r") as fh:
            return json.load(fh)

@pytest.fixture(scope="session")
def filedir():
    return os.path.join(here, "files")

@pytest.fixture
def get_binary():
    from moztest.selftest import fixtures

    def inner(app):
        if app != "firefox":
            pytest.xfail(reason="{} support not implemented".format(app))

        binary = fixtures.binary()
        if not binary:
            pytest.skip("could not find a {} binary".format(app))
        return binary

    return inner

@pytest.fixture
def create_args():
    args = Namespace(
        app="firefox",
        test="browsertime-tp6-unittest",
        binary="path/to/binary",
        gecko_profile=False,
        extra_profiler_run=False,
        debug_mode=False,
        page_cycles=None,
        page_timeout=None,
        test_url_params=None,
        host=None,
        run_local=True,
        browsertime=True,
        cold=False,
        live_sites=False,
        enable_marionette_trace=False,
        collect_perfstats=False,
        chimera=False,
    )

    def inner(**kwargs):
        for next_arg in kwargs:
            print(next_arg)
            print(kwargs[next_arg])
            setattr(args, next_arg, kwargs[next_arg])
        return args

    return inner

@pytest.fixture(scope="module")
def ConcretePerftest():
    class PerftestImplementation(Perftest):
        def check_for_crashes(self):
            super(PerftestImplementation, self).check_for_crashes()

        def clean_up(self):
            super(PerftestImplementation, self).clean_up()

        def run_test(self, test, timeout):
            super(PerftestImplementation, self).run_test(test, timeout)

        def run_test_setup(self, test):
            super(PerftestImplementation, self).run_test_setup(test)

        def run_test_teardown(self, test):
            super(PerftestImplementation, self).run_test_teardown(test)

        def set_browser_test_prefs(self):
            super(PerftestImplementation, self).set_browser_test_prefs()

        def get_browser_meta(self):
            return (), ()

        def setup_chrome_args(self, test):
            super(PerftestImplementation, self).setup_chrome_args(test)

    return PerftestImplementation

@pytest.fixture(scope="module")
def ConcreteBrowsertime():
    class BrowsertimeImplementation(Browsertime):
        @property
        def browsertime_args(self):
            return []

        def get_browser_meta(self):
            return (), ()

        def setup_chrome_args(self, test):
            super(BrowsertimeImplementation, self).setup_chrome_args(test)

    return BrowsertimeImplementation


from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from django.utils.translation import ugettext as _

from sendfile import sendfile

from shareholder.models import Shareholder, OptionPlan
from utils.formatters import human_readable_segments

@login_required
def positions(request):
    template = loader.get_template('positions.html')
    context = RequestContext(request, {})
    return HttpResponse(template.render(context))

@login_required
def options(request):
    template = loader.get_template('options.html')
    context = RequestContext(request, {})
    return HttpResponse(template.render(context))

@login_required
def log(request):
    template = loader.get_template('log.html')
    context = RequestContext(request, {})
    return HttpResponse(template.render(context))

@login_required
def shareholder(request, shareholder_id):
    template = loader.get_template('shareholder.html')
    shareholder = get_object_or_404(Shareholder, id=int(shareholder_id))
    securities = shareholder.company.security_set.all()

    # hack security props for shareholder spec data
    for sec in securities:
        if sec.track_numbers:
            if shareholder.current_segments(sec):
                sec.segments = human_readable_segments(
                    shareholder.current_segments(sec))
        sec.count = shareholder.share_count(security=sec) or 0
    context = RequestContext(request, {
                             'shareholder': shareholder,
                             'securities': securities})
    return HttpResponse(template.render(context))

@login_required
def optionsplan(request, optionsplan_id):
    template = loader.get_template('optionsplan.html')
    optionsplan = get_object_or_404(OptionPlan, id=int(optionsplan_id))
    context = RequestContext(request, {"optionplan": optionsplan})
    return HttpResponse(template.render(context))

@login_required
def optionsplan_download_pdf(request, optionsplan_id):
    optionplan = OptionPlan.objects.get(id=optionsplan_id)
    if optionplan.company.operator_set.filter(user=request.user).exists():
        return sendfile(request, optionplan.pdf_file.path)
    else:
        return HttpResponseForbidden(_("Permission denied"))

@login_required
def optionsplan_download_img(request, optionsplan_id):
    optionplan = OptionPlan.objects.get(id=optionsplan_id)
    if optionplan.company.operator_set.filter(user=request.user).exists():
        return sendfile(request, optionplan.pdf_file_preview_path())
    else:
        return HttpResponseForbidden(_("Permission denied"))


# -*- coding: utf-8 -*-
import os
import re

from django import forms

from .. import tasks
from ..models import CheckTask
from util.loggers import logger

from util.time_processing import plus_seconds

class XrayTaskForm(forms.ModelForm):
    """
    新增扫描任务 表单
    """

    class Meta:
        model = CheckTask
        # exclude = ['task_state', 'task_results', 'task_report', 'createtime', 'creator']
        fields = ('check_name', 'xray_address', 'scan_type', 'tag')
        # fields = '__all__'

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(XrayTaskForm, self).__init__(*args, **kwargs)

    def clean_scan_type(self, ):
        """
        验证类型
        """
        scan_type = self.cleaned_data.get("scan_type")
        SCAN_TYPE_CHOICE = ['webscan', 'servicescan', 'check', 'other']  # 必须和 model SCAN_TYPE_CHOICE一直

        if scan_type not in SCAN_TYPE_CHOICE:
            logger.error('新增扫描任务失败！扫描类型不支持！')
            raise forms.ValidationError("新增扫描任务失败！扫描类型不支持！")
        else:
            return scan_type

    def save(self, commit=True):
        instance = forms.ModelForm.save(self, False)

        if commit:
            instance.creator = self.request.user
            instance.updater = self.request.user
            instance.task_state = 'runing'  # 上传时修改任务状态
            instance.task_start_time = plus_seconds(5)  # 当前时间+5秒 大约任务开始时间
            url = self.cleaned_data.get("xray_address")
            types = self.cleaned_data.get("scan_type")
            instance.task_id = tasks.xray_shell_task.delay(url, types)  # 执行异步任务
            instance.save()
            logger.info(f'新增扫描任务成功！{instance.check_name}')

        return instance


from django.conf.urls import url, include
from django.contrib.auth.decorators import login_required
from django.contrib.sitemaps.views import index, sitemap
from django.views.decorators.cache import never_cache

from ckeditor_uploader import views as ckedit_views

from regluit.admin import site
from regluit.core.sitemaps import WorkSitemap, PublisherSitemap
from regluit.frontend.views import static_redirect_view

sitemaps = {
    'works': WorkSitemap,
    'publishers': PublisherSitemap,
}

urlpatterns = [
    url(r'^api/', include('regluit.api.urls')),
    url(r'', include('regluit.frontend.urls')),
    url(r'', include('regluit.payment.urls')),
    url(r'', include('regluit.libraryauth.urls')),
    url(r'', include('regluit.marc.urls')),
    url(r'^bisac/', include('regluit.bisac.urls')),
    url(r'^selectable/', include('selectable.urls')),
    url(r'^admin/', site.urls),
    url(r'^comments/', include('django_comments.urls')),
    url(r"^notification/", include('notification.urls')),
    url(r'^ckeditor/upload/', login_required(ckedit_views.upload), name='ckeditor_upload'),
    url(
        r'^ckeditor/browse/',
        never_cache(login_required(ckedit_views.browse)),
        name='ckeditor_browse'
    ),
    # questionnaire urls
    url(r'^survey/', include('questionnaire.urls')),
    # sitemaps
    url(r'^sitemap\.xml$', index, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'),
    url(r'^sitemap-(?P<section>.+)\.xml$', sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'),
    url(r'^\.well-known/acme-challenge/(?P<file_name>[\w\-_]*)',
        static_redirect_view, {'dir': '.well-known/acme-challenge'}),
]


import pygame, random, sys, os
from pygame.locals import *
from defs.defaults import *

# Initialize
pygame.init()
pygame.display.set_caption('The Organism Trail')
screen = pygame.display.set_mode((800,600))
FPS = 30
clock = pygame.time.Clock()
IMG_DIR = os.path.join('data', 'img')

# Prepare the splash and background images for Pygame.
splash = pygame.image.load(os.path.join(IMG_DIR, 'splash.png'))
splash = splash.convert()
background = pygame.image.load(os.path.join(IMG_DIR, 'background.png'))
background = background.convert()

# The main code is something of a mess currently.  This file handles all of
# the game's GUI, menu logic, etc.  All the cellular simulation occurs in
# the files in the folder 'defs'.

# Essentially, there is a Game class to keep track of where in the game you are.
# The Menu and MenuItem classes are simply used to display text and
# filter out mouse clicks to pass along to the Game class for processing.

class Game():
    def __init__(self):
        self.toDraw = []
        self.playerOps = []
        self.org = Organism('', {}, {})
        self.eco = None
        self.time = 0
        self.play = False

    # If a menu has a button clicked, then it passes that information here.
    # From here we can redraw stuff, pause simulation, etc.
    def handleButton(self, menu, button):
        # If the button is in the genes menu, then add the gene to playerOps
        # and update the player genes menue to be drawn.
        if menu.name == 'Genes':
            self.playerOps.append(operons[button.text])
            self.toDraw[1] = Menu("PGenes", [op.name for op in self.playerOps], center=(background.get_width()/4, None), fontSize=20, fontSpace=1)

        # If in the main menu, either quit or load the next menu.
        elif menu.name == 'Main':
            if button.text == 'Quit':
                sys.exit()
            elif button.text == 'Start':
                menu.deactivate()
                self.toDraw = [addGenesMenu, playerGenesMenu, goButtonMenu, addGenesTitle]

        # Clicking on a button in the player genes menu removes the operon
        # from the list, and updates that list for when it is redrawn.
        elif menu.name == 'PGenes':
            self.playerOps.remove(operons[button.text])
            self.toDraw[1] = Menu("PGenes", [op.name for op in self.playerOps], center=(background.get_width()/4, None), fontSize=20, fontSpace=1)

        # If the player clicks Go, then we need to create their organism,
        # initialize an environment and ecosystem, then load the menus for
        # the growth screen.
        elif menu.name == 'Go':
            self.playerOps = hiddenGenes + self.playerOps
            genome = Genome(self.playerOps)
            self.org = Organism('Player Organism', genome, copy.deepcopy(CELLR))
            env = Environment('Game Environment', 1, ENVR)
            self.eco = Ecosystem([self.org], env)
            self.toDraw = [playButtonMenu, pauseButtonMenu, timeMenu, countMenu, quitButtonMenu]

        # These should be self explanatory.
        elif menu.name == 'Play':
            self.play = True

        elif menu.name == 'Pause':
            self.play = False

        elif menu.name == 'Quit':
            sys.exit()

class MenuItem(pygame.font.Font):
    def __init__(self, text, position, fontSize=36, antialias=1, color=(255,255,255), background=None):
        pygame.font.Font.__init__(self, None, fontSize)
        self.text = text
        if background == None:
            self.textSurface = self.render(self.text, antialias, color)
        else:
            self.textSurface = self.render(self.text, antialias, color, background)
        self.position = self.textSurface.get_rect(centerx=position[0], centery=position[1])

    def get_pos(self):
        return self.position

    def get_text(self):
        return self.text

    def get_surface(self):
        return self.textSurface

    def draw(self, screen):
        screen.blit(self.get_surface(), self.get_pos())

    def handleEvent(self, event, game):
        self.text = self.text

class Menu():
    def __init__(self, name, items, center=(None, None), fontSize=36, fontSpace=4):
        self.name = name
        screen = pygame.display.get_surface()
        self.area = screen.get_rect()
        self.background = background
        self.active=False
        font = pygame.font.Font(None, fontSize)
        menuHeight = (fontSize+fontSpace)*len(items)
        if center[0]:
            centerX = center[0]
        else:
            centerX = self.background.get_width()/2
        if center[1]:
            startY = center[1]
        else:
            startY = self.background.get_height()/2 - menuHeight/2

        self.items = list()
        for item in items:
            centerY = startY + fontSize + fontSpace
            newItem = MenuItem(item, (centerX, centerY), fontSize=fontSize)
            self.items.append(newItem)
            startY = startY + fontSize + fontSpace

    def draw(self, screen):
        self.active = True
        for item in self.items:
            item.draw(screen)

    def isActive(self):
        return self.active

    def activate(self,):
        self.active = True

    def deactivate(self):
        self.active = False

    def handleEvent(self, event, game):
        if event.type == MOUSEBUTTONDOWN and self.isActive():
            currentItem = 0
            eventX = event.pos[0]
            eventY = event.pos[1]
            for item in self.items:
                textPos = item.get_pos()
                if eventX > textPos.left and eventX < textPos.right and eventY > textPos.top and eventY < textPos.bottom:
                    game.handleButton(self, item)

# Initialize a game.
game = Game()

# Draw the splash screen and title text.  Then wait 3 seconds and move on.
screen.blit(splash, (0,0))
splashMenu = Menu("Splash", ("The Organism Trail",), fontSize=80)
splashMenu.draw(screen)
pygame.display.flip()
pygame.time.wait(3000)
screen.blit(background, (0,0))

# Define all of the menus and items we will need to use.
mainMenu = Menu("Main", ("Start", "Quit"))
addGenesList = [op.name for op in displayedGenes]
addGenesMenu = Menu("Genes", addGenesList, center=(background.get_width()*3/4, None), fontSize=20, fontSpace=1)
playerGenesMenu = Menu("PGenes", [op.name for op in game.playerOps], center=(background.get_width()/4, None), fontSize=20, fontSpace=1)
goButtonMenu = Menu("Go", ('Go!',), center=(background.get_width()/2, background.get_height()*8/10))
addGenesTitle = MenuItem("Click operons on right to add, click operons on left to remove", (background.get_width()/2, background.get_height()/10))
playButtonMenu = Menu("Play", ('Play',), center=(background.get_width()/2, background.get_height()/16))
pauseButtonMenu = Menu("Pause", ('Pause',), center=(background.get_width()*1/4, background.get_height()/16))
quitButtonMenu= Menu("Quit", ('Quit',), center=(background.get_width()*3/4, background.get_height()/16))
timeMenu = Menu('Time', ('Time (minutes):', str(game.time)), center=(background.get_width()*1/4, background.get_height()*8/10))
countMenu = Menu('Cells', ('Number of Cells:', str(game.org.count)), center=(background.get_width()*3/4, background.get_height()*8/10))

# Queue the main menu to be drawn.
game.toDraw = [mainMenu]

# This is the main game loop.
while True:
    # Limits the FPS of the game.
    clock.tick(FPS)

    # Load a blank background.
    screen.blit(background, (0,0))

    # Draw everything in the game's drawing queue.
    for i in game.toDraw:
        i.draw(screen)

    # Update the display.
    pygame.display.flip()

    # game.play determines whether or not to execute the cellular simulation logic.
    if game.play:
        # Run an ecosystem cycle, then update the time and count.
        game.eco.cycle()
        game.time = game.time + 1
        game.count = int(game.eco.orgs[0].count)

        # If it hasn't grown at all since 10 minutes, then stop.
        if len(game.eco.tracker[game.eco.orgs[0]]) > 10 and game.eco.tracker[game.eco.orgs[0]][-10] == game.eco.tracker[game.eco.orgs[0]][-1]:
            limitedBy = game.eco.orgs[0].limitedBy()
            game.play = False

            # If we know why they stopped growing, then tell the player.
            if limitedBy:
                gameOverMenu = Menu("GameOver", ("Game Over", "Your organism stopped growing due to:", limitedBy))
            else:
                gameOverMenu = Menu("GameOver", ('Game Over', "Your organism stopped growing"))
            game.toDraw.append(gameOverMenu)
            pygame.display.flip()

        # Also stop after 3 game hours.
        if game.time >= 180:
            game.play = False
            gameOverMenu = Menu("GameOver", ("Time's Up!", ))
            game.toDraw.append(gameOverMenu)
            pygame.display.flip()

        # Update the drawing queue with the new time and cell count.
        game.toDraw[2] = Menu('Time', ('Time (minutes):', str(game.time)), center=(background.get_width()*1/4, background.get_height()*8/10))
        game.toDraw[3] = Menu('Cells', ('Number of Cells:', str(game.count)), center=(background.get_width()*3/4, background.get_height()*8/10))

        # Limits the rate at which the ecosystem cycles.  Can decrease or remove this to run faster.
        pygame.time.wait(125)

    # Handle all the Pygame events.
    for event in pygame.event.get():
        # Exit the program if the window is closed or escape is hit.
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                sys.exit()

        # If they click the mouse, then pass the event to every menu
        # currently being drawn so they can process it if necessary.
        elif event.type == pygame.MOUSEBUTTONDOWN:
            #print event  # Used for debugging.
            for m in game.toDraw:
                if m.handleEvent:
                    m.handleEvent(event, game)


#! /usr/bin/env python
import re
from pprint import pformat

import numpy as np

from aoc.utils import load_input_by_line

class Moon:
    def __init__(self, x, y, z, vx=0, vy=0, vz=0):
        self.x = x
        self.y = y
        self.z = z
        self.vx = vx
        self.vy = vy
        self.vz = vz

    @property
    def pos(self):
        return self.x, self.y, self.z

    @property
    def v(self):
        return self.vx, self.vy, self.vz

    @property
    def pot_e(self):
        return abs(self.x) + abs(self.y) + abs(self.z)

    @property
    def kin_e(self):
        return abs(self.vx) + abs(self.vy) + abs(self.vz)

    @property
    def e(self):
        return self.pot_e * self.kin_e

    def apply_gravity(self, o, axis):
        if axis & 1:
            if self.x < o.x:
                self.vx += 1
                o.vx -= 1
            elif self.x > o.x:
                self.vx -= 1
                o.vx += 1

        if axis & 2:
            if self.y < o.y:
                self.vy += 1
                o.vy -= 1
            elif self.y > o.y:
                self.vy -= 1
                o.vy += 1

        if axis & 4:
            if self.z < o.z:
                self.vz += 1
                o.vz -= 1
            elif self.z > o.z:
                self.vz -= 1
                o.vz += 1

    def move(self, axis):
        if axis & 1:
            self.x += self.vx
        if axis & 2:
            self.y += self.vy
        if axis & 4:
            self.z += self.vz

    def __eq__(self, o):
        return self.x == o.x and self.y == o.y and self.z == o.z

    def __str__(self):
        return f"<Moon(pos={self.pos}, v={self.v})>"

    def __repr__(self):
        return str(self)

class System:
    def __init__(self, moons: [Moon]):
        self.moons = moons
        self.size = len(moons)

    @property
    def e(self):
        return sum(m.e for m in self.moons)

    def step(self, n=1, axis=7):
        for i in range(n):
            self._step(axis)

    def _step(self, axis):
        self._apply_gravity(axis)
        self._move(axis)

    def _apply_gravity(self, axis):
        for i in range(self.size - 1):
            for j in range(i + 1, self.size):
                m1 = self.moons[i]
                m2 = self.moons[j]
                m1.apply_gravity(m2, axis)

    def _move(self, axis):
        for m in self.moons:
            m.move(axis)

    def get_period(self, axis):
        init = self._get_positions(axis)
        i = 0

        while True:
            i += 1
            self.step(axis=axis)
            if self._get_positions(axis) == init:
                return i * 2

    def _get_positions(self, axis):
        if axis == 1:
            return [m.vx for m in self.moons]

        if axis == 2:
            return [m.vy for m in self.moons]

        if axis == 4:
            return [m.vz for m in self.moons]

    def __eq__(self, o):
        return self.moons == o.moons

    def __str__(self):
        return pformat(self.moons)

    def __repr__(self):
        return str(self)

def create_system(input_values):
    moons = []

    matcher = re.compile(r"<x=(-?[0-9]+), y=(-?[0-9]+), z=(-?[0-9]+)>")

    for l in input_values:
        m = matcher.match(l)
        if not m:
            raise ValueError(l)

        x = int(m.group(1))
        y = int(m.group(2))
        z = int(m.group(3))

        moons.append(Moon(x, y, z))

    return System(moons)

def get_energy_after_steps(system, n=1):
    system.step(n)
    return system.e

def get_steps_before_repeat(system):
    px = system.get_period(1)
    py = system.get_period(2)
    pz = system.get_period(4)

    # noinspection PyUnresolvedReferences
    return np.lcm.reduce([px, py, pz])

def main():
    input_values = load_input_by_line("d12.txt")

    system = create_system(input_values)
    print(f"Part 1: {get_energy_after_steps(system, 1000)}")

    system = create_system(input_values)
    print(f"Part 2: {get_steps_before_repeat(system)}")

if __name__ == "__main__":
    from time import time as ts

    _t = ts()
    main()
    _t = ts() - _t

    print(f"Runtime: {_t:.3f}s")


import sys
from pathlib import Path

sys.path.append(
    str(
        Path(__file__).parent /
        '../../../third_party/SuperGluePretrainedNetwork'))

from models.superpoint import SuperPoint as SP  # noqa: E402

from ..utils.base_model import BaseModel  # noqa: E402

class SuperPoint(BaseModel):
    """SuperPoint Convolutional Detector and Descriptor.

    SuperPoint: Self-Supervised Interest Point Detection and
    Description. Daniel DeTone, Tomasz Malisiewicz, and Andrew
    Rabinovich. In CVPRW, 2019. https://arxiv.org/abs/1712.07629
    """

    default_conf = {
        'nms_radius': 4,
        'keypoint_threshold': 0.005,
        'max_keypoints': -1,
        'remove_borders': 4,
        'model_path': 'superpoint_v1.pth',
    }
    required_inputs = ['image']

    def _init(self, conf, model_path):
        self.conf = {**self.default_conf, **conf}
        self.conf['model_path'] = model_path / self.conf['model_path']
        self.net = SP(self.conf)

    def _forward(self, data):
        return self.net(data)


import torch.nn as nn
import torch

import numpy as np

class NCEClassifier(nn.Module):
    def __init__(self, outplanes, args):
        super(NCEClassifier, self).__init__()
        self.args = args
        self.num_classes = args.base_class
        self.temperature = nn.Parameter(torch.tensor(64.0), requires_grad=True)

    def forward(self, x, num_batch):
        query = x[:num_batch]
        proto = x[num_batch:]
        query = query.unsqueeze(1)
        proto = proto.unsqueeze(0).repeat(num_batch, 1, 1)
        scores = - torch.sum((proto - query) ** 2, 2) / self.temperature
        return scores


import utils.utils as utils

def new_field(curr_list, infinite_char):
    new_list = []
    new_list.append(infinite_char * (len(curr_list) + 2))
    for elem in curr_list:
        new_list.append(infinite_char + elem + infinite_char)
    new_list.append(infinite_char * (len(curr_list) + 2))
    return new_list

algo_str, pic_list = utils.read_pic_algo("files/task20.txt")
infinite_char = '.'
for rounds in range(50):
    new_list = new_field(pic_list, infinite_char)
    round_list = []
    for i in range(len(new_list)):
        round_row = ''
        for j in range(len(new_list[i])):
            pos = 8
            nr_algo = 0
            for m in range(-1, 2):
                for n in range(-1, 2):
                    l_pos = i + m
                    s_pos = j + n
                    if (
                        (l_pos < 0)
                        or (s_pos < 0)
                        or (l_pos >= len(new_list))
                        or (s_pos >= len(new_list[i]))
                    ):
                        if infinite_char == "#": nr_algo += 2 ** pos
                    else:
                        if new_list[l_pos][s_pos] == "#": nr_algo += 2 ** pos
                    pos -= 1
            round_row += algo_str[nr_algo]
        round_list.append(round_row)
    pic_list = round_list
    if infinite_char == '.': infinite_char = algo_str[0]
    else: infinite_char = algo_str[511]
    # for elem in pic_list:
    #     print(elem)
    # print()
num_pics = 0
for elem in pic_list:
    num_pics += elem.count('#')
print(f"Number of pics = {num_pics}")


import re, math

style = 'default'
indent_style = 'convention'
filename_style = 'snake_case'
tabsize_style = 0
insert_todo = True

def block_start() -> str:
    if style == 'gnu' or style == 'google':
        return '\n{\n'
    return ' {\n'

def space_after_func_name() -> str:
    if style == 'google':
        return ''
    return ' '

def type_spacing(type: str) -> str:
    if type.endswith('*') or type.endswith('&'):
        if style == 'google':
            return type + ' '
        match = re.search(r'(.+?)\s*([*&\s]+?)$', type)
        name = match.group(1)
        pt = match.group(2)
        if style == 'gnu':
            return name + ' ' + pt + '\n'
        return name + ' ' + pt
    if style == 'gnu':
        return type + '\n'
    return type + ' '

def columns() -> int:
    return 78

def indent_char() -> str:
    if indent_style != 'convention':
        return ' ' if indent_style == 'space' else '\t'
    if style == 'gnu' or style == 'google':
        return ' '
    return ' '

def indent() -> str:
    ch = indent_char()
    return ch * tabsize() if ch == ' ' else ch

def tabsize() -> int:
    if tabsize_style != 0:
        return tabsize_style
    if style == 'gnu' or style == 'google':
        return 2
    return 4

def spaces_to_indent(spaces: str) -> str:
    if indent_char() == ' ':
        return spaces
    else:
        num = len(spaces) / tabsize()
        return '\t' * int(round(num))

def param_indent_style() -> str:
    if style == 'gnu' or style == 'google':
        return 'double_indent'
    return 'vert_align'

def convert_case(text: str) -> str:
    if filename_style == 'snake_case':
        return snakecase(text)
    elif filename_style == 'hyphen-case':
        return snakecase(text).replace('_', '-')
    elif filename_style == 'lowercase':
        return snakecase(text).replace('_', '')
    elif filename_style == 'UPPERCASE':
        return snakecase(text).replace('_', '').upper()
    elif filename_style == 'camelCase':
        return camelcase(text)
    elif filename_style == 'PascalCase':
        return pascalcase(text)
    elif filename_style == 'CONST_CASE':
        return snakecase(text).upper()
    else:
        raise 'Invalid filename style'

def snakecase(text: str) -> str:
    text = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', text)
    text = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', text)
    text = re.sub(r'__+', '_', text)
    return text.lower()

def camelcase(text: str) -> str:
    text = re.sub(r'_+([a-z])', lambda m: m.group(1).upeer(), text)
    text = re.sub(r'^([A-Z]+)([A-Z][a-z])', lambda m: m.group(1).lower() + m.group(2), text)
    text = re.sub(r'^([A-Z])', lambda m: m.group(1).lower(), text)
    return text

def pascalcase(text: str) -> str:
    text = re.sub(r'_+([a-z])', lambda m: m.group(1).upeer(), text)
    text = re.sub(r'^([a-z]+)([A-Z][a-z])', lambda m: m.group(1).upper() + m.group(2), text)
    text = re.sub(r'^([a-z])', lambda m: m.group(1).upper(), text)
    return text

def header_guard(namespaces: list[str], class_name: str, suffix: str) -> str:
    suffix = suffix.replace('.', '').upper()
    ns = '_'.join(ns.replace('_', '').upper() for ns in namespaces)
    name = class_name.replace('_', '').upper()
    return f'{ns}_{name}_{suffix}'


# --------------------------------------------------------------------------------------------------- #
# -----------classをリスト化して、ランダムに取り出して表示させることのできるスクリプトの例です------------ #
# --------------------------------------------------------------------------------------------------- #

import random

class Zatugaku:
    def __init__(self, score, title, description, fromorkinds, url, thumbnail, point):
        for key,value in locals().items():
            if not key == "self":
                self.__dict__[key] = value

Zatulist = [Zatugaku(
                    "スコアです",
                    "タイトルです",
                    "詳細です",
                    "分類です",
                    "URLです",
                    "サムネです",
                    "ポイントです"
                    )
]

data = random.choice(Zatulist)
print(data.score,data.title,data.description,data.fromorkinds,data.url,data.thumbnail,data.point, sep="\n")


import numpy as np
import pandas as pd
import datetime as dt

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

from flask import Flask, jsonify

#################################################
# Database Setup
#################################################
engine = create_engine("sqlite:///Resources/hawaii.sqlite", echo=True)

# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)

# Save references to each table
station = Base.classes.station
measurement = Base.classes.measurement

# Create a database session object
session = Session(engine)

#################################################
# Flask Setup
#################################################
app = Flask(__name__)

#################################################
# Flask Routes
#################################################

# Home page
@app.route("/")
# List all routes that are available.
def welcome():
    """List all available api routes."""
    return (
        f"Available Routes:
"
        f"/api/v1.0/precipitation
"
        f"/api/v1.0/stations
"
        f"/api/v1.0/tobs
"
        f"/api/v1.0/start
"
        f"/api/v1.0/start/end"
    )

# Precipitation Route
@app.route("/api/v1.0/precipitation")
def precipitation():
    # Design a query to retrieve the last 12 months of precipitation data and plot the results.
    query_date = dt.date(2017, 8, 23) - dt.timedelta(days=365)
    # Perform a query to retrieve the date and precipitation scores
    date_prcp_data = session.query(measurement.date, measurement.prcp).\
        filter(measurement.date >= query_date).all()
    # Convert the query results to a dictionary using date as the key and prcp as the value.
    prcp_dict = dict(date_prcp_data)
    # Return the JSON representation of your dictionary.
    return jsonify(prcp_dict)

# Stations Route
@app.route("/api/v1.0/stations")
def stations():
    #Design a query to retrieve the stations
    stations = session.query(station.station).distinct().all()
    #Return a JSON list of stations from the dataset.
    return jsonify(stations)

# Temperature Route
@app.route("/api/v1.0/tobs")
def tobs():
    # Query the dates and temperature observations of the most active station for the last year of data.
    query_date = dt.date(2017, 8, 23) - dt.timedelta(days=365)
    active_station = session.query(measurement.date, measurement.tobs).\
        filter(measurement.date >= query_date).\
        filter(measurement.station == 'USC00519281')
    all_tobs = []
    for date, tobs in active_station:
        tobs_dict = {}
        tobs_dict['date'] = date
        tobs_dict['tobs'] = tobs
        all_tobs.append(tobs_dict)
    # Return a JSON list of temperature observations (TOBS) for the previous year.
    return jsonify(all_tobs)

# Start Only Route
@app.route("/api/v1.0/<start>")
def start_date_data(start):
    # When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date.
    start_results = session.query(measurement.date, func.min(measurement.tobs), func.avg(measurement.tobs), func.max(measurement.tobs)).\
        filter(measurement.date >= start).all()
    return_json=[]
    for each_result in start_results:
        return_json.append([each_result[0], each_result[1], each_result[2], each_result[3]])
    # Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range.
    return jsonify(return_json)

#Start and End Route
@app.route("/api/v1.0/<start>/<end>")
def start_end(start, end):
# Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range.
# When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive.
    end_results = session.query(measurement.date, func.min(measurement.tobs), func.avg(measurement.tobs), func.max(measurement.tobs)).\
        filter(measurement.date >= start).\
        filter(measurement.date <= end).all()
    return_end_json=[]
    for each_result in end_results:
        return_end_json.append([each_result[0], each_result[1], each_result[2], each_result[3]])
    # Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range.
    return jsonify(return_end_json)

# Close session
session.close()

if __name__ == "__main__":
    app.run(debug=True)


from Abstract.Instruccion import Instruccion
from Abstract.NodoArbol import NodoArbol
from Tabla_Simbolo.Excepcion import Excepcion
from Tabla_Simbolo.Simbolo import Simbolo

class Asignacion(Instruccion):
    #
    def __init__(self, identificador, expresion, fila, columna):
        self.identificador = identificador
        self.expresion = expresion
        self.fila = fila
        self.columna = columna

    def interpretar(self, tree, table):
        value = self.expresion.interpretar(tree, table) # Valor a asignar a la variable
        if isinstance(value, Excepcion): return value

        simbolo = Simbolo(self.identificador, self.expresion.tipo, self.fila, self.columna, value)

        result = table.actualizarTabla(simbolo)

        if isinstance(result, Excepcion): return result
        return None

    def getNodo(self):
        nodo = NodoArbol("ASIGNACION")
        nodo.addHijoValor(str(self.identificador))
        nodo.addHijoValor("=")
        nodo.addHijoNodo(self.expresion.getNodo())
        return nodo


# Bubble sort
def bubble(niz):
    for i in range(len(niz)):
        for j in range(0, len(niz)-i-1):
            if niz[j] > niz[j+1]:
                niz[j], niz[j+1] = niz[j+1], niz[j]
    return niz

# Selection Sort
def selection(niz):
    for i in range(len(niz)):
        mmin=i
        for j in range(i+1, len(niz)):
            if niz[mmin] > niz[j]:
                mmin=j
        niz[i], niz[mmin] = niz[mmin], niz[i]
    return niz

# Insertion Sort
def insertionSort(niz):
    for i in range(1, len(niz)):
        j=i-1
        tren=niz[i]
        while j>=0 and tren<niz[j]:
            niz[j+1]=niz[j]
            j-=1
        niz[j+1]=tren
    return niz

# Merge Sort
def mergeSort(niz):
    if len(niz) > 1:
        sred = len(niz)//2
        L = niz[:sred]
        R = niz[sred:]
        mergeSort(L)
        mergeSort(R)
        i=0
        j=0
        k=0

        while i < len(L) and j < len(R):
            if L[i] <= R[j]:
                niz[k] = L[i]
                i += 1
            else:
                niz[k] = R[j]
                j += 1
            k += 1

        while i < len(L):
            niz[k] = L[i]
            i += 1
            k += 1

        while j < len(R):
            niz[k] = R[j]
            j += 1
            k += 1
    return niz

# Quicksort
def podela(niz, donja, gornja):
    pivot=niz[gornja]
    i=donja-1

    for j in range(donja, gornja):
        if niz[j]<=pivot:
            i+=1
            niz[j], niz[i]=niz[i],niz[j]

    niz[i+1], niz[gornja]=niz[gornja], niz[i+1]
    return i+1

def quickSort(niz, donja, gornja):
    if donja<gornja :
        indeks=podela(niz, donja, gornja)
        quickSort(niz, donja, indeks-1)
        quickSort(niz, indeks+1, gornja)
    return niz

niz=[4, 3, 9, 3, 7, 1]

print(bubble(niz))
print(insertionSort([4, 2, 6, 1, 3]))
print(mergeSort(niz))
print(quickSort([3, 2, 6, 9, 4], 0, 4))
print(selection(niz))


def arithmetic_arranger(problems, val=False):
    if len(problems) > 5:
        return "Error: Too many problems."

    top_row, bottom_row, dashes, solutions = '', '', '', ''

    for problem in problems:
        operand1, operator, operand2 = problem.split()
        if operator not in ['+', '-']:
            return "Error: Operator must be '+' or '-'."
        if not (operand1.isdigit() and operand2.isdigit()):
            return "Error: Numbers must only contain digits."
        if len(operand1) > 4 or len(operand2) > 4:
            return "Error: Numbers cannot be more than four digits."

        width = max(len(operand1), len(operand2)) + 2
        top_row += operand1.rjust(width) + ' ' * 4
        bottom_row += operator + operand2.rjust(width - 1) + ' ' * 4
        dashes += '-' * width + '    '
        solutions += str(eval(problem)).rjust(width) + ' ' * 4

    arranged_problems = '\n'.join((top_row.rstrip(), bottom_row.rstrip(), dashes.rstrip()))
    if val:
        arranged_problems += '\n' + solutions.rstrip()

    return arranged_problems


# Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

# For example (Input -> Output):

# 2 -> 3 (1 + 2)
# 8 -> 36 (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8)

def summation(num):
    answer = 0
    i = 1
    for j in range(num):
        answer = j + i
        i += num / 2

    return answer

# Better Answer by brice1:
def summation(num):
    total = 0
    for i in range(0, num+1):
        total = total + i
    return total


# First run the following command to install open cv in ur maching
# pip install opencv-contrib-python

# Then run this one as well
# pip install caer

# READING IMAGE AND VIDEO
from operator import itruediv
import cv2 as cv

# to read an img we use .imread() which take the path of img as parameter.
firstImg = cv.imread('my.jpg')

# To print that img we use .imshow() which take window name as first parameter and variable name
# as second parameter.
cv.imshow('Raza with Hasnain',firstImg)
cv.waitKey(0)

# reading vid
# integer 0 is refer for web camera
# To read a video we use .VideoCapture() which take integer/path as a parameter.
firstVid = cv.VideoCapture('project.mp4')

# Let's run that video
while True:
    isTrue, frame = firstVid.read()
    cv.imshow('project',frame)

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

firstVid.release()
cv.destroyAllWindows()


#!/usr/bin/env python

from .kernel import DockerProxyKernel
from .parser import get_parser

from .parentpoller import setup_parent_poller

# get and parse arguments
inputs = get_parser().parse_args()

# Start proxy kernel setup
kernel = DockerProxyKernel()
kernel.register_signals()

# Start parent poller
setup_parent_poller(lambda: kernel.stop_kernel(None, None))

# Start kernel and wait for docker run to die off
kernel.start_kernel(cmd=inputs.cmd,
                    connection_file=inputs.connection_file,
                    docker_image=inputs.image,
                    docker_control_port=inputs.control,
                    docker_hb_port=inputs.hb,
                    docker_iopub_port=inputs.iopub,
                    docker_shell_port=inputs.shell,
                    docker_stdin_port=inputs.stdin,
                    docker=inputs.docker,
                    docker_arguments=inputs.docker_args)


import os

# 获取当前文件夹的绝对路径
current_folder = os.getcwd()

# 获取当前文件夹同级的 output_images 文件夹的绝对路径
SAVE_DIR_PATH = os.path.abspath(os.path.join(
    current_folder, 'JD-搜索结果页图片', 'output_images'))

# 网站 URL
PAGE_URL = 'https://www.jd.com/'


from sort import sort_algs
import numpy as np

x = np.array([1,4,2,5])
test_empty = np.array([])
test_zero = np.array([0])
test_neg = np.array([2,1,0,-1,-2])

collect_test = [test_empty,test_zero,test_neg,x]

# could test the number of expected conditionals, assignments?
# all(l[i] <= l[i+1] for i in range(len(l)-1)) # check that a list is sorted

def test_pointless_sort():
    assert np.array_equal(sort_algs.pointless_sort(x), np.array([1, 2, 3]))

def test_bubblesort():
    sort_algs.run_bubble_sort(x)
    for i in collect_test:
        assert np.array_equal(sort_algs.bubble_sort(i), np.array(sorted(i)))

def test_quicksort():
    sort_algs.run_quick_sort(x)
    for i in collect_test:
        assert np.array_equal(sort_algs.quick_sort(i), np.array(sorted(i)))