"""Administration form for general Review Board settings."""

from collections import OrderedDict
from urllib.parse import urlparse

from django import forms
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.module_loading import import_string
from django.utils.translation import gettext, gettext_lazy as _
from djblets.cache.backend_compat import normalize_cache_backend
from djblets.cache.forwarding_backend import DEFAULT_FORWARD_CACHE_ALIAS
from djblets.forms.fields import TimeZoneField
from djblets.siteconfig.forms import SiteSettingsForm

from reviewboard.admin.siteconfig import load_site_config

class BaseCacheSettingsForm(forms.Form):
    """Base class for a cache backend settings form.

    Version Added:
        4.0
    """

    def load(self, cache_backend_settings):
        """Load the cache backend settings into the form.

        Args:
            cache_backend_settings (dict):
                Settings for the cache backend.
        """
        pass

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        raise NotImplementedError

class FileCacheSettingsForm(BaseCacheSettingsForm):
    """Settings for the file-based cache backend.

    This backend is recommended only for simple test setups and development.
    """

    cache_path = forms.CharField(
        label=_('Cache Path'),
        help_text=_(
            'The file location for the cache. This must be writable by '
            'the web server.'
        ),
        required=True,
        widget=forms.TextInput(attrs={'size': '50'}),
        error_messages={
            'required': 'A valid cache path must be provided.'
        })

    def load(self, cache_backend_settings):
        """Load the cache backend settings into the form.

        Args:
            cache_backend_settings (dict):
                Settings for the cache backend.
        """
        cache_locations = cache_backend_settings['LOCATION']

        if not isinstance(cache_locations, list):
            cache_locations = [cache_locations]

        self.fields['cache_path'].initial = ';'.join(cache_locations)

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        return {
            'LOCATION': self.cleaned_data['cache_path'],
        }

    def clean_cache_path(self):
        """Clean the cache_path field.

        This will strip whitespace around the value and return it.

        Returns:
            unicode:
            The cache path, with whitespace stripped.
        """
        return self.cleaned_data['cache_path'].strip()

    class Meta:
        title = _('Local File Cache Settings')

class LocalMemoryCacheSettingsForm(BaseCacheSettingsForm):
    """Settings for the local memory cache backend.

    This is only available for development setups and cannot be used in
    production.
    """

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        # We want to specify a "reviewboard" location to keep items
        # separate from those in other caches.
        return {
            'LOCATION': 'reviewboard'
        }

    class Meta:
        title = _('Local Memory Cache Settings')

class MemcachedSettingsForm(BaseCacheSettingsForm):
    """Settings for the memcached backend.

    This is the recommended caching backend.
    """

    cache_host = forms.CharField(
        label=_('Cache Hosts'),
        help_text=_('The host or hosts used for the cache, in hostname:port '
                    'form. Multiple hosts can be specified by separating '
                    'them with a semicolon (;).'),
        required=True,
        widget=forms.TextInput(attrs={'size': '50'}),
        error_messages={
            'required': 'A valid cache host must be provided.'
        })

    def load(self, cache_backend_settings):
        """Load the cache backend settings into the form.

        Args:
            cache_backend_settings (dict):
                Settings for the cache backend.
        """
        cache_locations = cache_backend_settings['LOCATION']

        if not isinstance(cache_locations, list):
            cache_locations = [cache_locations]

        self.fields['cache_host'].initial = ';'.join(cache_locations)

    def build_cache_backend_settings(self):
        """Build new cache backend settings from the form data.

        Returns:
            dict:
            The new cache backend settings.
        """
        return {
            'LOCATION': self.cleaned_data['cache_host'].split(';'),
        }

    def clean_cache_host(self):
        """Clean the cache_host field.

        This will strip whitespace around the value and return it.

        Returns:
            unicode:
            The cache host, with whitespace stripped.
        """
        return self.cleaned_data['cache_host'].strip()

    class Meta:
        title = _('Memcached Settings')

