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

from openerp.osv import osv, fields

class connection_config(osv.osv):
    _name = 'connection.config'
    _description = 'Connection Config'

    def get_connection(self, cr, uid, ids, field_name, arg, context=None):
        """
        Record name is the name of the record (to be synchronized) and the mapping name.
        """
        res = {}
        for sync_obj in self.read(cr, uid, ids, ['model', 'id_src'], context=context):
            res[sync_obj['id']] = sync_obj['model'] + ' - ' + str(sync_obj['id_src'])
        return res

    _columns = {
        'url':fields.char('Url', size=256, required=True),
        'url_type':fields.selection([('check','Check In/Out'),('create','Create'),
                                       ('update','Update'),('delete','Delete')],string='Type',required=True),
        'last_check_date': fields.datetime('Last Check Date'),
        'b_run_again': fields.boolean('Cheking Again'),
        'date_run_again': fields.datetime('Running Date Again'),
    }

    _defaults = {
        'b_run_again': lambda *a: False,
    }

connection_config()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


import numpy as np
import pandas as pd

import imageio as io
from skimage.measure import label, regionprops
from skimage.color import label2rgb,gray2rgb
from skimage.segmentation import watershed
import cv2
import os
import scipy.ndimage as ndi

def watershedSegStack(seg_stack,num_lesions,postprocess_dir,cam_num):

    seg_stack = seg_stack.copy()
    imgs,rows,cols = seg_stack.shape
    sum_stack = np.sum(seg_stack,axis=(0)) / imgs
    seg_stack_save_pth = os.path.join(postprocess_dir,'cam' + str(cam_num) + 'segstack.png')
    cv2.imwrite( seg_stack_save_pth,255.0*gray2rgb(sum_stack) )

    bin_img = np.where(sum_stack > 0, True, False)
    distance = ndi.distance_transform_edt(bin_img)

    min_lesions_over_threshold = float('inf')
    max_lesions_under_threshold = 0
    enough_lesions_found = False
    best_labels = None
    threshold = 1.0
    for i in range(20):

        threshold -= 0.05
        starting_regions = np.where(sum_stack >= threshold, 1, 0)
        labels = label(starting_regions)

        label_map_save_pth = os.path.join(postprocess_dir, 'cam' + str(cam_num) + 'label_map_T{}.png'.format(str(int(threshold*100))))
        cv2.imwrite(label_map_save_pth,255.0*label2rgb(labels, colors=['red', 'green', 'blue', 'purple', 'pink', 'black']))

        num_good_lesions_found = 0
        regions = regionprops(labels)
        for region in regions:
            # maybe use circularity as a filter too?
            # TODO use circularity as well
            circularity = 4*np.pi*region.area / (region.perimeter * region.perimeter)
            x,y = region.centroid
            if region.area > 500 and circularity > 0.5:
                if x > rows * 0.1 and x < rows * 0.9 and y > cols * 0.1 and y < cols * 0.9:
                    num_good_lesions_found += 1
                else:
                    labels = np.where(labels==region.label,0,labels)
            else:
                labels = np.where(labels==region.label,0,labels)
        if num_good_lesions_found == num_lesions:
            best_labels = labels
            break
        elif num_good_lesions_found < min_lesions_over_threshold and num_good_lesions_found >= num_lesions:
            min_lesions_over_threshold = num_good_lesions_found
            enough_lesions_found = True
            best_labels = labels
        elif num_good_lesions_found > max_lesions_under_threshold and enough_lesions_found == False:
            max_lesions_under_threshold = num_good_lesions_found
            best_labels = labels

    labels = best_labels
    counts = []
    # regions doesn't include background
    regions = regionprops(labels)
    for region in regions:
        counts.append([region.area,region.label])
    counts.sort()

    while len(counts) > num_lesions:
        area, label_num = counts.pop(0)
        labels = np.where(labels == label_num, 0, labels)

    # now all the labels will be 1-num_lesion
    labels_unique = np.unique(labels)
    for i,lab_u in enumerate(labels_unique):
        labels = np.where(labels==lab_u,i,labels)

    label_map_ws = watershed(-distance, labels, mask=bin_img)
    label_map_rgb = np.array(255.0*label2rgb(label_map_ws,colors=['red','green','blue','purple','pink','black']),dtype='float32')
    label_map_bgr = cv2.cvtColor(label_map_rgb,cv2.COLOR_RGB2BGR)

    label_map_save_pth = os.path.join(postprocess_dir, 'cam' + str(cam_num) + 'label_map.png')
    rgb_label_map = np.float32(255.0*label2rgb(label_map_ws,colors=['red','green','blue','purple','pink','black']))
    cv2.imwrite( label_map_save_pth,cv2.cvtColor(rgb_label_map,cv2.COLOR_RGB2BGR) )

    return label_map_ws

def processSegStack(seg_stack,img_stack,num_lesions,labels_ws,imageDF,resize_ratio,postprocess_dir,imgsWLesions_dir):
    seg_stack = seg_stack.copy()
    # add first fake segmentation of zero to make processing easier
    num_imgs,rows,cols = seg_stack.shape
    first_seg = np.zeros((1,rows,cols))
    seg_stack = np.concatenate((first_seg,seg_stack),axis=0)

    alpha = 0.4
    #alpha = 1.0
    for i in range(num_imgs):
        df_index = i*num_lesions
        img_name = imageDF.iloc[df_index].loc['Image Name']
        leaf_img = np.array(img_stack[i],dtype='float32') # leaf_img is RGB

        original_img = leaf_img.copy()
        original_seg = original_img.copy()
        original_seg[:,:,0] = np.where(seg_stack[i+1,:,:]==1,255,original_seg[:,:,0])
        original_seg[:,:,1] = np.where(seg_stack[i+1,:,:]==1,0,original_seg[:,:,1])
        original_seg[:,:,2] = np.where(seg_stack[i+1,:,:]==1,0,original_seg[:,:,2])
        orig_seg_img = cv2.addWeighted(original_img,1-alpha,original_seg,alpha,0.0)
        orig_seg_img_pth = os.path.join(postprocess_dir, img_name.replace('.png','') + '_OSeg.png')
        orig_img_pth = os.path.join(postprocess_dir, img_name.replace('.png','') + '_OImg.png')
        cv2.imwrite(orig_seg_img_pth,cv2.cvtColor(orig_seg_img,cv2.COLOR_RGB2BGR))
        cv2.imwrite(orig_img_pth,cv2.cvtColor(original_img,cv2.COLOR_RGB2BGR))

        # current image is the previous segmentation AND the current segmentation
        # so that lesions don't randomly disappear
        seg_stack[i+1,:,:] = seg_stack[i+1,:,:] + seg_stack[i,:,:]
        continuous_seg = seg_stack[i+1,:,:]
        curr_labels = np.where(continuous_seg>0, labels_ws, 0)
        num_lesions_segmented = np.max(curr_labels)
        seg_image = 255.0*label2rgb(curr_labels,colors=['red','green','blue','purple','pink','black'])

        seg_image_mask = np.sum(seg_image,axis=2,keepdims=True)
        seg_image_mask = np.where(seg_image_mask>0,1,0)

        overlay = np.where(seg_image_mask==1,seg_image,leaf_img)
        overlay = np.array(overlay,dtype='float32')

        img_w_lesions = cv2.addWeighted(leaf_img,1-alpha,overlay,alpha,0.0)
        img_w_lesions_pth = os.path.join(imgsWLesions_dir, img_name.replace('.png','_lesions.png'))
        cv2.imwrite(img_w_lesions_pth,cv2.cvtColor(img_w_lesions,cv2.COLOR_RGB2BGR))

        lesion_total = 0
        for l in range(num_lesions_segmented):
                area_str = 'Lesion #'
                imageDF.at[df_index+l, area_str] = l+1
                lesion_size = np.count_nonzero(np.where(curr_labels==l+1,l+1,0))
                imageDF.at[df_index+l,'Lesion Area Pixels'] = lesion_size
                imageDF.at[df_index+l, 'Adjusted Lesion Pixels'] = lesion_size * resize_ratio
                lesion_total += lesion_size

        lesion_avg = lesion_total / num_lesions_segmented

        # Only record Avg Adj Pixel Size one time per image for easier statistical analysis
        #for l in range(num_lesions):
        #    imageDF.at[df_index+l, 'Avg Adj Pixel Size'] = lesion_avg * resize_ratio
        imageDF.at[df_index, 'Avg Adj Pixel Size'] = lesion_avg * resize_ratio

    return imageDF

def cleanDF(df):
    clean_df = df[[
        'Image Name',
        'File Location',
        'CameraID',
        'Year',
        'Month',
        'Day',
        'Hour',
        'Innoc Year',
        'Innoc Month',
        'Innoc Day',
        'Innoc Hour',
        'Hours Elapsed',
        'Lesion #',
        'Lesion Area Pixels',
        'ResizeRatio',
        'Adjusted Lesion Pixels',
        'Avg Adj Pixel Size',
        'Camera #',
        'Array #',
        'Leaf #',
        'Leaf Section #',
        'Covariable 1',
        'Covariable 2',
        'Covariable 3',
        'Covariable 4',
        'Vector Name',
        'Gene of Interest',
        'Comments',
        'Description']]
    return clean_df


"""Module containing class for collection of cases"""
from typing import Union, List, Dict
from sumo.wrapper import SumoClient
from fmu.sumo.explorer.objects._document_collection import DocumentCollection
from fmu.sumo.explorer.objects.case import Case
from fmu.sumo.explorer.pit import Pit

_CASE_FIELDS = [
    "_id",
    "fmu.case.name",
    "fmu.case.user.id",
    "_sumo.status",
    "access.asset",
    "masterdata.smda.field",
]

class CaseCollection(DocumentCollection):
    """A class for representing a collection of cases in Sumo"""

    def __init__(self, sumo: SumoClient, query: Dict = None, pit: Pit = None):
        """
        Args:
            sumo (SumoClient): connection to Sumo
            query (dict): elastic query object
            pit (Pit): point in time
        """
        super().__init__("case", sumo, query, _CASE_FIELDS, pit)

    @property
    def names(self) -> List[str]:
        """List of unique case names"""
        return self._get_field_values("fmu.case.name.keyword")

    @property
    async def names_async(self) -> List[str]:
        """List of unique case names"""
        return await self._get_field_values_async("fmu.case.name.keyword")

    @property
    def statuses(self) -> List[str]:
        """List of unique statuses"""
        return self._get_field_values("_sumo.status.keyword")

    @property
    async def statuses_async(self) -> List[str]:
        """List of unique statuses"""
        return await self._get_field_values_async("_sumo.status.keyword")

    @property
    def users(self) -> List[str]:
        """List of unique user names"""
        return self._get_field_values("fmu.case.user.id.keyword")

    @property
    async def users_async(self) -> List[str]:
        """List of unique user names"""
        return await self._get_field_values_async("fmu.case.user.id.keyword")

    @property
    def assets(self) -> List[str]:
        """List of unique asset names"""
        return self._get_field_values("access.asset.name.keyword")

    @property
    async def assets_async(self) -> List[str]:
        """List of unique asset names"""
        return await self._get_field_values_async("access.asset.name.keyword")

    @property
    def fields(self) -> List[str]:
        """List of unique field names"""
        return self._get_field_values(
            "masterdata.smda.field.identifier.keyword"
        )

    @property
    async def fields_async(self) -> List[str]:
        """List of unique field names"""
        return await self._get_field_values_async(
            "masterdata.smda.field.identifier.keyword"
        )

    def __getitem__(self, index: int) -> Case:
        doc = super().__getitem__(index)
        return Case(self._sumo, doc, self._pit)

    async def getitem_async(self, index: int) -> Case:
        doc = await super().getitem_async(index)
        return Case(self._sumo, doc)

    def filter(
        self,
        uuid: Union[str, List[str]] = None,
        name: Union[str, List[str]] = None,
        status: Union[str, List[str]] = None,
        user: Union[int, List[int]] = None,
        asset: Union[int, List[int]] = None,
        field: Union[str, List[str]] = None,
    ) -> "CaseCollection":
        """Filter cases

        Args:
            uuid (str or List[str]): case uuid
            name (str or List[str]): case name
            status (str or List[str]): case status
            user (str or List[str]): name of case owner
            asset (str or List[str]): asset
            field (str or List[str]): field

        Returns:
            CaseCollection: A filtered CaseCollection
        """
        must = self._utils.build_terms(
            {
                "_id": uuid,
                "fmu.case.name.keyword": name,
                "_sumo.status.keyword": status,
                "fmu.case.user.id.keyword": user,
                "access.asset.name.keyword": asset,
                "masterdata.smda.field.identifier.keyword": field,
            }
        )

        query = super()._add_filter({"bool": {"must": must}})
        return CaseCollection(self._sumo, query, self._pit)


