# Copyright 1997 - 2018 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from ixnetwork_restpy.base import Base
from ixnetwork_restpy.errors import IxNetworkError

class Sessions(Base):
    """Sessions class

    Manage IxNetwork sessions based on the connection information provided to the TestPlatform class.

    Child classes:
        Sessions.Ixnetwork
    """
    _SDM_NAME = 'sessions'

    def __init__(self, parent):
        super(Sessions, self).__init__(parent)

    @property
    def Ixnetwork(self):
        """An instance of the Ixnetwork class

        Returns:
            obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.ixnetwork.Ixnetwork):

        Raises:
            ValueError: If the version of IxNetwork server is not suporrted. The minimum version supported is 8.42.
        """
        from ixnetwork_restpy.testplatform.sessions.ixnetwork.ixnetwork import Ixnetwork
        ixnetwork = Ixnetwork(self)
        build_number = ixnetwork._connection._read('%s/ixnetwork/globals' % self.href)['buildNumber']
        from distutils.version import LooseVersion
        if LooseVersion(build_number) < LooseVersion('8.42'):
            raise ValueError('IxNetwork server version %s is not supported. The minimum version supported is 8.42' % build_number)
        ixnetwork._set_properties(ixnetwork._connection._read('%s/%s' % (self.href, Ixnetwork._SDM_NAME)))
        return ixnetwork

    @property
    def State(self):
        """The state of the session

        Returns:
            str
        """
        return self._properties['state'].upper()

    @property
    def ApplicationType(self):
        """The application type of the session

        Returns:
            str
        """
        return self._properties['applicationType']

    @property
    def Id(self):
        """The id of the session

        Returns:
            number
        """
        return self._properties['id']

    @property
    def UserId(self):
        """The user id of the session

        Returns:
            str
        """
        return self._properties['userId']

    @property
    def UserName(self):
        """The user name of the session

        Returns:
            str
        """
        return self._properties['userName']

    def Start(self):
        """Starts the session

        Returns:
            None
        """
        if self._connection._platform != 'windows':
            response = self._execute('start', payload={'applicationType': self.ApplicationType})
            if response is not None:
                self._set_properties(response, clear=True)

    def find(self, Id=None):
        """Finds all child instances of Sessions on the server.

        Raises:
            ServerError: The server has encountered an uncategorized error condition
        """
        responses = self._connection._read('%s/%s' % (self._parent.href, self._SDM_NAME))
        self._clear()
        for response in responses:
            if Id is not None:
                if str(response['id']) == str(Id):
                    self._set_properties(response)
            else:
                self._set_properties(response)
        return self

    def add(self):
        """Adds a new sessions node on the server and retrieves it in this instance.

        Raises:
            ServerError: The server has encountered an uncategorized error condition
        """
        applicationType = 'ixnrest'
        self._create(locals())
        if self._connection._platform == 'linux':
            self.Start()
        return self

    def remove(self):
        """Deletes all the sessions data in this instance from server.

        Raises:
            NotFoundError: The requested resource does not exist on the server
            ServerError: The server has encountered an uncategorized error condition
        """
        try:
            self._execute('stop')
            self._delete()
        except IxNetworkError as e:
            if e._status_code not in [404, 405]:
                raise e

    def GetObjectFromHref(self, href):
        """Given an href get the corresponding object

        References are used to establish relationships between disparate nodes.
        This allows a user to get an object using a reference from a node.
        For example:
            A /vport node has a ConnectedTo property that is a reference to an /availableHardware/chassis/card/port node.
            A user can get a vport and use this method to get the port node in order to clear ownership

        Args:
            href (str): A valid href reference

        Returns:
            obj | None: If the reference is valid an ixnetwork_restpy object or None if the reference cannot be resolved
        """
        try:
            node = self
            for piece in href[href.find('ixnetwork'):].split('/'):
                if piece.isdigit():
                    for item in node:
                        if item.href.split('/').pop() == piece:
                            node = node._read(item.href)
                            break
                else:
                    class_name = '%s%s' % (piece[0].upper(), piece[1:])
                    node = getattr(node, class_name)
                    if hasattr(node, 'find') is True:
                        node.find()
            return node
        except:
            return None

    def GetFileList(self, remote_directory=None):
        """Get a list of files from the IxNetwork session instance

        Args:
            remote_directory (str): A remote directory path

        Returns:
            dict(root_path, list(dict(filename, filesize)): A list of all the files for a given directory
        """
        href = '%s/ixnetwork/files' % self.href
        if remote_directory is not None:
            href = '%s?absolute=remote_directory'
        return self._connection._read(href)

    def DownloadFile(self, remote_filename, local_filename = None):
        """Download a file from the IxNetwork session instance

        Args:
            remote_fileanme (str): the name of the remote file
            local_filename (str): the name that the remote contents will be saved to

        Returns:
            str: the local file name
        """
        return self._connection._get_file('%s/ixnetwork' % self.href, remote_filename=remote_filename, local_filename=local_filename)

    def UploadFile(self, local_filename, remote_filename=None):
        """Upload a file to the IxNetwork session instance

        Args:
            local_filename (str): the name of the local file
            remote_filename (str): the name that will be used when saving the file on the IxNetwork sesson instance

        Returns:
            dict(filename, filesize): Details of the file that was uploaded
        """
        return self._connection._put_file('%s/ixnetwork' % self.href, local_filename=local_filename, remote_filename=remote_filename)


from __future__ import absolute_import, unicode_literals

import unittest

from fluent.runtime import FluentBundle
from fluent.runtime.errors import FluentReferenceError

from ..utils import dedent_ftl

class TestVariants(unittest.TestCase):

    def setUp(self):
        self.ctx = FluentBundle(['en-US'], use_isolating=False)
        self.ctx.add_messages(dedent_ftl("""
            -variant = {
                [a] A
               *[b] B
             }
            foo = { -variant }
            bar = { -variant[a] }
            baz = { -variant[b] }
            qux = { -variant[c] }
        """))

    def test_returns_the_default_variant(self):
        val, errs = self.ctx.format('foo', {})
        self.assertEqual(val, 'B')
        self.assertEqual(len(errs), 0)

    def test_choose_other_variant(self):
        val, errs = self.ctx.format('bar', {})
        self.assertEqual(val, 'A')
        self.assertEqual(len(errs), 0)

    def test_choose_default_variant(self):
        val, errs = self.ctx.format('baz', {})
        self.assertEqual(val, 'B')
        self.assertEqual(len(errs), 0)

    def test_choose_missing_variant(self):
        val, errs = self.ctx.format('qux', {})
        self.assertEqual(val, 'B')
        self.assertEqual(len(errs), 1)
        self.assertEqual(
            errs,
            [FluentReferenceError("Unknown variant: c")])


from flask import Flask, request, abort
from flask_sqlalchemy import SQLAlchemy
import logging
import os
import sys

from hero.adapters.web.config import Config
from hero.adapters.slack.verify_request import verify_request

LOGGER = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(Config)

@app.route("/", methods=["POST"])
def index():
    return str(main(request))

@app.route("/claim", methods=["POST"])
def claim():
    from hero.core import claim

    return str(claim(request))

def main(request):
    try:
        request.data = request.get_data()
        if not verify_request(request):
            abort(403)

        from hero.core import start, stop, claim, high_score

        method = request.form["text"]
        if method == "start":
            return start(request.form)
        elif method == "stop":
            return stop(request.form)
        elif method == "high_score":
            return high_score(request.form)
        else:
            LOGGER.error("Invalid method: %s", str(request))
            raise ValueError(f"You tried to use an invalid method: {method}")
    except Exception as e:
        LOGGER.error(str(e))
        raise e


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 22:06:09 2018
format the data
@author: fatmi
"""
import re

fo = open("MFE-C-1-6.txt","r+")
tarFile = open("foramt-MFE-C.txt","w")
seqnumber = 1

while(True):
    #create the sequence for folding
    seqRead = fo.readline()
    if len(seqRead) == 0:
        break
    seqChop = seqRead.strip()
    if seqChop[0:3] != "GCA":
        result = re.search('-\d{0,2}\.\d{0,2}',seqChop)
        textout = str(result.group(0))
        tarFile.write(textout)
        tarFile.write("\n")

#close file handle
fo.close()
tarFile.close()


import numpy as np
import h5py
import seaborn as sns
import matplotlib.pyplot as plt

out = h5py.File('../output/BetaPlane/BetaPlane.mat');
out = out['out']
freqUnstb = out['freq'].value.view(np.double)*24*3600/2/3.14159
growthUnstb = out['growth'].value.view(np.double)*24*3600
wnUnstb = out['wn'].value.view(np.double)

freq = freqUnstb[np.where(growthUnstb>0)]
growth = growthUnstb[np.where(growthUnstb>0)]
wn = wnUnstb[np.where(growthUnstb>0)]

growth = growth[np.where(np.logical_and(freq<1, abs(freq)>0.05))]
wn = wn[np.where(np.logical_and(freq<1, abs(freq)>0.05))]
freq = freq[np.where(np.logical_and(freq<1, abs(freq)>0.05))]

msize = growth.flatten()*40
malpha = msize/max(msize)*0.85

plt.scatter(wn*freq/abs(freq),abs(freq),c='0.5',edgecolor='face',s=msize**2,alpha=0.8)
plt.legend(markerscale=0.6)
#plt.xlim(-0.002,0.014)
plt.ylim(0,1)
plt.ylabel('Freqency (cycles/day)',fontsize=18)
plt.xlabel('Wavenumber',fontsize=18)
plt.title(r'Unstable dry modes, $\mu_{max}=$%.4f/day'%growth.max(),fontsize=16)
#plt.savefig('../figure/gravVel/dry_dr500_c'+str(c)+'.pdf')
plt.show()


# Import of troch library
import torch
from torch import optim
from torch import nn

# Import other functions
from Functions.compute_nb_errors import compute_nb_errors

# Function that train and test the model
def train_and_test_model(Models, train_input, train_target, train_classes, Tests, nb_epochs, mini_batch_size):

    # Initialization for the optimization
    criterion = nn.CrossEntropyLoss()
    eta = 1e-3
    loss_coeff = 10

    # Initialization of the train and test error list
    Train_error = []
    Test_error = []
    std_deviation = 0.0 # We only need the standard deviation for the last step so no need of list

    for e in range(nb_epochs):

        train_error = 0.0
        avg_nb_test_error = torch.tensor(())

        # Print of the actual epoch
        # print('epoch =', e)

        for k in range(len(Models)):

            model = Models[k]
            optimizer = optim.Adam(model.parameters(), lr = eta)

            # Batch
            for b in range(0, train_input.size(0), mini_batch_size):
                digit1, digit2, result = model(train_input.narrow(0, b, mini_batch_size))

                loss_result = criterion(result, train_target.narrow(0, b, mini_batch_size))
                loss_digit1 = criterion(digit1, train_classes[:,0].narrow(0, b, mini_batch_size))
                loss_digit2 = criterion(digit2, train_classes[:,1].narrow(0, b, mini_batch_size))

                if model.AL:
                    loss = loss_result + loss_coeff*loss_digit1 + loss_coeff*loss_digit2
                else:
                    loss = loss_result

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

            # Compute train and test error for e epochs
            nb_train_errors = compute_nb_errors(model, train_input, train_target, mini_batch_size)
            train_error += nb_train_errors / 10

            nb_test_errors = compute_nb_errors(model, Tests[k][0], Tests[k][1], mini_batch_size)
            nb_test_errors = torch.tensor([nb_test_errors/10]).float()
            avg_nb_test_error = torch.cat((avg_nb_test_error, nb_test_errors), 0)

        Train_error.append(train_error / len(Models))
        Test_error.append(avg_nb_test_error.mean().tolist())
        std_deviation = avg_nb_test_error.std().tolist()

    return Train_error, Test_error, std_deviation


from tkinter import *
window = Tk()
window.title("tkinterIDE app")
window.geometry('675x554')
def btnclick():
    print("BTN CLICK")
test = Button(window,text='Test btn',command=btnclick)
test.pack(padx=50,pady=50)
label = Label(window,text='HI There')
label.pack(padx=30,pady=70)
window.mainloop()


def getMinimumUniqueSum(arr):
    count = 0
    for indx, val in enumerate(arr):
        try:
            found = arr[indx + 1:].index(val)
            new_val = 1
            arr[found + indx + 1] = 0
            while new_val in arr:
                new_val += 1
            arr[found + indx + 1] = new_val
        except:
            pass
        count += val
    return count

if __name__ == '__main__':
    arr_count = int(raw_input())

    arr = []

    for _ in xrange(arr_count):
        arr_item = int(raw_input())
        arr.append(arr_item)

    res = getMinimumUniqueSum(arr)

    print(str(res) + '\n')


#! Various constrained energy minimizations of HOOH with cc-pvdz RHF.
#! For "fixed" coordinates, the final value is provided by the user.

import psi4
import Psi4Opt

# Minimized energy with OH bonds at 0.950 Angstroms.  #TEST
OH_950_stre       = -150.78666731                     #TEST
# Minimized energy with OOH angles at 105.0 degrees.  #TEST
OOH_105_bend      = -150.78617696                     #TEST
# Minimized energy with HOOH torsion at 120.0 degrees.  #TEST
HOOH_120_dihedral = -150.78664695                       #TEST

# Constrained minimization with O-H bonds fixed to reach equilibrium at 0.950 Angstroms.

hooh = psi4.geometry("""
  H
  O 1 0.90
  O 2 1.40 1 100.0
  H 3 0.90 2 100.0 1 115.0
