import os
import sys
#import matplotlib.pyplot as plt
import numpy as np
#import scipy.stats as stats
import xlwt
import subprocess
import pathlib
import pandas as pd
import time
from random import randint
from vehicleClass import Vehicle
from openSpaceClass import OpenSpace
from oneLaneClass import oneLaneObject
from allLanesClass import AllLanes
from datetime import datetime

if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")

listOfSimulation = []
numberOfSimulation = 1

sumoBinary = "/Users/alexandrelissac/Documents/SUMO/bin/sumo-gui"
for i in range(numberOfSimulation):
    randomSeed = str(randint(0,900))
    #randomSeed = "511"
    sumoCmd = [sumoBinary, "-c", "../Resources/FiveLanes/100v.sumocfg", "--lanechange-output", "lanechange.xml" ,"--seed", randomSeed , "--output-prefix", str(i),"--quit-on-end"]
    listOfSimulation.append(sumoCmd)

import traci
import traci.constants as tc

showGraph = False

def convertXMLintoCSV():
    dirName = "/Users/alexandrelissac/Desktop/Project/Simulation/Results/" + datetime.now().strftime('%d-%m-%Y_%H.%M.%S')
    pathlib.Path(dirName).mkdir(parents=True, exist_ok=True)
    for sim in range(numberOfSimulation):
        fileTargetLaneChange = str(sim) + "lanechange.xml"
        fileOutputLaneChnage = str(sim) + "_lanechange.csv"
        fileTargetTripInfo = str(sim) + "tripinfos.xml"
        fileOutputTripInfo = str(sim) + "_tripinfos.csv"
        subprocess.Popen(["python", "/Users/alexandrelissac/Documents/SUMO/tools/xml/xml2csv.py", "/Users/alexandrelissac/Desktop/Project/Simulation/Code/" + fileTargetLaneChange, "--output", dirName + "/" + fileOutputLaneChnage])
        subprocess.Popen(["python", "/Users/alexandrelissac/Documents/SUMO/tools/xml/xml2csv.py", "/Users/alexandrelissac/Desktop/Project/Simulation/Resources/FiveLanes/" + fileTargetTripInfo, "--output", dirName + "/" + fileOutputTripInfo])
    return dirName

def analyseResults(dirName):
    count = 0
    file_exist = True
    wb = xlwt.Workbook()
    ws = wb.add_sheet('Result Simulation')
    ws.write(0,0, "Simulation Number")
    ws.write(0,1, "Average Duration Trip")
    listOfAverageDurationTrip = []

    while(file_exist):
        fileDir = dirName + "/" + str(count) + "_tripinfos.csv"
        if not os.path.exists(fileDir):
            break
        try:
            currentCsv = pd.read_csv(fileDir, delimiter=';')
            currentAverageDurationTrip = np.mean(currentCsv['tripinfo_duration'])
            listOfAverageDurationTrip.append(currentAverageDurationTrip)
            ws.write(count + 1, 0, str(count))
            ws.write(count + 1, 1, str(currentAverageDurationTrip))
            count += 1
        except:
            print("ERROR: " + str(count))
            file_exist = False
            break

    ws.write(count + 1, 0, "Total Average")
    ws.write(count + 1, 1, str(np.mean(listOfAverageDurationTrip)))
    wb.save(dirName + '/results.xls')

def main():
    for idx, simulation in enumerate(listOfSimulation):
        traci.start(simulation)
        allLanes = AllLanes()
        print(str(randomSeed))
        while traci.simulation.getMinExpectedNumber() > 0:
            traci.simulationStep()
            allLanes.handlesAllManoeuvres()
            if traci.simulation.getCurrentTime() == 30000:
                allLanes.triggerRightChangeLane()
    dirName = convertXMLintoCSV() # Convert and get directory of new folder
    time.sleep(3) # Wait for computer to save converted csv file
    analyseResults(dirName)

if __name__ == '__main__':
    main()


from . import views
from django.urls import path

"""
    Url paths extended from from django.urls
"""
app_name = 'products'
urlpatterns = [
    path('products/', views.product_list_view, name='products'),
    path('products/<int:id>/', views.product_get_view),
]


# -*- coding:utf-8 -*-
import sys, pickle, os, random
import numpy as np
import io

## tags, BIO
pre_tag2label = {"O": 0,
             "B-PER": 1, "I-PER": 2,
             "B-LOC": 3, "I-LOC": 4,
             "B-ORG": 5, "I-ORG": 6
             }
tag2label = {u'0': 0,u'1': 1}

def read_corpus(corpus_path):
    """
    read corpus and return the list of samples
    :param corpus_path:
    :return: data
    """
    data = []
    with io.open(corpus_path, encoding='utf-8') as fr:
        lines = fr.readlines()
    sent_, tag_ = [], []
    for line in lines:
        # print("auas    ",line)
        if line != '\n':
            [char, label] = line.strip().split()
            sent_.append(char)
            tag_.append(label)
        else:
            data.append((sent_, tag_))
            sent_, tag_ = [], []

    return data
# root = r"C:\Users\auas\Desktop\auas\大四\毕设\中期"
root = "/home/jinsh/wiki_model/data/"
def auas_read_corpus(corpus_path = "extraction.corpus_all.json"):
    """
    read corpus and return the list of samples
    :param corpus_path:
    :return: data
    """
    data = []
    json_data = io.open(corpus_path, "r", encoding="utf8")
    # r = json.load(json_data)
    rr1 = json_data.readlines()
    rr2 = []
    rr3 = []

    for it in rr1:
        tmp_lst = [item for item in it.split(" ") if not item == ""]
        rr2.append(tmp_lst)
    for it in rr2:
        tmp_lst = [it.replace("\"", "").replace("\n", "") for it in it]
        rr3.append(tmp_lst)
    rr4 = []
    tmp_dic = {}
    got_word = 0
    for idx, it in enumerate(rr3):
        if it[0] == "_id":
            # print(tmp_dic)
            if idx == 0:
                continue
            else:
                rr4.append(tmp_dic)
            tmp_dic = {}
            tmp_dic["word"] = []
            tmp_dic["tag"] = []
        if it[0] == "word":
            tmp_dic["word"].append(it[2])
            got_word = 1
        if it[0] == "tag" and got_word == 1:
            got_word = 0
            tmp_dic["tag"].append(it[2])
    for tmp_dic in rr4[1:]:
        data.append((tmp_dic["word"], tmp_dic["tag"]))
    tot_len = len(data)
    tr = data[:int(0.8*tot_len)]
    tst = data[int(0.8*tot_len):]
    return [tr,tst]
def vocab_build(vocab_path, corpus_path = root + r"\extraction.corpus_all.json", min_count=1):
    """

    :param vocab_path:
    :param corpus_path:
    :param min_count:
    :return:
    """
    tr,tst = auas_read_corpus(corpus_path)
    data = tr+tst
    word2id = {}
    for sent_, tag_ in data:
        for word in sent_:
            if word.isdigit():
                word = '<NUM>'
            # elif ('\u0041' <= word <='\u005a') or ('\u0061' <= word <='\u007a'):
            #     word = '<ENG>'
            if word not in word2id:
                word2id[word] = [len(word2id)+1, 1]
            else:
                word2id[word][1] += 1
    low_freq_words = []
    for word, [word_id, word_freq] in word2id.items():
        if word_freq < min_count and word != '<NUM>' and word != '<ENG>':
            low_freq_words.append(word)
    for word in low_freq_words:
        del word2id[word]

    new_id = 1
    for word in word2id.keys():
        word2id[word] = new_id
        new_id += 1
    word2id['<UNK>'] = new_id
    word2id['<PAD>'] = 0

    print(len(word2id))
    with io.open(vocab_path, 'wb') as fw:
        pickle.dump(word2id, fw,protocol=2)
# auas_data_root = "/home/jinsh/wiki_model/data/"
# auas_data_path = r"C:\Users\auas\Desktop\auas\大四\毕设\中期之后\new_word2id.pkl"
# vocab_build(auas_data_path)
# exit(0)

def sentence2id(sent, word2id):
    """

    :param sent:
    :param word2id:
    :return:
    """
    sentence_id = []
    for word in sent:
        if word.isdigit():
            word = '<NUM>'
        elif ('\u0041' <= word <= '\u005a') or ('\u0061' <= word <= '\u007a'):
            word = '<ENG>'
        if word not in word2id:
            word = '<UNK>'
        sentence_id.append(word2id[word])
    return sentence_id

def read_dictionary(vocab_path):
    """

    :param vocab_path:
    :return:
    """
    vocab_path = os.path.join(vocab_path)
    with io.open(vocab_path, 'rb') as fr:
        word2id = pickle.load(fr)
    print('vocab_size:', len(word2id))
    return word2id

def random_embedding(vocab, embedding_dim):
    """

    :param vocab:
    :param embedding_dim:
    :return:
    """
    embedding_mat = np.random.uniform(-0.25, 0.25, (len(vocab), embedding_dim))
    embedding_mat = np.float32(embedding_mat)
    return embedding_mat

def pad_sequences(sequences, pad_mark=0):
    """

    :param sequences:
    :param pad_mark:
    :return:
    """
    max_len = max(map(lambda x : len(x), sequences))
    seq_list, seq_len_list = [], []
    for seq in sequences:
        seq = list(seq)
        seq_ = seq[:max_len] + [pad_mark] * max(max_len - len(seq), 0)
        seq_list.append(seq_)
        seq_len_list.append(min(len(seq), max_len))
    return seq_list, seq_len_list

def batch_yield(data, batch_size, vocab, tag2label, shuffle=False):
    """

    :param data:
    :param batch_size:
    :param vocab:
    :param tag2label:
    :param shuffle:
    :return:
    """
    if shuffle:
        random.shuffle(data)

    seqs, labels = [], []
    for (sent_, tag_) in data:
        sent_ = sentence2id(sent_, vocab)
        label_ = [tag2label[tag] for tag in tag_]

        if len(seqs) == batch_size:
            yield seqs, labels
            seqs, labels = [], []

        seqs.append(sent_)
        labels.append(label_)

    if len(seqs) != 0:
        yield seqs, labels


#문제 : https://programmers.co.kr/learn/courses/30/lessons/42747
#
#
#예시 :  citations  |  return
#  [3, 0, 6, 1, 5]        3
def solution(citations):
    count = len(citations)
    #5
    citations.sort(reverse=True)
    #citations = [6, 5, 3, 1 ,0]
    cnt = 0
    for i in range(count, 0, -1):
    #i는 5부터 0 까지 -1씩 적용된다.
        for k in range(len(citations)):
        #citations의 각 인덱스별로 비교해주기위한 for문

            if citations[k] >= i:
                cnt += 1
            #만약 해당 인덱스값이 i보다 크면 , count값보다 더 많은 횟수를 갖고있으면
            # cnt ++를 해준다.

        if cnt >= i:
            return i
        #그렇게 나온 cnt값을 가지고 i와 비교해서 cnt가 크면
        # i값이 문제에서 요구하는 최대 h-index값이므로 return i를 해주면된다.
        cnt = 0

    return cnt
    #만약 아무것도 일어나지않으면 cnt는 0을 반환해줘야한다.


from filecmp import dircmp
import os
import argparse
import easygui
import pandas as pd
from pathlib import Path
import sys
from PyQt5.QtWidgets import (QFileDialog, QAbstractItemView, QListView,
                             QTreeView, QApplication, QDialog)

def convert_bytes(num):
    #this function will convert bytes to MB.. GB.. etc
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return f'{num:.3f} {x}'
        num /= 1024.0