class GeneralSettingsForm(SiteSettingsForm):
    """General settings for Review Board."""

    _cache_backends = OrderedDict([
        ('locmem', {
            'name': _('Local memory cache (developer-only)'),
            'available': not settings.PRODUCTION,
            'backend_cls_path':
                'django.core.cache.backends.locmem.LocMemCache',
            'form_cls': LocalMemoryCacheSettingsForm,
        }),
        ('memcached', {
            'name': _('Memcached (recommended)'),
            'backend_cls_path':
                'django.core.cache.backends.memcached.PyMemcacheCache',
            'legacy_backend_cls_paths': [
                'django.core.cache.backends.memcached.CacheClass',
                'django.core.cache.backends.memcached.MemcachedCache',
            ],
            'form_cls': MemcachedSettingsForm,

        }),
        ('file', {
            'name': _('Local file cache'),
            'backend_cls_path':
                'django.core.cache.backends.filebased.FileBasedCache',
            'form_cls': FileCacheSettingsForm,
        }),
    ])

    CACHE_VALIDATION_KEY = '__rb-cache-validation__'
    CACHE_VALIDATION_VALUE = 12345

    company = forms.CharField(
        label=_('Company/Organization'),
        help_text=_('The optional name of your company or organization. '
                    'This will be displayed on your support page.'),
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    server = forms.CharField(
        label=_('Server'),
        help_text=_('The URL of this Review Board server. This should not '
                    'contain the subdirectory Review Board is installed in.'),
        widget=forms.TextInput(attrs={'size': '30'}))

    site_read_only = forms.BooleanField(
        label=_('Enable read-only mode'),
        help_text=_('Prevent non-superusers from making any changes to '
                    'Review Board.'),
        required=False)

    read_only_message = forms.CharField(
        label=_('Read-only message'),
        help_text=_('A custom message displayed when the site is in '
                    'read-only mode.'),
        required=False,
        widget=forms.TextInput(attrs={'size': '30'}))

    site_media_url = forms.CharField(
        label=_('Media URL'),
        help_text=(_('The URL to the media files. Set to '
                     '%smedia/ to use the default media path on '
                     'this server.')
                   % settings.SITE_ROOT),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))

    site_static_url = forms.CharField(
        label=_('Static URL'),
        help_text=(_('The URL to the static files, such as JavaScript files, '
                     'CSS files, and images that are bundled with Review '
                     'Board or third-party extensions. Set to '
                     '%sstatic/ to use the default static path '
                     'on this server.')
                   % settings.SITE_ROOT),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))

    site_admin_name = forms.CharField(
        label=_('Administrator Name'),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))
    site_admin_email = forms.EmailField(
        label=_('Administrator E-Mail'),
        required=True,
        widget=forms.TextInput(attrs={'size': '30'}))

    locale_timezone = TimeZoneField(
        label=_('Time Zone'),
        required=True,
        help_text=_('The time zone used for all dates on this server.'))

    cache_type = forms.ChoiceField(
        label=_('Cache Backend'),
        help_text=_('The type of server-side caching to use.'),
        required=True,
        widget=forms.Select(attrs={
            'data-subform-group': 'cache-backend',
        }))

    def __init__(self, siteconfig, data=None, files=None, *args, **kwargs):
        """Initialize the settings form.

        Args:
            siteconfig (djblets.siteconfig.models.SiteConfiguration):
                The site configuration being changed.

            data (dict, optional):
                The submitted form data.

            files (dict, optional):
                The uploaded file data.

            *args (tuple):
                Additional positional arguments for the form.

            **kwargs (dict):
                Additional keyword arguments for the form.
        """
        self.cache_backend_forms = {
            backend_id: backend_info['form_cls'](data=data, files=files)
            for backend_id, backend_info in self._cache_backends.items()
            if backend_info.get('available', True)
        }

        super(GeneralSettingsForm, self).__init__(siteconfig,
                                                  data=data,
                                                  files=files,
                                                  *args, **kwargs)

    def load(self):
        """Load settings from the form.

        This will populate initial fields based on the site configuration.
        It takes care to transition legacy (<= Review Board 1.7) cache
        backends, if still used in production, to a modern configuration.
        """
        domain_method = self.siteconfig.get('site_domain_method')
        site = Site.objects.get_current()

        # Load the rest of the settings from the form.
        super(GeneralSettingsForm, self).load()

        # Load the cache settings.
        cache_backend_info = self.siteconfig.get('cache_backend')
        cache_backend = (
            normalize_cache_backend(cache_backend_info,
                                    DEFAULT_FORWARD_CACHE_ALIAS) or
            normalize_cache_backend(cache_backend_info))

        cache_backend_path = cache_backend['BACKEND']
        cache_type = 'custom'

        for _cache_type, backend_info in self._cache_backends.items():
            if (cache_backend_path == backend_info['backend_cls_path'] or
                cache_backend_path in backend_info.get(
                    'legacy_backend_cls_paths', [])):
                cache_type = _cache_type
                break

        cache_type_choices = [
            (backend_id, backend_info['name'])
            for backend_id, backend_info in self._cache_backends.items()
            if backend_info.get('available', True)
        ]

        if cache_type == 'custom':
            cache_type_choices.append(('custom', gettext('Custom')))

        cache_type_field = self.fields['cache_type']
        cache_type_field.choices = tuple(cache_type_choices)
        cache_type_field.initial = cache_type

        if cache_type in self.cache_backend_forms:
            self.cache_backend_forms[cache_type].load(cache_backend)

        # This must come after we've loaded the general settings.
        self.fields['server'].initial = '%s://%s' % (domain_method,
                                                     site.domain)

    def save(self):
        """Save the form.

        This will write the new configuration to the database. It will then
        force a site configuration reload.
        """
        server = self.cleaned_data['server']

        if '://' not in server:
            # urlparse doesn't properly handle URLs without a scheme. It
            # believes the domain is actually the path. So we apply a prefix.
            server = 'http://' + server

        url_parts = urlparse(server)
        domain_method = url_parts[0]
        domain_name = url_parts[1]

        if domain_name.endswith('/'):
            domain_name = domain_name[:-1]

        site = Site.objects.get_current()

        if site.domain != domain_name:
            site.domain = domain_name
            site.save(update_fields=['domain'])

        self.siteconfig.set('site_domain_method', domain_method)

        cache_type = self.cleaned_data['cache_type']

        if cache_type != 'custom':
            cache_backend_info = self._cache_backends[cache_type]
            cache_form = self.cache_backend_forms[cache_type]
            cache_backend_settings = cache_form.build_cache_backend_settings()

            self.siteconfig.set('cache_backend', {
                DEFAULT_FORWARD_CACHE_ALIAS: dict({
                    'BACKEND': cache_backend_info['backend_cls_path'],
                }, **cache_backend_settings),
            })

        super(GeneralSettingsForm, self).save()

        # Reload any important changes into the Django settings.
        load_site_config()

    def is_valid(self):
        """Return whether the form is valid.

        This will check that this form, and the form for any selected cache
        backend, is valid.

        Returns:
            bool:
            ``True`` if all form fields are valid. ``False`` if any are
            invalid.
        """
        if not super(GeneralSettingsForm, self).is_valid():
            return False

        cache_form = self.cache_backend_forms.get(
            self.cleaned_data['cache_type'])

        return cache_form is None or cache_form.is_valid()

    def clean(self):
        """Clean and validate the form fields.

        This is called after all individual fields are validated. It does
        the remaining work of checking to make sure the resulting configuration
        is valid.

        Returns:
            dict:
            The cleaned form data.
        """
        cleaned_data = super(GeneralSettingsForm, self).clean()

        if 'cache_type' not in self.errors:
            cache_type = cleaned_data['cache_type']
            cache_backend_info = self._cache_backends.get(cache_type)
            cache_form = self.cache_backend_forms.get(cache_type)

            if (cache_backend_info is not None and
                cache_form is not None and
                cache_form.is_valid()):
                cache_backend = None

                try:
                    cache_backend_settings = \
                        cache_form.build_cache_backend_settings()

                    cache_cls = import_string(
                        cache_backend_info['backend_cls_path'])
                    cache_backend = cache_cls(
                        cache_backend_settings.get('LOCATION'),
                        {})

                    cache_backend.set(self.CACHE_VALIDATION_KEY,
                                      self.CACHE_VALIDATION_VALUE)
                    value = cache_backend.get(self.CACHE_VALIDATION_KEY)
                    cache_backend.delete(self.CACHE_VALIDATION_KEY)

                    if value != self.CACHE_VALIDATION_VALUE:
                        self.errors['cache_type'] = self.error_class([
                            _('Unable to store and retrieve values from this '
                              'caching backend. There may be a problem '
                              'connecting.')
                        ])
                except Exception as e:
                    self.errors['cache_type'] = self.error_class([
                        _('Error with this caching configuration: %s')
                        % e
                    ])

                # If the cache backend is open, try closing it. This may fail,
                # so we want to ignore any failures.
                if cache_backend is not None:
                    try:
                        cache_backend.close()
                    except Exception:
                        pass

        return cleaned_data

    class Meta:
        title = _('General Settings')
        save_blacklist = ('server', 'cache_type')

        subforms = (
            {
                'subforms_attr': 'cache_backend_forms',
                'controller_field': 'cache_type',
            },
        )

        fieldsets = (
            {
                'title': _('Site Settings'),
                'classes': ('wide',),
                'fields': ('company', 'server', 'site_media_url',
                           'site_static_url', 'site_admin_name',
                           'site_admin_email', 'locale_timezone',
                           'site_read_only', 'read_only_message'),
            },
            {
                'title': _('Cache Settings'),
                'classes': ('wide',),
                'fields': ('cache_type',),
            },
        )


# encoding: utf-8

class Table(object):
    def config_db(self,pkg):
        tbl=pkg.table('email_arr', pkey='id', name_long='email_arr', name_plural='email_arr',
                        caption_field='description', partition_agency_id='agency_id')
        self.sysFields(tbl)

        tbl.column('arrival_id',size='22', name_long='arrival_id'
                    ).relation('arrival.id', relation_name='arrival_email', mode='foreignkey', onDelete='cascade')
        tbl.column('dest', name_short='!![en]Destination',values='to:to,cc:cc')
        tbl.column('description', name_short='!![en]Email description')
        tbl.column('email', name_short='Email arrival')
        tbl.column('email_type', size=':3', name_short='!![en]Email type', values='to:to,cc:cc,ccn:ccn')
        tbl.aliasColumn('agency_id','@arrival_id.agency_id')
        tbl.formulaColumn('email_int',"$dest || ' ' || $description",order_by='$dest DESC',group_by='$dest', dtype='T')


#User function Template for python3

class Solution:

    def lcs(self,s1,s2,n1,n2):
        dp=[[None]*(n2+1) for _ in range(n1+1)]
        for i in range(n1+1):
            for j in range(n2+1):
                if i==0 or j==0:
                    dp[i][j]=0
                elif s1[i-1]==s2[j-1]:
                    dp[i][j]=1+dp[i-1][j-1]
                else:
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1])
        return dp[n1][n2]

    def shortestCommonSupersequence(self, X, Y, m, n):
        return m+n-self.lcs(X,Y,m,n)

GeekForGeek/Problem Of The Day/Shortest Common Supersequence.py


from flask import Flask, render_template, request
import requests

app = Flask(__name__)

# Route par défault / index
@app.route('/')
def index():
    return render_template('index.html')

# Route vers l'API
@app.route('/calendar', methods=['GET'])
def get_calendar():

    # Récupération de la variable year en GET
    year = request.args.get('year')

    # Récupération de la variable month en GET
    month = request.args.get('month')

    # URL de l'API
    api_url = 'http://localhost:8080/calendar?year=' + year + '&month=' + month

    try:
        # Requête HTTP
        response = requests.get(api_url)
    except:
        # Cas si exception
        print(f"Erreur lors de la requête")
        return render_template('error.html')
    else:
        # Cas si réussite
        if response.status_code == 200:
            # Cas si code == 200
            data = response.json()
            print(data["calendar"])
            return render_template('calendar.html', calendar=data['calendar'])
        else:
            # Cas si cde != 200
            print(f"Error for the request with status code {response.status_code}")
            return render_template('error.html')

if __name__ == '__main__':
    app.run(host="localhost", port=8000, debug=True)


import utils
import asyncio
import moteus_pi3hat
import time
import numpy as np
import math
import moteus
import os