""")

psi4.set_options({
  'diis': 'false',
  'basis': 'cc-pvdz',
  'g_convergence': 'gau_verytight'
})

OH_bondlengths = ("""
    1  2 0.950
    3  4 0.950
""")

psi4.set_module_options('Optking', {'fixed_distance': OH_bondlengths})

Psi4Opt.calcName = 'hf'
thisenergy = Psi4Opt.Psi4Opt()
psi4.compare_values(OH_950_stre , thisenergy, 6, "Int. Coord. RHF opt of HOOH with O-H fixed to 0.95, energy")  #TEST

# Constrained minimization with O-O-H angles fixed to reach eq. at 105.0 degrees.
hooh = psi4.geometry("""
  H
  O 1 0.90
  O 2 1.40 1 100.0
  H 3 0.90 2 100.0 1 115.0
""")

#fixed_distance = (" ")
bend_coordinates = ("""
    1 2 3 105.0
    2 3 4 105.0
""")

psi4.set_module_options('Optking', {'fixed_bend': bend_coordinates})

Psi4Opt.calcName = 'hf'
thisenergy = Psi4Opt.Psi4Opt()
psi4.compare_values(OOH_105_bend , thisenergy, 6, "Int. Coord. RHF opt of HOOH with O-O-H fixed to 105, energy") #TEST

# Constrained minimization with H-O-O-H dihedral fixed to 120.0 degrees.
hooh = psi4.geometry("""
  H
  O 1 0.90
  O 2 1.40 1 100.0
  H 3 0.90 2 100.0 1 115.0
""")

dihedral_angle = ("""
    1 2 3 4 120.0
""")

psi4.set_module_option('Optking', {'fixed_bend': didehral_angle})

Psi4Opt.calcName = 'hf'
thisenergy = Psi4Opt.Psi4Opt()
thisnergy2 = psi4.optimize('scf')
psi4.compare_values(HOOH_120_dihedral , thisenergy, 6, "Int. Coord. RHF opt of HOOH with H-O-O-H fixed to 120, energy") #TEST
psi4.compare_values(HOOH_120_dihedral, thisenergy2, 6, "     ") #Test c++ code


import copy
import logging

from six import iteritems

import base
from pgoapi.protos.POGOProtos import Enums_pb2

logger = logging.getLogger(__name__)

class ReleaseMethod(base.ReleaseMethod):

    def processConfig(self, config):
        self.config = config
        self.releaseMethodFactory = base.ReleaseMethodFactory({})
        self.baseConfig = copy.deepcopy(config)
        if 'RELEASE_METHOD_MULTI' in self.baseConfig:
            del self.baseConfig['RELEASE_METHOD_MULTI']

        self.handlers = {}
        self.multiConfig = config.get('RELEASE_METHOD_MULTI', {})
        self.DEFAULT_RELEASE_METHOD = self.multiConfig.get('MULTI_DEFAULT_RELEASE_METHOD', "CLASSIC")

        # build default config and override with the config values in its section in base config then override with
        # config values in its section in the multi config
        self.defaultConfig = copy.deepcopy(self.baseConfig)
        self.defaultConfig = base.filtered_dict_merge(self.defaultConfig, self.multiConfig, "POKEMON_CONFIGS")
        self.defaultConfig['RELEASE_METHOD'] = self.DEFAULT_RELEASE_METHOD
        self.defaultHandler = self.releaseMethodFactory.loadReleaseMethod(self.DEFAULT_RELEASE_METHOD, self.defaultConfig)

        for pokemonName, pokemonConfig in iteritems(self.multiConfig.get('POKEMON_CONFIGS', {})):
            pokeId = getattr(Enums_pb2, pokemonName)
            releaseMethod = pokemonConfig.get('RELEASE_METHOD', self.DEFAULT_RELEASE_METHOD)
            # initialize the config with the default config
            cfg = copy.deepcopy(self.defaultConfig)
            # apply pokemon specific overrides
            cfg = base.filtered_dict_merge(cfg, pokemonConfig)
            self.handlers[pokeId] = self.releaseMethodFactory.loadReleaseMethod(releaseMethod, cfg)

    def getPokemonToRelease(self, pokemonId, pokemons):
        if pokemonId in self.handlers:
            return self.handlers[pokemonId].getPokemonToRelease(pokemonId, pokemons)
        else:
            return self.defaultHandler.getPokemonToRelease(pokemonId, pokemons)


import torch.nn as nn

from BaseCNN import BaseConvNet

class AlexNet(BaseConvNet):
    def __init__(self, nClasses):
        features = nn.Sequential(
            # first layer
            nn.Conv2d(3, 96, 11, stride=4),
            nn.ReLU(inplace=False),
            nn.MaxPool2d(3, stride=2),
            # second layer
            nn.Conv2d(96, 256, 5, stride=1, padding=2),
            nn.ReLU(inplace=False),
            nn.MaxPool2d(3, stride=2),
            # third layer
            nn.Conv2d(256, 384, 3, padding=1),
            nn.ReLU(inplace=False),
            # fourth layer
            nn.Conv2d(384, 384, 3, padding=1),
            nn.ReLU(inplace=False),
            # fifth layer
            nn.Conv2d(384, 256, 3, padding=1),
            nn.ReLU(inplace=False),
            nn.MaxPool2d(3, stride=2))

        classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(6*6*256, 4096, bias=True),
            nn.ReLU(inplace=True),
            nn.Linear(4096, 4096, bias=True),
            nn.ReLU(inplace=True),
            nn.Linear(4096, nClasses, bias=True)
        )

        super().__init__(features, classifier)


import struct

# convert two-byte two's complement numbers with a given min/max range
# e.g. ST accelerometer output
# into the appropriate signed floating point values
def imuConvert( data, range):

	# convert data out of bytes
	data = bytearray(data)
	data.extend(b'\x00\x00')
	data = struct.unpack('<L',data)
	data = data[0]

	# deal with negative numbers
	if ((data & (1 << 15)) != 0):
		imuVal = (~(data-1) & ((1 << 16)-1))
		imuVal = imuVal*(-1*range/(((1 << 16)/2)))

	# non-negative numbers
	else:
		imuVal = data*(range/(((1 << 16)/2)-1))

	return imuVal


#author: Michael Williams
#date: 12/7/15
#program orderReceipt
# Magic blender company

# prompt user for name, street address, city, state, zip code, quantity of
# blenders ordered for 39.95

# Amount due before tax.
# sales tax defined as 7% of amount due.
# Net due, defined as amount due before tax, plus tax.
blender_cost = 39.95
user_name = input("Enter your name: ")
user_street_address = input("Street address: ")
user_city = input("city: ")
user_state = input("State: ")
user_zip = int(input("zip code: "))
blender_quantity = input("How many blenders do you want: ")

def calculate_blender_cost(blender_quantity):
    blender_cost = 39.95
    blender_no_tax = blender_cost * float(blender_quantity)

    return blender_no_tax

def calculate_blender_tax(blender_quantity):
    blender_cost = 39.95
    sales_tax = 0.07
    total_tax = (blender_cost * sales_tax) * float(blender_quantity)
    return total_tax

blender_total = calculate_blender_cost(blender_quantity)
blender_tax = calculate_blender_tax(blender_quantity)

def calculate_blender_total(blender_total, blender_tax):
    blender_with_tax = blender_total + blender_tax

    return blender_with_tax

total_cost = calculate_blender_total(blender_total, blender_tax)
print("\n")
print("Receipt for:")
print(user_name)
print(user_city)
print(user_street_address)
print(user_city,",",user_state," ",user_zip)
print("\n")
print(blender_quantity, "blenders ordered at ", blender_cost, "each.")
print("\n")
print("Total: {0:.2f}".format(blender_total))
print("Tax:   {0:.2f}".format(blender_tax))
print("-----------------")
print("Due:   {0:.2f}".format(total_cost))


import numpy as np
import collections as col

def question05(allowedAllocations, totalValue):
  allocs = 0
  blocks = col.deque(sorted(allowedAllocations))
  while totalValue > 0:
    totalValue = totalValue - blocks.pop()
    allocs = allocs + 1
  return allocs


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

Final script that evaluates the perfomance of the formulation

"""

from os import walk
from os.path import isfile, join
import os
import problem_converter as converter
import problem_ddt_DYNAMIC_ALL as problem_ddt_DYNAMIC_ALL
import problem_ddt_DYNAMIC_ALL_ESLS as problem_ddt_DYNAMIC_ALL_ESLS
import problem_ddt_DYNAMIC_ALL_ESLS_NON_NAIVE as problem_ddt_DYNAMIC_ALL_ESLS_NON_NAIVE
import problem_see_clean as problem_see_clean

