#!/usr/bin/env python

import os
import logging
import urllib
from time import time
from random import getrandbits
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import RequestHandler, WSGIApplication, template, wsgiref
from django.utils import simplejson

from yammerConfig import CONSUMER_KEY, CONSUMER_SECRET

REQUEST_TOKEN_URL = 'https://www.yammer.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://www.yammer.com/oauth/access_token'
USER_AUTH_URL = 'https://www.yammer.com/oauth/authorize'
DEFAULT_API_PREFIX = 'https://www.yammer.com/api/v1/'
DEFAULT_API_SUFFIX = '.json'

HEADERS = {
	'Content-Type': 'application/x-www-form-urlencoded',
	'Accept': '*/*',
	'Accept-Language': 'en-us',
	'Accept-Encoding': 'gzip, deflate',
	'Connection': 'keep-alive',
}

def getOAuthHeaders(token=None, token_secret='', verifier=None):
	OAuthHeaders = 'OAuth realm=""'
	OAuthHeaders += ', oauth_consumer_key="%s"' % CONSUMER_KEY

	if token:
		OAuthHeaders += ', oauth_token="%s"' % token

	OAuthHeaders += ', oauth_signature_method="PLAINTEXT"'
	OAuthHeaders += ', oauth_signature="%s%%26%s"' % (CONSUMER_SECRET, token_secret)
	currentTime = int(time())
	OAuthHeaders += ', oauth_timestamp="%s"' % currentTime
	OAuthHeaders += ', oauth_nonce="%s"' % currentTime

	if verifier:
		OAuthHeaders += ', oauth_verifier="%s"' % verifier

	OAuthHeaders += ', oauth_version="1.0"'
	return str(OAuthHeaders)

class MainHandler(RequestHandler):

	def get_cookie(self):
		return self.request.cookies.get('oauth.yammerfall', '')

	def set_cookie(self, value, path='/'):
		self.response.headers.add_header(
			'Set-Cookie',
			'%s=%s; path=%s; expires="Fri, 31-Dec-2021 23:59:59 GMT"' %
			('oauth.yammerfall', value, path)
			)

	def expire_cookie(self, path='/'):
		self.response.headers.add_header(
			'Set-Cookie',
			'%s=; path=%s; expires="Fri, 31-Dec-1999 23:59:59 GMT"' %
			('oauth.yammerfall', path)
			)

	def get(self):

		if self.request.get('expire_cookie', None) == 'now':
			logging.debug('EXPIRING COOKIE')
			self.expire_cookie()
			self.redirect('/')
			return

		if self.get_cookie():
			logging.debug('GOT COOKIE! %s' % self.get_cookie())
			template_values = {
				'messagesUrl': '/messages?%s' % self.get_cookie(),
			}
			path = os.path.join(os.path.dirname(__file__), "templates/home.html")
			self.response.out.write(template.render(path, template_values))
			return

		logging.debug('NO COOKIE!')

		HEADERS['Authorization'] = getOAuthHeaders()
		result = urlfetch.fetch(
			url=REQUEST_TOKEN_URL,
			payload='',
			method=urlfetch.POST,
			headers=HEADERS,
		)

		data = {}
		for nv in result.content.split('&'):
			(n, v) = nv.split('=')
			data[n] = v

		template_values = {
			'user_auth_url': USER_AUTH_URL,
			'oauth_token': data['oauth_token'],
			'oauth_token_secret': data['oauth_token_secret'],
		}
		path = os.path.join(os.path.dirname(__file__), "templates/login.html")
		self.response.out.write(template.render(path, template_values))
		return

	def post(self):

		logging.debug('AUTHORIZE WITH VERIFY CODE: %s' % self.request.get('oauth_verifier'))

		HEADERS['Authorization'] = getOAuthHeaders(
			token = self.request.get('oauth_token'),
			token_secret = self.request.get('oauth_token_secret'),
			verifier = self.request.get('oauth_verifier'))

		result = urlfetch.fetch(
			url=ACCESS_TOKEN_URL,
			method=urlfetch.POST,
			headers=HEADERS,
		)

		logging.debug('AUTHORIZED: %s' % result.content)

		self.set_cookie(result.content)
		self.redirect('/')

class MessagesHandler(RequestHandler):
	def get(self):

		HEADERS['Authorization'] = getOAuthHeaders(
			token = self.request.get('oauth_token'),
			token_secret = self.request.get('oauth_token_secret'))
		MSGS_URL = '%smessages%s' % (DEFAULT_API_PREFIX, DEFAULT_API_SUFFIX)

		result = urlfetch.fetch(
			url=MSGS_URL,
			method=urlfetch.GET,
			headers=HEADERS,
		)

		data = simplejson.loads(result.content)

		#self.response.out.write(data)

		users = {}
		ref_msgs = {}
		for r in data['references']:
			if r['type'] == 'user':
				users[r['id']] = r
				users[r['name']] = r
			elif r['type'] == 'message':
				ref_msgs[r['id']] = r

		for m in data['messages']:
			m['mugshot_url'] = users[m['sender_id']]['mugshot_url']
			m['full_name'] = users[m['sender_id']]['full_name']
			m['like_list'] = []
			if m['liked_by']['count'] > 0:
				for liked_by_name in m['liked_by']['names']:
					try:
						m['like_list'].append((liked_by_name['full_name'], users[liked_by_name['permalink']]['mugshot_url']))
					except:
						pass
			if m['replied_to_id']:
				in_reply_to = users[ref_msgs[m['replied_to_id']]['sender_id']]
				m['in_reply_to'] = (in_reply_to['full_name'], in_reply_to['mugshot_url'])

		template_values = {
			'messages' : data['messages'],
		}
		path = os.path.join(os.path.dirname(__file__), "templates/messagelist.html")
		self.response.out.write(template.render(path, template_values))