async def main():
    # Reset IMU
    moteus_pi3hat.Pi3HatRouter(mounting_deg={'roll': 0,
                                             'pitch': 0,
                                             'yaw': 0})
    time.sleep(0.5)
    con = (0,90,180) # usb down
    #con = (-90,0,-90) # usb up
    # create a moteus_pi3hat.Pi3HatRouter for IMU reading
    pr = moteus_pi3hat.Pi3HatRouter(mounting_deg={'roll': con[0],
                                                  'pitch': con[1],
                                                  'yaw': con[2]})
    time.sleep(4)
    _, _, _, init_euler_xyz = await utils.read_imu_data(pr)
    try:
        while True:
            quat_wxyz, vel_xyz, acc_xyz, euler_xyz = await utils.read_imu_data(pr)
            # quaternions
            w, x, y, z = quat_wxyz
            print(f'w={w:.4f},x={x:.4f},y={y:.4f},z={z:.4f}\n', end='\r')
            # angular verlocities (rad/s)
            wx, wy, wz = vel_xyz
            # print(f'wx={wx:.4f},wy={wy:.4f},wz={wz:.4f}\n')
            # angular accelerations (rad/s^2)
            acc_x, acc_y, acc_z = acc_xyz
            print(f'acc_x={acc_x:.4f},acc_y={acc_y:.4f},acc_z={acc_z:.4f}\n')
            # euler angles (rad)
            r, p, y = np.rad2deg(euler_xyz)
            print(f'roll={r:.4f},pitch={p:.4f},yaw={y:.4f}', end='\r')
            time.sleep(0.3)
    except BaseException as e:
        print(e)

if __name__ == '__main__':
    asyncio.run(main())


from flask import g
from flask_restful.inputs import natural, regex
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from utils.decorators import login_required
from models.article import Comment, Article
from models.user import User
# 导入数据库会话对象db
from models import db

class CommentsResource(Resource):
    method_decorators = {'post': [login_required]}

    def post(self):
        # 获取参数
        parser = RequestParser()
        parser.add_argument('target', type=int, required=True, location='json')
        parser.add_argument('content', required=True, location='json')
        parser.add_argument('parent_id', default=0,
                            type=natural, location='json')
        args = parser.parse_args()
        target = args.target   # 文章id
        content = args.content  # 评论内容
        parent_id = args.parent_id if args.parent_id is not None else 0  # 父评论id 0表示的是一级评论

        # 发布评论数据(评论-回复)
        comment = Comment(
            user_id=g.userid,
            article_id=target,
            parent_id=parent_id,
            content=content
        )
        db.session.add(comment)

        if parent_id > 0:
            # 评论的回复数加1
            Comment.query.filter(Comment.id == parent_id).update(
                {'reply_count': Comment.reply_count + 1})
        else:
            # 文章的评论数加1
            Article.query.filter_by(id=target).update(
                {'comment_count': Article.comment_count + 1})

        # 提交事务
        db.session.commit()

        # 返回结果
        return {'com_id': comment.id, 'target': target, 'parent_id': parent_id}, 201

    def get(self):
        # 获取参数
        parser = RequestParser()
        parser.add_argument('source', type=int, required=True, location='args')
        parser.add_argument('offset', type=int, default=0, location='args')
        parser.add_argument('limit', type=int, default=10, location='args')
        parser.add_argument('type', required=True,
                            location='args', type=regex(r'[ac]'))
        args = parser.parse_args()

        type = args.type  # 如果type = a，source就表示文章id type=c, source表示评论的id
        source = args.source  # 文章id
        offset = args.offset  # 上一页最大的评论的id
        limit = args.limit    # 每页返回的数量

        if type == 'a':
            # 查询评论列表
            # 过滤条件 文章id = source & 评论id>offset & parent_id == 0
            data = db.session.query(
                Comment.id, Comment.user_id, Comment.ctime,
                Comment.content, Comment.reply_count, Comment.like_count,
                User.name, User.profile_photo
            ).join(User, User.id == Comment.user_id).filter(
                Comment.article_id == source,
                Comment.id > offset,
                Comment.parent_id == 0
            ).order_by(Comment.id.asc()).limit(limit).all()

            # 评论的总数量
            total_count = Comment.query.filter(
                Comment.article_id == source, Comment.parent_id == 0).count()

            # 最后一条评论的id, 前端用于判断是否剩余评论, 无值返回None
            end_comment = Comment.query.filter(
                Comment.article_id == source,
                Comment.parent_id == 0
            ).order_by(Comment.id.desc()).first()
        else:
            # 获取评论的回复数
            data = db.session.query(
                Comment.id, Comment.user_id, Comment.ctime,
                Comment.content, Comment.reply_count, Comment.like_count,
                User.name, User.profile_photo
            ).join(User, User.id == Comment.user_id).filter(
                Comment.id > offset,
                Comment.parent_id == source  # source是评论id
            ).order_by(Comment.id.asc()).limit(limit).all()

            # 回复的总数量
            total_count = Comment.query.filter(
                Comment.parent_id == source).count()

            # 最后一条评论的id, 前端用于判断是否剩余评论, 无值返回None
            end_comment = Comment.query.filter(
                Comment.parent_id == source
            ).order_by(Comment.id.desc()).first()

        # 序列化
        comment_list = [
            {
                'com_id': i.id,
                'aut_id': i.user_id,
                'aut_name': i.name,
                'aut_photo': i.profile_photo,
                'pubdate': i.ctime.isoformat(),
                'content': i.content,
                'reply_count': i.reply_count,
                'like_count': i.like_count,
            } for i in data
        ]

        # 本次请求最后一条评论的id, 作为下次请求的offset, 无值返回None
        last_id = data[-1].id if len(data) > 0 else None

        end_id = end_comment.id if end_comment is not None else None

        return {
            'total_count': total_count,
            'last_id': last_id,
            'end_id': end_id,
            'results': comment_list,
        }


# n, s = map(int, input().split())
#
# L = []
# for _ in range(n):
#     L.append(list(map(int, input().split())))
#
# deg = [[] for _ in range(105)]
# ans = 0
# K = [False]*105
# def dfs(v):
#     global ans, K, L
#     K[v] = True
#     ans += 1
#     for i in L[v]:
#         if not K[i]:
#           dfs(i)
#
# for i in range(1, n+1):
#     for j in range(1, n+1):
#         if L[j-1] == 1:
#             deg[i].append(j)
#
# dfs(s)
# print(L)
# # print(K)
# print(ans)

from sys import stdin, stdout

result = 0
n, s = map(int, stdin.readline().split())

a = [[] for _ in range(105)]

visited = [False] * 105

for i in range(1, n + 1):
    row = list(map(int, stdin.readline().split()))
    for j in range(1, n + 1):
        if row[j - 1] == 1:
            a[i].append(j)

def dfs(v):
    global result, visited, a
    visited[v] = True
    result += 1
    for i in a[v]:
        if not visited[i]:
            dfs(i)

dfs(s)
stdout.write(str(result))

обход_графа.py


# https://www.acmicpc.net/problem/1935

# https://www.acmicpc.net/problem/1918
# 위 문제의 연장선 -> 후위 표기식 계산법

n = int(input())
equation = input()
nums = {}
for i in range(n):
    nums[i+65] = int(input())
stack=[]
for char in equation:
    if char.isalpha():
        stack.append(char)
    else:
        second = stack.pop()
        first = stack.pop()
        if str(first).isalpha():
            first = nums[ord(first)]
        if str(second).isalpha():
            second = nums[ord(second)]
        temp = 0
        if char == "+":
            temp = first + second
        if char == "-":
            temp = first - second
        if char == "*":
            temp = first * second
        if char == "/":
            temp = first / second
        stack.append(temp)

print("%.2f" % stack[0])


# coding:utf-8
import datetime
from dateutil import rrule

class Betdate:
    def __init__(self, start_time, end_time):
        self.start = datetime.datetime.strptime(start_time, "%Y, %m, %d")
        self.end = datetime.datetime.strptime(end_time, "%Y, %m, %d")

    def days(self):
        d = self.end - self.start
        return d.days if d.days > 0 else False

    def weeks(self):
        weeks = rrule.rrule(rrule.WEEKLY, dtstart=self.start, until=self.end)
        return weeks.count()

Date = Betdate("2021, 3, 22", "2022, 3, 12")
Date.start = datetime.datetime.today() #实例属性的修改
print(Date.__dict__) #打印实例属性
d = Date.days()
w = Date.weeks()
print(d,w)


from environment import Environment
from config import Config