import glob
import os

def createExe(fileName):
	exeFileName = fileName
	masmPath = "C:\\masm\\8086\\"
	os.system(masmPath+"masm "+exeFileName+", , ;\n")
	os.system(masmPath+"link "+exeFileName+", , ;\n")
	os.system("del *.OBJ \n") # clean up unnecessary remnants
	os.system("del *.LST \n")
	os.system("del *.MAP \n")

def findFiles():
	filesList=[]
	for name in glob.glob('*.asm'):
		filesList.append(name[:-4])
	filesList.sort()
	print(filesList)
	for file in filesList:
		createExe(file)

findFiles()


from flask import Flask, render_template, request
import jsonify
import requests
import pickle
import numpy as np
import sklearn

app = Flask(__name__)
model = pickle.load(open('insurance_rf.pkl', 'rb'))

@app.route('/')
def home():
    return render_template('index.html')

@app.route("/predict", methods=['POST'])
def predict():
    northwest=0
    southeast=0
    southwest=0
    if request.method == 'POST':
        Age = int(request.form['age'])
        Gender=request.form['gender']
        BMI=float(request.form['bmi'])
        Children=int(request.form['children'])
        Smoker=request.form['smoker']
        Region=request.form['region']
        if(Gender=='male'):
            Gender=1
        else:
            Gender=0
        if(Smoker=='yes'):
            Smoker=1
        else:
            Smoker=0
        if(Region=='northwest'):
            northwest=1
            southeast=0
            southwest=0
        elif(Region=='southeast'):
            northwest=0
            southeast=1
            southwest=0
        elif(Region=='southwest'):
            northwest=0
            southeast=0
            southwest=1
        else:
            northwest=0
            southeast=0
            southwest=0

        prediction=model.predict([[Age,BMI,Children,Gender,Smoker,northwest,southeast,southwest]])
        output=round(prediction[0],2)
        return render_template('index.html',prediction_text="INSURANCE CHARGES- {}".format(output))

if __name__=="__main__":
    app.run(debug=True)


from itertools import combinations

def isPrime(number):
    if number < 2:
        return False
    else:
        for num in range(2, number):
            if number % num == 0:
                return False
        return True

def Prime(n):
    prime_num = []
    for num in range(n):
        if isPrime(num):
            prime_num.append(num)
    return prime_num

def solution(nums):
    answer = 0
    num_combines = combinations(nums, 3)
    nums_sum = sum(nums)
    prime_num = Prime(nums_sum)
    for num in num_combines:
        if sum(num) in prime_num:
            answer += 1
    return answer

nums = [1,2,7,6,4]
print(solution(nums))

알고리즘/3주 모의고사 소수.py

3주 모의고사 소수.py


"""This module contains a function for loading and processing the
distributed representations for the dataset in question. Then generating
a BatchGenerator that is compatible with the modified pipeline.

The modified pipeline will then train the specified model with the
input distributed representations along with its standard inputs

Results will be recorded in a results object that is returned at the end
or saved optionally as a pkl.
"""
import os
import json
import re
import torch
import networkx as nx
from pathlib import Path

from chemicalx.data import BatchGenerator
from chemicalx import modified_dr_pipeline # note use of custom pipeline
from data.g2dr_funcs import g2dr

def pipeline_dr_model(model,
    num_epochs,
    batch_size,
    drug_features,
    c_features,
    triples,
    train_size=0.5,
    random_state=123,
    bool_context_features=False,
    bool_drug_features=False,
    bool_drug_molecules=False,
    bool_drug_dr_features=False):
    """This function takes a model and its hyperparameters and trains
    it on the triples dataset using the split and random seed specified.

    After training it produces a results object which can be used
    for further analysis.

    Args:
        model (nn.module): a chemicalx compliant model that we have implemented
            which uses the distributed representations learned
        num_epochs (int): number of epochs to train the model
        batch_size (int): batch size for training
        drug_features (chemicalx.DrugFeatures): The augmented drug features, has to contain
            the DR values if learning a model that utilises the DR
        c_features (chemicalx.ContextFeatures): context features
        triples (chemicalx.LabeledTriples): the Labeled triples forming the drug pair dataset
        train_size (float): value between 0.0 and 1.0 that signifies how large
            the training set should be
        random_state (int): for reproduction of results
    """
    train, test = triples.train_test_split(train_size=train_size, random_state=random_state)
    train_generator = BatchGenerator(batch_size=batch_size,
                               context_features=bool_context_features,
                               drug_features=bool_drug_features,
                               drug_molecules=bool_drug_molecules,
                               drug_dr_features=bool_drug_dr_features,
                               context_feature_set=c_features,
                               drug_feature_set=drug_features,
                               labeled_triples=train)
    test_generator = BatchGenerator(batch_size=batch_size,
                               context_features=bool_context_features,
                               drug_features=bool_drug_features,
                               drug_molecules=bool_drug_molecules,
                               drug_dr_features=bool_drug_dr_features,
                               context_feature_set=c_features,
                               drug_feature_set=drug_features,
                               labeled_triples=test)

    results = modified_dr_pipeline(
        train_batch_generator = train_generator,
        test_batch_generator = test_generator,
        model=model,
        # Data arguments
        context_features=bool_context_features,
        drug_features=bool_drug_features,
        drug_molecules=bool_drug_molecules,
        drug_dr_features=bool_drug_dr_features,
        # Training arguments
        epochs=num_epochs,
    )

    return results

def save_output_results(results, fh, save_model=False):
    """Save the results object to a specified path."""
    if save_model:
        torch.save(results.model, fh+"_model.pkl")
    fh = Path(fh)
    fh_dirname = os.path.dirname(fh)
    if not os.path.isdir(fh_dirname):
        os.makedirs(fh_dirname)
    Path(fh).write_text(
        json.dumps(
            {
                "evaluation": results.metrics,
                "losses": results.losses,
                "training_time": results.train_time,
                "evaluation_time": results.evaluation_time,
            },
            indent=2,
        )
    )

def train_dr_model(embedding_dirpath,
    embedding_dataset,
    embedding_decomposition,
    embedding_dimension,
    embedding_num_epochs,
    model,
    num_epochs,
    batch_size,
    train_size=0.5,
    random_state=123,
    save_results=True,
    save_model=False,
    results_folder="results",
    bool_context_features=False,
    bool_drug_features=False,
    bool_drug_molecules=False,
    bool_drug_dr_features=False):
    """This utility function aims to bring together
    learning/loading the distributed representations
    and feeding
    """

    # Check if results already exists
    results_fh = f"{embedding_dataset.dataset_name}_{embedding_decomposition}_{embedding_dimension}_{embedding_num_epochs}_{type(model).__name__}_{num_epochs}__{batch_size}_{train_size}_{random_state}.json"
    results_fh = os.path.join(results_folder, results_fh)
    if os.path.exists(results_fh):
        print("# This has already been learned and evaluated, returning dict of metrics")
        with open(results_fh) as fh:
            results = json.load(fh)
            return results

    # Check the DR embedding file, if its available, load the embeddings
    # otherwise learn the desired embeddings
    dataset = embedding_dataset
    drug_features = dataset.get_drug_features()
    c_features = dataset.get_context_features()
    triples = dataset.get_labeled_triples()

    # Load and torch tensor -ize the embeddings
    drug_dr_embeddings = g2dr(embedding_dataset,
        embedding_decomposition,
        embedding_dimension,
        embedding_num_epochs,
        embedding_dirpath)
    for drug in drug_dr_embeddings.keys():
        drug_dr_embeddings[drug] = torch.FloatTensor(drug_dr_embeddings[drug])

    # augment the drug_features with the dr embeddings
    for drug_name in drug_features.keys():
        drug_features[drug_name]['dr'] = drug_dr_embeddings[drug_name]

    # train and evaluate the DR compatible model with the new data
    results = pipeline_dr_model(model,
        num_epochs,
        batch_size,
        drug_features,
        c_features,
        triples,
        train_size=train_size,
        random_state=random_state,
        bool_context_features=bool_context_features,
        bool_drug_features=bool_drug_features,
        bool_drug_molecules=bool_drug_molecules,
        bool_drug_dr_features=bool_drug_dr_features)

    if save_results:
        save_output_results(results, results_fh, save_model=save_model)

    return results

def train_non_dr_model(model,
    dataset,
    num_epochs,
    batch_size,
    train_size,
    random_state,
    save_results,
    save_model,
    results_folder="results",
    bool_context_features=False,
    bool_drug_features=False,
    bool_drug_molecules=False,
    bool_drug_dr_features=False):
    """This utility function trains and evaluates non dr based models

    """
    # Check if results already exists
    results_fh = f"{dataset.dataset_name}_{type(model).__name__}_{num_epochs}__{batch_size}_{train_size}_{random_state}.json"
    results_fh = os.path.join(results_folder, results_fh)
    if os.path.exists(results_fh):
        print("# This has already been learned and evaluated, returning dict of metrics")
        with open(results_fh) as fh:
            results = json.load(fh)
            return results

    drug_features = dataset.get_drug_features()
    c_features = dataset.get_context_features()
    triples = dataset.get_labeled_triples()

    results = pipeline_dr_model(model,
        num_epochs,
        batch_size,
        drug_features,
        c_features,
        triples,
        train_size=train_size,
        random_state=random_state,
        bool_context_features=bool_context_features,
        bool_drug_features=bool_drug_features,
        bool_drug_molecules=bool_drug_molecules,
        bool_drug_dr_features=bool_drug_dr_features)

    if save_results:
        save_output_results(results, results_fh, save_model=save_model)

    return results


import numpy as np

from qiskit import Aer, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.opflow import StateFn, PauliSumOp,AerPauliExpectation,ListOp,Gradient

from qiskit.utils import QuantumInstance,algorithm_globals

algorithm_globals.random_seed = 42

# set method to calculate expeceted values
expval  = AerPauliExpectation()

# define gradient method
gradient = Gradient()

# define quantum instances (statevector and sample based)
qi_sv = QuantumInstance(Aer.get_backend("aer_simulator_statevector"))

# we set shots to 10 as this will determine the number of samples later on.
qi_qasm = QuantumInstance(Aer.get_backend("aer_simulator"),shots = 10)

from qiskit_machine_learning.neural_networks import OpflowQNN