# ------------------------------------------------------------------------------
# self runner -- gae cached main() function
# ------------------------------------------------------------------------------

def main():
	logging.getLogger().setLevel(logging.DEBUG)
	application = WSGIApplication([
		('/', MainHandler),
		('/messages', MessagesHandler),
	   ], debug=True)

	wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
	main()


# Andrew Sala
# MadLibs2.0
def Welcome():
    print("Enter the following requested words for a cool paragraph!\n")
    theme = int(input("Select one of the following themes:\n 1 = Pizza\n 2 = Astronaut\n 3 = Summer\n"))
# user will choose a theme out of the three given options to pick what they would like their mad lib to be about
    if theme == 1:
        PizzaPizza()
    elif theme == 2:
        Summer()
    elif theme == 3:
        Astronaut()
# after theme is picked program will ask the user to enter a certain type of word
def PizzaPizza():
    adj1 = input("Adjective:")
    nat = input("Nationality:")
    person = input("First and Last Name:")
    noun1 = input("Noun:")
    adj2 = input("Adjective:")
    noun2 = input("Noun:")
    adj3 = input("Adjective:")
    adj4 = input("Adjective:")
    plural = input("Plural Noun:")
    noun3= input("Noun:")
    number = input("Number:")
    shapes = input("Shapes:")
    food = input("Food:")
    food1 = input("Food:")
    number2 = input("Number:")
# each word is represented by a variable to which will be placed in a paragraph to make the mad lib
# after the user enters in their last word their paragraph will print
    yes = 'Pizza was invented by a {} {} chef named {}. To make a pizza you need to \ntake a lump of {} and make a thin, round {} {} Then you cover it with {}, sauce\n{}, cheese, and fresh chopped {}. Next you have to bake it\nin a very hot {}. When it is done cut it into {}, {} Some kids like {} pizza the best, but my\nfavorite is the {} pizza. If I could, I would eat pizza {} times a day!\n'.format(adj1, nat, person, noun1, adj2, noun2, adj3, adj4, plural, noun3, number, shapes, food, food1, number2)
    print(yes)
    wf = open('madlibs.txt', 'a')
    wf.write(yes)
    wf.write('\n')
    wf.close()
# the paragraph will then print to a file and save it there
def Summer():
    name = input("First Name:")
    place = input("Place:")
    adj = input("Adjective:")
    plural = input("Plural Noun:")
    adj2 = input("Adjective:")
    plural2 = input("Plural Noun:")
    place1 = input("Place:")
    act = input("Action Verb:")
    plu= input("Plural Noun:")
    plu2 = input("Plural Noun:")
    ooun = input("Noun:")
    actv = input("Action Verb:")
    verbact = input("Action Verb:")
    adje = input("Adjective:")
# repeat the above 3 times for the same results in each theme
    yea = "Last summer, my mom and dad took me and {} on a trip to {}. The weather there is very\n{}! Northern {} has many {} and they make {} {} there. Many people\nalso go to {} to {} or see the {}. The people that live there\nlove to eat {} and are very proud of their big {}. They also like\nto {} in the sun and swim in the {}! It was a really {} trip!\n".format(name, place, adj, place, plural, adj2, plural2, place1, act, plu, plu2, ooun, actv, verbact, adje)
    print(yea)
    wf = open('madlibs.txt', 'a')
    wf.write(yea)
    wf.write('\n')
    wf.close()
def Astronaut():
    verbing = input("Verb Ending -ing:")
    verb = input("Verb:")
    vehicle = input("Vehicle:")
    verb1 = input("Verb:")
    tools = input("Tools:")
    nouns = input("Plural Noun:")
    color = input("Color:")
    adj = input("Adjective:")
    color1 = input("Color:")
    number = input("Number:")
    bod = input("Body Part:")
    bod1 = input("Body Part:")
    verby = input("Verb:")
    verb5 = input("Verb:")
    vehicle1 = input("Vehicle:")
    place = input("Place:")
    verb9 = input("Verb:")
    yed = "Instead of {} every day to an office, I want to {} to \nouter space on a {} for my job. I'd {} science experiments using {} and {}, and get \nto see {} holes and {} stars up close. Maybe I'd even get to meet and alien life form, with {} skin \nand  {} {} and {}. When it's time to {} to Earth I'll {} in a {}, and \nland safely in a {} where friends and family will {} me and welcome me home.\n".format(verbing, verb, vehicle, verb1, tools, nouns, color, adj, color1, number, bod, bod1, verby, verb5, vehicle1, place, verb9)
    print(yed)
    wf = open('madlibs.txt', 'a')
    wf.write(yed)
    wf.write('\n')
    wf.close()
Welcome()