class Evaluator() :

    @staticmethod
    def evaluate(generation_num,genome,env,steps,render=False) :

        genome.create_model()
        env.initialize()

        state = env.preprocess(env.reset())

        total_fitness = 0
        for step in range(steps) :
            if(render) :
                env.render()
            action = env.actionProcessor(genome.run(state))
            next_state,fitness,done,info = env.step(action)

            total_fitness += fitness
            state = env.preprocess(next_state)
            if(done) :
                env.close()
                genome.fitness = total_fitness
                print('Genome {} , fitness : {}'.format(generation_num,total_fitness))
                return genome

        env.close()
        genome.fitness = total_fitness
        print('Genome {} , fitness : {}'.format(generation_num,total_fitness))
        return genome


from image_convert import ImageConvert
from pickle import load
from os import path

def calculate_distance(sub_picture_values, network_outputs):
    values_sum = 0
    for sub_picture_value, network_output in zip(sub_picture_values, network_outputs):
        values_sum += (sub_picture_value - network_output) ** 2
    return values_sum ** 0.5

def filter_relative_distances(sub_picture_values, network_outputs, epsilon):
    network_output_size = len(network_outputs)
    successes = 0
    for sub_picture_value, network_output in zip(sub_picture_values, network_outputs):
        if abs(sub_picture_value - network_output) <= epsilon:
            successes += 1
    return successes / float(network_output_size)

with open("Best K Models\\model_num_-292-_hidden_size_-99-_learning_rate_-0.1.pickle", 'rb') as model_file:
    network = load(model_file)

larry_picture_converter = ImageConvert(path.join('Images', path.join('Person', 'Larry_Manevitz.png')), (256, 256), (30, 30), 'L')
larry_sub_pictures = larry_picture_converter.get_sub_images_data_list()

person_testing_results = []
for larry_sub_picture in larry_sub_pictures:
    network.update_input_layer_neurons_value(larry_sub_picture)
    person_testing_results.append(network.calculate_net_output())

approximation_epsilon = 0.2
distance_result = 0
filter_result = []
for person_testing_result, larry_sub_picture in zip(person_testing_results, larry_sub_pictures):
    distance_result += calculate_distance(person_testing_result, larry_sub_picture)
    filter_result.append(filter_relative_distances(person_testing_result, larry_sub_picture, approximation_epsilon))
print("CALCULATE DISTANCE RESULT = ", distance_result)
print("FILTER RELATIVE DISTANCES RESULT = ", sum(filter_result) / 64.0)

print("displaying original larry picture")
larry_picture_converter.show_image_on_screen(person_testing_results)

print("displaying larry picture after network test run")
larry_picture_converter.show_image_on_screen(larry_sub_pictures)


import os

def iterate_n_days(data, n_days):
    population = [0] * 9
    # population is a list of quantities - index being days until reproduction
    for x in data:
        population[x] += 1
    for _ in range(n_days):
        n_new = population.pop(0)
        population[6] += n_new
        population.append(n_new)
    return sum(population)

def task_1(data):
    return iterate_n_days(data, n_days=80)

def task_2(data):
    return iterate_n_days(data, n_days=256)

def main():
    for line in open(os.getcwd() + '/data/day_06.txt'):
        data = [int(x) for x in line.split(',')]
    print(task_1(data))
    print(task_2(data))

if __name__ == '__main__':
    main()


import argparse
import json
from collections import OrderedDict
from pathlib import Path
from xml.etree.ElementTree import parse

import spacy
from simalign import SentenceAligner
from tqdm import tqdm

myaligner = SentenceAligner(model="bert", token_type="bpe", matching_methods="mai")

def load_ali(file: Path):
    root = parse(file).getroot()
    fromdoc = root.attrib['fromDoc']
    todoc = root.attrib['toDoc']
    links = []
    for link in root:
        lstr = link.attrib['xtargets']
        t = lstr.split(';')
        assert len(t) == 2
        links.append((t[0].split(), t[1].split()))
    return fromdoc, todoc, links

def load_text(file: Path):
    root = parse(file).getroot()
    ret = OrderedDict()
    for sent in root:
        ret[sent.attrib['id']] = sent.text.strip()
    return ret

nlp = {'pl': spacy.load('pl_spacy_model_morfeusz'), 'en': spacy.load('en_core_web_sm')}

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('alidir', type=Path)
    parser.add_argument('outfile', type=Path)

    args = parser.parse_args()

    alidir = args.alidir

    ret = []
    for ali in tqdm(list(alidir.glob('*.alignment.xml'))):
    # for ali in tqdm([alidir/'EN0001.en.pl.alignment.xml',alidir/'PL0001.en.pl.alignment.xml']):
        tok = ali.name.split('.')
        assert len(tok) == 5
        name = tok[0]
        # from_lang = tok[1]
        # to_lang = tok[2]
        from_file, to_file, ali_links = load_ali(ali)
        from_doc = load_text(alidir / from_file)
        to_doc = load_text(alidir / to_file)
        from_lang = from_file.split('.')[-2]
        to_lang = to_file.split('.')[-2]

        phrases = []
        for link in ali_links:
            from_txt = []
            for l in link[1]:
                from_txt.append(from_doc[l].strip())
            from_txt = ' '.join(from_txt)
            if len(from_txt) == 0:
                from_txt = '**blank**'

            doc = nlp[from_lang](from_txt)
            from_lemma = []
            n = False
            for token in doc:
                if not n:
                    from_lemma.append(token.lemma_)
                else:
                    from_lemma[-1] = from_lemma[-1] + token.lemma_
                if token.whitespace_:
                    n = False
                else:
                    n = True

            to_txt = []
            for l in link[0]:
                to_txt.append(to_doc[l].strip())
            to_txt = ' '.join(to_txt)
            if len(to_txt) == 0:
                to_txt = '**blank**'

            doc = nlp[to_lang](to_txt)
            to_lemma = []
            n = False
            for token in doc:
                if not n:
                    to_lemma.append(token.lemma_)
                else:
                    to_lemma[-1] = to_lemma[-1] + token.lemma_
                if token.whitespace_:
                    n = False
                else:
                    n = True

            alignment = myaligner.get_word_aligns(from_txt, to_txt)

            phrases.append({
                'words': {
                    from_lang: [{'orig': x[0], 'lemma': x[1], 'corr': None, 'hl': False} for x in
                                zip(from_txt.split(), from_lemma)],
                    to_lang: [{'orig': x[0], 'lemma': x[1], 'corr': None, 'hl': False} for x in
                              zip(to_txt.split(), to_lemma)]
                },
                'alignment': alignment['inter']
            })

        ret.append({
            'name': name,
            'direction': [from_lang, to_lang],
            'phrases': phrases
        })

    with open(args.outfile, 'w') as f:
        json.dump(ret, f, indent=4)


temp1=num=53896
foo=0
while temp1>0:
    min=temp1%10
    temp2=temp1//10
    temp1=min
    p=10
    while temp2>0:
        a=temp2%10
        if a<min:
            temp1=min*p+temp1
            min=a
        else:
            temp1=a*p+temp1
        p=p*10
        temp2=temp2//10
    foo=foo*10+min
    temp1=temp1//10
print(foo)


from django.dispatch import receiver
from django.db.models.signals import post_delete
from dataset.models import Question, Answer

@receiver(post_delete, sender=Question)
def post_delete_question(sender, instance, *args, **kwargs):
    if instance.content:
        instance.content.delete()

@receiver(post_delete, sender=Answer)
def post_delete_answer(sender, instance, *args, **kwargs):
    if instance.content:
        instance.content.delete()


import cv2
import pynput
from pynput.keyboard import Key, Controller
from ContinuousGesturePredictor import continuousGesturePredictor
#Open notes and test inputs
#Requires pynput installed -> pip install pynput
#Instead of pynput, other libraries can be used according to your preference: keyboard, pyautogui
keyboard = Controller()
camera=cv2.VideoCapture(0)
predizGesto=continuousGesturePredictor()
while(True):
    _, frame = camera.read()
    predizGesto.main(frame)
    prediction = predizGesto.className

    if predizGesto.keypress == ord("q"): #Press 'q' to exit
        break

    #Assign actions for each prediction
    if prediction == "Fist":
        keyboard.press('a')
        keyboard.release('a')

    elif prediction == "Joinha":
        keyboard.press('b')
        keyboard.release('b')

    elif prediction == "Ok":
        keyboard.press('c')
        keyboard.release('c')

    elif prediction == "Palm":
        keyboard.press(Key.space)
        keyboard.release(Key.space)

    elif prediction == "Swing":
        keyboard.press('d')
        keyboard.release('d')