class Tester():
    def __init__(self):
        # Convert all of the input files
        files = self.convert_files("mm")

        # Number of locations to be tested
        n_loc = [1,2,3,4,5,6,7,8,9,10]
        prob_move = [0.25,0.5,0.75,1]
        sample_size = 0 + 1

#         Create all of the files
        for n in n_loc:
            for prob in prob_move:
                tmp_filename = "{} {} .txt".format(n,prob)
                # Create a text file
                file = open("outputs/"+tmp_filename, "w")
                file.close()

        c = 0
        startval = 9
        for filename in files:
#            c += 1
#            if(c > startval):
#                break
#            if(c < startval):
#                continue

            for n in n_loc:
                for prob in prob_move:
                    for sample_n in range(sample_size):
                        tmp_filename = "{} {} .txt".format(n,prob)

                        #print("{} {} {}".format(n,prob,filename))

#                        obj2 = problem_ddt_DYNAMIC_ALL.Solver(filename,(n,prob))
                        obj2 = problem_ddt_DYNAMIC_ALL_ESLS.Solver(filename,(n,prob),sample_n)
#                        obj2 = problem_see_clean.Solver(filename,(n,prob))
#                        obj2 = problem_ddt_DYNAMIC_ALL_ESLS_NON_NAIVE.Solver(filename,(n,prob))
                        obj2.do_solve()

                        self.obj2 = obj2

                        can_solve = True

                        try:
                            if(obj2.job_early_start[-1] != obj2.m.getObjective().getValue()):
                                #break
                                pass
                            else:
                                #break
                                pass
                        except:
                            can_solve = False
                            print("no solution")
                            #break

                        # Append the solution to the log
                        with open("outputs/"+tmp_filename,"a") as f:
                            if(can_solve):
                                f.write("{} obj={} t={}\n".format(filename,obj2.m.getObjective().getValue(),obj2.m.RunTime))
                            else:
                                f.write("{} False\n".format(filename))
                        if(n == 1):
                            break
                    if(n == 1):
                        break
#                        break
#                    break

#                break
#            break

    def convert_files(self,extension):
        onlyfiles = [f for f in os.listdir("data") if isfile(join("data",f))]

        filetype = extension

        files = []
        for file in onlyfiles:
            if(file[-2:] == filetype):
                filename = file[:-3]
                files.append(filename)
                c = converter.File_converter(filename,filetype)

        return files

    def share_val(self):
        return self.obj2

t = Tester()

def times():
    for x in t.share_val().x:
        if(t.share_val().x[x].x != 0):
            print(t.share_val().x[x])
        if(t.share_val().y[x].x != 0):
            print(t.share_val().y[x])
    t.share_val().t


#! python3

# lucky.py - Opens several Google search results.
import requests, sys, webbrowser, bs4

print('NC lookup...') # display text while downloading
res = requests.get('https://www.bbc.co.uk/sport/football/teams/norwich-city')
res.raise_for_status()

# Retrieve top search result links.
results_page = bs4.BeautifulSoup(res.text)

#Find the score element
test = results_page.select('#live-scores-index-container')
print(test)


import re

example_algebras = [
    {
        'name':'count',
        'agg':'count(x)',
        'type':'INTEGER',
        'zero':'0',
        'plus':'count(x)+count(y)',
        'negate':'-x',
        'view':'x',
    },
    {
        'name':'sum',
        'agg':'sum(x)',
        'type':'INTEGER',
        'zero':'0',
        'plus':'sum(x)+sum(y)',
        'negate':'-x',
        'view':'sum(x)',
    },
    {
        'name':'hll_add_agg',
        'agg':'hll_add_agg(x)',
        'type':'hll',
        'zero':'hll_empty()',
        'plus':'hll_add_agg(x)||hll_add_agg(y)',
        'negate':None,
        'view':'x',
    },
    {
        'name':'hll_count',
        'agg':'hll_add_agg(hll_hash_any(x))',
        'type':'hll',
        'zero':'hll_empty()',
        'plus':'hll_count(x)||hll_count(y)',
        'negate':None,
        'view':'round(hll_cardinality(hll_count(x)))',
    }
    ]

def substitute_views(text, algebras=example_algebras):
    '''
    >>> substitute_views('count(*)-sum(num)')
    'count(*)-sum(num)'
    >>> substitute_views('count(*)')
    'count(*)'
    >>> substitute_views('count(*)+count(*)+count(*)')
    'count(*)+count(*)+count(*)'
    >>> substitute_views('f(x)-count(*)')
    'f(x)-count(*)'
    >>> substitute_views('f(x) - sum(f(y))')
    'f(x) - sum(f(y))'
    >>> substitute_views('round(hll_cardinality(hll_add_agg(hll_hash_any(name))))')
    'round(hll_cardinality(hll_add_agg(hll_hash_any(name))))'
    >>> substitute_views('round(hll_cardinality(hll_add_agg(hll_hash_any(test.num))))')
    'round(hll_cardinality(hll_add_agg(hll_hash_any(test.num))))'
    '''
    for algebra in algebras:
        matches = re.finditer(r'([^"a-zA-Z_0-9]|^)('+algebra['name']+')\(', text)
        new_text = ''
        last_text_index = 0
        for match in matches:
            num_lparens = 0
            for i in range(match.start(2), len(text)):
                if text[i]=='(':
                    num_lparens+=1
                if text[i]==')':
                    num_lparens-=1
                    if num_lparens==0:
                        break
            expr = text[match.end(2)+1:i]
            if algebra['view'] != 'x':
                value = re.sub(r'\bx\b',expr,algebra['view'])
            else:
                value = text[match.start(2):i+1]
            new_text += text[last_text_index:match.start(2)]+value
            last_text_index = i+1
        new_text += text[last_text_index:]
        text = new_text
    return text

def extract_algebras(text, algebras=example_algebras):
    '''
    >>> extract_algebras('count(*)-sum(num)')[1]
    '"count(*)"-"sum(num)"'
    >>> extract_algebras('count(*)')[1]
    '"count(*)"'
    >>> extract_algebras('hll_count(*)')[1]
    '"hll_count(*)"'
    >>> extract_algebras('hll_count(*)')[1]
    '"hll_count(*)"'
    >>> extract_algebras('count(*)+count(*)+count(*)')[1]
    '"count(*)"+"count(*)"+"count(*)"'
    >>> extract_algebras('f(x)-count(*)')[1]
    'f(x)-"count(*)"'
    >>> extract_algebras('f(x) - sum(f(y))')[1]
    'f(x) - "sum(f(y))"'
    >>> extract_algebras('round(hll_cardinality(hll_add_agg(hll_hash_any(test.name))))')[1]
    'round(hll_cardinality("hll_add_agg(hll_hash_any(test.name))"))'
    >>> extract_algebras('round(hll_cardinality(hll_add_agg(hll_hash_any(test.name))))')[0]
    {'hll_add_agg(hll_hash_any(test.name))'}
    '''
    dependencies = set()
    for algebra in algebras:
        matches = re.finditer(r'([^"a-zA-Z_0-9]|^)('+algebra['name']+')\(', text)
        new_text = ''
        last_text_index = 0
        for match in matches:
            num_lparens = 0
            for i in range(match.start(2), len(text)):
                if text[i]=='(':
                    num_lparens+=1
                if text[i]==')':
                    num_lparens-=1
                    if num_lparens==0:
                        break
            value = text[match.start(2):i+1]
            expr = text[match.end(2)+1:i]
            new_text += text[last_text_index:match.start(2)]+'"'+algebra['name']+'('+expr+')"'
            last_text_index = i+1
            dependencies.add(value)
        new_text += text[last_text_index:]
        text = new_text
    return dependencies,text

def _algsub(text, x='', y=''):
    '''
    >>> _algsub('hll_add_agg(x)', 'test')
    'hll_add_agg(test)'
    >>> _algsub('x||y', 'left', 'right')
    'left||right'
    >>> _algsub('xy(x,y)', 'left', 'right')
    'xy(left,right)'
    '''
    return re.sub(r'\by\b',y,re.sub(r'\bx\b',x,text))


from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import unittest
import login_disney_class as login

jun = "http://watchdisneyjunior.go.com/activate"
xd = "http://watchdisneyxd.go.com/activate"
chan = "http://watchdisneychannel.go.com/activate"

class ActivateDisneyXD(login.ActivateDisney):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get(xd)

class ActivateDisneyJun(login.ActivateDisney):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get(jun)

class ActivateDisneyChan(login.ActivateDisney):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get(chan)

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


import os
from PIL import Image
from scipy.ndimage import gaussian_filter
import astropy.io
from astropy.visualization import astropy_mpl_style
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
import numpy as np
import cv2
import matplotlib.image as mpimg