def file_size(file_path):
    #this function will return the file size
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)

def get_files(folder):

	df = pd.DataFrame(columns=['Filename', 'Path', 'Size'])
	for root, dirs, file in os.walk(folder):
		for x in file:
			size = file_size(os.path.join(root, x))
			temp_df = pd.DataFrame([[x, root, size]], columns=['Filename', 'Path', 'Size'])
			df = df.append(temp_df, ignore_index=True)

	return df

class getExistingDirectories(QFileDialog):
    def __init__(self, *args):
        super(getExistingDirectories, self).__init__(*args)
        self.setOption(self.DontUseNativeDialog, True)
        self.setFileMode(self.Directory)
        self.setOption(self.ShowDirsOnly, True)
        self.findChildren(QListView)[0].setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.findChildren(QTreeView)[0].setSelectionMode(QAbstractItemView.ExtendedSelection)

qapp = QApplication(sys.argv)
dlg = getExistingDirectories()
if dlg.exec_() == QDialog.Accepted:
    list_of_folders = dlg.selectedFiles()

df = pd.DataFrame(columns=['Filename', 'Path', 'Size'])
for x in list_of_folders:
	print(x)
	temp_df = get_files(x)
	df = df.append(temp_df, ignore_index=True)

print(df)


import json
import logging
import multiprocessing
import os
from typing import Any, Dict, Optional, Union

import lib.infers
import lib.trainers
from monai.networks.nets import BasicUNet

from monailabel.interfaces.config import TaskConfig
from monailabel.interfaces.tasks.infer_v2 import InferTask
from monailabel.interfaces.tasks.train import TrainTask
from monailabel.utils.others.generic import download_file, strtobool

logger = logging.getLogger(__name__)

class SegmentationNuclei(TaskConfig):
    def init(self, name: str, model_dir: str, conf: Dict[str, str], planner: Any, **kwargs):
        super().init(name, model_dir, conf, planner, **kwargs)

        # Labels
        self.labels = {
            "Neoplastic cells": 1,
            "Inflammatory": 2,
            "Connective/Soft tissue cells": 3,
            "Dead Cells": 4,
            "Epithelial": 5,
        }
        self.label_colors = {
            "Neoplastic cells": (255, 0, 0),
            "Inflammatory": (255, 255, 0),
            "Connective/Soft tissue cells": (0, 255, 0),
            "Dead Cells": (0, 0, 0),
            "Epithelial": (0, 0, 255),
        }

        consep = strtobool(self.conf.get("consep", "true"))
        if consep:
            self.labels = {
                "Other": 1,
                "Inflammatory": 2,
                "Epithelial": 3,
                "Spindle-Shaped": 4,
            }
            self.label_colors = {
                "Other": (255, 0, 0),
                "Inflammatory": (255, 255, 0),
                "Epithelial": (0, 0, 255),
                "Spindle-Shaped": (0, 255, 0),
            }

        # Model Files
        self.path = [
            os.path.join(self.model_dir, f"pretrained_{name}{'_consep' if consep else ''}.pt"),  # pretrained
            os.path.join(self.model_dir, f"{name}{'_consep' if consep else ''}.pt"),  # published
        ]

        # Download PreTrained Model
        if strtobool(self.conf.get("use_pretrained_model", "true")):
            url = f"{self.conf.get('pretrained_path', self.PRE_TRAINED_PATH)}"
            url = f"{url}/pathology_segmentation_bunet_nuclei{'_consep' if consep else ''}.pt"
            download_file(url, self.path[0])

        # Network
        self.network = BasicUNet(
            spatial_dims=2,
            in_channels=3,
            out_channels=len(self.labels) + 1,
            features=(32, 64, 128, 256, 512, 32),
        )

    def infer(self) -> Union[InferTask, Dict[str, InferTask]]:
        preload = strtobool(self.conf.get("preload", "false"))
        roi_size = json.loads(self.conf.get("roi_size", "[1024, 1024]"))
        logger.info(f"Using Preload: {preload}; ROI Size: {roi_size}")

        task: InferTask = lib.infers.SegmentationNuclei(
            path=self.path,
            network=self.network,
            labels=self.labels,
            preload=preload,
            roi_size=roi_size,
            config={
                "label_colors": self.label_colors,
                "max_workers": max(1, multiprocessing.cpu_count() // 2),
            },
        )
        return task

    def trainer(self) -> Optional[TrainTask]:
        output_dir = os.path.join(self.model_dir, self.name)
        load_path = self.path[0] if os.path.exists(self.path[0]) else self.path[1]

        task: TrainTask = lib.trainers.SegmentationNuclei(
            model_dir=output_dir,
            network=self.network,
            load_path=load_path,
            publish_path=self.path[1],
            labels=self.labels,
            description="Train Nuclei Segmentation Model",
            config={
                "max_epochs": 10,
                "train_batch_size": 16,
                "val_batch_size": 16,
            },
        )
        return task


# Given N axis-aligned rectangles where N > 0, determine if they all together fo
# rm an exact cover of a rectangular region.
#
#  Each rectangle is represented as a bottom-left point and a top-right point. F
# or example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-lef
# t point is (1, 1) and top-right point is (2, 2)).
#
#
#
#  Example 1:
#
#
# rectangles = [
#   [1,1,3,3],
#   [3,1,4,2],
#   [3,2,4,4],
#   [1,3,2,4],
#   [2,3,3,4]
# ]
#
# Return true. All 5 rectangles together form an exact cover of a rectangular re
# gion.
#
#
#
#
#
#
#
#
#  Example 2:
#
#
# rectangles = [
#   [1,1,2,3],
#   [1,3,2,4],
#   [3,1,4,2],
#   [3,2,4,4]
# ]
#
# Return false. Because there is a gap between the two rectangular regions.
#
#
#
#
#
#
#
#
#  Example 3:
#
#
# rectangles = [
#   [1,1,3,3],
#   [3,1,4,2],
#   [1,3,2,4],
#   [3,2,4,4]
# ]
#
# Return false. Because there is a gap in the top center.
#
#
#
#
#
#
#
#
#  Example 4:
#
#
# rectangles = [
#   [1,1,3,3],
#   [3,1,4,2],
#   [1,3,2,4],
#   [2,2,4,4]
# ]
#
# Return false. Because two of the rectangles overlap with each other.
#
#
#  Related Topics Line Sweep
#  👍 452 👎 86

# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
    def isRectangleCover(self, rectangles):
        """
        :type rectangles: List[List[int]]
        :rtype: bool
        """
        corners = set()
        area = 0
        for x1, y1, x2, y2 in rectangles:
            for x, y in [(x1, y1), (x2, y2), (x1, y2), (x2, y1)]:
                if (x, y) in corners:
                    corners.remove((x, y))
                else:
                    corners.add((x, y))

            area += (x2 - x1) * (y2 - y1)
        if len(corners) != 4:
            return False

        corners = sorted(corners)
        return (corners[-1][0] - corners[0][0]) * (corners[-1][1] - corners[0][1]) == area
# print(Solution().isRectangleCover([
#   [1,1,3,3],
#   [3,1,4,2],
#   [1,3,2,4],
#   [2,2,4,4]
# ]
# ))
# leetcode submit region end(Prohibit modification and deletion)


from flask import Flask,jsonify, Blueprint, render_template
from sys import version
import numpy
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from flask_login import login_required

import os
from pathogen_memo.controllers import countbyquery

#Set word_count_site_name
barplotbv = Blueprint('barplotbv', __name__)

@barplotbv.route('/dashboard', methods=['GET'])
@login_required
def barplotb():
    a1 = countbyquery.get_query_count('aerobe', 'Aerobic')
    a2 = countbyquery.get_query_count('aerobe', 'Aerophilic')
    a3 = countbyquery.get_query_count('aerobe', 'Anaerobic')
    a4 = countbyquery.get_query_count('aerobe', 'Facultative Anaerobic')
    a5 = countbyquery.get_query_count('aerobe', 'NA')

    fig = plt.figure()
    ax = fig.add_axes([0,0,1,1])
    colors = ['Aerobic', 'Aerophilic','Anaerobic', 'Facultative Anaerobic', 'NA']
    pathomemb = [a1,a2,a3,a4,a5]
    tick_label = ['Aerobic', 'Aerophilic','Anaerobic', 'Facultative Anaerobic', 'NA']
    ax.bar(colors,pathomemb, tick_label=tick_label, width=0.8, color=['navy','blue','cyan','lightcyan','gray'])
    # naming the y-axis
    plt.ylabel('Pathogens - Counts')
    # naming the x-axis
    plt.xlabel('Pathogens categories')
    # plot title
    plt.rc('legend',fontsize=35)
    plt.title('Aerobe categories counts')

    plt.show()

    filePath = 'pathogen_memo/static/img/barplotb.png'
    if os.path.exists(filePath):
        os.remove(filePath)
    plt.savefig(filePath, ext='png', bbox_inches="tight")
    return render_template('dashboard.html', url='/static/img/barplotb.png')


# -*- coding: utf-8 -*-
"""
Created on Thu Apr  1 20:08:09 2021

@author: antons.sincovs
"""
import time

# fibonnacci calculation with iteration
def fib_rec(n):
    if n <= 1:
        return n
    else:
        return fib_rec(n - 1) + fib_rec( n - 2)

# fibonacci calclation with recursion
def fib_iter(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        n1 = 0
        n2 = 1
        fib = 0
        for _ in range(2,n+1):
            fib = n1 + n2
            n1 , n2 = n2 , fib
        return fib

# settting Fibonacci number
n = 20

# timing with recursion
pk1 = time.perf_counter()
print(fib_rec(n))
pk2 = time.perf_counter()
print(pk2 - pk1, "recursion time")

# timing with iteration
pk3 = time.perf_counter()
print (fib_iter(n))
pk4 = time.perf_counter()
print(pk4 - pk3, "iteration time")

# overall result comparison
print("Iteration is",round((pk2 - pk1)/(pk4 - pk3),2), "times faster than recursion")


print("Welcome to the Band name generator!")

# Overcomplicated functions to prevent blank names
def request_city():
    city = input("Enter your birth city:\n") # Request City
    if city == "":
        print("City cannot be blank!")
        return request_city() # City is blank, loop back and ask again
    else:
        return city

def request_pet_name():
    pet_name = input("Enter the name of one of your pets:\n") # Request pet name
    if pet_name == "":
        print("Pet name cannot be blank!")
        return request_pet_name() # Pet name is blank, loop back and ask again
    else:
        return pet_name

city = request_city()
pet_name = request_pet_name()

print("Your band name is: {0} {1}".format(city, pet_name))


import copy
row_length, column_length = 0, 0

def is_quadrate(i, j, board, dp):
    global row_length, column_length
    if i-1 < 0 or j-1 < 0:
        return board[i][j]
    else:
        dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1
        return dp[i][j]

def solution(board):
    global row_length, column_length
    answer = 0
    row_length = len(board)
    column_length = len(board[0])
    dp = copy.deepcopy(board)
    for i in range(row_length):
        for j in range(column_length):
            if dp[i][j]:
                answer = max(answer, is_quadrate(i, j, board, dp))
    return answer**2

print(solution([[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 0]]))
print(solution([[0, 0, 1, 1], [1, 1, 1, 1]]))

가장큰정사각형찾기.py


"""
Module with Q-learning

Classes:
    Qlearning
"""
import environment as ev
from agent import Agent

class Qlearning:
    @staticmethod
    def learn_strategy(
        agent: Agent,
        discount_factor: float,
        learning_rate: float,
        epochs: int,
        max_steps: int
    ) -> None:
        """
        Perform Q-learning
        :param agent: agent performing action
        :param discount_factor: discount factor for future rewards
        :param learning_rate: rate at which strategy should learn
        :param epochs: number of training iterations
        :param max_steps: maximum steps that agent can perform in iteration
        """
        avg_rewards_progress = []
        for i in range(epochs):
            # Maximum number of steps
            steps = max_steps
            # Starting position for iteration
            pos_x, pos_y = agent.get_pos()

            # While possible steps and not reached exit
            while steps > 0 and not agent.reached_exit():
                # Pick action
                action = agent.pick_action()
                # Perform action and get new location
                next_x, next_y = agent.get_new_position(action)

                # Receive reward and calculate temporal difference
                reward = ev.rewards[next_x][next_y]
                old_q_val = ev.q_values[pos_x][pos_y][action]
                temporal_difference = (
                    reward - old_q_val
                    + discount_factor * max(ev.q_values[next_x][next_y])
                )

                # Update q-value for action and node pair. Round to 2 decimal palces
                new_q_val = old_q_val + temporal_difference * learning_rate
                ev.q_values[pos_x][pos_y][action] = round(new_q_val, 2)

                steps -= 1
                pos_x, pos_y = agent.get_pos()

            # Find new starting position
            agent.set_new_start_position()

            # Save q-values every 50 iterations
            if (i + 1) % 50 == 0:
                avg_values = [[round(sum(values)/4) for values in row[:-1]] for row in ev.q_values[:-1]]
                avg_rewards_progress.append(avg_values)
                print("Iteration:", i + 1)
                for row in avg_values:
                    print("".join(str(val).rjust(5) for val in row))
        return avg_rewards_progress


#loading all the needed libraries
import dash
import dash_core_components as dcc
from dash import html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc

# must add this line in order for the app to be deployed successfully on Heroku
# from app import server
from app import app
# import all pages in the app
from apps import world,home,compare,trends
server = app.server
# building the navigation bar
dropdown = dbc.DropdownMenu(
    children=[
        dbc.DropdownMenuItem("Home", href="/home"),
        dbc.DropdownMenuItem("Powerful Nations", href="/world"),
        dbc.DropdownMenuItem("Trends(2005-2015)", href="/trends"),
        dbc.DropdownMenuItem("Compare", href="/compare"),

    ],
    nav = True,
    in_navbar = True,
    label = "Goto Page",
)

navbar = dbc.Navbar(
    dbc.Container(
        [
            html.A(
                # code for initial column in the navigation bar
                dbc.Row(
                    [
                        dbc.Col(html.Img(src="/assets/main_logo.png", height="80px",width="200px")),
                        dbc.Col(dbc.NavbarBrand("World Military Dashboard", className="ml-2")),

                    ],
                    align="center",
                ),
                href="/home",
            ),
            dbc.NavbarToggler(id="navbar-toggler2"),
            dbc.Collapse(
                dbc.Nav(
                    # right align for dropdown
                    [dropdown], className="ml-auto", navbar=True
                ),
                id="navbar-collapse2",
                navbar=True,
            ),
        ]
    ),
    color="dark",
    dark=True,
    className="mb-4",
)

def toggle_navbar_collapse(n, is_open):
    if n:
        return not is_open
    return is_open

for i in [2]:
    app.callback(
        Output(f"navbar-collapse{i}", "is_open"),
        [Input(f"navbar-toggler{i}", "n_clicks")],
        [State(f"navbar-collapse{i}", "is_open")],
    )(toggle_navbar_collapse)

# embedding the navigation bar
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    navbar,
    html.Div(id='page-content')
])