import argparse

rules = '''rule mf
  command = mf '\mode=ljfour; mode_setup; input $in'

rule gftopk
  command = gftopk $in $out

rule texgen
  command = PYTHONPATH=../../tasks/build python3 -m gen.texgen $in

rule pdflatex
  command = pdflatex $in

rule convert
  command = convert -density 300 -trim -monochrome -white-threshold 50% -black-threshold 50% $in -quality 100 -gravity center -extent 96x96 -transparent white $out

rule copy
  command = cp $in $out

'''

build = '''
build %s.600gf: mf ../../data/metafont/%s/%s/%s.mf
build %s.600pk: gftopk %s.600gf
build %s.tex: texgen %s.600pk
build %s.pdf: pdflatex %s.tex
build %s.png: convert %s.pdf
build ../../data/glyph/%s/%s/%s.png: copy %s.png
'''

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--build-directory", type=str, default='tasks/build', help="build directory")
opt = parser.parse_args()

if __name__ == '__main__':
    import os.path as pth
    from glob import glob

    script = rules
    for mffile in glob('data/metafont/*/*/*.mf'):
        chname = pth.basename(mffile).replace('.mf', '')
        params = list([chname for _ in list(range(build.count('%s')))])
        params[1] = chname[0]
        params[2] = chname[1]
        params[-4] = chname[0]
        params[-3] = chname[1]
        content = build % tuple(params)
        script += content

    with open('%s/build.ninja' % opt.build_directory, 'w') as f:
        f.write(script)
        f.flush()


'''
Created on 19 feb 2018

@author: Serena Sensini
'''

class ARCHEOZOOLOGY(object):
	#def __init__"
	def __init__(self,
	id_,
	code,
	n_rilievo,
	n_codice,
	anno,
	sito,
	quadrato,
	us,
	periodo,
	fase,
	specie,
	classe,
	ordine,
	famiglia,
	elemnto_anat_generico,
	elem_specifici,
	taglia,
	eta,
	lato,
	lunghezza,
	larghezza,
	spessore,
	porzione,
	peso,
	coord_x,
	coord_y,
	coord_z,
	azione,
	modulo_osso
	):
		self.id_=id_
		self.code=code
		self.n_rilievo=n_rilievo
		self.n_codice=n_codice
		self.anno=anno
		self.sito=sito
		self.quadrato=quadrato
		self.us=us
		self.periodo=periodo
		self.fase=fase
		self.specie=specie
		self.classe=classe
		self.ordine=ordine
		self.famiglia=famiglia
		self.elemnto_anat_generico=elemnto_anat_generico
		self.elem_specifici=elem_specifici
		self.taglia=taglia
		self.eta=eta
		self.lato=lato
		self.lunghezza=lunghezza
		self.larghezza=larghezza
		self.spessore=spessore
		self.porzione=porzione
		self.peso=peso
		self.coord_x=coord_x
		self.coord_y=coord_y
		self.coord_z=coord_z
		self.azione=azione
		self.modulo_osso=modulo_osso

	#def __repr__"
	def __repr__(self):
		return "<ARCHEOZOOLOGY('%d', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%r', '%r', '%r', '%r', '%s', '%s')>" % (
		self.id_,
		self.code,
		self.n_rilievo,
		self.n_codice,
		self.anno,
		self.sito,
		self.quadrato,
		self.us,
		self.periodo,
		self.fase,
		self.specie,
		self.classe,
		self.ordine,
		self.famiglia,
		self.elemnto_anat_generico,
		self.elem_specifici,
		self.taglia,
		self.eta,
		self.lato,
		self.lunghezza,
		self.larghezza,
		self.spessore,
		self.porzione,
		self.peso,
		self.coord_x,
		self.coord_y,
		self.coord_z,
		self.azione,
		self.modulo_osso
		)


#!/usr/bin/env python3

# reproducible results
import numpy as np
import random as rn
import tensorflow as tf
np.random.seed(1337)
rn.seed(1337)
tf.set_random_seed(1337)
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['PYTHONHASHSEED'] = '0'
from keras import backend as bke
s = tf.Session(graph=tf.get_default_graph())
bke.set_session(s)

# the rest of imports
import sys, random, gc, keras
sys.path.append('../Lib/')
sys.dont_write_bytecode = True
from sklearn.metrics import f1_score
from keras.callbacks import EarlyStopping
from sklearn.model_selection import train_test_split

# ignore sklearn warnings
def warn(*args, **kwargs):
  pass
import warnings
warnings.warn = warn

def sample(params):
  """Sample a configuration from param space"""

  config = {}

  for param, value in params.items():
    if hasattr(value, 'rvs'):
      # this is a scipy.stats distribution
      config[param] = value.rvs()
    else:
      # this is a tuple
      config[param] = random.choice(value)

  return config

def run(
  make_model,  # function that returns a keras model
  fixed_args,  # make_model and other fixed arguments
  param_space, # possible hyperparameter values
  x_train,     # training examples
  y_train,     # training labels
  x_val=None,  # validation examples
  y_val=None,  # validation labels
  n=100,       # number of iterations
  verbose=0):  # suppress output
  """Random search"""

  # need a validation set?
  if x_val == None:
    x_train, x_val, y_train, y_val = \
      train_test_split(x_train, y_train, test_size=0.2)

  # configurations and their scores
  config2score = {}

  for i in range(n):

    # prevent OOM errors
    gc.collect()
    bke.clear_session()

    config = sample(param_space)
    args = config.copy()
    args.update(fixed_args)

    model = make_model(args)

    erstop = EarlyStopping(
      monitor='val_loss',
      min_delta=0,
      patience=2,
      restore_best_weights=True)

    optim = getattr(keras.optimizers, args['optimizer'])
    model.compile(
      loss=args['loss'],
      optimizer=optim(lr=10**args['log10lr']),
      metrics=['accuracy'])

    model.fit(
      x_train,
      y_train,
      validation_data=(x_val, y_val),
      epochs=args['epochs'],
      batch_size=args['batch'],
      verbose=0,
      callbacks=[erstop])

    # add effective number of epochs to config
    if erstop.stopped_epoch > 0:
      config['epochs'] = erstop.stopped_epoch - 1
    else:
      config['epochs'] = 0

    # probability for each class; (test size, num of classes)
    distribution = model.predict(x_val)

    # turn into an indicator matrix
    distribution[distribution < 0.5] = 0
    distribution[distribution >= 0.5] = 1

    f1 = f1_score(y_val, distribution, average='macro')
    config2score[tuple(config.items())] = f1

    if verbose == 1:
      print('[%d] %s' % (i + 1, config))
      print('[%d] score: %.3f' % (i + 1, f1))

  return config2score

if __name__ == "__main__":

  pass


import random as r
import  turtle as t

t.speed(0)
t.shape('turtle')
t.color('red')

x=1
while x < 200:
    t.right(r.randint(-180,180))
    t.forward(r.randint(4,40))
    x+=1


# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

AUTHOR = u'CCC-CH'
SITENAME = u'CCC-CH'
SITEURL = u'https://www.ccc-ch.ch'
TIMEZONE = u'Europe/Zurich'
DEFAULT_LANG = u'de'
DEFAULT_DATE_FORMAT = '%a %d. %B %Y'

# Page path
PAGE_PATHS = ['pages']

# Menu
MENUITEMS = (
              ('Home', 'index.html', None),
              ('CCC-CH', '#', [
                ('FAQ', 'faq.html'),
                ('Statuten', 'statuten.html'),
                ('Mitglieder', 'members.html'),
                ('Pressereaktionen', 'category_pressreview.html'),
              ]),
              ('Medienmitteilungen', 'category_medien.html', None),
              ('Intern', '#', [
                ('Protokolle', 'protokolle.html'),
                ('Mitgliederbeiträge', 'mitgliederbeitraege.html'),
                ('Gettogether', 'gettogether.html'),
                ('Schleuder', 'schleuder.html'),
              ]),
            )