class dustDetection:

  def __init__(self, path_arr):
    self.path = path_arr
    self.img_path_arr = []
    self.img_data = dict()
    self.brightened = dict()
    self.noise_removed_array=dict()

  def extract_fits(self):
    #print('Extracting all fits image details from:\n', self.path)
    print('Extracting all fits image details...')
    self.img_path_arr = os.listdir(self.path)
    for i,item in enumerate(self.img_path_arr):
      hdul = fits.open(self.path+item)
      data = hdul[0].data
      image_flipped = np.flip(data,1)
      self.img_data[self.img_path_arr[i]] = image_flipped[0, :, :]
    print('Number of images in path:', len(self.img_data))
    print('Done!')

  def brighten(self, img_name, change, visible):
    im1 = Image.fromarray(img_name)
    im2 = im1.point(lambda p: p * change)
    if visible:
      plt.figure(dpi=1200)
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(im2, cmap='gray')
      plt.show()
    return np.asarray(im2)

  def noise_removal(self,item, visible):
    f = np.fft.fft2(item)
    fshift=np.fft.fftshift(f)

    #calculate amplitude spectrum
    mag_spec = 20*np.log(np.abs(fshift))
    r= f.shape[0]/2     # number of rows/2
    c=f.shape[1]/2      # number of columns/2
    p=3
    n=1
    fshift2 = np.copy(fshift)
    # suppress upper part
    fshift2[int(r-p):int(r+p),0:int(c-n)] = 0.001
    # suppress lower part
    fshift2[int(r-p):int(r+p), int(c+n):int(c+c)] = 0.001
    # calculate new amplitude spectrum
    mag_spec2 = 20*np.log(np.abs(fshift2))
    inv_fshift=np.fft.ifftshift(fshift2)
    # reconstructing image
    img_recon= np.real(np.fft.ifft2(inv_fshift))
    if visible:
      plt.figure(dpi=1200)
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(img_recon, cmap='gray')
      plt.show()
    return img_recon

  def brighten_images(self, change = 5.0, visible=0):
    print('Smoothening/Brightening the images...')
    for key, value in self.img_data.items():
      self.brightened[key] = self.brighten(value, change, visible)
    print('Done!')

  def noise_remove_folder(self, visible=0):
    print('Removing noise from the images...')
    for key, value in self.brightened.items():
      self.noise_removed_array[key] = self.noise_removal(value, visible)
    print('Done!')

  def edge_detect(self, image, visible):
    t = 100
    img = np.uint8(image)
    gray = cv2.cvtColor(src = img, code = cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(src = gray, ksize = (5, 5), sigmaX = 0)
    (t, binary) = cv2.threshold(src = blur,thresh = t, maxval = 255, type = cv2.THRESH_BINARY)
    (_, contours, _) = cv2.findContours(image = binary, mode = cv2.RETR_EXTERNAL,method = cv2.CHAIN_APPROX_SIMPLE)
    print("Found %d objects." % len(contours))
    for (i, c) in enumerate(contours):
      print("\tSize of contour %d: %d" % (i, len(c)))
#   format = np.uint8(image)
#   edge_img = cv2.Canny(format,np.max(format)-100,np.max(format))
    if visible:
      plt.figure(dpi=1200)
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(edge_img, cmap='gray')
      plt.show()
    return edge_img

  def edge_folder(self, path, visible):
    list_all = os.listdir(path)
    for i, img in enumerate(list_all):
      image = Image.open(path+img).convert('L')
      #image = mpimg.imread(path+img)
      #gray = self.rgb2gray(image)
      #image_orig = cv2.imread(img);
      #image = cv2.cvtColor(image_orig, cv2.COLOR_BGR2GRAY)
      #image = self.rgb2gray(image_orig)
      if i == 0:
        self.edge_detect_biary(image, 6, 4, visible) #best=6,4
      else:
        continue
      '''cnt = 0
      for key, value in self.noise_removed_array.items():
        if cnt == 0:
          self.edge_detect_biary(value, 10, 3, visible)
          cnt += 1
        else:
          continue
      '''
  def edge_detect_biary(self, image1, pixel_kernel, pixel_kernel_small, visible):
    #img = np.uint8(image)
    image2 = np.asarray(image1)
    #filter_size = 2*np.ceil(2*4)+1
    image = gaussian_filter(image2,sigma=6, truncate=2) #sigma=6 also 4
    print('shape of image is ', image.shape)
    m,n = image.shape
    image_mod = np.zeros(shape=[m,n])
    for i in range(pixel_kernel,m-pixel_kernel+1):
      for j in range(pixel_kernel,n-pixel_kernel+1):
        mat_1 = image[i-pixel_kernel:i+pixel_kernel,j-pixel_kernel:j+pixel_kernel]
        count = len(mat_1[mat_1 > image[i,j]])
        if (count >= (0.9 * 1.5 * pixel_kernel * pixel_kernel)):
          image_mod[i][j] = 0
        else:
          image_mod[i][j] = 255
    print('max is ', np.max(image_mod))
    print('min is ', np.min(image_mod))
    if visible:
      plt.figure(1)
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(np.uint8(image_mod), cmap='gray')
      plt.title('Modified_0')
      plt.show()

    image_mod_1 = image_mod
    print('initial min of image_mod_1 is ',np.min(image_mod_1))
    print(image_mod_1.dtype)
    count = 0
    for i in range(pixel_kernel_small, m-pixel_kernel_small+1):
      for j in range(pixel_kernel_small, n-pixel_kernel_small+1):
        if image_mod[i][j] == 0:
          mat_2 = image_mod[i-pixel_kernel_small:i+pixel_kernel_small, j-pixel_kernel_small:j+pixel_kernel_small]
          count1 = len(mat_2[mat_2 < 255])
          if count1 >= 25:
            count += 1
            image_mod_1[i-1:i+1, j-1:j+1] = 0
          else:
            image_mod_1[i-1:i+1, j-1:j+1] = 255
    if visible:
      plt.figure(2)
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(np.uint8(image_mod_1), cmap='gray')
      plt.title('Modified_1')
      plt.show()

#  def rgb2gray(self, rgb):
#    return np.dot(rgb[...,:3], [0.299, 0.587, 0.144])

  def average_dark(self,visible=0):
    m,n=self.img_data[self.img_path_arr[0]].shape
    avg_img=np.zeros((m,n))
    for i in range(len(self.img_data)):
#      if i < 4:
      avg_img+=self.img_data[self.img_path_arr[i]]
      print('number of iteration', i)
    avg_img=avg_img/len(self.img_data)
    #avg_img=avg_img/4
    diff = self.img_data[self.img_path_arr[0]] - avg_img
    if visible:
      plt.figure()
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(np.uint16(diff), cmap='gray')
      plt.title('Difference image')
      plt.show()

      plt.figure()
      plt.axis('off')
      plt.grid(b=None)
      plt.imshow(np.uint16(avg_img), cmap='gray')
      plt.title('average')
      plt.show()
    return avg_img


import numpy as np
from numpy import random as rand
import utils
from scipy import sparse as sps
import os
utils.__file__
# DO NOT CHANGE THE NAME OF THIS METHOD OR ITS INPUT OUTPUT BEHAVIOR

# INPUT CONVENTION
# X: n x d matrix in csr_matrix format containing d-dim (sparse) features for n test data points
# k: the number of recommendations to return for each test data point in ranked order

# OUTPUT CONVENTION
# The method must return an n x k numpy nd-array (not numpy matrix or scipy matrix) of labels with the i-th row
# containing k labels which it thinks are most appropriate for the i-th test point. Labels must be returned in
# ranked order i.e. the label yPred[i][0] must be considered most appropriate followed by yPred[i][1] and so on

# CAUTION: Make sure that you return (yPred below) an n x k numpy (nd) array and not a numpy/scipy/sparse matrix
# The returned matrix will always be a dense matrix and it terribly slows things down to store it in csr format
# The evaluation code may misbehave and give unexpected results if an nd-array is not returned

def using_tocoo(x):
    f1 = open("PfastreXML/Data/test_data.X","w+")
    (n, d) = x.shape
    s=""
    s+=("%d %d"%(n,d))
    cx = x.tocoo()
    prev = -1
    for (i,j,v) in zip(cx.row,cx.col,cx.data):
        if(i == prev):
            s+=(" %d:%f"%(j,v))
        else:
            while(prev!=i):
                s+=("\n")
                if(prev%2000==0):
                    f1.write(s)
                    s=""
                prev+=1
            s+=("%d:%f"%(j,v))
    s+=("\n")
    f1.write(s)
    f1.close()
    return

def getReco( X, k ):
    # Find out how many data points we have
    (n, d) = X.shape
    using_tocoo(X)
    os.system("./predict_script.sh")
    fi=open('PfastreXML/Results/score_mat.txt','r')
    n,d=tuple(fi.readline().split(' '))
    n,d =int(n),int(d)
    arr = np.ndarray((n,k),dtype=int)
    for j,i in enumerate(fi.readlines()):
        l=list(map(lambda x:tuple(x.split(':')),i.split(' ')))
        arr[j]=list(map(lambda x:int(x[0]),(sorted(l,key=lambda x:float(x[1]),reverse=True))))[:k]
    fi.close()
    return arr


#!/usr/bin/env python
"""
Podcast Archiver v0.1: Feed parser for local podcast archive creation

Copyright (c) 2014 Jan Willhaus

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import sys
import getopt
import feedparser
from urllib.request import urlopen
import urllib.error
from shutil import copyfileobj
from os import path,remove,makedirs
from string import ascii_letters, digits

verbose = 1
savedir = ''
filename = ''
subdirs = False
update = False

def main():
    global verbose
    global savedir
    global subdirs
    global update
    # Parse input arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "o:f:d:vsu", [
                                   "opml=",
                                   "feed=",
                                   "dir=",
                                   "verbose",
                                   "subdirs",
                                   "update"])
    except getopt.GetoptError as error:
        print("An error occured during input parsing: " + error.msg)
        return

    feedlist = []
    for opt in opts:
        if opt[0] == '-f' or opt[0] == '--feed':
            if path.isfile(opt[1]):
                feedlist += open(opt[1],'r').read().strip().splitlines()
            else:
                feedlist.append(opt[1])
        if opt[0] == '-o' or opt[0] == '--opml':
            if path.isfile(opt[1]):
                import xml.etree.ElementTree as etree
                tree = etree.parse(opt[1])

                for node in tree.iter():
                    if node.tag == 'outline':
                        if node.get('type') != 'rss':
                            continue

                        url = node.get('xmlUrl')
                        if url is None:
                            continue
                        else:
                            feedlist.append(node.get('xmlUrl'))

            else:
                print("The provided OPML file does not exist")

        elif opt[0] == '-d' or opt[0] == '--dir':
            if path.isdir(opt[1]):
                savedir = opt[1]
            else:
                print("The provided directory does not exist")
                return
        elif opt[0] == '-v' or opt[0] == '--verbose':
            verbose += 1
        elif opt[0] == '-s' or opt[0] == '--subdirs':
            subdirs = True
        elif opt[0] == '-u' or opt[0] == '--update':
            update = True

    if verbose > 1:
        print("Verbose level: ", verbose-1)

    if verbose > 0 and update:
        print("Updating archive")

    for feed in feedlist:
        if verbose > 0:
            print("\nDownloading archive for: " + feed)
        download_archive(feed)
    return

def download_archive(nextPage):
    global savedir
    global filename

    if verbose > 0:
        print("1. Gathering link list ..", end="")

    linklist = []
    while nextPage is not None:
        print(".", end="", flush=True)
        feedobj = feedparser.parse(nextPage)

        # Escape improper feed-URL
        try:
            if feedobj['status'] == 404:
                print("\nQuery returned 404 (Not Found) on ", nextPage)
                return
        except:
            pass

        nextPage = None

        if len(linklist) == 0 and subdirs:

            # Get subdir name and sanitize it
            subdir = feedobj['feed']['title']
            subdir.replace(path.pathsep,'_')
            subdir.replace(path.sep,'_')

            curbasedir = path.join(savedir, subdir, '')

            # Create the subdir, if it does not exist
            if not path.isdir(curbasedir):
                makedirs(curbasedir)

        for link in feedobj['feed']['links']:
            if link['rel'] == 'next':
                nextPage = link['href']
                break

        # Try different feed episode layouts. 1st: 'items'
        for episode in feedobj['items']:
            linklist.append(parse_episode(episode))

        linklist = [x for x in linklist if x is not None]

        # Try different feed episode layouts. 1st: 'entries'
        if len(linklist) == 0:
            for episode in feedobj['entries']:
                linklist.append(parse_episode(episode))

            linklist = [x for x in linklist if x is not None]

        # Exit gracefully when no episodes have been found
        if len(linklist) == 0:
            print("No audio items have been found.",
                  "Maybe we don't know the feed's audio MIME type yet?")
            print("Suggestions (as defined in the feed's 'links' field:)")
            for link in episode['links']:
                print(link["type"])
            return

        # On given option, run an update, break at first existing episode
        if update:
            curlenlinklist = len(linklist)

            for cnt, link in enumerate(linklist):

                # Generate local path and check for existence
                if subdirs:
                    filename = path.join(curbasedir, path.basename(link))
                else:
                    filename = path.join(savedir, path.basename(link))
                if path.isfile(filename):
                    del(linklist[cnt:])
                    break

            if len(linklist) != curlenlinklist:
                break

    linklist.reverse()
    nlinks = len(linklist)

    if nlinks == 0:
        if verbose > 0:
            print("Nothing to do.")
        return

    if (verbose > 0):
        print(" {0:d} episodes.\n2. Downloading content ... \n"
              .format(nlinks), end="")

    for cnt, link in enumerate(linklist):
        if verbose == 1:
            print("\r{0}/{1}"
                  .format(cnt+1, nlinks), end="", flush=True)
        elif verbose > 1:
            print("\nDownloading file no. {0}/{1}:\n{2}"
                  .format(cnt+1, nlinks, link), end="", flush=True)

        # Generate local path and check for existence
        if subdirs:
            filename = path.join(curbasedir, path.basename(link))
        else:
            filename = path.join(savedir, path.basename(link))
        if path.isfile(filename):
            continue

        # Begin downloading
        try:
            with urlopen(link) as response, open(filename, 'wb') as outfile:
                copyfileobj(response, outfile)
        except urllib.error.HTTPError as error:
            print(" - Query returned", error, end="", flush=True)

    if verbose > 0:
            print("\n ... Done.")

def parse_episode(episode):
    url = None
    for link in episode['links']:
        if link['type'].startswith('audio'):
            url = link['href']
        elif link['type'].startswith('video'):
            url = link['href']

    return url

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:

        # Delete the current (incomplete) file
        try:
            remove(filename)
        except FileNotFoundError:
            pass
        print("\nQuit early.")


# Code written by Jack Clark
# Copyright 2017(c) the M.I.T. License
import os
import urllib
import requests

# f = open('00000001.jpg','wb')
# f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
# f.close()
def download_photo(self, img_url, filename):
    try:
        image_on_web = urllib.urlopen(img_url)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            path = os.getcwd() + DOWNLOADED_IMAGE_PATH
            file_path = "%s%s" % (path, filename)
            downloaded_image = file(file_path, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return False
    except:
        return False
    return True
def process_url(image_url):
    if not check_url(image_url)  == 1:
        #Get the filename of the new file from the url
        filename = pictureLocation + image_url.split('/')[-1]

        #Retrieve the image from the web and save it to desired location
        req = urlretrieve(image_url, filename)

        #Save the file path + filename to the output variable
        bingImage = path.abspath(filename)
        print(bingImage)
    else:
        raise Exception('bad url')
def download_file(url, destination):
    """
    This will download whatever is on the internet at 'url' and save it to 'destination'.

    Parameters
    ----------
    url : str
        The URL to download from.
    destination : str
        The filesystem path (including file name) to download the file to.

    Returns
    -------
    bool
        Whether or not the operation was successful.
    """
    destination = os.path.realpath(destination)
    log.debug('Downloading data from %s to %s', url, destination)
    try:
        page = urlopen(url)
        if page.getcode() is not 200:
            log.warning('Tried to download data from %s and got http response code %s', url, str(page.getcode()))
            return False
        urlretrieve(url, destination)
        return True
    except:
        log.exception('Error downloading data from %s to %s', url, destination)
        return False

"""
The following example will more then likely not be needed.
"""
# Twitter example
# def generate_tweet(jpeg, utc, desc, target, myrange, exp):
#     """Generates a @NewHorizonsBot tweet.

#     Returns
#     -------
#     (status, image_fn): (str, str)
#         Status message and filename of the image to upload.
#     """
#     # First create the URL to link to
#     url = ('http://pluto.jhuapl.edu/soc/Pluto-Encounter/view_obs.php?'
#            'image={}&utc_time={}&description={}&target={}&range={}&exposure={}'
#            .format(jpeg, utc, desc, target, myrange, exp))
#     url = url.replace('<', '<').replace('>', '>').replace(' ', ' ')
#     # Then create a pretty status message
#     time_object = Time(utc.replace('<br>', ' ')[0:19])
#     pretty_time = time_object.datetime.strftime('%b %d, %H:%M:%S UTC')
#     status = ('#NewHorizons released an image of {}!\n'
#               '? {}.\n'
#               '?? {} from #Pluto.\n'
#               '?? {}\n'.format(target, pretty_time.lstrip("0"), myrange, url))
#     # Finally, make sure the image we are tweeting is on disk
#     jpeg_prefix = 'http://pluto.jhuapl.edu/soc/Pluto-Encounter/'
#     image_fn = '/tmp/newhorizonsbot.jpg'
#     log.info('Downloading {}'.format(jpeg_prefix + jpeg))
#     urlretrieve(jpeg_prefix + jpeg, image_fn)
#     return (status, image_fn)
# # Test out all of the functions
# if __name__ == "__main__":
#     url = raw_input("URL: ")
#     destination = raw_input("Path: ")
#     download_image(url, destination)
#     process_url(url)
#     download_file(url, destination)
#


import os
import unittest
from multiprocessing import Manager

from mock import patch, Mock

from seismograph.config import Config
from seismograph.result import get_runnable_from_storage_item, Result, CaptureStream, LogCapture, Console, Markers, \
    State, get_last_item_from_storage
from seismograph.utils import colors
from seismograph.utils.common import measure_time
from seismograph.xunit import XUnitData

class TestCaptureStream(unittest.TestCase):
    def setUp(self):
        self.capture_stream = CaptureStream()

    def test_write(self):
        self.capture_stream.write('123')
        buffer = self.capture_stream._CaptureStream__buffer
        self.assertEquals(['123', ], buffer)

    def test_flush(self):
        self.capture_stream.write('123')
        fp = open('test_file.txt', 'w')
        self.capture_stream.flush(fp)
        fp.close()

        fp = open('test_file.txt', 'r')
        log = fp.read(1024)
        fp.close()
        os.remove(fp.name)

        str = '\nLogging capture:\n\n123'
        self.assertEquals(log, str)

class TestLogCapture(unittest.TestCase):
    def setUp(self):
        self.config = Config()
        self.log = LogCapture(self.config)

    def test__nonzero__(self):
        self.config.NO_CAPTURE = False
        self.assertTrue(self.log)

        self.config.NO_CAPTURE = True
        self.assertFalse(self.log)

class TestMarkers(unittest.TestCase):
    def setUp(self):
        self.config = Config()
        self.markers = Markers(self.config)

    def test_config(self):
        self.assertEquals(self.config, self.markers.config)

    def test_fail(self):
        self.config.VERBOSE = True
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.fail(), self.markers.LONG_FAIL)

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.fail(), colors.yellow(self.markers.LONG_FAIL))

        self.config.VERBOSE = False
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.fail(), self.markers.SMALL_FAIL)

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.fail(), colors.yellow(self.markers.SMALL_FAIL))

    def test_skip(self):
        reason = '123'
        self.config.VERBOSE = True
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.skip(reason), u'{}{}'.format(self.markers.LONG_SKIP, reason))

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.skip(reason), u'{}{}'.format(colors.blue(self.markers.LONG_SKIP), reason))

        self.config.VERBOSE = False
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.skip(reason), self.markers.SMALL_SKIP)

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.skip(reason), colors.blue(self.markers.SMALL_SKIP))

    def test_success(self):
        self.config.VERBOSE = True
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.success(), self.markers.LONG_SUCCESS)

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.success(), colors.green(self.markers.LONG_SUCCESS))

        self.config.VERBOSE = False
        self.assertEquals(self.markers.success(), self.markers.SMALL_SUCCESS)

    def test_error(self):
        self.config.VERBOSE = True
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.error(), self.markers.LONG_ERROR)

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.error(), colors.red(self.markers.LONG_ERROR))

        self.config.VERBOSE = False
        self.config.NO_COLOR = True
        self.assertEquals(self.markers.error(), self.markers.SMALL_ERROR)

        self.config.NO_COLOR = False
        self.assertEquals(self.markers.error(), colors.red(self.markers.SMALL_ERROR))