# measure_wav.py
# Paul Boersma 2019-06-02
#
# A sample script that uses the OpenVokaturi library to extract the emotions from
# a wav file on disk. The file can contain a mono or stereo recording.
#
# Call syntax:
#   python3 measure_wav.py path_to_sound_file.wav

import sys
import scipy.io.wavfile
import json

sys.path.append("./lib")
import Vokaturi

def init(path):
    print("Loading library...")
    Vokaturi.load(path)
    print("Analyzed by: %s" % Vokaturi.versionAndLicense())

print("Reading sound file...")

def detect(audio, ar=11025):
    print("===== sample rate %d" % ar)
    samples = audio
    buffer_length = len(samples)
    print("   %d samples, %d channels" % (buffer_length, samples.ndim))
    c_buffer = Vokaturi.SampleArrayC(buffer_length)
    if samples.ndim == 1:
        c_buffer[:] = samples[:] / 32768.0  # mono
    else:
        c_buffer[:] = 0.5*(samples[:,0]+0.0+samples[:,1]) / 32768.0  # stereo

    print("Creating VokaturiVoice...")
    voice = Vokaturi.Voice(ar, buffer_length)

    print("Filling VokaturiVoice with samples...")
    voice.fill(buffer_length, c_buffer)

    print("Extracting emotions from VokaturiVoice...")
    quality = Vokaturi.Quality()
    emProb = Vokaturi.EmotionProbabilities()
    voice.extract(quality, emProb)

    if quality.valid:
        result = {}
        result['Neutral'] = emProb.neutrality
        result['Happy'] = emProb.happiness
        result['Sad'] = emProb.sadness
        result['Angry'] = emProb.anger
        result['Fear'] = emProb.fear
        return result
    else:
        return {'msg': 'quality is invalid'}
    voice.destroy()


import os
import socket
import sys

#create an INET, STREAMing socket
s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)
#now connect to the web server on port 80
# - the normal http port
s.connect((socket.gethostname(), 8000))

message = "test"

s.sendall(message)
oded = s.recv(2014)
print >>sys.stderr, oded


import random

# Constants
FASTFW_START = 1*10**9
FASTFW_END = int(1.1*10**9)
WORKLOAD_COUNT = 40
SEED = 5669
BW_BM = 2
REST_BM = 2

# Benchmarks
bw_benchmarks = ['mcf','gap','apsi','facerec', 'galgel', 'mesa', 'swim']
other_benchmarks = ['wupwise', 'vortex1', 'sixtrack', 'gcc', 'art', 'gzip', 'mgrid', 'applu']

#bw_benchmarks = ['gcc', 'wupwise', 'swim', 'mgrid', 'applu', 'art', 'facerec', 'ammp', 'lucas', 'apsi']
#other_benchmarks = ['gzip', 'vpr', 'mcf', 'crafty', 'parser', 'eon', 'perlbmk', 'gap', 'vortex1', 'bzip', 'twolf', 'mesa', 'galgel', 'equake', 'sixtrack', 'fma3d']
cpus = [4]

random.seed(SEED)

outfile = open("workloads.py", 'w')
outfile.write("# Autogenerated workload configuration file\n\n")
outfile.write("workloads = {\n\n")

for cpu_count in cpus:

    outfile.write(str(cpu_count)+":{\n")
    for i in range(WORKLOAD_COUNT):

        useBenchmarks = []
        useFW = []

        num_bw = 0
        num_all = 0

        for j in range(BW_BM):
            fastfw = random.randint(FASTFW_START, FASTFW_END)

            bm = -1
            run = True
            while run:
                bm = random.randint(0, len(bw_benchmarks)-1)
                allreadyInUse = False
                for b in useBenchmarks:
                    if bw_benchmarks[bm] == b:
                        allreadyInUse = True

                if not allreadyInUse:
                    run = False

            useFW.append(fastfw)
            useBenchmarks.append(bw_benchmarks[bm])

        for j in range(REST_BM):
            fastfw = random.randint(FASTFW_START, FASTFW_END)

            bm = -1
            run = True
            while run:
                bm = random.randint(0, len(other_benchmarks)-1)
                allreadyInUse = False
                for b in useBenchmarks:
                    if other_benchmarks[bm] == b:
                        allreadyInUse = True

                if not allreadyInUse:
                    run = False

            useFW.append(fastfw)
            useBenchmarks.append(other_benchmarks[bm])

        if i == (WORKLOAD_COUNT-1):
            outfile.write(str(i+1)+":("+str(useBenchmarks)+","+str(useFW)+")\n")
        else:
            outfile.write(str(i+1)+":("+str(useBenchmarks)+","+str(useFW)+"),\n")

    outfile.write("},\n\n")

outfile.write("}\n")
outfile.close()


# Sebastian Thomas (coding at sebastianthomas dot de)

# https://leetcode.com/problems/climbing-stairs/
#
# 70. Climbing Stairs
#
# You are climbing a staircase. It takes n steps to reach the top.
#
# Each time you can either climb 1 or 2 steps. In how many distinct ways
# can you climb to the top?

def climb_stairs(n: int) -> int:
    if n == 0 or n == 1:
        return 1

    last_count = 1
    count = 1
    for _ in range(n - 1):
        last_count, count = count, last_count + count

    return count

if __name__ == '__main__':
    print(climb_stairs(2))  # 2
    print(climb_stairs(3))  # 3