I18N_SUBSITES = {
    'de': {
        'LOCALE': "de_CH.UTF-8",
        'STATIC_PATHS': [
            'files'
        ],
        'MENUITEMS': MENUITEMS,
    },
    'fr': {
        'LOCALE': "fr_CH.UTF-8",
        'STATIC_PATHS': [
            'files'
        ],
        'MENUITEMS': [
            ('Home', 'index.html', None),
            ('CCC-CH', '#', [
                ('Statuts', 'statuten.html'),
            ]),
        ],
    },
    'it': {
        'LOCALE': "it_CH.UTF-8",
        'STATIC_PATHS': [
            'files'
        ],
        'MENUITEMS': [
            ('Home', 'index.html', None),
            ('CCC-CH', '#', [
                ('Statuti', 'statuten.html'),
            ]),
        ],
    },
    'en': {
        'LOCALE': "en_GB.UTF-8",
        'STATIC_PATHS': [
            'files'
        ],
        'MENUITEMS': [
            ('Home', 'index.html', None),
            ('Press releases', 'category_media.html', None),
        ],
    }
}

# Sole author and don't use categories ... disable these features
#AUTHOR_SAVE_AS = ''
#AUTHORS_SAVE_AS = ''
#CATEGORY_SAVE_AS = ''
#CATEGORIES_SAVE_AS = ''

# don't show categories and pages in the menu
DISPLAY_PAGES_ON_MENU = False
DISPLAY_CATEGORIES_ON_MENU = False

# Feed generation is usually not desired when developing
FEED_ALL_RSS = None
FEED_ALL_ATOM = None
FEED_RSS = 'feeds/rss.xml'
FEED_ATOM = 'feeds/atom.xml'
CATEGORY_FEED_ATOM = 'feeds/atom_%s.xml'
CATEGORY_FEED_RSS = 'feeds/rss_%s.xml'
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

# URL settings
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
ARTICLE_URL = '{slug}.html'
PAGE_URL = '{slug}.html'
PAGE_SAVE_AS = '{slug}.html'
TAG_URL = 'tag-{slug}.html'
TAG_SAVE_AS = 'tag-{slug}.html'
TAGS_URL = 'tags.html'
TAGS_SAVE_AS = 'tags.html'
ARCHIVES_URL = 'archives.html'
ARCHIVES_SAVE_AS = 'archives.html'
CATEGORY_URL = 'category_{slug}.html'
CATEGORY_SAVE_AS = 'category_{slug}.html'

# Contact
EMAIL_ADDR = 'webmaster@ccc-ch.ch'

# Plugins
PLUGIN_PATHS = ['plugins']
PLUGINS = ['i18n_subsites']

# Theme
THEME = 'theme'
STATIC_PATHS = ['images', 'media', 'articles', 'docs', 'extra/robots.txt', 'extra/favicon.ico', 'extra/htaccess']
PATH_METADATA = 'pages/(?P<path>.*)\..*'
EXTRA_PATH_METADATA = {
    'extra/robots.txt': {'path': 'robots.txt'},
    'extra/favicon.ico': {'path': 'favicon.ico'},
    'extra/htaccess': {'path': '.htaccess'},
}

# Licence
LICENCE_NAME = 'BY-NC-SA'
LICENCE_URL = 'http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US'
LICENCE_URL_IMG = 'http://i.creativecommons.org/l/by-nc-sa/3.0/80x15.png'

# Tag cloud
TAG_CLOUD_STEPS = 4


import pytchat
from openpyxl import Workbook, load_workbook
import os
from pathlib import Path

original = input('Click share on the youtube live and then paste the link here: ')
link = original.replace('https://www.youtube.com/watch?v=','')
link = link.replace('https://www.youtube.com/live/', '')
link = link.replace('?feature=share','')

file_name = input('Enter the name of the excel file without a file extension: ') + ".xlsx"
location = input('Enter the file location or leave blank to place inside this directory: ')

if location == '':
    current = Path(os.getcwd())
    location = str(current.parents[0])+'\\'+file_name

try:
    workbook = load_workbook(location)
    worksheet = workbook.active
except:
    workbook = Workbook()
    worksheet = workbook.active
    worksheet['A1'].value = original
    worksheet['A2'].value = 'Date and time'
    worksheet['B2'].value = 'Username'
    worksheet['C2'].value = 'Message'
    worksheet['D2'].value = 'Amount'
    workbook.save(location)

for cell in worksheet["A"]:
    if cell.value is None:
        break
else:
    row = cell.row + 1

chat = pytchat.create(video_id=link)
while chat.is_alive():
    try:
        for c in chat.get().sync_items():
            if c.type == 'superChat':
                print(c.datetime, '[', c.author.name, '] - ', c.message, '-', c.amountString)
                worksheet['A'+str(row)].value = c.datetime
                worksheet['B'+str(row)].value = c.author.name
                worksheet['C'+str(row)].value = c.message
                worksheet['D'+str(row)].value = c.amountString
                workbook.save(location)
                row = row+1
    except AttributeError:
        print("Error occurred. Restarting...")
        chat = pytchat.create(video_id=link.replace('https://www.youtube.com/watch?v=',''))


import imageRead as ir
num_of_black = 0

# https://www.kylepaulsen.com/stuff/NetpbmViewer/

fileName = "BoatPic.pbm"
#fileName = "A.pbm"

metaData = ir.read(fileName)
maxSize = metaData[0]
image = metaData[1]

for r in range(maxSize):
    print(str(image[r]))
    for i in range(len(image[r])):
        if image[r][i]:
            num_of_black += 1

# Pixel count code goes here

print("\nNumber of black pixels = ", num_of_black)


# -*- coding: utf-8 -*-
"""
Created on Tue Jul  2 03:29:47 2019

@author: NRAD
"""

import numpy as np

import pandas as pd

import os

path=r'D:\medical datasets\breast-cancer-dataset-from-breakhis\fold1\test\40X\B_40X'

pngs_test = []

# r=root, d=directories, f = files

for r, d, f in os.walk(path):
    for file in f:
        pngs_test.append(file)

print(len(pngs_test))

zeros=np.zeros((len(pngs_test),2))

df=pd.DataFrame(zeros,columns=['binary','multiclass'])

print('okay')

for i in range(len(pngs_test)):

    index1=pngs_test[i].index('_')

    index2=pngs_test[i].index('_',index1+1)

    index3=pngs_test[i].index('-')

    binary_class=pngs_test[i][index1+1]

    multiclass=pngs_test[i][index1+3:index3]

    if binary_class=='B':

        df['binary'][i]=0

    else:

        df['binary'][i]=1

    if multiclass==str('A'):

        df['multiclass'][i]=2

    elif multiclass==str('F'):

        df['multiclass'][i]=3

    elif multiclass==str('PT'):

        df['multiclass'][i]=4

    elif multiclass==str('TA'):

        df['multiclass'][i]=5

    elif multiclass==str('DC'):

        df['multiclass'][i]=6

    elif multiclass==str('LC'):

        df['multiclass'][i]=7

    elif multiclass==str('MC'):

        df['multiclass'][i]=8

    elif multiclass==str('PC'):

        df['multiclass'][i]=9

name=r'C:\Users\NRAD.NRAD-28\Desktop\codec_test_csv.csv'

df.to_csv(name)


# link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == "":
            return 0
        longest = 1
        for i in range(len(s)-1):
            for j in range(i+1+longest, len(s)+1):
                lencurr = len(s[i:j])
                if len(set(s[i:j]))<lencurr:
                    break
                if lencurr>longest:
                    longest = lencurr
        return longest

Longest Substring Without Repeating Characters/submission.py


import numpy as np
from bob.gradiant.core.classes.evaluation.metrics.metric import Metric

class Apcer(Metric):
    """
    Attack Presentation Classification Error Rate: proportion of attack presentations incorrectly classified as bona fide presentations
    """
    def __init__(self, name, threshold=None):
        super(Apcer, self).__init__(name, 'APCER')
        self.threshold = threshold
        self.threshold_needed = True

    def compute(self, y_score, y_true):
        attack_ids = np.unique(y_true)
        attack_ids = np.trim_zeros(attack_ids)  # Remove genuine labels
        result_attacks = []
        for ind_attack in attack_ids:
            array_attacks = y_score[y_true == ind_attack]
            result = array_attacks[array_attacks >= self.threshold].shape[0] / float(len(array_attacks))
            result_attacks.append(result)
        return 100*max(result_attacks), self.threshold

    def set_threshold(self, threshold):
        self.threshold = threshold


# For-loops