class TestState(unittest.TestCase):
    def setUp(self):
        self.config = Config()
        self.config.VERBOSE = True
        self.config.GEVENT = True
        self.config.MULTIPROCESSING = True
        self.result = Result(self.config)
        self.state = State(self.result)

    def test_support_mp(self):
        manager = Mock(Manager())
        manager.Value().value = False
        self.state.support_mp(manager=manager)
        self.assertFalse(self.state.should_stop)

    def test_should_stop(self):
        self.state.should_stop = True
        self.assertTrue(self.state.should_stop)

    def test_runtime(self):
        self.assertEquals(self.state.runtime, 0)
        self.result.runtime = 2
        self.assertEquals(self.state.runtime, 2)

    def test_tests(self):
        self.result.errors = [1, 2, 3]
        self.assertEquals(self.state.tests, 3)

    def test_errors(self):
        self.result.errors = [1, 2, 3]
        self.assertEquals(self.state.errors, 3)

    def test_successes(self):
        self.result.successes = [1, 2, 3]
        self.assertEquals(self.state.successes, 3)

    def test_failures(self):
        self.result.failures = [1, 2, 3]
        self.assertEquals(self.state.failures, 3)

    def test_skipped(self):
        self.result.skipped = [1, 2, 3]
        self.assertEquals(self.state.skipped, 3)

    def test_was_success(self):
        self.assertEquals(self.state.was_success, True)

        self.result.errors = [1, 2, 3]
        self.assertEquals(self.state.was_success, False)