# constuct parameterized circuit
params1 = [Parameter("input1"),Parameter("weights1")]
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.ry(params1[0],0)
qc1.rx(params1[1],0)
qc_sfn1 = StateFn(qc1)

# construct the cost operator
H1 = StateFn(PauliSumOp.from_list([("Z",1.0),("X",1.0)]))

# combine operator and circuit to objective function
op1 = ~H1 @ qc_sfn1
print(op1)
# construct opflowqnn with the operator, the input parameters, the weight parameters
qnn1 = OpflowQNN(op1, [params1[0]], [params1[1]], expval, gradient, qi_sv)

input1 = algorithm_globals.random.random(qnn1.num_inputs)
weights1 = algorithm_globals.random.random(qnn1.num_weights)

out = qnn1.forward(input1,weights1)
print(out)
back = qnn1.backward(input1, weights1)
print(back)
print("End of the calculation")


import subprocess as sp
from collections import defaultdict
import numpy as np
import pandas as pd
import argparse
import pickle
import os
import re

'''
This script creates feature matrix from VCF files for downstream ML analysis
'''
parser=argparse.ArgumentParser(description='Append MIC phenotype to MIC dataframe')
parser.add_argument('-MIC',help='MIC phenotype dataframe',required=True)
parser.add_argument('-pheno',help='Output folder',required=True)
args=parser.parse_args()

drug=(os.path.basename(args.pheno)).split('_')[0]
print(drug)
pheno_series={}

with open(args.pheno,'r') as f:
    for l in f:
        sample,pheno=l.strip().split()
        pheno_series[sample]=pheno

pheno_series=pd.Series(pheno_series,name=drug,dtype='category')
print(pheno_series.cat.categories)
pheno_series=pheno_series.cat.reorder_categories(['NA','Sus','Low','High','Resistant'],ordered=True)
print(pheno_series.cat.categories)

df=pickle.load(open(args.MIC,'rb'))
print(f'Preivous shape: {df.shape}')
print(df.head())
out_df=pd.concat([df,pheno_series],axis=1,join='inner')
print(f'New shape: {out_df.shape}')
print(out_df.head())
#print(f'Sorted {out_df[drug].sort_values()}')

out_df.to_pickle(path=args.MIC)


import logging
import sys
from pathlib import Path
from typing import Union
import datetime

import discord.ext.commands
from discord import Message
from discord.ext.commands.bot import Bot
from google.cloud import firestore
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

from .analytics import log_command
from .cogs import Help, Settings, Dictionary, Statistics
from .dictionary_api import DictionaryAPI
from .utils import get_bot_permissions

# Set up logging
logger = logging.getLogger(__name__)

def get_prefix(bot: Bot, message: Message):
    preferences_cog = bot.get_cog('Settings')
    return preferences_cog.scoped_property_manager.get('prefix', message.channel)

class DiscordBotClient(Bot):

    def __init__(self, dictionary_apis: [DictionaryAPI], ffmpeg_path: Union[str, Path], **kwargs):
        """
        Creates a new Discord bot client.
        :param dictionary_apis: A list of 'DictionaryAPI's that are available for the bot to use.
        :param ffmpeg_path:
        :param kwargs:
        """
        super().__init__(get_prefix, help_command=None, **kwargs)
        slash = SlashCommand(self, sync_commands=True)  # This needs to be here for slash commands to work!
        self.add_cog(Help())
        self.add_cog(Dictionary(self, dictionary_apis, ffmpeg_path))
        self.add_cog(Settings())
        self.add_cog(Statistics(self))

        @self.before_invoke
        async def before_command_invoked(context: commands.Context):
            if isinstance(context.command, discord.ext.commands.Group):
                return
            logger.info(f'[G: "{context.guild}", C: "{context.channel}"] "{context.message.content}"')
            log_command(context.command.name, False, context)

        @self.event
        async def on_slash_command(context: SlashContext):
            logger.info(f'[G: "{context.guild}", C: "{context.channel}"] "/{context.command}" {context.kwargs}')
            log_command(context.command, True, context)

    async def on_command_error(self, context: commands.Context, exception: Exception):
        if isinstance(exception, commands.errors.CommandNotFound):
            pass  # Ignore command not found
        elif isinstance(exception, commands.errors.MissingRequiredArgument):
            await context.send('Invalid command usage!')
        elif isinstance(exception, commands.errors.ArgumentParsingError):
            await context.send('Invalid arguments! Usage: `' + context.command.usage + '`')
        elif isinstance(exception, commands.errors.CommandInvokeError) and isinstance(exception.original, discord.errors.Forbidden):
            logger.error(f'Missing permissions. We have {get_bot_permissions(context)}', exc_info=exception)
        else:
            logger.error('Error on command!', exc_info=exception)
            await super().on_command_error(context, exception)

    async def on_error(self, event_method, *args, **kwargs):
        exception = sys.exc_info()[1]
        if isinstance(exception, discord.errors.Forbidden):
            if isinstance(args[0], discord.Message):
                fake_context = type('', (), {'channel': args[0].channel})()
                logger.error(f'Missing permissions. We have {get_bot_permissions(fake_context)}', exc_info=exception)

    async def on_ready(self):
        logger.info(f'Logged on as {self.user}!')

        # Check for new guilds
        firestore_client = firestore.Client()
        for guild in self.guilds:
            document = firestore_client.collection('guilds').document(str(guild.id))
            snapshot = document.get()
            if not snapshot.exists:
                await self.on_guild_join(guild)

    async def on_message(self, message: discord.Message):

        # If we are mentioned, show our prefix and help
        if self.user in message.mentions:
            prefix = get_prefix(self, message)
            await message.reply(f'My prefix here is `{prefix}`\nUse `{prefix}help` to view available commands.', mention_author=False)

        await super().on_message(message)

    async def on_guild_join(self, guild: discord.Guild):
        logger.info('Joined guild: ' + guild.name)

        firestore_client = firestore.Client()
        guild_document = firestore_client.collection('guilds').document(str(guild.id))
        snapshot = guild_document.get()

        if not snapshot.exists:
            guild_document.set({
                'joined': datetime.datetime.now()
            })


import operator

OPERATIONS = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}

class Node:
    def __init__(self):
        self.data = None
        self.left: Node = None
        self.right: Node = None
        self.root: Node = self

    def getLeftChild(self):
        if self.left is None:
            self.left = Node()
            self.left.setRoot(root=self)
        return self.left

    def getRightChild(self):
        if self.right is None:
            self.right = Node()
            self.right.setRoot(root=self)
        return self.right

    def getLeft(self):
        return self.left

    def getRight(self):
        return self.right

    def getValue(self):
        return self.data

    def setValue(self, data: str):
        self.data = data

    def setRoot(self, root):
        self.root = root

    def getNodeRoot(self):
        return self.root

    def printNode(self, delimiter: str):
        s = self.root.getValue() + delimiter + self.data
        if self.left is not None:
            s += ' ' + self.left.printNode('\\')
        if self.right is not None:
            s += ' ' + self.right.printNode('/')
        return s

class TreeParser:
    def __init__(self, expr: str):
        self._expr = expr
        self.currentNode = Node()
        self.root = self.currentNode

    def build_tree(self):
        for token in self._expr.split():
            if token == '(':
                self.currentNode = self.currentNode.getLeftChild()

            elif token in OPERATIONS.keys():
                self.currentNode.setValue(data=token)
                self.currentNode = self.currentNode.getRightChild()

            elif token == ')':
                self.currentNode = self.currentNode.getNodeRoot()

            elif token not in OPERATIONS.keys():
                self.currentNode.setValue(data=token)
                self.currentNode = self.currentNode.getNodeRoot()

        return self.root

class TreeEvaluator:
    def __init__(self):
        pass

    def resolve_tree(self, tree: Node):
        leftNode = tree.getLeft()
        rightNode = tree.getRight()

        if leftNode is not None and rightNode is not None:
            op = OPERATIONS[tree.getValue()]
            right_result = self.resolve_tree(rightNode)
            left_result = self.resolve_tree(leftNode)
            result = op(left_result, right_result)
            return result
        else:
            return self.try_to_parse(tree.getValue())

    def try_to_parse(self, data: str):
        try:
            return int(data)
        except ValueError:
            return float(data)
        except ValueError:
            return data


import solution

class Solution(solution.Solution):
    def solve(self, test_input=None):
        nums, pos = test_input
        nums = nums.copy()
        index = 0
        curr = head = ListNode(nums.pop(0))
        node = None
        while nums:
            if index == pos:
                node = curr
            curr.next = ListNode(nums.pop(0))
            curr = curr.next
            index += 1
        if node:
            curr.next = node
        return self.hasCycle(head)

    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = fast = head
        while fast:
            slow = slow.next
            if fast.next:
                fast = fast.next.next
            else:
                return False
            if fast == slow:
                return True
        return False

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


#!/usr/bin/env python

import turtle
import sys
import tkinter as tk

#s = turtle.getscreen()
t = turtle.Turtle()
#color('red', 'yellow')

while True:
    t.forward(200)
    t.left(150)
    if abs(t.pos()) < 1:
        break
        #t.circle(60)

t.end_fill()
sys.exit()


'''
拖动控件之间的边界：QSplitter

'''
import sys,math
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Splitter(QWidget):
    def __init__(self):
        super(Splitter,self).__init__()
        self.initUI()
    def initUI(self):
        layout=QHBoxLayout(self)
        self.setWindowTitle('QSplitter例子')
        self.setGeometry(300,300,300,200)

        topleft=QFrame()#创建框架
        topleft.setFrameShape(QFrame.StyledPanel)

        bottom=QFrame()
        bottom.setFrameShape(QFrame.StyledPanel)

        splitter1=QSplitter(Qt.Horizontal)#水平拖动
        textedit=QTextEdit()#创建文本框
        splitter1.addWidget(topleft)#将框架放到水平拖动上（Frame不可输入文字）
        splitter1.addWidget(textedit)#将文本框放到谁平拖动上（因为topleft在textedit之前，所以toleft在左边），左右结构
        splitter1.setSizes([100,200])#设置左右两个框的宽度

        splitter2 = QSplitter(Qt.Vertical)#上下拖动
        splitter2.addWidget(splitter1)#上下结构
        splitter2.addWidget(bottom)
        splitter2.setSizes([150,150])

        layout.addWidget(splitter2)#将总的放到布局中
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Splitter()
    main.show()
    sys.exit(app.exec_())

104.拖动控件之间的边界.py

104.拖动控件之间的边界.py


import os
import sys
import json
import requests
from dotenv import load_dotenv

load_dotenv()

try:
    path = sys.argv[1]
except IndexError:
    path = input('Path to .md file:\n')

with open(path, 'r') as file:
    md_text = file.read()

TOKEN = os.getenv('TOKEN')
URL = 'https://api.github.com/markdown'
HEADERS = {
    'Accept': 'application/vnd.github+json',
    'Authorization': f'token {TOKEN}'
}
body = {
    'text': md_text
}
response = requests.post(URL, data=json.dumps(body), headers=HEADERS)

if response.ok:
    print(response.text)

    path_dest = path.replace('.md', '.html')
    if os.path.exists(path_dest):
        while True:
            answer = input(
                'An HTML file with that name already exists, '
                'do you wish to overwrite this file? (y/n)'
            ).strip().lower()
            if answer in ('n', 'no'):
                print('\n---File was not written.')
                input('Press any key to close')
                sys.exit()
            elif answer in ('y', 'yes'):
                break

    with open(path_dest, 'w+') as file:
        file.write(response.text)

    print('\n---Operation successful')