for i in range(10):
    if i == 5:
        continue
    print(i)
    if i == 7:
        break
else:
    print('In else')

print('Done')

values = [1, 2, 3, 'Anna', True]

for i, value in enumerate(values):
    print('hej', i, value)

for i in range(len(values)):
    print('hej', i, values[i])

# Use range to create a list

values = list(range(2, 100, 4))

print(values)

# if-statement
x = 10
y = 20

if x > 10 or y == 20:
    print('Bigger than 10')
else:
    print('Less or equal to 10')

grade = 25

if grade < 10:
    print('bad')
elif grade < 20:
    print('ok')
elif grade < 30:
    print('good')

# While-loop

x = 10

while x < 44:
    print(x)
    x *= 2


from app.Operation import Operation, OperationMenu

class TensorOperation(Operation):
    def __init__(self, operand0, operand1, operator):
        super().__init__(operand0, operand1, operator)

class TensorOperationMenu(OperationMenu):
    def __init__(self):
        pass

    def getOperations(self):

        import torch

        operations = {
            'Addition': torch.add,
            'Subtraction': torch.sub,
            'Multiplication': torch.mul,
            'Division': torch.div,
            'True Division': torch.true_divide,
            'Floor Division': torch.floor_divide,
            'Remainder': torch.remainder,
            'Modulo': torch.fmod,
            'Power': torch.pow,
            'Less Than': torch.lt,
            'Less Than or Equal To': torch.le,
            'Greater Than': torch.gt,
            'Greater Than or Equal To': torch.ge,
            'Equal': torch.eq,
            'Not Equal': torch.ne,
            'Maximum': torch.max,
            'Minimum': torch.min,
            'Element-wise Maximum': torch.maximum,
            'Element-wise Minimum': torch.minimum,
            'Copysign': torch.copysign,
            'Arc Tangent 2': torch.atan2,
            'Euclidean Distance': torch.dist,
            'Inner Product': torch.inner,
            'Kronecker Product': torch.kron,
        }

        return operations


from flask import Flask, jsonify, abort

app = Flask(__name__)
users = [
    {
        "id": 1,
        "nome": "Fulano",
        "idade": 30
    },
    {
        "id": 2,
        "nome": "Ciclano",
        "idade": 40
    }
]

@app.route('/users/api/1.0/users', methods=['GET'])
def get_users():
    return jsonify({'users': users})