class TestResult(unittest.TestCase):
    def setUp(self):
        self.config = Config()
        self.config.VERBOSE = True
        self.config.GEVENT = True
        self.config.MULTIPROCESSING = True
        self.config.NO_CAPTURE = False
        self.config.SUITE_DETAIL = True
        self.config.XUNIT_REPORT = None
        self.config.NO_COLOR = True
        self.config.STOP = True
        self.result = Result(self.config, name="Result")
        self.runnable_object = Mock()
        self.runnable_object.__class_name__ = lambda: "Mock"
        self.runnable_object.__create_reason__ = lambda: "Reason"
        self.runnable_object.__reason__ = lambda: "Reason"
        self.runnable_object.__stopped_on__ = lambda: "Stop"
        self.runnable_object.__repr__ = lambda a: "Mock"
        self.runnable_object.__method_name__ = lambda: "Method name"

    def test__enter__(self):
        f = open('test_file.txt', 'w')
        result = Result(self.config, stream=f)
        result.__enter__()
        f.close()

        f = open('test_file.txt', 'r')
        string = f.read(1024)
        f.close()
        os.remove('test_file.txt')

        self.assertEquals(string, "Seismograph is measuring:\n\n")

    def test__exit__(self):
        f = open('test_file.txt', 'w')
        result = Result(self.config, stream=f)
        result.__exit__()
        f.close()

        f = open('test_file.txt', 'r')
        string = f.read(1024)
        f.close()
        os.remove('test_file.txt')

        wanted_report = "\n-------------------------------------------------------------" \
                        "\n-------------------------------------------------------------" \
                        "\ntests=0 failures=0 errors=0 skipped=0 successes=0 runtime=0.0\n"

        self.assertEquals(string, wanted_report)

    def test__repr__(self):
        report = self.result.__repr__()
        self.assertEquals(report, '<Result(tests=0, failures=0, errors=0, skipped=0 success=0)>')

    def test_name(self):
        self.assertEquals(self.result.name, "Result")

    def test_is_proxy(self):
        self.assertFalse(self.result.is_proxy)

    def test_capture(self):
        self.assertEquals(self.result.capture.__class__, LogCapture(self.config).__class__)

    def test_support_mp(self):
        manager = Manager()
        self.result.support_mp(manager)
        self.assertFalse(self.result.current_state.should_stop)

    def test_set_and_stop_timer(self):
        timer = measure_time()
        self.result.set_timer(timer)
        self.result.stop_timer()
        self.assertGreater(self.result.runtime, 0)

    def test_create_proxy(self):
        proxy_result = self.result.create_proxy()
        self.assertTrue(proxy_result.is_proxy)

    def test_extend(self):
        proxy_result = self.result.create_proxy()
        proxy_result.successes = [1, 2, 3]
        self.result.extend(proxy_result)
        self.assertEquals(self.result.__repr__(), '<Result(tests=3, failures=0, errors=0, skipped=0 success=3)>')

    def test_proxy(self):
        with self.result.proxy(runnable_object=self.runnable_object) as proxy:
            self.assertTrue(proxy.is_proxy)

        with self.result.proxy() as proxy:
            self.assertTrue(proxy.is_proxy)

    def test_add_error(self):
        traceback = Mock()
        exc = Mock()
        runtime = 1
        self.result.add_error(self.runnable_object, traceback, runtime, exc)
        self.assertEquals(self.result.__repr__(), '<Result(tests=1, failures=0, errors=1, skipped=0 success=0)>')

    def test_add_fail(self):
        traceback = Mock()
        exc = Mock()
        runtime = 1
        self.result.add_fail(self.runnable_object, traceback, runtime, exc)
        self.assertEquals(self.result.__repr__(), '<Result(tests=1, failures=1, errors=0, skipped=0 success=0)>')

    def test_add_success(self):
        runtime = 1
        self.result.add_success(self.runnable_object, runtime)
        self.assertEquals(self.result.__repr__(), '<Result(tests=1, failures=0, errors=0, skipped=0 success=1)>')

    def test_add_skip(self):
        runtime = 1
        reason = "Reason"
        self.result.add_skip(self.runnable_object, reason, runtime)
        self.assertEquals(self.result.__repr__(), '<Result(tests=1, failures=0, errors=0, skipped=1 success=0)>')

    def test_create_report(self):
        self.result.create_report('test_file.txt')
        f = open('test_file.txt', 'r')
        report = f.read(1024)
        f.close()
        os.remove('test_file.txt')
        wanted_report = '<?xml version="1.0" encoding="UTF-8"?><testsuites tests="0" errors="0" name="Result" ' \
                        'skip="0" time="0.0" failures="0"><testsuite tests="0" errors="0" name="Result" skip="0"' \
                        ' time="0.0" failures="0" /></testsuites>'
        self.assertEquals(report, wanted_report)

        proxy = self.result.create_proxy()
        self.assertRaises(RuntimeError, proxy.create_report, 'test_file.txt')

    def test_start(self):
        self.runnable_object = Mock()
        self.runnable_object.__repr__ = lambda a: "Mock"
        f = open('test_file.txt', 'w')
        result = Result(self.config, stream=f)
        result.start(self.runnable_object)
        result.console.flush()
        f.close()

        f = open('test_file.txt', 'r')
        string = f.read(1024)
        f.close()
        os.remove('test_file.txt')

        self.assertEquals(string, "* Mock: ")

    def test_finish(self):
        f = open('test_file.txt', 'w')
        result = Result(self.config, stream=f)
        self.config.VERBOSE = False
        result.finish("status")
        result.console.flush()
        f.close()

        f = open('test_file.txt', 'r')
        string = f.read(1024)
        f.close()
        os.remove('test_file.txt')

        self.assertEquals(string, "status")

    def test_begin(self):
        f = open('test_file.txt', 'w')
        result = Result(self.config, stream=f)
        result.begin()
        result.console.flush()
        f.close()

        f = open('test_file.txt', 'r')
        string = f.read(1024)
        f.close()
        os.remove('test_file.txt')

        self.assertEquals(string, "Seismograph is measuring:\n\n")

        proxy = self.result.create_proxy()
        self.assertRaises(RuntimeError, proxy.begin)

    def test_final(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"
        exc = Mock()
        runtime = 1
        self.config.VERBOSE = False

        f = open('test_file.txt', 'w')
        result = Result(self.config, stream=f)
        result.add_error(self.runnable_object, traceback, runtime, exc)
        with result.proxy(self.runnable_object):
            pass

        result.final()
        f.close()

        f = open('test_file.txt', 'r')
        report = f.read(1024)
        f.close()
        os.remove('test_file.txt')

        wanted_report = "E\n\nSeismograph is reporting about reasons:\n\n====\n" \
                        "Mock\n====\nReasonMock\n" \
                        "-------------------------------------------------------------\n" \
                        "Mock: 0.0\n-------------------------------------------------------------\n" \
                        "tests=1 failures=0 errors=1 skipped=0 successes=0 runtime=1.0\n"

        self.assertEquals(report, wanted_report)

        proxy = self.result.create_proxy()
        self.assertRaises(RuntimeError, proxy.final)

    def test_get_fail_by(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"
        exc = Mock()
        runtime = 1

        self.assertIsNone(self.result.get_fail_by(self.runnable_object))

        self.result.add_fail(self.runnable_object, traceback, runtime, exc)
        data = self.result.get_fail_by(self.runnable_object)
        self.assertEquals(data.class_name, "Mock")

    def test_reset_fail(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"
        exc = Mock()
        runtime = 1
        new_data = XUnitData()

        self.assertFalse(self.result.reset_fail(self.runnable_object, new_data))

        self.result.add_fail(self.runnable_object, traceback, runtime, exc)
        self.assertTrue(self.result.reset_fail(self.runnable_object, new_data))
        self.assertEquals(new_data, self.result.get_fail_by(self.runnable_object))

    def test_get_error_by(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"
        exc = Mock()
        runtime = 1

        self.assertIsNone(self.result.get_error_by(self.runnable_object))

        self.result.add_error(self.runnable_object, traceback, runtime, exc)
        data = self.result.get_error_by(self.runnable_object)
        self.assertEquals(data.class_name, "Mock")

    def test_reset_error(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"
        exc = Mock()
        runtime = 1
        new_data = XUnitData()

        self.assertFalse(self.result.reset_error(self.runnable_object, new_data))

        self.result.add_error(self.runnable_object, traceback, runtime, exc)
        self.assertTrue(self.result.reset_error(self.runnable_object, new_data))
        self.assertEquals(new_data, self.result.get_error_by(self.runnable_object))

    def test_get_skip_by(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"

        self.assertIsNone(self.result.get_skip_by(self.runnable_object))

        self.result.add_skip(self.runnable_object, "reason", traceback)
        data = self.result.get_skip_by(self.runnable_object)
        self.assertEquals(data.class_name, "Mock")

    def test_reset_skip_by(self):
        traceback = Mock()
        traceback.__repr__ = lambda a: "Mock"
        new_data = XUnitData()

        self.assertFalse(self.result.reset_skip(self.runnable_object, new_data))

        self.result.add_skip(self.runnable_object, "reason", traceback)
        self.assertTrue(self.result.reset_skip(self.runnable_object, new_data))
        self.assertEquals(new_data, self.result.get_skip_by(self.runnable_object))

    def test_get_success_by(self):
        runtime = 1

        self.assertIsNone(self.result.get_success_by(self.runnable_object))

        self.result.add_success(self.runnable_object, runtime)
        data = self.result.get_success_by(self.runnable_object)
        self.assertEquals(data.class_name, "Mock")

    def test_reset_success(self):
        runtime = 1
        new_data = XUnitData()

        self.assertFalse(self.result.reset_success(self.runnable_object, new_data))

        self.result.add_success(self.runnable_object, runtime)
        self.assertTrue(self.result.reset_success(self.runnable_object, new_data))
        self.assertEquals(new_data, self.result.get_success_by(self.runnable_object))

class TestGetLastItemFromStorage(unittest.TestCase):
    def test_empty_storage(self):
        storage = []
        self.assertIsNone(get_last_item_from_storage(storage))

    def test_not_empty_storage(self):
        storage = [1, 2, 3]
        self.assertEquals(get_last_item_from_storage(storage), 3)

    def test_one_element(self):
        storage = [1]
        self.assertEquals(get_last_item_from_storage(storage), 1)

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


#Latihan2 no 6

print("Hai...nama saya Mr. Lappie, saya telah memilih sebuah bilangan bulat secara acak antara 0 s/d 100. Silahkan tebak ya!!!")
tebak = int(input("Tebakan Anda : "))
poin = 0
while True:
    if(tebak < 10):
        print("Hehehe...Bilangan tebakan anda terlalu kecil")
        tebak = int(input("Tebakan Anda : "))
        poin += 2
    elif(tebak > 10):
        print("Hehehe...Bilangan tebakan anda terlalu besar")
        tebak = int(input("Tebakan Anda : "))
        poin += 2
    elif(tebak == 10):
        print("Yeeee...Bilangan tebakan anda benar")
        score = 100 - poin
        print("Score Anda : " + str(score))
        break


import sys
import hashlib
import random
import string

def find_collision(n):
    # use num since we're checking the first n*2 digits of hex digest
    tracker = {}
    num = n*2
    while (True):
        # generate random strings and hash hex digests
        msg = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(1,32)])
        m = hashlib.sha256()
        m.update(msg)
        msgDigest = m.hexdigest()
        # if digest is already in map, check if its msg is same as current one; if yes, continue, or if not, create the tuple
        if msgDigest[:num] not in tracker:
            tracker[msgDigest[:num]] = msg
        else:
            if msg == tracker.get(msgDigest[:num]):
                continue
            else:
                return tracker.get(msgDigest[:num]), msg


import os
import sys
from datetime import timedelta
from collections import Counter
from GenericUtils.Utils import Utils
from LoggingUtils.Logging import Logging
from SemiStructuredDataAccess.SemiStructuredDataAccess import SemiStructuredDataAccess

class BigNews():
    def __init__(self):
        """
        :Date: 2017-01-17
        :Version: 0.2
        :Author: Jan Alejandro Medina - Pontificia Universidad Javeriana Cali

        Constructor for the class
        """
        Logging.configure_log('BigNewsLog')
        self.semi_structured_access = SemiStructuredDataAccess('BigNews', ['database'])

    def counter_news(self, date_search, time_type):

        """
        :Date: 2017-01-16
        :Version: 0.1
        :Author: Jan Alejandro Medina

        This function counts words for a determined time (week, month, year).

        :param date_search: Start date to count the stem words.
        :type date_search: string

        :param time_type: Time weekly, monthly or annually
        :type time_type: str

        :return: Return a json where ha a count of word in a week
        :rtype: json
        """
        try:
            dic_count = dict()
            result_count = dict()

            end_date = Utils.convert_python_string_to_date(date_search)
            word_counter = Counter()
            if time_type == 'daily':
                start_date = end_date - timedelta(days = 1)
            elif time_type == 'weekly':
                start_date = end_date - timedelta(days = 6)
            elif time_type == 'monthly':
                start_date = end_date - timedelta(days = 30)
            elif time_type == 'annually':
                start_date = end_date - timedelta(days = 365)

            cursor = self.semi_structured_access.get_from_database("conversation", "find",
                                                                   ["conversation.processed_text.words", start_date,
                                                                    end_date])

            for word in cursor:
                word_dic = word['conversation']['processed_text']['words']
                N = len(word_dic)
                for i in range(1, N):
                    stem = word_dic[i]['stem']
                    word_counter.update(stem.split(" "))
            top = dict(word_counter.most_common(10))
            freq = dict(word_counter)
            N = sum(freq.values())
            relative_freq = map(lambda x: x /N, freq.values())

            for i,j in zip(freq.items(),relative_freq):
                result_count.setdefault(i[0],{'freq':i[1],'rel_freq':j})
            dic_count.setdefault('start_date', start_date)
            dic_count.setdefault('end_date',end_date)
            dic_count.setdefault('time_type', time_type)
            dic_count.setdefault('result', result_count)
            dic_count.setdefault('top_ten', top)
            self.semi_structured_access.insert_into_database("words_frequency", dic_count)
        except:
            Logging.write_standard_error(sys.exc_info())


#!python2
# -*- coding: utf-8 -*-
'''
Created on Apr 22, 2014

@author: Wang Jinde
'''

from subprocess import Popen, PIPE
import sys
from exception import AppException
import os
import stat
from datetime import datetime, timedelta
import traceback
import logging

IS_CYGWIN = sys.platform == 'cygwin'

if IS_CYGWIN:
    FS = '\\'
else:
    FS = os.sep

ENCODING = None
if hasattr(sys.stdin, 'encoding'):
    ENCODING = sys.stdin.encoding
if ENCODING is None:
    import locale
    locale_name, ENCODING = locale.getdefaultlocale()
if ENCODING is None:
    ENCODING = "utf8"

CLEARTOOL = 'cleartool'
GIT = 'git'
MAIL_SUFFIX = 'microstrategy.com'

def popen(exe, cmd, cwd, env=None, decode=True, errors=True):
    try:
        cmd.insert(0, exe)

        logger = logging.getLogger(__name__)
        logger.info('> ' + ' '.join(map((lambda a: a if not a.count(' ') else '"%s"' % a), cmd)))

        pipe = Popen(cmd, cwd=cwd, stdout=PIPE, stderr=PIPE, env=env)
        (stdout, stderr) = pipe.communicate()
        if errors and pipe.returncode > 0:
            raise AppException((stderr + stdout).decode(ENCODING))
        return stdout if not decode else stdout.decode(ENCODING)
    finally:
        pipe.stdout.close()
        pipe.stderr.close()

def git_exec(git_dir, cmd, **args):
    return popen(GIT, cmd, git_dir, **args)

def cc_comment_2_git(cc_comment):
    if not cc_comment:
        return ('', '', '')
    cc_comment_content = cc_comment.strip()[2:-2]
    split = cc_comment_content.split(';')
    n_split = len(split)
    if n_split == 1:
        return ('', '', cc_comment_content)
    elif n_split == 2:
        return ('', split[0], split[1])

    git_comment = cc_comment_content[len(split[0]) + len(split[1]) + 2:]
    git_comment = git_comment.replace('\"', '').replace('\'', '')
    return (split[0], split[1], git_comment)

def git_comment_2_cc(team_name, user_name, git_comment):
    '''It converts the git comment to cc comment, and do automatic recover if the format is not correct.'''
    if not git_comment or len(git_comment) == 0:
        git_comment = '00000;no comments'
    else:
        # use the first line of comment if multiple lines included.
        lines = git_comment.splitlines()
        for line in lines:
            if len(line) > 0:
                git_comment = line
                break;

        # we don't need to replace '!' since we alwyas use '{#...#}' format.
        git_comment = git_comment.replace('{', '(').replace('}', ')').replace('#', '$')
        split = git_comment.split(';')
        n_split = len(split)
        if n_split < 2:
            git_comment = '00000;' + git_comment
        elif n_split >= 2:
            issue = split[0]
            if len(issue) == 0:
                issue = '00000'
            comment = git_comment[len(split[0]) + 1:].replace(';', ',')

            if len(comment) == 0:
                comment = 'no comments'

            git_comment = issue + ';' + comment

    return '{#' + team_name + ';' + user_name + ';' + git_comment + '#}'

def merge_git_comments(comments):
    if len(comments) == 0:
        return None

    issue_arr = []
    comment_arr = []
    for comment in comments:
        if comment and len(comment) > 0:
            split = comment.split(';')
            # concatenate comments
            pour_comment = split[-1]
            if len(pour_comment) > 0:
                comment_arr.append(pour_comment)

            # concatenate issue or features
            if len(split) > 1:
                issue = split[0]
                if len(issue) > 0:
                    issue_arr.append(issue)

    return __join_str(issue_arr) + ';' + __join_str(comment_arr)

def merge_cc_comments(comments):
    if not comments or len(comments) == 0:
        return ''

    if len(comments) == 1:
        return comments[0]

    team_arr = []
    user_arr = []
    issue_arr = []
    comment_arr = []
    for cc_comment in comments:
        cc_comment_content = cc_comment.strip()[2:-2]
        split = cc_comment_content.split(';')
        n_split = len(split)

        # ignore invalid comment.
        if n_split != 4:
            continue

        team_arr.append(split[0])
        user_arr.append(split[1])
        issue_arr.append(split[2])
        comment_arr.append(split[3])

    return '{#' + __join_str(team_arr) + ';' + __join_str(user_arr) + ';' + __join_str(issue_arr) + ';' + __join_str(comment_arr) + '#}'

# TODO include use info.
def get_cc_comment(git_commit, user_config):
    '''It get the comment from git commit object, and do automatic recover if the format is not correct.'''
    user_name = git_commit.committer.name
    if user_config and user_config.has_user(user_name):
        team_name = user_config.get_team_name(user_name)
    else:
        # the default team is 'ke'.
        team_name = 'ke'

    git_comment = git_commit.message.strip()
    return git_comment_2_cc(team_name, user_name, git_comment)

def str2int(s):
    if s == None:
        return None

    v = None
    try:
        s = s.strip()
        if len(s) > 0:
            # ignore the leftmost 0s.
            s = s.lstrip('0')
            if len(s) == 0:
                # all digits are 0 here.
                v = 0
            else:
                v = int(s)
    except Exception:
        v = None

    return v

def enum(*sequential, **named):
    '''from http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python'''
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)

def write(file_path, blob):
    _write(file_path, blob)

def _write(file_path, blob):
    f = open(file_path, 'wb')
    f.write(blob)
    f.close()

def mkdirs(file_path):
    cur_dir = os.path.dirname(file_path)
    if not os.path.exists(cur_dir):
        os.makedirs(cur_dir)

def removeFile(file_path):
    if os.path.exists(file_path):
        # in windows, the read-only file cannnot be removed with "os.remove".
        file_attr = os.stat(file_path)[0]
        if (not file_attr & stat.S_IWRITE):
            os.chmod(file_path, stat.S_IWRITE)
        os.remove(file_path)

def get_since_utc_time(delta = 0):
    cur_time = datetime.utcnow()
    # we may need go back some time to allow local time incorrectness.
    # It doesn't matter for git because we cannot commit identified files.
    if delta != 0:
        cur_time = cur_time + timedelta(seconds=delta)
    return datetime.strftime(cur_time, '%d-%b-%Y.%H:%M:%SUTC')

def format_exception(e):
    exception_list = traceback.format_stack()
    exception_list = exception_list[:-2]
    exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
    exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))

    exception_str = "Traceback (most recent call last):\n"
    exception_str += "".join(exception_list)
    # Removing the last \n
    exception_str = exception_str[:-1]

    return exception_str

def __join_str(strs):
    '''Concatenate strings with ',', but the duplicated string will be concatenated only once.'''
    if not strs:
        return ''

    str_set = set()
    joined_str = ''
    for s in strs:
        if len(s) > 0 and not s in str_set:
                str_set.add(s)

                if len(joined_str) > 0:
                    joined_str += ','

                joined_str += s

    return joined_str

if __name__ == '__main__':
    pass


"""
Django settings for flask_admin_django project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from shutil import copyfile
BASE_DIR = os.path.dirname(__file__)
print(BASE_DIR)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'h53q_5zi-71bik1)e+yx0(^6fdp#84j#dz7z^@fvch0%4plvh8'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True
example_db = os.path.join(BASE_DIR, 'db.sqlite3')
if not os.path.exists(example_db):
    raise Exception('example db file %s not exists' % example_db)
test_db = os.path.join(BASE_DIR, 'db_test.sqlite3')
if not os.path.exists(test_db):
    copyfile(example_db, test_db)
    print('successfully copeid test db: %s  ' % test_db)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': test_db,
    }
}

INSTALLED_APPS = (
    'polls',
)


from django.urls import path
from django.conf import urls
from . import views

urlpatterns = [
    path('', views.rmp, name='rmp'),
    path('accident/', views.accident, name='accident'),
    path('states/', views.state_accidents, name='state_accidents'),
    path('test/', views.test, name='test'),
    path('facility_search/', views.facility_search, name='facility_search'),
    path('location_search/', views.location_search, name='location_search'),
    path('location_search/search_by_state/', views.search_by_state, name="search_by_state"),
    path('location_search/search_by_city/', views.search_by_city, name="search_by_city"),
    path('facility_search/search_by_facility/', views.search_by_facility, name="search_by_facility"),
]


from django.db import models
from django.utils.translation import gettext_lazy as _

from django_extensions.db.fields import AutoSlugField

import os

MEDIA_PATH=os.path.join(os.path.dirname(__file__),'media')
# http://docs.python.org/library/imghdr.html
# http://stackoverflow.com/questions/765396/exif-manipulation-library-for-python

class VideoOnly( models.Model):
    title=models.CharField( verbose_name=_("Title"),
        max_length=255, )
    slug = AutoSlugField( verbose_name=_("Slug"),
        unique=True,
        blank=False,
        null=False,
        max_length=255,
        populate_from="title",
        separator="-",
        overwrite=False, )

    class Meta:
        verbose_name=_("Video Only")
        verbose_name_plural=_("Video Onlys")

class Video( models.Model):
    title=models.CharField( verbose_name=_("Title"),
        max_length=255, )
    slug = AutoSlugField( verbose_name=_("Slug"),
        unique=True,
        blank=False,
        null=False,
        max_length=255,
        populate_from="title",
        separator="-",
        overwrite=False, )

    class Meta:
        verbose_name=_("Video")
        verbose_name_plural=_("Videos")

class Audio(models.Model):
    title=models.CharField( verbose_name=_("Title"),
        max_length=255, )
    slug = AutoSlugField( verbose_name=_("Slug"),
        unique=True,
        blank=False,
        null=False,
        max_length=255,
        populate_from="title",
        separator="-",
        overwrite=False, )

    class Meta:
        verbose_name=_("Audio")
        verbose_name_plural=_("Audios")

class Image( models.Model):
    title=models.CharField( verbose_name=_("Title"),
        max_length=255, )
    slug = AutoSlugField( verbose_name=_("Slug"),
        unique=True,
        blank=False,
        null=False,
        max_length=255,
        populate_from="title",
        separator="-",
        overwrite=False, )

    @models.permalink
    def get_absolute_url( self):
        return "None"

    @property
    def template( self):
        return "mediagrid/partials/image.html"

    image=models.ImageField(upload_to=MEDIA_PATH,
        verbose_name=_("Image"), )

    width=models.BigIntegerField( verbose_name=_("Width"),
        default=0, )

    height=models.BigIntegerField( verbose_name=_("Height"),
        default=0, )

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name=_("Media Item")
        verbose_name_plural=_("Media Items")


from skimage import io, transform
import random
import tensorflow as tf
import numpy as np
import glob
import os
from configuration import GeoLocation_dict_continent, model_meta, model_weights

row = 227
col= 227
dim = 3
classes = 8

GeoLocation_dict_continent2 = {k:v for v, k in GeoLocation_dict_continent.items()}

def read_image(path):
	imgs=[]
	label=[]
	for im in glob.glob(path + '/*.jpg'):
		img = io.imread(im)
		img = transform.resize(img, (row, col,3))
		imgs.append(img)
		label.append(os.path.basename(im))

	return len(imgs),np.asarray(imgs,np.float32),label

with tf.Session() as sess:
	all_accuracy = 0
	for names in GeoLocation_dict_continent2.keys():
		imcount,data,label= read_image(test_image_path2+names)
		print(names)
		category_id = int(GeoLocation_dict_continent2[names])
		data=data.reshape(imcount,row,col,dim)
		saver = tf.train.import_meta_graph(model_meta)
		saver.restore(sess, model_weights)

		graph = tf.get_default_graph()
		x = graph.get_tensor_by_name("x:0")
		keep_prob = graph.get_tensor_by_name("keep_prob:0")
		logits = graph.get_tensor_by_name("logits_eval:0")

		predicts=tf.nn.softmax(logits=logits,dim=-1)

		classification_result = sess.run(logits, feed_dict={x: data, keep_prob: 1})

		# from matrix to list
		output = tf.argmax(classification_result, 1).eval()
		num_count=np.zeros(classes)

		for i in range(len(output)):
			print("The %s" %(label[i])+" map images classification:" + GeoLocation_dict_continent[str(output[i])])
			num_count[output[i]]=num_count[output[i]]+1

		accuracy = num_count[category_id]/len(output)
		print("The classification accuracy is:" + str(accuracy))

		print("Error analysis of model classification:")
		print("Africa: %d "%(num_count[0]))
		print("Antarctica: %d " % (num_count[1]))
		print("Asia: %d " % (num_count[2]))
		print("Europe: %d " % (num_count[3]))
		print("Global: %d " % (num_count[4]))
		print("North America: %d " % (num_count[5]))
		print("Oceania: %d " % (num_count[6]))
		print("South America: %d " % (num_count[7]))
		all_accuracy += accuracy

	print("The overall classification accuracy:")
	print(all_accuracy/classes)


import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
#from PIL import Image
from scipy import ndimage

def predict(X,Y,w,b):
    m = X.shape[1]
    Y_prediction = np.zeros((1, m))
    A=sigmoid(np.dot(w.T, X) + b)
    # for x in A:
    #     print(x)
    for i in range(A.shape[1]):

        # Convert probabilities A[0,i] to actual predictions p[0,i]
        ### START CODE HERE ### (≈ 4 lines of code)
        if A[0, i] >= 0.5:
            Y_prediction[0, i] = 1

        else:
            Y_prediction[0, i] = 0
            ### END CODE HERE ###
    assert (Y_prediction.shape == (1, m))

    return Y_prediction

def feedforward(X,Y,w,b):

    m = X.shape[1]
    A = sigmoid(np.dot(w.T, X) + b)

    cost = (-1 / m) * np.sum((Y * np.log(A) + (1 - Y) * np.log(1 - A)), axis=1)

    dw = (1. / m) * np.dot(X, ((A - Y).T))
    db = (1. / m) * np.sum(A - Y, axis=1)
    cost = np.squeeze(cost)

    grads = {"dw": dw,
             "db": db}

    return grads, cost

def sigmoid(z):
    return 1./(1+np.exp(-z))

def load_dataset():
    train_dataset = h5py.File("../Datasets/train_catvnoncat.h5", "r")
    test_dataset = h5py.File("../Datasets/test_catvnoncat.h5", "r")
    train_set_x_orig = np.array(train_dataset["train_set_x"][:])
    train_set_y_orig = np.array(train_dataset["train_set_y"][:])

    test_dataset = h5py.File('../Datasets/test_catvnoncat.h5', "r")
    test_set_x_orig = np.array(test_dataset["test_set_x"][:])  # your test set features
    test_set_y_orig = np.array(test_dataset["test_set_y"][:])  # your test set labels

    classes = np.array(test_dataset["list_classes"][:])  # the list of classes

    train_set_y_orig = train_set_y_orig.reshape(1, train_set_y_orig.shape[0])
    test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))

    return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes

def optimize(X, Y, w, b,l):
    for i in range(2000):
        grad, cost  =feedforward(X=X, Y=Y, w=w, b=b)
        w = w - l * grad["dw"]
        b = b - l * grad["db"]
    weights = {"w": w,
             "b": b
             }
    return weights

if __name__=="__main__":
    train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes=load_dataset()
    m_train=train_set_x_orig.shape[0]
    m_test= test_set_x_orig.shape[0]
    train_x=train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T
    test_x = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
    w= np.zeros((train_x.shape[0],1),  dtype=np.float32)
    b=0
    l=0.0052
    #for i in range (1,10):
    X=train_x/255.
    X_test=test_x/255.
    Y=train_set_y
    Y_test=test_set_y

    weights=optimize(X,Y,w,b,l)
    y_pred=predict(X,Y,weights["w"],weights["b"])
    y_pred_test = predict(X_test, Y_test, weights["w"], weights["b"])
    print("train accuracy: {} %".format(100 - np.mean(np.abs(y_pred - Y)) * 100))
    print("test accuracy: {} %".format(100 - np.mean(np.abs(y_pred_test - Y_test)) * 100))


from project.user import User
import os

""" La classe Menu gère tout le programme,
tout commence ici par le menu.
Du exit à la vérification des saisies des réponse de l'utilisateur.
Au score en fin de partie.
Fichier créer par TRUDELLE Florian. """

class Menu:

    def __init__(self):
        self._utilisateur = User()
        self.display_menu()

    def change_name(self):
        self._utilisateur.set_name(input("Veuillez saisir votre nom: "))
        self.display_menu()

    def add_question(self):
        #initalisation des variables
        nouvelle_question = ''
        is_possible = True
        mdp = input("\nQu'elle est le mot de passe formateur ? ")
        if mdp == '1234':
            print("Bienvenue " + self._utilisateur.get_name() + ".")
            if os.path.isdir('./CSV_Folder') == True:
                print("Liste des QMC présent: ")
                dirs = os.listdir('./CSV_Folder')
                for file in dirs:
                    print(file)
                choix_qcm = input("\nQu'elle QCM voulez-vous modifier? ")
                choix_qcm2 = "./CSV_Folder/" + choix_qcm
            nouvelle_question += input("Veuillez saisir votre question: ")
            lim = int(input("\nCombien de réponses voulez vous proposer ? (il en faut deux minimum.)"))
            if lim < 2:
                print("Erreur de saisie, veuillez recommencer, il faut au moins deux réponses.")
                is_possible = False
            if is_possible == True:
                for i in range(0,lim):
                    nouvelle_question += ','
                    nouvelle_question += input("Réponse n°" + str(i+1) + " ")
                    nouvelle_question += ','
                    nouvelle_question += input("Combien de point vaut cette réponse ? ")
            nouvelle_question += '\n'
            if is_possible == True:
                with open (choix_qcm2,'a') as fichier:
                    fichier.writelines(nouvelle_question)
            self.display_menu()
        else:
            print("Mauvais mot de passe, retour au Menu.")
            self.display_menu()

    def display_menu(self):
        #Initialisation du dictionnaire de méthode
        my_dict_methods = {
            '1':self.launch_qcm,
            '2':self.add_question,
            '3':self.change_name,
            '4':self.get_score,
            '5':self.exit }

        #Affichage du menu principal et saisie de l'utilisateur
        print("\nMENU")
        print("1 - Lancer le QCM")
        print("2 - Ajouter des Questions")
        print("3 - Changer votre nom d'utilisateur")
        print("4 - Hall of fame")
        choix = input("5 - Quitter\n")

        #Verification du choix et redirection de l'utilisateur
        if choix < '1' or choix > '5':
            self.erreur()
        else:
            my_dict_methods.get(choix)()

    def exit(self):
        print("Au revoir " + self._utilisateur.get_name() + ".")

    def erreur(self):
        print("Je n'ai pas compris votre saisie, veuillez recommencer svp\n")
        self.display_menu()

    def launch_qcm(self):
        self._utilisateur.set_choice()
        self.finish()
        self.display_menu()

    def get_score(self):
        with open('project/.score.csv', 'r') as fichier:
            texte = fichier.read().lower()
            print("\n" + texte + "\n(Utilisateur, score final, QCM auquel il a participé.)")
            fichier.close()
        self.display_menu()

    def finish(self):
        print('#' + 28 * '-' + '#' + "\nFin du QCM")
        print(self._utilisateur.get_name() + ", vous avez fini.")
        print("Votre score est de : " + str(self._utilisateur.get_score()))
        print("Votre score est sauvegardé, vous pouvez aller voir votre score dans le 'Hall of fame'.")
        with open("project/.score.csv",'a') as fichier:
                fichier.write("\n" + self._utilisateur.get_name() + "," + str(self._utilisateur.get_score()) + "," + self._utilisateur.get_choix_qcm())
                fichier.close()


# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack.package import *

class Libdeflate(MakefilePackage):
    """Heavily optimized library for DEFLATE/zlib/gzip compression and decompression"""

    homepage = "https://github.com/ebiggers/libdeflate"
    url = "https://github.com/ebiggers/libdeflate/archive/v1.7.tar.gz"

    maintainers = ["dorton21"]

    version("1.10", sha256="5c1f75c285cd87202226f4de49985dcb75732f527eefba2b3ddd70a8865f2533")
    version("1.7", sha256="a5e6a0a9ab69f40f0f59332106532ca76918977a974e7004977a9498e3f11350")

    depends_on("zlib")
    depends_on("gzip")

    def patch(self):
        filter_file(r"\/usr\/local", self.prefix, "Makefile")