#for dynamic functionality of the code
@app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/world':
        return world.layout
    elif pathname == '/compare':
        return compare.layout
    elif pathname == '/trends':
        return trends.layout
    else:
        return home.layout

if __name__ == '__main__':
    app.run_server(port = 8079, debug=True)


myDict = {
      "prabhat": "mr Perfect",
      "gudan": "monu lover",
    "marks": [1,2,3,4,5,6,7,8,9,0] ,
    "anotherDict" : {'Lovely':'Lohra lover' },
    1:2
}
# Method of dictionary
print(list(myDict.keys()))# printing the keys of dictionary
print(list(myDict.values())) # printing the values of dictionary
print(myDict.items()) # printing the (key,value) of all content of dictionary
gama = {
   "Prabhat": "Hero",
   "Sima": "prabhat's mother",
   "Chitranjan": "prabhat's father"
}
myDict.update(gama) # To add new key-value pairs use myDict.update()
print(myDict.get("gudan"))# print key value associated with key "gudan"
print(myDict["gudan2"])# print key value associated with key "gudan"
# The difference between .key and [] syntax
print(myDict.get("gudan2"))# Returns None as gudan2 is not present in the dictionary
print(myDict["gudan2"])# Throws a error as gudan2 is not present in the dictionaryt

Python course with Prabhat/5. Chapter 5/02_dictionary_methods.py


from collections import OrderedDict
from scipy.integrate import odeint
from abstract_model import ModelABC
import numpy as np

class OdeModel(ModelABC):
    """Differential-based Models integrated with SciPy LSODA wrapper

    Attributes
    ----------
    model : func (x0, t, xout, p)
        A callable function that computes the time derivative at timesteps t as a function of parameters p.\n
        Signature is slightly different from the `scipy.odeint` signature due to limitations of `numba`
    sens_model: func (x0, t, xout, p)
        A callable function that computes the sensitivity equations for model.  Can be generated using the tools
        in the `symbolic` package.
    n_vars : int
        The number of state variables in the model
    param_order : list
        Order in which the parameters appear in the model.  Important for returning the jacobian in the correct
        order.
    use_jit : bool , optional
        Whether or not to jit `sens_model` and `model` using numba
    """

    def __init__(self, model, sens_model, n_vars, param_order,
                 model_name='Model', use_jit=True, model_jac=None,
                 sens_model_jac=None, jit_type='numba'):
        self._unjitted_model = model  # Keep unjitted version just in case
        self._unjitted_sens_model = sens_model
        self._unjitted_model_jac = model_jac
        self._unijitted_sens_model_jac = sens_model_jac
        self._jit_enabled = False

        super(OdeModel, self).__init__(model, n_vars, param_order, model_name)
        self.sens_model = sens_model
        self.model_jac = model_jac
        self.sens_model_jac = sens_model_jac
        self.use_jac = True
        self.jit_type = jit_type

        if use_jit:
            self.enable_jit()

    def enable_jit(self):
        if self.jit_type == 'numba':
            from numba import jit as numba_jit

            self._model = numba_jit("void(f8[:], f8, f8[:], f8[:])")(self._unjitted_model)
            self.sens_model = numba_jit("void(f8[:], f8, f8[:], f8[:])")(self._unjitted_sens_model)

            if self.model_jac is not None:
                self.model_jac = numba_jit("void(f8[:], f8, f8[:, :], f8[:])")(self._unjitted_model_jac)

            if self.sens_model_jac is not None:
                self.sens_model_jac = numba_jit("void(f8[:], f8, f8[:, :], f8[:])")(self._unijitted_sens_model_jac)

        elif self.jit_type == 'hope':
            from hope import jit as hope_jit

            self._model = hope_jit(self._unjitted_model)
            self.sens_model = hope_jit(self._unjitted_sens_model)

            if self.model_jac is not None:
                self.model_jac = hope_jit(self._unjitted_model_jac)

            if self.sens_model_jac is not None:
                self.sens_model_jac = hope_jit(self._unijitted_sens_model_jac)

        else:
            raise ValueError('jit_type has to be "hope" or "numba"')

        self._jit_enabled = True

    def disable_jit(self):
        self._model = self._unjitted_model
        self.sens_model = self._unjitted_sens_model
        self.model_jac = self._unjitted_model_jac
        self.sens_model_jac = self._unijitted_sens_model_jac
        self._jit_enabled = False

    def calc_jacobian(self, experiment_params, t_sim, init_conditions):
        # TODO: BROKEN COMMENTS
        """
        Simulates the model including the sensitivity equations.

        Parameters
        ----------
        experiment_params: :class:`~numpy:numpy.ndarray`
            An (n,) dimensional array containing the parameters of the model
        t_sim: :class:`~numpy:numpy.ndarray`
            An (t,) dimensional array containing the timesteps at which to simulate the model
        init_conditions: :class:`~numpy:numpy.ndarray`
            An (k,) dimensional array containing the initial conditions of the model, where k = m + n*m
            where m is the number of state variables in the original model, and n is the number of parameters

        Returns
        -------
        sensitivity_eqns: :class:`~numpy:numpy.ndarray`
            An (len(t_sim), n*m) dimensional array containing the sensitivity of each of the m state variables
            with respect to the n-non fixed parameters

        Notes
        -----
        The jacobian is returned with respect to the model parameters, not the global parameters
        """

        yout = np.zeros_like(init_conditions)
        def func_wrapper(y, t):
            self.sens_model(y, t, yout, experiment_params)
            return yout

        if self.sens_model_jac is None or not self.use_jac:
            jac_wrapper = None
        else:
            jacout = np.zeros((len(init_conditions), len(init_conditions)))
            def jac_wrapper(y, t):
                self.sens_model_jac(y, t, jacout, experiment_params)
                return jacout

        jacobian_sim = odeint(func_wrapper, init_conditions, t_sim, Dfun=jac_wrapper, col_deriv=True,
                              rtol=1e-10, atol=1e-10)
        # y_sim has dimensions (t_sim, n_vars + n_exp_params*n_vars)
        sensitivity_eqns = jacobian_sim[:, self.n_vars:]
        return sensitivity_eqns

    def simulate(self, experiment_params, t_sim, init_conditions=None):
        """
        Simulates the model using the `experiment` specific parameters.

        Evaluates :math:`Y_{sim}` using the parameters from `experiment`.

        Parameters
        ----------
        experiment_params: :class:`~numpy:numpy.ndarray`
            An (n,) dimensional array containing the parameters of the model
        t_sim: :class:`~numpy:numpy.ndarray`
            An (t,) dimensional array containing the timesteps at which to simulate the model
        init_conditions: :class:`~numpy:numpy.ndarray` , optional
            An (m,) dimensional array containing the initial conditions of the model, where m is the number
            of state variables in the model.
            Default: init_conditions = np.zeros((m,))

        Returns
        -------
        model_sim: :class:`~numpy:numpy.ndarray`
            An (len(t_sim), m) dimensional array containing the simulation at the timesteps
            specified by t_sim
        """
        if init_conditions is None:
            init_conditions = np.zeros((self._n_vars,))

        if self.model_jac is None or not self.use_jac:
            jac_wrapper = None
        else:
            jacout = np.zeros((len(init_conditions), len(init_conditions)))
            def jac_wrapper(y, t):
                self.model_jac(y, t, jacout, experiment_params)
                return jacout

        yout = np.zeros_like(init_conditions)
        def func_wrapper(y, t):
            self._model(y, t, yout, experiment_params)
            return yout

        model_sim = odeint(func_wrapper, init_conditions, t_sim, Dfun=jac_wrapper, col_deriv=True,
                           rtol=1e-10, atol=1e-10)
        return model_sim


"""
App project
"""
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.audio import SoundLoader
try:
	import pygame
	pygame.mixer.init()
except ModuleNotFoundError:
	pygame = None