@app.route('/users/api/1.0/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = [u for u in users if u["id"] == user_id]
    if len(user) == 0:
        return abort(404)
    return jsonify({"user": user[0]})


import random
import copy
from itertools import cycle

class Conway:

     def __init__ (self,textlistobject=None,displaydictobject=None,cells=None,livechar='█',deadchar=' ',constitute=True,y_min=0,y_max=None,x_min=0,x_max=None,randomizing=True,changing=True):

          if displaydictobject is None:
               displaydictobject = {}
          if textlistobject and not displaydictobject:
               for y_pos, y in enumerate(textlistobject):
                    for x_pos,x in enumerate(y):
                         displaydictobject[(y_pos,x_pos)] = textlistobject[y_pos][x_pos]

          if not y_max:
               self.max_y = max(c[0] for c in displaydictobject)
          else:
               self.max_y = y_max
          if not x_max:
               self.max_x = min(c[1] for c in displaydictobject)
          else:
               self.max_x = x_max
          self.y_min = y_min
          self.x_min = x_min
          self.cells = {}
          if cells and isinstance(cells,dict):
               self.cells = cells
          self.deadchar = deadchar
          self.random_mode = randomizing
          self.livechar = livechar
          self.old_image = {}
          self.mode_iterator = cycle(range(11))
          self.mode = next(self.mode_iterator)
          self.modes = {}
          self.modes[0] = {0:[2,3],
                           1:[3],
                           2:'life'}
          self.modes[1]  = {0:[1,3,5,7],
                            1:[1,3,5,7],
                            2:'replicator'}
          self.modes[2]  = {0:[4],
                            1:[2,5],
                            2:'no name 1'}
          self.modes[3]  = {0:[0,1,2,3,4,5,6,7,8],
                            1:[3],
                            2:'life without death'}
          self.modes[4]  = {0:[3,4],
                            1:[3,4],
                            2:'34 life'}
          self.modes[5]  = {0:[5,6,7,8],
                            1:[3,5,6,7,8],
                            2:'Diamoeba'}
          self.modes[6]  = {0:[1,2,5],
                            1:[3,6],
                            2:'2*2'}
          self.modes[7]  = {0:[2,3],
                            1:[3,6],
                            2:'HighLife'}
          self.modes[8]  = {0:[3,4,6,7,8],
                            1:[3,6,7,8],
                            2:'Day&Night'}
          self.modes[9]  = {0:[2,4,5],
                            1:[3,6,8],
                            2:'Morley'}
          self.modes[10]  = {0:[4,6,7,8],
                            1:[3,5,6,7,8],
                            2:'Anneal'}

          self.odds = {1:(1000,1000),
                       2:(1000,1000),
                       3:(1000,1000),
                       4:(1000,1000)}
          self.displaydictobject = displaydictobject
          self.distance = 1
          self.odd_factor = 100
          self.background = copy.deepcopy(self.displaydictobject)
          self.changing = changing
          if cells and isinstance(cells,(set,list)):
                    for c in cells:

                         if self.get_char(c[0],c[1]) == livechar:
                              self.cells[c] = True
                         elif self.get_char(c[0],c[1]) == deadchar:
                              self.cells[c] = False

                    self.y_min = min([c[0] for c in cells])
                    self.max_y = max([c[0] for c in cells])
                    self.x_min = min([c[1] for c in cells])
                    self.max_x = max([c[1] for c in cells])

          elif constitute:

               for y in  range(self.y_min,self.max_y):
                    for x in range(self.x_min,self.max_x):

                         if self.get_char(y,x)  == livechar:
                              self.cells[(y,x)] = True
                         elif self.get_char(y,x) == deadchar:
                              self.cells[(y,x)] = False
          for c in self.cells:
               self.old_image[c] = self.get_char(c[0],c[1])

     def get_char (self,y_pos,x_pos):

          if (y_pos,x_pos) in self.displaydictobject:
               return self.displaydictobject[(y_pos,x_pos)][0]
          else:
               return self.deadchar

     def change_odds (self,odds=(920,1000),key=1):
          if isinstance(odds,tuple) and key in [1,2,3,4]:
               self.odds[key] = odds

     def change_distance (self,distance=1):
          if 0 <= distance < 5:
               self.distance = distance

     def get_properties (self):
          return self.odds,self.distance
     def change_mode (self):
          self.mode = next(self.mode_iterator)
          return self.modes[self.mode]
     def change_random (self):
          self.random_mode = not self.random_mode
          return self.random_mode
     def burst (self):

          y = random.randrange(self.y_min+5,self.max_y-5)
          x = random.randrange(self.x_min+5,self.max_x-5)

          if self.surrounding_count(self.surrounding_coords((y,x),distance=3)) == 0:

               for c in self.surrounding_coords((y,x),distance=5):
                    self.cells[c] = self.randomize(random.choice([False,True]),(95-int(((abs(c[0]-y))+(abs(c[1]-x)))/2)*20,100))

     def randomize (self,boolean,odds=None):
          if self.random_mode:

               if not odds:
                    odds = self.odds
               if random.randint(0,odds[1]+1) <= odds[0]:
                    return boolean
               else:
                    return not boolean
          else:
               return boolean

     def surrounding_coords (self,coord,distance=1):
          y = coord[0]
          x = coord[1]

          surround = []
          for y_off in range(-distance,distance+1):
               for x_off in range(-distance,distance+1):
                    if abs(y_off) + abs(x_off) != 0:
                         if self.y_min <= y+y_off < self.max_y and self.x_min <= x+x_off < self.max_x:
                              surround.append((y+y_off,x+x_off))
          return surround

     def surrounding_count (self,surround=None):

          if not surround:
               surround = []
          count = 0
          for s in surround:
               if s in self.cells:
                    if self.cells[s]:
                         count += 1
          return count

     def get_surrounding (self,coord):
          return self.surrounding_count(self.surrounding_coords(coord,distance=self.distance))

     def cycle_through_cells (self):

          if self.changing:
               if random.choice(range(50)) == 25:
                    self.random_mode = not self.random_mode

          new_cells = {}

          for cell in self.cells:

               if self.cells[cell]:

                    if self.get_surrounding(cell) in self.modes[self.mode][0]:
                         new_cells[cell] = self.randomize(True,odds=self.odds[1])

                    else:
                         new_cells[cell] = self.randomize(False,odds=self.odds[2])

               else:
                    if self.get_surrounding(cell) in self.modes[self.mode][1]:
                         new_cells[cell] = self.randomize(True,odds=self.odds[3])

                    else:
                         new_cells[cell] = self.randomize(False,odds=self.odds[4])

          self.cells = new_cells

     def generate (self):

          self.cycle_through_cells()

          for y in range(self.y_min,self.max_y):
               segment = ''
               for x in range(self.x_min,self.max_x):
                    if (y,x) in self.cells:
                         self.displaydictobject[(y,x)] = ({False:self.deadchar,True:self.livechar}[self.cells[(y,x)]],None,None)
                    else:
                         if (y,x) in self.background:
                              self.displaydictobject[(y,x)] = self.background[(y,x)]

          return self.displaydictobject

if __name__ == '__main__':

     textlistobject =['                    '*10,
                      '                    '*10,
                      '                    '*10,
                      '                    '*10,
                      '                    '*10,
                      '                    '*10,
                      '                    '*10]*5

     x = Conway(textlistobject)
     print('\n'.join(textlistobject))

     while True:

          textlistobject = x.generate()
          x.burst()
          print('\n'.join(x.textlistobject))

          input('?')


from __future__ import (absolute_import, division, print_function, unicode_literals)

#Fundamentals
import statistics
import numpy as np
from collections import namedtuple
import filterpy.stats as stats
from numpy.random import randn
from filterpy.stats import plot_gaussian_pdf, gaussian
import random

#filtering

#https://filterpy.readthedocs.io/en/latest/#filterpy-gh
from filterpy.gh import GHFilter
#https://filterpy.readthedocs.io/en/latest/discrete_bayes/discrete_bayes.html
from filterpy.discrete_bayes import predict, normalize
from filterpy.discrete_bayes import update
#https://filterpy.readthedocs.io/en/latest/#filterpy-kalman
import filterpy.kalman as kf
from filterpy.kalman import KalmanFilter
from filterpy.common import Q_discrete_white_noise

#Data generation for Kalman filter:
import copy
import math
#Plotting
import matplotlib as mpl
import plotly.graph_objects as go
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt

def plotter(data_y,hypothesis_y, error_1, error_2):
  fig = go.Figure()
  # Add traces
  fig.add_trace(go.Scatter(y=data_y,
                      mode='markers',
                      name='data',
                      error_y=dict(
                      type='data',
                      symmetric=False,
                      array=error_1,
                      arrayminus=error_2)))

  fig.add_trace(go.Scatter(y=hypothesis_y,
                      mode='lines',
                      name='hypothesis'))

  fig.update_layout(
      autosize=False,
      width=800,
      height=300,
      margin=dict(
          l=5,
          r=5,
          b=10,
          t=10,
          pad=4
      ),
      paper_bgcolor="White",
  )
  fig.show()

def plotter_2(measurements, predictions, estimations,true_data):
  fig = go.Figure()
  colors = ['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']
  # Add traces
  fig.add_trace(go.Scatter(x=list(range(1,len(estimations))) , y=measurements,
                      mode='markers',
                      name='measurements',line=dict(color='red', width=2)))
  fig.add_trace(go.Scatter(x=list(range(1,len(estimations))) , y=predictions,
                      mode='lines+markers',
                      name='predictions',
                      line=dict(color=colors[2], width=2,dash='dash')))
  fig.add_trace(go.Scatter(x=list(range(0,len(estimations))) , y=estimations,
                      mode='lines+markers',
                      name='estimations',
                      line=dict(color=colors[1], width=2,dash='dot')))
  fig.add_trace(go.Scatter(x=list(range(0,len(estimations))) , y=true_data,
                      mode='lines',
                      line=dict(color=colors[0], width=2),
                      name='Truth'))

  fig.update_layout(
      autosize=False,
      width=800,
      height=300,
      margin=dict(
          l=5,
          r=5,
          b=10,
          t=10,
          pad=4
      ),
      paper_bgcolor="White",
  )
  fig.show()

# Aux. function for plotting:
def plot_products(g1, g2):
    plt.figure(figsize=(7,3), dpi=100)
    product = gaussian_multiply(g1, g2)

    xs = np.arange(5, 15, 0.1)
    ys = [stats.gaussian(x, g1.mean, g1.var) for x in xs]
    plt.plot(xs, ys, label='$\mathcal{N}$'+'$({},{})$'.format(g1.mean, g1.var))

    ys = [stats.gaussian(x, g2.mean, g2.var) for x in xs]
    plt.plot(xs, ys, label='$\mathcal{N}$'+'$({},{})$'.format(g2.mean, g2.var))

    ys = [stats.gaussian(x, product.mean, product.var) for x in xs]
    plt.plot(xs, ys, label='product', ls='--')
    plt.legend();

def show_legend():
    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

def plot_predictions(p, rng=None, label='Prediction'):
    if rng is None:
        rng = range(len(p))
    plt.scatter(rng, p, marker='v', s=40, edgecolor='r',
                facecolor='None', lw=2, label=label)

def plot_filter(xs, ys=None, dt=None, c='C0', label='Filter', var=None, **kwargs):
    """ plot result of KF with color `c`, optionally displaying the variance
    of `xs`. Returns the list of lines generated by plt.plot()"""

    if ys is None and dt is not None:
        ys = xs
        xs = np.arange(0, len(ys) * dt, dt)
    if ys is None:
        ys = xs
        xs = range(len(ys))

    lines = plt.plot(xs, ys, color=c, label=label, **kwargs)
    if var is None:
        return lines

    var = np.asarray(var)
    std = np.sqrt(var)
    std_top = ys+std
    std_btm = ys-std

    plt.plot(xs, ys+std, linestyle=':', color='k', lw=2)
    plt.plot(xs, ys-std, linestyle=':', color='k', lw=2)
    plt.fill_between(xs, std_btm, std_top,
                     facecolor='yellow', alpha=0.2)

    return lines

def plot_measurements(xs, ys=None, dt=None, color='k', lw=1, label='Measurements',
                      lines=False, **kwargs):
    """ Helper function to give a consistant way to display
    measurements in the book.
    """
    if ys is None and dt is not None:
        ys = xs
        xs = np.arange(0, len(ys)*dt, dt)

    plt.autoscale(tight=False)
    if lines:
        if ys is not None:
            return plt.plot(xs, ys, color=color, lw=lw, ls='--', label=label, **kwargs)
        else:
            return plt.plot(xs, color=color, lw=lw, ls='--', label=label, **kwargs)
    else:
        if ys is not None:
            return plt.scatter(xs, ys, edgecolor=color, facecolor='none',
                        lw=2, label=label, **kwargs),
        else:
            return plt.scatter(range(len(xs)), xs, edgecolor=color, facecolor='none',
                        lw=2, label=label, **kwargs),

def plot_track(xs, ys=None, dt=None, label='Track', c='k', lw=2, **kwargs):
    if ys is None and dt is not None:
        ys = xs
        xs = np.arange(0, len(ys)*dt, dt)
    if ys is not None:
        return plt.plot(xs, ys, color=c, lw=lw, ls=':', label=label, **kwargs)
    else:
        return plt.plot(xs, color=c, lw=lw, ls=':', label=label, **kwargs)

def plot_tracks_2(ps, actual,y_lim=None,
               xlabel='time', ylabel='position',
               title='Kalman Filter', count=10):

    plot_track(actual, c='k')
    plot_filter(range(1, count + 1), ps)

    plt.legend(loc=4)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.show()

gaussian = namedtuple('Gaussian', ['mean', 'var'])
gaussian.__repr__ = lambda s: '𝒩(μ={:.3f}, 𝜎²={:.3f})'.format(s[0], s[1])

def gaussian_multiply(g1, g2):
    #Note that we are using tuples:
    mean = (g1.var * g2.mean + g2.var * g1.mean) / (g1.var + g2.var)
    variance = (g1.var * g2.var) / (g1.var + g2.var)
    return gaussian(mean, variance)

def update(prior, likelihood):
    posterior = gaussian_multiply(likelihood, prior)
    return posterior