else:
    print('Something went wrong')
    print(response.status_code)

input('Press any key to close')


from RadialBasisFunction import *
import numpy as np
from sklearn import datasets

C=3
F=2
X,Y = datasets.make_classification(
    n_features=C,
    n_classes=F,
    n_samples=200,
    n_redundant=0,
    n_clusters_per_class=1
)

X=X.T
Y=np.array([Y])

RBF =RadialBasisFunction(C,4)
RBF.Train(X,Y,5,100)


import pygame
import datetime
pygame.init()

WIDTH=1080
HEIGHT=720
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock=pygame.image.load("images/main-clock.png").convert()
scale_clock = pygame.transform.scale(
    clock, (clock.get_width() // 2,
              clock.get_height() // 2))
clockr=scale_clock.get_rect(center=(WIDTH/2, HEIGHT/2))

second=pygame.image.load("images/left-hand.png").convert_alpha()
scale_second=pygame.transform.scale(
    second, (second.get_width() // 2,
               second.get_height() // 2))

minute=pygame.image.load("images/right-hand.png").convert_alpha()
scale_minute=pygame.transform.scale(
    minute, (minute.get_width() // 2,
               minute.get_height() // 2))

done = False
while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
        screen.fill((255,255,255))
        screen.blit(scale_clock, clockr)
        t=datetime.datetime.now()
        minutes, seconds=t.minute, t.second
        rots = pygame.transform.rotate(scale_second, (-6*seconds)+90)
        rots_rect = rots.get_rect(center=(540, 360))
        screen.blit(rots, rots_rect)
        rotm = pygame.transform.rotate(scale_minute, (-6*minutes)+90) #(-6*minutes-0.1*seconds)+90
        rotm_rect = rotm.get_rect(center=(540, 360))
        screen.blit(rotm, rotm_rect)
        pygame.display.update()


import os
import shutil
from typing import List, Tuple

import pytest

from src.models.running_token import RunningToken
from src.models.token import Token

# folder names and paths of all test files
test_files_folder_name = 'test_files'
xml_files_folder_name = 'xml'
temp_xml_files_folder_name = 'temp_xml'

def pytest_sessionstart():
    """
    Called after the Session object has been created and
    before performing collection and entering the run test loop.

    When working with xml files, we copy all files to
    a new directory to prevent overwriting of test files.
    All tests are performed there.

    We copy all xml-files from test/test_files/xml to test/test_files/temp_xml
    """

    pytest_root = os.path.dirname(os.path.abspath(__file__))
    xml_folder = os.path.join(pytest_root,
                              test_files_folder_name,
                              xml_files_folder_name)
    temp_xml_folder = os.path.join(pytest_root,
                                   test_files_folder_name,
                                   temp_xml_files_folder_name)

    try:
        shutil.copytree(xml_folder, temp_xml_folder)
    except FileExistsError:
        pass

def pytest_sessionfinish():
    """
    Called after whole test run finished, right before
    returning the exit status to the system.

    We use this timing to delete the temporary xml folder.
    """
    pytest_root = os.path.dirname(os.path.abspath(__file__))
    temp_xml_folder = os.path.join(pytest_root,
                                   test_files_folder_name,
                                   temp_xml_files_folder_name)
    shutil.rmtree(temp_xml_folder)

@pytest.fixture(scope='module', autouse=True)
def xml_folders_path():
    """
    Fixture to access all the xml test files.
    Returns the path to the temporary ones to use. Doesnt return the path to
    the original ones to prevent overwriting.
    """
    pytest_root = os.path.dirname(os.path.abspath(__file__))
    temp_xml_folder = os.path.join(pytest_root,
                                   test_files_folder_name,
                                   temp_xml_files_folder_name)
    return temp_xml_folder

@pytest.fixture(scope='function', autouse=True)
def empty_token() -> Token:
    return Token(attributes=None)

@pytest.fixture(scope='function', autouse=True)
def empty_running_token() -> RunningToken:
    return RunningToken(attributes=None)

@pytest.fixture(scope='function', autouse=True)
def example_token() -> Token:
    attributes = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
    return Token(attributes=attributes)

@pytest.fixture(scope='function', autouse=True)
def example_running_token() -> RunningToken:
    attributes = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
    return RunningToken(attributes=attributes)

@pytest.fixture(scope='module', autouse=True)
def nn_word() -> List[Tuple[str, str]]:
    return [('contract', 'NN')]

@pytest.fixture(scope='module', autouse=True)
def adj_word() -> List[Tuple[str, str]]:
    return [('to', 'TO'), ('be', 'VB'), ('smart', 'JJ')]

@pytest.fixture(scope='module', autouse=True)
def nn_vb_nn_sentence() -> List[Tuple[str, str]]:
    return [('contract', 'NN'), ('sending', 'VBG'), ('agreement', 'NN')]

@pytest.fixture(scope='module', autouse=True)
def xx_nn_xx_sentence() -> List[Tuple[str, str]]:
    return [('sending', 'VBG'), ('contract', 'NN'), ('green', 'ADJ')]


sklad = {
  "1N4148": 250,
  "BAV21": 54,
  "KC147": 147,
  "2N7002": 97,
  "BC547C": 10
}
kod=input("Zadej kód součástky: ")
mnozstvi=int(input("Zadej množství součástek: "))

# je/není skladem
if kod in sklad:
    print(f'Součástka {kod} je skladem.')
else:
    print((f'Součástka {kod} není skladem.'))
    exit()

# je skladem, ale je 1. méně / 2. více
if mnozstvi>sklad[kod]:
    print(f'Počet {mnozstvi} kusů požadované součástky {kod} není skladem Lze prodat pouze {sklad[kod]} kusů.')
    del sklad[kod]
else:
    print(f'Poptávku lze uspokojit. Počet {mnozstvi} kusů požadované součástky {kod} je skladem.')
    sklad[kod] -= mnozstvi
    print(f'Zbývá {sklad[kod]} kusů součástky {kod}')


from collections import Node

# Definition for a Node.
""""
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
"""

class Solution:
    def treeToDoublyList(self, root: 'Node') -> 'Node':
        # first analyze BST ppties
        # analye what a circular LL is as well
        # we need to do this inplace so we need to reassign pointers
        # from the example, we will need an inorder traversal(left, root and right)
        # easiest/cleanest way is dfs

        # we need head and tail pointer for linked list
        # will the linkedlist have prev/next or right and left?

        if not root:
            return

        def dfs(node):
            nonlocal head, tail

            if not node:
                return
            dfs(node.left)

            # handle tail and head
            if tail:
                tail.right = node
                node.left = tail
            else:
                head = node

            tail = node

            dfs(node.right)

        head, tail = None, None
        dfs(root)
        head.left = tail
        tail.right = head

        return head


# Creating a Bouncing Ball Screensaver using OpenCV-Python
# Task- Create a Window that we can write text on. If we don’t write for 5 seconds screensaver will start.

import cv2
import numpy as np

def screensaver():
    img = np.zeros((480,640,3),dtype='uint8')
    dx,dy =1,1
    x,y = 100,100
    while True:
        # Display the image
        cv2.imshow('Screensaver',img)
        k = cv2.waitKey(10)
        img = np.zeros((480,640,3),dtype='uint8')  #This line will help in making different circle everytime loop runs.
        # Increment the position
        x = x+dx
        y = y+dy
        cv2.circle(img,(x,y),20,(255,130,140),-1)
        if k != -1:
            break
        # Change the sign of increment on collision with the boundary
        if y >=480 or y<=0 :
           dy *= -1

        if x >=640 or x<=0 :
           dx *= -1
    cv2.destroyAllWindows()

# Background Image
img1 = cv2.imread('./images/aryan__bindal.jpg')
# Initialize these for text placement
i = 0
a,b = 30,30
while True:
    cv2.imshow('My Photo',img1)
    k = cv2.waitKey(5000)
    # If no key is pressed, display the screensaver
    if k == -1:
        screensaver()
    # Press q to quit
    elif k == ord('q'):
        break
    # Otherwise write real time text on the image.
    # This is used for visualization only
    # You can use anything here.
    else:
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img1,chr(k),(a+i,b), font, 1,(0,0,0),3,cv2.LINE_AA)
 # The shape[] attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m).
 # So Y.shape[0] is n and Y.shape[1] is m.
        if a+i >= img1.shape[1]:
            b = b+15
            i = 0
        i +=20

cv2.destroyAllWindows()


import pandas as pd
import re
from utils import ANALYTICS_DATASET, ENVIRONMENT_SHORT_NAME

def get_data_archiving(sql_file):
    """Run SQL query and save data in a dataframe."""

    params = {"{{ANALYTICS_DATASET}}": ANALYTICS_DATASET}

    file = open(sql_file, "r")
    sql = file.read()

    for param, table_name in params.items():
        sql = sql.replace(param, table_name)

    archives_df = pd.read_gbq(sql, dialect="standard")

    return archives_df

def preprocess_data_archiving(
    _df,
    object_type,
    parent_folder_to_archive,
    limit_inactivity_in_days,
):

    # Compute the number of days since last activity of a card
    _df = _df.assign(
        days_since_last_execution=lambda _df: pd.to_datetime("today")
        - _df["last_execution_date"].dt.tz_localize(None)
    )

    if ENVIRONMENT_SHORT_NAME == "prod":
        _df["destination_collection_id"] = (  # Get the archive collection id
            _df["archive_location_level_2"]
            .dropna()
            .str.split("/")
            .apply(lambda x: x[-1])
        )
        _df = _df[
            ~_df["archive_location_level_2"].isna()
        ]  # Remove elements for which destination collection is empty.
        # Filter the inactive cards in the folder we want to archive.
        _df = _df[
            (
                _df["days_since_last_execution"]
                >= pd.to_timedelta(limit_inactivity_in_days, unit="d")
            )
            & (_df["parent_folder"].isin(parent_folder_to_archive))
        ]

    if ENVIRONMENT_SHORT_NAME == "dev" or ENVIRONMENT_SHORT_NAME == "stg":
        _df["destination_collection_id"] = 29
        # In dev, we consider a card to be inactive after 1 day of inactivity.
        _df = _df[(_df["days_since_last_execution"] >= pd.to_timedelta(1, unit="d"))]

    if object_type == "card":
        _df_to_archive = (
            _df.drop("collection_id", axis=1)
            .rename(
                columns={
                    "card_id": "id",
                    "card_name": "name",
                    "card_collection_id": "collection_id",
                }
            )
            .assign(
                object_type=object_type
            )  # Take the min of the 'archive_question' boolean to be more restrictive
        )

        _dict_to_archive = (  # Stock data in a dict
            _df_to_archive[
                [
                    "id",
                    "name",
                    "object_type",
                    "collection_id",
                    "destination_collection_id",
                    "total_users",
                    "total_views",
                    "nbr_dashboards",
                    "last_execution_date",
                    "last_execution_context",
                    "total_errors",
                    "parent_folder",
                    "days_since_last_execution",
                ]
            ]
            .assign(
                destination_collection_id=lambda _df: _df[
                    "destination_collection_id"
                ].astype(int)
            )
            .sort_values("id")
            .drop_duplicates()
            .to_dict(orient="records")
        )

        return _dict_to_archive

class move_to_archive:
    def __init__(self, movement, metabase, gcp_project, analytics_dataset):
        self.movement = movement
        self.id = movement.get("id", None)
        self.name = movement.get("name", None)
        self.object_type = movement.get("object_type", None)
        self.destination_collection = movement.get("destination_collection_id", None)
        self.collection_id = movement.get("collection_id", None)
        self.last_execution_date = movement.get("last_execution_date", None)
        self.last_execution_context = movement.get("last_execution_context", None)
        self.parent_folder = movement.get("parent_folder", None)
        self.gcp_project = gcp_project
        self.analytics_dataset = analytics_dataset

        self.metabase_connection = metabase

    def rename_archive_object(self):
        """Rename the object to archive. Add ['Archive - '] prefix to object name."""

        if re.search("archive", self.name, re.IGNORECASE):
            archive_name = self.name
        else:
            archive_name = "[Archive] - " + self.name

        params = {"name": archive_name}

        if self.object_type == "card":
            result = self.metabase_connection.put_card(self.id, params)

        return result

    def move_object(self):
        """Move the object from its original collection to the archive collection."""

        id_list = [self.id]

        if self.object_type == "card":
            result = self.metabase_connection.update_card_collections(
                id_list, self.destination_collection
            )

        archived_logs = []

        if result.get("status") == "ok":
            archived_logs.append(
                {
                    "id": self.id,
                    "object_type": self.object_type,
                    "status": "success",
                    "new_collection_id": self.destination_collection,
                    "previous_collection_id": self.collection_id,
                    "archived_at": pd.Timestamp.now(),
                    "last_execution_date": self.last_execution_date,
                    "last_execution_context": self.last_execution_context,
                    "parent_folder": self.parent_folder,
                }
            )
        else:
            archived_logs.append(
                {
                    "id": self.id,
                    "object_type": self.object_type,
                    "status": result.get("status"),
                    "new_collection_id": self.destination_collection,
                    "previous_collection_id": self.collection_id,
                    "archived_at": pd.Timestamp.now(),
                    "last_execution_date": self.last_execution_date,
                    "last_execution_context": self.last_execution_context,
                    "parent_folder": self.parent_folder,
                }
            )
        return archived_logs

    def save_logs_bq(self):
        """Save the movement in a BQ table."""

        archived_logs_dict = self.move_object()
        archived_logs_df = pd.DataFrame(archived_logs_dict)
        archived_logs_df.to_gbq(
            f"""{self.gcp_project}.{self.analytics_dataset}.logs_metabase_archiving""",
            project_id=self.gcp_project,
            if_exists="append",
        )
        return "Logs saved in BQ"


from sys import platform
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from tabulate import tabulate
import string
import settings
df = pd.read_csv("Cleaned_dataset.csv")

df = df.iloc[0:10000,:]

features = ['Name', 'Platform', 'Genre']
def combine_features (row):
    return row['Name'] + " " +  row['Platform'] + " " + row['Genre']

searchTerms = []
df["combine_features"] = df.apply(combine_features, axis=1)

def get_genre_from_name(name):
    genres_to_return = []
    sep_games = name.split()
    print (sep_games)
    i = 0
    while (i < len(sep_games)):
        for index, row in df.iterrows():

            all_games_with_no_spaces = ""
            all_genres = row['Genre'].lower()
            all_games  = row['Name'].lower()
            all_games_with_no_spaces += all_games.replace (" ", "" )
            if all_games_with_no_spaces in sep_games[i] or sep_games[i] in all_games_with_no_spaces:
                 genres_to_return.append(all_genres)
        i = i + 1
    genres_to_return = set(genres_to_return)
    return(genres_to_return)

def list_to_string(lst):
    game_string  = ""
    for g in lst:
        game_string += g + " "
    return game_string

def get_genres():
  print("Enter your favourite video game genres (Action, sport, Shooter, etc.)")
  genres = input("type 'skip' OR if multiple separate them with comma:  ")
  genres = " ".join(["".join(n.split()) for n in genres.lower().split(',')])
  return genres

def get_platforms():
  print("\nEnter your favourite gaming platform(s) (PC, Playstation, etc.)")
  platforms = input("type 'skip' OR if multiple separate them with comma:  ")
  platforms = " ".join(["".join(n.split()) for n in platforms.lower().split(',')])
  return platforms

def get_games():
  print("\nEnter some games that you previously played and enjoyed (Wii Sports, Resident Evil, Call of Duty, etc.)")
  games = input("type 'skip' OR if multiple separate them with comma:  ")
  games = " ".join(["".join(n.split()) for n in games.lower().split(',')])
  return games

def get_searchTerms():

  genre = get_genres()
  if genre != 'skip':
    searchTerms.append(genre)

  platform = get_platforms()
  if platform != 'skip':
    searchTerms.append(platform)

  game = get_games()
  genres_from_games = []
  if game != 'skip':
    genres_from_games = (get_genre_from_name(game))
    str_genres_from_games = list_to_string(genres_from_games)
    searchTerms[0] = searchTerms[0] + " " + str_genres_from_games
  # print (searchTerms)
  return searchTerms

def make_recommendation(searchTerms, games = df):
  new_row = games.iloc[-1,:].copy()

  # searchTerms = get_searchTerms()
  new_row.iloc[-1] = " ".join(searchTerms)
  games = df.append(new_row)

  count = CountVectorizer(stop_words='english')
  count_matrix = count.fit_transform(games['combine_features'])

  cosine_sim  = cosine_similarity(count_matrix, count_matrix)
  settings.games = games
  return cosine_sim
  # settings.sim_scores = list(enumerate(cosine_sim2[-1,:]))
  # settings.sim_scores = sorted(settings.sim_scores, key=lambda x: x[1], reverse=True)

  # lst = []
  # for i in range(1, 50):
  #   indx = settings.sim_scores[i][0]

  #   format_dec = "{:.2f}%".format((((settings.sim_scores[i][1])+1.0)/2.0)*100.0)
  #   tmp = [settings.games['Name'].iloc[indx],settings.games['Genre'].iloc[indx],settings.games['Platform'].iloc[indx], settings.games['Year_of_Release'].iloc[indx], settings.games['Publisher'].iloc[indx],
  #   settings.games['Critic_Score'].iloc[indx], settings.games['User_Score'].iloc[indx], settings.games['Rating'].iloc[indx], format_dec]
  #   lst.append(tmp)
  #   return lst
  # print(tabulate(lst, headers=['Name','Genre', 'Platform', 'Year_of_Release', 'Publisher','Critic_Score', 'User_Score', 'Rating', 'Compatibility']))

make_recommendation(searchTerms)


import os

def file_tree(Path, file_filter=None, num_of_space=0):
    for element in os.listdir(Path):
        NewPath = Path + '/' + element
        if os.path.isdir(NewPath):
            print(num_of_space * '\t' + element)
            file_tree(NewPath, file_filter, num_of_space=(num_of_space + 1))
        elif file_filter == None or element.endswith(file_filter):
            print(num_of_space * '\t' + element)

Path = input('enter dir: ')
Filter = input('enter filter: ')
file_tree(Path, Filter)


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

# C Style
a = 0b10111011
b = 0xc5f
print('Binary is %d, hex is %d' % (a, b))

print('==========================================')

# Python3 Style
a = 1234.5678
formatted = format(a, ',.2f')  # ","で3桁で区切る
print(formatted)

b = 'my string'
formatted = format(b, '^20s')  # "^" でセンタリング
print('*', formatted, '*')

key = 'my_var'
value = 1.234
formatted = '{} = {}'.format(key, value)
print(formatted)
formatted = '{0} = {1}'.format(key, value)
print(formatted)
formatted = '{:<10} = {:.2f}'.format(key, value)
print(formatted)

print('==========================================')

# Python3.6 format string
key = 'my_var'
value = 1.234
formatted = f'{key} = {value}'
print(formatted)
formatted = f'{key!r:<10} = {value:.2f}'
print(formatted)

pantry = [
    ('avocados', 1.25),
    ('bananas', 2.5),
    ('cherries', 15)
]
for i, (item, count) in enumerate(pantry):
    f_string = f'#{i+1}: {item.title():<10s} = {round(count)}'
    print(f_string)

# Note:
#  str.title() : 単語の先頭の一文字を大文字、他を小文字に変換
#  round : 数値の丸め込み(正確な四捨五入にはならにので注意)


from functools import reduce

numeros = input("ingrese numeros:")
numerosEnList = sorted(numeros)
print(numerosEnList)
numerosImpares = []

for i in numerosEnList:
    if int(i) % 2 != 0:
        numerosImpares.append(int(i))

print(numerosImpares)

def suma(a, b):
    return a + b

resultado = reduce(suma, numerosImpares)

print(resultado)


from __future__ import unicode_literals

import json
import datetime

from django.template.defaultfilters import escape

from program.models import Program
from notification.models import Notif
from ourjseditor import api
from .models import Comment

# /program/PRO_ID/comment/new
@api.StandardAPIErrors("POST")
@api.login_required
def new_comment(request, program_id):
    data = json.loads(request.body)

    # A JSON of `null` gets parsed into a Python of `None`
    # If parent isn't passed, KeyError, caught by StandardAPIErrors
    parent_comment = data["parent"]
    if parent_comment is None:
        depth = 0
    else:
        try:
            parent_comment = Comment.objects.get(comment_id=parent_comment, program_id=program_id)
        except Comment.DoesNotExist:
            return api.error("Invalid comment parent")
        depth = parent_comment.depth + 1

    if depth > 1:
        return api.error("Comments have gone too deep!")

    if parent_comment is not None:
        parent_comment.reply_count += 1
        parent_comment.save()

    program = Program.objects.get(program_id=program_id)

    created_comment = Comment.objects.create(
        user=request.user,
        program=program,
        parent=parent_comment,
        depth=depth,
        content=data["content"],
        original_content=data["content"],
    )

    link = "/program/{0}#comment-{1}".format(created_comment.program.program_id, created_comment.comment_id)

    if depth == 0:
        if program.user != created_comment.user:
            Notif.objects.create(
                target_user=program.user,
                link=link,
                description="{0} left a comment on your program, {1}".format(
                    escape(request.user.profile.display_name), escape(program.title)
                ),
                source_comment=created_comment
            )
    else:
        # Create a list of everyone in the comment thread and spam them all
        to_notify = set(Comment.objects
            .filter(parent=parent_comment)
            .exclude(user=parent_comment.user) # Not the thread starter, they get a different message
            .exclude(user=created_comment.user) # Not the user who posted this comment
            .values_list("user", flat=True)
        )

        for user in to_notify:
            Notif.objects.create(
                target_user_id=user,
                link=link,
                description="{0} commented on a thread on {1}".format(
                    escape(request.user.profile.display_name), escape(program.title)
                ),
                source_comment=created_comment
            )

        # Notify the original comment creator separately, if that's not the same person that posted this reply
        if parent_comment.user != created_comment.user:
            Notif.objects.create(
                target_user=parent_comment.user,
                link=link,
                description="{0} replied to your comment on {1}".format(
                    escape(request.user.profile.display_name), escape(program.title)
                ),
                source_comment=created_comment
            )

    response = api.succeed({"id": created_comment.comment_id}, status=201)
    response["Location"] = link
    return response

# /api/program/PRO_ID/comment/COMMENT_ID
# /api/comment/COMMENT_ID
@api.StandardAPIErrors("GET", "PATCH", "DELETE")
def comment(request, *args):
    if len(args) == 1:
        comment_id = args[0]

        requested_comment = Comment.objects.get(comment_id=comment_id)
    elif len(args) == 2:
        program_id = args[0]
        comment_id = args[1]

        requested_comment = Comment.objects.get(program_id=program_id, comment_id=comment_id)

    if request.method == "GET":
        return api.succeed(requested_comment.to_dict())

    # Comment editing!
    elif request.method == "PATCH":
        data = json.loads(request.body)

        if request.user != requested_comment.user:
            return api.error("Not authorized.", status=401)

        requested_comment.content = data["content"]
        requested_comment.edited = datetime.datetime.now()

        requested_comment.save()

        return api.succeed()
    elif request.method == "DELETE":
        if request.user != requested_comment.user:
            return api.error("Not authorized.", status=401)

        parent = requested_comment.parent
        if parent is not None:
            parent.reply_count -= 1
            parent.save()

        requested_comment.delete()

        return api.succeed()

# Endpoint for what KA calls replies, i.e. comments on comments, i.e. comments with a depth > 0
# Note: POST requests for these are still made to /api/program/PRO_ID/comments, just with "parent": "COMMENT_ID"
# /api/program/PRO_ID/comment/COMMENT_ID/comments
# /api/comment/COMMENT_ID/comments
@api.StandardAPIErrors("GET")
def comment_comments(request, *args):
    if len(args) == 1:
        comment_id = args[0]

        comments = Comment.objects.select_related("user__profile").filter(parent__comment_id=comment_id).order_by("created")
    elif len(args) == 2:
        program_id = args[0]
        comment_id = args[1]

        comments = Comment.objects.select_related("user__profile").filter(program_id=program_id, parent__comment_id=comment_id).order_by("created")

    comments = list(comments)
    return api.succeed({
        "comments": [c.to_dict() for c in comments]
    })

# /program/PRO_ID/comments
@api.StandardAPIErrors("GET")
def program_comments(request, program_id):
    comments = list(Comment.objects.select_related("user__profile").filter(program_id=program_id, depth=0).order_by("-created"))
    return api.succeed({
        "comments": [c.to_dict() for c in comments]
    })


import sys
import os
import gui.button
from argument_parser import ArgumentParser
from data_extraction.collect_data import CollectData
from data_extraction.request_handler import RequestHandler
from data_extraction.url_collector import UrlCollector
from data_storage.data_holder import DataHolder

if os.getcwd() not in sys.path:
    sys.path.insert(0, os.getcwd())

BASE_URL = "https://books.toscrape.com/"

def init_request_handler():
    try:
        page_handler = RequestHandler.create_request_handler(BASE_URL)
    except ValueError as ve:
        print(ve)
        return None
    else:
        return page_handler

def main(args):
    request_handler = init_request_handler()
    if not request_handler:
        exit(1)

    if args.gui:
        gui.button.Button(request_handler)
    else:
        url_collector = UrlCollector(request_handler)
        data_holder = DataHolder()
        collector = CollectData(args.books, args.genres, args.filters, args.keywords, args.title,
                                args.titles_json, request_handler, url_collector, data_holder)
        collector.collect_books_data()
        collector.collection.sort_collection(args.sorting)
        collector.collection.export_data_to_file()

if __name__ == "__main__":
    parser = ArgumentParser()
    main(parser.parse_arguments())


from flask import Flask, request, render_template
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import os

app = Flask(__name__)

# Get the absolute path to your application's directory
#app_directory = os.path.dirname(os.path.abspath(__file__))

# Construct the absolute path to model.keras
#model_file_path = os.path.join(app_directory, "/home/deepak04/mysite/plant_disease_prediction.h5")

# Load the trained Keras model without custom objects
#model_keras = tf.keras.models.load_model(model_file_path)

# Specify the directory and model file name
directory = ''
model_filename = 'plant_disease_prediction.h5'

# Construct the full filepath
model_filepath = os.path.join(directory, model_filename)
print(model_filepath)
# Load the Keras model
model_keras = tf.keras.models.load_model(model_filepath)

output_class = ["corn maize_northen leaf blight","Corn(maize)_Cercospora_leaf_spot","Orange", "Peach_bacterial_spot", "Peach_healthy", "Pepper bell bacterial spot", "pepper bell healthy", "potato early blight", "potato helathy", "potato late blight","rasberry healthy","squash powdery mildew","strawberry leaf scorch","strawberry healthy","Tomato bacterial spot","Tomato early blight","Tomato healthy","Tomato late blight","Tomato leaf mold","Tomato mosaic virus","Tomato septoria leaf spot","Tomato spider mites","Tomato target spot","Tomato yellow leaf curl virus","apple scab","apple blac rot","apple cedar apple rust","apple helathy","blueberry healthy","cherry(including sour) powder mildew","cherry(including sour)healthy","corn maize common rust","corn maize healthy","grape esca","grape black rot","grape healthy","grape leaf blight","soyabean healthy"]

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    # Get the uploaded image
    img = request.files['image']

    if img.filename == '':
        return render_template('index.html', error="No file selected")

    img_path = "static/uploaded_image.jpg"
    img.save(img_path)

    test_image = image.load_img(img_path, target_size=(224, 224))
    test_image = image.img_to_array(test_image) / 255
    test_image = np.expand_dims(test_image, axis=0)

    predicted_array = model_keras.predict(test_image)
    predicted_value = output_class[np.argmax(predicted_array)]
    predicted_accuracy = round(np.max(predicted_array) * 100, 2)

    return render_template('index.html', prediction_value=predicted_value,
                               prediction_accuracy=predicted_accuracy,image_path=img_path)

if __name__ == '__main__':
    app.run(debug=True)


import sys, os

def indice(liste,element):
	return liste.index(element)

if __name__ == '__main__':

	commande = []
	for i in range(1,len(sys.argv)):
		if '-' in sys.argv[i] :
			pass
		else:
			args = []
			if i != len(sys.argv) - 1 and '-' not in sys.argv[i+1]:
				args.append(sys.argv[i])
				for j in range(i+1,len(sys.argv)):
					if sys.argv[j] != '--then' and sys.argv[j] != '--else' and sys.argv[j] != '--fi':
						args.append(sys.argv[j])
					else :
						break
				commande.append((args[0],args))
			else:
				commande.append((sys.argv[i],[sys.argv[i]]))

	arguments = sys.argv[1:]
	indice_then = indice(arguments,'--then')
	indice_else = indice(arguments, '--else')
	indice_fi = indice(arguments, '--fi')
	command1 = arguments[0]
	indice_command1 = indice(arguments,command1)
	command2 = arguments[indice_then + 1]
	indice_command2 = indice(arguments,command2)
	command3 = arguments[indice_else + 1]
	indice_command3 = indice(arguments,command3)
	commandes = [command1,command2,command3]

	for i in range(len(commandes)):
		if commandes[i] == '--then' or commandes[i] == '--else' or commandes[i] == '--fi':
			print("Usage: {} command1 arg ... --then command2 arg ... [ --else command3 arg ...] --fi".format(sys.argv[0], file=sys.stderr))
			sys.exit(1)

	pid = os.fork()
	if pid == 0:
		comm1,arg1 = commande[0]
		os.execvp(comm1,arg1)
	else:
		pid, status = os.wait()
		if os.WIFEXITED(status):
			if os.WEXITSTATUS(status) == 0:
				comm2,arg2 = commande[1]
				os.execvp(comm2,arg2)
			else:
				comm3,arg3 = commande[2]
				os.execvp(comm3,arg3)
		sys.exit(0)


'''

RESPONSE WITH HTML CONTENTS

Let's response with our first web page written in HTML. We know nothing about HTML. It is the language used for the
creating web pages,that describes the structure of the document.

Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web
pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the
document.

HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page.

In our server we are changing the contents. Instead of responding with a string, we will send a message in HTML. It is
important to change the Content-type header from text/plain to text/html for indicating that we are sending HTML code
instead of plain text.

'''

import socket
import termcolor

IP = "192.168.0.195"
PORT = 8080
MAX_OPEN_REQUESTS = 5

def process_client(cs):
    """Process the client request.
    Parameters:  cs: socket for communicating with the client"""

    # Read client message. Decode it as a string
    msg = cs.recv(2048).decode("utf-8")

    # Print the received message, for debugging
    print()
    print("Request message: ")
    termcolor.cprint(msg, 'green')

    # Build the HTTP response message. It has the following lines
    # Status line
    # header
    # blank line
    # Body (content to send)

    # This new contents are written in HTML language
    contents = """
    <!DOCTYPE html>

        <meta charset="utf-8">
        <title>Green server</title>

GREEN SERVER

I am the Green Server! :-)

    """

    # -- Everything is OK
    status_line = "HTTP/1.1 200 OK\r\n"

    # -- Build the header
    header = "Content-Type: text/html\r\n"
    header += "Content-Length: {}\r\n".format(len(str.encode(contents)))

    # -- Build the message by joining together all the parts
    response_msg = str.encode(status_line + header + "\r\n" + contents)
    cs.send(response_msg)

    # Close the socket
    cs.close()

# MAIN PROGRAM

# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the IP and PORT
serversocket.bind((IP, PORT))

# Configure the server sockets
# MAX_OPEN_REQUESTS connect requests before refusing outside connections
serversocket.listen(MAX_OPEN_REQUESTS)

print("Socket ready: {}".format(serversocket))

while True:
    # accept connections from outside
    # The server is waiting for connections
    print("Waiting for connections at {}, {} ".format(IP, PORT))
    (clientsocket, address) = serversocket.accept()

    # Connection received. A new socket is returned for communicating with the client
    print("Attending connections from client: {}".format(address))

    # Service the client
    process_client(clientsocket)


"""Defines hyperparameters and runtime settings for the Deep Q-Network."""

# The network learning rate.
LEARNING_RATE = 1e-6

# Initial probability of the learner taking a random action.
# This probability decays over time as the learner experiences the world.
EXPLORATION_START_RATE = 1

# Final probability of the learner taking a random action.
# The exploration rate should decay linearly to this value.
EXPLORATION_END_RATE = 0.05

# The number of time steps that pass before the learner's exploration rate
# decays to its final value. Determines the rate at which the exploration
# rate decays.
FINAL_EXPLORATION_TIME = 1000000

# When predicting the "value" of a state and action, we discount the value
# of potential future rewards by multiplying by this constant.
DISCOUNT = 0.9

# When the network's parameters are updated, we sample this many previous
# state-action-reward triples to use as a training set for the network.
BATCH_SIZE = 32

# The number of iterations for which a chosen action is repeated.
# Necessary for actions to have "real" consequences in the game world.
ACTION_REPEAT = 4

# Number of iterations for which we take random actions, to build a foundation
# for our state-action-reward memory.
REPLAY_START_SIZE = 50000

# Maximum size of the replay memory.
REPLAY_MEMORY_SIZE = 100000

# How many actions are to be performed between network updates.
UPDATE_FREQUENCY = 4

# How often the Q-learner should log its state.
LOG_FREQUENCY = 10000

# How often to write to log file.
LOG_WRITE_FREQUENCY = 10000

# How many times should the state be logged in a row.
LOG_IN_A_ROW = 1

# How often the Q-learner should save its parameters.
SAVE_FREQUENCY = 500000

# Shape of the frames to use in the network.
FRAME_HEIGHT, FRAME_WIDTH = (84, 84)

# The number of frames used in a state object.
STATE_FRAMES = 4

# Whether to use duel architecture or not.
DUELING_ARCHITECTURE = False

# Whether to include pooling layers or not.
POOLING_ARCHITECTURE = False

# Where to log score ratio.
LOG_PATH = 'score_ratio_log.txt'

# Where to save and load network weights to/from.
CHK_PATH = './deep_q_model/'


import glob
import os

import corner
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.stats

import matplotlib.lines as mlines

VIOLET_COLOR = "#8E44AD"
BILBY_BLUE_COLOR = '#0072C1'

PARAMS = dict(
    # chi_eff=dict(l=r"$\chi_{eff}$", r=(-1, 1)),
    # chi_p=dict(l=r"$\chi_{p}$", r=(-1, 1)),
    cos_tilt_1=dict(l=r"$\cos(t1)$", r=(-1, 1)),
    # cos_tilt_2=dict(l=r"$\cos(t2)$", r=(-1, 1)),
    # cos_theta_12=dict(l=r"$\cos \theta_{12}$", r=(-1, 1)),
    cos_theta_1L=dict(l=r"$\cos \theta_{1L}$", r=(-1, 1)),
    tilt_1=dict(l=r"$tilt_{1}$", r=(0, np.pi)),
    theta_1L=dict(l=r"$\theta_{1L}$", r=(0, np.pi)),
    diff=dict(l=r"diff", r=(-np.pi, np.pi)),
)

CORNER_KWARGS = dict(
    smooth=0.9,
    label_kwargs=dict(fontsize=30),
    title_kwargs=dict(fontsize=16),
    truth_color='tab:orange',
    quantiles=[0.16, 0.84],
    levels=(1 - np.exp(-0.5), 1 - np.exp(-2), 1 - np.exp(-9 / 2.)),
    plot_density=False,
    plot_datapoints=False,
    fill_contours=True,
    max_n_ticks=3,
    verbose=False,
    use_math_text=True,
)

def add_agn_samples_to_df(df):
    df['s1x'], df['s1y'], df['s1z'] = df['spin_1x'], df['spin_1y'], df['spin_1z']
    df['s2x'], df['s2y'], df['s2z'] = df['spin_2x'], df['spin_2y'], df['spin_2z']
    df['s1_dot_s2'] = (df['s1x'] * df['s2x']) + (df['s1y'] * df['s2y']) + (df['s1z'] * df['s2z'])
    df['s1_mag'] = np.sqrt((df['s1x'] * df['s1x']) + (df['s1y'] * df['s1y']) + (df['s1z'] * df['s1z']))
    df['s2_mag'] = np.sqrt((df['s2x'] * df['s2x']) + (df['s2y'] * df['s2y']) + (df['s2z'] * df['s2z']))
    df['cos_theta_12'] = df['s1_dot_s2'] / (df['s1_mag'] * df['s2_mag'])
    # Lhat = [0, 0, 1]
    df['cos_theta_1L'] = df['s1z'] / (df['s1_mag'])
    print(df['cos_theta_1L'].describe())
    return df

def calculate_weight(df, sigma):
    mean = 1
    clip_a, clip_b = -1, 1
    a, b = (clip_a - mean) / sigma, (clip_b - mean) / sigma
    costheta_prior = scipy.stats.truncnorm(a=a, b=b, loc=mean, scale=sigma)
    df['weight'] = np.abs(np.exp(costheta_prior.logpdf(df['cos_theta_1L'])))
    df['weight'] = df['weight'] * np.abs(np.exp(costheta_prior.logpdf(df['cos_theta_12'])))
    return df

def process_res(r):
    params = list(PARAMS.keys())
    labels = [PARAMS[p]['l'] for p in params]
    range = [PARAMS[p]['r'] for p in params]

    label = os.path.basename(r).split("_")[0]
    df = pd.read_csv(r, " ")
    df = add_agn_samples_to_df(df)
    df['tilt1'], df['theta_1L'] = np.arccos(df['cos_tilt_1']), np.arccos(df['cos_theta_1L'])
    df['diff'] = df['tilt1'] - df['theta_1L']

    df = calculate_weight(df, sigma=0.5)
    kwargs = CORNER_KWARGS.copy()
    kwargs.update(labels=labels, range=range)

    fig = corner.corner(df[params], color=BILBY_BLUE_COLOR, **kwargs)

    #
    # dfnew = df.copy()
    # dfnew = dfnew.sample(
    #     frac=0.1,
    #     weights='weight',
    #     replace=True
    # )
    # normalising_weights_s2 = np.ones(len(dfnew)) * len(df) / len(dfnew)
    # fig = corner.corner(dfnew[params], color=VIOLET_COLOR, weights=normalising_weights_s2,  fig=fig, **kwargs)
    #
    # orig_line = mlines.Line2D([], [], color=BILBY_BLUE_COLOR, label="Original Posterior")
    # weighted_line = mlines.Line2D([], [], color=VIOLET_COLOR,label=r"Reweighted Posterior" )
    # plt.legend(handles=[orig_line, weighted_line], fontsize=25,
    #            frameon=False,
    #            bbox_to_anchor=(1, len(PARAMS)), loc="upper right")

    fig.suptitle(label, fontsize=24)
    fig.savefig(f"{label}.png")
    plt.close(fig)

def main():
    res = glob.glob(
        "../datafiles/samples/downsampled_posterior_samples_v1.0.0/*_samples.dat")
    for r in res:
        try:
            process_res(r)
            print(f"Processed {r}")
        except Exception:
            print(f"Skipping {r}")

if __name__ == '__main__':
    # main()
    process_res("../datafiles/samples/downsampled_posterior_samples_v1.0.0/GW150914_downsampled_posterior_samples.dat")


from __future__ import annotations
from typing import List, Tuple, Optional
import re
import os

from .basic import Unit
from .pattern import PatternLoader

class VplParser:
    @staticmethod
    def finish(text):
        return text if text.endswith("\n") else text + "\n"

    @staticmethod
    def unwrap(text):
        while text.endswith("\n"):
            text = text[:-1]
        if text.startswith("\"") and text.endswith("\""):
            text = text[1:-1]
        return VplParser.finish(text)

    @staticmethod
    class CaseData:
        def __init__(self, case="", inp="", outp="", grade: Optional[int] = None):
            self.case: str = case
            self.input: str = VplParser.finish(inp)
            self.output: str = VplParser.unwrap(VplParser.finish(outp))
            self.grade: Optional[int] = grade

        def __str__(self):
            return "case=" + self.case + '\n' \
                   + "input=" + self.input \
                   + "output=" + self.output \
                   + "gr=" + str(self.grade)

    regex_vpl_basic = r"case= *([ \S]*) *\n *input *=(.*?)^ *output *=(.*)"
    regex_vpl_extended = r"case= *([ \S]*) *\n *input *=(.*?)^ *output *=(.*?)^ *grade *reduction *= *(\S*)% *\n?"

    @staticmethod
    def filter_quotes(x):
        return x[1:-2] if x.startswith('"') else x

    @staticmethod
    def split_cases(text: str) -> List[str]:
        regex = r"^ *[Cc]ase *="
        subst = "case="
        text = re.sub(regex, subst, text, 0, re.MULTILINE | re.DOTALL)
        return ["case=" + t for t in text.split("case=")][1:]

    @staticmethod
    def extract_extended(text) -> Optional[CaseData]:
        f = re.match(VplParser.regex_vpl_extended, text, re.MULTILINE | re.DOTALL)
        if f is None:
            return None
        try:
            gr = int(f.group(4))
        except ValueError:
            gr = None
        return VplParser.CaseData(f.group(1), f.group(2), f.group(3), gr)

    @staticmethod
    def extract_basic(text) -> Optional[CaseData]:
        m = re.match(VplParser.regex_vpl_basic, text, re.MULTILINE | re.DOTALL)
        if m is None:
            return None
        return VplParser.CaseData(m.group(1), m.group(2), m.group(3), None)

    @staticmethod
    def parse_vpl(content: str) -> List[CaseData]:
        text_cases = VplParser.split_cases(content)
        seq: List[VplParser.CaseData] = []

        for text in text_cases:
            case = VplParser.extract_extended(text)
            if case is not None:
                seq.append(case)
                continue
            case = VplParser.extract_basic(text)
            if case is not None:
                seq.append(case)
                continue
            print("invalid case: " + text)
            exit(1)
        return seq

    @staticmethod
    def to_vpl(unit: CaseData):
        text = "case=" + unit.case + "\n"
        text += "input=" + unit.input
        text += "output=\"" + unit.output + "\"\n"
        if unit.grade is not None:
            text += "grade reduction=" + str(unit.grade) + "%\n"
        return text

class Loader:
    regex_tio = r"^ *>>>>>>>> *(.*?)\n(.*?)^ *======== *\n(.*?)^ *<<<<<<<< *\n?"

    def __init__(self):
        pass

    @staticmethod
    def parse_cio(text, source, crude_mode=False):
        unit_list = []
        text = "\n" + text

        for test_case in text.split("\n#__case")[1:]:
            unit = Unit()
            unit.source = source
            unit.output = test_case
            unit_list.append(unit)

        for unit in unit_list:
            test = unit.output
            if "\n$end" in test:
                test = test.split("\n$end")[0] + "\n$end"

            lines = test.split("\n")
            tags = lines[0].strip().split(" ")
            if tags[-1].endswith("%"):
                unit.grade = int(tags[-1][0:-1])
                del tags[-1]
            else:
                unit.grade = None
            unit.case = " ".join(tags)
            unit.output = "\n".join(lines[1:])

        # concatenando testes contínuos
        for i in range(len(unit_list)):
            unit = unit_list[i]
            if "\n$end" not in unit.output and (i < len(unit_list) - 1):
                unit_list[i + 1].output = unit.output + '\n' + unit_list[i + 1].output
                unit.output = unit.output + "\n$end\n"

        for unit in unit_list:
            lines = unit.output.split('\n')
            unit.output = ""
            unit.input = ""
            # filtrando linhas vazias e comentários
            for line in lines:
                if crude_mode:  #
                    unit.output += line + '\n'
                    if line == "" or line.startswith("$") or line.startswith("#"):
                        unit.input += line + '\n'
                else:
                    if line != "" and not line.startswith("#"):
                        unit.output += line + '\n'
                        if line.startswith("$"):
                            unit.input += line[1:] + '\n'
        for unit in unit_list:
            unit.fromCio = True

        return unit_list

    @staticmethod
    def parse_tio(text: str, source: str = "") -> List[Unit]:

        # identifica se tem grade e retorna case name e grade
        def parse_case_grade(value: str) -> Tuple[str, Optional[int]]:
            if value.endswith("%"):
                words = value.split(" ")
                last = value.split(" ")[-1]
                _case = " ".join(words[:-1])
                grade_str = last[:-1]           # ultima palavra sem %
                try:
                    _grade = int(grade_str)
                    return _case, _grade
                except ValueError:
                    pass
            return value, None

        matches = re.findall(Loader.regex_tio, text, re.MULTILINE | re.DOTALL)
        unit_list = []
        for m in matches:
            case, grade = parse_case_grade(m[0])
            unit_list.append(Unit(case, m[1], m[2], grade, source))
        return unit_list

    @staticmethod
    def parse_vpl(text: str, source: str = "") -> List[Unit]:
        data_list = VplParser.parse_vpl(text)
        output: List[Unit] = []
        for m in data_list:
            output.append(Unit(m.case, m.input, m.output, m.grade, source))
        return output

    @staticmethod
    def parse_dir(folder) -> List[Unit]:
        pattern_loader = PatternLoader()
        files = sorted(os.listdir(folder))
        matches = pattern_loader.get_file_sources(files)

        unit_list: List[Unit] = []
        try:
            for m in matches:
                unit = Unit()
                unit.source = os.path.join(folder, m.label)
                unit.grade = 100
                with open(os.path.join(folder, m.input_file)) as f:
                    value = f.read()
                    unit.input = value + ("" if value.endswith("\n") else "\n")
                with open(os.path.join(folder, m.output_file)) as f:
                    value = f.read()
                    unit.output = value + ("" if value.endswith("\n") else "\n")
                unit_list.append(unit)
        except FileNotFoundError as e:
            print(str(e))
        return unit_list

    @staticmethod
    def parse_source(source: str) -> List[Unit]:
        if os.path.isdir(source):
            return Loader.parse_dir(source)
        if os.path.isfile(source):
            #  if PreScript.exists():
            #      source = PreScript.process_source(source)
            with open(source) as f:
                content = f.read()
            if source.endswith(".vpl"):
                return Loader.parse_vpl(content, source)
            elif source.endswith(".tio"):
                return Loader.parse_tio(content, source)
            elif source.endswith(".md"):
                tests = Loader.parse_tio(content, source)
                tests += Loader.parse_cio(content, source)
                return tests
            else:
                print("warning: target format do not supported: " + source)  # make this a raise
        else:
            raise FileNotFoundError('warning: unable to find: ' + source)
        return []


import requests
from bs4 import BeautifulSoup
import os
#os.chdir('~/crawl')

from selenium import webdriver
from selenium.webdriver import FirefoxOptions
from selenium.webdriver.common.by import By
opts = FirefoxOptions()
opts.add_argument("--headless")
browser = webdriver.Firefox(firefox_options=opts)
#browser = webdriver.Firefox()
browser.get(("https://investment.credit-suisse.com/Search/Start?start=1&PageContext=ArticleSearch"))
html_source = browser.page_source

browser.find_element_by_xpath("//select[@id='DomicilePoolpartyConceptId']/option[@value='http://poolpartyw.csintra.net/SolutionNetThesaurus/Switzerland']").click()
browser.find_element_by_xpath("//select[@id='UiLanguagePoolpartyConceptId']/option[@value='http://poolpartyw.csintra.net/SolutionNetThesaurus/English']").click()
browser.find_element_by_id('loginButton').click()

globalCount = 0
count = 0
url = browser.current_url

current = url

while True:
    print(browser.current_url)
    links = []
    sources = []
    for url in browser.find_elements_by_xpath('//a[starts-with(@href, "/Article")]'):
        article = url.get_attribute('href')
        links.append(article)
    for url in links:
        browser.get(url)
        print(browser.current_url)
        content = browser.page_source
        sources.append(content)
        text_file = open(os.path.join("~/crawl/rawDat",str(globalCount)+"_Output.txt"), "w")
        text_file.write(content)
        text_file.close()
        print(globalCount)
        globalCount = globalCount + 1
    browser.get(current)
    count = count + 25
    current = 'https://investment.credit-suisse.com/Search/Start?start=%s&PageContext=ArticleSearch' % (count)


'''
Access Point Test

Copyright (c) 2009 Jouni Miettunen
http://jouni.miettunen.googlepages.com/

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

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

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

1.00 2009-03-19 Initial release
     Based on Forum Nokia wiki samples
     Based on experiments done with not-yet-released app

Coding music by Parov Stelar:
- Libella Swing
- Flame of Fame
'''

import e32
import appuifw

# Warning: it takes a long time to import these two!
import socket
import urllib

VERSION = u"1.00"

# Global variables
g_apid = 0
g_text = None

def show_text(a_text=""):
    ''' Put some text on-screen '''
    g_text.clear()
    if a_text:
        g_text.add(unicode(a_text))
    else:
        g_text.add(u"Testing (default) Access Point." +\
            u"Check Options menu for operations.\n\n" +\
            u"Enjoy,\n\n--jouni")

def select_ap(a_id=0):
    ''' Select temporary default access point '''
    if a_id:
        apid = a_id
    else:
        apid = socket.select_access_point()

    # zero is not a valid AP number
    if apid:
        apo = socket.access_point(apid)
        socket.set_default_access_point(apo)
        return apo
    else:
        return None

def menu_fetch_url(a_url="", a_ap=0):
    ''' Fetch given URL using given access point '''
    # Tell user something is happening
    show_text("Trying to fetch:\n\n" + a_url)
    # Show user something is happening
    e32.ao_yield()

    # Set access point
    # Note that id is used only to find access point
    apo = select_ap(a_ap)
    if not apo:
        appuifw.note(u"Cancelled!")
        show_text()
        return

    if a_url:
        f = urllib.urlopen(a_url)
        d = f.read()
        f.close()
        apo.stop()
        show_text(d)
    else:
        appuifw.note(u"Missing URL!")

def menu_default_ap():
    ''' Ask user to select default access point '''
    global g_apid
    g_apid = socket.select_access_point()

def menu_clear_ap():
    ''' Forget default access point selection '''
    global g_apid
    g_apid = 0

def menu_about():
    ''' Callback for menu item About '''
    appuifw.note(u'Access Point Test v'+VERSION+'\n'+\
        u'jouni.miettunen.googlepages.com\n\u00a92009 Jouni Miettunen')

def cb_quit():
    ''' Clean-up before application exit '''
    app_lock.signal()

# Initialize application
appuifw.app.orientation = 'portrait'
appuifw.app.title = u'Test AP'
appuifw.app.exit_key_handler = cb_quit
appuifw.app.menu = [
    (u"Fetch google.com", lambda:menu_fetch_url("http://www.google.com/webhp", g_apid)),
    (u"Access point", (
        (u"Set default AP", menu_default_ap),
        (u"Clear default AP", menu_clear_ap))),
    (u"About", menu_about),
    (u"Exit", cb_quit)]

# Initialize application UI
g_text = appuifw.Text()
appuifw.app.body = g_text
show_text()

# Wait for user to do anything
app_lock = e32.Ao_lock()
app_lock.wait()


# -*- coding: utf-8 -*-
"""
Created on Mon Sep  6 22:36:08 2021

@author: user
"""

import random
import numpy as np

def medir_temp(n):

    mu = 0
    sigma = 0.2
    temp_normal = 37.5

    mediciones = []
    for i in range(n):
        mediciones.append(temp_normal + random.normalvariate(mu,sigma))

    arr = np.array(mediciones)

    np.save('../Data/temperaturas',arr)
    return mediciones

def resumen_temp(n):
    mediciones = medir_temp(n)

    valor_maximo = max(mediciones)
    valor_minimo = min(mediciones)
    promedio = sum(mediciones)/n

    if n % 2 == 0: #si es par
        var1 = mediciones[int(n/2)]
        var2 = mediciones[int(n/2 + 1)]
        mediana = (var1 + var2) / 2
    if n % 2 == 1: # si es impar
        mediciones.sort()
        ordenadas = mediciones
        mediana = ordenadas[int(n/2 + 0.5)]

    return valor_maximo, valor_minimo, promedio, mediana

if __name__ == '__main__':
    mediciones = medir_temp(99)
    medidas = resumen_temp(99)


import multiprocessing as mp
from parallel_data_processing.parallel_join.hash_join import hash_join
def range_partition(data, range_indices):

    result = []

    new_data = data[:]
    new_data=sorted(new_data,key=lambda new_data:new_data[1])

    # Calculate the number of bins
    range_index = len(range_indices)

    # For each bin, perform the following
    for i in range(range_index):
        # Find elements to be belonging to each range
        lower_part = [x for x in new_data if x[1] < range_indices[i]]
        # Add the partitioned list to the result
        result.append(lower_part)
        # Find the last element in the previous partition
        last_element = lower_part[-1]
        # Find the index of of the last element
        last = new_data.index(last_element)
        # Remove the partitioned list from the dataset
        new_data = new_data[last + 1:]

    #append the remeaning list
    result.append(new_data)

    return result

def disjoint_join(table_1, table_2, processor_num):

    result = []

    ### START CODE HERE ###

    # --- Implement the algorithm

    # Partition T1 & T2 into sub-tables using range_partition().
    partition_result_1=range_partition(table_1,[10,20])
    partition_result_2=range_partition(table_2,[10,20])
    data_size=len(partition_result_1)
    assert (data_size==processor_num), "The number of the sub-tables must be the equal to the n_processor"
    pool = mp.Pool(processes=processor_num)

    parallel_result=[pool.apply_async(hash_join,[partition_result_1[index],partition_result_2[index]])
                     for index in range(data_size)]

    for processor in parallel_result:
        output=processor.get()
        result.append(output)

    ### END CODE HERE ###

    return result

if __name__ == '__main__':
    table_r = [('Adele', 8), ('Bob', 22), ('Clement', 16), ('Dave', 23), ('Ed', 11),
               ('Fung', 25), ('Goel', 3), ('Harry', 17), ('Irene', 14), ('Joanna', 2),
               ('Kelly', 6), ('Lim', 20), ('Meng', 1), ('Noor', 5), ('Omar', 19)]

    table_s = [('Arts', 8), ('Business', 15), ('CompSc', 2), ('Dance', 12), ('Engineering', 7),
               ('Finance', 21), ('Geology', 10), ('Health', 11), ('IT', 18)]

    print(disjoint_join(table_r,table_s,3))


#!/usr/bin/env python3
"""
module
"""
import tensorflow as tf
sdp_attention = __import__('5-sdp_attention').sdp_attention

class MultiHeadAttention(tf.keras.layers.Layer):
    """
    multiheadattention
    """
    def __init__(self, dm, h):
        """ init """
        if type(dm) is not int:
            raise TypeError(
                "dm must be int representing dimensionality of model")
        if type(h) is not int:
            raise TypeError(
                "h must be int representing number of heads")
        super(MultiHeadAttention, self).__init__()
        self.h = h
        self.dm = dm
        self.depth = dm // h
        self.Wq = tf.keras.layers.Dense(units=dm)
        self.Wk = tf.keras.layers.Dense(units=dm)
        self.Wv = tf.keras.layers.Dense(units=dm)
        self.linear = tf.keras.layers.Dense(units=dm)

    def split_heads(self, x, batch):
        """
        Split heads
        """
        x = tf.reshape(x, (batch, -1, self.h, self.depth))
        x = tf.transpose(x, perm=[0, 2, 1, 3])
        return x

    def call(self, Q, K, V, mask):
        """ call """
        # batch = Q.get_shape().as_list()[0]
        batch = tf.shape(Q)[0]

        q = self.Wq(Q)
        k = self.Wk(K)
        v = self.Wv(V)

        q = self.split_heads(q, batch)
        k = self.split_heads(k, batch)
        v = self.split_heads(v, batch)

        attention, weights = sdp_attention(q, k, v, mask)

        attention = tf.transpose(attention, perm=[0, 2, 1, 3])
        concat_attention = tf.reshape(attention, (batch, -1, self.dm))
        outputs = self.linear(concat_attention)

        return outputs, weights


from datetime import datetime, timedelta
import requests
import json
import eel

@eel.expose
def ten_newest_question(tag):
    url = "http://api.stackexchange.com/2.2/search?order=desc&sort=creation&tagged=" + tag + \
          "&site=stackoverflow&filter=withbody&pagesize=10"
    data = requests.get(url).json()

    with open('./nginx-1.17.8/html/demo/json/ten_newest_question.json', 'w') as f:
        json.dump(data, f)

@eel.expose
def ten_voted_question(tag):
    last_week = datetime.today() - timedelta(days=7)
    url = "http://api.stackexchange.com/2.2/search?order=desc&sort=votes&tagged=" + tag + \
          "&site=stackoverflow&filter=withbody&pagesize=10&fromdate="+str(int(last_week.timestamp()))
    data = requests.get(url).json()

    with open('./nginx-1.17.8/html/demo/json/ten_voted_question.json', 'w') as f:
        json.dump(data, f)

eel.init('nginx-1.17.8')
eel.start('html/demo/index.html')