def playm(sound):
	""" Crossplatform sound playing """
	if isinstance(sound,str):
		if pygame:
			s = pygame.mixer.Sound(sound)
		else:
			s = SoundLoader.load(sound)
		s.play()
		return s
	else:
		try:
			s.play()
			return s
		except AttributeError as a:
			return s

oakm = 'data/aud/Oak.wav'
oakm = playm(oakm)

try:
	import pygame
	pygame.mixer.init()
	sound = pygame.mixer.Sound('data/aud/106.wav')
	tjuta = 'data/aud/Oak.mp3'
	sound.play()
	tjuta = pygame.mixer.music.load(tjuta)
	#if tjuta is None:
	#	tjuta = pygame.mixer.music.load('data/aud/tjuta.wav')
except Exception as e:
	print(e)
	sound = SoundLoader.load('data/aud/106.wav')
	sound.play()
	tjuta = SoundLoader.load('data/aud/tjuta.wav')

"""

sound = SoundLoader.load('data/aud/106.wav')
if sound:
	print("Sound found at %s" % sound.source)
	print("Sound is %.3f seconds" % sound.length)
	sound.play()
import random

red = [1,0,0,1]
green = [0,1,0,1]
blue =  [0,0,1,1]
purple = [1,0,1,1]

class HBoxLayoutExample(App):
    def build(self):
        layout = BoxLayout(padding=10)
        colors = [red, green, blue, purple]

        for i in range(5):
            btn = Button(text="Button #%s" % (i+1),
                         background_color=random.choice(colors)
                         )

            layout.add_widget(btn)
        return layout

class Imgap(App):
    def build(self):
        img = Image(source='data/img/castle.png',
                    size_hint=(1, .5),
                    pos_hint={'center_x':.5, 'center_y':.5})
        label = Label(text='Hello from Kivy',
                      size_hint=(.5, .5),
                      pos_hint={'center_x': .5, 'center_y': .5})

        return img
"""
class MainApp(App):
    def build(self):
        self.icon = 'icon.ico'
        self.button = Button(text='CLICK HERE FOR FREE ROBUX !!!  NO SCAM !',
                        size_hint=(.5, .5),
                        background_color = [0,0,1,.5],
                        background_normal = "",
                        pos_hint={'center_x': .5, 'center_y': .5})
        self.button.bind(on_press=self.on_press_button)
        self.red = 0
        return self.button

    def on_press_button(self, instance):
        print('You pressed the button!')
        if not self.red:
            sound.play()
            self.button.background_color = [1,0,0,1]
            self.button.background_down = 'data/img/colors/green.png'
            self.button.text = "You have been TROLLED !!!!!!!!!!!XD"
            self.red += 1
        elif self.red:
            pygame.mixer.music.play()
            self.red = 0
            self.button.background_color = [0,0.8,0,1]
            self.button.background_down = 'data/img/colors/green.png'
            self.button.text = "Jo mama :O is so fat :D that she's yo DAD !!§XDDDDD"

if __name__ == '__main__':
    app = MainApp()
    app.run()


import torch.nn.functional as F
import torch

import numpy as np

def to_crop_resize(img, bbox, landm, resize=128):
    buff = torch.zeros(img.size(0), img.size(1), resize, resize)
    landm_buff = torch.zeros_like(landm)
    for i, (box, mark) in enumerate(zip(bbox, landm)):
        # image cropping and resizing
        x1, y1, x2, y2 = box
        im = img[i,:,y1:y2,x1:x2].unsqueeze(0)
        buff[i] = F.interpolate(im, [resize, resize], mode='bilinear', align_corners=False)

        # landmark rescaling
        h, w = im.shape[2:]
        y_scale, x_scale = resize / h, resize / w
        mark = mark.to(torch.float64)
        mark[::2] = (mark[::2]-x1) * x_scale
        mark[1::2] = (mark[1::2]-y1) * y_scale
        landm_buff[i] = mark.to(torch.int64)
    return buff, landm_buff

def to_restore_size(img, cropped, bbox):
    buff = torch.zeros_like(img)
    for i, box in enumerate(bbox):
        x1, y1, x2, y2 = box
        img[i,:,y1:y2,x1:x2] = F.interpolate(cropped[i].unsqueeze(0),
                                             [y2-y1, x2-x1], mode='bilinear', align_corners=False)[0]
    return img

def to_expand_bbox(bbox, landm, h, w, percentage=0.05):
    shrink_percentage = np.random.uniform(-percentage, percentage)

    pnts_x = landm[:,0::2]
    pnts_y = landm[:,1::2]
    max_x = pnts_x.max(1)[0]
    min_x = pnts_x.min(1)[0]
    max_y = pnts_y.max(1)[0]
    min_y = pnts_y.min(1)[0]
    minmax_xy = torch.stack([min_x, min_y, max_x, max_y])
    minmax_xy = minmax_xy.t()

    gap = (bbox - minmax_xy).to(torch.float64).to(bbox.device)

    x1 = torch.stack([bbox[:,0], min_x]).t().min(1, keepdim=True)[0]
    y1 = torch.stack([bbox[:,1], min_y]).t().min(1, keepdim=True)[0]
    x2 = torch.stack([bbox[:,2], max_x]).t().max(1, keepdim=True)[0]
    y2 = torch.stack([bbox[:,3], max_y]).t().max(1, keepdim=True)[0]
#    expanded_ = torch.cat([x1, y1, x2, y2], dim=1)+ (gap * (0.5+shrink_percentage)).to(bbox.dtype)
#    expanded_ = torch.cat([x1, y1, x2, y2], dim=1)+ (gap * 0.8).to(bbox.dtype)
    expanded_ = torch.cat([x1, y1, x2, y2], dim=1)+ (gap * 0.5).to(bbox.dtype)

    expanded_[:,0] = torch.where(expanded_[:,0] > 0, expanded_[:,0], 0*torch.ones_like(expanded_[:,0]))
    expanded_[:,1] = torch.where(expanded_[:,1] > 0, expanded_[:,1], 0*torch.ones_like(expanded_[:,1]))
    expanded_[:,2] = torch.where(expanded_[:,2] < w, expanded_[:,2], w*torch.ones_like(expanded_[:,2]))
    expanded_[:,3] = torch.where(expanded_[:,3] < h, expanded_[:,3], h*torch.ones_like(expanded_[:,3]))

    return expanded_

def to_apply_mask(img, bbox):
    """mask bbox of image"""
    for i, box in enumerate(bbox):
        x1, y1, x2, y2 = box
#        img[i][:,y1:y2,x1:x2] = 2*(128/255)-1
#        noise = np.random.normal(0.0, 0.1)
#        img[i][:,y1:y2,x1:x2] = torch.from_numpy(noise)
        img[i][:,y1:y2,x1:x2] = img[i][:,y1:y2,x1:x2].normal_(0.0, 0.1)
    return img

def to_onehot(landm, h, w):
    onehot = torch.zeros(landm.shape[0], 1, h, w)
    for i, mark in enumerate(landm):
        mark = torch.where(mark > 127, torch.tensor(127).to(mark.device), mark)
        onehot[i,0,mark[0],mark[1]] = 1
        onehot[i,0,mark[2],mark[3]] = 1
        onehot[i,0,mark[4],mark[5]] = 1
        onehot[i,0,mark[6],mark[7]] = 1
        onehot[i,0,mark[8],mark[9]] = 1
    return onehot

def softmax_(fake_cls):
    return torch.nn.functional.softmax(fake_cls.detach(), dim=1)

def accuracy_(real_cls, predicted):
    argmax = torch.argmax(predicted, dim=1)
    correct_ = torch.where(argmax==real_cls, torch.ones_like(argmax), torch.zeros_like(argmax)).to(predicted.dtype)
    return torch.sum(correct_) / len(real_cls)

# Load fewer layers of pre-trained models if possible
def load(model, cpk_file, netname=None):
    if netname is not None:
        pretrained_dict = torch.load(cpk_file)[netname]
    else:
        pretrained_dict = torch.load(cpk_file)
    model_dict = model.state_dict()
    pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
    model_dict.update(pretrained_dict)
    model.load_state_dict(model_dict)


#!/usr/bin/env python
"""Time tracking

Usage:
  timetracking -p PROJECTNAME [-c] start
  timetracking [-p PROJECTNAME] end
  timetracking [-a] list
  timetracking report
  timetracking add
  timetracking -h

Options:
-p PROJECTNAME --project=PROJECTNAME    project name
-c --continue                           also continue tracking other active projects
-a --active                             list only projects currently being tracked
-h --help                               show this help message
"""

import os
import sys
from docopt import docopt

import projects
import tracker

def print_help():
    """Prints out the help message"""
    print(__doc__)

def main(argv):
    """Main controller for time tracking functions"""

    project_name = ""
    continue_previous = False

    args = docopt(__doc__, version="0.1")

    if args['--project']:
        project_name = load_project(args['--project'])

    if args['--continue']:
        continue_previous = True

    if args['list']:
        if args['--active']:
            print("\n".join(tracker.currently_tracked_projects()))
        else:
            print("\n".join(projects.names()))
    elif args['start']:
        if not continue_previous:
            tracker.stop_all()
        tracker.start(project_name)
    elif args['end']:
        if project_name:
            tracker.stop(project_name)
        else:
            tracker.stop_all()
    elif args['report']:
        tracker.print_report()
    elif args['add']:
        add_new_project()

def load_project(project_name):
    """Sets project name after checking it is valid"""
    if not projects.exists(project_name):
        print("Invalid project: {}".format(project_name))
        sys.exit(1)
    else:
        return project_name

def add_new_project():
    """Asks for project data and adds the project"""
    project_name = input("Project name: ").replace(' ', '')
    try:
        projects.add_project(project_name)
    except projects.ProjectError as e:
        print("Cannot add project {}, error: {}".format(project_name, e))
        print(e.args)
        print(type(e).__name__)

if __name__ == "__main__":
    main(sys.argv[1:])


"""
Author:     Brian Mascitello
Date:       12/5/2017
Websites:   http://adventofcode.com/2015/day/12
Info:       --- Day 12: JSAbacusFramework.io ---
            --- Part Two ---
"""

import json

data = json.load(open('Day12Q1 2015 Input.txt'))

def calculate_sum(input_data):
    summation = 0
    if not isinstance(input_data, (dict, int, list)):
        return 0
    else:
        if isinstance(input_data, dict):
            if "red" in input_data.values():
                return 0
            for value in input_data.values():
                summation += calculate_sum(value)
        elif isinstance(input_data, int):
            return summation + input_data
        else:
            for item in input_data:
                summation += calculate_sum(item)
        return summation

print(calculate_sum(data))  # 87842

Advent of Code 2015/Day 12 2015/Day12Q2 2015.py


# 2. Задайте список. Напишите программу, которая определит,
# присутствует ли в заданном списке строк некое число.

import os
os.system("clear")

list1 = ["2", "43", "5", "331", "91", "35", "79", "53"]
x = input("Введите число: ")

for i in list1:
    if x == i:
        print(f"число {i} присутствует в списке")
        break
else:
    print("заданное число отсутствует в списке")

def check(stringlist: list, n: str) -> bool:
    for i in stringlist:
        if n == i:
            return True
    return False

my_list = ["2", "3", "3425", "0", "-1"]
x = input("Введите искомое число: ")
if check(my_list, x):
    print("Число есть в последовательности", my_list)
else:
    print("Числа нет в последовательности", my_list)


import csv
import os
from users_api.models import WdaeUser
from django.core.management.base import BaseCommand, CommandError
from .import_base import ImportUsersBase