class Solution(object):
    def maxProductPath(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int

        Optimization problem
            - Greedy
            - Dynamic Programming
        ans = self.dp(grid, 0, 0)
        return ans % (10**9 + 7) if ans >= 0 else -1

    def dp(self, grid, row, col):
        if (row, col) == (len(grid)-1, len(grid[0])-1):
            return grid[row][col]

        moveRight, moveDown = 0, 0

    def greedy():

           [1,-2,1]
           [1,-2,1]
           [3,-4,1]

        heap -> store the coordinate and the current product
                sort the heap based on the current product
                max heap

        use a heap to do a greedy bfs

        while elements in the heap
            remove coordinate and product
            if current coordinate is target, return the current product
            check down and right moves
                if in bounds
                    add to heap and update coordinate and product
        """
        self.memo = {}
        ans = self.dp(grid, 0, 0, grid[0][0])
        return ans % (10**9 + 7) if ans >= 0 else -1

    def dp(self, grid, row, col, currProduct):
        if (row, col, currProduct) in self.memo:
            return self.memo[(row, col, currProduct)]
        if (row, col) == (len(grid)-1, len(grid[0])-1):
            return currProduct

        moveRight, moveDown = float('-inf'), float('-inf')

        if row + 1 < len(grid):
            moveDown = self.dp(grid, row+1, col, currProduct * grid[row+1][col])

        if col + 1 < len(grid[0]):
            moveRight = self.dp(grid, row, col+1, currProduct * grid[row][col+1])

        self.memo[(row, col, currProduct)] = max(moveRight, moveDown)
        return max(moveRight, moveDown)

    def greedy():

        heap = [(-grid[0][0], 0, 0)]  # product, row, col
        targetRow, targetCol = len(grid)-1, len(grid[0])-1
        moves = [(0,1),(1,0)]
        ans = float('-inf')
        seen = set()

        while heap:
            currProduct, currRow, currCol = heapq.heappop(heap)
            currProduct *= -1

            if (currRow, currCol, currProduct) in seen:
                continue

            seen.add((currRow, currCol, currProduct))

            if (currRow, currCol) == (targetRow, targetCol):
                ans = max(ans, currProduct)
                continue

            for moveRow, moveCol in moves:
                newRow, newCol = currRow+moveRow, currCol+moveCol
                if 0<=newRow<len(grid) and 0<=newCol<len(grid[0]):  # if in bounds
                    newProduct = currProduct * grid[newRow][newCol]
                    heapq.heappush(heap, (-newProduct, newRow, newCol))

        return ans % (10**9 + 7) if ans >= 0 else -1

Algorithms/Leetcode/1594 - Maximum Non Negative Product in a Matrix.py


from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense, Conv2D, MaxPooling2D
from datetime import datetime, timedelta
from prefect import Flow, Parameter, task
from prefect.schedules import IntervalSchedule
import warnings
warnings.filterwarnings(action="ignore")
from sklearn.metrics import balanced_accuracy_score, f1_score, \
    roc_auc_score, precision_score, recall_score
import os
import mlflow
from dagshub import DAGsHubLogger
from tensorflow.keras.models import load_model

image_shape = (130,130,3)

train_path = 'data\cell_images/train'
test_path = 'data\cell_images/test'

batch_size = 16

image_gen = ImageDataGenerator(rotation_range=20,  # rotate the image 20 degrees
                               width_shift_range=0.10,  # Shift the pic width by a max of 5%
                               height_shift_range=0.10,  # Shift the pic height by a max of 5%
                               # rescale=1/255, # Rescale the image by normalzing it.
                               shear_range=0.1,  # Shear means cutting away part of the image (max 10%)
                               zoom_range=0.1,  # Zoom in by 10% max
                               horizontal_flip=True,  # Allo horizontal flipping
                               fill_mode='nearest'  # Fill in missing pixels with the nearest filled value
                               )

train_image_gen = image_gen.flow_from_directory(train_path,
                                                target_size=image_shape[:2],
                                                color_mode='rgb',
                                                batch_size=batch_size,
                                                class_mode='binary')

test_image_gen = image_gen.flow_from_directory(test_path,
                                               target_size=image_shape[:2],
                                               color_mode='rgb',
                                               batch_size=batch_size,
                                               class_mode='binary', shuffle=False)

train_path = 'data\cell_images\train'
test_path = 'data\cell_images\test'

@task
def train_model():
    model = Sequential()

    model.add(Conv2D(filters=32, kernel_size=(3, 3), input_shape=image_shape, activation='relu', ))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(filters=64, kernel_size=(3, 3), input_shape=image_shape, activation='relu', ))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(filters=64, kernel_size=(3, 3), input_shape=image_shape, activation='relu', ))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())

    model.add(Dense(128))
    model.add(Activation('relu'))

    # Dropouts help reduce overfitting by randomly turning neurons off during training.
    # Here we say randomly turn off 50% of neurons.
    model.add(Dropout(0.5))

    # Last layer, remember its binary so we use sigmoid
    model.add(Dense(1))
    model.add(Activation('sigmoid'))

    model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

    model.summary()

    early_stop = EarlyStopping(monitor='val_loss', patience=2)

    warnings.filterwarnings('ignore')

    model.fit_generator(train_image_gen, epochs=20,
                        validation_data=test_image_gen,
                        callbacks=[early_stop])
    model.save('model/malaria_detector_model.h5')
    return model

@task
def evaluate(a):
    #link up to dagshub MLFlow environment
    os.environ['MLFLOW_TRACKING_URI'] = 'https://dagshub.com/joe88data/deep_learning_model_for_detecting_malaria_infected_red_blood_cell.mlflow'
    os.environ['MLFLOW_TRACKING_USERNAME'] = 'joe88data'
    os.environ['MLFLOW_TRACKING_PASSWORD'] = 'e94114ca328c75772401898d749decb6dbcbeb21'
    with mlflow.start_run():
        # Load data and model
        a  = load_model('model/malaria_detector_model.h5')
        a.evaluate_generator(test_image_gen)
        pred_probabilities = a.predict_generator(test_image_gen)

        # Get predictions
        predictions = pred_probabilities > 0.5

        # Get metrics
        f1 = f1_score(test_image_gen.classes,predictions)
        print(f"F1 Score of this model is {f1}.")

        # get metrics
        accuracy = balanced_accuracy_score(test_image_gen.classes,predictions)
        print(f"Accuracy Score of this model is {accuracy}.")

        area_under_roc = roc_auc_score(test_image_gen.classes,predictions)
        print(f"Area Under ROC is {area_under_roc}.")

        precision = precision_score(test_image_gen.classes,predictions)
        print(f"Precision of this model is {precision}.")

        recall = recall_score(test_image_gen.classes,predictions)
        print(f"Recall for this model is {recall}.")

        # helper class for logging model and metrics
        class BaseLogger:
            def __init__(self):
                self.logger = DAGsHubLogger()

            def log_metrics(self, metrics: dict):
                mlflow.log_metrics(metrics)
                self.logger.log_metrics(metrics)

        logger = BaseLogger()

        # function to log metrics to dagshub and mlflow
        def log_metrics(**metrics: dict):
            logger.log_metrics(metrics)
        # log metrics to remote server (dagshub)
        #log_params(a)
        log_metrics(f1_score=f1, accuracy_score=accuracy, area_Under_ROC=area_under_roc, precision=precision,
                recall=recall)

#adding schedule here automate the pipeline and make it run every 10 minutes
schedule = IntervalSchedule(interval=timedelta(minutes=10))

#create and run flow locally. To schedule to workflow to be automatically triggered every 4 hrs,
#add 'schedule' as Flow parameter (ie with Flow("loan-default-prediction", schedule)
with Flow("malaria_detection_model_training_flow") as flow:
    model = train_model()
    evaluate(model)

#flow.visualize()
flow.run()
#connect to prefect 1 cloud
flow.register(project_name='malaria-detection-model')
flow.run_agent()


from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtGui
import qdarkgraystyle
from datetime import date
import requests
import threading
import os
import bar_search
import traceback, sys

# Defines all the signals we'll need for the the various processes we are running in Qthreads
class WorkerSignals(QObject):
    finished = pyqtSignal()
    result = pyqtSignal(object)
    error = pyqtSignal(tuple)
    progress = pyqtSignal(int)

class Worker(QRunnable):
    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        # Store constructor arguments (re-used for processing)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        # Add the callback to our kwargs
        self.kwargs['progress_callback'] = self.signals.progress

    @pyqtSlot()
    def run(self):
        # Retrieve args/kwargs here; and fire processing using them
        try:
            result = self.fn(*self.args, **self.kwargs)
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result)  # Return the result of the processing
        finally:
            self.signals.finished.emit()  # Done

class Main_Window(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(Main_Window, self).__init__(*args, **kwargs)

        # Download thread
        self.download = None
        self.window_exited = False
        self.downloading = False;

        # Creates threadpool to handle threads
        self.threadpool = QThreadPool()

        # Scraping thread
        self.scrape = threading.Thread(target=self.scrape_data)

        self.fileName = ''

        self.style = qdarkgraystyle.load_stylesheet()

        self.setStyleSheet(self.style)
        self.setFixedSize(350, 220)
        self.setWindowTitle("Bar Code Analyzer")
        self.setWindowIcon(QtGui.QIcon("graphics/blue-document-excel-table.png"))

        self.main_layout = QVBoxLayout()

        self.top_layout = QVBoxLayout()

        self.choose_layout = QHBoxLayout()

        self.update_layout = QHBoxLayout()

        self.output_file_layout = QHBoxLayout()

        self.control_layout = QHBoxLayout()

        # Choose button horizontal layout
        self.choose_button = QPushButton('Choose File')
        self.choose_button.setFixedWidth(75)
        self.choose_button.clicked.connect(self.choose_file)
        self.choose_button.setToolTip('Choose input .xlsx file for barcode analyzer')

        self.hchoose_button = QPushButton('?')
        self.hchoose_button.clicked.connect(
            lambda: self.info_popup('About the Input File', 'Please select the excel file '
                                                            'containing the barcodes you '
                                                            'wish to input \n\nThe '
                                                            'requirements for this file '
                                                            'are as follows:\n1. The '
                                                            'barcodes must be stored in '
                                                            'the first column.\n2. Column '
                                                            'A must have a header of '
                                                            '"Barcodes".\n3. The barcode '
                                                            'data must be stored as a '
                                                            'String.'))
        self.hchoose_button.setFixedWidth(25)
        self.hchoose_button.setToolTip('Help')

        self.choose_label = QLabel()

        self.choose_layout.addWidget(self.choose_button)
        self.choose_layout.addWidget(self.hchoose_button)
        self.choose_layout.addWidget(self.choose_label)

        # Update button horizontal layout

        self.update_button = QPushButton('Update')
        self.update_button.clicked.connect(self.update_database)
        self.update_button.setToolTip('Updates database to current version')

        self.hupdate_button = QPushButton('?')
        self.hupdate_button.setFixedWidth(25)
        self.hupdate_button.clicked.connect(lambda: self.info_popup('About Updating', 'This functions updates the '
                                                                                '.csv file used for pulling the '
                                                                                'data for each for of the '
                                                                                'barcodes. It takes about 2-3 '
                                                                                'minutes to update and is '
                                                                                'generally a good idea if you '
                                                                                'think some data is missing in '
                                                                                'the output. Please do not '
                                                                                'close the program while it is '
                                                                                'updating'))
        self.hupdate_button.setToolTip('Help')

        date_txt = open('data/update_date.txt', 'r')
        date = date_txt.readline()
        self.update_label = QLabel('Last Updated: ' + date[:len(date) - 1])
        self.update_label.setAlignment(Qt.AlignCenter)

        self.update_layout.addWidget(self.update_button)
        self.update_layout.addWidget(self.hupdate_button)
        self.update_layout.addWidget(self.update_label)

        # Creates Scrape Data button

        self.scrape_button = QPushButton('Scrape Data')
        self.scrape_button.setEnabled(False)
        self.scrape_button.clicked.connect(self.scrape_wrapper)

        # Output file path

        self.output_label = QLabel('Output Path:')
        self.output_entry = QLineEdit()
        self.output_entry.setText(os.path.expanduser('~\\Documents\\output_workbook.xlsx'))

        self.output_file_layout.addWidget(self.output_label)
        self.output_file_layout.addWidget(self.output_entry)

        # Assembles top layout

        self.top_layout.addLayout(self.choose_layout)
        self.top_layout.addLayout(self.update_layout)
        self.top_layout.addSpacerItem(QSpacerItem(10,5))
        self.top_layout.addLayout(self.output_file_layout)
        self.top_layout.addWidget(self.scrape_button)

        # Assembles main layout

        self.main_layout.addLayout(self.top_layout)

        self.progress_bar = QProgressBar()
        self.progress_bar.setAlignment(Qt.AlignCenter)
        self.progress_bar.setValue(0)
        self.main_layout.addWidget(self.progress_bar)

        # Sets the layout to main window

        self.widget = QWidget()
        self.widget.setLayout(self.main_layout)

        self.setCentralWidget(self.widget)

    def closeEvent(self, event):
        self.window_exited = True
        self.downloading = False

        print('Quitting')
        self.download.quit()
        os.remove('data/temp.csv')
        if self.scrape.is_alive():
            self.scrape.join()

    def choose_file(self):
        self.fileName = QFileDialog.getOpenFileName(self, 'Select Input Excel File', os.path.expanduser('~/Documents'), 'Excel Files (*.xlsx)')
        temp = str(self.fileName[0])
        try:
            temp.index(':')
        except ValueError:
            return
        else:
            self.choose_label.setText(temp)
            self.scrape_button.setEnabled(True)

    def throw_error(self, title, text):
        error = QMessageBox()
        error.setWindowTitle(title)
        error.setText(text)
        error.setWindowIcon(QtGui.QIcon("graphics/compile-error.png"))
        error.setIcon(QMessageBox.Critical)

        error.exec()

    def info_popup(self, title, text):
        popup = QMessageBox()
        popup.setWindowTitle(title)
        popup.setText(text)
        popup.setWindowIcon(QtGui.QIcon("graphics/information.png"))
        popup.setIcon(QMessageBox.Information)

        popup.exec_()

    def update_database(self):
        today = date.today()
        self.update_date = today.strftime("%m/%d/%y")
        self.update_label.setText('Last Updated: ' + self.update_date)

        date_txt = open("data/update_date.txt", "w")

        print(self.update_date, file=date_txt)
        date_txt.close()

        self.update_button.setEnabled(False)
        self.scrape_button.setEnabled(False)

        self.download = Worker(self.download_csv)

        self.downloading = True;

        self.download.signals.finished.connect(self.download_cleanup)
        self.download.signals.progress.connect(self.progress_bar.setValue)

        self.threadpool.start(self.download)

    def download_csv(self, progress_callback):
        print('Beginning file download with requests')

        url = "https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv"

        # Downloading file
        with open('/Users/Elliot/PycharmProjects/Bar-Code-Nutrition-Data/data/temp.csv',
                  'wb') as f:
            response = requests.get(url, stream=True)
            total_length = 2917101258
            dl = 0
            total_length = int(total_length)
            for data in response.iter_content(chunk_size=8192):
                dl += len(data)
                f.write(data)

                # Calculating approx progress
                progress = int((float(dl) / float(total_length)) * 100)

                # Emitting signal to progress update function in order to safely update the value
                progress_callback.emit(progress)

                # Abort flag for thread in case download gets interrupted
                #if not self.downloading:
                    #return
            f.close()

    def download_cleanup(self):
        print('Clean starting')
        os.remove('data/en.openfoodfacts.org.products.csv')
        os.rename('data/temp.csv', 'data/en.openfoodfacts.org.products.csv')
        self.reset_window()

    def scrape_wrapper(self):
        if not self.scrape.is_alive():
            self.update_button.setEnabled(False)
            self.choose_button.setEnabled(False)
            self.scrape.start()
            self.scrape_button.setText('Stop')
        else:
            self.window_exited = True
            self.scrape.join()
            self.reset_window()

    def scrape_data(self):
        bc = bar_search.getBarcodes(self.fileName[0])
        scraped_data = bar_search.read_csv(bc, window=self)
        if scraped_data is None:
            return
        bar_search.write_xl(scraped_data, path=self.output_entry.text())
        return

    def reset_window(self):
        self.scrape_button.setEnabled(True)
        self.scrape_button.setText('Scrape Data')
        self.choose_button.setEnabled(True)
        self.progress_bar.setValue(0)

app = QApplication([])

window = Main_Window()
window.show()

app.exec_()


# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# <codecell>

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

labels = ['Positive', 'Negative', 'Others']
fracs_ios4 = [745, 530, 2552 - 745 - 530]
fracs_ios5 = [787, 451, 2491 - 787 - 451]
fracs_ios6 = [843, 492, 2611 - 843 - 492]
fracs_ios7 = [729, 595, 2374 - 729 - 595]

explode = (0.05, 0, 0)

colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', 'burlywood']
plt.title('')
the_grid = GridSpec(2, 2)
plt.subplot(the_grid[0, 0], aspect = 1)
plt.pie(fracs_ios4, explode, labels = labels, colors = colors,
        autopct = '%1.1f%%', shadow = True)
plt.title('iOS 4', bbox = {'facecolor':'white', 'alpha':0.5, 'pad':5})

plt.subplot(the_grid[0, 1], aspect = 1)
plt.pie(fracs_ios5, explode, labels = labels, colors = colors,
        autopct = '%1.1f%%', shadow = True)
plt.title('iOS 5', bbox = {'facecolor':'white', 'alpha':0.5, 'pad':5})

plt.subplot(the_grid[1, 0], aspect = 1)
plt.pie(fracs_ios6, explode, labels = labels, colors = colors,
        autopct = '%1.1f%%', shadow = True)
plt.title('iOS 6', bbox = {'facecolor':'white', 'alpha':0.5, 'pad':5})

plt.subplot(the_grid[1, 1], aspect = 1)
plt.pie(fracs_ios7, explode, labels = labels, colors = colors,
        autopct = '%1.1f%%', shadow = True)
plt.title('iOS 7', bbox = {'facecolor':'white', 'alpha':0.5, 'pad':5})

plt.show()

# <codecell>


# importing required libraries
import math
import rasterio
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
import cv2
from functools import lru_cache

@lru_cache(maxsize=32)
def import_data(url):
  return rasterio.open(url)

# claculate NDVI using ndvi_calculation function
def ndvi_calculation(band_nir,band_red):
  ndvi = (band_nir.astype(float) - band_red.astype(float)) / (band_nir + band_red) # The Eq. for ndvi
  return ndvi

def calculate(url, ndviValue=0):

  # opening the tiff file
  sat_data = import_data(url)
  width_in_projected_units = sat_data.bounds.right - sat_data.bounds.left
  height_in_projected_units = sat_data.bounds.top - sat_data.bounds.bottom
  print("Width: {}, Height: {}".format(width_in_projected_units, height_in_projected_units))

  #print the shape of data
  sat_data.shape
  print(sat_data)

  #print the width and height
  print("Rows: {}, Columns: {}".format(sat_data.height, sat_data.width))
  row_min = 0
  col_min = 0
  row_max = sat_data.height - 1
  col_max = sat_data.width - 1
  topleft = sat_data.transform * (row_min, col_min)
  botright = sat_data.transform * (row_max, col_max)
  print("Top left corner coordinates: {}".format(topleft))
  print("Bottom right corner coordinates: {}".format(botright))

  # print the number of bands
  print(sat_data.count)

  #the indices will be 8 beacuse it has 8 dimeansions
  print(sat_data.indexes)

  with rasterio.open(url) as src: #reads red (6th) band
    band_red = src.read(6)
  with rasterio.open(url) as src: #reads nir (8th) band
    band_nir = src.read(8)

  np.seterr(divide='ignore',invalid='ignore')

  # checking the output for the ndvi_calculation fuction
  ndvi = ndvi_calculation(band_nir,band_red)

  print(np.nanmin(ndvi))
  print(np.nanmax(ndvi))

  meta = src.meta
  print(meta)

  ndvi_dtype = ndvi.dtype
  print(ndvi_dtype)

  kwargs = meta

  kwargs.update(dtype=ndvi_dtype)

  kwargs.update(count=1)

  with rasterio.open('Newimage.tif', 'w', **kwargs) as dst:
          dst.write(ndvi, 1)

  class MidpointNormalize(colors.Normalize):

      def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
          self.midpoint = midpoint
          colors.Normalize.__init__(self, vmin, vmax, clip)

      def __call__(self, value, clip=None):

          x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
          return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))

  # Write it out to a GeoTIff file in a EPSG 4326 projection
  with rasterio.open(
          'Newimage.tif',
          'w',
          driver='GTiff',
          width=sat_data.width,
          height=sat_data.height,
          count=1,
          dtype= np.uint8,
          nodata=0,
          transform=sat_data.transform,
          crs={'init': 'EPSG:4326'}) as dst:
      dst.write(ndvi, 1)

  min=np.nanmin(ndvi)
  max=np.nanmax(ndvi)

  mid=0.1

  # Display NDVI through Red-Yellow-Blue color
  colormap = plt.cm.RdYlGn
  norm = MidpointNormalize(vmin=min, vmax=max, midpoint=mid)
  fig = plt.figure(figsize=(20,10))

  ax = fig.add_subplot(111)
  cbar_plot = ax.imshow(ndvi, cmap=colormap, vmin=min, vmax=max, norm=norm)
  ax.axis('off')
  ax.set_title('NDVI Index', fontsize=17, fontweight='bold')

  cbar = fig.colorbar(cbar_plot, shrink=0.65)

  fig.savefig("ndvi-image.jpg", dpi=300, bbox_inches='tight', pad_inches=0.7)

  # display the image with NDVI values
  plt.show()

  fig2 = plt.figure(figsize=(20,10))
  ax = fig2.add_subplot(111)

  # display the Histogram for NDVI to explore pixel number vs. NDVI value
  plt.title("NDVI Histogram", fontsize=18, fontweight='bold')
  plt.xlabel("NDVI values", fontsize=14)
  plt.ylabel("Number of pixels", fontsize=14)

  x = ndvi[~np.isnan(ndvi)]
  color = 'g'
  ax.hist(x,bins=30,color=color,histtype='bar', ec='black')
  plt.show()

  min=np.nanmin(ndvi)
  max=np.nanmax(ndvi)

  mid=0.1

  colormap = plt.cm.RdYlGn
  norm = MidpointNormalize(vmin=min, vmax=max, midpoint=mid)
  fig1 = plt.figure(figsize=(20,10))

  ax = fig1.add_subplot(111)
  cbar_plot = ax.imshow(ndvi, cmap=colormap, vmin=min, vmax=max, norm=norm)
  ax.axis('off')

  fig1.savefig("ndviresult.jpg", dpi=600, bbox_inches='tight', pad_inches=0.7)

  ndvi_min=np.nanmin(ndvi)
  ndvi_max=np.nanmax(ndvi)
  print(min)
  print(max)
  print('Min NDVI: %.3f, Max NDVI: %.3f' % (np.nanmin(ndvi), np.nanmax(ndvi)))
  ndvi_range = max -min
  print('ndvi_range:',ndvi_range)

  # open the saved image
  image1 = cv2.imread('ndviresult.jpg')
  # converting the image into grey scale color
  img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)

  # determine the minimum and maximum NDVI values
  print('Min NDVI: %.3f, Max NDVI: %.3f' % (np.nanmin(ndvi), np.nanmax(ndvi)))
  # ask the user to enter a valid NDVI value

  ndvi_range = (ndvi_max - ndvi_min)
  newMax = 255
  newMin = 0
  NewRange = (newMax - newMin)

  # converting the NDVI value entered by user into 0-255 scale
  NewValue = (((ndviValue - ndvi_min) * NewRange) / ndvi_range) + newMin
  NewValue = int(NewValue)

  # convert the greay scale image into a binary image using the specified NDVI threshold
  ret, thresh2 = cv2.threshold(img, NewValue, 255, cv2.THRESH_BINARY_INV)

  # display the binary NDVI image result
  cv2.imshow(thresh2)

  # save the output binary image
  cv2.imwrite('imageBinary.jpg', thresh2)


import sys
sys.stdin = open("input.txt", "r")

T = int(input())
for test_case in range(1, T + 1):
    time = int(input())
    check = list(map(int, input().split()))
    check.sort()
    most = check[0]
    many = 1
    now_many = 1
    now = check[0]
    for i in range(1, len(check)):
        if now != check[i]:
            if now_many >= many:
                most = check[i-1]
                many = now_many
            now = check[i]
            now_many = 1
        else:
            now_many += 1
    print("#", end="")
    print(test_case, end=" ")
    print(most)


import random
from exceptions.letter_input_errors import LetterAlreadyGuessedError

class Word:
    words = tuple(["python", "java", "swift", "javascript"])

    def __init__(self):
        self.word = Word.words[random.randint(0, len(Word.words) - 1)]
        self.revealed_word = "-" * len(self.word)
        self.guessed_letters = set()

    def reveal_letters(self, letter):
        found = False

        if letter in self.guessed_letters:
            print(self.guessed_letters)
            raise LetterAlreadyGuessedError()

        for i, word_letter in enumerate(self.word):
            if letter == word_letter:
                revealed = list(self.revealed_word)
                revealed[i] = letter
                self.revealed_word = "".join(revealed)
                found = True

        self.guessed_letters.add(letter)

        return found


import sys
input = sys.stdin.readline

n, m = map(int, input().split())

map = [list(input().rstrip()) for _ in range(n)]
check = [[0]*m for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def bfs():
    q = [(0, 0)]
    while q:
        x, y = q.pop(0)
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx >= 0 and ny >= 0 and nx < n and ny < m and map[nx][ny] == '1' and check[nx][ny] == 0:
                check[nx][ny] = check[x][y] + 1
                q.append((nx, ny))
    return check[n-1][m-1]

print(bfs()+1)