class Command(ImportUsersBase, BaseCommand):
    help = (
        "Delete all users and adds new ones from csv. "
        "Required column names for the csv file - Email. "
        "Optional column names - Groups, Name, Password"
    )

    def add_arguments(self, parser):
        parser.add_argument("file", type=str)

    def handle(self, *args, **options):
        csvfilename = options["file"]
        assert os.path.exists(csvfilename)

        try:
            with open(csvfilename, "rt") as csvfile:
                resreader = csv.DictReader(csvfile)
                WdaeUser.objects.all().delete()
                for res in resreader:
                    self.handle_user(res)
            print(
                "\033[92m"
                + "Successfully restored users from file!"
                + "\033[0m"
            )

        except csv.Error:
            raise CommandError(
                'There was a problem while reading "%s"' % args[0]
            )
        except IOError:
            raise CommandError('File "%s" not found' % args[0])


n=int(input("Type of cross(eg:3 4 5...): "))
cond=True
while cond:
    if n<3:
       print("Cross starts from 3 ONLY!!!")
       n=int(input("Type of cross(eg:3 4 5...): "))
    else:
        cond=False
matrix=['0' for x in range(n**2)]
def check(player): #Function for checking whether the player has won
    l=0
    m=n-1
    k=0
    p=n*(n-1)
    comp=0
    while l<(n**2)-n+2:
        t=s=r=q=0
        for i in range(l,m): #horizontal check
           if matrix[i]==matrix[i+1] and matrix[i]!='0':
             t+=1
           else:
               break
        for i in range(k,p,n): #vertical check
           if matrix[i]==matrix[i+n] and matrix[i]!='0':
             s+=1
           else:
               break
        for i in range(0,(n**2)-(n+1),n+1): #left diagonal check
            if matrix[i]==matrix[i+(n+1)] and matrix[i]!='0':
               if i==(n**2)-(n+2):
                   r=2
            else:
                break
        for i in range(n-1,((n**2)-n)+1,n-1): #right diagonal check
            if matrix[i]==matrix[i+(n-1)] and matrix[i]!='0':
               if i==(((n**2)-n)+1)-n:
                   q=2
            else:
                break
        if t==n-1 or s==n-1 or r==2 or q==2:
            comp=1
            break
        p+=1
        k+=1
        l+=n
        m+=n
    print(t,s,r,q)
    if comp==1:
       print("PLAYER ***",player,"*** WON ! ! ! !")
       return 1
def display(): #Function to display the moves
    l=0
    m=n
    for i in range(n):
        for i in matrix[l:m]:
            print(i,end='|')
        print()
        l+=n
        m+=n
num=list(range(0,n**2))
def inputCheck(vari): #Function to check whether the input is valid
    s=1
    for i in num:
        if i==vari:
            s=0
    if s==0:
        return 0
    else:
        return 1
def tie(num): #Function to check tie
    leng=len(num)
    if leng==0:
        print("***MATCH TIED!!!***")
        return 1
#printing pos
li=[int(x) for x in range(0,n**2)]
for i in li:
    if i%n==0:
        print()
    print(i+1,end='|')
print()
#----
while True:
    x=int(input('Player1:'))
    x=x-1
    inputCheck1=inputCheck(x)
    crct=True
    while crct:
        if x>n**2:
            state="WARNING...The positions are from 1 to ",n**2," ONLY..."
        else:
            state="Space already used"
        if inputCheck1==1:
            print(state)
            x=int(input('player1:'))
            x=x-1
            inputCheck1=inputCheck(x)
        elif inputCheck1==0:
            crct=False
    num.remove(x)
    tie1=tie(num)
    if(tie1==1):
        break
    matrix[x]='1'
    res=check('1')
    display()
    if res==1:
        break
    y=int(input('player2:'))
    y=y-1
    inputCheck1=inputCheck(y)
    crct=True
    while crct:
        if y>n**2:
            state="WARNING...The positions are from 1 to ",n**2," ONLY..."
        else:
            state="Space already used"
        if inputCheck1==1:
           print(state)
           y=int(input('player2:'))
           y=y-1
           inputCheck1=inputCheck(y)
        elif inputCheck1==0:
            crct=False
    num.remove(y)
    tie1=tie(num)
    if(tie1==1):
        break
    matrix[y]='2'
    res=check('2')
    display()
    if res==1:
        break


from disco.bot import Plugin

class TutorialPlugin(Plugin):
    @Plugin.command('ping')
    def command_ping(self, event):
        event.msg.reply('pong')

    @Plugin.command('test')
    def command_test(self, event):
        event.msg.reply('I pass')

    @Plugin.command('divide', '<a:int> <b:int>', group='math')
    def on_math_dividpi_command(self, event, a, b):
        if a==0:
            return event.msg.reply('can not divide by zero')
        elif b==0:
            return event.msg.reply('can not divide by zero')
        event.msg.reply( '{}'.format(a) + ' goes into ' + '{}'.format(b) + '\n{}'.format(b/a) + ' times' )

    @Plugin.command('how many times can', ' <a:int> <b:int>', group='math')
    def on_math_divid_command(self, event, a, b):
        if a==0:
            return event.msg.reply('can not divide by zero')
        elif b==0:
            return event.msg.reply('can not divide by zero')
        event.msg.reply('it goes into ' + '{}'.format(b) + ' {}'.format(b//a) + ' times, with a ' + '{}'.format(b%a) + ' remainder' )

    @Plugin.command('help')
    def on_help_command(self, event):
         event.msg.reply('Help list version 0.01 \nCOMMANDS\n ping \n test \n im \'content\' \n i wish to file a complaint against \'content\' \n echo \'content\' \n MATH \n math how many times can \'a\' \'b\' \n math add \'a\' \'b\' \n math divide \'a\' \'b\'')

    #'{}'.


import unittest
from unittest.mock import patch

from tmc import points
from tmc.utils import load, load_module, reload_module, get_stdout, check_source
from functools import reduce
import os
import textwrap
from random import randint

exercise = 'src.histogrammi'
function = 'histogrammi'

@points('5.histogrammi')
class VanhinTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        with patch('builtins.input', side_effect=[AssertionError("Syötteen pyytämistä ei odotettu")]):
           cls.module = load_module(exercise, 'fi')

    def test_0_paaohjelma_kunnossa(self):
        ok, line = check_source(self.module)
        message = """Funktioita testaava koodi tulee sijoittaa lohkon
if __name__ == "__main__":
sisälle. Seuraava rivi tulee siirtää:
"""
        self.assertTrue(ok, message+line)

    def test_1_funktio_olemassa(self):
        try:
            from src.histogrammi import histogrammi
        except:
            self.assertTrue(False, f'Koodistasi pitäisi löytyä funktio nimeltä histogrammi(merkkijono: str)')

        try:
            histogrammi = load(exercise, function, 'fi')
            koodi = """histogrammi("abba")"""
            histogrammi("abba")
        except:
            self.assertTrue(False, f'Tarkista että funktiota voi kutsua seuraavasti:\n{koodi}')

    def test_2_abba_toimii(self):
        histogrammi = load(exercise, function, 'fi')

        sana = "abba"
        with patch('builtins.input', side_effect=["2"] * 10):
            reload_module(self.module)
            koodi = F'histogrammi("{sana}")'

            output_alussa = get_stdout()

            histogrammi(sana)

            output_all = get_stdout().replace(output_alussa, '', 1)

            output = [l for l in output_all.split("\n") if len(l)>0 ]

            self.assertTrue(len(output_all)>0, f'Funktiokutsu {koodi} ei tulosta mitään')
            exp = ["a **", "b **"]
            self.assertEqual(len(exp), len(output),  f'Funktiokutsun {koodi} pitäisi tulostaa {len(exp)} riviä, se tulosti {len(output)} riviä. Tulostus oli\n{output_all}')
            for rivi in exp:
                self.assertTrue(rivi in output, f'Funktiokutsun {koodi} pitäisi tulostaa rivi \n{rivi}\nSitä ei löytynyt. Tulostus oli\n{output_all}')

    def test_3_saippia_toimii(self):
        histogrammi = load(exercise, function, 'fi')

        sana = "saippua"
        with patch('builtins.input', side_effect=["2"] * 10):
            reload_module(self.module)
            koodi = F'histogrammi("{sana}")'

            output_alussa = get_stdout()

            histogrammi(sana)

            output_all = get_stdout().replace(output_alussa, '', 1)

            output = [l for l in output_all.split("\n") if len(l)>0 ]

            self.assertTrue(len(output_all)>0, f'Funktiokutsu {koodi} ei tulosta mitään')
            exp = [ "s *", "a **", "i *", "p **", "u *" ]
            self.assertEqual(len(exp), len(output),  f'Funktiokutsun {koodi} pitäisi tulostaa {len(exp)} riviä, se tulosti {len(output)} riviä. Tulostus oli\n{output_all}')
            for rivi in exp:
                self.assertTrue(rivi in output, f'Funktiokutsun {koodi} pitäisi tulostaa rivi \n{rivi}\nSitä ei löytynyt. Tulostus oli\n{output_all}')

    def test_3_histogrammi_toimii(self):
        histogrammi = load(exercise, function, 'fi')

        sana = "histogrammi"
        with patch('builtins.input', side_effect=["2"] * 10):
            reload_module(self.module)
            koodi = F'histogrammi("{sana}")'

            output_alussa = get_stdout()

            histogrammi(sana)

            output_all = get_stdout().replace(output_alussa, '', 1)

            output = [l for l in output_all.split("\n") if len(l)>0 ]

            self.assertTrue(len(output_all)>0, f'Funktiokutsu {koodi} ei tulosta mitään')
            exp = """h *
i **
s *
t *
o *
g *
r *
a *
m **""".split('\n')
            self.assertEqual(len(exp), len(output),  f'Funktiokutsun {koodi} pitäisi tulostaa {len(exp)} riviä, se tulosti {len(output)} riviä. Tulostus oli\n{output_all}')
            for rivi in exp:
                self.assertTrue(rivi in output, f'Funktiokutsun {koodi} pitäisi tulostaa rivi \n{rivi}\nSitä ei löytynyt. Tulostus oli\n{output_all}')

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


import json
import requests
from bs4 import BeautifulSoup
import sys
import os
import os.path
import shutil

try : # Tries to create a folder called images
    os.mkdir('images')

except: # If the image folder already exists it deletes the folder and creates a new one to get rid of residual images
    print("Image Folder Already Exists. New Folder Being Made.\n")
    shutil.rmtree('./images') # Deletes the folder
    os.mkdir('images') # Creates a new folder

private_tester = 0 # Create a variable to test if the profile is private or has no posts

# Downloads the image with the filename being the number image it is
def download_image(url, number): # Creates the function and sets its parameters
    image_browser = requests.get(url) # Creates a requests object to go to the image url
    image_file = open("./images/" + str(number) + '.jpg', "w") # Creates a jpg images in the images folder
    image_file.write(image_browser.content) # Writes the content to the image by scraping the image data from the url
    image_file.close() # Closes the file

# Finds the Image links
while private_tester == 0: # Checks to make sure a valid user is entered

    completed = 0 # Value to check when a valid instagram username is entered

    # If it's an invalid instagram username, it prompts you to enter a valid one
    while completed != 200: # While invalid profiles are entered
        link = 'https://www.instagram.com/' + raw_input('Enter Instagram Username: ') # Gets the Instagram profile link
        pagefile = requests.get(link) # Creates an object for the instagram user's information
        completed = pagefile.status_code # Checks if a valid Instagram link was entered. If it was, value should be 200.

        if completed != 200: # If it's an invalid username
            print("\nError: Invalid Instagram Username. Please Enter a New User.\n") # Print this text then prompt for new username

    parser = BeautifulSoup(pagefile.text, 'lxml') # Parses the instagram website using lxml

    ig_json = parser.find('script', text=lambda t: t.startswith('window._sharedData')).text.split(' = ', 1)[1].rstrip(';') # Strips the useless information and just leaves the image data and stores it in a JSON for easy manipulation
    url_file = json.loads(ig_json) # Opens the JSON file and creates an object that we can find the urls from

    for count in url_file['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges']: # Goes through each instagram post and finds the link to the 480 x 600 image
        photo_link = count['node']['thumbnail_resources'][3]['src'] # Creates a string with the image link
        private_tester += 1 # If it has a post, increment it
        download_image(photo_link, private_tester) # Passes the link and number to the image download function

    if private_tester == 0:
        print("Error: User Private Or Has No Photos. Please Enter A New User.\n") # Prints out error message

print("Images Successfully Downloaded.\n") # Tells us that we downloaded a valid user's urls


import pytest
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from sqlalchemy.orm import clear_mappers

from app import create_app
from repositories.sql_alchemy.mapping.user_mapping import user_mapping
from repositories.sql_alchemy.mapping.favorite_document_mapping import favorite_document_mapping

@pytest.fixture
def db():
    db, metadata = init()
    mapping_tables(metadata=metadata)
    metadata.create_all()
    yield db
    db.session.commit()
    destroy_tables(metadata=metadata)

@pytest.fixture(scope="session")
def db_session():
    db, metadata = init()
    mapping_tables(metadata=metadata)
    metadata.create_all()
    yield db
    truncate_tables(metadata=metadata, connection=db.engine.connect())
    db.session.commit()
    destroy_tables(metadata=metadata)

def init():
    app = create_app(modules=[])
    app.config['TESTING'] = True
    db = SQLAlchemy(app)
    metadata = MetaData(db.engine)
    return db, metadata

def mapping_tables(metadata: MetaData):
    try:
        clear_mappers()
        user_mapping(metadata)
    except Exception as e:
        print(e)

def truncate_tables(metadata, connection):
    for table in reversed(metadata.sorted_tables):
        connection.execute(table.delete())

def destroy_tables(metadata):
    metadata.reflect()
    metadata.drop_all()


# Licensed under a 3-clause BSD style license - see LICENSE.rst

"""This module implements the combiner class."""

import numpy as np
from numpy import ma

try:
    import bottleneck as bn
except ImportError:
    HAS_BOTTLENECK = False
else:
    HAS_BOTTLENECK = True

from .core import sigma_func

from astropy.nddata import CCDData, StdDevUncertainty
from astropy.stats import sigma_clip
from astropy.utils import deprecated_renamed_argument
from astropy import log

__all__ = ['Combiner', 'combine']

def _default_median(): # pragma: no cover
    if HAS_BOTTLENECK:
        return bn.nanmedian
    else:
        return np.nanmedian

def _default_average(): # pragma: no cover
    if HAS_BOTTLENECK:
        return bn.nanmean
    else:
        return np.nanmean

def _default_sum(): # pragma: no cover
    if HAS_BOTTLENECK:
        return bn.nansum
    else:
        return np.nansum

def _default_std(): # pragma: no cover
    if HAS_BOTTLENECK:
        return bn.nanstd
    else:
        return np.nanstd

class Combiner:
    """
    A class for combining CCDData objects.

    The Combiner class is used to combine together `~astropy.nddata.CCDData` objects
    including the method for combining the data, rejecting outlying data,
    and weighting used for combining frames.

    Parameters
    -----------
    ccd_iter : list or generator
        A list or generator of CCDData objects that will be combined together.

    dtype : str or `numpy.dtype` or None, optional
        Allows user to set dtype. See `numpy.array` ``dtype`` parameter
        description. If ``None`` it uses ``np.float64``.
        Default is ``None``.

    Raises
    ------
    TypeError
        If the ``ccd_iter`` are not `~astropy.nddata.CCDData` objects, have different
        units, or are different shapes.

    Examples
    --------
    The following is an example of combining together different
    `~astropy.nddata.CCDData` objects::

        >>> import numpy as np
        >>> import astropy.units as u
        >>> from astropy.nddata import CCDData
        >>> from ccdproc import Combiner
        >>> ccddata1 = CCDData(np.ones((4, 4)), unit=u.adu)
        >>> ccddata2 = CCDData(np.zeros((4, 4)), unit=u.adu)
        >>> ccddata3 = CCDData(np.ones((4, 4)), unit=u.adu)
        >>> c = Combiner([ccddata1, ccddata2, ccddata3])
        >>> ccdall = c.average_combine()
        >>> ccdall  # doctest: +FLOAT_CMP
        CCDData([[ 0.66666667,  0.66666667,  0.66666667,  0.66666667],
                 [ 0.66666667,  0.66666667,  0.66666667,  0.66666667],
                 [ 0.66666667,  0.66666667,  0.66666667,  0.66666667],
                 [ 0.66666667,  0.66666667,  0.66666667,  0.66666667]]...)
    """
    def __init__(self, ccd_iter, dtype=None):
        if ccd_iter is None:
            raise TypeError("ccd_iter should be a list or a generator of CCDData objects.")

        if dtype is None:
            dtype = np.float64

        default_shape = None
        default_unit = None

        ccd_list = list(ccd_iter)

        for ccd in ccd_list:
            # raise an error if the objects aren't CCDData objects
            if not isinstance(ccd, CCDData):
                raise TypeError(
                    "ccd_list should only contain CCDData objects.")

            # raise an error if the shape is different
            if default_shape is None:
                default_shape = ccd.shape
            else:
                if not (default_shape == ccd.shape):
                    raise TypeError("CCDData objects are not the same size.")

            # raise an error if the units are different
            if default_unit is None:
                default_unit = ccd.unit
            else:
                if not (default_unit == ccd.unit):
                    raise TypeError("CCDData objects don't have the same unit.")

        self.ccd_list = ccd_list
        self.unit = default_unit
        self.weights = None
        self._dtype = dtype

        # set up the data array
        new_shape = (len(ccd_list),) + default_shape
        self.data_arr = ma.masked_all(new_shape, dtype=dtype)

        # populate self.data_arr
        for i, ccd in enumerate(ccd_list):
            self.data_arr[i] = ccd.data
            if ccd.mask is not None:
                self.data_arr.mask[i] = ccd.mask
            else:
                self.data_arr.mask[i] = ma.zeros(default_shape)

        # Must be after self.data_arr is defined because it checks the
        # length of the data array.
        self.scaling = None

    @property
    def dtype(self):
        return self._dtype

    @property
    def weights(self):
        """
        Weights used when combining the `~astropy.nddata.CCDData` objects.

        Parameters
        ----------
        weight_values : `numpy.ndarray` or None
            An array with the weight values. The dimensions should match the
            the dimensions of the data arrays being combined.
        """
        return self._weights

    @weights.setter
    def weights(self, value):
        if value is not None:
            if isinstance(value, np.ndarray):
                if value.shape != self.data_arr.data.shape:
                    if value.ndim != 1:
                        raise ValueError("1D weights expected when shapes of the data and weights differ.")
                    if value.shape[0] != self.data_arr.data.shape[0]:
                        raise ValueError("Length of weights not compatible with specified axis.")
                self._weights = value
            else:
                raise TypeError("weights must be a numpy.ndarray.")
        else:
            self._weights = None

    @property
    def scaling(self):
        """
        Scaling factor used in combining images.

        Parameters
        ----------
        scale : function or `numpy.ndarray`-like or None, optional
            Images are multiplied by scaling prior to combining
            them. Scaling may be either a function, which will be applied to
            each image to determine the scaling factor, or a list or array
            whose length is the number of images in the `~ccdproc.Combiner`.
        """
        return self._scaling

    @scaling.setter
    def scaling(self, value):
        if value is None:
            self._scaling = value
        else:
            n_images = self.data_arr.data.shape[0]
            if callable(value):
                self._scaling = [value(self.data_arr[i]) for
                                 i in range(n_images)]
                self._scaling = np.array(self._scaling)
            else:
                try:
                    len(value) == n_images
                    self._scaling = np.array(value)
                except TypeError:
                    raise TypeError("scaling must be a function or an array "
                                    "the same length as the number of images.")
            # reshape so that broadcasting occurs properly
            for i in range(len(self.data_arr.data.shape)-1):
                self._scaling = self.scaling[:, np.newaxis]

    # set up IRAF-like minmax clipping
    def clip_extrema(self, nlow=0, nhigh=0):
        """Mask pixels using an IRAF-like minmax clipping algorithm.  The
        algorithm will mask the lowest nlow values and the highest nhigh values
        before combining the values to make up a single pixel in the resulting
        image.  For example, the image will be a combination of
        Nimages-nlow-nhigh pixel values instead of the combination of Nimages.

        Parameters
        -----------
        nlow : int or None, optional
            If not None, the number of low values to reject from the
            combination.
            Default is 0.

        nhigh : int or None, optional
            If not None, the number of high values to reject from the
            combination.
            Default is 0.

        Notes
        -----
        Note that this differs slightly from the nominal IRAF imcombine
        behavior when other masks are in use.  For example, if ``nhigh>=1`` and
        any pixel is already masked for some other reason, then this algorithm
        will count the masking of that pixel toward the count of nhigh masked
        pixels.

        Here is a copy of the relevant IRAF help text [0]_:

        nlow = 1, nhigh = (minmax)
            The number of low and high pixels to be rejected by the "minmax"
            algorithm. These numbers are converted to fractions of the total
            number of input images so that if no rejections have taken place
            the specified number of pixels are rejected while if pixels have
            been rejected by masking, thresholding, or nonoverlap, then the
            fraction of the remaining pixels, truncated to an integer, is used.

        References
        ----------
        .. [0] image.imcombine help text.
           http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?imcombine
        """

        if nlow is None:
            nlow = 0
        if nhigh is None:
            nhigh = 0

        argsorted = np.argsort(self.data_arr.data, axis=0)
        mg = np.mgrid[[slice(ndim)
                       for i, ndim in enumerate(self.data_arr.shape) if i > 0]]
        for i in range(-1*nhigh, nlow):
            # create a tuple with the indices
            where = tuple([argsorted[i, :, :].ravel()] +
                          [i.ravel() for i in mg])
            self.data_arr.mask[where] = True

    # set up min/max clipping algorithms
    def minmax_clipping(self, min_clip=None, max_clip=None):
        """Mask all pixels that are below min_clip or above max_clip.

         Parameters
         -----------
         min_clip : float or None, optional
             If not None, all pixels with values below min_clip will be masked.
             Default is ``None``.

         max_clip : float or None, optional
             If not None, all pixels with values above min_clip will be masked.
             Default is ``None``.
        """
        if min_clip is not None:
            mask = (self.data_arr < min_clip)
            self.data_arr.mask[mask] = True
        if max_clip is not None:
            mask = (self.data_arr > max_clip)
            self.data_arr.mask[mask] = True

    # set up sigma  clipping algorithms
    @deprecated_renamed_argument('use_astropy', None, arg_in_kwargs=True,
                                 since='2.4.0',
                                 message='The use_astropy argument has been removed because '
                                         'astropy sigma clipping is now always used.'
                                 )
    def sigma_clipping(self, low_thresh=3, high_thresh=3,
                       func='mean', dev_func='std', **kwd):
        """
        Pixels will be rejected if they have deviations greater than those
        set by the threshold values. The algorithm will first calculated
        a baseline value using the function specified in func and deviation
        based on dev_func and the input data array. Any pixel with a
        deviation from the baseline value greater than that set by
        high_thresh or lower than that set by low_thresh will be rejected.

        Parameters
        -----------

        low_thresh : positive float or None, optional
            Threshold for rejecting pixels that deviate below the baseline
            value. If negative value, then will be convert to a positive
            value. If None, no rejection will be done based on low_thresh.
            Default is 3.

        high_thresh : positive float or None, optional
            Threshold for rejecting pixels that deviate above the baseline
            value. If None, no rejection will be done based on high_thresh.
            Default is 3.

        func : {'median', 'mean'} or callable, optional
            The statistic or callable function/object used to compute
            the center value for the clipping. If using a callable
            function/object and the ``axis`` keyword is used, then it must
            be able to ignore NaNs (e.g., `numpy.nanmean`) and it must have
            an ``axis`` keyword to return an array with axis dimension(s)
            removed. The default is ``'median'``.

        dev_func : {'std', 'mad_std'} or callable, optional
            The statistic or callable function/object used to compute the
            standard deviation about the center value. If using a callable
            function/object and the ``axis`` keyword is used, then it must
            be able to ignore NaNs (e.g., `numpy.nanstd`) and it must have
            an ``axis`` keyword to return an array with axis dimension(s)
            removed. The default is ``'std'``.

        kwd
            Any remaining keyword arguments are passed to astropy's
            :func:`~astropy.stats.sigma_clip` function.
        """

        # Remove in 3.0
        _ = kwd.pop('use_astropy', True)

        self.data_arr.mask = sigma_clip(self.data_arr.data,
                                        sigma_lower=low_thresh,
                                        sigma_upper=high_thresh,
                                        axis=kwd.get('axis', 0),
                                        copy=kwd.get('copy', False),
                                        maxiters=kwd.get('maxiters', 1),
                                        cenfunc=func,
                                        stdfunc=dev_func,
                                        masked=True,
                                        **kwd).mask

    def _get_scaled_data(self, scale_arg):
        if scale_arg is not None:
            return self.data_arr * scale_arg
        if self.scaling is not None:
            return self.data_arr * self.scaling
        return self.data_arr

    def _get_nan_substituted_data(self, data):
        # Get the data as an unmasked array with masked values filled as NaN
        if self.data_arr.mask.any():
            data = np.ma.filled(data, fill_value=np.nan)
        else:
            data = data.data
        return data

    def _combination_setup(self,
                           user_func,
                           default_func,
                           scale_to):
        """
        Handle the common pieces of image combination data/mask setup.
        """
        data = self._get_scaled_data(scale_to)

        # Play it safe for now and only do the nan thing if the user is using
        # the default combination function.
        if user_func is None:
            combo_func = default_func
            # Subtitute NaN for masked entries
            data = self._get_nan_substituted_data(data)
            masked_values = np.isnan(data).sum(axis=0)
        else:
            masked_values = self.data_arr.mask.sum(axis=0)
            combo_func = user_func

        return data, masked_values, combo_func

    # set up the combining algorithms
    def median_combine(self, median_func=None, scale_to=None,
                       uncertainty_func=sigma_func):
        """
        Median combine a set of arrays.

        A `~astropy.nddata.CCDData` object is returned with the data property set to
        the median of the arrays. If the data was masked or any data have been
        rejected, those pixels will not be included in the median. A mask will
        be returned, and if a pixel has been rejected in all images, it will be
        masked. The uncertainty of the combined image is set by 1.4826 times
        the median absolute deviation of all input images.

        Parameters
        ----------
        median_func : function, optional
            Function that calculates median of a `numpy.ma.MaskedArray`.
            Default is `numpy.ma.median`.

        scale_to : float or None, optional
            Scaling factor used in the average combined image. If given,
            it overrides `scaling`.
            Defaults to None.

        uncertainty_func : function, optional
            Function to calculate uncertainty.
            Defaults is `~ccdproc.sigma_func`.

        Returns
        -------
        combined_image: `~astropy.nddata.CCDData`
            CCDData object based on the combined input of CCDData objects.

        Warnings
        --------
        The uncertainty currently calculated using the median absolute
        deviation does not account for rejected pixels.
        """

        data, masked_values, median_func = \
            self._combination_setup(median_func,
                                    _default_median(),
                                    scale_to)

        medianed = median_func(data, axis=0)

        # set the mask
        mask = (masked_values == len(self.data_arr))

        # set the uncertainty

        # This still uses numpy for the median because the astropy
        # code requires that the median function take the argument
        # overwrite_input and bottleneck doesn't allow that argument.
        # This is ugly, but setting ignore_nan to True should make sure
        # that either nans or masks are handled properly.
        if uncertainty_func is sigma_func:
            uncertainty = uncertainty_func(data, axis=0, ignore_nan=True)
        else:
            uncertainty = uncertainty_func(data, axis=0)
        # Divide uncertainty by the number of pixel (#309)
        uncertainty /= np.sqrt(len(self.data_arr) - masked_values)
        # Convert uncertainty to plain numpy array (#351)
        # There is no need to care about potential masks because the
        # uncertainty was calculated based on the data so potential masked
        # elements are also masked in the data. No need to keep two identical
        # masks.
        uncertainty = np.asarray(uncertainty)

        # create the combined image with a dtype matching the combiner
        combined_image = CCDData(np.asarray(medianed, dtype=self.dtype),
                                 mask=mask, unit=self.unit,
                                 uncertainty=StdDevUncertainty(uncertainty))

        # update the meta data
        combined_image.meta['NCOMBINE'] = len(self.data_arr)

        # return the combined image
        return combined_image

    def _weighted_sum(self, data, sum_func):
        """
        Perform weighted sum, used by both ``sum_combine`` and in some cases
        by ``average_combine``.
        """
        if self.weights.shape != data.shape:
            # Add extra axes to the weights for broadcasting
            weights = np.reshape(self.weights, [len(self.weights), 1, 1])
        else:
            weights = self.weights

        # Turns out bn.nansum has an implementation that is not
        # precise enough for float32 sums. Doing this should
        # ensure the sums are carried out as float64
        weights = weights.astype('float64')
        weighted_sum = sum_func(data * weights, axis=0)
        return weighted_sum, weights

    def average_combine(self, scale_func=None, scale_to=None,
                        uncertainty_func=_default_std(), sum_func=_default_sum()):
        """
        Average combine together a set of arrays.

        A `~astropy.nddata.CCDData` object is returned with the data property
        set to the average of the arrays. If the data was masked or any
        data have been rejected, those pixels will not be included in the
        average. A mask will be returned, and if a pixel has been
        rejected in all images, it will be masked. The uncertainty of
        the combined image is set by the standard deviation of the input
        images.

        Parameters
        ----------
        scale_func : function, optional
            Function to calculate the average. Defaults to
            `numpy.nanmean`.

        scale_to : float or None, optional
            Scaling factor used in the average combined image. If given,
            it overrides `scaling`. Defaults to ``None``.

        uncertainty_func : function, optional
            Function to calculate uncertainty. Defaults to `numpy.ma.std`.

        sum_func : function, optional
            Function used to calculate sums, including the one done to
            find the weighted average. Defaults to `numpy.nansum`.

        Returns
        -------
        combined_image: `~astropy.nddata.CCDData`
            CCDData object based on the combined input of CCDData objects.
        """
        data, masked_values, scale_func = \
            self._combination_setup(scale_func,
                                    _default_average(),
                                    scale_to)
        # # set up the data
        # data = self._get_scaled_data(scale_to)

        # # Subtitute NaN for masked entries
        # data = self._get_nan_substituted_data(data)

        # Do NOT modify data after this -- we need it to be intact when we
        # we get to the uncertainty calculation.
        if self.weights is not None:
            weighted_sum, weights = self._weighted_sum(data, sum_func)
            mean = weighted_sum / sum_func(weights, axis=0)
        else:
            mean = scale_func(data, axis=0)

        # calculate the mask

        mask = (masked_values == len(self.data_arr))

        # set up the deviation
        uncertainty = uncertainty_func(data, axis=0)
        # Divide uncertainty by the number of pixel (#309)
        uncertainty /= np.sqrt(len(data) - masked_values)
        # Convert uncertainty to plain numpy array (#351)
        uncertainty = np.asarray(uncertainty)

        # create the combined image with a dtype that matches the combiner
        combined_image = CCDData(np.asarray(mean, dtype=self.dtype),
                                 mask=mask, unit=self.unit,
                                 uncertainty=StdDevUncertainty(uncertainty))

        # update the meta data
        combined_image.meta['NCOMBINE'] = len(data)

        # return the combined image
        return combined_image

    def sum_combine(self, sum_func=None, scale_to=None,
                    uncertainty_func=_default_std()):
        """
        Sum combine together a set of arrays.

        A `~astropy.nddata.CCDData` object is returned with the data property
        set to the sum of the arrays. If the data was masked or any
        data have been rejected, those pixels will not be included in the
        sum. A mask will be returned, and if a pixel has been
        rejected in all images, it will be masked. The uncertainty of
        the combined image is set by the multiplication of summation of
        standard deviation of the input by square root of number of images.
        Because sum_combine returns 'pure sum' with masked pixels ignored, if
        re-scaled sum is needed, average_combine have to be used with
        multiplication by number of images combined.

        Parameters
        ----------
        sum_func : function, optional
            Function to calculate the sum. Defaults to
            `numpy.nansum` or ``bottleneck.nansum``.

        scale_to : float or None, optional
            Scaling factor used in the sum combined image. If given,
            it overrides `scaling`. Defaults to ``None``.

        uncertainty_func : function, optional
            Function to calculate uncertainty. Defaults to `numpy.ma.std`.

        Returns
        -------
        combined_image: `~astropy.nddata.CCDData`
            CCDData object based on the combined input of CCDData objects.
        """

        data, masked_values, sum_func = \
            self._combination_setup(sum_func,
                                    _default_sum(),
                                    scale_to)

        if self.weights is not None:
            summed, weights = self._weighted_sum(data, sum_func)
        else:
            summed = sum_func(data, axis=0)

        # set up the mask
        mask = (masked_values == len(self.data_arr))

        # set up the deviation
        uncertainty = uncertainty_func(data, axis=0)
        # Divide uncertainty by the number of pixel (#309)
        uncertainty /= np.sqrt(len(data) - masked_values)
        # Convert uncertainty to plain numpy array (#351)
        uncertainty = np.asarray(uncertainty)
        # Multiply uncertainty by square root of the number of images
        uncertainty *= len(data) - masked_values

        # create the combined image with a dtype that matches the combiner
        combined_image = CCDData(np.asarray(summed, dtype=self.dtype),
                                 mask=mask, unit=self.unit,
                                 uncertainty=StdDevUncertainty(uncertainty))

        # update the meta data
        combined_image.meta['NCOMBINE'] = len(self.data_arr)

        # return the combined image
        return combined_image

def _calculate_step_sizes(x_size, y_size, num_chunks):
    """
    Calculate the strides in x and y to achieve at least
    the ``num_chunks`` pieces.

    Parameters
    ----------
    """
    # First we try to split only along fast x axis
    xstep = max(1, int(x_size / num_chunks))

    # More chunks are needed only if xstep gives us fewer chunks than
    # requested.
    x_chunks = int(x_size / xstep)

    if x_chunks >= num_chunks:
        ystep = y_size
    else:
        # The x and y loops are nested, so the number of chunks
        # is multiplicative, not additive. Calculate the number
        # of y chunks we need to get at num_chunks.
        y_chunks = int(num_chunks / x_chunks) + 1
        ystep = max(1, int(y_size / y_chunks))

    return xstep, ystep

def _calculate_size_of_image(ccd,
                             combine_uncertainty_function):
    # If uncertainty_func is given for combine this will create an uncertainty
    # even if the originals did not have one. In that case we need to create
    # an empty placeholder.
    if ccd.uncertainty is None and combine_uncertainty_function is not None:
        ccd.uncertainty = StdDevUncertainty(np.zeros(ccd.data.shape))

    size_of_an_img = ccd.data.nbytes
    try:
        size_of_an_img += ccd.uncertainty.array.nbytes
    # In case uncertainty is None it has no "array" and in case the "array" is
    # not a numpy array:
    except AttributeError:
        pass
    # Mask is enforced to be a numpy.array across astropy versions
    if ccd.mask is not None:
        size_of_an_img += ccd.mask.nbytes
    # flags is not necessarily a numpy array so do not fail with an
    # AttributeError in case something was set!
    # TODO: Flags are not taken into account in Combiner. This number is added
    #       nevertheless for future compatibility.
    try:
        size_of_an_img += ccd.flags.nbytes
    except AttributeError:
        pass

    return size_of_an_img

def combine(img_list, output_file=None,
            method='average', weights=None, scale=None, mem_limit=16e9,
            clip_extrema=False, nlow=1, nhigh=1,
            minmax_clip=False, minmax_clip_min=None, minmax_clip_max=None,
            sigma_clip=False,
            sigma_clip_low_thresh=3, sigma_clip_high_thresh=3,
            sigma_clip_func=ma.mean, sigma_clip_dev_func=ma.std,
            dtype=None, combine_uncertainty_function=None,
            overwrite_output=False, **ccdkwargs):
    """
    Convenience function for combining multiple images.

    Parameters
    -----------
    img_list : `numpy.ndarray`, list or str
        A list of fits filenames or `~astropy.nddata.CCDData` objects that will be
        combined together. Or a string of fits filenames separated by comma
        ",".

    output_file : str or None, optional
        Optional output fits file-name to which the final output can be
        directly written.
        Default is ``None``.

    method : str, optional
        Method to combine images:

        - ``'average'`` : To combine by calculating the average.
        - ``'median'`` : To combine by calculating the median.
        - ``'sum'`` : To combine by calculating the sum.

        Default is ``'average'``.

    weights : `numpy.ndarray` or None, optional
        Weights to be used when combining images.
        An array with the weight values. The dimensions should match the
        the dimensions of the data arrays being combined.
        Default is ``None``.

    scale : function or `numpy.ndarray`-like or None, optional
        Scaling factor to be used when combining images.
        Images are multiplied by scaling prior to combining them. Scaling
        may be either a function, which will be applied to each image
        to determine the scaling factor, or a list or array whose length
        is the number of images in the `Combiner`. Default is ``None``.

    mem_limit : float, optional
        Maximum memory which should be used while combining (in bytes).
        Default is ``16e9``.

    clip_extrema : bool, optional
        Set to True if you want to mask pixels using an IRAF-like minmax
        clipping algorithm.  The algorithm will mask the lowest nlow values and
        the highest nhigh values before combining the values to make up a
        single pixel in the resulting image.  For example, the image will be a
        combination of Nimages-low-nhigh pixel values instead of the
        combination of Nimages.

        Parameters below are valid only when clip_extrema is set to True,
        see :meth:`Combiner.clip_extrema` for the parameter description:

        - ``nlow`` : int or None, optional
        - ``nhigh`` : int or None, optional

    minmax_clip : bool, optional
        Set to True if you want to mask all pixels that are below
        minmax_clip_min or above minmax_clip_max before combining.
        Default is ``False``.

        Parameters below are valid only when minmax_clip is set to True, see
        :meth:`Combiner.minmax_clipping` for the parameter description:

        - ``minmax_clip_min`` : float or None, optional
        - ``minmax_clip_max`` : float or None, optional

    sigma_clip : bool, optional
        Set to True if you want to reject pixels which have deviations greater
        than those
        set by the threshold values. The algorithm will first calculated
        a baseline value using the function specified in func and deviation
        based on sigma_clip_dev_func and the input data array. Any pixel with
        a deviation from the baseline value greater than that set by
        sigma_clip_high_thresh or lower than that set by sigma_clip_low_thresh
        will be rejected.
        Default is ``False``.

        Parameters below are valid only when sigma_clip is set to True. See
        :meth:`Combiner.sigma_clipping` for the parameter description.

        - ``sigma_clip_low_thresh`` : positive float or None, optional
        - ``sigma_clip_high_thresh`` : positive float or None, optional
        - ``sigma_clip_func`` : function, optional
        - ``sigma_clip_dev_func`` : function, optional

    dtype : str or `numpy.dtype` or None, optional
        The intermediate and resulting ``dtype`` for the combined CCDs. See
        `ccdproc.Combiner`. If ``None`` this is set to ``float64``.
        Default is ``None``.

    combine_uncertainty_function : callable, None, optional
        If ``None`` use the default uncertainty func when using average, median or
        sum combine, otherwise use the function provided.
        Default is ``None``.

    overwrite_output : bool, optional
        If ``output_file`` is specified, this is passed to the
        `astropy.nddata.fits_ccddata_writer` under the keyword ``overwrite``;
        has no effect otherwise.
        Default is ``False``.

    ccdkwargs : Other keyword arguments for `astropy.nddata.fits_ccddata_reader`.

    Returns
    -------
    combined_image : `~astropy.nddata.CCDData`
        CCDData object based on the combined input of CCDData objects.
    """
    if not isinstance(img_list, list):
        # If not a list, check whether it is a numpy ndarray or string of
        # filenames separated by comma
        if isinstance(img_list, np.ndarray):
            img_list = img_list.tolist()
        elif isinstance(img_list, str) and (',' in img_list):
            img_list = img_list.split(',')
        else:
            try:
                # Maybe the input can be made into a list, so try that
                img_list = list(img_list)
            except TypeError:
                raise ValueError(
                    "unrecognised input for list of images to combine.")

    # Select Combine function to call in Combiner
    if method == 'average':
        combine_function = 'average_combine'
    elif method == 'median':
        combine_function = 'median_combine'
    elif method == 'sum':
        combine_function = 'sum_combine'
    else:
        raise ValueError("unrecognised combine method : {0}.".format(method))

    # First we create a CCDObject from first image for storing output
    if isinstance(img_list[0], CCDData):
        ccd = img_list[0].copy()
    else:
        # User has provided fits filenames to read from
        ccd = CCDData.read(img_list[0], **ccdkwargs)

    if dtype is None:
        dtype = np.float64

    # Convert the master image to the appropriate dtype so when overwriting it
    # later the data is not downcast and the memory consumption calculation
    # uses the internally used dtype instead of the original dtype. #391
    if ccd.data.dtype != dtype:
        ccd.data = ccd.data.astype(dtype)

    # If the template image doesn't have an uncertainty, add one, because the
    # result always has an uncertainty.
    if ccd.uncertainty is None:
        ccd.uncertainty = StdDevUncertainty(np.zeros_like(ccd.data))

    # If the template doesn't have a mask, add one, because the result may have
    # a mask
    if ccd.mask is None:
        ccd.mask = np.zeros_like(ccd.data, dtype=bool)

    size_of_an_img = _calculate_size_of_image(ccd,
                                              combine_uncertainty_function)

    no_of_img = len(img_list)

    # Set a memory use factor based on profiling
    if method == 'median':
        memory_factor = 3
    else:
        memory_factor = 2

    memory_factor *= 1.3

    # determine the number of chunks to split the images into
    no_chunks = int((memory_factor * size_of_an_img * no_of_img) / mem_limit) + 1
    if no_chunks > 1:
        log.info('splitting each image into {0} chunks to limit memory usage '
                 'to {1} bytes.'.format(no_chunks, mem_limit))
    xs, ys = ccd.data.shape

    # Calculate strides for loop
    xstep, ystep = _calculate_step_sizes(xs, ys, no_chunks)

    # Dictionary of Combiner properties to set and methods to call before
    # combining
    to_set_in_combiner = {}
    to_call_in_combiner = {}

    # Define all the Combiner properties one wants to apply before combining
    # images
    if weights is not None:
        to_set_in_combiner['weights'] = weights

    if scale is not None:
        # If the scale is a function, then scaling function need to be applied
        # on full image to obtain scaling factor and create an array instead.
        if callable(scale):
            scalevalues = []
            for image in img_list:
                if isinstance(image, CCDData):
                    imgccd = image
                else:
                    imgccd = CCDData.read(image, **ccdkwargs)

                scalevalues.append(scale(imgccd.data))

            to_set_in_combiner['scaling'] = np.array(scalevalues)
        else:
            to_set_in_combiner['scaling'] = scale

    if clip_extrema:
        to_call_in_combiner['clip_extrema'] = {'nlow': nlow,
                                               'nhigh': nhigh}

    if minmax_clip:
        to_call_in_combiner['minmax_clipping'] = {'min_clip': minmax_clip_min,
                                                  'max_clip': minmax_clip_max}

    if sigma_clip:
        to_call_in_combiner['sigma_clipping'] = {
            'low_thresh': sigma_clip_low_thresh,
            'high_thresh': sigma_clip_high_thresh,
            'func': sigma_clip_func,
            'dev_func': sigma_clip_dev_func}

    # Finally Run the input method on all the subsections of the image
    # and write final stitched image to ccd
    for x in range(0, xs, xstep):
        for y in range(0, ys, ystep):
            xend, yend = min(xs, x + xstep), min(ys, y + ystep)
            ccd_list = []
            for image in img_list:
                if isinstance(image, CCDData):
                    imgccd = image
                else:
                    imgccd = CCDData.read(image, **ccdkwargs)

                # Trim image and copy
                # The copy is *essential* to avoid having a bunch
                # of unused file references around if the files
                # are memory-mapped. See this PR for details
                # https://github.com/astropy/ccdproc/pull/630
                ccd_list.append(imgccd[x:xend, y:yend].copy())

            # Create Combiner for tile
            tile_combiner = Combiner(ccd_list, dtype=dtype)

            # Set all properties and call all methods
            for to_set in to_set_in_combiner:
                setattr(tile_combiner, to_set, to_set_in_combiner[to_set])
            for to_call in to_call_in_combiner:
                getattr(tile_combiner, to_call)(**to_call_in_combiner[to_call])

            # Finally call the combine algorithm
            combine_kwds = {}
            if combine_uncertainty_function is not None:
                combine_kwds['uncertainty_func'] = combine_uncertainty_function

            comb_tile = getattr(tile_combiner, combine_function)(**combine_kwds)

            # add it back into the master image
            ccd.data[x:xend, y:yend] = comb_tile.data
            if ccd.mask is not None:
                ccd.mask[x:xend, y:yend] = comb_tile.mask
            if ccd.uncertainty is not None:
                ccd.uncertainty.array[x:xend, y:yend] = comb_tile.uncertainty.array
            # Free up memory to try to stay under user's limit
            del comb_tile
            del tile_combiner
            del ccd_list

    # Write fits file if filename was provided
    if output_file is not None:
        ccd.write(output_file, overwrite=overwrite_output)

    return ccd