diff --git "a/1477.jsonl" "b/1477.jsonl" new file mode 100644--- /dev/null +++ "b/1477.jsonl" @@ -0,0 +1,757 @@ +{"seq_id":"79128817","text":"'''\nThis script is called automatically by the tic tac toe program, after completing\nall required runs on a particular algorithm. Keep in mind that it does not know which\nalgorithm's results are being plotted!!!\nTo generate a graph with the right label, the algorithmName needs to be substituted for\nthe name of the algorithm that you are planning on getting results from.\nThis is designed to print 1000 runs of a single code execution and not the average of many.\n'''\nimport matplotlib.pyplot as plt\n\nX, Y = [], []\nx_val = 0\n#for line in open(\"spinup/algos/pytorch/ppo/rewards_two_nets.txt\", 'r'):\n#for line in open(\"spinup/algos/pytorch/ppo/rewards.txt\", 'r'):\nfor line in open(\"spinup/algos/pytorch/ppo/ppg_64.txt\", 'r'):\n#for line in open(\"algos/pytorch/ppo/original_ppg.txt\", 'r'):\n values = [s for s in line.split()]\n #x_val+=float(values[1])\n X.append(float(values[1]))\n Y.append(float(values[3]))\n\nplt.title(\"True reward received per episode\") \nplt.xlabel('Episodes')\nplt.ylabel('True reward')\n\nplt.plot(X, Y, c='r', label='True reward')\n\nplt.legend()\n\nplt.show()\n","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"67043685","text":"from Statistics.PopulationMean import population_mean\nfrom Calculators.Subtraction import subtraction\nfrom Calculators.Squaring import square\nfrom Calculators.Division import division\n\n\ndef population_variance(data):\n data = [num for elem in data for num in elem]\n new_data = [float(x) for x in data]\n u = population_mean(new_data)\n deviations = subtraction(new_data, u)\n sq_deviations = square(deviations)\n x = len(new_data)\n y = sum(sq_deviations)\n d = division(x, y)\n return d\n","sub_path":"Statistics/PopulationVariance.py","file_name":"PopulationVariance.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"434406784","text":"\"\"\"empty message\n\nRevision ID: dd349380cb93\nRevises: \nCreate Date: 2021-03-20 18:14:29.647344\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'dd349380cb93'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('activity',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('pet_id', sa.Integer(), nullable=True),\n sa.Column('activity_type', sa.String(), nullable=True),\n sa.Column('time', sa.Time(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('owner',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('phone', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('pet',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('owner_id', sa.Integer(), nullable=True),\n sa.Column('nickname', sa.String(), nullable=True),\n sa.Column('room_number', sa.Integer(), nullable=True),\n sa.Column('check_in_date', sa.Date(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('pet')\n op.drop_table('owner')\n op.drop_table('activity')\n # ### end Alembic commands ###\n","sub_path":"homework/pet_hotel_hw/migrations/versions/dd349380cb93_.py","file_name":"dd349380cb93_.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"650301596","text":"def read_matrix():\n row_index, column_index = map(int, input().split())\n matrix = []\n for r in range(row_index):\n row = input().split()\n matrix.append(row)\n return matrix\n\n\ndef swap_command(indices, matrix):\n row_one, col_one, row_two, col_two = indices\n matrix[row_one][col_one], matrix[row_two][col_two] = matrix[row_two][col_two], matrix[row_one][col_one]\n for r in range(len(matrix)):\n print(' '.join(str(el) for el in matrix[r]))\n\n\ndef input_validator(data, matrix):\n command = data.split()[0]\n if not command == \"swap\":\n return False\n coordinates = data.split()[1:]\n if not len(coordinates) == 4:\n return False\n coordinates = [int(x) for x in coordinates]\n first_row, first_column, second_row, second_column = coordinates\n if not (0 <= first_row < len(matrix) and 0 <= second_row < len(matrix) and 0 <= first_column < len(\n matrix[0]) and 0 <= second_column < len(matrix[0])):\n return False\n else:\n return coordinates\n\n\nmatrix = read_matrix()\n\nEND_COMMAND = \"END\"\n\nwhile True:\n data = input()\n if data == END_COMMAND:\n break\n is_valid_input = input_validator(data, matrix)\n if is_valid_input:\n swap_command(is_valid_input, matrix)\n else:\n print(\"Invalid input!\")\n continue\n","sub_path":"multidimensional_lists_exercise/matrix_shuffling.py","file_name":"matrix_shuffling.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"283098688","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PyQt4 import QtCore, QtGui\n\nclass NodeWindow(QtGui.QDialog):\n \"\"\"docstring for NodeWindow\"\"\"\n def __init__(self):\n super(NodeWindow, self).__init__()\n self.resize(300, 200)\n self.setUnifiedTitleAndToolBarOnMac(True)\n","sub_path":"src/ui/nodeWindow.py","file_name":"nodeWindow.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"54748398","text":"\n\nclass Combat:\n\n def __init__(self, event_queue, entity_manager):\n self.event_queue = event_queue\n self.entities = []\n self.event_queue.register(self)\n self.entity_manager = entity_manager\n\n def is_alive(self, hp_component):\n if hp_component.hp > 0:\n return True\n else:\n return False\n\n def take_damage(self, target, damage, attacker):\n target_component = self.entity_manager.get_component(attacker, \"fighter\")\n target_component.hp -= damage\n target_name = self.entity_manager.get_component(target, \"name\")._name\n self.event_queue.queue.append({\"message\":\"{} suffers {} damage!\".format(target_name, damage)})\n\n if not self.is_alive(target_component):\n self.event_queue.queue.insert(0, {\"dead\":(target, attacker)})\n attacker_name = self.entity_manager.get_component(attacker, \"name\")._name\n self.event_queue.queue.append({\"message\":\"{} slays {}!\".format(attacker_name, target_name)})\n\n def attack(self, attacker, target):\n attacker_name = self.entity_manager.get_component(attacker, \"name\")._name\n target_name = self.entity_manager.get_component(attacker, \"name\")._name\n self.event_queue.queue.append({\"message\":\"{} strikes {}!\".format(attacker_name, target_name)})\n damage = 20\n self.event_queue.queue.insert(0, {\"damage\":(target, damage, attacker)})\n\n def receive_event(self, action):\n if action.keys()[0] == \"attack\":\n self.attack(action.get(\"attack\")[0], action.get(\"attack\")[1])\n elif action.keys()[0] == \"damage\":\n self.take_damage(action.get(\"damage\")[0], action.get(\"damage\")[1], action.get(\"damage\")[2])\n","sub_path":"combat.py","file_name":"combat.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"485252067","text":"from flask import Flask, render_template, request\r\nfeature_set = ['amusement_park', 'atm', 'bank', 'bar', 'bus_station', 'cafe', 'department_store', 'gym', 'hospital', 'library',\r\n 'night_club', 'park', 'pharmacy', 'police', 'school', 'shopping_mall', 'supermarket', 'train_station']\r\nfeature_set_ratings = []\r\nglobal_average = 0\r\n\r\n\r\ndef processGooglePlacesData():\r\n import pandas\r\n import numpy\r\n import sys\r\n import numpy\r\n\r\n for place_type in feature_set:\r\n dataset = pandas.read_excel(\r\n \"./datasets/GooglePlacesAPI/\"+place_type+\"_dataset.xls\",)\r\n ratings = numpy.array(dataset.iloc[:, [1]])\r\n mean_rating = 0\r\n ratings_count = 0\r\n for rating in ratings:\r\n if rating > 0.0:\r\n mean_rating = mean_rating + rating\r\n ratings_count = ratings_count + 1\r\n\r\n '''if ratings_count == 0:\r\n mean_rating = 0\r\n else:\r\n mean_rating = mean_rating / ratings_count'''\r\n\r\n mean_rating = mean_rating / ratings.__len__()\r\n feature_set_ratings.append(mean_rating*20)\r\n\r\n print(\"
\" + place_type + \": \" + str(mean_rating*20) + \", \" + str(ratings.__len__()) + \" records fetched.\")\r\n\r\n average = 0\r\n for i in feature_set_ratings:\r\n average = average + i\r\n global global_average \r\n global_average = average / feature_set_ratings.__len__()\r\n\r\nprocessGooglePlacesData()\r\n\r\n\r\n\r\n#Web Rendering\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/analyse', methods=['POST', 'GET'])\r\ndef analyse():\r\n processGooglePlacesData()\r\n return render_template('analyse.html', result=request.form, ratings=feature_set_ratings, global_average=global_average)\r\n\r\n@app.route('/result')\r\ndef result():\r\n return render_template('result.html', ratings=feature_set_ratings, global_average=global_average)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n\r\n","sub_path":"LivabilityAnalysis/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"164098669","text":"\n\nnew_path = 'LaTex2e_files/variables_amp.tex'\nnew_vars = open(new_path,'w', encoding='utf-8')\n\n\nstr0 = 'N0' + input('Enter Necro_ID: ')\nstr00 = str0\nprint ('%variables para la ampliatoria ', str0)\nvalue = '%variables para la ampliatoria '+ str0\nnew_vars.write(value +'\\n\\n') \n\nnew_vars.write('%variables de la identificación del asunto\\n\\n')\nstr = input('Enter num Juzgado: ')\nnew_vars.write('\\\\def' + '\\\\numj{' + str +'}\\n')\n\nstr = input('Enter Juzgado: ');\nnew_vars.write('\\\\def' + '\\\\juzgado{' + str +'}\\n')\n\nstr = 'DP: ' + input('Enter DP: ');\nnew_vars.write('\\\\def' + '\\\\asunto{' + str +'}\\n')\n\n#str = input('Enter Necro_ID: ');\nnew_vars.write('\\\\def' + '\\\\necro{' + str00 +'}\\n')\n\nstr = input('Enter Fecha necro (yyyy-mm-dd): ');\nnew_vars.write('\\\\def' + '\\\\fechnecro{' + str +'}\\n\\n\\n')\n\n##ampliatoria firmada por 2\nstr = input('Firmas tú sólo? (1/0)')\nif str == 0:\n ayte = input('Nombre del segundo firmante. ')\n##por terminar de implementar (18/11/17)\n\n\n#%variables de la relación facultativa\n\nnew_vars.write('%variables de la relación facultativa\\n')\n\nstr = input('Enter Corpse: ');\nnew_vars.write('\\\\def' + '\\\\corpse{' + str +'}\\n')\n\n#%variables del dictamen\n\nstr = int(input('Enter INT Services: (1=Q, 2=H, 3=QH, 4=B, 5=QB, 6=HB, 7=QHB)'));\nif str == 1 :\n\tnew_vars.write('\\\\def' + '\\\\servINT{al Servicio de Química}\\n\\n\\n')\nelif str == 2:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{al Servicio de Histopatología}\\n\\n\\n')\nelif str == 3:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{a los Servicios de Química y de Histopatología}\\n\\n\\n')\nelif str == 4:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{ al Servicio de Biología}\\n\\n\\n')\nelif str == 5:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{ a los Servicios de Química y de Biología}\\n\\n\\n')\nelif str == 6:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{ a los Servicios de Histopatología y de Biología}\\n\\n\\n')\nelif str == 7:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{ a los Servicios de Química, Histopatología y Biología}\\n\\n\\n')\nelse:\n\t\tnew_vars.write('\\\\def' + '\\\\servINT{al Servicio de Química}\\n\\n\\n')\n\t\t\n\n#%variables del dictamen\n\nnew_vars.write('%variables del Dictamen\\n')\n\nstr = input('Enter Dictamen ID: (Sxx-yyyyy)');\nnew_vars.write('\\\\def' + '\\\\dictamen{' + str +'}\\n')\n\n\n#%variables de las consideraciones mf\n\nnew_vars.write('%variables de las consideraciones mf\\n')\n\nask = int(input('hay toxicología? (0/1)'))\nstr000 = 'En el citado Dictamen se informa de que en los estudios toxicológicos realizados '\nif ask == 1:\n\task = int(input('hay substancias? (0/1)'))\n\tif ask == 0:\n\t\tstr000 = str000 + 'no se ha detectado la presencia de ninguna substancia tóxica o estupefaciente.'\n\t\tnew_vars.write('\\\\def' + '\\\\sust_toxi{' + str000 +'}\\n')\n\telse:\n\t\tstr000 = str000 + 'se ha detectado la presencia de '\n\t\tstr = input('Enter tóxicos hallados: ')\n\t\tnew_vars.write('\\\\def' + '\\\\sust_toxi{' + str000 + str +'}\\n')\nelse:\n\tnew_vars.write('\\\\def' + '\\\\sust_toxi{}\\n')\n\nask = int(input('hay Histopatología ? (0/1)'))\nif ask == 1:\n\tstr = 'El estudio histopatológico pone de manifiesto la presencia de '\n\task = (input('Resumen histopat:'))\n\tnew_vars.write('\\\\def' + '\\\\res_histopat{' + str + ask + ' como sus hallazgos más significativos.' +'}\\par\\n')\nelse:\n\tnew_vars.write('\\\\def' + '\\\\res_histopat{}\\n')\n\nask = int(input('hay Biología ? (0/1)'))\nif ask == 1:\n\tstr = 'El estudio biológico de las muestras remitidas concluye que '\n\task = (input('Resumen biológico:'))\n\tnew_vars.write('\\\\def' + '\\\\resbiolo{' + str + ask +'}\\par\\n')\nelse:\n\tnew_vars.write('\\\\def' + '\\\\resbiolo{}\\n')\n\nstr_date = input('Enter Fecha informe autopsia (yyyy-mm-dd): ');\nnew_vars.write('\\\\def' + '\\\\fechainfo{' + str_date +'}\\n')\n\nstr000 = ''\nstr001 = ''\n\ncong = int(input('Es el Dictamen congruente con la Autopsia? (1/0)'))\nif cong == 1:\n\tstr000 = 'Los resultados del Dictamen resultan, por tanto, congruentes con las conclusiones provisionales alcanzadas en el Informe Forense de Autopsia emitido el '\n\tstr001 = 'De todo lo anteriormente expuesto se concluye que: '\n\t\nelse:\n\tstr000 = 'Por consiguiente, los nuevos resultados aportados en el Dictamen amplían y modifican las conclusiones alcanzadas en el Informe Forense de Autopsia emitido el '\n\tstr001 = 'De todo lo anteriormente expuesto se concluye que: '\nnew_vars.write('\\\\def' + '\\\\consida{'+ str000 +'}\\n')\nnew_vars.write('\\\\def' + '\\\\considb{'+ str001 +'}\\n')\n\n\n#variables de la etiologia ML\nnew_vars.write('%variables de la etiologia ML \\n')\n\n#%variables de la etiologia\n\n\nstr = input('Tipo de muerte: ');\nnew_vars.write('\\\\def' + '\\\\tip_muerte{' + str +'}\\n')\n\nstr = input('Causa fundamental: ');\nnew_vars.write('\\\\def' + '\\\\etiol_muerte{' + str +'}\\n')\n\nstr = input('Contexto: ');\nnew_vars.write('\\\\def' + '\\\\contexto_etiol{' + str +'}\\n')\n\nstr = input('Hora de la muerte: ');\nnew_vars.write('\\\\def' + '\\\\hora_muerte{' + str +'}\\n')\n\nstr = input('Fecha de la muerte: ');\nnew_vars.write('\\\\def' + '\\\\fecha_muerte{' + str +'}\\n')\n\nprint('fin de la inicialización de variables')\n\nnew_vars.close()\n","sub_path":"prLaTex2e-Ampliatorias/fill_vars_amp.py","file_name":"fill_vars_amp.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"223820073","text":"from os.path import (\n abspath,\n dirname,\n join,\n)\n\nimport pytest\n\nfrom mimesis import settings\nfrom mimesis.exceptions import UndefinedSchema\nfrom mimesis.schema import Schema\n\nPATH = abspath(join(dirname(__file__), 'data_fixtures'))\n\n\n@pytest.fixture(params=settings.LIST_OF_LOCALES)\ndef schema(request):\n return Schema(request.param)\n\n\n@pytest.fixture\ndef valid_schema():\n return dict(\n id='cryptographic.uuid',\n name='text.word',\n version='development.version',\n owner=dict(\n email='personal.email',\n token='cryptographic.token',\n creator='personal.full_name'),\n sites=[{'home_page': 'internet.home_page'}],\n )\n\n\n@pytest.fixture\ndef invalid_schema():\n return dict(\n id='none.none',\n name='text.none',\n version='development.none',\n owner=dict(\n email='personal.none',\n token='cryptographic.none',\n creator='personal.none',\n ),\n sites=[{'home_page': 'internet.home_page'}],\n )\n\n\ndef test_valid_schema(schema, valid_schema):\n result = schema.load(schema=valid_schema).create(iterations=1)\n assert isinstance(result, dict) # check type_to decorator\n\n result_2 = schema.load(schema=valid_schema).create(iterations=10)\n\n assert isinstance(result_2, list)\n assert len(result_2) == 10\n\n\ndef test_invalid_schema(schema, invalid_schema):\n with pytest.raises(AttributeError):\n schema.load(schema=invalid_schema).create()\n\n\ndef test_load_schema_by_path(schema):\n valid_path = PATH + '/schema.json'\n result = schema.load(path=valid_path)\n assert isinstance(result.schema, dict)\n\n\ndef test_load_invalid_schema(schema):\n invalid_json_file = PATH + '/invalid_schema.json'\n with pytest.raises(ValueError):\n schema.load(path=invalid_json_file)\n\n\ndef test_load_schema_by_invalid_path(schema):\n invalid_path = PATH + '/schema.j'\n\n with pytest.raises(FileNotFoundError):\n schema.load(path=invalid_path)\n\n\ndef test_undefined_schema(schema):\n with pytest.raises(UndefinedSchema):\n schema.create()\n","sub_path":"tests/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"592243460","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 18 00:05:13 2019\r\n\r\n@author: Tony\r\n\"\"\"\r\n\r\nfrom keras.models import load_model\r\n\r\nimport numpy as np\r\nimport cv2\r\nimport os\r\n\r\nimport time\r\n\r\nmodel = load_model('./WeightVGG.h5')\r\nPath = './Tmp/'\r\n# Picture Path\r\nSemaphore = 0\r\n# Empty: 0, NotEmpty: 1\r\nPredictList = list()\r\n# Picture Filename\r\n\r\ndef Predict():\r\n global Path\r\n global Semaphore\r\n global PredictList\r\n \r\n while True:\r\n while Semaphore == 0:\r\n filename = os.listdir(Path)\r\n if len(filename) == 0:\r\n time.sleep(1)\r\n else:\r\n PredictList = filename\r\n Semaphore += 1\r\n\r\n if Semaphore == 1:\r\n for i in range(len(PredictList)):\r\n img = cv2.imread(Path + PredictList[i])[:, :, ::-1]\r\n x = np.array([cv2.resize(img, (224, 224))])\r\n y = model.predict(x)\r\n y = np.argmax(y)\r\n if y == 0:\r\n species = 'cat'\r\n else:\r\n species = 'dog'\r\n with open('./Result/' + PredictList[i][0: -4] + '.txt', 'w') as f:\r\n f.write(species)\r\n os.remove('./Tmp/' + PredictList[i])\r\n PredictList.clear()\r\n Semaphore -= 1\r\n \r\nPredict()\r\n ","sub_path":"PredictionServer.py","file_name":"PredictionServer.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"13385154","text":"# automaton class for experiment 2\n# increase sensing sectors to 4, pulling and pushing in alternative order\n\nfrom math import *\nfrom utilities import reset_radian\n\nclass Automaton:\n def __init__(self, pos, vel, ori, radius, alpha):\n self.pos = list(pos) # pos[0] for x, pos[1] for y, convert to list\n self.vel = vel # signed scalar\n self.ori = ori # global orientation of positive moving axis\n self.radius = radius # radius of circle for sensing range\n # alpha is relative angle of moving direction to dividing direction\n self.alpha = alpha # should not be changed during the life of the automaton\n self.neighbor_detected = False # boolean to indicate if there is neighbor in range\n self.fb_vector = [0, 0] # feedback vector as acceleration\n self.fb_mag_coef = 5.0\n self.accel_t = 0.0 # tangential acceleration, can be negative\n self.accel_r = 0.0 # centripetal acceleration, can be negative\n self.accel_ori = 0.0 # relative orientation of acceleration\n def reset_detection(self):\n # reset feedback vector and detection flag\n self.fb_vector = [0, 0]\n self.neighbor_detected = False\n def check_neighbor(self, pos):\n # input position of the automaton to be compared with\n # accumulate changes on the feedback vector\n dist_temp = hypot(pos[0]-self.pos[0], pos[1]-self.pos[1])\n if dist_temp < self.radius: # input automaton inside sensing circle\n if (not self.neighbor_detected):\n self.neighbor_detected = True # set detection flag\n # 1.calculate feedback based on distance\n # proportional to how close the neighbor to the automaton\n fb_magnitude = (self.radius - dist_temp) * self.fb_mag_coef\n # 2.also change magnitude of feedback according to beta\n # theta_fb is the absolute direction of feedback vector\n theta_fb = atan2(pos[1]-self.pos[1], pos[0]-self.pos[0])\n # beta is angle of feedback vector to positive dividing direction\n beta = reset_radian(theta_fb - self.ori + self.alpha)\n # beta_coef is to be applied to fb_magnitude, in [-1, 1]\n # (0, pi/2) pulling sector\n # (pi/2, pi) pushing sector\n # (pi, 3*pi/2) pulling sector\n # (3*pi/2, 2*pi) pushing sector\n beta_coef = sin(beta*2) # it happens to be a sin() function\n # apply beta_coef to the feedback magnetitude, make it signed\n fb_magnitude = fb_magnitude * beta_coef\n # 3.add feedback as acceleration from input automaton\n self.fb_vector[0] = self.fb_vector[0] + cos(theta_fb)*fb_magnitude\n self.fb_vector[1] = self.fb_vector[1] + sin(theta_fb)*fb_magnitude\n def calculate_accel(self):\n # calculate both tangential and centripetal acceleration\n # based on accumulated feedback vector from all in-range neighbors\n accel_magnitude = hypot(self.fb_vector[0], self.fb_vector[1])\n # relative orientation to the positive moving direction\n self.accel_ori = reset_radian(atan2(self.fb_vector[1], self.fb_vector[0]) - self.ori)\n # tangiential and centripetal acceleration\n self.accel_t = accel_magnitude * cos(self.accel_ori)\n self.accel_r = accel_magnitude * sin(self.accel_ori)\n def update_with_accel(self, delta_t): # update with calculated acceleration\n # update position, velocity, and orientation\n vel_new = self.vel + self.accel_t * delta_t\n # ori_delta is the change in orientation, counter-clockwise is positive\n if self.vel == 0: # no change in orientation if no speed\n ori_delta = 0\n else:\n # velocity is signed; should not reset this radian angle ori_delta\n ori_delta = self.accel_r*delta_t/self.vel\n # should avoid overshooting of rotating angle, choosing smaller one\n if self.accel_r > 0:\n if self.vel > 0:\n ori_delta = min(ori_delta, reset_radian(self.accel_ori))\n elif self.vel < 0:\n ori_delta = max(ori_delta, reset_radian(self.accel_ori - pi))\n elif self.accel_r < 0:\n if self.vel > 0:\n ori_delta = max(ori_delta, reset_radian(self.accel_ori))\n elif self.vel < 0:\n ori_delta = min(ori_delta, reset_radian(self.accel_ori + pi))\n ori_new = reset_radian(self.ori + ori_delta)\n # use middle value of velocity and orientation to calculation next position\n vel_mid = (vel_new + self.vel) / 2\n ori_mid = (ori_new + self.ori) / 2\n # update position\n self.pos[0] = self.pos[0] + cos(ori_mid)*vel_mid * delta_t\n self.pos[1] = self.pos[1] + sin(ori_mid)*vel_mid * delta_t\n # update the new velocity and orientation\n self.vel = vel_new\n self.ori = ori_new\n def update_without_accel(self, delta_t): # update without acceleration\n # if no acceleration, velocity keeps the same\n self.pos[0] = self.pos[0] + cos(self.ori)*self.vel * delta_t\n self.pos[1] = self.pos[1] + sin(self.ori)*self.vel * delta_t\n def check_boundary(self, arena_size): # rebound the automaton on boundaries\n if self.vel == 0: return # nothing to do if automaton is still\n # use velocities in Cartesian arena coordinates to control automaton rebound\n vel_x_temp = self.vel * cos(self.ori)\n vel_y_temp = self.vel * sin(self.ori)\n if (self.pos[0] >= arena_size[0]/2 and vel_x_temp > 0) \\\n or (self.pos[0] <= -arena_size[0]/2 and vel_x_temp < 0):\n # if automaton out of left or right bouddaries\n # flip positive moving direction along vertical line\n self.ori = reset_radian(2*(pi/2) - self.ori)\n if (self.pos[1] >= arena_size[1]/2 and vel_y_temp > 0) \\\n or (self.pos[1] <= -arena_size[1]/2 and vel_y_temp < 0):\n # if automaton out of top or bottom bouddaries\n # flip positive moving direction along horizontal line\n self.ori = reset_radian(2*(0) - self.ori)\n # accessors for Automaton class\n def get_pos(self):\n return self.pos\n def get_ori(self):\n return self.ori\n def get_radius(self):\n return self.radius\n def get_alpha(self):\n return self.alpha\n def get_detection_status(self):\n return self.neighbor_detected\n\n\n\n","sub_path":"experiment_2_automaton.py","file_name":"experiment_2_automaton.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"449539121","text":"from weasyprint import HTML\n#import flask\nfrom flask import Flask, render_template, send_file, request\nfrom datetime import date\nimport os\napp = Flask(__name__)\nimport io\n\n\n# html =HTML('invoice.html')\n# html.write_pdf('invoice.pdf')\n\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef hello_world():\n posted_data =request.get_json() or {}\n today = date.today()#.strftime(\"%B %-d, %Y\")\n today =today.strftime(\"%d/%m/%Y\")\n invoice_number = 123\n default_data = {\n 'duedate': 'August 1, 2019',\n 'from_addr': {\n 'addr1': '12345 Sunny Road',\n 'addr2': 'Sunnyville, CA 12345',\n 'company_name': 'Python Tip'\n },\n 'invoice_number': 123,\n 'items': [{\n 'charge': 300.0,\n 'title': 'website design'\n },\n {\n 'charge': 75.0,\n 'title': 'Hosting (3 months)'\n },\n {\n 'charge': 10.0,\n 'title': 'Domain name (1 year)'\n }\n ],\n 'to_addr': {\n 'company_name': 'Acme Corp',\n 'person_email': 'john@example.com',\n 'person_name': 'John Dilly'\n }\n }\n \n duedate = posted_data.get('duedate', default_data['duedate'])\n from_addr = posted_data.get('from_addr', default_data['from_addr'])\n to_addr = posted_data.get('to_addr', default_data['to_addr'])\n invoice_number = posted_data.get('invoice_number', \n default_data['invoice_number'])\n items = posted_data.get('items', default_data['items'])\n #for item in items:\n #total = sum(deal['charge'] for deal in item)\n total = sum([i['charge'] for i in items])\n \n\n rendered= render_template('invoice.html', date=today,from_addr=from_addr, to_addr=to_addr, items=items, total=total, invoice_number=invoice_number,duedate=duedate)\n \n html =HTML(string=rendered)\n rendered_pdf =html.write_pdf()\n return send_file(\n io.BytesIO(rendered_pdf),\n download_name='invoice.pdf'\n )\n \n\n\n \n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"70882199","text":"import logging\nimport json\nimport uuid\nimport traceback\n\nfrom enum import Enum\nfrom functools import wraps\nfrom redis import StrictRedis\n\nfrom d3a_interface.utils import wait_until_timeout_blocking, key_in_dict_and_not_none\nfrom d3a_api_client import APIClientInterface\nfrom concurrent.futures.thread import ThreadPoolExecutor\nfrom d3a_api_client.constants import MAX_WORKER_THREADS\n\nroot_logger = logging.getLogger()\nroot_logger.setLevel(logging.INFO)\n\n\nclass RedisAPIException(Exception):\n pass\n\n\ndef registered_connection(f):\n @wraps(f)\n def wrapped(self, *args, **kwargs):\n if not self.is_active:\n raise RedisAPIException(f'Registration has not completed yet.')\n return f(self, *args, **kwargs)\n return wrapped\n\n\nclass Commands(Enum):\n OFFER = 1\n BID = 2\n DELETE_OFFER = 3\n DELETE_BID = 4\n LIST_OFFERS = 5\n LIST_BIDS = 6\n DEVICE_INFO = 7\n\n\nclass RedisClient(APIClientInterface):\n def __init__(self, area_id, client_id, autoregister=True, redis_url='redis://localhost:6379',\n pubsub_thread=None):\n super().__init__(area_id, client_id, autoregister, redis_url)\n self.redis_db = StrictRedis.from_url(redis_url)\n self.pubsub = self.redis_db.pubsub() if pubsub_thread is None else pubsub_thread\n # TODO: Replace area_id (which is a area name slug now) with \"area_uuid\"\n self.area_id = area_id\n self.client_id = client_id\n self.device_uuid = None\n self.is_active = False\n self._blocking_command_responses = {}\n self._subscribe_to_response_channels(pubsub_thread)\n self.executor = ThreadPoolExecutor(max_workers=MAX_WORKER_THREADS)\n if autoregister:\n self.register(is_blocking=True)\n\n def _subscribe_to_response_channels(self, pubsub_thread=None):\n channel_subs = {\n self._response_topics[c]: self._generate_command_response_callback(c)\n for c in Commands\n }\n\n channel_subs[f'{self.area_id}/response/register_participant'] = self._on_register\n channel_subs[f'{self.area_id}/response/unregister_participant'] = self._on_unregister\n channel_subs[f'{self._channel_prefix}/events/market'] = self._on_market_cycle\n channel_subs[f'{self._channel_prefix}/events/tick'] = self._on_tick\n channel_subs[f'{self._channel_prefix}/events/trade'] = self._on_trade\n channel_subs[f'{self._channel_prefix}/events/finish'] = self._on_finish\n\n self.pubsub.subscribe(**channel_subs)\n if pubsub_thread is None:\n self.pubsub.run_in_thread(daemon=True)\n\n def register(self, is_blocking=False):\n logging.info(f\"Trying to register to {self.area_id} as client {self.client_id}\")\n if self.is_active:\n raise RedisAPIException(f'API is already registered to the market.')\n data = {\"name\": self.client_id, \"transaction_id\": str(uuid.uuid4())}\n self._blocking_command_responses[\"register\"] = data\n self.redis_db.publish(f'{self.area_id}/register_participant', json.dumps(data))\n\n if is_blocking:\n try:\n wait_until_timeout_blocking(lambda: self.is_active, timeout=120)\n except AssertionError:\n raise RedisAPIException(\n f'API registration process timed out. Server will continue processing your '\n f'request on the background and will notify you as soon as the registration '\n f'has been completed.')\n\n def unregister(self, is_blocking=False):\n logging.info(f\"Trying to unregister from {self.area_id} as client {self.client_id}\")\n\n if not self.is_active:\n raise RedisAPIException(f'API is already unregistered from the market.')\n\n data = {\"name\": self.client_id, \"transaction_id\": str(uuid.uuid4())}\n self._blocking_command_responses[\"unregister\"] = data\n self.redis_db.publish(f'{self.area_id}/unregister_participant', json.dumps(data))\n\n if is_blocking:\n try:\n wait_until_timeout_blocking(lambda: not self.is_active, timeout=120)\n except AssertionError:\n raise RedisAPIException(\n f'API unregister process timed out. Server will continue processing your '\n f'request on the background and will notify you as soon as the unregistration '\n f'has been completed.')\n\n @property\n def _channel_prefix(self):\n return f\"{self.area_id}/{self.client_id}\"\n\n @property\n def _command_topics(self):\n return {\n Commands.OFFER: f'{self._channel_prefix}/offer',\n Commands.BID: f'{self._channel_prefix}/bid',\n Commands.DELETE_OFFER: f'{self._channel_prefix}/delete_offer',\n Commands.DELETE_BID: f'{self._channel_prefix}/delete_bid',\n Commands.LIST_OFFERS: f'{self._channel_prefix}/list_offers',\n Commands.LIST_BIDS: f'{self._channel_prefix}/list_bids',\n Commands.DEVICE_INFO: f'{self._channel_prefix}/device_info'\n }\n\n @property\n def _response_topics(self):\n response_prefix = self._channel_prefix + \"/response\"\n return {\n Commands.OFFER: f'{response_prefix}/offer',\n Commands.BID: f'{response_prefix}/bid',\n Commands.DELETE_OFFER: f'{response_prefix}/delete_offer',\n Commands.DELETE_BID: f'{response_prefix}/delete_bid',\n Commands.LIST_OFFERS: f'{response_prefix}/list_offers',\n Commands.LIST_BIDS: f'{response_prefix}/list_bids',\n Commands.DEVICE_INFO: f'{response_prefix}/device_info',\n }\n\n def _wait_and_consume_command_response(self, command_type, transaction_id):\n def check_if_command_response_received():\n return any(command == command_type and\n \"transaction_id\" in data and data[\"transaction_id\"] == transaction_id\n for command, data in self._blocking_command_responses.items())\n logging.debug(f\"Command {command_type} waiting for response...\")\n wait_until_timeout_blocking(check_if_command_response_received, timeout=120)\n command_output = self._blocking_command_responses.pop(command_type)\n logging.debug(f\"Command {command_type} got response {command_output}\")\n return command_output\n\n def _generate_command_response_callback(self, command_type):\n def _command_received(msg):\n try:\n message = json.loads(msg[\"data\"])\n except Exception as e:\n logging.error(f\"Received incorrect response on command {command_type}. \"\n f\"Response {msg}. Error {e}.\")\n return\n logging.debug(f\"Command {command_type} received response: {message}\")\n if 'error' in message:\n logging.error(f\"Error when receiving {command_type} command response.\"\n f\"Error output: {message}\")\n return\n else:\n self._blocking_command_responses[command_type] = message\n return _command_received\n\n def _publish_and_wait(self, command_type, data):\n data.update({\"transaction_id\": str(uuid.uuid4())})\n self.redis_db.publish(self._command_topics[command_type], json.dumps(data))\n return self._wait_and_consume_command_response(command_type, data[\"transaction_id\"])\n\n @registered_connection\n def offer_energy(self, energy, price):\n logging.debug(f\"Client tries to place an offer for {energy} kWh at {price} cents.\")\n return self._publish_and_wait(Commands.OFFER, {\"energy\": energy, \"price\": price})\n\n @registered_connection\n def offer_energy_rate(self, energy, rate):\n logging.debug(f\"Client tries to place an offer for {energy} kWh at {rate} cents/kWh.\")\n return self._publish_and_wait(Commands.OFFER, {\"energy\": energy, \"price\": rate * energy})\n\n @registered_connection\n def bid_energy(self, energy, price):\n logging.info(f\"Client tries to place a bid for {energy} kWh at {price} cents.\")\n return self._publish_and_wait(Commands.BID, {\"energy\": energy, \"price\": price})\n\n @registered_connection\n def bid_energy_rate(self, energy, rate):\n logging.info(f\"Client tries to place a bid for {energy} kWh at {rate} cents/kWh.\")\n return self._publish_and_wait(Commands.BID, {\"energy\": energy, \"price\": rate * energy})\n\n @registered_connection\n def delete_offer(self, offer_id=None):\n if offer_id is None:\n logging.debug(f\"Client tries to delete all offers.\")\n else:\n logging.debug(f\"Client tries to delete offer {offer_id}.\")\n return self._publish_and_wait(Commands.DELETE_OFFER, {\"offer\": offer_id})\n\n @registered_connection\n def delete_bid(self, bid_id=None):\n if bid_id is None:\n logging.debug(f\"Client tries to delete all bids.\")\n else:\n logging.debug(f\"Client tries to delete bid {bid_id}.\")\n return self._publish_and_wait(Commands.DELETE_BID, {\"bid\": bid_id})\n\n @registered_connection\n def list_offers(self):\n logging.debug(f\"Client tries to read its posted offers.\")\n return self._publish_and_wait(Commands.LIST_OFFERS, {})\n\n @registered_connection\n def list_bids(self):\n logging.debug(f\"Client tries to read its posted bids.\")\n return self._publish_and_wait(Commands.LIST_BIDS, {})\n\n @registered_connection\n def device_info(self):\n logging.debug(f\"Client tries to read the device information.\")\n return self._publish_and_wait(Commands.DEVICE_INFO, {})\n\n def _on_register(self, msg):\n message = json.loads(msg[\"data\"])\n self._check_buffer_message_matching_command_and_id(message)\n if 'available_publish_channels' not in message or \\\n 'available_subscribe_channels' not in message:\n raise RedisAPIException(f'Registration to the market {self.area_id} failed.')\n\n logging.info(f\"Client was registered to market: {message}\")\n self.is_active = True\n\n def executor_function():\n self.on_register(message)\n self.executor.submit(executor_function)\n\n def _on_unregister(self, msg):\n message = json.loads(msg[\"data\"])\n self._check_buffer_message_matching_command_and_id(message)\n self.is_active = False\n if message[\"response\"] != \"success\":\n raise RedisAPIException(f'Failed to unregister from market {self.area_id}.'\n f'Deactivating connection.')\n\n def _on_market_cycle(self, msg):\n message = json.loads(msg[\"data\"])\n logging.info(f\"A new market was created. Market information: {message}\")\n\n def executor_function():\n try:\n self.on_market_cycle(message)\n except Exception as e:\n logging.error(f\"_on_market_cycle raised exception: {e}. \\n Traceback: {traceback.format_exc()}\")\n self.executor.submit(executor_function)\n\n def _on_tick(self, msg):\n message = json.loads(msg[\"data\"])\n logging.info(f\"Time has elapsed on the device. Progress info: {message}\")\n\n def executor_function():\n try:\n self.on_tick(message)\n except Exception as e:\n logging.error(f\"on_tick raised exception: {e}. \\n Traceback: {traceback.format_exc()}\")\n\n self.executor.submit(executor_function)\n\n def _on_trade(self, msg):\n message = json.loads(msg[\"data\"])\n logging.info(f\"A trade took place on the device. Trade information: {message}\")\n\n def executor_function():\n try:\n self.on_trade(message)\n except Exception as e:\n logging.error(f\"on_trade raised exception: {e}. \\n Traceback: {traceback.format_exc()}\")\n self.executor.submit(executor_function)\n\n def _on_finish(self, msg):\n message = json.loads(msg[\"data\"])\n logging.info(f\"Simulation finished. Information: {message}\")\n\n def executor_function():\n try:\n self.on_finish(message)\n except Exception as e:\n logging.error(f\"on_finish raised exception: {e}. \\n Traceback: {traceback.format_exc()}\")\n self.executor.submit(executor_function)\n\n def _check_buffer_message_matching_command_and_id(self, message):\n if key_in_dict_and_not_none(message, \"transaction_id\"):\n transaction_id = message[\"transaction_id\"]\n if not any(command in [\"register\", \"unregister\"] and \"transaction_id\" in data and\n data[\"transaction_id\"] == transaction_id\n for command, data in self._blocking_command_responses.items()):\n raise RedisAPIException(\"There is no matching command response in _blocking_command_responses.\")\n else:\n raise RedisAPIException(\n \"The answer message does not contain a valid 'transaction_id' member.\")\n\n def on_register(self, registration_info):\n pass\n\n def on_market_cycle(self, market_info):\n pass\n\n def on_tick(self, tick_info):\n pass\n\n def on_trade(self, trade_info):\n pass\n\n def on_finish(self, finish_info):\n pass","sub_path":"d3a_api_client/redis_client_base.py","file_name":"redis_client_base.py","file_ext":"py","file_size_in_byte":13320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"134153833","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n########进货的url#######\n path('jinhuo/', views.jinhuo_list),\n path('jinhuo/add_jinhuo/', views.add_jinhuo),\n path('jinhuo/del_jinhuo/', views.del_jinhuo),\n path('jinhuo/edit_jinhuo/', views.eidt_jinhuo),\n path('', views.shouye),\n path('jinhuo/search_jinhuo/', views.search_jinhuo),\n##########销售的url#############\n path('xiaoshou/', views.xiaoshou_list),\n path('xiaoshou/add_xiaoshou/', views.add_xiaoshou),\n path('xiaoshou/search_xiaoshou/', views.search_xiaoshou),\n##########库存的url##############\n path('kucun/', views.kucun_list),\n path('kucun/search_kucun/', views.search_kucun),\n##############返货的url##########\n path('fanhuo/', views.fanhuo_list),\n path('fanhuo/add_fanhuo/', views.add_fanhuo),\n path('fanhuo/search_fanhuo/', views.search_fanhuo),\n##############会员积分################\n path('vip/', views.vip_list),\n path('vip/add_vip/', views.add_vip),\n path('vip/add_yucun/', views.add_yucun),\n path('vip/duihuan/', views.jifen_duihuan),\n path('vip/vip_detial/', views.vip_detial),\n path('vip/search_vip/', views.search_vip)\n]","sub_path":"first_web/shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"343160646","text":"# Author: Heike, Sean\nfrom __future__ import annotations\n\nimport copy\nimport logging\nimport string\nimport random\nimport os\nfrom typing import Dict, List, Tuple, Set, Optional, Union, Any, cast\nfrom mypy_extensions import TypedDict\n\nfrom mypy_extensions import TypedDict\nfrom sklearn_crfsuite import CRF, metrics\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import TreebankWordTokenizer\n\n\nfrom dere.taskspec import TaskSpecification, SpanType\nfrom dere.corpus import Corpus, Instance, Span\nfrom dere.models import Model\nfrom dere.utils import progressify\n\nfrom sklearn.externals import joblib\n\nword_tokenizer = TreebankWordTokenizer()\n\nFeatures = Dict[str, Union[str, bool]]\n\n\nclass SpanClassifier(Model):\n\n def __init__(\n self, task_spec: TaskSpecification, model_spec: Dict[str, Any],\n gazetteer: Optional[str] = None\n ) -> None:\n super().__init__(task_spec, model_spec)\n self.target_span_types: List[SpanType] = []\n self.given_span_types: List[SpanType] = []\n for span_type in list(task_spec.span_types):\n if span_type.predict:\n self.target_span_types.append(span_type)\n else:\n self.given_span_types.append(span_type)\n self.gazetteer: Dict[str, Set[str]] = {}\n if gazetteer is not None:\n model_spec_dir = os.path.join(*os.path.split(model_spec['__path__'])[:-1])\n gazetteer_path = os.path.join(model_spec_dir, gazetteer)\n self.read_gazetteer(gazetteer_path)\n\n # TODO(Sean) -- move this to Model.__init__\n self.logger = logging.getLogger(\"dere\")\n\n self.target2classifier: Dict[str, CRF] = {}\n self.ps = PorterStemmer()\n\n # initialize everything necessary\n self.logger.debug(\"[SpanClassifier] initialized successfully\")\n\n def shuffle(self, X: List, y: List) -> Tuple[List, List]:\n indices = [i for i in range(len(X))]\n # using shuffle instead of permutation to reproduce set from old code\n # TODO: change to permutation as this is more elegant\n random.seed(1111)\n random.shuffle(indices)\n X_shuffled = [X[i] for i in indices]\n y_shuffled = [y[i] for i in indices]\n return X_shuffled, y_shuffled\n\n def train(\n self,\n corpus_train: Corpus,\n dev_corpus: Optional[Corpus] = None,\n ) -> None:\n self.logger.info(\"[SpanClassifier] Extracting features...\")\n X_train = self.get_features(corpus_train)\n self.logger.info(\"[SpanClassifier] Extracting features done\")\n\n self.logger.debug(\"[SpanClassifier] using \" + str(len(X_train)) + \" sentences for training\")\n\n if dev_corpus is not None:\n self.logger.info(\"[SpanClassifier] Extracting features from dev corpus...\")\n X_dev = self.get_features(dev_corpus)\n self.logger.info(\"[SpanClassifier] Extracting features from dev corpus done\")\n\n self.logger.info(\n \"[SpanClassifier] target span types: \" + str([st.name for st in self.target_span_types])\n )\n\n Setup = TypedDict(\"Setup\", {\"aps\": bool, \"c2v\": float})\n default_setup: Setup = {\"aps\": True, \"c2v\": 0.1}\n if dev_corpus is None:\n self.logger.warning(\n \"[SpanClassifier] No dev corpus given. Using setup: \" + str(default_setup)\n )\n for t in self.target_span_types:\n X_train2 = self.get_span_type_specific_features(corpus_train, t)\n X_train_merged = self.merge_features(X_train, X_train2)\n self.logger.debug(\"[SpanClassifier] Optimizing classifier for class \" + str(t))\n target_t = self.get_binary_labels(corpus_train, t, use_bio=True)\n self.logger.debug(\"[SpanClassifier] %r\", target_t)\n\n X_train_merged, target_t = self.shuffle(X_train_merged, target_t)\n\n if dev_corpus is None:\n crf = CRF(\n algorithm=\"l2sgd\",\n all_possible_transitions=True,\n all_possible_states=default_setup[\"aps\"],\n c2=default_setup[\"c2v\"],\n )\n crf.fit(X_train_merged, target_t)\n self.target2classifier[t.name] = crf\n else:\n # get features for dev corpus\n X_dev2 = self.get_span_type_specific_features(dev_corpus, t)\n X_dev_merged = self.merge_features(X_dev, X_dev2)\n y_dev = self.get_binary_labels(dev_corpus, t, use_bio=True)\n self.logger.info(\"[SpanClassifier] Starting grid search for \" + t.name)\n # optimize on dev\n best_f1 = -1.0\n best_setup: Setup = {\"c2v\": 0.001, \"aps\": True}\n stopTraining = False\n aps_possibilities = [True, False]\n c2v_possibilities = [0.001, 0.01, 0.1, 0.3, 0.5, 0.6, 0.9,\n 0.99, 1.0, 1.3, 1.6, 3.0, 6.0, 10.0]\n num_hyperparam_combination = len(aps_possibilities) * len(c2v_possibilities)\n for aps_index, aps in enumerate(aps_possibilities):\n if stopTraining:\n break\n\n def message(i: int, val: float) -> str:\n return \"c2v: {}, aps: {} | {}/{}\".format(\n val,\n aps,\n i + 1,\n num_hyperparam_combination,\n )\n\n for c2v in progressify(\n c2v_possibilities,\n message,\n offset=aps_index*len(c2v_possibilities),\n length=num_hyperparam_combination,\n ):\n if stopTraining:\n break\n cur_setup: Setup = {\"aps\": aps, \"c2v\": c2v}\n self.logger.debug(\"[SpanClassifier] Current setup: \" + str(cur_setup))\n crf = CRF(\n algorithm=\"l2sgd\",\n all_possible_transitions=True,\n all_possible_states=aps,\n c2=c2v,\n )\n crf.fit(X_train_merged, target_t)\n\n micro_f1 = self._eval(crf, X_dev_merged, y_dev)\n if micro_f1 > best_f1:\n self.target2classifier[t.name] = crf\n best_setup = cur_setup\n best_f1 = micro_f1\n if micro_f1 == 1.0: # cannot get better\n stopTraining = True\n self.logger.info(\"[SpanClassifier] Best setup: \" + str(best_setup))\n with open(\"best_parameters_span\", 'a') as out:\n out.write(t.name)\n out.write(\"\\n\")\n for k, v in best_setup.items():\n out.write(str(k) + \"\\t\" + str(v) + \"\\n\")\n out.write(\"\\n\")\n self.logger.info(\"[SpanClassifier] Retraining best setup with all available data\")\n X_train_all = X_train_merged + X_dev_merged\n target_all = target_t + y_dev\n X_train_all, target_all = self.shuffle(X_train_all, target_all)\n crf = CRF(\n algorithm=\"l2sgd\",\n all_possible_transitions=True,\n all_possible_states=best_setup[\"aps\"],\n c2=best_setup[\"c2v\"]\n )\n crf.fit(X_train_all, target_all)\n self.target2classifier[t.name] = crf\n self.logger.info(\"[SpanClassifier] Finished training\")\n\n def _eval(\n self, classifier: CRF, X_dev: List[List[Features]], y_dev: List[List[str]]\n ) -> float:\n y_pred = classifier.predict(X_dev)\n try:\n self.logger.debug(\n \"[SpanClassifier] %s\",\n metrics.flat_classification_report(\n y_dev, y_pred, labels=[\"I\", \"B\"], digits=3\n )\n )\n except ZeroDivisionError:\n pass\n micro_f1 = metrics.flat_f1_score(\n y_dev, y_pred, average=\"micro\", labels=[\"I\", \"B\"]\n )\n self.logger.debug(\"[SpanClassifier] micro F1: \" + str(micro_f1))\n return micro_f1\n\n def predict(self, corpus: Corpus) -> None:\n # input:\n # raw_data: list of list of Token instances\n\n if self.target_span_types is None:\n self.logger.error(\n \"[SpanClassifier] target span types are not initialized. Use train function\"\n + \" first or load existing model to initialize it\"\n )\n return\n X_test = self.get_features(corpus)\n predictions = {}\n for t in self.target_span_types:\n self.logger.debug(\"[SpanClassifer] %r\", t)\n X_test2 = self.get_span_type_specific_features(corpus, t)\n X_test_merged = self.merge_features(X_test, X_test2)\n y_pred = self.target2classifier[t.name].predict(X_test_merged)\n for X_item, y_item in zip(X_test_merged, y_pred):\n self.logger.debug(\"[SpanClassifier] %r\", X_item)\n self.logger.debug(\"[SpanClassifier] %r\", y_item)\n self.logger.debug(\"[SpanClassifier] -----\")\n predictions[t.name] = y_pred\n self.prepare_results(predictions, corpus)\n\n def get_spans_for_tokens(\n self, tokens: List[Tuple[int, int]], instance: Instance\n ) -> List[List[Span]]:\n spans_for_tokens = [] # one list of spans per token\n for (t_left, t_right) in tokens:\n token_spans = []\n for s in instance.spans:\n # because of multi-token annotations:\n if s.left <= t_left and t_right <= s.right:\n token_spans.append(s)\n else:\n \"\"\"\n if tokenization did not split a word in the same way as\n annotation\n Example: train id: 10229815: \"CTLA-4-Mediated\" -> is not\n split into two tokens but annotation is only for first part\n CTLA-4\n solution here: adapt label but do not adapt tokenization\n because it cannot be adapted for unseed test data either\n two special cases:\n \"\"\"\n if s.left == t_left and t_right > s.right:\n token_spans.append(s)\n elif t_right == s.right and t_left < s.left:\n token_spans.append(s)\n spans_for_tokens.append(token_spans)\n # sanity check: we need one label for each token\n assert len(spans_for_tokens) == len(tokens)\n return spans_for_tokens\n\n def get_binary_labels(\n self, corpus: Corpus, t: SpanType, use_bio: bool = False\n ) -> List[List[str]]:\n binary_labels = []\n for instance in corpus.instances:\n instance_text = instance.text.replace('\"', \"'\")\n instance.text = instance_text\n instance_tokens = list(word_tokenizer.span_tokenize(instance_text))\n spans_for_tokens = self.get_spans_for_tokens(instance_tokens, instance)\n\n # do binarization based on given target label t\n instance_binary_labels: List[str] = []\n\n for idx, token_spans in enumerate(spans_for_tokens):\n for span in token_spans:\n if span.span_type == t:\n if use_bio:\n if idx > 0 and span in spans_for_tokens[idx - 1]:\n instance_binary_labels.append(\"I\")\n else:\n instance_binary_labels.append(\"B\")\n else:\n instance_binary_labels.append(\"1\")\n break\n else: # for-else: if we don't find a span of our type\n if use_bio:\n instance_binary_labels.append(\"O\")\n else:\n instance_binary_labels.append(\"0\")\n\n # sanity check: we need one label for each token\n assert len(instance_binary_labels) == len(instance_tokens)\n\n binary_labels.append(instance_binary_labels)\n return binary_labels\n\n def read_gazetteer(self, filename: str) -> None:\n with open(filename) as f:\n for line in f:\n line = line.strip()\n parts = line.split(\" \")\n label = parts[0]\n example = \" \".join(parts[1:])\n if label not in self.gazetteer:\n self.gazetteer[label] = set()\n self.gazetteer[label].add(example.lower())\n\n def get_span_type_specific_features(\n self, corpus: Corpus, target: SpanType\n ) -> List[List[Features]]:\n feature_list = []\n for instance in corpus.instances:\n instance_text = instance.text.replace('\"', \"'\")\n instance.text = instance_text\n words = list(word_tokenizer.tokenize(instance_text))\n instance_feature_list = []\n for word in words:\n features: Features = {}\n if target.name in self.gazetteer:\n features[\"in_\" + str(target.name) + \"_gazetteer\"] = (\n word.lower() in self.gazetteer[target.name]\n )\n instance_feature_list.append(features)\n feature_list.append(instance_feature_list)\n return feature_list\n\n def merge_features(\n self, features1: List[List[Features]], features2: List[List[Features]]\n ) -> List[List[Features]]:\n result = copy.deepcopy(features1)\n for instance_features1, instance_features2 in zip(result, features2):\n for f1, f2 in zip(instance_features1, instance_features2):\n f1.update(f2)\n return result\n\n def word_features(self, word: str, prefix: str) -> Features:\n return {\n prefix + \".lower\": word.lower(),\n prefix + \".isupper\": word.isupper(),\n prefix + \".istitle\": word.istitle(),\n prefix + \".isdigit\": word.isdigit(),\n prefix + \".containsdigit\": self.contains_digit(word),\n prefix + \".containspunct\": self.contains_punct(word),\n prefix + \".stem\": self.get_stem(word),\n }\n\n def token_features(\n self, instance: Instance, token: Tuple[int, int], prefix: str\n ) -> Features:\n left, right = token\n word = instance.text[left:right]\n features = self.word_features(word, prefix)\n for given_span_type in self.given_span_types:\n features[\n prefix + \".is_\" + str(given_span_type.name)\n ] = self.is_token_in_span(instance, token, given_span_type)\n return features\n\n def get_features(self, corpus: Corpus) -> List[List[Features]]:\n feature_list = []\n for instance in progressify(corpus.instances, \"getting features\"):\n instance_text = instance.text.replace('\"', \"'\")\n instance.text = instance_text\n token_spans = list(word_tokenizer.span_tokenize(instance_text))\n instance_feature_list = []\n for i, token in enumerate(token_spans):\n features = self.token_features(instance, token, \"word\")\n\n # context features: features of previous token\n if i > 0:\n prev_token = token_spans[i - 1]\n features.update(\n self.token_features(instance, prev_token, \"-1:word\")\n )\n else:\n features[\"BOS\"] = True\n\n # context features: features of next token\n if i < len(token_spans) - 1:\n next_token = token_spans[i + 1]\n features.update(\n self.token_features(instance, next_token, \"+1:word\")\n )\n else:\n features[\"EOS\"] = True\n\n instance_feature_list.append(features)\n\n feature_list.append(instance_feature_list)\n return feature_list\n\n def is_token_in_span(\n self, instance: Instance, token: Tuple[int, int], span_type: SpanType\n ) -> bool:\n left, right = token\n for span in instance.spans:\n if span.span_type == span_type:\n if span.left <= left and span.right >= right:\n return True\n else: # If tokenizer does not split the same way as annotation\n if span.left == left and right > span.right:\n return True\n elif span.right == right and left < span.left:\n return True\n return False\n\n def contains_digit(self, word: str) -> bool:\n return len(set(word) & set(string.digits)) > 0\n\n def contains_punct(self, word: str) -> bool:\n # TODO -- change to string.punctuation\n punct = \".,-\"\n return len(set(word) & set(punct)) > 0\n\n def get_stem(self, word: str) -> str:\n return self.ps.stem(word)\n\n def prepare_results(\n self, predictions: Dict[str, List[List[str]]], corpus: Corpus\n ) -> None:\n self.logger.info(\"[SpanClassifier] Preparing results...\")\n for i, instance in enumerate(corpus.instances):\n instance_text = instance.text.replace('\"', \"'\")\n instance.text = instance_text\n instance_tokens = list(word_tokenizer.span_tokenize(instance_text))\n for target_span_type in self.target_span_types:\n instance_predictions = predictions[target_span_type.name][i]\n current_span_left: Optional[int] = None\n current_span_right = 0\n for token, label in zip(instance_tokens, instance_predictions):\n if label != \"O\":\n d_msg = \"token: \" + str(token) + \"\\t\" + str(instance.text[token[0]:token[1]])\n d_msg += \"\\t\" + \"label: \" + str(target_span_type)\n self.logger.debug(\"[SpanClassifier] %r\", d_msg)\n if current_span_left is not None and label in \"BO\":\n instance.new_span(\n target_span_type,\n current_span_left,\n current_span_right,\n )\n current_span_left = None\n if label == \"B\":\n current_span_left = token[0]\n if label in \"BI\":\n current_span_right = token[1]\n if current_span_left is not None: # otherwise spans at end of window are neglected\n instance.new_span(\n target_span_type,\n current_span_left,\n current_span_right,\n )\n self.logger.info(\"[SpanClassifier] Preparing results done\")\n","sub_path":"dere/models/_baseline/span_classifier.py","file_name":"span_classifier.py","file_ext":"py","file_size_in_byte":19337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"229946791","text":"\"\"\"\r\nPython makes performing file I/O simple. Take a look\r\nat how to read and write to files here:\r\n\r\nhttps://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\r\n\"\"\"\r\n\r\n# Open up the \"foo.txt\" file (which already exists) for reading\r\n# Print all the contents of the file, then close the file\r\n# Note: pay close attention to your current directory when trying to open \"foo.txt\"\r\n\r\n# YOUR CODE HERE\r\n#open the file assign to f, then read it into read_data, print.\r\nf = open(\"foo.txt\", \"r\")\r\nread_data = f.read()\r\nprint(read_data)\r\nf.close()\r\n# Open up a file called \"bar.txt\" (which doesn't exist yet) for\r\n# writing. Write three lines of arbitrary content to that file,\r\n# then close the file. Open up \"bar.txt\" and inspect it to make\r\n# sure that it contains what you expect it to contain\r\n\r\n# YOUR CODE HERE\r\n\r\n#open the file to read first 3 lines\r\nwith open('foo.txt') as myfile:\r\n heads = [next(myfile) for x in range(3)]\r\n#write the first 3 lines into a bar.txt\r\nwith open('bar.txt', 'w') as writefile:\r\n writefile.writelines(heads)","sub_path":"src/13_file_io.py","file_name":"13_file_io.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"557584569","text":"import unittest\n\nfrom conans.test.utils.tools import TestClient, TestBufferConanOutput\nimport os\nimport zipfile\nfrom conans.test.utils.test_files import temp_folder\nfrom conans.util.files import load, save_files, save\nfrom conans.client.remote_registry import RemoteRegistry, Remote\nfrom mock import patch\nfrom conans.client.rest.uploader_downloader import Downloader\nfrom conans import tools\nfrom conans.client.conf import ConanClientConfigParser\nimport shutil\n\n\nwin_profile = \"\"\"[settings]\n os: Windows\n\"\"\"\n\nlinux_profile = \"\"\"[settings]\n os: Linux\n\"\"\"\n\nremotes = \"\"\"myrepo1 https://myrepourl.net False\nmy-repo-2 https://myrepo2.com True\n\"\"\"\n\nregistry = \"\"\"myrepo1 https://myrepourl.net False\n\nPkg/1.0@user/channel myrepo1\n\"\"\"\n\nsettings_yml = \"\"\"os:\n Windows:\n Linux:\narch: [x86, x86_64]\n\"\"\"\n\nconan_conf = \"\"\"\n[log]\nrun_to_output = False # environment CONAN_LOG_RUN_TO_OUTPUT\nlevel = 10 # environment CONAN_LOGGING_LEVEL\n\n[general]\ncompression_level = 6 # environment CONAN_COMPRESSION_LEVEL\ncpu_count = 1 # environment CONAN_CPU_COUNT\n\n[proxies]\n# Empty section will try to use system proxies.\n# If don't want proxy at all, remove section [proxies]\n# As documented in http://docs.python-requests.org/en/latest/user/advanced/#proxies\nhttp = http://user:pass@10.10.1.10:3128/\nno_proxy = mylocalhost\nhttps = None\n# http = http://10.10.1.10:3128\n# https = http://10.10.1.10:1080\n\"\"\"\n\n\ndef zipdir(path, zipfilename):\n with zipfile.ZipFile(zipfilename, 'w', zipfile.ZIP_DEFLATED) as z:\n for root, _, files in os.walk(path):\n for f in files:\n z.write(os.path.join(root, f))\n\n\nclass ConfigInstallTest(unittest.TestCase):\n\n def setUp(self):\n self.client = TestClient()\n registry_path = self.client.client_cache.registry\n\n save(registry_path, \"\"\"my-repo-2 https://myrepo2.com True\nconan-center https://conan-center.com\n\nMyPkg/0.1@user/channel my-repo-2\nOther/1.2@user/channel conan-center\n\"\"\")\n save(os.path.join(self.client.client_cache.profiles_path, \"default\"), \"#default profile empty\")\n save(os.path.join(self.client.client_cache.profiles_path, \"linux\"), \"#empty linux profile\")\n\n def _create_profile_folder(self, folder=None):\n folder = folder or temp_folder(path_with_spaces=False)\n save_files(folder, {\"settings.yml\": settings_yml,\n \"remotes.txt\": remotes,\n \"profiles/linux\": linux_profile,\n \"profiles/windows\": win_profile,\n \"config/conan.conf\": conan_conf,\n \"pylintrc\": \"#Custom pylint\"})\n return folder\n\n def _create_zip(self, zippath=None):\n folder = self._create_profile_folder()\n zippath = zippath or os.path.join(folder, \"myconfig.zip\")\n zipdir(folder, zippath)\n return zippath\n\n def _check(self, install_path):\n settings_path = self.client.client_cache.settings_path\n self.assertEqual(load(settings_path).splitlines(), settings_yml.splitlines())\n registry_path = self.client.client_cache.registry\n registry = RemoteRegistry(registry_path, TestBufferConanOutput())\n self.assertEqual(registry.remotes,\n [Remote(\"myrepo1\", \"https://myrepourl.net\", False),\n Remote(\"my-repo-2\", \"https://myrepo2.com\", True),\n ])\n self.assertEqual(registry.refs, {\"MyPkg/0.1@user/channel\": \"my-repo-2\"})\n self.assertEqual(sorted(os.listdir(self.client.client_cache.profiles_path)),\n sorted([\"default\", \"linux\", \"windows\"]))\n self.assertEqual(load(os.path.join(self.client.client_cache.profiles_path, \"linux\")).splitlines(),\n linux_profile.splitlines())\n self.assertEqual(load(os.path.join(self.client.client_cache.profiles_path, \"windows\")).splitlines(),\n win_profile.splitlines())\n conan_conf = ConanClientConfigParser(self.client.client_cache.conan_conf_path)\n self.assertEqual(conan_conf.get_item(\"log.run_to_output\"), \"False\")\n self.assertEqual(conan_conf.get_item(\"log.run_to_file\"), \"False\")\n self.assertEqual(conan_conf.get_item(\"log.level\"), \"10\")\n self.assertEqual(conan_conf.get_item(\"general.compression_level\"), \"6\")\n self.assertEqual(conan_conf.get_item(\"general.sysrequires_sudo\"), \"True\")\n self.assertEqual(conan_conf.get_item(\"general.cpu_count\"), \"1\")\n self.assertEqual(conan_conf.get_item(\"general.config_install\"), install_path)\n self.assertEqual(conan_conf.get_item(\"proxies.no_proxy\"), \"mylocalhost\")\n self.assertEqual(conan_conf.get_item(\"proxies.https\"), \"None\")\n self.assertEqual(conan_conf.get_item(\"proxies.http\"), \"http://user:pass@10.10.1.10:3128/\")\n self.assertEqual(\"#Custom pylint\",\n load(os.path.join(self.client.client_cache.conan_folder, \"pylintrc\")))\n\n def install_file_test(self):\n \"\"\" should install from a file in current dir\n \"\"\"\n zippath = self._create_zip()\n self.client.run('config install \"%s\"' % zippath)\n self._check(zippath)\n self.assertTrue(os.path.exists(zippath))\n\n def test_without_profile_folder(self):\n shutil.rmtree(self.client.client_cache.profiles_path)\n zippath = self._create_zip()\n self.client.run('config install \"%s\"' % zippath)\n self.assertEqual(sorted(os.listdir(self.client.client_cache.profiles_path)),\n sorted([\"linux\", \"windows\"]))\n self.assertEqual(load(os.path.join(self.client.client_cache.profiles_path, \"linux\")).splitlines(),\n linux_profile.splitlines())\n\n def install_url_test(self):\n \"\"\" should install from a URL\n \"\"\"\n\n def my_download(obj, url, filename, **kwargs): # @UnusedVariable\n self._create_zip(filename)\n\n with patch.object(Downloader, 'download', new=my_download):\n self.client.run(\"config install http://myfakeurl.com/myconf.zip\")\n self._check(\"http://myfakeurl.com/myconf.zip\")\n\n # repeat the process to check\n self.client.run(\"config install http://myfakeurl.com/myconf.zip\")\n self._check(\"http://myfakeurl.com/myconf.zip\")\n\n def install_repo_test(self):\n \"\"\" should install from a git repo\n \"\"\"\n\n folder = self._create_profile_folder()\n with tools.chdir(folder):\n self.client.runner('git init .')\n self.client.runner('git add .')\n self.client.runner('git config user.name myname')\n self.client.runner('git config user.email myname@mycompany.com')\n self.client.runner('git commit -m \"mymsg\"')\n\n self.client.run('config install \"%s/.git\"' % folder)\n self._check(\"%s/.git\" % folder)\n\n def reinstall_test(self):\n \"\"\" should use configured URL in conan.conf\n \"\"\"\n zippath = self._create_zip()\n self.client.run('config set general.config_install=\"%s\"' % zippath)\n self.client.run(\"config install\")\n self._check(zippath)\n\n def reinstall_error_test(self):\n \"\"\" should use configured URL in conan.conf\n \"\"\"\n error = self.client.run(\"config install\", ignore_error=True)\n self.assertTrue(error)\n self.assertIn(\"Called config install without arguments\", self.client.out)\n","sub_path":"conans/test/command/config_install_test.py","file_name":"config_install_test.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"203907321","text":"import tensorflow as tf\nimport models.inception_resnet_v1 as network\nimport os\nfrom sys import argv\nimport sys\n\nimage_size=160\ncentral_fraction = 0.875\nmodel_base_file_name = \"\"\n\ndef print_usage():\n print(\"Usage: \")\n print(\"python3 convert_facenet.py model_base=\")\n print(\" where is the base file name of the saved tensorflow model files\")\n print(\" For example if your model files are: \")\n print(\" facenet.index\")\n print(\" facenet.data-00000-of-00001\")\n print(\" facenet.meta\")\n print(\" then is 'facenet' and you would pass model_base=facenet\")\n\n\n# handle the arguments\n# return False if program should stop or True if args are ok\ndef handle_args():\n global model_base_file_name\n model_base_file_name = None\n for an_arg in argv:\n if (an_arg == argv[0]):\n continue\n\n elif (str(an_arg).lower() == 'help'):\n return False\n\n elif (str(an_arg).startswith('model_base=')):\n arg, val = str(an_arg).split('=', 1)\n model_base_file_name = str(val)\n print(\"model base file name is: \" + model_base_file_name)\n return True\n\n else:\n return False\n\n if (model_base_file_name == None or len(model_base_file_name) < 1):\n return False\n\n return True\n\n\n\n# This function is called from the entry point to do\n# all the work.\ndef main():\n\n if (not handle_args()):\n # invalid arguments exit program\n print_usage()\n return 1\n\n with tf.Graph().as_default():\n image = tf.placeholder(\"float\", shape=[1, image_size, image_size, 3], name='input')\n prelogits, _ = network.inference(image, 1.0, phase_train=False,bottleneck_layer_size=512)\n normalized = tf.nn.l2_normalize(prelogits, 1, name='l2_normalize')\n output = tf.identity(normalized, name='output')\n saver = tf.train.Saver(tf.global_variables())\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n print('Restoring ' + model_base_file_name)\n saver.restore(sess, model_base_file_name)\n\n # Save the network for fathom\n dir = os.path.dirname(model_base_file_name)\n dir = os.path.join(dir,'ncs')\n os.mkdir(dir)\n saver.save(sess,os.path.join(dir,'model'))\n\n\n# main entry point for program. we'll call main() to do what needs to be done.\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"src/movidius_face.py","file_name":"movidius_face.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"499745638","text":"#!/usr/bin/python27\n\nimport os, os.path\nimport sys\nimport time \nimport datetime\nimport multiprocessing\nimport subprocess \nimport random \n\n\nclass IP_MAN(multiprocessing.Process):\n\n def __init__(self, iface, n_req):\n multiprocessing.Process.__init__(self)\n self.HOSTS = {}; # a dictonary that holds the ips and their access time intervals \n self.READ_INT = 1; # time to wait before next log read \n self.BLOCKED_FILE = 'blocked.dat'; # a file that stores blocked ips \n self.IFACE = iface; # the interface specified in the [ --iface ] option\n self.N_REQ = n_req;\n \n def run(self):\n while 1:\n time.sleep(self.READ_INT);\n self.store_hosts('all.dat');\n self.check_hosts_time(self.HOSTS);\n self.HOSTS = {};\n\n # Store each host in a dictionary with its access time intervals\n # self.HOSTS\n def store_hosts(self, filename):\n if os.path.exists(filename):\n with open(filename, 'r+') as fp:\n contents = fp.readlines();\n contents.reverse();\n\n for line in contents:\n ip = ((line.split('\\n')[0].split(' - ')[1]).split(']:')[0])[1:];\n t_time = ((((line.split('\\n')[0].split(' - ')[0]).split(' [')[1]).split(' ')[1])[:-1]);\n\n if ip in self.HOSTS:\n self.HOSTS[ip].append(t_time);\n else:\n self.HOSTS[ip] = [];\n self.HOSTS[ip].append(t_time);\n\n\n # Check each host's last [ --limit ] access time intervals \n # and if the time difference is <= [ --limit ] [1 sec for each request] block the connection \n def check_hosts_time(self, hosts):\n for host in hosts:\n if len(hosts[host]) >= self.N_REQ:\n t = hosts[host][:self.N_REQ];\n now = ((datetime.datetime.now()).strftime('%H:%M')).split(':');\n to_sub = [ tt for tt in t if tt.split(':')[0] == now[0] and tt.split(':')[1] == now[1] ];\n\n if len(to_sub) == self.N_REQ:\n s1 = to_sub[0].split(':')[-1].split(',')[0];\n s2 = to_sub[-1].split(':')[-1].split(',')[0];\n\n if int(s1) - int(s2) < self.N_REQ:\n if self.is_blocked(host, self.BLOCKED_FILE):\n pass;\n else:\n subprocess.call(['./block.sh', host, self.IFACE]); \n self.store_blocked(host, self.BLOCKED_FILE); \n \n def is_blocked(self, ip, fp):\n if os.path.exists(fp):\n f = open(fp, 'r+');\n l = f.readlines();\n f.close();\n if ip+'\\n' in l:\n return True;\n\n def store_blocked(self, ip, f):\n if os.path.exists(f):\n m = 'a';\n else:\n m = 'w';\n f = open(f, m);\n f.write(ip+'\\n');\n f.close();\n\n\n# This class is responsible for the [all.dat] log file clearing \n# when it reaches N number of lines \nclass FLUSHER(multiprocessing.Process):\n def __init__(self, log_lines):\n multiprocessing.Process.__init__(self)\n self.LOG_LINES = log_lines;\n\n def run(self):\n while 1:\n self.clear_all_dat('all.dat');\n time.sleep(1.2);\n \n def clear_all_dat(self, file):\n if os.path.exists(file):\n f = open(file, 'r+');\n nl = len(f.readlines());\n if int(nl) >= int(self.LOG_LINES):\n f.truncate(0);\n\n","sub_path":"src/ip_man.py","file_name":"ip_man.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"98049149","text":"#!/usr/bin/env python3 \r\n# Name: Andrew Zarzar (azarzar) \r\n# Group Members: None\r\n\r\n'''\r\nRead a DNA string from user input and return a collapsed substring of embedded Ns to: {count}\r\n\r\nExample: \r\n input: AaNNNNNNGTC\r\noutput: AA{6}GTC\r\n\r\nAny lower case letters are converted to uppercase\r\n'''\r\nclass DNAstring (str):\r\n \r\n def length (self):\r\n return (len(self))\r\n \r\n def sift(self):\r\n dna = self\r\n dna = dna.lower()\r\n dna = dna.replace(\"a\", \"A\")\r\n dna = dna.replace(\"t\", \"T\")\r\n dna = dna.replace(\"c\", \"C\")\r\n dna = dna.replace(\"g\",\"G\")\r\n newDNA = self.purify(dna)\r\n return newDNA\r\n \r\n def purify(self, sif):\r\n dna = sif\r\n l = list(dna)\r\n count = 0\r\n nCount = 1\r\n while count < len(sif):\r\n c = l[count]\r\n d = str(l[count-1])\r\n if c.islower():\r\n l[count] = \"{\"+ str(nCount) +\"}\"\r\n if (count!=0) and (d == \"{\"+ str(nCount-1) +\"}\"): l[count-1] = \"\"\r\n count = count+1\r\n nCount = nCount+1\r\n else:\r\n nCount = 1\r\n count = count+1 \r\n return \"\".join(l)\r\n \r\n''' Get user DNA data and clean it up.''' \r\ndef main(): \r\n data = input('Enter DNA data: ')\r\n thisDNA = DNAstring (data)\r\n siftDNA = thisDNA.sift()\r\n print (\"\")\r\n print(\"seqCleaner does NOT remove special characters or numbers from the input.\\n\")\r\n print (\"Cleaned DNA data: \" + siftDNA)\r\nmain()\r\n\r\n\r\n\r\n#https://stackoverflow.com/questions/10953189/count-lower-case-characters-in-a-string\r\n # - provided guidance for implemenation of lowercase character identifier\r\n \r\n#https://stackoverflow.com/questions/41752946/replacing-a-character-from-a-certain-index\r\n # - provided guidance for replacing items in a list\r\n \r\n#https://stackoverflow.com/questions/19970532/how-to-check-a-string-for-a-special-character\r\n # - provided guidance for inplemenation of special character identification. (NOT IMPLEMENTED IN CODE ABOVE)\r\n ","sub_path":"seqclean(Nocomments).py","file_name":"seqclean(Nocomments).py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"441227667","text":"# def sample input user value ??\n\n# local value call in only def .\n# global value call in any where in def out def or otherwise any where ok call u user choice ..\n\ndef sample():\n\ta = int(input(\"A: \"))\n\tb = int(input(\"B: \"))\n\tsum = a + b\n\tprint(\"total sum : \",sum)\nsample()\n\n\n'''\nA: 5\nB: 9\ntotal sum : 14\n'''","sub_path":"python_program/def_input_user_arguments.py","file_name":"def_input_user_arguments.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"20741226","text":"#!flask/bin/python\n\nfrom flask import Flask, jsonify, request, g, abort, request\nfrom flask.ext.httpauth import HTTPBasicAuth\nfrom flask.ext.cors import CORS, cross_origin\nfrom itsdangerous import (TimedJSONWebSignatureSerializer\n as Serializer, BadSignature, SignatureExpired)\n\nimport mimetypes \nfrom bson import json_util\nfrom config import *\nimport json \nimport datetime\nimport os \nimport requests\nimport email\nimport traceback \nimport logging\nimport csv\nimport pandas as pd\nimport numpy as np\nimport sys\n\nimport smtplib\nimport mimetypes\nimport email\nimport email.mime.application\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"*\": {\"origins\": \"*\"} }, allow_headers='*', methods= ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'])\napp.secret_key = os.urandom(24)\napp.config[\"indexes\"] = {}\napp.config[\"articles\"] = []\n\n\n@app.before_first_request\ndef setup():\n indexes = {}\n with open('articles') as f:\n app.config[\"articles\"] = json.load(f)\n\n \n with open('indexes.csv', 'rb') as csvfile:\n _indexes = csv.reader(csvfile, delimiter=',')\n for r in _indexes:\n if r[0] == 'Date': \n r = [i.replace('\"',\"'\") for i in r]\n key = r[-1]#get the last element which is the name of the province/state\n indexes[key] = []\n del r[-1] #delete the last element since it was added on manually in the csv and would affect pandas df loading\n indexes[key].append(r)\n\n for k in indexes:\n app.config[\"indexes\"][k] = (pd.DataFrame(indexes[k][1:], columns=indexes[k][0])).set_index('Date')\n\n if not app.debug:\n # In production mode, add log handler to sys.stderr.\n app.logger.addHandler(logging.StreamHandler())\n app.logger.setLevel(logging.DEBUG)\n\n\n@app.route('/index', methods = ['GET'])\n@cross_origin()\ndef index():\n indexes = request.args['indexes'].split(',')\n df = pd.concat([app.config[\"indexes\"][ind] for ind in indexes], axis=1)\n df.index = pd.to_datetime(df.index, format=\"%m/%d/%Y\")\n df.sort_index(inplace=True)\n df.replace('', np.nan, inplace=True)\n df.where(pd.notnull(df), None, inplace=True)\n data = {'columns' : df.columns.tolist(),\n 'data' : df.reset_index().values.tolist()}\n return json.dumps(data, default=json_util.default), 200\n\n\n@app.route('/contact', methods = ['POST'])\n@cross_origin()\ndef contact():\n payload = {'secret': GRECAPTCHA, \n 'response': request.form['g-recaptcha-response'],\n 'remoteip' : request.remote_addr}\n r = requests.post('https://www.google.com/recaptcha/api/siteverify', params=payload)\n if not r.json()['success']:\n return jsonify(success=False),200\n\n msg = email.mime.Multipart.MIMEMultipart()\n msg['Subject'] = request.form['widget-contact-form-subject']\n msg['From'] = MAIL_USERNAME\n msg['To'] = MAIL_USERNAME\n body = \"\"\"\n Name: %s\n Email: %s\n\n Message: %s\n \"\"\" % (request.form['widget-contact-form-name'], request.form['widget-contact-form-email'],\n request.form['widget-contact-form-message'])\n body = email.mime.Text.MIMEText(body)\n msg.attach(body)\n s = smtplib.SMTP(host=MAIL_HOST, port=MAIL_PORT)\n s.login(MAIL_USERNAME,MAIL_PASSWORD)\n s.sendmail(msg['From'],msg['To'], msg.as_string())\n s.quit()\n return jsonify(success=True),200\n\n\n@app.route('/news', methods = ['GET'])\n@cross_origin()\ndef news():\n if 'article_id' in request.args:\n article_id = int(request.args['article_id'])\n for art in app.config['articles']:\n if art['id'] == article_id:\n return jsonify(art), 200\n else:\n return jsonify({'articles' : app.config['articles']}), 200\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"130193597","text":"# 출처 https://happy-obok.tistory.com/5\n# https://radimrehurek.com/gensim/models/ldamodel.html\n# https://wikidocs.net/30708\n\nfrom collections import Counter\nimport pickle, csv, codecs\nfrom gensim import corpora, models\nimport gensim\nfrom gensim.models import LdaModel\nfrom gensim.test.utils import datapath\n\nprint(\"loading token_words.csv\")\ndata_word = []\nwith codecs.open('noun_token_words_4.csv', 'r') as f:\n rdr = csv.reader(f)\n next(rdr)\n for i, line in enumerate(rdr):\n data_word.append(line)\n print(\"Complete loading\")\n\n\nid2word=corpora.Dictionary(data_word)\nid2word.filter_extremes(no_below = 10) #10회 이하로 등장한 단어는 삭제\ntexts = data_word\ncorpus=[id2word.doc2bow(text) for text in texts]\nprint(corpus[1])\n\nlda = LdaModel(corpus, num_topics=10, id2word=id2word)\n\ntemp_file = datapath(\"noun_model_2\")\nlda.save(temp_file)\n\nlda = LdaModel.load(temp_file)\n\n\ntopics = lda.print_topics(num_words=10)\nfor topic in topics:\n print(topic)\n\"\"\"\n\nmallet_path = 'mallet-2.0.8/bin/mallet'\nldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=10, id2word=id2word)\n\n\n# https://ratsgo.github.io/from%20frequency%20to%20semantics/2017/07/09/lda/\n# topic\nK=9\n\n\n# 각 토픽이 각 문서에 할당되는 횟수\n# Counter로 구성된 리스트\n# 각 Counter는 각 문서를 의미\nprint(\"counting documents topic\")\ndocument_topic_counts = [Counter() for _ in documents]\n\n# 각 단어가 각 토픽에 할당되는 횟수\n# Counter로 구성된 리스트\n# 각 Counter는 각 토픽을 의미\nprint(\"Preprosessing topic modelling\")\ntopic_word_counts = [Counter() for _ in range(K)]\n\n# 각 토픽에 할당되는 총 단어수\n# 숫자로 구성된 리스트\n# 각각의 숫자는 각 토픽을 의미함\ntopic_counts = [0 for _ in range(K)]\n\n# 각 문서에 포함되는 총 단어수\n# 숫자로 구성된 리스트\n# 각각의 숫자는 각 문서를 의미함\ndocument_lengths = list(map(len, documents))\n\n# 단어 종류의 수\ndistinct_words = set(word for document in documents for word in document)\nV = len(distinct_words)\n\n# 총 문서의 수\nD = len(documents)\n\ndef p_topic_given_document(topic, d, alpha=0.1):\n # 문서 d의 모든 단어 가운데 topic에 속하는\n # 단어의 비율 (alpha를 더해 smoothing)\n return ((document_topic_counts[d][topic] + alpha) /\n (document_lengths[d] + K * alpha))\n\ndef p_word_given_topic(word, topic, beta=0.1):\n # topic에 속한 단어 가운데 word의 비율\n # (beta를 더해 smoothing)\n return ((topic_word_counts[topic][word] + beta) /\n (topic_counts[topic] + V * beta))\n\ndef topic_weight(d, word, k):\n # 문서와 문서의 단어가 주어지면\n # k번째 토픽의 weight를 반환\n return p_word_given_topic(word, k) * p_topic_given_document(k, d)\n\ndef choose_new_topic(d, word):\n return sample_from([topic_weight(d, word, k) for k in range(K)])\n\nimport random\ndef sample_from(weights):\n # i를 weights[i] / sum(weights)\n # 확률로 반환\n total = sum(weights)\n # 0과 total 사이를 균일하게 선택\n rnd = total * random.random()\n # 아�� 식을 만족하는 가장 작은 i를 반환\n # weights[0] + ... + weights[i] >= rnd\n for i, w in enumerate(weights):\n rnd -= w\n if rnd <= 0:\n return i\n\n\nrandom.seed(0)\n\n\n\n# 각 단어를 임의의 토픽에 랜덤 배정\nprint(\"assigning word to topic in random\")\ndocument_topics = [[random.randrange(K) for word in document]\n for document in documents]\n\n# 위와 같이 랜덤 초기화한 상태에서\n# AB를 구하는 데 필요한 숫자를 세어봄\nfor d in range(D):\n for word, topic in zip(documents[d], document_topics[d]):\n document_topic_counts[d][topic] += 1\n topic_word_counts[topic][word] += 1\n topic_counts[topic] += 1\nprint(\"start topic modelling\")\nfor iter in range(3):\n print(iter)\n for d in range(D):\n for i, (word, topic) in enumerate(zip(documents[d],\n document_topics[d])):\n # 깁스 샘플링 수행을 위해\n # 샘플링 대상 word와 topic을 제외하고 세어봄\n document_topic_counts[d][topic] -= 1\n topic_word_counts[topic][word] -= 1\n topic_counts[topic] -= 1\n document_lengths[d] -= 1\n\n # 깁스 샘플링 대상 word와 topic을 제외한\n # 말뭉치 모든 word의 topic 정보를 토대로\n # 샘플링 대상 word의 새로운 topic을 선택\n new_topic = choose_new_topic(d, word)\n document_topics[d][i] = new_topic\n\n # 샘플링 대상 word의 새로운 topic을 반영해\n # 말뭉치 정보 업데이트\n document_topic_counts[d][new_topic] += 1\n topic_word_counts[new_topic][word] += 1\n topic_counts[new_topic] += 1\n document_lengths[d] += 1\n\npickle_list = [document_topics, document_topic_counts, topic_word_counts, topic_counts]\n\nf = open('document_topics.csv', 'w', newline=\"\")\nwr = csv.writer(f)\nfor word in document_topics:\n wr.writerow(word)\nf.close()\n\nwith open('document_topic.pickle','wb') as fw:\n pickle.dump(pickle_list, fw)\n print(\"dumping complete\")\n \n \n\"\"\"","sub_path":"topic_modelling_LDA.py","file_name":"topic_modelling_LDA.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"154900503","text":"# Задача - 1\n# Опишите несколько классов TownCar, SportCar, WorkCar, PoliceCar\n# У каждого класса должны быть следующие аттрибуты:\n# speed, color, name, is_police - Булево значение.\n# А так же несколько методов: go, stop, turn(direction) - которые должны сообщать,\n# о том что машина поехала, остановилась, повернула(куда)\n\n# Задача - 2\n# Посмотрите на задачу-1 подумайте как выделить общие признаки классов\n# в родительский и остальные просто наследовать от него.\n\nmoving_speed = 100\n\nclass Car:\n def __init__(self, speed=0, color=\"black\", name=\"car\", direction = 1,is_police=False):\n self._speed = speed\n self._color = color\n self._name = name\n self._is_police = is_police\n self._direction = direction\n\n def get_speed(self):\n return self._speed\n\n def get_color(self):\n return self._color\n\n def get_name(self):\n return self._name\n\n def get_is_police(self):\n return self._is_police\n\n def go(self):\n if self._speed == 0:\n self._speed = moving_speed * self._direction #имитируем движение - 2-e скорости: 0 - в покое и 100 - движение - что то типа передач\n print(f\"car {self._name} is going\")\n\n def stop(self):\n if self._speed != 0:\n self._speed = 0\n print(f\"car {self._name} is stoped\")\n\n def turn(self, direction):\n try:\n if self._speed != 0:\n raise ValueError(\"Speed is not 0!\")\n if direction != 1 and direction != -1:\n raise ValueError(\"direction m.b. 1 or -1\")\n self._direction = direction\n print(f\"direction is turned for {self._name} on {self._direction}\")\n except ValueError as err1:\n print(err1.args)\n except TypeError as err2:\n print(err2.args)\n\nclass TownCar(Car):\n def __init__(self, speed, color, name, direction):\n super().__init__(speed, color, name, direction)\n\nclass SportCar(Car):\n def __init__(self, speed, color, name, direction):\n super().__init__(speed, color, name, direction)\n\nclass WorkCar(Car):\n def __init__(self, speed, color, name, direction):\n super().__init__(speed, color, name, direction)\n\nclass PoliceCar(Car):\n def __init__(self, speed, color, name, direction):\n super().__init__(speed, color, name, direction,True)\n\n\ntownCar = TownCar(0,\"white\",\"Volkswagen\",1)\npoliceCar = PoliceCar(0,\"black\",\"Ferrari\",1)\n\nprint(townCar.get_color())\nprint(townCar.get_is_police())\n\nprint(policeCar.get_color())\nprint(policeCar.get_is_police())\n\ntownCar.go()\nprint(townCar.get_speed())\ntownCar.stop()\nprint(townCar.get_speed())\ntownCar.turn(-1)\n\npoliceCar.turn(-1)\npoliceCar.go()\nprint(policeCar.get_speed())\npoliceCar.stop()\nprint(policeCar.get_speed())\n\n\n","sub_path":"Lesson6/python-1-lesson6-easy.py","file_name":"python-1-lesson6-easy.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"451734006","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nModules for Gamma model\n- MultiHeadAttention\n- FeedForward\n- CRF\nCreated on 2020/5/15 \n\"\"\"\n\n__author__ = \"Yihang Wu\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .attention import build_attention\n\n\nclass MultiHeadAttention(nn.Module):\n\n def __init__(self, model_dim=512, num_heads=8, dropout_rate=0.0, attention_type='scaled_dot'):\n super().__init__()\n\n assert model_dim % num_heads == 0, 'model_dim should be devided by num_heads'\n\n self.h_size = model_dim\n self.num_heads = num_heads\n self.head_h_size = model_dim // num_heads\n\n self.linear_q = nn.Linear(self.h_size, self.h_size)\n self.linear_k = nn.Linear(self.h_size, self.h_size)\n self.linear_v = nn.Linear(self.h_size, self.h_size)\n\n self.attention = build_attention(attention_type, q_dim=self.head_h_size, k_dim=self.head_h_size)\n self.dropout = nn.Dropout(dropout_rate)\n self.lnorm = nn.LayerNorm(model_dim)\n\n def forward(self, q, k, v, attn_mask=None):\n batch_size = q.size(0)\n\n # Residual\n residual = q\n\n # Linear projection\n q = self.linear_q(q)\n k = self.linear_k(k)\n v = self.linear_v(v)\n\n # Form multi heads\n q = q.view(self.num_heads * batch_size, -1, self.head_h_size) # (h * B, T_q, D / h)\n k = k.view(self.num_heads * batch_size, -1, self.head_h_size) # (h * B, T_k, D / h)\n v = v.view(self.num_heads * batch_size, -1, self.head_h_size) # (h * B, T_v, D / h)\n\n if attn_mask is not None:\n attn_mask = attn_mask.repeat(self.num_heads, 1, 1) # (h * B, T_q, T_k)\n\n context, attention = self.attention(q, k, v, attn_mask=attn_mask)\n # context: (h * B, T_q, D_v) attention: (h * B, T_q, T_k)\n\n # Concatenate heads\n context = context.view(batch_size, -1, self.h_size) # (B, T_q, D)\n\n # Dropout\n output = self.dropout(context) # (B, T_q, D)\n\n # Residual connection and Layer Normalization\n output = self.lnorm(residual + output) # (B, T_q, D)\n\n return output, attention\n\n\nclass FeedForward(nn.Module):\n\n def __init__(self, model_dim=512, hidden_dim=2048, dropout_rate=0.0):\n super().__init__()\n\n self.model_dim = model_dim\n self.hidden_dim = hidden_dim\n self.dropout_rate = dropout_rate\n\n self.linear1 = nn.Linear(self.model_dim, self.hidden_dim)\n self.linear2 = nn.Linear(self.hidden_dim, self.model_dim)\n self.norm = nn.LayerNorm(model_dim)\n self.dropout = nn.Dropout(dropout_rate)\n\n def forward(self, x):\n output = self.linear2(F.relu(self.linear1(x)))\n\n output = self.dropout(output)\n\n output = self.norm(output + x)\n return output\n\n\nclass CRF(nn.Module):\n\n def __init__(self, num_entities, pad_idx, bos_idx, eos_idx, device):\n super().__init__()\n self.num_entities = num_entities\n self.bos_idx = bos_idx\n self.eos_idx = eos_idx\n self.pad_idx = pad_idx\n self.cuda = device == 'cuda'\n\n self.transitions = nn.Parameter(torch.empty(self.num_entities, self.num_entities)) # treated as Parameter\n\n self._init_transitions()\n\n def forward(self, emissions, entities, mask=None):\n \"\"\"Forward logic that computes the negative logarithm likelihood\n\n Args:\n emissions (torch.Tensor): emission matrix, which should be the output of previous layer (B, T, num_entities)\n entities (torch.LongTensor): given entities sequence (B, T)\n mask (torch.BoolTensor): indicates valid positions within each sequence in the batch (B, T)\n\n Returns:\n (torch.Tensor): neg-log-likelihood as loss, mean over batch (1,)\n\n \"\"\"\n\n if mask is None:\n mask = torch.ones(emissions.shape[:2], dtype=torch.float, device='cuda' if self.cuda else 'cpu').bool()\n\n score = self._score(emissions, entities, mask) # (B,)\n partition = self._log_partition(emissions, mask) # (B,)\n return -torch.mean(score - partition) # (1,)\n\n def _init_transitions(self):\n nn.init.uniform_(self.transitions, -0.1, 0.1)\n\n # Enforce contraints with a big negative number (from 'row' to 'column')\n # so exp(-10000) will tend to zero\n self.transitions.data[:, self.bos_idx] = -10000 # no transition to BOS\n self.transitions.data[self.eos_idx, :] = -10000 # no transition from eos (except to PAD)\n self.transitions.data[self.pad_idx, :] = -10000 # no transition from pad (except to PAD)\n self.transitions.data[:, self.pad_idx] = -10000 # no transition to pad (except from PAD)\n self.transitions.data[self.pad_idx, self.pad_idx] = 0\n self.transitions.data[self.pad_idx, self.eos_idx] = 0\n\n def _score(self, emissions, entities, mask):\n \"\"\"\n\n Args:\n emissions (torch.Tensor): emission matrix, which should be the output of previous layer (B, T, num_entities)\n entities (torch.LongTensor): given entities sequence (B, T)\n mask (torch.BoolTensor): indicates valid positions within each sequence in the batch (B, T)\n\n Returns:\n torch.Tensor: scores of each entity sequence in current batch: (B,)\n\n \"\"\"\n batch_size, seq_len = entities.shape\n\n scores = torch.zeros(batch_size, dtype=torch.float, device='cuda' if self.cuda else 'cpu')\n\n first_ents = entities[:, 0] # first entities (B,)\n last_valid_idx = mask.sum(1) - 1 # (B,)\n last_ents = entities.gather(1, last_valid_idx.unsqueeze(1)).squeeze() # last entities (B,)\n\n t_scores = self.transitions[self.bos_idx, first_ents]\n\n e_scores = emissions[:, 0].gather(1, first_ents.unsqueeze(1)).squeeze() # (B,)\n\n scores += e_scores + t_scores\n\n # For each remaining entities(words)\n for i in range(1, seq_len):\n prev_ents = entities[:, i - 1] # previous entities\n curr_ents = entities[:, i] # current entities\n\n # Calculate emission and transition scores\n e_scores = emissions[:, i].gather(1, curr_ents.unsqueeze(1)).squeeze() # (B,)\n t_scores = self.transitions[prev_ents, curr_ents] # (B,)\n\n # Apply masking --- If position is PAD, then the contributing score should be 0\n e_scores = e_scores * mask[:, i]\n t_scores = t_scores * mask[:, i]\n\n scores += e_scores + t_scores\n\n # Transition score from last entity to EOS\n scores += self.transitions[last_ents, self.eos_idx]\n\n return scores # (B,)\n\n def _log_partition(self, emissions, mask):\n \"\"\"\n\n Args:\n emissions (torch.Tensor): emission matrix, which should be the output of previous layer (B, T, num_entities)\n mask (torch.BoolTensor): indicates valid positions within each sequence in the batch (B, T)\n\n Returns:\n (torch.Tensor): partition scores for current batch (B,)\n \"\"\"\n\n batch_size, seq_len, num_ents = emissions.shape\n\n # Antilog of partition part of score, which will be finally applied a logsumexp()\n alphas = self.transitions[self.bos_idx, :].unsqueeze(0) + emissions[:, 0] # (B, num_ents)\n\n for i in range(1, seq_len):\n alpha_t = []\n\n for ent in range(num_ents):\n # Emission scores for current entity, broadcast to entity-wise\n e_scores = emissions[:, i, ent].unsqueeze(1) # (B, 1)\n\n # Transition scores for current entity, broadcast to batch-wise\n t_scores = self.transitions[:, ent].unsqueeze(0) # (1, num_entities)\n\n # Combine current scores with previous alphas (in log space: add instead of multiply)\n scores = e_scores + t_scores + alphas # (B, num_entities)\n\n alpha_t.append(torch.logsumexp(scores, dim=1)) # inner (B,)\n\n new_alphas = torch.stack(alpha_t, dim=0).t() # (B, num_entities)\n\n masking = mask[:, i].int().unsqueeze(1) # (B, 1)\n alphas = masking * new_alphas + (1 - masking) * alphas\n\n # Transition scores from last entity to EOS\n end_scores = alphas + self.transitions[:, self.eos_idx].unsqueeze(0) # (B, num_entities)\n\n return torch.logsumexp(end_scores, dim=1)\n\n def viterbi_decode(self, emissions, mask):\n \"\"\"Find the most probable entity sequence by applying viterbi decoding\n\n Args:\n emissions (torch.Tensor): emission matrix, which should be the output of previous layer (B, T, num_entities)\n mask (torch.BoolTensor): indicates valid positions within each sequence in the batch (B, T)\n\n Returns:\n (tuple): tuple containing:\n (torch.Tensor): viterbi score for each sequence in current batch (B,).\n (list[list[int]]): best sequences of entities of this batch, representing in indexes (B, *)\n\n \"\"\"\n batch_size, seq_len, num_ents = emissions.shape\n\n alphas = self.transitions[self.bos_idx, :].unsqueeze(0) + emissions[:, 0] # (B, num_ents)\n\n backpointers = []\n\n for i in range(1, seq_len):\n alpha_t = []\n backpointers_t = []\n\n for ent in range(num_ents):\n # Emission scores for current entity, broadcast to entity-wise\n e_scores = emissions[:, i, ent].unsqueeze(1) # (B, 1)\n\n # Transition scores for current entity, broadcast to batch-wise\n t_scores = self.transitions[:, ent].unsqueeze(0) # (1, num_entities)\n\n # Combine current scores with previous alphas (in log space: add instead of multiply)\n scores = e_scores + t_scores + alphas # (B, num_entities)\n\n # Find the highest score and the entity associated with it\n max_scores, max_ents = torch.max(scores, dim=-1)\n\n # Add the max score for current entity\n alpha_t.append(max_scores) # inner: (B,)\n\n # Add the corresponding entity to backpointers\n backpointers_t.append(max_ents) # backpointers_t finally (num_entities, B)\n\n new_alphas = torch.stack(alpha_t, dim=0).t() # (B, num_entities)\n\n masking = mask[:, i].int().unsqueeze(1) # (B, 1)\n alphas = masking * new_alphas + (1 - masking) * alphas\n\n backpointers.append(backpointers_t) # finally (T-1, num_entities, B)\n\n # Transition scores from last entity to EOS\n end_scores = alphas + self.transitions[:, self.eos_idx].unsqueeze(0) # (B, num_entities)\n\n # Final most probable score and corresponding entity\n max_final_scores, max_final_ents = torch.max(end_scores, dim=-1) # (B,)\n\n # Decode the best sequence for current batch\n # Follow the backpointers to find the best sequence of entities\n best_seqs = []\n emission_lens = mask.sum(dim=1) # (B,)\n\n for i in range(batch_size):\n sample_len = emission_lens[i].item()\n\n sample_final_entity = max_final_ents[i].item()\n\n sample_backpointers = backpointers[: sample_len - 1]\n\n best_path = [sample_final_entity]\n\n best_entity = sample_final_entity\n\n for backpointers_t in reversed(sample_backpointers):\n best_entity = backpointers_t[best_entity][i].item()\n best_path.insert(0, best_entity)\n\n best_seqs.append(best_path) # best_seqs finally (B, *)\n\n return max_final_scores, best_seqs\n","sub_path":"ner/gamma/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":11618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"164912235","text":"import requests\nfrom bs4 import BeautifulSoup\n\nimport time\nfrom time import localtime, strftime, mktime\n\nimport codecs\n\nimport smtplib\nfrom email.mime.text import MIMEText\n\nimport sys\n\nsys.path.insert(0, '/home/ybbaigo/one/codeSnippet')\nimport python\npython.init()\n\nwhile True:\n fileName = \"netease\" + strftime(\"@%Y-%m-%d.%H:%M:%S\", localtime())\n \n dataFile = codecs.open(fileName, 'w', 'utf-8')\n \n url = 'http://caipiao.163.com/order/jclq/'\n result = requests.get(url)\n encoded = result.text.encode(\"utf-8\", 'ignore')\n soup = BeautifulSoup(encoded) \n tables = soup.find_all(\"tbody\") \n for rows in tables[0].contents:\n \n lTeam = rows.name == \"tr\" and rows.attrs.has_key(\"teamname\") == True and rows.attrs[\"teamname\"] == \"NBA\"\n rTeam = rows.name == \"tr\" and len(rows.attrs) == 0\n \n if lTeam or rTeam:\n for row in rows.contents:\n if row.name == \"td\" and len(row.attrs) == 0:\n if row.contents[0].name == \"a\":\n dataFile.write(row.contents[0].attrs[\"title\"] + '\\t')\n else:\n dataFile.write(row.contents[0] + '\\t')\n \n if row.name == \"td\" and row.attrs.has_key(\"class\") and row.attrs[\"class\"][0] == \"bidCounts\":\n dataFile.write(row.contents[0].strip() + '\\t')\n \n if row.name == \"td\" and row.attrs.has_key(\"class\") and row.attrs[\"class\"][0] == \"btn_box\":\n dataFile.write(row.contents[0].contents[0][0:2] + '\\t')\n dataFile.write(row.contents[0].contents[0][3:] + '\\n')\n \n dataFile.close() \n\n dataFile = open(fileName, 'rb')\n msg = MIMEText(dataFile.read())\n dataFile.close()\n\n msg['Subject'] = 'Daily Report'\n msg['From'] = \"ybbaigo@gmail.com\"\n msg['To'] = \"ybbaigo@gmail.com\"\n\n s = smtplib.SMTP('smtp.gmail.com', 587)\n s.ehlo()\n s.starttls()\n s.login(\"ybbaigo@gmail.com\", \"Hello196\")\n s.sendmail(\"ybbaigo@gmail.com\", \"ybbaigo@gmail.com\", msg.as_string())\n s.close()\n python.logging.info('Successfully sent mail') \n\n time.sleep(86400)\n\n","sub_path":"nba/data/online/nba.extraction.online.py","file_name":"nba.extraction.online.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"62108999","text":"lst = []\nn = int(input('so phan tu: '))\nfor i in range(n):\n\tlst.append(int(input()))\nanswer = []\nfor v in lst:\n\tif v % 5 == 0:\n\t\tanswer.append(v)\nif len(answer) == 0:\n\tanswer = [0]\nprint(answer)","sub_path":"lab2/list5.py","file_name":"list5.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"117578718","text":"#! python3\n# 2048.py - 2048 is a simple game where you combine tiles by sliding them up, \n# down, left, or right with the arrow keys. You can actually get a fairly high \n# score by repeatedly sliding in an up, right, down, and left pattern over and \n# over again. Write a program that will open the game at \n# https://gabrielecirulli.github.io/2048/ and keep sending up, right, down, and \n# left keystrokes to automatically play the game.\n\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nbrowser = webdriver.Firefox()\nbrowser.get('https://gabrielecirulli.github.io/2048/')\n\n# Wait a few seconds to dismiss the stupid cookie message\ntime.sleep(5)\nbrowser.find_element_by_tag_name('.cookie-notice-dismiss-button').click()\n\n# Find the gameboard\ngameBoard = browser.find_element_by_tag_name('html')\n\nwhile True:\n gameBoard.send_keys(Keys.UP)\n gameBoard.send_keys(Keys.RIGHT)\n gameBoard.send_keys(Keys.DOWN)\n gameBoard.send_keys(Keys.LEFT)\n\n # if the game is over, click the retry button\n retryButton = browser.find_element_by_tag_name('.retry-button')\n if retryButton.location['x'] > 0:\n retryButton.click()","sub_path":"ch11/2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"326847607","text":"'''\r\n\r\nDefiniamo adiacenti di un pixel p di un immagine i pixel adiacenti a p in orizzontale o in verticale.\r\nSe un pixel e' sul bordo dell'immagine il suo vicinato non comprende i pixel non contenuti nell'immagine.\r\nIl pixel dell'immagine con coordinate(x,y) ha dunque come adiacenti i pixel \r\ncon coordinate (x-1,y),(x+1,y),(x,y-1),(x,y+1) appartenenti all'immagine. \r\n \r\nDefiniamo connessi due pixel se e' possibile dall'uno raggiungere l'altro spostandosi solo su \r\npixel adiacenti e dello stesso colore (ovviamente perche' cio' sia possobile e' necessario \r\nche i due pixel abbiano lo stesso colore).\r\n\r\nPer caricare e salvare immagini PNG usate le funzioni load e save che abbiamo preparato nel modulo immagini.py .\r\n\r\nScrivere una funzione ricolora(fname, lista, fnameout) che presi:\r\n- il percorso di un file che contiene un'immagine in formato PNG\r\n- una lista di quadruple del tipo (x,y,c1,c2) dove x e y sono coordinate di un pixel dell'immagine e c1 e c2 due triple colore RGB\r\n- il percorso di un file (fnameout) da creare\r\nlegge l'immagine in fname, esegue un'operazione di ricolorazione di alcuni pixel dell'immagine e \r\nregistra l'immagine ricolorata nel file fnameout.\r\n\r\nL'operazione di ricolorazione e' la seguente. Per ciascuna delle quadruple (x,y,c1,c2) della lista (nell'ordine), \r\n- tutti i pixel connessi al pixel di coordinate (x,y) nell'immagine vanno ricolorati col colore c1, \r\n- tutti i pixel del perimetro (che si trovano sul 'bordo') della zona che si e' appena colorata devono essere ricolorati col colore c2.\r\nIl perimetro della zona colorata è l'insieme dei pixel che non hanno tutti e 4 i vicini che fanno parte della zona ricolorata \r\n(ovvero almeno uno è di un colore diverso da quello che si sta ricolorando oppure almeno uno non esiste perchè sarebbe fuori dall'immagine)\r\n\r\nSi consideri ad esempio l'immagine 'I1.png', l'invocazione di ricolora('I1.png',[(10,10,(255,0,0), (0,0,255))],’OUT1.png')\r\nprodurra' l'immagine 'OUT1.png' identica all'immagine di partenza se non per il fatto che,\r\n tutti i pixel adiacenti al pixel di coordinate (10,10) (e di colore verde), verranno ricolorati \r\n di rosso ((255,0,0)), mentre i pixel sul bordo della zona inizialmente verde vengono ricolorati di blu.\r\n\r\nPer ciascuna area ricolorata bisogna inoltre calcolare area interna e perimetro, che sono definite come segue:\r\n- l'area interna e' il numero di pixel ricolorati con il colore c1\r\n- il perimetro è il numero di pixel ricolorati con il colore c2\r\n\r\nLa funzone deve tornare la lista di coppie (area interna, perimetro) nello stesso ordine in cui sono state colorate le aree.\r\n \r\nPer altri esempi vedere il file grade03.txt \r\n'''\r\n\r\nfrom immagini import *\r\n#from IPython.display import Image, display\r\n \r\ndef ricolora(fname, lista, fnameout):\r\n img=load(fname)\r\n# display(Image(fname))\r\n lc=[]\r\n for t in lista:\r\n lc,img=passo(t,img,lc)\r\n\r\n save(img,fnameout)\r\n# display(Image(fnameout))\r\n return lc\r\n \r\n \r\ndef passo(t,img,lc): \r\n y=t[0]\r\n x=t[1]\r\n c1=t[2]\r\n c2=t[3]\r\n c=img[x][y]\r\n dev=0\r\n ia=set()\r\n ip=set()\r\n ia.add((x,y))\r\n itest=ia.copy()\r\n gt=ia.copy()\r\n while itest!=set():\r\n for el in itest:\r\n if inside(img,el[0]-1,el[1]) and img[el[0]-1][el[1]]==c:\r\n ia.add((el[0]-1,el[1]))\r\n else:\r\n ip.add((el[0],el[1]))\r\n \r\n if inside(img,el[0],el[1]+1) and img[el[0]][el[1]+1]==c:\r\n ia.add((el[0],el[1]+1))\r\n else:\r\n ip.add((el[0],el[1]))\r\n \r\n if inside(img,el[0]+1,el[1]) and img[el[0]+1][el[1]]==c:\r\n ia.add((el[0]+1,el[1]))\r\n else:\r\n ip.add((el[0],el[1])) \r\n \r\n if inside(img,el[0],el[1]-1) and img[el[0]][el[1]-1]==c:\r\n ia.add((el[0],el[1]-1))\r\n else:\r\n ip.add((el[0],el[1]))\r\n \r\n itest=(ia-gt)\r\n gt=ia.copy()\r\n \r\n for el in ia:\r\n img[el[0]][el[1]]=c1\r\n for el in ip:\r\n img[el[0]][el[1]]=c2\r\n p=len(ip)\r\n a=len(ia)-p\r\n lc=lc+[(a,p)] \r\n \r\n return lc,img\r\n \r\n \r\ndef righe(img) : return len(img)\r\ndef colonne(img) : return len(img[0])\r\n \r\ndef inside(img, x, y):\r\n return 0 <= x < righe(img) and 0 <= y < colonne(img) \r\n\r\n \r\n#ricolora('I6.png',[(200,200,(255,255,0),(255,255,0))],'test10.png') ","sub_path":"students/1817203/homework03/program03.py","file_name":"program03.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"51498727","text":"from django.conf.urls import url,include,patterns\nfrom musicsharing import views\nfrom postman.views import WriteView\nfrom django.conf.urls import (\nhandler400, handler403, handler404, handler500\n)\n\nhandler404 = 'musicsharing.views.page_not_found'\nhandler500 = 'musicsharing.views.internal_server_error'\nhandler403 = 'musicsharing.views.forbidden'\nhandler400 = 'musicsharing.views.bad_request'\n\nurlpatterns = patterns('postman.views',\n url(r'^messages/write/(?:(?P[^/#]+)/)?$',\n WriteView.as_view(autocomplete_channels=('user')),\n name='write')\n\t) + [\n\t\n\t\t# player\n\turl(r'^$',views.home,name='home'),\n\turl(r'^upload$',views.upload),\n\turl(r'^get_lyric/(?P.+)$',views.get_lyric),\n\turl(r'^music/(?P.+)$',views.get_audio),\n\turl(r'^get_audio_index$',views.get_audio_index,name='all_music'),\n\turl(r'^picture/(?P.+)$',views.get_picture),\n\n\t# single song\n\n\turl(r'^remove-song-repo$',views.remove_song_repo),\n\n\t# profile\n\turl(r'^profile/(?P.*)$',views.profile,name='profile'),\n\turl(r'^edit-profile$',views.edit_profile),\n\turl(r'^get-profile-picture/(?P\\d+)$',views.get_profile_picture),\n\n\t# list\n\turl(r'^playlist$',views.playlist,name='playlist'),\n\turl(r'^edit-playlist$',views.edit_playlist),\n\turl(r'^manage-songs$',views.manage_songs,name='manage_songs'),\n\turl(r'^create-list$',views.create_list),\n\turl(r'^get-list/(?P-?\\d+)/(?P.*)$',views.get_list),\n\turl(r'^delete-list$',views.delete_list),\n\turl(r'^get-list-picture/(?P.+)$',views.get_list_picture),\n\turl(r'^get-list-name$',views.get_list_name),\n\n\t# song in list\n\turl(r'^delete-song$',views.delete_song),\n\turl(r'^add-song$',views.add_song),\n\n\t# search\n\n\turl(r'^search/$',views.search),\n\n\t# friend\n\turl(r'^friend-stream$',views.friend_stream,name='friend_stream'),\n\turl(r'^follow/(?P.+)$',views.follow),\n\turl(r'^unfollow/(?P.+)$',views.unfollow),\n\turl(r'^my-friend$',views.my_friend),\n\n\n\t# post\n\turl(r'^post$',views.post),\n\n\t#comment\n\turl(r'^comment$',views.comment),\n\n\t# third party package\n\turl(r'messages/',include('postman.urls',namespace='postman',app_name='postman')),\n\turl(r'notifications/',include('pinax.notifications.urls')),\n\turl(r'^ajax_select/', include('ajax_select.urls')),\n\turl(r'^accounts/',include('allauth.urls')),\n\n\t\n] \n\n\n","sub_path":"musicsharing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"351292069","text":"from data.capture.capture_dataset_utils import *\n\n# preset for different type of dataset\ndata_meta_dict = {\n 'bundle': {\n 'calib': 'calibration.txt',\n 'frame_list': 'bundle.list.txt',\n 'recon': 'bundle'\n },\n 'yfcc': {\n 'calib': 'recaled_calibration.txt',\n 'frame_list': 'raw_images.list.txt',\n 'recon': 'bundle.out',\n },\n '1dsfm': {\n 'calib': 'calibration.txt',\n 'frame_list': 'ImageList.txt',\n 'recon': 'gt_bundle.out',\n }\n}\n\n\ndef filtering_edge_cache(edge_cache: dict, num_nodes, verbose=False):\n filtered_edge_cache = dict()\n filtered_inout_mat = np.zeros((num_nodes, num_nodes))\n\n for key, val in edge_cache.items():\n Rt = val['Rt']\n if np.abs(Rt[0, 0]) < 1e-4 and np.abs(Rt[1, 1]) < 1e-4 and np.abs(Rt[2, 2]) < 1e-4:\n continue\n\n if np.isnan(Rt).sum() > 1 or np.isinf(Rt).sum() > 1:\n continue\n\n filtered_edge_cache[key] = val\n\n tokens = key.split('-')\n n1, n2 = int(tokens[0]), int(tokens[1])\n filtered_inout_mat[n1, n2] = 1\n filtered_inout_mat[n2, n1] = 1\n\n if verbose:\n print('[Filtered] %d / %d' % (len(filtered_edge_cache), len(edge_cache)))\n return filtered_edge_cache, filtered_inout_mat\n\n\nclass CaptureDataset(Dataset):\n\n def __init__(self, dataset_dir, dataset_list, img_lmdb_paths=None,\n node_edge_lmdb_path=None,\n img_max_dim=480,\n sampling_num_range=[100, 500],\n sub_graph_nodes=24,\n sample_res_cache=None,\n sampling_undefined_edge=False,\n load_img=True,\n load_keypt_match=False,\n load_node_edge_feat=False,\n outlier_edge_thres_deg=None,\n transform_func='default'):\n\n self.num_dataset = len(dataset_list)\n self.dataset_dir = dataset_dir\n self.sampling_num_range = sampling_num_range\n self.sub_graph_nodes = sub_graph_nodes\n self.img_max_dim = img_max_dim\n self.sampling_undefined_edge = sampling_undefined_edge\n self.load_img = load_img\n self.load_keypt_match = load_keypt_match\n self.load_node_edge_feat = load_node_edge_feat\n self.use_lmdb = False\n if outlier_edge_thres_deg is None:\n print('[Capture Dataset] Use default outlier edge thres = 50 deg')\n self.outlier_edge_thres_deg = 50\n else:\n print('[Capture Dataset] Use configed outlier edge thres = %d deg' % outlier_edge_thres_deg)\n self.outlier_edge_thres_deg = outlier_edge_thres_deg\n\n if self.load_node_edge_feat is True:\n if node_edge_lmdb_path is None:\n raise Exception('Can not found node edge feature lmdb: %s' % node_edge_lmdb_path)\n self.node_feat_lmdb = LMDBModel(node_edge_lmdb_path)\n node_edge_meta_path = node_edge_lmdb_path.split('.lmdb')[0] + '.bin'\n with open(node_edge_meta_path, 'rb') as f:\n self.edge_feat_dict, self.node_feat_meta_dict = pickle.load(f)\n f.close()\n\n if self.load_img is True and img_lmdb_paths is not None:\n self.use_lmdb = True\n self.lmdb_db = LMDBModel(img_lmdb_paths[0])\n self.lmdb_meta = pickle.load(open(img_lmdb_paths[1], 'rb'))\n\n self.transform_func = transform_func\n if self.transform_func == 'default':\n self.transform_func = transforms.Compose([transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])])\n\n # read image list and calibration ------------------------------------------------------------------------------\n self.frame_list = {}\n self.K = {}\n self.dataset_names = []\n for ds in dataset_list:\n dataset_name = ds['name']\n self.dataset_names.append(dataset_name)\n\n # frame-list\n bundle_prefix = ds['bundle_prefix']\n frame_list = read_image_list(\n os.path.join(dataset_dir, dataset_name, data_meta_dict[bundle_prefix]['frame_list']))\n self.frame_list[dataset_name] = frame_list\n\n # camera calibration\n K, img_dim = read_calibration(\n os.path.join(dataset_dir, dataset_name, data_meta_dict[bundle_prefix]['calib']))\n self.K[dataset_name] = K\n\n # read camera extrinsic ----------------------------------------------------------------------------------------\n self.Es = {}\n\n self.inout_mat = {}\n self.covis_map = {}\n self.edge_local_feat_cache = {}\n self.total_sample_num = 0\n\n max_scene_edges = 0 # determine the max edges for ratio sampling\n min_scene_edges = 1400000\n print('[Captured dataset Init] load in. and out. edges')\n z_flip = np.diag([1, 1, -1])\n for ds in tqdm(dataset_list):\n dataset_name = ds['name']\n bundle_prefix = ds['bundle_prefix']\n\n # read camera poses\n Es, _ = read_poses(os.path.join(dataset_dir, dataset_name, data_meta_dict[bundle_prefix]['recon']))\n self.Es[dataset_name] = Es\n\n # graph connectivity and inlier/outlier marker\n inoutMat = np.load(os.path.join(dataset_dir, dataset_name, 'inoutMat.npy'))\n covis_map = np.load(os.path.join(dataset_dir, dataset_name, 'covis.npy'))\n\n # read edge cache (Rt)\n if self.load_keypt_match:\n with open(os.path.join(dataset_dir, dataset_name, 'edge_feat_pos_cache.bin'), 'rb') as f:\n edge_feat_pos_cache = pickle.load(f)\n f.close()\n else:\n with open(os.path.join(dataset_dir, dataset_name, 'edge_rt_cache.bin'), 'rb') as f:\n edge_feat_pos_cache = pickle.load(f)\n f.close()\n edge_feat_pos_cache, inoutMat = filtering_edge_cache(edge_feat_pos_cache, inoutMat.shape[0])\n self.edge_local_feat_cache[dataset_name] = edge_feat_pos_cache\n self.inout_mat[dataset_name] = inoutMat\n self.covis_map[dataset_name] = inoutMat\n\n num_edges = len(edge_feat_pos_cache)\n if num_edges > max_scene_edges:\n max_scene_edges = num_edges\n if num_edges < min_scene_edges:\n min_scene_edges = num_edges\n\n if min_scene_edges * 30 < max_scene_edges:\n # sampling ratio from the scene has most edges should be clamped.\n max_scene_edges = 30 * min_scene_edges\n\n \"\"\" Sampling ---------------------------------------------------------------------------------------------------\n \"\"\"\n self.edge_sampler = {}\n self.samples = [] # (dataset_id, sub-graph sample_id)\n\n if sample_res_cache is None or not os.path.exists(sample_res_cache):\n\n print('[Captured dataset Init] sampling sub_graphs')\n for ds_id, ds in enumerate(dataset_list):\n dataset_name = ds['name']\n edge_feat_pos_cache = self.edge_local_feat_cache[dataset_name]\n\n n_Cameras = len(self.Es[dataset_name])\n inoutMat = self.inout_mat[dataset_name]\n # edge_feat_pos_cache = self.edge_local_feat_cache[dataset_name]\n for i in range(n_Cameras):\n for j in range(n_Cameras):\n if ((\"%d-%d\" % (i, j)) in edge_feat_pos_cache or\n (\"%d-%d\" % (j, i)) in edge_feat_pos_cache):\n inoutMat[i, j] = 1\n # for i in range(n_Cameras):\n # for j in range(n_Cameras):\n # if (\"%d-%d\" % (i, j) not in edge_feat_pos_cache) and (\"%d-%d\" % (j, i) not in edge_feat_pos_cache):\n # inoutMat[i, j] = 0\n num_edges = len(self.edge_local_feat_cache[dataset_name])\n\n # determine sampling number based on ratio of edges among other scenes\n sample_ratio = float(num_edges) / float(max_scene_edges)\n print('%s: Sampling Ratio: %.2f' % (dataset_name, sample_ratio))\n sample_num = int(sampling_num_range[1] * sample_ratio)\n if sample_num < sampling_num_range[0]:\n sample_num = sampling_num_range[0]\n if sample_num > sampling_num_range[1]:\n sample_num = sampling_num_range[1]\n\n # sampling\n gen = SamplingGenerator(n_Cameras, inoutMat)\n gen.setSamplingSize(sub_graph_nodes)\n gen.setSamplingNumber(sample_num)\n gen.generation(\n use_undefine=self.sampling_undefined_edge, get_max_node=False)\n\n print(\"test inoutmat\")\n for edges in gen.sampling_edge:\n flag = False\n for edge in edges:\n\n if (\"%d-%d\" % (edge[0], edge[1]) in edge_feat_pos_cache) or (\n \"%d-%d\" % (edge[1], edge[0]) in edge_feat_pos_cache):\n continue\n else:\n flag = True\n if flag:\n print(\"bad\")\n\n filtered_sampled_num = len(gen.sampling_node)\n print('[Captured dataset Init] %s: (filtered: %d, all: %d)' % (\n dataset_name, filtered_sampled_num, num_edges))\n\n self.samples += [(ds_id, i)\n for i in range(filtered_sampled_num)]\n self.edge_sampler[dataset_name] = (\n gen.sampling_node, gen.sampling_edge, gen.sampling_edge_label)\n\n if sample_res_cache is not None:\n with open(sample_res_cache, 'wb') as f:\n pickle.dump([self.samples, self.edge_sampler], f)\n f.close()\n print('[Captured Init] Save subgraph fast cache to %s.' %\n sample_res_cache)\n\n elif os.path.exists(sample_res_cache):\n with open(sample_res_cache, 'rb') as f:\n s = pickle.load(f)\n self.samples, self.edge_sampler = s\n f.close()\n\n print('[Captured Init] Load subgraph fast cache from %s.' %\n sample_res_cache)\n\n print('[Captured Init] Done, %d samples' % len(self.samples))\n print('[Captured Init] Rt_rel_12: n2 to n1')\n random.shuffle(self.samples)\n\n def __len__(self):\n return len(self.samples)\n\n def get_linkage(self, idx):\n dataset_idx, sub_graph_id = self.samples[idx]\n\n dataset_name = self.dataset_names[dataset_idx]\n frame_list = self.frame_list[dataset_name]\n sampling_node, sampling_edge, sampling_edge_label = self.edge_sampler[dataset_name]\n # edge_local_feat_cache = self.edge_local_feat_cache[dataset_name]\n\n subgraph_nodes = sampling_node[sub_graph_id]\n subgraph_edges = sampling_edge[sub_graph_id]\n subgraph_label = sampling_edge_label[sub_graph_id]\n sub_graph_nodes = len(subgraph_nodes)\n\n \"\"\" Load image -------------------------------------------------------------------------------------------------\n \"\"\"\n img_ids = []\n img_names = []\n img_id2sub_id = {}\n sub_id2img_id = {}\n\n # print(dataset_name)\n for i, imageID in enumerate(subgraph_nodes):\n # load image by image ID\n img_key = dataset_name + '/' + frame_list[imageID]\n img_ids.append(imageID)\n img_names.append(img_key)\n img_id2sub_id[imageID] = i\n sub_id2img_id[i] = imageID\n\n edge_subnode_idx = []\n edge_ori_idx = []\n\n for i, edge in enumerate(subgraph_edges):\n reconnect_idx = (img_id2sub_id[edge[0]], img_id2sub_id[edge[1]])\n edge_subnode_idx.append(reconnect_idx)\n\n n1, n2 = edge[0], edge[1]\n edge_ori_idx.append((n1, n2))\n\n return dataset_name, img_ids, img_names, edge_ori_idx, edge_subnode_idx, img_id2sub_id, sub_id2img_id\n\n def __getitem__(self, idx):\n\n dataset_idx, sub_graph_id = self.samples[idx]\n\n dataset_name = self.dataset_names[dataset_idx]\n frame_list = self.frame_list[dataset_name]\n sampling_node, sampling_edge, sampling_edge_label = self.edge_sampler[dataset_name]\n edge_local_feat_cache = self.edge_local_feat_cache[dataset_name]\n\n subgraph_nodes = sampling_node[sub_graph_id]\n subgraph_edges = sampling_edge[sub_graph_id]\n subgraph_label = sampling_edge_label[sub_graph_id]\n sub_graph_nodes = len(subgraph_nodes)\n\n \"\"\" Node -------------------------------------------------------------------------------------------------------\n \"\"\"\n imgs = []\n img_names = []\n img_ori_dim = []\n cam_Es, cam_Ks = [], []\n img_id2sub_id = {}\n sub_id2img_id = {}\n node_feats = []\n\n # print(dataset_name)\n for i, imageID in enumerate(subgraph_nodes):\n\n # load image by image ID\n img_key = dataset_name + '/' + frame_list[imageID]\n if self.load_img is True:\n if self.use_lmdb is True:\n # load image from lmdb\n img = self.lmdb_db.read_ndarray_by_key(img_key, dtype=np.uint8)\n h, w = self.lmdb_meta[img_key]['dim']\n res_h, res_w = self.lmdb_meta[img_key]['lmdb_dim']\n img = img.reshape(int(res_h), int(res_w), 3)\n else:\n # load image from image file\n img_path = os.path.join(\n self.dataset_dir, dataset_name, frame_list[imageID] + '.jpg')\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n h, w = img.shape[:2]\n\n # resize the image\n res_h, res_w = img.shape[:2]\n min_dim = res_h if res_h < res_w else res_w\n down_factor = float(self.img_max_dim) / float(min_dim)\n img = cv2.resize(img, dsize=(\n int(res_w * down_factor), int(res_h * down_factor)))\n img = img.astype(np.float32) / 255.0\n\n img = torch.from_numpy(img)\n img = img.permute(2, 0, 1)\n if self.transform_func is not None:\n img = self.transform_func(img)\n\n imgs.append(img)\n else:\n res_h = h = 0\n res_w = w = 0\n imgs.append(torch.ones(1))\n\n # load image feature (node feat)\n if self.load_node_edge_feat:\n key = '%s,%d' % (dataset_name, imageID)\n if key not in self.node_feat_meta_dict:\n raise Exception('Node feat %s not found' % key)\n node_feat = self.node_feat_lmdb.read_ndarray_by_key(key).ravel()\n node_feats.append(torch.from_numpy(node_feat).unsqueeze(0))\n else:\n node_feat = torch.zeros((1, 1))\n node_feats.append(node_feat)\n\n # load remaining information (E, K)\n img_ori_dim.append((h, w))\n img_names.append(img_key)\n\n camera_E = self.Es[dataset_name][imageID]\n cam_Es.append(torch.from_numpy(camera_E).float())\n camera_K = self.K[dataset_name][imageID]\n cam_Ks.append(torch.from_numpy(camera_K).float())\n\n # create converter dict\n img_id2sub_id[imageID] = i\n sub_id2img_id[i] = imageID\n\n cam_Es = torch.stack(cam_Es, dim=0)\n cam_Ks = torch.stack(cam_Ks, dim=0)\n node_feats = torch.cat(node_feats, dim=0)\n\n \"\"\" Edges ------------------------------------------------------------------------------------------------------\n \"\"\"\n out_graph_mat = np.zeros((sub_graph_nodes, sub_graph_nodes), dtype=np.float32)\n out_covis_mat = np.zeros((sub_graph_nodes, sub_graph_nodes), dtype=np.float32)\n\n edge_local_matches_n1 = []\n edge_local_matches_n2 = []\n edge_subnode_idx = []\n edge_type = torch.zeros(len(subgraph_edges), dtype=torch.long)\n edge_rel_Rt = []\n edge_rel_err = []\n edge_feats = []\n\n for i, edge in enumerate(subgraph_edges):\n\n # remap index to subgraph\n reconnect_idx = (img_id2sub_id[edge[0]], img_id2sub_id[edge[1]])\n edge_subnode_idx.append(reconnect_idx)\n\n label = subgraph_label[i]\n covis_value = self.covis_map[dataset_name][edge[0], edge[1]]\n if covis_value == 0:\n covis_value = self.covis_map[dataset_name][edge[1], edge[0]]\n\n out_graph_mat[reconnect_idx[0], reconnect_idx[1]] = label\n out_graph_mat[reconnect_idx[1], reconnect_idx[0]] = label\n out_covis_mat[reconnect_idx[0], reconnect_idx[1]] = covis_value\n out_covis_mat[reconnect_idx[1], reconnect_idx[0]] = covis_value\n\n n1, n2 = edge[0], edge[1]\n if '%d-%d' % (n1, n2) in edge_local_feat_cache:\n edge_cache = edge_local_feat_cache['%d-%d' % (n1, n2)]\n\n if self.load_keypt_match:\n pts1 = torch.from_numpy(edge_cache['n1_feat_pos'])\n pts2 = torch.from_numpy(edge_cache['n2_feat_pos'])\n # edge_type[i] = 1 if edge_cache['type'] == 'I' else 0\n\n Rt = edge_cache['Rt'].astype(np.float32)\n Rt_inv = cam_opt.camera_pose_inv(Rt[:3, :3], Rt[:3, 3])\n if np.isnan(Rt_inv).sum() > 1:\n Rt_inv[:3, :3] = Rt[:3, :3].T\n Rt_inv[:3, :3] = Rt[:3, 3]\n\n if Rt[0, 0] == 0 and Rt[1, 1] == 0 and Rt[2, 2] == 0:\n Rt_inv = np.eye(4)[:3, :].astype(np.float32)\n\n edge_rel_Rt.append(torch.from_numpy(Rt_inv))\n\n rel_err = edge_cache['rel_err']\n edge_type[i] = 1 if rel_err < self.outlier_edge_thres_deg else 0\n edge_rel_err.append(rel_err)\n\n elif '%d-%d' % (n2, n1) in edge_local_feat_cache:\n edge_cache = edge_local_feat_cache['%d-%d' % (n2, n1)]\n if self.load_keypt_match:\n pts1 = torch.from_numpy(edge_cache['n2_feat_pos'])\n pts2 = torch.from_numpy(edge_cache['n1_feat_pos'])\n # edge_type[i] = 1 if edge_cache['type'] == 'I' else 0\n Rt_n2ton1 = edge_cache['Rt'].astype(np.float32)\n edge_rel_Rt.append(torch.from_numpy(Rt_n2ton1))\n\n rel_err = edge_cache['rel_err']\n edge_type[i] = 1 if rel_err < self.outlier_edge_thres_deg else 0\n edge_rel_err.append(rel_err)\n\n else:\n raise Exception(\"edge not found %s (%d, %d)\" % (dataset_name, n1, n2))\n\n if self.load_keypt_match:\n edge_local_matches_n1.append(pts1)\n edge_local_matches_n2.append(pts2)\n else:\n edge_local_matches_n1 = torch.zeros(1)\n edge_local_matches_n2 = torch.zeros(2)\n\n # load edge feat\n if self.load_node_edge_feat:\n key1 = '%s,%d-%d' % (dataset_name, n1, n2)\n key2 = '%s,%d-%d' % (dataset_name, n2, n1)\n if key1 in self.edge_feat_dict:\n edge_feat = self.node_feat_lmdb.read_ndarray_by_key(key1)\n edge_feats.append(torch.from_numpy(edge_feat.ravel()).unsqueeze(0))\n elif key2 in self.edge_feat_dict:\n edge_feat = self.node_feat_lmdb.read_ndarray_by_key(key2)\n edge_feats.append(torch.from_numpy(edge_feat.ravel()).unsqueeze(0))\n else:\n raise Exception('Edge feature not found on %s' % key1)\n else:\n edge_feats.append(torch.zeros((1, 1)))\n\n edge_rel_err = torch.from_numpy(np.asarray(edge_rel_err).astype(np.float32))\n out_graph_mat = torch.from_numpy(out_graph_mat)\n out_covis_mat = torch.from_numpy(out_covis_mat)\n edge_feats = torch.cat(edge_feats, dim=0)\n\n if len(edge_subnode_idx) != len(edge_rel_Rt):\n raise Exception(\"Error\")\n\n return dataset_name, idx, img_names, imgs, img_ori_dim, cam_Es, cam_Ks, out_graph_mat, img_id2sub_id, sub_id2img_id, out_covis_mat, edge_subnode_idx, edge_type, edge_local_matches_n1, edge_local_matches_n2, edge_rel_Rt, edge_rel_err, node_feats, edge_feats\n","sub_path":"data/capture/capture_dataset_nonimage.py","file_name":"capture_dataset_nonimage.py","file_ext":"py","file_size_in_byte":20787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"644003208","text":"# import all packages\nimport theano\nfrom theano import tensor as T\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\nimport numpy as np\nfrom StringIO import StringIO \nfrom theano.tensor.nnet.conv import conv2d\nfrom theano.tensor.signal.downsample import max_pool_2d\nimport random \nfrom scipy.stats.stats import pearsonr\nimport collections \nfrom itertools import chain, combinations\nfrom random import shuffle\nimport gc\nfrom collections import Counter\nfrom math import sqrt\nfrom itertools import combinations, chain\n\nsrng = RandomStreams()\n\ndef floatX(X):\n return np.asarray(X, dtype=theano.config.floatX)\n\ndef init_weights(shape):\n return theano.shared(floatX(np.random.randn(*shape) * 0.01))\n\ndef rectify(X):\n return T.maximum(X, 0.)\n\ndef softmax(X):\n e_x = T.exp(X - X.max(axis=1).dimshuffle(0, 'x'))\n return e_x / e_x.sum(axis=1).dimshuffle(0, 'x')\n\ndef dropout(X, p=0.):\n if p > 0:\n retain_prob = 1 - p\n X *= srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX)\n X /= retain_prob\n return X\n\n# load input features\ndef loadX(fname, feat_num=15):\n with open(fname) as fin:\n dat = np.loadtxt(StringIO(fin.read()), dtype=\"float32\") \n max_len = 0 \n res = []\n for i in xrange(1, int(max(dat[:,0]))+1):\n x = dat[dat[:,0]==i,1:]\n res.append(x)\n return res\n\n# load target - gene expression value\ndef loadY(fname):\n with open(fname) as fin:\n dat_Y = np.loadtxt(StringIO(fin.read()), dtype=\"float32\") \n return dat_Y.reshape(-1, 1)\n\n# load connection matrix between enhancers and promoters\ndef loadC(fname):\n matches = collections.defaultdict(list)\n with open(fname) as fin:\n for line in fin:\n [p, e] = map(int, line.strip().split())\n matches[p].append(e)\n return matches\n \ndef RMSprop(cost, params, lr=0.001, rho=0.9, epsilon=1e-6):\n grads = T.grad(cost=cost, wrt=params)\n updates = []\n for p, g in zip(params, grads):\n acc = theano.shared(p.get_value() * 0.)\n acc_new = rho * acc + (1 - rho) * g ** 2\n gradient_scaling = T.sqrt(acc_new + epsilon)\n g = g / gradient_scaling\n updates.append((acc, acc_new))\n updates.append((p, p - lr * g))\n return updates\n \ndef model(X1, X2, w1, w2, w3, p_drop_conv):\n # first half of the first layer\n l1a = T.flatten(dropout(T.mean(rectify(conv2d(X1, w1, border_mode='valid')), axis=3), p_drop_conv), outdim=2)\n # second half of the first layer\n l1b = T.flatten(dropout(T.mean(rectify(conv2d(X2, w2, border_mode='valid')), axis=3), p_drop_conv), outdim=2)\n # combine two pars as first layer\n l1 = T.concatenate([l1a, l1b], axis=1) \n # combine two pars as first layer\n pyx = T.dot(l1, w3)\n return pyx\n\ndef learning(x1, x2, y, nid, epchs, mini_batch_size):\n # model 0 - learning from promoter\n final = []\n index = np.array(range(x1.shape[0]))\n for i in range(epchs):\n random.shuffle(index)\n for start, end in zip(range(0, len(x1), mini_batch_size), range(mini_batch_size, len(x1), mini_batch_size)):\n cost = train(x1[index][start:end], x2[index][start:end], y[index][start:end])\n gc.collect()\n return final\n\ndef update(E, index, feat_num):\n if len(index) > 0:\n ee = list(map(lambda x: np.dstack(E[x]), index))\n ee = np.concatenate(ee, axis=2).reshape(1, 1, feat_num, -1)\n else:\n ee = np.array([]).reshape(1, 1, feat_num, -1)\n return ee\n \ndef constructE(P, E, M, feat_num):\n tmp = [update(E, M[i], feat_num) for i in xrange(len(P))]\n max_len = max([tmp[i].shape[3] for i in xrange(len(tmp))])\n res = [np.concatenate((tmp[i], np.zeros((1,1,feat_num, max_len - tmp[i].shape[3]))), axis=3) for i in xrange(len(tmp))]\n res = np.array(res)\n res = res.reshape(-1, 1, feat_num, max_len)\n return res\n\n\n \n# defining all the parameters\np_drop_conv = 0.5 # dropout rate for cov_layer\nmini_batch_size = 100 # [40 - 100]\nlr = 0.005 # learning rate \nfeat_num = 19 # number of chip features\nchip_motif_len = 6 # length of motif matrix\nchip_motif_num = 200 # number of motifs \n\ndat_XP = loadX(\"datX_P.dat\", feat_num)\ndat_XP = np.array(dat_XP).reshape(len(dat_XP), 1, feat_num, -1)\ndat_XE = loadX(\"datX_E.dat\", feat_num)\ndat_Y = loadY(\"datY.dat\")\nloops = loadC(\"promoters.enhancers.connect.txt\")\n\ndat_XE = constructE(dat_XP, dat_XE, loops, feat_num)\n\n# 5-fold cross validation\nindex = np.array(range(dat_XP.shape[0]))\nres = []\nrandom.shuffle(index)\nindex = index[1:15931]\ngroups = np.array(np.split(index, 5))\n\n\nfor j in range(5):\n mask = np.ones(5,dtype=bool)\n mask[j] = 0\n te_index = groups[j]\n tr_index = groups[mask].reshape(-1,)\n trX_P = dat_XP[tr_index]\n trX_E = dat_XE[tr_index] \n trY = dat_Y[tr_index]\n teX_P = dat_XP[te_index]\n teX_E = dat_XE[te_index]\n teY = dat_Y[te_index]\n\n X1 = T.ftensor4()\n X2 = T.ftensor4()\n Y = T.fmatrix()\n \n w1 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\n w2 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\n w3 = init_weights((chip_motif_num*2, 1000))\n w4 = init_weights((1000, 1))\n \n noise_py_x = model(X1, X2, w1, w2, w3, w4, 0.5, 0.6)\n py_x = model(X1, X2, w1, w2, w3, 0., 0.)\n \n cost = T.mean(T.sqr(noise_py_x - Y))\n params = [w1, w2, w3]\n updates = RMSprop(cost, params, lr)\n \n train = theano.function(inputs=[X1, X2, Y], outputs=cost, updates=updates, allow_input_downcast=True)\n predict = theano.function(inputs=[X1, X2], outputs=py_x, allow_input_downcast=True)\n \n for i in range(0, epchs):\n for start, end in zip(range(0, len(trX_P), mini_batch_size), range(mini_batch_size, len(trX_P), mini_batch_size)):\n train(trX_P[start:end], trX_E[start:end], trY[start:end])\n preds_te = predict(teX_P, teX_E)\n print(epchs, pearsonr(preds_te, teY)[0][0])\n \n \n # learn by promoters with an empty enhancers\n res = learning(teX_P, teX_E, teY, 0, 50, mini_batch_size)\n\n # symbolic variables\n X = T.ftensor4()\n Y = T.fmatrix()\n\n w1 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\n w2 = init_weights((chip_motif_num, 1))\n noise_py_x = model(X, w1, w2, p_drop_conv)\n py_x = model(X, w1, w2, 0.)\n\n cost = T.mean(T.sqr(noise_py_x - Y))\n params = [w1, w2]\n updates = RMSprop(cost, params, lr)\n\n train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True)\n predict = theano.function(inputs=[X], outputs=py_x, allow_input_downcast=True)\n\n for i in range(0, epchs):\n for start, end in zip(range(0, len(trX), mini_batch_size), range(mini_batch_size, len(trX), mini_batch_size)):\n train(trX[start:end], trY[start:end])\n preds_te = predict(teX)\n preds_tr = predict(trX)\n tmp = (epchs, pearsonr(preds_tr, trY)[0][0], pearsonr(preds_te, teY)[0][0])\n print(tmp)\n res.append(tmp)\n\n\n\n\nX1 = T.ftensor4()\nX2 = T.ftensor4()\nY = T.fmatrix()\n\nw1 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\nw2 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\nw3 = init_weights((chip_motif_num*2, 1))\n\nnoise_py_x = model(X1, X2, w1, w2, w3, p_drop_conv)\npy_x = model(X1, X2, w1, w2, w3, 0.)\n\ncost = T.mean(T.sqr(noise_py_x - Y))\nparams = [w1, w2, w3]\nupdates = RMSprop(cost, params, lr)\n\ntrain = theano.function(inputs=[X1, X2, Y], outputs=cost, updates=updates, allow_input_downcast=True)\npredict = theano.function(inputs=[X1, X2], outputs=py_x, allow_input_downcast=True)\n\n# learn by promoters with an empty enhancers\nres = learning(dat_XP, dat_X, dat_Y, 0, 50, mini_batch_size)\n\nenhancers = []\nfor i in range(1, 50):\n # postive prediction\n (trX_update, enh_tmp) = update_X(matches_dist, dat_X_P, dat_X_E, dat_Y, max_enhancer_num, n_jobs) \n # append the enhancers\n enhancers.append(enh_tmp)\n # re-initilize all the parameters\n X1 = T.ftensor4()\n X2 = T.ftensor4()\n Y = T.fmatrix()\n \n w1 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\n w2 = init_weights((chip_motif_num, 1, feat_num, chip_motif_len))\n w3 = init_weights((chip_motif_num*2, 1))\n \n noise_py_x = model(X1, X2, w1, w2, w3, p_drop_conv)\n py_x = model(X1, X2, w1, w2, w3, 0.)\n \n cost = T.mean(T.sqr(noise_py_x - Y))\n params = [w1, w2, w3]\n updates = RMSprop(cost, params, lr)\n \n train = theano.function(inputs=[X1, X2, Y], outputs=cost, updates=updates, allow_input_downcast=True)\n predict = theano.function(inputs=[X1, X2], outputs=py_x, allow_input_downcast=True)\n # now predict (randomly drop 20% of observations)\n ind_sample = random.sample(range(trX_update.shape[0]), int(trX_update.shape[0]*0.8))\n res += learning(dat_X_P[ind_sample], trX_update[ind_sample], dat_Y[ind_sample], i, 20, mini_batch_size)\n gc.collect()\n\nnp.savetxt(\"pred_trX.txt\", np.dstack((predict(dat_X_P, trX_update), dat_Y)).reshape(-1, 2))\nnp.savetxt(\"loops.raw.rep1.txt\", np.array(enhancers).reshape(-1, max_enhancer_num))\nnp.savetxt(\"res.rep1.txt\", np.array(res))\n","sub_path":"results/11-14-2015/DL_enhancer.py","file_name":"DL_enhancer.py","file_ext":"py","file_size_in_byte":9123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"117617356","text":"#!/opt/py-env/bin/python\n# -*- coding: UTF-8 -*-\n\nROUND = {\n 1009: \"众筹\",\n 1010: \"种子轮\",\n 1011: \"天使轮\",\n 1020: \"Pre-A轮\",\n 1030: \"A轮\",\n 1031: \"A+轮\",\n 1039: \"Pre-B轮\",\n 1040: \"B轮\",\n 1041: \"B+轮\",\n 1050: \"C轮\",\n 1051: \"C+轮\",\n 1060: \"D轮\",\n 1070: \"E轮\",\n 1080: \"F轮\",\n 1090: \"后期阶段\",\n 1100: \"Pre-IPO\",\n 1105: \"新三板\",\n 1106: \"新三板定增\",\n 1109: \"ICO\",\n 1110: \"IPO\",\n 1111: \"Post-IPO\",\n 1112: \"定向增发\",\n 1120: \"并购\",\n 1130: \"战略投资\",\n 1131: \"战略合并\",\n 1140: \"私有化\",\n 1150: \"债权融资\",\n 1160: \"股权转让\"\n}\n\nCURRENCY = {\n 3010: \"美元\",\n 3020: \"人民币\",\n 3030: \"新加坡元\",\n 3040: \"欧元\",\n 3050: \"英镑\",\n 3060: \"日元\",\n 3070: \"港币\",\n 3080: \"澳元\"\n}\n\n\ndef get_round_desc(round):\n return ROUND.get(round, \"轮次未知\")\n\n\ndef gen_investment_desc(num, precise, preciseDesc, currency):\n if preciseDesc is not None and preciseDesc.strip() != \"\":\n return preciseDesc.strip()\n\n if num is None or num < 10000:\n return \"金额未知\"\n\n _str = \"\"\n if precise == 'N':\n _temp = str(int(num))\n l = len(_temp)\n if l <= 5:\n _str = \"数万\"\n elif l == 6:\n _str = \"数十万\"\n elif l == 7:\n _str = \"数百万\"\n elif l == 8:\n _str = \"数千万\"\n elif l == 9:\n _str = \"数亿\"\n elif l == 10:\n _str = \"数十亿\"\n else:\n _str = \"百亿以上\"\n else:\n if num > 10000 and num < 10000 * 10000:\n _num1 = int(num/10000)\n _num2 = int(num%10000/100)\n _str = \"%s\" % _num1\n if _num2 > 0:\n _str = \"%s.%s\" % (_str, _num2)\n _str = \"%s万\" % _str\n else:\n _num1 = int(num / 10000 / 10000)\n _num2 = int(num % 100000000 / 10000 / 100)\n _str = \"%s\" % _num1\n if _num2 > 0:\n _str = \"%s.%s\" % (_str, _num2)\n _str = \"%s亿\" % _str\n\n _currency = CURRENCY.get(currency, \"\")\n return \"%s%s\" % (_str, _currency)\n\n\ndef gen_investors(investorsRaw, investors):\n if investors is None and investorsRaw is None:\n return \"未透露\"\n if investors is None:\n return investorsRaw\n\n # _str=\"\"\n # items = json.loads(investors)\n # conn = db.connect_torndb()\n # for item in items:\n # if item[\"type\"] == \"investor\":\n # investor_id = item[\"id\"]\n # investor = conn.get(\"select * from investor where id=%s\", investor_id)\n # if investor is not None and investor[\"active\"] !='N' and investor[\"online\"]=='Y':\n # _str += '%s' % (investor_id, item[\"text\"])\n # else:\n # _str += item[\"text\"]\n # else:\n # _str += item[\"text\"]\n # conn.close()\n # return _str\n return investorsRaw\n\n\n","sub_path":"data/util/funding_helper.py","file_name":"funding_helper.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"380482006","text":"import csv\nimport re\nfrom termcolor import colored\nfrom janome.tokenizer import Tokenizer\nfrom janome.analyzer import Analyzer\nfrom janome.tokenfilter import POSKeepFilter\n#from janome.tokenfilter import CompoundNounFilter \nfrom janome.tokenfilter import TokenCountFilter\n\ntokenizer = Tokenizer()\ntoken_filters = [POSKeepFilter(['名詞','動詞','助詞','形容詞','助動詞']), TokenCountFilter()] #品詞フィルタ-、カウントフィルター\nanalyzer = Analyzer([], tokenizer, token_filters)\nhiragana = '[ぁ-ん]'\nlist_qes = []\nlist_word = []\n\n#with open('/Users/suzukitaichi/Desktop/program/pro_code/Q_database/samDB_utf8.csv', 'r', encoding='utf-8') as f:\nwith open('/Users/suzukitaichi/Desktop/program/pro_code/Q_database/qesAll_utf8_2.csv', 'r', encoding='utf-8') as f: \n reader = csv.reader(f)\n \n for row in reader:\n str1 = row[1]+row[2]\n print(\"===================\")\n print(colored(\"Qes_ID:\",\"red\"), colored(row[0],\"blue\"))\n print(\"===================\")\n print(colored(str1, \"green\"))\n print(\"===================\")\n\n for token in analyzer.analyze(str1):\n #print(token)\n if re.match(hiragana,token[0]) and len(token[0]) == 1:\n continue\n print(token)\n list_word.append(token)\n #print(colored(list_word, \"red\")) \n #list_word.clear()\n\nprint(list_word) \n\n\n","sub_path":"Another/Sotsuken_Code/Qes_Analysis2.py","file_name":"Qes_Analysis2.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"219483073","text":"def show_board(board = ['null', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']):\n print(board[7]+'|'+board[8]+'|'+board[9]+'|')\n print(board[4]+'|'+board[5]+'|'+board[6]+'|')\n print(board[1]+'|'+board[2]+'|'+board[3]+'|')\n\n\ndef player_input():\n selection = input('Select which mark do you want to play: X or O\\n')\n if selection == 'X':\n player1 = 'X'\n player2 = 'O'\n else:\n player1 = 'O'\n player2 = 'X'\n while selection != 'X' and selection != 'O':\n print('Enter a valid option\\n')\n selection = input('Select which mark do you want to play: X or O\\n')\n\ndef place_marker():\n position = input('select where to put the marker\\n')\n return position\n \n\nnew_board = []\nshow_board()\ncounter = 0\nwhile counter < 10:\n position = place_marker()\n new_board.insert(int(position),'X')\n show_board(new_board)\n counter += 1\n print(new_board)","sub_path":"python_for_beginners/exercises/programs/milestone_project_1/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"122451715","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nfrom array import array\n\nimport EnvManager\nfrom ROOT import (gROOT, gStyle,\n TCanvas, TGraph, TLatex,\n kRed)\n\n#_______________________________________________________________________________\nif __name__ == '__main__':\n gROOT.Reset()\n EnvManager.Load()\n # parser = argparse.ArgumentParser()\n # parser.add_argument('summary_txt')\n # parsed, unpased = parser.parse_known_args()\n fig_file = EnvManager.fig_dir + '/ShowEffGraph.pdf'\n vth1 = array('d')\n eff1 = array('d')\n vth2 = array('d')\n eff2 = array('d')\n for s in [238, 288, 338, 388]:\n vth1.append(s)\n for e in [0.381, 0.361, 0.328, 0.296]:\n eff1.append(e)\n for s in [288, 338, 388]:\n vth2.append(s)\n for e in [0.425, 0.439, 0.437]:\n eff2.append(e)\n c1 = TCanvas('c1', 'c1', 1000, 800)\n c1.SetGrid()\n g1 = TGraph(len(vth1), vth1, eff1)\n g2 = TGraph(len(vth2), vth2, eff2)\n g1.SetMarkerSize(2)\n g2.SetMarkerSize(2)\n g1.SetMarkerStyle(8)\n g2.SetMarkerStyle(8)\n g2.SetMarkerColor(kRed)\n g1.GetYaxis().SetRangeUser(0,0.5)\n g1.GetXaxis().SetTitle('SDC3-Vth')\n g1.SetTitle('SdcOutTracking Efficiency')\n g1.Draw(\"AP\")\n g2.Draw(\"P\")\n c1.Print(fig_file)\n","sub_path":"ShowEffGraph.py","file_name":"ShowEffGraph.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"131931710","text":"import datetime\r\nfrom datetime import date, timedelta\r\n\r\nschedule = {\r\n \"timeZone\" : \"+5:30\",\r\n \"startDate\" : (\"2021-02-01T00:00:00.000Z\"),\r\n \"endDate\" : (\"2021-02-10T00:00:00.000Z\"),\r\n \"businessHours\" : {\r\n \"startTime\" : \"03:30\",\r\n \"endTime\" : \"12:30\",\r\n \"format\" : \"24 hours\",\r\n \"durationInHours\" : 3,\r\n \"includeWeekends\" : True,\r\n \"includeHolidays\" : True\r\n },\r\n \"breakHours\" : [\r\n {\r\n \"startTime\" : \"07:30\",\r\n \"endTime\" : \"08:30\",\r\n \"format\" : \"24 hours\",\r\n \"durationInHours\" : \"\"\r\n }\r\n ],\r\n \"holidays\" : [{\"startDate\" : (\"2021-02-01T00:00:00.000Z\"),\r\n \"endDate\" : (\"2021-02-08T00:00:00.000Z\")}],\r\n \"weekends\" : [\r\n \"Saturday\",\r\n \"Sunday\"\r\n ],\r\n \"slots\": [\r\n {\r\n \"dateID\": \"\",\r\n \"date\": \"2021-01-28T00:00:00.000Z\",\r\n \"timings\": [{\"timeID\": \"\", \"startTime\" : \"03:00\", \"endTime\" : \"17:00\"}]\r\n }\r\n ]\r\n\r\n}\r\n\r\ndef prepare_slots(schedule):\r\n #changes need to be done in slots method it only works if we have only one slot i ah day \r\n def slots(list,weekend,holidays): #here we are removing weekdays from slots\r\n slot = []\r\n for i in range(len(list)):\r\n if (list[i][1] not in weekend) & ( list[i][2] not in holidays):\r\n slot.append({\"dateID\": \"\",\r\n \"date\" : list[i][2]+\"T00:00:00.000Z\",\r\n \"timings\": [{\"timeID\": \"\",\"startTime\" : list[i][0][0], \"endTime\" : list[i][0][1]}]\r\n })\r\n return slot\r\n def find_slots(stime,etime,start_date,end_date,slot_time):\r\n days = []\r\n date = start_date\r\n while date <= end_date:\r\n year,month,day = str(date).split('-')[0],str(date).split('-')[1],str(date).split('-')[2] #added by me\r\n d = datetime.date(int(year),int(month),int(day))\r\n tempd = date.strftime(\"%Y-%m-%d\")\r\n hours = []\r\n time = datetime.datetime.strptime(stime, '%H:%M')\r\n end = datetime.datetime.strptime(etime, '%H:%M')\r\n while time <= end:\r\n hours.append(time.strftime(\"%H:%M\"))\r\n time += datetime.timedelta(minutes=slot_time)\r\n date += datetime.timedelta(days=1)\r\n days.append([hours,d.strftime(\"%A\"),tempd ])\r\n return days\r\n #dates\r\n sy,sm,sd =int(schedule[\"startDate\"].split('-')[0]),int(schedule[\"startDate\" ].split('-')[1]),int(schedule[\"startDate\" ].split('-')[2].split('T')[0])\r\n ey,em,ed =int(schedule[\"endDate\"].split('-')[0]),int(schedule[\"endDate\" ].split('-')[1]),int(schedule[\"endDate\" ].split('-')[2].split('T')[0])\r\n start_date = datetime.datetime(sy,sm,sd).date()\r\n end_date = datetime.datetime(ey,em,ed).date() \r\n #non workings\r\n weekend = schedule[\"weekends\"] \r\n #time section\r\n start_time = schedule[\"businessHours\"][\"startTime\"]\r\n end_time = schedule[\"businessHours\"][\"endTime\"]\r\n slot_time = schedule[\"businessHours\"][\"durationInHours\"]*60 # taking in mins\r\n break_start = schedule[\"breakHours\"][0][\"startTime\"]\r\n break_end = schedule[\"breakHours\"][0][\"endTime\"] \r\n \r\n #holidays section\r\n sdate = date(int(schedule[\"holidays\"][0][\"startDate\"].split('-')[0]),int(schedule[\"holidays\"][0][\"startDate\" ].split('-')[1]),int(schedule[\"holidays\"][0][\"startDate\" ].split('-')[2].split('T')[0])) # start date\r\n edate = date(int(schedule[\"holidays\"][0][\"endDate\"].split('-')[0]),int(schedule[\"holidays\"][0][\"endDate\"].split('-')[1]),int(schedule[\"holidays\"][0][\"endDate\"].split('-')[2].split('T')[0])) # end date\r\n\r\n delta = edate - sdate # as timedelta\r\n holidays = []\r\n for i in range(delta.days + 1):\r\n day = sdate + timedelta(days=i)\r\n holidays.append(str(day))\r\n \r\n\r\n #slots get splitted to before time and after time\r\n # before break\r\n before_b= find_slots(start_time,break_start,start_date,end_date,slot_time) \r\n main_slots = slots(before_b, weekend,holidays)\r\n # after break\r\n after_b = find_slots(break_end,end_time,start_date,end_date,slot_time) \r\n slots_after_break = slots(after_b, weekend, holidays)\r\n\r\n for i in slots_after_break:\r\n main_slots.append(i)\r\n\r\n return main_slots\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"slot_task.py","file_name":"slot_task.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"144848906","text":"#!/usr/bin/env python3\n# coding:utf-8\n__author__ = 'lishikun4'\n\nimport sys\nimport os\nimport yaml\nimport datetime\nimport logging\nimport logging.config\nimport spa_utils\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\nfrom pyspark import SparkFiles\nfrom pyspark.sql.types import StructType\nfrom pyspark.sql.types import StructField\nimport pyspark.sql.types as sql_type\n\napp_name = os.path.basename(__file__)\nspark = SparkSession.builder.appName(app_name).enableHiveSupport().getOrCreate()\nspark.sparkContext.addPyFile('logging.conf')\nspark.sparkContext.addPyFile('params.yaml')\n\nlogging.config.fileConfig(SparkFiles.get('logging.conf')) # 读取logging的配置信息\nlogger = logging.getLogger(app_name) # logger名称与任务名称相同\n\n# 读取任务参数\nparams = spa_utils.load_params()\nlogger.info('parameter file loaded')\nlogger.debug(params)\n\n# 命令行参数有更高的优先级\nif len(sys.argv) >= 2:\n params['update_start'] = sys.argv[1]\n params['update_end'] = sys.argv[1]\nif len(sys.argv) >= 3:\n params['update_end'] = sys.argv[2]\nif len(sys.argv) >= 4:\n params['write_mode'] = sys.argv[3]\n\n# 读取start date和end date\nupdate_start = params['update_start']\nupdate_end = params['update_end']\n\ntraffic_schema = StructType([\n StructField('op_time', sql_type.StringType()),\n StructField('item_sku_id', sql_type.StringType()),\n StructField('sku_name', sql_type.StringType()),\n StructField('web_site_id', sql_type.IntegerType()),\n StructField('pv', sql_type.LongType()),\n StructField('uv', sql_type.LongType()),\n StructField('visits', sql_type.LongType()),\n StructField('dt', sql_type.StringType())\n])\n\n# 读取流量表\ntraffic_df = spa_utils.read_table('app_cmo_ol_client_sku_3_to_bjmart_di', start = update_start, end = update_end,\n spark=spark, params=params, sep='\\t', header=True,\n schema=traffic_schema)\n\n# app.app_pa_traffic_dtsku\n# sku流量模型\n# 粒度(dt, sku)\ndf_sku_traffic = traffic_df\\\n .groupBy(['item_sku_id', 'dt'])\\\n .agg(\n F.sum('pv').alias('pv'),\n F.sum('uv').alias('uv')\n)\ndf_sku_traffic = df_sku_traffic.select(['item_sku_id', 'pv', 'uv', 'dt'])\n\nspark.sql(\"set hive.exec.dynamic.partition=true\")\nspark.sql(\"set hive.exec.dynamic.partition.mode=nonstrict\")\nlogger.info('inserting app.app_pa_traffic_dtsku...')\nspa_utils.save_result(df_sku_traffic,\n 'app.app_pa_traffic_dtsku',\n partitioning_columns=['dt'],\n write_mode=params['write_mode'],\n spark=spark, params = params)","sub_path":"liao_spa/SPA_traffic_sku.py","file_name":"SPA_traffic_sku.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"263917352","text":"from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.support.wait import WebDriverWait\n#最基本的使用小案例\nbrowser = webdriver.Chrome() #声明浏览器对象\ntry:\n browser.get('https://www.baidu.com') #访问网址\n # browser.execute_script('document.getElementById(\"nr\").value=\"50\"')\n input = browser.find_element_by_id('kw') #通过ID查找元素\n input.send_keys('Python') #向元素输入内容\n input.send_keys(Keys.ENTER) #回车\n wait = WebDriverWait(browser,10)\n # 等待指定元素加载进来\n wait.until(ec.presence_of_all_elements_located((By.ID,'content_left')))\n #提取搜索引擎结果的核心代码(绝密)\n result=browser.find_elements_by_css_selector('#content_left .result.c-container .t')\n for r in result:\n print(r.text)\n print(r.find_element_by_css_selector('a').get_attribute('href'))\nfinally:\n browser.close()","sub_path":"mainpy/SeLeniu.py","file_name":"SeLeniu.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"578366170","text":"import wx\nimport wx.xrc\n\nfrom ObjectListView import ObjectListView, ColumnDefn\n\nfrom db.get_subjects import getSubjects, getSubjectGroups\nfrom db.save_subject import editSubject, deleteSubject\n\n# import sys\n# sys.path.insert(0, r'/F:/PythonApps/Kangangu')\n\n\n###########################################################################\n# Class ViewSubjects\n###########################################################################\n\n\nclass ViewSubjects(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(642, 406),\n style=wx.TAB_TRAVERSAL)\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n self.m_staticText17 = wx.StaticText(self, wx.ID_ANY, u\"All Subjects\", wx.DefaultPosition, wx.DefaultSize,\n wx.ALIGN_CENTRE)\n self.m_staticText17.Wrap(-1)\n self.m_staticText17.SetFont(wx.Font(14, 70, 90, 92, False, wx.EmptyString))\n\n container.Add(self.m_staticText17, 0, wx.TOP | wx.EXPAND, 25)\n\n horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n left_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n OLV_sizer = wx.BoxSizer(wx.VERTICAL)\n\n #\n # Subjects Object list View\n # ----------------------------------------------------------------\n # Search\n # ----------------------------------------------------------------\n\n search_container = wx.BoxSizer(wx.HORIZONTAL)\n\n self.refresh_btn = wx.BitmapButton(self, wx.ID_ANY,\n wx.Bitmap(u\"images/reload_16x16.bmp\", wx.BITMAP_TYPE_ANY),\n wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW)\n\n self.refresh_btn.SetBitmapHover(wx.Bitmap(u\"images/reload_16x16_rotated.bmp\", wx.BITMAP_TYPE_ANY))\n search_container.Add(self.refresh_btn, 0, wx.BOTTOM | wx.LEFT | wx.RIGHT, 5)\n\n self.m_staticText53 = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.m_staticText53.Wrap(-1)\n search_container.Add(self.m_staticText53, 1, wx.ALL, 5)\n\n self.search_subjects = wx.SearchCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,\n wx.TE_PROCESS_ENTER)\n self.search_subjects.ShowSearchButton(True)\n self.search_subjects.ShowCancelButton(False)\n search_container.Add(self.search_subjects, 0, wx.BOTTOM | wx.RIGHT, 8)\n\n OLV_sizer.Add(search_container, 0, wx.EXPAND, 5)\n\n #\n #\n # ----------------------------------------------------------------\n # Table\n # ----------------------------------------------------------------\n self.classes = getSubjects()\n\n self.subjectsOLV = ObjectListView(self, wx.ID_ANY, style=wx.LC_REPORT | wx.SUNKEN_BORDER)\n self.setSubjectsData()\n\n OLV_sizer.Add(self.subjectsOLV, 1, wx.EXPAND | wx.ALL, 5)\n\n # ----------------------------------------------------------------\n #\n #\n left_sizer.Add(OLV_sizer, 1, wx.EXPAND, 5)\n\n left_btns_sizer = wx.BoxSizer(wx.VERTICAL)\n\n self.edit_subject_btn = wx.Button(self, wx.ID_ANY, u\"Edit Subject\", wx.DefaultPosition, wx.DefaultSize, 0)\n left_btns_sizer.Add(self.edit_subject_btn, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 5)\n\n self.delete_subject_btn = wx.Button(self, wx.ID_ANY, u\"Delete\", wx.DefaultPosition, wx.DefaultSize, 0)\n left_btns_sizer.Add(self.delete_subject_btn, 0, wx.ALL | wx.EXPAND, 5)\n\n left_sizer.Add(left_btns_sizer, 0, wx.EXPAND, 5)\n\n horizontal_sizer.Add(left_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n right_sizer = wx.BoxSizer(wx.VERTICAL)\n\n #\n # ------------------------------------------------------------------------\n # EDIT FORM\n # ------------------------------------------------------------------------\n #\n\n self.edit_subject_panel = EditSubject(self)\n right_sizer.Add(self.edit_subject_panel, 1, wx.EXPAND)\n\n horizontal_sizer.Add(right_sizer, 1, wx.ALL | wx.EXPAND, 8)\n\n container.Add(horizontal_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n self.SetSizer(container)\n self.Layout()\n\n # Connect Events\n self.refresh_btn.Bind(wx.EVT_BUTTON, self.refreshTable)\n self.search_subjects.Bind(wx.EVT_TEXT, self.searchSubjects)\n self.search_subjects.Bind(wx.EVT_TEXT_ENTER, self.searchSubjects)\n\n self.edit_subject_btn.Bind(wx.EVT_BUTTON, self.getSubjectInfo)\n self.delete_subject_btn.Bind(wx.EVT_BUTTON, self.deleteSubject)\n\n def setSubjectsData(self, data=None):\n self.subjectsOLV.SetColumns([\n ColumnDefn(\"ID\", \"left\", 50, \"subject_id\"),\n ColumnDefn(\"Name\", \"center\", 125, \"subject_name\"),\n ColumnDefn(\"Alias\", \"center\", 90, \"subject_alias\"),\n ColumnDefn(\"Compulsory\", \"center\", 100, \"compulsory\"),\n ColumnDefn(\"Group\", \"center\", 110, \"group\"),\n ])\n\n self.subjectsOLV.SetObjects(self.classes)\n\n def updateSubjectsOLV(self, event): # Refresh classes table\n data = getSubjects()\n self.subjectsOLV.SetObjects(data)\n\n def refreshTable(self, event):\n self.updateSubjectsOLV(\"\")\n\n def searchSubjects(self, event):\n search = self.search_subjects.GetLineText(0)\n data = getSubjects(search)\n self.subjectsOLV.SetObjects(data)\n\n def getSubjectInfo(self, event): # In order to edit\n if not self.subjectsOLV.GetSelectedObject():\n dlg = wx.MessageDialog(None, \"Click on a row in order to edit subject.\",\n 'Error Message.',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n else:\n self.rowData = self.subjectsOLV.GetSelectedObject()\n rowObj = self.subjectsOLV.GetSelectedObject()\n\n self.edit_subject_panel.subject_id.SetValue(str(rowObj['subject_id']))\n self.edit_subject_panel.subject_name.SetValue(rowObj['subject_name'])\n self.edit_subject_panel.subject_alias.SetValue(rowObj['subject_alias'])\n self.edit_subject_panel.compulsory.SetValue(rowObj['compulsory'])\n self.edit_subject_panel.subject_group.SetValue(rowObj['group'])\n\n def deleteSubject(self, event):\n if self.subjectsOLV.GetSelectedObject():\n rowObj = self.subjectsOLV.GetSelectedObject()\n\n dlg = wx.MessageDialog(None, \"Are you sure? \\nThis action cannot be reversed.\", 'Warning Message.', wx.YES_NO | wx.ICON_WARNING)\n retCode = dlg.ShowModal()\n\n if retCode == wx.ID_YES:\n if deleteSubject(rowObj[\"subject_id\"]):\n dlg = wx.MessageDialog(None, \"Subject deleted successfully.\", 'Success Message.',\n wx.OK | wx.ICON_EXCLAMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n self.updateSubjectsOLV(\"\")\n else:\n rowObj=\"\"\n dlg.Destroy()\n\n\n else:\n dlg = wx.MessageDialog(None, \"Click on a row to delete a subject.\", 'Error Message.',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n\n\nclass EditSubject(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(561, 458),\n style=wx.TAB_TRAVERSAL)\n self.parent = parent\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n bSizer73 = wx.BoxSizer(wx.HORIZONTAL)\n\n bSizer28 = wx.BoxSizer(wx.VERTICAL)\n\n self.m_staticText30 = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.m_staticText30.Wrap(-1)\n bSizer28.Add(self.m_staticText30, 1, wx.ALL | wx.EXPAND, 5)\n\n bSizer73.Add(bSizer28, 1, wx.EXPAND, 5)\n\n bSizer36 = wx.BoxSizer(wx.VERTICAL)\n\n sbSizer2 = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u\"Edit Subject Form\"), wx.VERTICAL)\n\n #\n # hidden subject id field\n #\n subject_id_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.subject_id = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.subject_id.Hide()\n\n subject_id_sizer.Add(self.subject_id, 0, wx.ALL, 10)\n\n full_name_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.statictext = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Full Name\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.statictext.Wrap(-1)\n full_name_sizer.Add(self.statictext, 1, wx.ALL, 10)\n\n self.subject_name = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n full_name_sizer.Add(self.subject_name, 4, wx.ALL, 10)\n\n sbSizer2.Add(full_name_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n alias_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.statictext1 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Subject Alias\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.statictext1.Wrap(-1)\n alias_sizer.Add(self.statictext1, 1, wx.ALL, 10)\n\n self.subject_alias = wx.TextCtrl(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n alias_sizer.Add(self.subject_alias, 4, wx.ALL, 10)\n\n sbSizer2.Add(alias_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n compulsory_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.compulsory_label = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Compulsory\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.compulsory_label.Wrap(-1)\n compulsory_sizer.Add(self.compulsory_label, 1, wx.ALL, 10)\n\n compulsoryChoices = [u\"No (Not compulsory in any form)\", u\"Yes (In all forms)\", u\"Partially (Only in lower forms)\"]\n self.compulsory = wx.ComboBox(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, compulsoryChoices, wx.CB_READONLY)\n compulsory_sizer.Add(self.compulsory, 4, wx.ALL, 10)\n\n sbSizer2.Add(compulsory_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n subject_group_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.subject_group_label = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Group\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.subject_group_label.Wrap(-1)\n subject_group_sizer.Add(self.subject_group_label, 1, wx.ALL, 10)\n\n self.groups = getSubjectGroups()\n groupChoices = self.groups['names']\n\n self.subject_group = wx.ComboBox(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, groupChoices, wx.CB_READONLY)\n subject_group_sizer.Add(self.subject_group, 4, wx.ALL, 10)\n\n sbSizer2.Add(subject_group_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n btns_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.m_staticText22 = wx.StaticText(sbSizer2.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.m_staticText22.Wrap(-1)\n btns_sizer.Add(self.m_staticText22, 1, wx.ALL, 5)\n\n self.cancel_btn = wx.Button(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Cancel\", wx.DefaultPosition, wx.DefaultSize,\n 0)\n btns_sizer.Add(self.cancel_btn, 0, wx.ALL, 10)\n\n self.edit_subject = wx.Button(sbSizer2.GetStaticBox(), wx.ID_ANY, u\"Save\", wx.DefaultPosition, wx.DefaultSize,\n 0)\n btns_sizer.Add(self.edit_subject, 0, wx.ALL, 10)\n\n sbSizer2.Add(btns_sizer, 3, wx.ALL | wx.EXPAND, 10)\n\n bSizer36.Add(sbSizer2, 1, 0, 50)\n\n bSizer73.Add(bSizer36, 1, wx.ALL | wx.EXPAND, 5)\n\n bSizer281 = wx.BoxSizer(wx.VERTICAL)\n\n self.m_staticText302 = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.m_staticText302.Wrap(-1)\n bSizer281.Add(self.m_staticText302, 1, wx.ALL | wx.EXPAND, 5)\n\n bSizer73.Add(bSizer281, 1, wx.EXPAND, 5)\n\n container.Add(bSizer73, 1, wx.EXPAND, 5)\n\n self.SetSizer(container)\n self.Layout()\n\n # Connect Events\n self.cancel_btn.Bind(wx.EVT_BUTTON, self.cancelEditSubject)\n self.edit_subject.Bind(wx.EVT_BUTTON, self.saveEditSubject)\n\n def __del__(self):\n pass\n\n # Virtual event handlers, overide them in your derived class\n def cancelEditSubject(self, event):\n self.subject_id.SetValue(\"\")\n self.subject_name.SetValue(\"\")\n self.subject_alias.SetValue(\"\")\n self.compulsory.SetSelection(-1)\n self.subject_group.SetSelection(-1)\n\n def saveEditSubject(self, event):\n self.edit_subject.Enable(False)\n\n subject_id = self.subject_id.GetLineText(0)\n subject_name = self.subject_name.GetLineText(0)\n subject_alias = self.subject_alias.GetLineText(0)\n compulsory_index = self.compulsory.GetCurrentSelection()\n compulsory = self.compulsory.GetString(compulsory_index)\n groupName = self.subject_group.GetStringSelection()\n groupIndex = self.subject_group.GetCurrentSelection()\n\n subject_alias = subject_alias.replace(\" \", \"\")\n\n # Check if a subject has been selected\n if subject_id != \"\":\n # ---------- VALIDATION ----------\n error = \"\"\n\n if subject_name == \"\":\n error = error + \"The Full Name field is required.\\n\"\n\n if subject_alias == \"\":\n error = error + \"The Subject Alias field required.\\n\"\n\n if compulsory_index == -1:\n error = error + \"The Compulsory field is required.\\n\"\n\n if groupIndex == -1:\n error = error + \"The Group field is required.\\n\"\n else:\n if groupName == \"Mathematics\" and (compulsory == \"No\" or compulsory == \"Partially\"):\n error = error + \"Mathematics is a compulsory subject.\\n\"\n if groupName == \"Language\" and (compulsory == \"No\" or compulsory == \"Partially\"):\n error = error + \"Languages are compulsory subjects.\\n\"\n\n if error:\n dlg = wx.MessageDialog(None, error, 'Validation Error', wx.OK | wx.ICON_WARNING)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n # if compulsory == \"Yes\":\n # compulsory = 1\n # elif compulsory == \"No\":\n # compulsory = 0\n # else: # Partialy\n # compulsory = 2\n\n group = self.groups['ids'][groupIndex]\n\n data = {\n \"subject_id\": subject_id,\n \"subject_name\": subject_name,\n \"subject_alias\": subject_alias,\n \"compulsory\": compulsory_index,\n \"group\": group\n }\n\n if editSubject(data):\n dlg = wx.MessageDialog(None, \"Subject Edited Successfully.\", 'Success Message',\n wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n self.parent.updateSubjectsOLV(\"\")\n self.cancelEditSubject(\"\")\n else:\n dlg = wx.MessageDialog(None, \"Edit Failed. Try Again.\", 'Failed.',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n dlg = wx.MessageDialog(None, \"Please select subject to edit.\", 'Validation Error', wx.OK | wx.ICON_WARNING)\n dlg.ShowModal()\n dlg.Destroy()\n\n self.edit_subject.Enable(True)\n\n\n","sub_path":"ViewSubjects.py","file_name":"ViewSubjects.py","file_ext":"py","file_size_in_byte":16358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"623782921","text":"from bs4 import BeautifulSoup\nfrom urllib import request\nimport gspread\nimport json\n\n#ServiceAccountCredentials:Googleの各サービスへアクセスできるservice変数を生成します。\nfrom oauth2client.service_account import ServiceAccountCredentials \n\n#2つのAPIを記述しないとリフレッシュトークンを3600秒毎に発行し続けなければならない\nscope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']\n\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('python-pornhub-47b8b4f92c97.json', scope)\n\n#OAuth2の資格情報を使用してGoogle APIにログインします。\ngc = gspread.authorize(credentials)\n\nSPREADSHEET_KEY = '16VpdI8ABHYbh7lRjoawaQODarMcVc4B7kohr1_ckags'\n\n#共有設定したスプレッドシートのシート1を開く\nworksheet = gc.open_by_key(SPREADSHEET_KEY).worksheet('Python-Pornhub')\n\nurl = 'https://jp.pornhub.com/video/search?search=%E5%B7%A8%E4%B9%B3'\nresponse = request.urlopen(url)\nsoup = BeautifulSoup(response)\nresponse.close()\n\nPornhub_href = ('https://jp.pornhub.com' + soup.find('div',class_='phimage').a.get('href'))\nPornhub_title = (soup.find('div',class_='thumbnail-info-wrapper').a.get('title'))\nPornhub_image = (soup.find('div',class_='phimage').img.get('data-mediabook'))\n\nprint('https://jp.pornhub.com' + soup.find_all('div',class_='phimage').a.get('href')[1])\n#worksheet.update_cell(2,1, Pornhub_title)\n#worksheet.update_cell(2,2, Pornhub_href)\n#worksheet.update_cell(2,3, Pornhub_image)","sub_path":"mymod.py","file_name":"mymod.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"234006571","text":"import os\n\nimport io\nimport sys\nimport glob\nimport keras\nimport time\nimport h5py\nimport random\nimport gc\n\nimport numpy as np\n\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom keras import __version__\nfrom keras.utils import np_utils\nfrom keras.preprocessing import image\nfrom keras.models import Model, load_model\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.applications.vgg19 import preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import SGD\nfrom keras.callbacks import *\n\nfrom collections import Counter\nfrom PIL import Image\n\nWeights_Path = \"../../models/type/VGG19/type_VGG19_weights.h5\"\n\n\nclass RijksVGG19Net(object):\n def __init__(self, hdf5_path, results_path, nb_classes, tl_mode):\n\n self.tl_mode = \"fine_tuning\"\n self.width = 224\n self.height = 224\n self.channels = 3\n\n self.train_batch_size = 64\n self.val_batch_size = 64\n self.test_batch_size = 32\n\n self.epochs = 100\n\n self.activation = \"relu\"\n self.optimizer = SGD(lr=0.0001, momentum=0.9)\n self.loss = \"categorical_crossentropy\"\n self.early_stopping = keras.callbacks.EarlyStopping(\n monitor='val_loss', patience=7, verbose=1, mode='auto')\n self.hdf5_path = hdf5_path\n self.nb_classes = nb_classes\n\n self.results_path = os.path.join(results_path, \"from_one_art_to_another\", \"VGG19\")\n self.make_results_path()\n self.save_model = keras.callbacks.ModelCheckpoint(os.path.join(self.results_path, 'weights{epoch:08d}.h5'), save_weights_only=True, period=1)\n\n def load_images(self, name, split):\n\n f = h5py.File(os.path.join(self.hdf5_path, name), 'r')\n images = list(f[split])\n\n return(images)\n\n def load_encodings(self, name, split):\n h5f_labels = h5py.File(os.path.join(self.hdf5_path, name), 'r')\n labels = h5f_labels[split][:]\n\n return(labels)\n\n def my_generator(self, mode):\n\n if mode == \"__train\":\n X_ = self.X_train\n y_ = self.y_train\n batch_size = self.train_batch_size\n\n elif mode == \"__val\":\n X_ = self.X_val\n y_ = self.y_val\n batch_size = self.val_batch_size\n\n elif mode == \"__test\":\n X_ = self.X_test\n y_ = self.y_test\n batch_size = self.test_batch_size\n\n start_batch = 0\n end_batch = start_batch + batch_size\n end_epoch = False\n\n while True:\n\n # Returns a random batch indefinitely from X_train, needed also in order to catch exception\n\n batch = list()\n\n if len(X_) - end_batch < 0:\n end_epoch = True\n start_batch = start_batch - batch_size + 1\n end_batch = end_batch - batch_size + 1\n\n for imgs in X_[start_batch:end_batch]:\n img = image.load_img(io.BytesIO(\n imgs), target_size=(self.width, self.height))\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = preprocess_input(img)\n\n batch.append(img)\n\n batch = np.asarray(batch)\n\n X_batch = np.reshape(\n batch, (batch.shape[0], self.width, self.height, self.channels))\n y_batch = np.asarray([item for item in y_[start_batch:end_batch]])\n\n yield(X_batch, y_batch)\n\n start_batch += batch_size\n end_batch += batch_size\n\n if end_epoch == True:\n start_batch = 0\n end_batch = start_batch + batch_size\n end_epoch = False\n\n def make_results_path(self):\n if not os.path.exists(self.results_path):\n os.makedirs(self.results_path)\n\n def make_model_path(self):\n if not os.path.exists(self.model_path):\n os.makedirs(self.model_path)\n\n def get_model(self):\n initial_model = keras.applications.vgg19.VGG19()\n initial_model.load_weights(Weights_Path, by_name=True)\n initial_model.layers.pop()\n\n x = initial_model.layers[-1].output\n x = Dense(self.nb_classes, activation=\"softmax\")(x)\n\n model = Model(input=initial_model.input, output=x)\n\n return model\n\n def setup_transfer_learning_mode(self, base_model):\n if self.tl_mode == \"off_the_shelf\":\n for layer in base_model.layers[:-2]:\n layer.trainable = False\n\n base_model.layers[-1].trainable = True\n base_model.compile(optimizer=\"rmsprop\",\n loss=self.loss, metrics=[\"accuracy\"])\n\n elif self.tl_mode == \"fine_tuning\":\n for layer in base_model.layers:\n layer.trainable = True\n base_model.compile(optimizer=self.optimizer,\n loss=self.loss, metrics=[\"accuracy\"])\n\n def train(self):\n\n model = self.get_model()\n self.setup_transfer_learning_mode(model)\n\n self.X_train = self.load_images('training_images.hdf5', 'X_train')\n self.y_train = self.load_encodings('training_labels.hdf5', 'y_train')\n\n self.X_val = self.load_images('validation_images.hdf5', 'X_val')\n self.y_val = self.load_encodings('validation_labels.hdf5', 'y_val')\n\n # self.X_test = self.load_images('testing_images.hdf5', 'X_test')\n # self.y_test = self.load_encodings('testing_labels.hdf5', 'y_test')\n\n tl_history = model.fit_generator(self.my_generator('__train'), steps_per_epoch=len(self.X_train) // self.train_batch_size, nb_epoch=self.epochs,\n validation_data=self.my_generator('__val'), validation_steps=len(self.X_val) // self.val_batch_size, callbacks=[self.early_stopping, self.save_model])\n np.save(os.path.join(self.results_path, \"transfer_learning_accuracies_shelf.npy\"),\n tl_history.history[\"val_acc\"])\n model.save(os.path.join(self.results_path, \"TL_VGG19_model.h5\"))\n model.save_weights(os.path.join(self.results_path, \"TL_VGG19_weights.h5\"))\n","sub_path":"transfer_learning_experiment/from_one_art_to_another/RijksVGG19Net.py","file_name":"RijksVGG19Net.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"449115643","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom transformers import BertTokenizer, BertConfig, BertModel\nfrom torchtext import data\nimport pickle\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom itertools import chain\n\ngpu = 0\ndevice = torch.device('cuda:%d' % (\n gpu) if torch.cuda.is_available() else 'cpu')\n\n####################################################################\n###################### Load data & preprocess ######################\n####################################################################\n\nPRETRAINED_MODEL_NAME = 'allenai/scibert_scivocab_uncased'\ntokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)\n\nwith open('./token_info/label2int.pickle', 'rb') as file:\n label2int = pickle.load(file)\nfile.close()\n\n\ndef remain_text(x):\n return str(x)\n\n\ndef bert_tokenize(x):\n x = tokenizer.tokenize(x)\n if len(x) > 511:\n return x[:256] + x[-255:]\n return x\n\n\ndef label_onehot(x):\n x = x.strip().split(' ')\n res = np.zeros(len(label2int))\n for k in x:\n if k in label2int:\n res[label2int[k]] = 1\n return res\n\n\nCONTENT = data.Field(sequential=True, tokenize=bert_tokenize, preprocessing=tokenizer.convert_tokens_to_ids, init_token=tokenizer.cls_token_id,\n pad_token=tokenizer.pad_token_id, unk_token=tokenizer.unk_token_id, use_vocab=False, lower=True, batch_first=True, include_lengths=False)\nLABEL = data.LabelField(sequential=False, tokenize=remain_text,\n preprocessing=label_onehot, dtype=torch.float, lower=False, use_vocab=False)\nID = data.LabelField(sequential=False, tokenize=remain_text,\n dtype=torch.float, lower=False, use_vocab=False)\n\nDataSet = data.TabularDataset(\n path='./data/test_data.csv', format='csv',\n fields={'content': ('content', CONTENT),\n 'Id': ('Id', ID)}\n)\n\nBATCH_SIZE = 24\nvalid_iterator = data.BucketIterator(\n DataSet,\n batch_size=BATCH_SIZE,\n device=device,\n sort=False\n)\n\nint2label = {v: k for k, v in label2int.items()}\n\n\ndef inference(batch, model, device):\n model.eval()\n logits = model(batch)\n return logits\n\n\nmodel_path = './model/bert-multilabel_best.pkl'\nmodel = torch.load(model_path, map_location=device)\nmodel.to(device)\n\nthreshold = 0.345\neach_threshold = {'ENGINEERING': threshold,\n 'THEORETICAL': threshold,\n 'EMPIRICAL': threshold,\n 'OTHERS': threshold}\n\nids = []\npredictions = []\n\nlen_valid = len(valid_iterator)\nvalid_loop = tqdm(enumerate(valid_iterator), total=len_valid, position=0)\n\nfor batch_idx, batch in valid_loop:\n logits = inference(batch, model, device)\n logits = nn.Sigmoid()(logits)\n logits = logits.detach().cpu().numpy()\n Id = batch.Id.detach().cpu().numpy()\n for i in range(len(logits)):\n predictions.append(list(logits[i]))\n ids.append(int(Id[i]))\n\ntagging = []\nfor i in range(len(ids)):\n y_hat = [int2label[i] for i, x in enumerate(\n predictions[i]) if x >= each_threshold[int2label[i]]]\n most_pred = np.argmax(predictions[i])\n if len(y_hat) == 0:\n y_hat = [int2label[most_pred]]\n tagging.append(y_hat)\n\nres_id = []\nfor i in range(len(ids)):\n res_id.append([ids[i]]*len(tagging[i]))\n\nsubmit = pd.DataFrame(\n {'Id': list(chain(*res_id)), 'pred': list(chain(*tagging))})\nsubmit = pd.get_dummies(submit, 'pred')\nsubmit = submit.groupby('Id').sum().reset_index()\nsubmit.columns = ['Id', 'EMPIRICAL', 'ENGINEERING', 'OTHERS', 'THEORETICAL']\nsubmit = submit[['Id', 'THEORETICAL', 'ENGINEERING', 'EMPIRICAL', 'OTHERS']]\n\nsubmit.to_csv('./data/submit.csv', index=False)\n","sub_path":"src/eval_test.py","file_name":"eval_test.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"420249373","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis Test involves taking the running average of a handful of images \nto then calculate the difference to the individual images.\n\n- Results are lackluster\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\npath_img = \"D:/ECM_PROJECT/images/\"\n\nlist_img_name = []\nlist_img_name.append(\"12_30_image0000_0.jpg\")\nlist_img_name.append(\"12_30_image0002_0.jpg\")\nlist_img_name.append(\"12_30_image0003_0.jpg\")\nlist_img_name.append(\"12_30_image0005_0.jpg\")\nlist_img_name.append(\"12_30_image0006_0.jpg\")\n\ncv2.destroyAllWindows()\n\n\n# %%\n\ndef load_img_small(imgpath, div_factor=4):\n img = cv2.imread(imgpath, 0) # load img as grayscale\n \n width = int(img.shape[1] / div_factor)\n height = int(img.shape[0] / div_factor)\n dim = (width, height)\n \n resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) \n return resized\n\n\n\n# %%\n\nlist_img = []\n\nfor img_name in list_img_name:\n list_img.append(load_img_small(path_img + img_name,10))\n\n# %%\nksize = 21\nlist_blurr=[]\nfor img in list_img:\n list_blurr.append( cv2.GaussianBlur(img,(ksize,ksize),0) ) # blurr the images\n\n# i=0\n# for img in list_img:\n# i=i+1\n# cv2.imshow('blur_'+str(i),img)\n\n# %%\navg = np.float32(list_blurr[0])\n\nfor img in list_blurr:\n cv2.accumulateWeighted(img,avg,0.1)\navg = np.uint8(avg)\n\ncv2.imshow('image - avg',avg)\n\n# %%\nlist_diff = []\nfor img in list_blurr:\n list_diff.append( np.uint8( np.abs(np.int16(img) - np.int16(avg)) ) )\n\nindex = 4\ncv2.imshow('image - avg',avg)\ncv2.imshow('blurr',list_blurr[index])\ncv2.imshow('diff',list_diff[index])\n\n\n# %%\n\n\n\n\n\n\n\n\n\n\n\n\n# print(\"Hit any key to exit...\")\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n\n\n\ndef main():\n pass\n\n\n# ----------------------------------------------------------------------------\nif __name__== \"__main__\":\n\tprint(\"Calling main function.)\\n\")\n\tmain()","sub_path":"V_01/test_01.py","file_name":"test_01.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"353855516","text":"\n# Given an array of non-negative integers, you are initially positioned at the first index\n# of the array. Each element in the array represents your maximum jump length at that position.\n# Determine if you are able to reach the last index.\n\nclass Solution(object):\n def canJump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if not nums:\n return False\n i = 0\n max_index = nums[i]\n while i < len(nums) and i <= max_index:\n new_index = nums[i] + i\n max_index = max(max_index, new_index)\n i += 1\n if i == len(nums):\n return True\n else:\n return False\n\n\n\n\nif __name__ == '__main__':\n arr = [3,2,1,0,4]\n solution = Solution()\n print(solution.canJump(arr))","sub_path":"Jump Game.py","file_name":"Jump Game.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"271639696","text":"#############################################################\n# Copyright (c) Wilson Lam 2020 #\n# utils.tester contains classes that work with data & model #\n# for testing. To use the module: `import utils.tester` or #\n# `from utils.tester import [class name] #\n#############################################################\n\nimport os\nimport torch\nimport subprocess\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nfrom io import BytesIO\nfrom model import ModelMaker\nfrom dataset.ENindoor67 import ENindoor67Preprocessed, ENindoor67StreamingBody, ENindoor67Datasets\nfrom torch.utils.data import DataLoader\nfrom sklearn.preprocessing import normalize\nfrom sklearn.metrics import classification_report\nfrom matplotlib.ticker import MaxNLocator\nfrom collections import Counter\nfrom heapq import nlargest, nsmallest\n\nBENCHMARK_MODEL = 'resnext101'\n\n\nclass ModelLoader:\n \n \"\"\"\n Base class for Tester. Loads model artefacts.\n \"\"\"\n \n def __init__(self,\n model_loading_params,\n model_weights='best_acc',\n **kwargs):\n \n \"\"\"\n Instantiates a ModelLoader.\n @params model_loading_params (dict) : keyword arguments\n to load a model\n @params model_weights (str) : either `best_acc` or\n `min_val_loss`\n \n return:\n ModelLoader object.\n \"\"\"\n \n # Value checking\n assert model_weights in ['best_acc', 'min_val_loss'],\\\n \"Invalid model weight option: {}.\\\n Either `best_acc` or `min_val_loss`\".format(model_weights)\n \n self._model_weights = model_weights # model weights to store\n self._model_path = self._download_model(**model_loading_params)\n self.load_model() # load model\n \n \n def _download_model(self,\n downloader,\n model_uri,\n local_path,\n session,\n training_job,\n model_file='model.tar.gz',\n **kwargs):\n \n \"\"\"\n Helper function to download model from S3.\n @params downloader (S3Downloader) : S3downloader object\n @params model_uri (str) : model's S3 location\n @params local_path (str) : target path to store `model_file`\n @params session (sagemaker.session): Sagemaker session\n @params training_job (str) : name of training job\n @params model_file (str) : model file name;\n default: `model.tar.gz`\n \n return:\n Path to model arefacts (str)\n \"\"\"\n \n # Set paths & store training job name\n model_path = os.path.join(local_path, model_file)\n model_local_dir = os.path.join(local_path, training_job)\n self._training_job_name = training_job\n \n # Create directory, download model & unzip if file not exist yet\n if not os.path.exists(model_local_dir):\n # Create folder\n os.mkdir(model_local_dir)\n \n # Download model artefacts\n print(\"Downloading model - {} from {}.\".format(training_job,\n model_uri))\n downloader.download(s3_uri=model_uri,\n local_path=local_path,\n sagemaker_session=session)\n \n # Unzip artefacts\n print(\"Unzipping {}...\".format(model_file))\n\n subprocess.check_call(['tar','-zxvf', model_path,\n '-C', model_local_dir+'/'])\n subprocess.check_call(['rm', '-rf', model_path])\n \n return model_local_dir\n \n \n def load_model(self,\n files=dict(\n info='model_info.pth',\n model='model.pth',\n summary='training_summary.pth'),\n benchmark=BENCHMARK_MODEL):\n \n \"\"\"\n Helper function to load model into ModeLoader object.\n @params files (dict) : collection of filenames\n @params benchmark (str) : name of benchmark model\n \"\"\"\n print(\"Loading model.\")\n\n # Load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(self._model_path,\n files['info'])\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n self.model_info = model_info\n \n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model\n device = torch.device(\"cuda\"\n if torch.cuda.is_available()\n else \"cpu\")\n\n # Instantiate the model \n model, _ = ModelMaker().make_model(**model_info)\n \n # Load the training summary\n summary_path = os.path.join(self._model_path,\n files['summary'])\n \n with open(summary_path, 'rb') as f:\n # Skip alternative weights for benchmark model\n if benchmark in self._training_job_name:\n skips = ['best_acc_model_wts',\n 'min_val_loss_model_wts']\n summary = torch.load(f, map_location='cpu')\n self._training_summary = {k:v\n for k, v in summary.items()\n if k not in skips}\n else:\n self._training_summary = torch.load(f,map_location='cpu')\n \n # Model weights to load\n load_wts = self._model_weights + '_model_wts'\n \n if benchmark in self._training_job_name:\n model_path = os.path.join(self._model_path,\n files['model'])\n with open(model_path, 'rb') as model_f:\n model_weights = torch.load(model_f,\n map_location='cpu')\n model.load_state_dict(model_weights)\n else:\n model.load_state_dict(self._training_summary[load_wts])\n \n # Set to eval mode\n model.to(device).eval()\n\n print(\"Done loading model.\")\n self.model = model\n \n \n def to_model(self, model_weights, benchmark=BENCHMARK_MODEL):\n \n \"\"\"\n Switch model weights to a model with best val acc\n or min val loss.\n \n @params model_weights (str) : either `best_acc` or `min_val_loss`\n @params benchmark (str) : name of benchmark model\n \"\"\"\n \n # Value checking\n assert model_weights in ['best_acc', 'min_val_loss'],\\\n \"Invalid model weight option: {}.\\\n Either `best_acc` or `min_val_loss`\".format(model_weights)\n \n # Limit switching for benchmark to avoid KeyError\n assert benchmark not in self._training_job_name, \\\n \"Cannot switch a benchmark model.\"\n \n # Switch and Load model weigths\n self._model_weights = model_weights\n load_wts = self._model_weights + '_model_wts'\n self.model.load_state_dict(self._training_summary[load_wts])\n \n \nclass TestLoader:\n \n \"\"\"\n Helper & base class for loading test data.\n \"\"\"\n \n def __init__(self, data, seed=1, **kwargs):\n \n \"\"\"\n Instantiates a TestLoader object.\n @params data (str) : local or S3 location of\n preprocessed data\n @params seed (int) : random seed\n \"\"\"\n \n # Read data into dataloading objects\n if isinstance(data, BytesIO):\n self.dataset = ENindoor67Preprocessed(data)\n \n else:\n self.dataset = ENindoor67StreamingBody(data)\n \n print(\"Compiled test data.\")\n \n # Set random seed\n self.seed = seed\n \n \n def _load_data(self, batch_size=32, shuffle=True):\n \n \"\"\"\n Fetch Dataloader object.\n @params batch_size (int) : size of each batch\n @params shuffle (bool) : if `True` the data\n will be shuffled\n \n Return torch.utils.data.DataLoader object\n \"\"\"\n \n # Set random seed\n torch.random.manual_seed(self.seed)\n \n return DataLoader(self.dataset,\n batch_size=batch_size,\n shuffle=shuffle)\n \n def _get_class_dict(self):\n\n \"\"\"\n Helper function to retrieve numerical label\n & actual class label mapping dictionary.\n \"\"\"\n \n # Make sure there is a dataset \n assert self.dataset is not None, \\\n \"Empty Dataset: please read in data first.\"\n\n return dict(zip(self.dataset.labels,\n self.dataset.categories))\n\nclass Summaries(ModelLoader):\n \n \"\"\"\n Extends ModelLoader; carries training\n +/- evaluation summaries.\n Parent class of TesterBase object.\n \"\"\"\n \n def __init__(self, **kwargs):\n \n \"\"\"\n Instantiates a Summaries object.\n @params keyword arugments from TesterBase\n \n Following attributes will be loaded with\n _read_summaries():\n @attr _conf_mat (np.array) : confusion matrix\n @attr _predictions (np.array) : model predictions\n @attr _ground_truths(np.array): ground truth label\n @attr _acc_dict (dict) : label-accuracy mappings\n @attr _accuracy (float) : overall accuracy from test\n \"\"\"\n \n ModelLoader.__init__(self, **kwargs)\n self._conf_mat = None\n self._predictions = None\n self._ground_truths = None\n self._accuracy = 0.0\n self._acc_dict = {} # Old version attribute\n self._read_summaries(**kwargs)\n \n \n def __repr__(self):\n \n \"\"\"\n Return all attributes except eval_summary\n \"\"\"\n\n info = 'MIT INDOOR 67 SUMMARIES('\n\n for k, v in self.__dict__.items():\n\n if k == '_eval_summary':\n continue\n\n info += \" {}={}\\n\".format(k, v)\n\n info += \")\"\n\n return info\n \n \n def _read_summaries(self, **kwargs):\n \n \"\"\"\n Read in .pth files to Summaries object.\n Keyword arugments:\n @params summary_path (str) : path to model artefacts\n & summary data\n \"\"\"\n \n # Set paths\n if 'summary_path' in kwargs:\n eval_sum_pth = os.path.join(kwargs['summary_path'],\n 'evaluation_summary.pth')\n \n # Old file format from LocalTester\n eval_sum_pkl = os.path.join(kwargs['summary_path'],\n 'evaluation_summary.pkl')\n \n train_sum_path = os.path.join(kwargs['summary_path'],\n 'training_summary.pth')\n \n model_info_path = os.path.join(kwargs['summary_path'],\n 'model_info.pth')\n \n # Evaluation Summary\n \n if (os.path.exists(eval_sum_pth)\n or os.path.exists(eval_sum_pkl)):\n \n if os.path.exists(eval_sum_pth):\n summary = torch.load(open(eval_sum_pth, 'rb'),\n map_location='cpu')\n else:\n summary = pickle.load(open(eval_sum_pkl, 'rb'))\n\n items = self.__dict__.keys()\n for item in items:\n try:\n self.__dict__[item] = summary[self._model_weights][item]\n except KeyError:\n continue\n\n self._eval_summary = self.__dict__\n \n # Training Summary\n if os.path.exists(train_sum_path):\n self._training_summary = torch.load(open(train_sum_path, 'rb'),\n map_location='cpu')\n \n # Model Info\n if os.path.exists(model_info_path):\n self.model_info = torch.load(open(model_info_path, 'rb'),\n map_location='cpu')\n\n \n def confusion_matrix(self, normalized=True, show=True):\n \n \"\"\"\n Return confusion matrix of the evaluated model.\n @params normalized (bool) : if `True` the matrix\n will be normalized;\n @params show (bool) : if `True`, plot the matrix\n \"\"\"\n \n assert self._conf_mat is not None, \\\n \"Empty Confusion Matrix. Please evaluate the model first.\"\n \n # Copy the confusion matrix\n conf_mat = self._conf_mat\n \n # Set plot title\n title = \"Confusion Matrix\"\n \n # Normalize the matrix & update title if `normalized` = True\n if normalized:\n conf_mat = normalize(conf_mat, axis=1, norm='l1')\n title = \"Normalized \" + title\n \n # Return matrix in np.array if `show` is False\n if not show:\n return conf_mat\n \n fig, ax = plt.subplots(figsize=(15,15))\n sns.heatmap(conf_mat, cmap='BuPu', linewidths=.5, ax=ax)\n ax.set_title(title)\n plt.show()\n \n\n def report(self, averaged=False, style=False):\n \n \"\"\"\n Return classification report from evaluation as pd.Dataframe.\n \"\"\"\n \n # Data Check\n assert (self._ground_truths is not None\n and self._predictions is not None),\\\n \"Empty data. Please evaluate the model first.\"\n \n # Get report as dictionary\n report_dict = classification_report(self._ground_truths,\n self._predictions,\n zero_division=0,\n output_dict=True)\n \n output = pd.DataFrame.from_dict(report_dict).T\n \n if averaged:\n output = pd.DataFrame.from_dict(report_dict).T[-3:]\n \n if style:\n return output.style\n \n return output\n \n \n def _sort_k(self, k, metric, ascending):\n \n \n \"\"\"\n Base function of bottom_k() and top_k()\n @params k (int): number of classes to show\n @params metric (str): metric to determine sorting:\n `precision`, `recall`, or `f1`\n @params ascending(bool): `True` for bottom_k(),\n `False` for top_k()\n \"\"\"\n \n # Data Check\n assert (self._ground_truths is not None\n and self._predictions is not None),\\\n \"Empty data. Please evaluate the model first.\"\n \n assert k <= len(self._predictions), \\\n \"Invalid number for MIT 67 Indoort Dataset. \\\n Must be smaller or equal to {}.\" \\\n .format(len(self._predictions))\n \n assert metric in ['precision', 'recall', 'f1-score'], \\\n \"Metric can only either be `precision`, `recall`,\"\\\n \" or `f1`, not {}\".format(metric)\n \n try:\n class_dict = self._get_class_dict()\n \n except:\n if '_acc_dict' in self.__dict__: # Old version attribute\n class_dict = dict([label.split(' - ')\n for label in self._acc_dict])\n \n else:\n class_dict = self.class_dict\n \n \n return (self.report()\n .reset_index()\n .replace(class_dict)\n .rename(columns={'index':'category'})\n .set_index('category')[:-3][metric]\n .sort_values(ascending=ascending)[:k]\n .apply(pd.Series)\n .rename(columns={0:metric})\n .style)\n \n \n \n def bottom_k(self, k, metric='precision'):\n \n \"\"\"\n Return the lowest k classes w.r.t `metric`.\n @params k (int): number of classes to show\n @params metric (str): metric to determine sorting:\n `precision`, `recall`, or `f1`\n \"\"\"\n \n return self._sort_k(k=k, metric=metric, ascending=True)\n \n \n def top_k(self, k, metric='precision'):\n \n \"\"\"\n Return the highest k classes w.r.t `metric`.\n @params k (int): number of classes to show\n @params metric (str): metric to determine sorting:\n `precision`, `recall`, or `f1`\n \"\"\"\n \n return self._sort_k(k=k, metric=metric, ascending=False)\n \n \n def training_history(self):\n \n \"\"\"\n Plot training and validation accuracy and loss.\n \"\"\"\n \n # Check if value exists\n assert self.model_info is not None, \\\n \"Model info not found.\"\n assert self._training_summary is not None, \\\n \"Training summary not found.\"\n \n # Load information and write to title\n \n # Model information \n model_info = \"model: {}\".format(self.model_info['model'])\n \n # Hyperparameters, model architecture, and optimizer settings\n hp = ', '.join([\"{}={}\".format(k,v)\n for k, v in self._training_summary['hyperparameters'].items()\n if k in ['batch_size',\n 'optimizer',\n 'lr',\n 'dropout',\n 'sampling',\n 'blocks_unfrozen']])\n \n # Best validation accuracy \n best_val_acc = \"best val acc: \\\n {}\".format(self._training_summary['best_acc'])\n \n # Minimum validation loss\n min_val_loss = \"min val loss: \\\n {}\".format(self._training_summary['min_val_loss'])\n \n # Setting layouts \n fig, axes = plt.subplots(1, 2, figsize=(16,8))\n fig.subplots_adjust(top=0.8)\n \n # Enumerate `training_summary` dict and plot data\n aspects = ['loss', 'accuracy']\n for i, aspect in enumerate(aspects):\n hist = self._training_summary[aspect]\n for phase in ['train', 'val']:\n axes[i].plot(np.arange(1, len(hist[phase])+1), hist[phase], label=phase)\n axes[i].set_title(aspect.upper())\n axes[i].set_xlabel('epochs')\n axes[i].set_ylabel(aspect)\n axes[i].xaxis.set_major_locator(MaxNLocator(nbins=5, integer=True))\n axes[i].legend()\n\n \n # Write title\n fig.suptitle(\"Training History\\\n \\n{}\\n{}\\n{}\\n{}\".format(model_info,\n hp,\n best_val_acc,\n min_val_loss), fontsize=16, y = 0.98)\n plt.show()\n\n \nclass TesterBase(TestLoader, Summaries):\n \n \"\"\"\n Base class for Testers:\n Parent classes: TestLoader & Summaries\n \"\"\"\n \n def __init__(self, **kwargs):\n \n \"\"\"\n Construct by passing kwargs to parent classes\n \"\"\"\n \n Summaries.__init__(self, **kwargs)\n TestLoader.__init__(self, **kwargs)\n \n \nclass LocalTester(TesterBase):\n \n \"\"\"\n Object to administer testing at local computer.\n Parent class: TesterBase\n \"\"\" \n \n def __init__(self,\n show_history=False,\n **kwargs):\n \n \"\"\"\n Construct LocalTester.\n @params show_history (bool) : if `True`, plot training\n history; default: `False`\n @params keyword arguments to be passed to parent class\n \"\"\"\n # Pass kwargs to parent class \n TesterBase.__init__(self, **kwargs)\n self.class_dict = self._get_class_dict()\n \n # Plot training history if show_history is `True` \n if show_history:\n self.training_history()\n \n \n def __repr__(self):\n \n \"\"\"\n Show Training summary / test summary.\n \"\"\"\n \n skip_items = ['training_time',\n 'best_acc_model_wts',\n 'min_val_loss_model_wts']\n \n details = self._training_summary\n info = 'MIT_INDOOR_67_TRAINING_SUMMARY('\n if self._eval_summary:\n info = 'MIT_INDOOR_67_TESTING SUMMARY('\n details = self._eval_summary\n skip_items += ['_training_summary']\n \n for k, v in details.items():\n \n if k in skip_items:\n continue\n \n info += \" {}={}\\n\".format(k, v)\n \n info += \")\"\n \n return info\n \n \n def run(self, batch_size=32):\n \n \"\"\"\n Evaluate model on test set;\n load test set from grandparent class TestLoader.\n \n @param batch_size (int) : size of each batch\n \n Write evaluation summary to self._eval_summary\n and file `evaluation summary.pth`\n \"\"\"\n \n device = torch.device(\"cuda\"\n if torch.cuda.is_available()\n else \"cpu\")\n \n # Initialize variables\n num_classes = self._training_summary['hyperparameters']['num_classes']\n self._conf_mat = np.zeros((num_classes, num_classes),int) \n ground_truth = np.array([])\n predicted = np.array([])\n dataloader = self._load_data(batch_size=batch_size)\n \n print(\"Start evaluating model on test data...\")\n \n self.model.to(device)\n \n # Iterate through each batch of test data\n for i, batch in enumerate(dataloader):\n \n batch_x, batch_y = batch\n \n batch_x = batch_x.to(device)\n batch_y = batch_y.to(device)\n with torch.set_grad_enabled(False):\n y_preds = self.model(batch_x)\n _, preds = torch.max(y_preds.data, 1)\n \n ground_truth = np.append(ground_truth,\n batch_y.numpy())\n predicted = np.append(predicted,\n preds.numpy())\n \n if (i+1) % 10 == 0:\n print(\"{} / {} batch of test data evaluated\"\n .format(i+1, len(dataloader)))\n \n # Store y and y_hat in LocalTester instance\n self._ground_truths = ground_truth.astype('int32')\n self._predictions = predicted.astype('int32')\n \n # Count y and y_hat pairs\n temp_dict = Counter(zip(self._ground_truths,\n self._predictions))\n \n # Enumerate y and y_hat and store values in confusion matrix \n for k, v in temp_dict.items():\n self._conf_mat[k] = v\n \n # Calcuate the overall Top-1 accuracy of each class\n true_positives = np.diag(self._conf_mat)\n self._accuracy = (true_positives.sum() / \n (len(true_positives) * \n 1.0))\n \n \n print(\"Evaluation ends.\")\n print(\"TEST ACC: {}\".format(self._accuracy))\n \n # Write evaluation summary to instance and file\n self.eval_summary(verbose=False, to_pickle=True)\n \n \n def eval_summary(self, verbose=True, to_pickle=False):\n \n \"\"\"\n Store evaluation summary to instance.\n @params verbose (bool) : if `True`, print out summary\n @params to_pickle(bool) : if `True`, write summary to file\n \"\"\"\n \n # Items to skip \n skip_items = ['model',\n 'dataset',\n '_model_path',\n 'seed',\n '_model_weights',\n '_training_summary',\n 'model_info',\n '_eval_summary']\n \n # Store values in a dictionary\n self._eval_summary = {\n self._model_weights :\n {\n k : v\n for k, v in self.__dict__.items()\n if k not in skip_items\n }\n }\n \n # Print evaluation summary\n if verbose:\n print(self)\n \n # Write to file\n if to_pickle:\n eval_file = os.path.join(self._model_path, 'evaluation_summary.pth')\n \n if os.path.exists(eval_file):\n existing_summary = torch.load(open(eval_file, 'rb'),\n map_location='cpu')\n self._eval_summary.update(existing_summary)\n\n with open(eval_file, 'wb') as f:\n torch.save(self._eval_summary, f)\n \n\n# Under construction\n# class S3Tester(TesterBase):\n \n# def __init__(self, model, **kwargs):\n# TesterBase.__init__(self, **kwargs)\n# self.dataloader = self._load_data(batch_size=200)\n# self.model = model\n \n# def run(self):\n# device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n# self.model.to(device)\n# self._predictions = np.array([])\n# self._ground_truths = np.array([])\n \n# for batch in self.dataloader:\n \n# batch_x, batch_y = batch\n# batch_x = batch_x.to(device)\n# batch_y = batch_y.to(device)\n# with torch.set_grad_enabled(False):\n# y_preds = self.model(batch_x)\n# _, preds = torch.max(y_preds.data, 1)\n \n# self._ground_truth = np.append(self._ground_truth,\n# batch_y.cpu().detach().numpy())\n# self._predictions = np.append(self._predictions,\n# preds.cpu().detach().numpy())\n \n# assert len(self._ground_truth) == len(self._predictions)\n# length = len(self._ground_truth)\n# output = np.concatenate([self._predictions,\n# self._ground_truths]).reshape(2, length)\n \n# return output\n \n \n \n ","sub_path":"source/utils/.ipynb_checkpoints/tester-checkpoint.py","file_name":"tester-checkpoint.py","file_ext":"py","file_size_in_byte":27487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"237409307","text":"# -*- coding: utf8 -*-\n\"\"\"\nParse data in ini format\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nimport logging\n\n# code from project kaptan\ntry:\n import ConfigParser as configparser\n from StringIO import StringIO\n\n configparser.RawConfigParser.read_file = configparser.RawConfigParser.readfp\nexcept ImportError: # Python 3\n import configparser\n from io import StringIO\n\nfrom . import BaseParser\n\nLOGGER = logging.getLogger(\"config\")\n\n\nclass KaptanIniParser(configparser.RawConfigParser):\n \"\"\"\n internal parser\n \"\"\"\n\n def as_dict(self):\n \"\"\"\n transfer to dict\n \"\"\"\n\n d = dict(self._sections)\n for k in d:\n d[k] = dict(self._defaults, **d[k])\n d[k].pop('__name__', None)\n return d\n\n\nclass IniParser(BaseParser):\n \"\"\"\n Parse data in ini format\n \"\"\"\n\n def __init__(self, name):\n \"\"\"\n :param name: parser name\n \"\"\"\n super(IniParser, self).__init__()\n self.name = name\n\n def parse(self, data):\n \"\"\"\n parse text in ini format to python dict\n :param data: text in ini format\n \"\"\"\n\n config = KaptanIniParser()\n try:\n # ConfigParser.ConfigParser wants to read value as file / IO\n config.read_file(StringIO(data))\n return config.as_dict()\n except Exception as err:\n LOGGER.error('config %s: fail to parse ini config, the error is %s', self.name, err)\n return {}\n\n def dump(self, config):\n \"\"\"\n not implement for ini format\n \"\"\"\n\n raise NotImplementedError('Exporting .ini format is not supported.')\n","sub_path":"complexconfig_python/complexconfig/parser/ini_parser.py","file_name":"ini_parser.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"350667758","text":"import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('0.0.0.0', 2222))\ns.listen(10)\n\nwhile True:\n conn, addr = s.accept()\n data = conn.recv(1024)\n print(data)\n if not data or data == b\"close\":\n print(\"no data\")\n else:\n print(\"another data\")\n conn.send(data)\n conn.close()\n","sub_path":"Web_tehnology/zad_server10_1_6_7.py","file_name":"zad_server10_1_6_7.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"533702052","text":"# 导入库\nimport copy\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import r2_score\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\n\n# 库设置\nsns.set_style(\"darkgrid\")\nwarnings.filterwarnings(\"ignore\")\n\n\nif __name__ == '__main__':\n \"\"\"---------------------------------------准备---------------------------------------\"\"\"\n # 导入完整数据\n df = pd.read_csv('../data/cleaned_google_play_store.csv')\n\n # 导入数值数据\n numerical_features = ['Rating', 'Reviews', 'Size', 'Installs', 'Price',\n 'Last Updated Till Now', 'Android Ver', 'Name Length',\n 'Data Flow', 'Sale Volume', 'Review Install Ratio']\n numerical_data = pd.read_csv('../data/cleaned_google_play_store.csv', usecols=numerical_features)\n\n # 导入机器学习格式数据\n ml_features = ['Reviews', 'Size', 'Installs', 'Price',\n 'Last Updated Till Now', 'Android Ver', 'Name Length',\n 'Data Flow', 'Sale Volume', 'Review Install Ratio']\n x = pd.read_csv('../data/cleaned_google_play_store.csv', usecols=ml_features)\n y = pd.read_csv('../data/cleaned_google_play_store.csv', usecols=['Rating', ])\n x_train, x_test, y_train, y_test = train_test_split(x.values, y.values, test_size=0.3, random_state=6)\n\n \"\"\"---------------------------------------单特征分析---------------------------------------\"\"\"\n # 单特征分布情况柱状图 (e.g. Category; Content Rating)\n plt.figure(figsize=(15, 19))\n fig = sns.countplot(x=df['Category'])\n fig.set_xticklabels(fig.get_xticklabels(), rotation=90)\n plt.savefig('../image/category_bar.png', dpi=170)\n\n plt.figure(figsize=(15, 19))\n fig = sns.countplot(x=df['Content Rating'])\n fig.set_xticklabels(fig.get_xticklabels(), rotation=90)\n plt.savefig('../image/content_rating_bar.png', dpi=170)\n\n # 单特征分布情况密度图 (e.g. Rating; Android Ver; Last Updated Till Now; Name Length)\n plt.figure()\n fig = sns.distplot(a=df['Rating'].values, kde=True, bins=50, color='purple', axlabel='Rating')\n plt.legend([\"($\\mu=${0:.2g}, $\\sigma=${1:.2f})\".format(np.average(df['Rating'].values),\n np.std(df['Rating'].values))])\n plt.savefig('../image/rating_distribution.png', dpi=170)\n\n plt.figure()\n fig = sns.distplot(a=df['Last Updated Till Now'].values, kde=False, bins=50, color='purple',\n axlabel='Last Updated Till Now')\n plt.legend([\"($\\mu=${0:.2g}, $\\sigma=${1:.2f})\".format(np.average(df['Last Updated Till Now'].values),\n np.std(df['Last Updated Till Now'].values))])\n plt.savefig('../image/last_updated_till_now_distribution.png', dpi=170)\n\n plt.figure()\n fig = sns.distplot(a=df['Android Ver'].values, kde=True, bins=50, color='purple', axlabel='Android Ver')\n plt.legend([\"($\\mu=${0:.2g}, $\\sigma=${1:.2f})\".format(np.average(df['Android Ver'].values),\n np.std(df['Android Ver'].values))])\n plt.savefig('../image/android_ver_distribution.png', dpi=170)\n\n plt.figure()\n fig = sns.distplot(a=df['Name Length'].values, kde=True, bins=50, color='purple', axlabel='Name Length')\n plt.legend([\"($\\mu=${0:.2g}, $\\sigma=${1:.2f})\".format(np.average(df['Name Length'].values),\n np.std(df['Name Length'].values))])\n plt.savefig('../image/name_length_distribution.png', dpi=170)\n\n # Mean-Decreased Impurity(MDI) 数值特征重要性直方图\n rf_mdi = RandomForestRegressor(n_estimators=200, n_jobs=-1, random_state=6)\n rf_mdi.fit(x, y)\n feature_importance_list = list(map(lambda x: round(x, 3), rf_mdi.feature_importances_))\n mdi_feature_importance_data_frame = pd.DataFrame()\n mdi_feature_importance_data_frame['feature_name'] = pd.Series(ml_features)\n mdi_feature_importance_data_frame['mdi_feature_importance'] = pd.Series(feature_importance_list)\n plt.figure(figsize=(15, 7))\n fig = sns.barplot(x='mdi_feature_importance', y='feature_name', data=mdi_feature_importance_data_frame)\n plt.savefig('../image/mdi_feature_importance.png', dpi=170)\n\n # Mean-Decreased Accuracy(MDA) 数值特征重要性直方图\n rf_mda = RandomForestRegressor(n_estimators=200, n_jobs=-1, random_state=6)\n rf_mda.fit(x_train, y_train)\n original_r2_score = r2_score(y_test, rf_mda.predict(x_test))\n mda_feature_importance_list = []\n for (index, feature) in enumerate(ml_features):\n x_feature_permutation_test = copy.deepcopy(x_test)\n np.random.shuffle(x_feature_permutation_test[:, index])\n permutation_r2_score = r2_score(y_test, rf_mda.predict(x_feature_permutation_test))\n mda = (original_r2_score - permutation_r2_score) / original_r2_score\n mda_feature_importance_list.append(mda)\n mda_feature_importance_data_frame = pd.DataFrame()\n mda_feature_importance_data_frame['feature_name'] = pd.Series(ml_features)\n mda_feature_importance_data_frame['mda_feature_importance'] = pd.Series(mda_feature_importance_list)\n plt.figure(figsize=(15, 7))\n fig = sns.barplot(x='mda_feature_importance', y='feature_name', data=mda_feature_importance_data_frame)\n plt.savefig('../image/mda_feature_importance.png', dpi=170)\n\n \"\"\"---------------------------------------双特征分析---------------------------------------\"\"\"\n # 相关性矩阵热力图 (只有数值型特征参与运算)\n correlations = numerical_data.corr()\n plt.figure(figsize=(19, 19))\n sns.heatmap(correlations, xticklabels=correlations.columns,\n yticklabels=correlations.columns, cmap='RdYlGn',\n center=0, annot=True)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.savefig('../image/correlation.png', dpi=170)\n\n # 全数值特征散点图 (只有数值型特征参与运算)\n plt.figure(figsize=(40, 40))\n fig = sns.pairplot(numerical_data)\n plt.savefig('../image/pairwise_scatter.png', dpi=170)\n\n # 双特征散点图与线性回归线 (e.g. 数值单特征 vs Rating)\n plt.figure()\n fig = sns.jointplot(x='Reviews', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/reviews_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Size', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/size_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Installs', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/installs_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Last Updated Till Now', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/lutn_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Android Ver', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/android_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Name Length', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/name_length_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Data Flow', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/dataflow_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Sale Volume', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/sale_volume_rating.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Review Install Ratio', y='Rating', data=df, color='purple', kind='reg')\n plt.savefig('../image/rir_rating.png', dpi=170)\n\n # 双特征散点图与线性回归线 (相关性绝对值高的双特征 e.g. Reviews vs Installs, LUTN vs Android Ver)\n plt.figure()\n fig = sns.jointplot(x='Last Updated Till Now', y='Android Ver', data=df, color='purple', kind='reg')\n plt.savefig('../image/lutn_av_.png', dpi=170)\n\n plt.figure()\n fig = sns.jointplot(x='Reviews', y='Installs', data=df, color='purple', kind='reg')\n plt.savefig('../image/reviews_installs_.png', dpi=170)\n\n # 类(category)内Rating分布密度图\n category_to_rating_list = {}\n for i in range(len(df)):\n if df['Category'].values[i] in category_to_rating_list:\n category_to_rating_list[df['Category'].values[i]].append(df['Rating'].values[i])\n else:\n category_to_rating_list[df['Category'].values[i]] = [df['Rating'].values[i], ]\n\n color_list = ['red', 'orange', 'grey', 'green', 'blue', 'purple', 'cyan', 'chocolate', 'coral', 'gold', 'khaki',\n 'lavender', 'maroon', 'linen', 'lime', 'navy', 'olive', 'midnightblue', 'paleturquoise', 'pink',\n 'salmon', 'sienna', 'tan', 'teal', 'wheat', 'white', 'black', 'aqua', 'aquamarine', 'azure', 'beige',\n 'bisque', 'fuchsia']\n fig = plt.figure(figsize=(20, 10))\n ax1 = fig.add_subplot(111)\n for (index, category) in enumerate(category_to_rating_list):\n ax1 = sns.kdeplot(np.array(category_to_rating_list[category]),\n shade=False,\n label=category,\n color=color_list[index])\n ax1.set_xlabel('Rating')\n ax1.set_ylabel('Density')\n plt.savefig('../image/rating_across_category.png', dpi=170)\n\n # 年龄层(content Rating)内Rating分布密度图\n content_to_rating_list = {}\n for i in range(len(df)):\n if df['Content Rating'].values[i] in content_to_rating_list:\n content_to_rating_list[df['Content Rating'].values[i]].append(df['Rating'].values[i])\n else:\n content_to_rating_list[df['Content Rating'].values[i]] = [df['Rating'].values[i], ]\n\n fig = plt.figure(figsize=(10, 5))\n ax1 = fig.add_subplot(111)\n for (index, content_rating) in enumerate(content_to_rating_list):\n ax1 = sns.kdeplot(np.array(content_to_rating_list[content_rating]),\n shade=False,\n label=content_rating,\n color=color_list[index])\n ax1.legend(loc=(index + 1))\n ax1.set_xlabel('Rating')\n ax1.set_ylabel('Density')\n plt.savefig('../image/rating_across_content.png', dpi=170)\n","sub_path":"code/2_data_analysis.py","file_name":"2_data_analysis.py","file_ext":"py","file_size_in_byte":10373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"270734816","text":"whalecounts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]\n\n\ndef find_two_smallest(L):\n \"\"\" (see before) \"\"\"\n # Get a sorted copy of the list so that the two smallest items are at the\n # front\n temp_list= sorted(L)\n smallest = temp_list[0]\n next_smallest= temp_list[1]\n # Find their indices in the original list L\n min1 = L.index(smallest)\n min2 = L.index(next_smallest)\n # Return the indices of the two\n return (min1, min2)\n\n\nif __name__ == '__main__':\n print(find_two_smallest(whalecounts))","sub_path":"Intro_To_Python/Lec17/sort_then_find3.py","file_name":"sort_then_find3.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"477516309","text":"import gym\nfrom rlkit.data_management.awr_env_replay_buffer import AWREnvReplayBuffer\nfrom rlkit.data_management.env_replay_buffer import EnvReplayBuffer\nfrom rlkit.data_management.split_buffer import SplitReplayBuffer\nfrom rlkit.envs.wrappers import NormalizedBoxEnv, StackObservationEnv, RewardWrapperEnv\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.samplers.data_collector import MdpPathCollector, ObsDictPathCollector\nfrom rlkit.samplers.data_collector.step_collector import MdpStepCollector\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterministic, PolicyFromQ\nfrom rlkit.torch.sac.awac_trainer import AWACTrainer\nfrom rlkit.torch.torch_rl_algorithm import (\n TorchBatchRLAlgorithm,\n TorchOnlineRLAlgorithm,\n)\n\nfrom rlkit.demos.source.hdf5_path_loader import HDF5PathLoader\nfrom rlkit.demos.source.mdp_path_loader import MDPPathLoader\nfrom rlkit.visualization.video import save_paths, VideoSaveFunction\n\nfrom multiworld.core.flat_goal_env import FlatGoalEnv\nfrom multiworld.core.image_env import ImageEnv\nfrom multiworld.core.gym_to_multi_env import GymToMultiEnv\n\nfrom rlkit.launchers.experiments.ashvin.rfeatures.encoder_wrapped_env import EncoderWrappedEnv\nfrom rlkit.launchers.experiments.ashvin.rfeatures.rfeatures_model import TimestepPredictionModel\n\nimport torch\nimport numpy as np\nfrom torchvision.utils import save_image\n\nfrom rlkit.exploration_strategies.base import \\\n PolicyWrappedWithExplorationStrategy\nfrom rlkit.exploration_strategies.gaussian_and_epislon import GaussianAndEpislonStrategy\nfrom rlkit.exploration_strategies.ou_strategy import OUStrategy\n\nimport os.path as osp\nfrom rlkit.core import logger\nfrom rlkit.misc.asset_loader import load_local_or_remote_file\nimport pickle\n\nimport copy\nimport torch.nn as nn\nfrom rlkit.samplers.data_collector import MdpPathCollector # , CustomMdpPathCollector\nfrom rlkit.demos.source.dict_to_mdp_path_loader import DictToMDPPathLoader\nfrom rlkit.torch.networks import MlpQf, TanhMlpPolicy\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy\nfrom rlkit.torch.lvm.bear_vae import VAEPolicy\nfrom rlkit.torch.sac.bear import BEARTrainer\nfrom rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm\n\n\nENV_PARAMS = {\n 'half-cheetah': { # 6 DoF\n 'env_id':'HalfCheetah-v2',\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'HalfCheetah-v2',\n 'env_demo_path': dict(\n path=\"demos/icml2020/mujoco/hc_action_noise_15.npy\",\n obs_dict=False,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n path=\"demos/icml2020/mujoco/hc_off_policy_15_demos_100.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'ant': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Ant-v2',\n 'env_demo_path': dict(\n path=\"demos/icml2020/mujoco/ant_action_noise_15.npy\",\n obs_dict=False,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n path=\"demos/icml2020/mujoco/ant_off_policy_15_demos_100.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'walker': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Walker2d-v2',\n 'env_demo_path': dict(\n path=\"demos/icml2020/mujoco/walker_action_noise_15.npy\",\n obs_dict=False,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n path=\"demos/icml2020/mujoco/walker_off_policy_15_demos_100.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'hopper': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Hopper-v2'\n },\n 'humanoid': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Humanoid-v2'\n },\n 'inv-double-pendulum': { # 2 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'InvertedDoublePendulum-v2'\n },\n 'pendulum': { # 2 DoF\n 'num_expl_steps_per_train_loop': 200,\n 'max_path_length': 200,\n 'min_num_steps_before_training': 2000,\n 'target_update_period': 200,\n 'env_id':'Pendulum-v2'\n },\n 'swimmer': { # 6 DoF\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'env_id':'Swimmer-v2'\n },\n\n 'pen-v0': {\n 'env_id': 'pen-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n 'door-v0': {\n 'env_id': 'door-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n 'relocate-v0': {\n 'env_id': 'relocate-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n 'hammer-v0': {\n 'env_id': 'hammer-v0',\n # 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 200,\n # 'num_epochs': 1000,\n },\n\n 'pen-sparse-v0': {\n 'env_id': 'pen-binary-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/pen2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n # path=\"demos/icml2020/hand/pen_bc_sparse1.npy\",\n # path=\"demos/icml2020/hand/pen_bc_sparse2.npy\",\n # path=\"demos/icml2020/hand/pen_bc_sparse3.npy\",\n path=\"demos/icml2020/hand/pen_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'door-sparse-v0': {\n 'env_id': 'door-binary-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/door2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n # path=\"demos/icml2020/hand/door_bc_sparse1.npy\",\n # path=\"demos/icml2020/hand/door_bc_sparse3.npy\",\n path=\"demos/icml2020/hand/door_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'relocate-sparse-v0': {\n 'env_id': 'relocate-binary-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/relocate2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n # path=\"demos/icml2020/hand/relocate_bc_sparse1.npy\",\n path=\"demos/icml2020/hand/relocate_bc_sparse4.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n 'hammer-sparse-v0': {\n 'env_id': 'hammer-binary-v0',\n 'max_path_length': 200,\n 'sparse_reward': True,\n 'env_demo_path': dict(\n path=\"demos/icml2020/hand/hammer2_sparse.npy\",\n obs_dict=True,\n is_demo=True,\n ),\n 'env_offpolicy_data_path': dict(\n path=\"demos/icml2020/hand/hammer_bc_sparse1.npy\",\n obs_dict=False,\n is_demo=False,\n train_split=0.9,\n ),\n },\n}\n\ndef compute_hand_sparse_reward(next_obs, reward, done, info):\n return info['goal_achieved'] - 1\n\ndef encoder_wrapped_env(variant):\n representation_size = 128\n output_classes = 20\n\n model_class = variant.get('model_class', TimestepPredictionModel)\n model = model_class(\n representation_size,\n # decoder_output_activation=decoder_activation,\n output_classes=output_classes,\n **variant['model_kwargs'],\n )\n # model = torch.nn.DataParallel(model)\n\n model_path = variant.get(\"model_path\")\n # model = load_local_or_remote_file(model_path)\n state_dict = torch.load(model_path)\n model.load_state_dict(state_dict)\n model.to(ptu.device)\n model.eval()\n\n traj = np.load(variant.get(\"desired_trajectory\"), allow_pickle=True)[0]\n\n goal_image = traj[\"observations\"][-1][\"image_observation\"]\n goal_image = goal_image.reshape(1, 3, 500, 300).transpose([0, 1, 3, 2]) / 255.0\n # goal_image = goal_image.reshape(1, 300, 500, 3).transpose([0, 3, 1, 2]) / 255.0 # BECAUSE RLBENCH DEMOS ARENT IMAGE_ENV WRAPPED\n # goal_image = goal_image[:, :, :240, 60:500]\n goal_image = goal_image[:, :, 60:, 60:500]\n goal_image_pt = ptu.from_numpy(goal_image)\n save_image(goal_image_pt.data.cpu(), 'gitignore/goal.png', nrow=1)\n goal_latent = model.encode(goal_image_pt).detach().cpu().numpy().flatten()\n\n initial_image = traj[\"observations\"][0][\"image_observation\"]\n initial_image = initial_image.reshape(1, 3, 500, 300).transpose([0, 1, 3, 2]) / 255.0\n # initial_image = initial_image.reshape(1, 300, 500, 3).transpose([0, 3, 1, 2]) / 255.0\n # initial_image = initial_image[:, :, :240, 60:500]\n initial_image = initial_image[:, :, 60:, 60:500]\n initial_image_pt = ptu.from_numpy(initial_image)\n save_image(initial_image_pt.data.cpu(), 'gitignore/initial.png', nrow=1)\n initial_latent = model.encode(initial_image_pt).detach().cpu().numpy().flatten()\n\n # Move these to td3_bc and bc_v3 (or at least type for reward_params)\n reward_params = dict(\n goal_latent=goal_latent,\n initial_latent=initial_latent,\n type=variant[\"reward_params_type\"],\n )\n\n config_params = variant.get(\"config_params\")\n\n env = variant['env_class'](**variant['env_kwargs'])\n env = ImageEnv(env,\n recompute_reward=False,\n transpose=True,\n image_length=450000,\n reward_type=\"image_distance\",\n # init_camera=sawyer_pusher_camera_upright_v2,\n )\n env = EncoderWrappedEnv(\n env,\n model,\n reward_params,\n config_params,\n **variant.get(\"encoder_wrapped_env_kwargs\", dict())\n )\n env = FlatGoalEnv(env, obs_keys=[\"state_observation\", ])\n\n return env\n\n\ndef resume(variant):\n data = load_local_or_remote_file(variant.get(\"pretrained_algorithm_path\"), map_location=\"cuda\")\n algo = data['algorithm']\n\n algo.num_epochs = variant['num_epochs']\n\n post_pretrain_hyperparams = variant[\"trainer_kwargs\"].get(\"post_pretrain_hyperparams\", {})\n algo.trainer.set_algorithm_weights(**post_pretrain_hyperparams)\n\n algo.train()\n\n\ndef process_args(variant):\n if variant.get(\"debug\", False):\n variant['max_path_length'] = 50\n variant['batch_size'] = 5\n variant['num_epochs'] = 5\n variant['num_eval_steps_per_epoch'] = 100\n variant['num_expl_steps_per_train_loop'] = 100\n variant['num_trains_per_train_loop'] = 10\n variant['min_num_steps_before_training'] = 100\n variant['trainer_kwargs']['num_pretrain_steps'] = min(10, variant['trainer_kwargs'].get('num_pretrain_steps', 0))\n\n\ndef experiment(variant):\n import mj_envs\n\n env_params = ENV_PARAMS.get(variant.get('env'), {})\n variant.update(env_params)\n env_name = variant.get(\"env\", None)\n env_id = variant.get('env_id', None)\n env_class = variant.get('env_class', None)\n\n if env_name in [\n 'pen-v0', 'pen-sparse-v0', 'pen-notermination-v0', 'pen-binary-v0',\n 'door-v0', 'door-sparse-v0', 'door-binary-v0',\n 'relocate-v0', 'relocate-sparse-v0', 'relocate-binary-v0',\n 'hammer-v0', 'hammer-sparse-v0', 'hammer-binary-v0',\n ]:\n import mj_envs\n expl_env = gym.make(env_params.get('env_id', env_name))\n eval_env = gym.make(env_params.get('env_id', env_name))\n elif env_name in [ # D4RL envs\n \"maze2d-open-v0\", \"maze2d-umaze-v0\", \"maze2d-medium-v0\", \"maze2d-large-v0\",\n \"maze2d-open-dense-v0\", \"maze2d-umaze-dense-v0\", \"maze2d-medium-dense-v0\", \"maze2d-large-dense-v0\",\n \"antmaze-umaze-v0\", \"antmaze-umaze-diverse-v0\", \"antmaze-medium-diverse-v0\",\n \"antmaze-medium-play-v0\", \"antmaze-large-diverse-v0\", \"antmaze-large-play-v0\",\n \"pen-human-v0\", \"pen-cloned-v0\", \"pen-expert-v0\", \"hammer-human-v0\", \"hammer-cloned-v0\", \"hammer-expert-v0\",\n \"door-human-v0\", \"door-cloned-v0\", \"door-expert-v0\", \"relocate-human-v0\", \"relocate-cloned-v0\", \"relocate-expert-v0\",\n \"halfcheetah-random-v0\", \"halfcheetah-medium-v0\", \"halfcheetah-expert-v0\", \"halfcheetah-mixed-v0\", \"halfcheetah-medium-expert-v0\",\n \"walker2d-random-v0\", \"walker2d-medium-v0\", \"walker2d-expert-v0\", \"walker2d-mixed-v0\", \"walker2d-medium-expert-v0\",\n \"hopper-random-v0\", \"hopper-medium-v0\", \"hopper-expert-v0\", \"hopper-mixed-v0\", \"hopper-medium-expert-v0\"\n ]:\n import d4rl\n expl_env = gym.make(env_name)\n eval_env = gym.make(env_name)\n elif env_id:\n expl_env = NormalizedBoxEnv(gym.make(env_id))\n eval_env = NormalizedBoxEnv(gym.make(env_id))\n elif env_class:\n expl_env = NormalizedBoxEnv(env_class())\n eval_env = NormalizedBoxEnv(env_class())\n else:\n expl_env = NormalizedBoxEnv(variant['env']())\n eval_env = NormalizedBoxEnv(variant['env']())\n\n # expl_env = gym.make(variant['env'])\n # eval_env = gym.make(variant['env'])\n\n if variant.get('add_env_demos', False):\n variant[\"path_loader_kwargs\"][\"demo_paths\"].append(variant[\"env_demo_path\"])\n\n if variant.get('add_env_offpolicy_data', False):\n variant[\"path_loader_kwargs\"][\"demo_paths\"].append(variant[\"env_offpolicy_data_path\"])\n\n action_dim = int(np.prod(eval_env.action_space.shape))\n state_dim = obs_dim = np.prod(expl_env.observation_space.shape)\n M = 256\n\n qf_kwargs = copy.deepcopy(variant['qf_kwargs'])\n qf_kwargs['output_size'] = 1\n qf_kwargs['input_size'] = action_dim + state_dim\n qf1 = MlpQf(**qf_kwargs)\n qf2 = MlpQf(**qf_kwargs)\n\n target_qf_kwargs = copy.deepcopy(qf_kwargs)\n target_qf1 = MlpQf(**target_qf_kwargs)\n target_qf2 = MlpQf(**target_qf_kwargs)\n\n policy_class = variant.get(\"policy_class\", TanhGaussianPolicy)\n policy_kwargs = copy.deepcopy(variant['policy_kwargs'])\n policy_kwargs['action_dim'] = action_dim\n policy_kwargs['obs_dim'] = state_dim\n policy = policy_class(**policy_kwargs)\n\n vae_policy = VAEPolicy(\n obs_dim=obs_dim,\n action_dim=action_dim,\n latent_dim=action_dim * 2,\n )\n\n # vae_eval_path_collector = MdpPathCollector(\n # eval_env,\n # vae_policy,\n # # max_num_epoch_paths_saved=5,\n # # save_images=False,\n # )\n\n\n replay_buffer = variant.get('replay_buffer_class', EnvReplayBuffer)(\n max_replay_buffer_size=variant['replay_buffer_size'],\n env=expl_env,\n )\n demo_train_replay_buffer = variant.get('replay_buffer_class', EnvReplayBuffer)(\n max_replay_buffer_size=variant['replay_buffer_size'],\n env=expl_env,\n )\n demo_test_replay_buffer = variant.get('replay_buffer_class', EnvReplayBuffer)(\n max_replay_buffer_size=variant['replay_buffer_size'],\n env=expl_env,\n )\n\n trainer_class = variant.get(\"trainer_class\", BEARTrainer)\n trainer = trainer_class(\n env=eval_env,\n policy=policy,\n qf1=qf1,\n qf2=qf2,\n target_qf1=target_qf1,\n target_qf2=target_qf2,\n vae=vae_policy,\n replay_buffer=replay_buffer,\n **variant['trainer_kwargs']\n )\n\n expl_path_collector = MdpPathCollector(\n expl_env,\n # policy,\n trainer.eval_policy, # PolicyFromQ(qf1, policy),\n **variant['expl_path_collector_kwargs']\n )\n eval_path_collector = MdpPathCollector(\n eval_env,\n # save_images=False,\n # MakeDeterministic(policy),\n trainer.eval_policy, # PolicyFromQ(qf1, policy),\n **variant['eval_path_collector_kwargs']\n )\n\n path_loader_class = variant.get('path_loader_class', MDPPathLoader)\n path_loader_kwargs = variant.get(\"path_loader_kwargs\", {})\n path_loader = path_loader_class(trainer,\n replay_buffer=replay_buffer,\n demo_train_buffer=demo_train_replay_buffer,\n demo_test_buffer=demo_test_replay_buffer,\n **path_loader_kwargs,\n # demo_off_policy_path=variant['data_path'],\n )\n # path_loader.load_bear_demos(pickled=False)\n path_loader.load_demos()\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n # vae_evaluation_data_collector=vae_eval_path_collector,\n replay_buffer=replay_buffer,\n # q_learning_alg=True,\n # batch_rl=variant['batch_rl'],\n **variant['algo_kwargs']\n )\n\n\n algorithm.to(ptu.device)\n trainer.pretrain_q_with_bc_data(256)\n algorithm.train()\n","sub_path":"rlkit/launchers/experiments/ashvin/bear_rl.py","file_name":"bear_rl.py","file_ext":"py","file_size_in_byte":17269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"629308009","text":"#!/usr/bin/env python3\n\n\"\"\"\nDatabase Operation.\n\nFunctions\n---------\n- :func:`query_oracle`: query the oracle db, and filter the returns.\n\"\"\"\n# Time: 2018-01-29T07:22:11.208Z\n# Author: Zili Wang\n# E-mail: zili_wang@163.com\n\nfrom sqlalchemy import create_engine\nfrom incident.errors import OracleParamsNull\nimport geopy\nfrom datetime import datetime, timedelta\nfrom geopy.distance import VincentyDistance, vincenty\nimport pandas as pd\n\n\ndef query_oracle(username, passwd, host, port, server_name, lat, lon, itime,\n distance, timeinterval):\n \"\"\"query the oracle db, and filter the returns.\n\n Parameters\n ---------\n username: str\n user name.\n passwd: str\n passwords.\n host: str\n host ip.\n port: int\n port.\n server_name: str\n server name.\n lat: float\n latitude.\n lon: float\n longitude.\n itime: str\n incident accur time, %Y-%m-%d %H:%M:%S.\n distance: int\n the query distance threshold(km).\n timeinterval: int\n time interval for query(s).\n\n Returns\n -------\n list(tuple(str, str))\n list which element is tuple('id', 'desc').\n\n Raise\n -----\n :class:`cx_Oracle.DatabaseError`:\n connect oracle service error.\n \"\"\"\n origin = geopy.Point(lat, lon)\n destination = VincentyDistance(kilometers=distance).destination(\n origin, 0)\n geo_diff = abs(lat - destination.latitude)\n q_start_time = (\n datetime.strptime(itime, '%Y-%m-%d %H:%M:%S') -\n timedelta(seconds=timeinterval)).strftime('%Y-%m-%d %H:%M:%S')\n q_end_time = (\n datetime.strptime(itime, '%Y-%m-%d %H:%M:%S') +\n timedelta(seconds=timeinterval)).strftime('%Y-%m-%d %H:%M:%S')\n \"\"\"\n SELECT incidentinformationid FROM INCIDENTAPPEALINFORMATION where\n POWER(POWER(incidentlongitude - 10, 2) +\n POWER(incidentlatitude - 10, 2), 0.5) < 2 and ROWNUM < 10\n -----------------------------------\n abandon as the oracle response slowly.\n \"\"\"\n sql = (\"SELECT incidentinformationid,incidentlongitude,\"\n \"incidentlatitude,incidentdescription \"\n \"FROM INCIDENTAPPEALINFORMATION WHERE \"\n \"incidenttime between \"\n \"to_date(\\'{0}\\',\\'yyyy-mm-dd hh24:mi:ss\\') \"\n \"and to_date(\\'{1}\\',\\'yyyy-mm-dd hh24:mi:ss\\') \"\n \"and incidentlongitude between {2} and {3} and \"\n \"incidentlatitude between {4} and {5} \".format(\n q_start_time, # start time\n q_end_time, # end time\n lon - geo_diff, # min lon\n lon + geo_diff, # max lon\n lat - geo_diff, # min lat\n lat + geo_diff)) # max lat\n url = (\"oracle://{}:{}@(DESCRIPTION = (LOAD_BALANCE=on) (FAILOVER=ON) \"\n \"(ADDRESS = (PROTOCOL = TCP)(HOST = {})(PORT = {})) \"\n \"(CONNECT_DATA = (SERVER = DEDICATED) \"\n \"(SERVICE_NAME = {})))\".format(\n username, passwd, host, port, server_name))\n connection = create_engine(url).connect() # connect oracle db\n records_df = pd.read_sql_query(sql, connection)\n connection.close() # close the connection\n\n if records_df.empty:\n return None\n # next step: filter the records which has distance more then threshold\n return [(v['incidentinformationid'], v['incidentdescription'])\n for i, v in records_df.iterrows() if\n is_geo_distance_include(lat, lon, v['incidentlatitude'],\n v['incidentlongitude'], distance)]\n\n\ndef is_geo_distance_include(lat1, lon1, lat2, lon2, distance):\n \"\"\"compare two geo point, if the distance more then given return False,\n else return True\"\"\"\n if vincenty((lon1, lat1), (lon2, lat2)).kilometers > distance:\n return False\n return True\n","sub_path":"incident/data_opt.py","file_name":"data_opt.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"438317494","text":"from django.shortcuts import redirect, render\nfrom lists.models import Item\n\ndef home_page(request):\n\tkomentar = ''\n\tif Item.objects.count() == 0 :\n\t\tkomentar = 'yey, waktunya berlibur'\n\telif Item.objects.count() < 5:\n\t\tkomentar = 'sibuk tapi santai'\n\telse:\n\t\tkomentar = 'oh tidak'\n\tif request.method == 'POST':\n\t\tItem.objects.create(text=request.POST['item_text'])\n\t\treturn redirect('/')\n\t\t\n\titems = Item.objects.all()\n\treturn render(request, 'home.html', {'items' : items, 'komentar' : komentar})\n\t\t\n","sub_path":"lists/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"506769768","text":"import random\nimport time\n\nfrom Classes import Wizard, Monster, SmallAnimal, Dragon\n\n\ndef main():\n printHeader()\n gameLoop()\n\n\ndef printHeader():\n print('--------------------')\n print(' Wizard App')\n print('--------------------')\n print()\n\n\ndef gameLoop():\n\n monsters = [\n SmallAnimal('Toad', 1),\n Monster('Tiger', 12),\n SmallAnimal('Bat', 3),\n Dragon('Dragon', 50, 75, True),\n Wizard('Evil Wizard', 1000)\n ]\n hero = Wizard('Gandolf', 75)\n\n\n while True:\n\n activeMonster = random.choice(monsters)\n print('A {} of level {} has appeard from the woods...\\n'.format(activeMonster.name, activeMonster.level))\n\n cmd = input('Do you [a]ttack, [r]un or [l]ook around? ')\n if cmd == 'a':\n if hero.attack(activeMonster):\n monsters.remove(activeMonster)\n else:\n print('The wizard runs and hides to recover....\\n')\n time.sleep(3)\n print('The wizard returns at full strength...\\n')\n\n elif cmd == 'r':\n print('The wizard doubts his power and runs away.\\n')\n elif cmd == 'l':\n print('The wizard {} takes a close look around himself and sees: '.format(hero.name))\n for m in monsters:\n print(' * A {} of level {}'.format(m.name, m.level))\n else:\n print('Exiting game')\n break\n\n if not monsters:\n print('Well done!!!\\nYou have defeated all of the monsters!')\n break\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Wizard app/Wizard app.py","file_name":"Wizard app.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"88603660","text":"import pygame\nimport pangolin as pango\nfrom OpenGL.GL import *\nimport numpy as np\nimport PIL\nimport cv2\nfrom PIL import Image\n\n\ndef main():\n win = pango.CreateWindowAndBind(\"Visualization Tool 3d\", 640*2, 480*2)\n glEnable(GL_DEPTH_TEST)\n\n # Define Projection and initial ModelView matrix\n\n # ProjectionMatrix (int w, int h, double fu, double fv, double u0, double v0, double zNear, double zFar)\n pm = pango.ProjectionMatrix(640, 480, 420, 420, 320, 240, 0.5, 100)\n\n # This allows changing of \"camera\" angle : glulookat style model view matrix (x, y, z, lx, ly, lz, AxisDirection Up) Forward is -z and up is +y\n # mv = pango.ModelViewLookAt(-1, 2, -2,\n # 0, 1, 0,\n # 0, -1, 0)\n # mv = pango.ModelViewLookAt(10, 10, 20,\n # 0, 0, 0,\n # 0, -1, 0)\n # This is normal view of object\n # mv = pango.ModelViewLookAt(-1, 0, 5, 0, 0, 0, pango.AxisY) ## TODO: what is axis y and axis x\n mv = pango.ModelViewLookAt(0.3, 0, -2.5,\n 0, 0, 0,\n 0, -0.5, 0)\n\n '''\n The gluLookAt function provides an easy and intuitive way to set the camera position and orientation. Basically it has three groups of parameters, each one is composed of 3 floating point values. The first three values indicate the camera position. The second set of values defines the point we’re looking at. Actually it can be any point in our line of sight.The last group indicates the up vector, this is usually set to (0.0, 1.0, 0.0), meaning that the camera’s is not tilted. If you want to tilt the camera just play with these values. For example, to see everything upside down try (0.0, -1.0, 0.0).\n '''\n\n s_cam = pango.OpenGlRenderState(pm, mv)\n\n # Create Interactive View in window\n handler = pango.Handler3D(s_cam)\n d_cam = (\n pango.CreateDisplay()\n .SetBounds(\n pango.Attach(0),\n pango.Attach(1),\n pango.Attach.Pix(1), # side bar which can be used for notification system\n pango.Attach(1),\n -640.0 / 480.0,\n )\n .SetHandler(handler)\n )\n\n # pango.CreatePanel(\"ui\").SetBounds(\n # pango.Attach(0), pango.Attach(1), pango.Attach(0), pango.Attach.Pix(ui_width)\n # )\n # var_ui = pango.Var(\"ui\")\n # var_ui.a_Button = False\n # var_ui.a_double = (0.0, pango.VarMeta(0, 5))\n # var_ui.an_int = (5, pango.VarMeta(0, 5))\n # var_ui.a_double_log = (3.0, pango.VarMeta(1, 1e4, logscale=True))\n # var_ui.a_checkbox = (False, pango.VarMeta(toggle=True))\n # var_ui.an_int_no_input = 5\n # var_ui.a_str = \"sss\"\n #\n # ctrl = -96\n # pango.RegisterKeyPressCallback(ctrl + ord(\"a\"), a_callback)\n\n vid = cv2.VideoCapture(\"../Sidewalk.mp4\")\n # texture_data = vid.read()[1]\n pbo = 0\n pbo = glGenBuffers(1, pbo)\n while not pango.ShouldQuit():\n # Clear screen and activate view to render into\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glClearColor(0.1, 0.3, 0.3, 0.0)\n glLineWidth(5)\n glPointSize(15)\n pango.DrawLine([[-1, 1, 0], [-1, 1, -1]]) # down is positive y, right is positive x - this does bottom left\n pango.DrawLine([[1, -1, 0], [1, -1, -1]]) # top right\n pango.DrawLine([[-1, -1, 0], [-1, -1, -1]]) # top left\n pango.DrawLine([[1, 1, 0], [1, 1, -1]]) # bottom right\n pango.DrawPoints([[-1, 1, -1], [1, -1, -1], [-1, -1, -1], [1, 1, -1]])\n\n ret, texture_data = vid.read()\n texture_data = cv2.rotate(cv2.cvtColor(cv2.resize(texture_data, (1400, 1400)), cv2.COLOR_BGR2RGBA), cv2.ROTATE_180)\n height, width, dims = texture_data.shape\n\n glEnable(GL_TEXTURE_2D)\n\n bytes = (height * width * dims)\n glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo)\n glBufferData(GL_PIXEL_PACK_BUFFER,\n bytes,\n texture_data,\n GL_DYNAMIC_DRAW)\n pbo\n\n # texid = glGenTextures(1)\n #\n # glBindTexture(GL_TEXTURE_2D, texid)\n # glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,\n # 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data)\n #\n # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\n # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\n # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)\n # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)\n\n d_cam.Activate(s_cam)\n\n glBegin(GL_QUADS)\n\n glVertex3f(1.0, 1.0, -0.05)\n glVertex3f(-1.0, 1.0, -0.05)\n glVertex3f(-1.0, 1.0, 0.05)\n glVertex3f(1.0, 1.0, 0.05)\n\n glVertex3f(1.0, -1.0, -0.05)\n glVertex3f(-1.0, -1.0, -0.05)\n glVertex3f(-1.0, -1.0, 0.05)\n glVertex3f(1.0, -1.0, 0.05)\n\n glVertex3f(1.0, 1.0, 0.05)\n glVertex3f(-1.0, 1.0, 0.05)\n glVertex3f(-1.0, -1.0, 0.05)\n glVertex3f(1.0, -1.0, 0.05)\n\n glTexCoord2f(0.0, 1.0)\n glVertex3f(1.0, -1.0, -0.05)\n glTexCoord2f(1.0, 1.0)\n glVertex3f(-1.0, -1.0, -0.05)\n glTexCoord2f(1.0, 0.0)\n glVertex3f(-1.0, 1.0, -0.05)\n glTexCoord2f(0.0, 0.0)\n glVertex3f(1.0, 1.0, -0.05)\n\n glVertex3f(-1.0, 1.0, 0.05)\n glVertex3f(-1.0, 1.0, -0.05)\n glVertex3f(-1.0, -1.0, -0.05)\n glVertex3f(-1.0, -1.0, 0.05)\n\n glVertex3f(1.0, 1.0, 0.05)\n glVertex3f(1.0, 1.0, -0.05)\n glVertex3f(1.0, -1.0, -0.05)\n glVertex3f(1.0, -1.0, 0.05)\n\n glEnd()\n\n # glBegin(GL_LINES)\n # for cubeEdge in cubeEdges:\n # for cubeVertex in cubeEdge:\n # glVertex3fv(cubeVertices[cubeVertex])\n # glEnd()\n #\n\n # Swap Frames and Process Events\n pango.FinishFrame()\n\n # glDeleteTextures(texid)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"display_3d/3d_display.py","file_name":"3d_display.py","file_ext":"py","file_size_in_byte":5877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"637075036","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 14 14:11:47 2020\r\n\r\n@author: sanathoi\r\n\"\"\"\r\n# storing conditions \r\ninterest=None\r\ndeposit =float(input(\"Enter the deposit amount:\"))\r\ntime=float(input(\"Enter the no of terms:\"))\r\nokrate3=deposit<2000 and time>=2\r\nokrate5=deposit>=2000 and time>=2\r\nif okrate3:\r\n interest= deposit*0.03*time\r\n print(\"The interest for rs\",deposit,\"is\",interest)\r\nelif okrate5:\r\n interest= deposit478*0.05*time\r\n print(\"The interest for rs\",deposit,\"is\",interest)\r\nprint(\"Thank you for banking with us.\")\r\n","sub_path":"storingCondi.py","file_name":"storingCondi.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"191609860","text":"#\n# Copyright 2013 eNovance \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\n\nfrom sqlalchemy import MetaData, Table, Column, Index\nfrom sqlalchemy import String, Text\n\n\ndef upgrade(migrate_engine):\n meta = MetaData()\n meta.bind = migrate_engine\n table = Table('alarm', meta, autoload=True)\n\n type = Column('type', String(50), default='threshold')\n type.create(table, populate_default=True)\n\n rule = Column('rule', Text())\n rule.create(table)\n\n for row in table.select().execute().fetchall():\n query = []\n if row.matching_metadata is not None:\n matching_metadata = json.loads(row.matching_metadata)\n for key in matching_metadata:\n query.append({'field': key,\n 'op': 'eq',\n 'value': matching_metadata[key]})\n rule = {\n 'meter_name': row.meter_name,\n 'comparison_operator': row.comparison_operator,\n 'threshold': row.threshold,\n 'statistic': row.statistic,\n 'evaluation_periods': row.evaluation_periods,\n 'period': row.period,\n 'query': query\n }\n table.update().where(table.c.id == row.id).values(rule=rule).execute()\n\n index = Index('ix_alarm_counter_name', table.c.meter_name)\n index.drop(bind=migrate_engine)\n table.c.meter_name.drop()\n table.c.comparison_operator.drop()\n table.c.threshold.drop()\n table.c.statistic.drop()\n table.c.evaluation_periods.drop()\n table.c.period.drop()\n table.c.matching_metadata.drop()\n","sub_path":"ceilometer/storage/sqlalchemy/migrate_repo/versions/016_simpler_alarm.py","file_name":"016_simpler_alarm.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"540442957","text":"from django.core.management import BaseCommand\nfrom houses import models as house_models\n\n\nclass Command(BaseCommand):\n help = 'This command create amenities for houses.'\n\n def handle(self, *args, **options):\n amenities = [\n \"주방\",\n \"샴���\",\n \"난방\",\n \"에어컨\",\n \"세탁기\",\n \"건조기\",\n \"무선 인터넷\",\n \"아침식사\",\n \"실내 벽난로\",\n \"옷걸이\",\n \"다리미\",\n \"헤어드라이어\",\n \"노트북 작업 공간\",\n \"TV\",\n \"아기 침대\",\n \"유아용 식탁의자\",\n \"셀프 체크인\",\n \"화재경보기\",\n \"일산화탄소 경보기\",\n \"욕실 단독 사용\",\n \"피아노\",\n ]\n\n for a in amenities:\n house_models.Amenity.objects.create(name=a)\n self.stdout.write(self.style.SUCCESS(\"Amenities created!\"))\n","sub_path":"backend/houses/management/commands/seed_amenity.py","file_name":"seed_amenity.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"472642340","text":"# Data Pre-processing Template - To be imported anywhere\n\n# Import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Import sklearn libraries\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression\n\n# Import Dataset\ndataset = pd.read_csv('Salary_Data.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 1].values\n\nprint(dataset.head())\nprint(X)\nprint(y)\n\n# Split the dataset to train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)\n\nprint(X_train)\nprint(y_train)\n\nprint(X_test)\nprint(y_test)\n\n# Feature scaling\n\"\"\"\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\"\"\"\n\n# Fit the data to linear regressor\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Predicting the test_set results\ny_pred = regressor.predict(X_test)\nprint(y_pred)\nprint(y_test)\n\n# Visualising the Training set results\n# plt.scatter(X_train, y_train, color='red')\n# plt.plot(X_train, regressor.predict(X_train), color='blue')\n# plt.title('Salary vs Experience (Training set)')\n# plt.xlabel('Years of Experience')\n# plt.ylabel('Salary')\n# plt.show()\n\n# Visualising the Test set results\nplt.scatter(X_test, y_test, color='red')\nplt.plot(X_train, regressor.predict(X_train), color='blue')\nplt.title('Salary vs Experience (Test set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n","sub_path":"regression/simple_linear_regression/simple_linear_regression.py","file_name":"simple_linear_regression.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"588692406","text":"'''\nDataset object wrapper for something given in memory (array of arrays, numpy matrix)\n'''\n__authors__ = \"Markus Beissinger\"\n__copyright__ = \"Copyright 2015, Vitruvian Science\"\n__credits__ = [\"Markus Beissinger\"]\n__license__ = \"Apache\"\n__maintainer__ = \"OpenDeep\"\n__email__ = \"dev@opendeep.org\"\n\n# standard libraries\nimport logging\n# third party libraries\nimport numpy\n# internal imports\nfrom opendeep.utils.nnet import sharedX\nimport opendeep.data.dataset as datasets\nfrom opendeep.data.dataset import Dataset\nimport opendeep.utils.file_ops as files\nfrom opendeep.utils.nnet import make_shared_variables\n\nlog = logging.getLogger(__name__)\n\nclass MemoryMatrix(Dataset):\n '''\n Dataset object wrapper for something given in memory (numpy matrix, theano matrix)\n '''\n def __init__(self, train_X, train_Y=None, valid_X=None, valid_Y=None, test_X=None, test_Y=None):\n log.info('Wrapping matrix from memory')\n super(self.__class__, self).__init__()\n\n # make sure the inputs are arrays\n train_X = numpy.array(train_X)\n self._train_shape = train_X.shape\n self.train_X = sharedX(train_X)\n if train_Y:\n self.train_Y = sharedX(numpy.array(train_Y))\n\n if valid_X:\n valid_X = numpy.array(valid_X)\n self._valid_shape = valid_X.shape\n self.valid_X = sharedX(valid_X)\n if valid_Y:\n self.valid_Y = sharedX(numpy.array(valid_Y))\n\n if test_X:\n test_X = numpy.array(test_X)\n self._test_shape = test_X.shape\n self.test_X = sharedX(test_X)\n if test_Y:\n self.test_Y = sharedX(numpy.array(test_Y))\n\n def getDataByIndices(self, indices, subset):\n '''\n This method is used by an iterator to return data values at given indices.\n :param indices: either integer or list of integers\n The index (or indices) of values to return\n :param subset: integer\n The integer representing the subset of the data to consider dataset.(TRAIN, VALID, or TEST)\n :return: array\n The dataset values at the index (indices)\n '''\n if subset is datasets.TRAIN:\n return self.train_X.get_value(borrow=True)[indices]\n elif subset is datasets.VALID and hasattr(self, 'valid_X') and self.valid_X:\n return self.valid_X.get_value(borrow=True)[indices]\n elif subset is datasets.TEST and hasattr(self, 'test_X') and self.test_X:\n return self.test_X.get_value(borrow=True)[indices]\n else:\n return None\n\n def getLabelsByIndices(self, indices, subset):\n '''\n This method is used by an iterator to return data label values at given indices.\n :param indices: either integer or list of integers\n The index (or indices) of values to return\n :param subset: integer\n The integer representing the subset of the data to consider dataset.(TRAIN, VALID, or TEST)\n :return: array\n The dataset labels at the index (indices)\n '''\n if subset is datasets.TRAIN and hasattr(self, 'train_Y') and self.train_Y:\n return self.train_Y.get_value(borrow=True)[indices]\n elif subset is datasets.VALID and hasattr(self, 'valid_Y') and self.valid_Y:\n return self.valid_Y.get_value(borrow=True)[indices]\n elif subset is datasets.TEST and hasattr(self, 'test_Y') and self.test_Y:\n return self.test_Y.get_value(borrow=True)[indices]\n else:\n return None","sub_path":"opendeep/data/memory_matrix.py","file_name":"memory_matrix.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"137482529","text":"import pkg_resources\nimport sys\n\nfrom elasticgit.workspace import EG, F, Q\n\n__all__ = ['EG', 'F', 'Q']\n__version__ = pkg_resources.require('elastic-git')[0].version\n\nversion_info = {\n 'language': 'python',\n 'language_version_string': sys.version,\n 'language_version': '%d.%d.%d' % (\n sys.version_info.major,\n sys.version_info.minor,\n sys.version_info.micro,\n ),\n 'package': 'elastic-git',\n 'package_version': __version__\n}\n","sub_path":"elasticgit/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"533927659","text":"import os\n\nimport requests\nfrom PyQt5.QtCore import QAbstractTableModel, pyqtSignal, Qt, QVariant, QModelIndex, QSize\nfrom PyQt5.QtGui import QPixmap\n\nimport pyconfig\nfrom pythread import threaded\n\nDISPLAY_KEY = 0\nDICT_KEY = 1\nEDIT_KEY = 2\nBEFORE_KEY = 3\n\n\nclass ServerStateHandler:\n def __init__(self, servers):\n self.servers = servers\n self.servers.connected.connect(self.on_connection)\n self.servers.disconnected.connect(self.on_disconnection)\n self.servers.refresh.connect(self.on_refresh)\n\n def on_connection(self, server_name):\n pass\n\n def on_disconnection(self, server_name):\n pass\n\n def on_refresh(self, server_name, section):\n pass\n\n\nclass ModelTableListDict(QAbstractTableModel):\n busy = pyqtSignal('PyQt_PyObject')\n refreshed = pyqtSignal()\n\n def __init__(self, list_key, connect=None):\n\n QAbstractTableModel.__init__(self, None)\n self.list = []\n self.list_key = list_key\n\n def refresh(self):\n pass\n\n def rowCount(self, parent=None, *args, **kwargs):\n if self.list is None:\n self.list = []\n return len(self.list)\n\n def columnCount(self, parent=None, *args, **kwargs):\n return len(self.list_key)\n\n def headerData(self, section, orientation, role=None):\n if role == Qt.DisplayRole and orientation == Qt.Horizontal:\n try:\n return QVariant(self.get_key(section, role=DISPLAY_KEY))\n except IndexError as e:\n print(\"headerData:\", e, section)\n\n return QAbstractTableModel.headerData(self, section, orientation, role)\n\n def data(self, index, role=None):\n if not index.isValid():\n return QVariant()\n\n try:\n if role == Qt.DisplayRole:\n key = self.get_key(index.column())\n if key:\n before = self.get_key(index.column(), role=BEFORE_KEY)\n if before:\n return QVariant(before(self.list[index.row()][key]))\n else:\n return QVariant(self.list[index.row()][key])\n\n elif role == Qt.DecorationRole:\n return self.get_decoration_role(index)\n\n elif role == Qt.UserRole:\n key = self.get_key(index.column())\n if key:\n return QVariant(self.list[index.row()][key])\n\n elif role == Qt.ToolTipRole:\n return self.get_toolTip_role(index)\n\n elif role is None:\n return self.list[index.row()]\n\n except TypeError:\n return QVariant(\"#!TYPE_ERROR\")\n\n except IndexError:\n return QVariant(\"#!INDEX_ERROR\")\n\n except KeyError:\n return QVariant(\"#!EMPTY\")\n\n return QVariant()\n\n def setData(self, index, value, role=None):\n if not index.isValid():\n return False\n\n row = index.row()\n low_index = self.createIndex(row, 0)\n high_index = self.createIndex(row, len(self.list_key))\n\n try:\n if role is None:\n self.list[row] = value\n\n elif role == Qt.EditRole:\n key = self.get_key(index.column())\n self.list[row][key] = value\n\n self.dataChanged.emit(low_index, high_index, [])\n return True\n\n except TypeError as e:\n print(\"setData\", e)\n except IndexError as e:\n print(\"setData\", e)\n\n return False\n\n def flags(self, index):\n if index.isValid():\n if self.get_key(index.column(), role=EDIT_KEY):\n return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable\n return Qt.ItemIsEnabled | Qt.ItemIsSelectable\n return Qt.ItemIsEnabled\n\n def insertRows(self, row, count, parent=None):\n self.beginInsertRows(QModelIndex(), row, row + count - 1)\n if row == self.rowCount():\n for i in range(0, count):\n self.list.append({})\n else:\n for i in range(0, count):\n self.list.insert(row + i, {})\n self.endInsertRows()\n return True\n\n def removeRows(self, row, count, parent=None):\n self.beginRemoveRows(QModelIndex(), row, row + count - 1)\n del self.list[row:row + count]\n self.endRemoveRows()\n return True\n\n # start custom function\n\n def get_decoration_role(self, index):\n return QVariant()\n\n def get_toolTip_role(self, index):\n return QVariant()\n\n def clear(self):\n self.removeRows(0, self.rowCount())\n\n def add_data(self, data):\n try:\n row_index = self.rowCount()\n self.insertRow(row_index)\n self.setData(self.createIndex(row_index, 0), data)\n except RuntimeError:\n pass\n\n def reset_data(self, data):\n self.beginResetModel()\n self.list = data\n self.endResetModel()\n\n def get_index_of(self, column, value):\n for i in range(0, len(self.list)):\n if self.list[i][column] == value:\n return self.createIndex(i, 0)\n\n def get_key(self, column, role=DICT_KEY):\n return self.list_key[column][role]\n\n def get_keys(self, role=DICT_KEY, add=None):\n for i in range(0, len(self.list_key)):\n yield self.get_key(i, role=role)\n if add:\n for el in add:\n yield el\n\n def begin_busy(self):\n self.busy.emit(True)\n\n def end_busy(self):\n self.busy.emit(False)\n\n def end_refreshed(self):\n self.refreshed.emit()\n\n def close(self):\n pass\n\n\nclass PosterManager:\n def __init__(self):\n self.poster_mini_path = pyconfig.get(\"rsc.poster_mini_path\")\n self.poster_original_path = pyconfig.get(\"rsc.poster_original_path\")\n\n def get_poster_path(self, poster_path, mini=False):\n if poster_path is None:\n return \"rsc/404.jpg\"\n if mini:\n return self.poster_mini_path + poster_path\n else:\n return self.poster_original_path + poster_path\n\n def poster_exists(self, poster_path):\n if poster_path is None:\n return False\n if not os.path.exists(self.get_poster_path(poster_path, mini=True)):\n self.get_poster(poster_path)\n return False\n if not os.path.exists(self.get_poster_path(poster_path)):\n self.get_poster(poster_path)\n return False\n return True\n\n @threaded(\"poster\")\n def get_poster(self, poster_path):\n print(\"get poster\", poster_path)\n if poster_path is None:\n return\n original_path = self.poster_original_path + poster_path\n mini_path = self.poster_mini_path + poster_path\n\n if not os.path.exists(original_path) or not os.path.exists(mini_path):\n\n response = requests.get(\"https://image.tmdb.org/t/p/original\" + poster_path, stream=True)\n if response.status_code == 200:\n with open(original_path, 'wb') as f:\n for chunk in response:\n f.write(chunk)\n pixmap = QPixmap(original_path).scaled(QSize(154, 231), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n pixmap.save(mini_path, \"JPG\")","sub_path":"mediaCenter_lib/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"190874984","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/23 19:43\n# @Author :Wang Guosong\n# @File : some_test.py\n# @Software : PyCharm\n\nimport pandas as pd\nimport numpy as np\nimport string\n\ndf = pd.DataFrame(np.random.random(100).reshape([20, 5]), columns=list(string.ascii_lowercase[0:5]))\nlen(df)\n\ndf = pd.DataFrame(np.random.random(100).reshape([5, 20]), columns=list(string.ascii_lowercase[0:20]))\nlen(df)\n\ndef test_name():\n print([i for i in range(10000000)])\n\ntest_name()\na = test_name\na()\n\n\nlist(filter((lambda x: x > 0), range(-5, 5)))\n\nM = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\nN = [[2, 2, 2],\n [3, 3, 3],\n [4, 4, 4]]\n\n\n[[M[row][col] * N[row][col] for col in range(3)] for row in range(3)]\n\n\ndef gen(N):\n for i in range(N):\n # return i ** 2\n yield i ** 2\n\nfor i in gen(5):\n print(i, end=':')\n\ntest = (x + '\\n' for x in 'aaa, bbb, ccc'.split(','))\ntest\na, b, c= (x + '\\n' for x in 'aaa, bbb, ccc'.split(','))\na, b, c = test\na\n\n\nG = (c * 4 for c in 'SPAM')\nG\nnext(G)\nI = iter(G)\nnext(I)\n\nline = 'aa bbb c'\n\ndef gensub(line):\n for x in line.split():\n if len(x) > 1:\n yield x.upper()\n\n''.join(gensub(line))\n\ndef retsub(line):\n for x in line.split():\n if len(x) > 1:\n return x.upper()\n\n''.join(retsub(line))\n\n\ndef fund():\n pass\n\ndef default():\n pass\n\nbranch = {\n 'spam': lambda x: x + 1,\n 'ham' : fund,\n 'eggs': lambda x: x + 2}\n\nchoice = 'spam'\nbranch.get(choice, default())\ns = (\n 'aaa'\n 'bbbb'\n)\ns = \"\"\"\naaaa\nbbb\n\"\"\"\n\n[a for a in dir(dict) if not a.startswith('__')]","sub_path":"some_test.py","file_name":"some_test.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"7986323","text":"\"\"\"\nSecond-Hand-Shop Project\n\n@author: Malte Gerth\n@copyright: Copyright (C) 2015 Malte Gerth\n@license: MIT\n@maintainer: Malte Gerth\n@email: mail@malte-gerth.de\n\"\"\"\n\nfrom django.conf.urls import url\n\nfrom .views import (\n dashboard,\n book_sale_list,\n sale_list_detail,\n ArticleCreateView,\n ArticleDetailView,\n ArticleUpdateView,\n ArticleDeleteView,\n request_confirmation,\n request_confirmation_done,\n change_shipping_address,\n select_postal_delivery,\n)\n\n__author__ = \"Malte Gerth \"\n__copyright__ = \"Copyright (C) 2015 Malte Gerth\"\n__license__ = \"MIT\"\n\nurlpatterns = [\n url(r\"^dashboard/$\", dashboard, name=\"dashboard\"),\n url(r\"^booking/$\", book_sale_list, name=\"book_sale_list\"),\n url(r\"^request-confirmation/$\", request_confirmation, name=\"request_confirmation\"),\n url(\n r\"^request-confirmation/done/$\",\n request_confirmation_done,\n name=\"request_confirmation_done\",\n ),\n url(r\"^details/$\", sale_list_detail, name=\"sale_list\"),\n url(\n r\"^shipping-address/$\", change_shipping_address, name=\"change_shipping_address\"\n ),\n url(\n r\"^select-postal-delivery/$\",\n select_postal_delivery,\n name=\"select_postal_delivery\",\n ),\n url(r\"^article/create/$\", ArticleCreateView.as_view(), name=\"article_create\"),\n url(\n r\"^article/details/(?P\\d+)$\",\n ArticleDetailView.as_view(),\n name=\"article_detail\",\n ),\n url(\n r\"^article/update/(?P\\d+)$\",\n ArticleUpdateView.as_view(),\n name=\"article_update\",\n ),\n url(\n r\"^article/delete/(?P\\d+)$\",\n ArticleDeleteView.as_view(),\n name=\"article_delete\",\n ),\n]\n","sub_path":"src/sale_lists/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"314582303","text":"import json\r\nimport socket\r\nfrom math import floor\r\nimport sys, time\r\nclass OrderSystem:\r\n\r\n\t# clientMap = {'D7730003':1}#, 'D18138':0.1, 'D7730001':1}\r\n\t# lotSize = 20\r\n\r\n\tdef directSend(self,orderDetails):\r\n\t\tmessage={}\r\n\t\tmessage['orderDetails'] = orderDetails\r\n\t\tmessage['algoName'] = 'Straddle Write 4x'\r\n\t\tprint(message)\r\n\t\tmessage=json.dumps(message)\r\n\t\tself.orderSock.send(str.encode(message))\r\n\t\torderUniqueID=self.orderSock.recv(1024)\r\n\t\torderUniqueID=json.loads(message)\r\n\t\torderUniqueID = 1000\r\n\t\treturn orderUniqueID\r\n\r\n\tdef place_order(self,exchangeSegment,exchangeInstrumentID,\r\n\t\t\t\t productType,orderType,orderSide,orderQuantity, algoName, clientID, orderSock):\r\n\r\n\t\torderDetails={'algoName':algoName,'orderDetails':{'exchangeSegment': exchangeSegment, 'exchangeInstrumentID': exchangeInstrumentID,\r\n\t\t\t\t\t\t\t'productType': productType, 'orderType': orderType, 'orderSide': orderSide,\r\n\t\t\t\t\t\t\t'timeInForce': 'DAY', 'disclosedQuantity': 0,\r\n\t\t\t\t\t\t\t'orderQuantity': orderQuantity, 'limitPrice': 0, 'stopPrice': 0, 'clientID':clientID\r\n\t\t\t\t\t\t\t}}\r\n\r\n\t\tprint(orderDetails)\r\n\t\torderDetails=json.dumps(orderDetails)\r\n\t\torderSock.send(str.encode(orderDetails))\r\n\t\torderUniqueID=orderSock.recv(1024)\r\n\r\n\tdef placeSliceOrder(self,exchangeSegment,exchangeInstrumentID,\r\n\t\t\t\t productType,orderType,orderSide,orderQuantity,algoName,clientID,\r\n\t\t\t\t sliceSize, waitTime,authenticationKey):\r\n\r\n\t\torderSock = socket.socket()\r\n\t\thost = '192.168.0.103' # Server IP\r\n\t\tport = 40004\r\n\r\n\t\ttry:\r\n\t\t\torderSock.connect((host, port))\r\n\t\t\tprint(\"Client Connected In Order System\")\r\n\t\t\tkey = json.dumps({'algoName':algoName,\r\n\t\t\t\t\t\t\t\t'authenticationKey':authenticationKey})\r\n\t\t\torderSock.send(str.encode(key))\r\n\t\t\tverificationCheck=orderSock.recv(1024)\r\n\t\t\tprint('Check: ', verificationCheck)\r\n\t\t\tverificationCheck = verificationCheck.decode(\"utf-8\") \r\n\t\t\tif verificationCheck != '1':\r\n\t\t\t\traise Exception(verificationCheck)\r\n\t\t\t\tsys.exit(0)\r\n\r\n\t\texcept Exception as e:\r\n\t\t\traise Exception ('Error connecting Order Server', e)\r\n\t\t\tsys.exit(0)\r\n\r\n\t\tplaceQuantity = orderQuantity\r\n\r\n\t\twhile placeQuantity!=0:\r\n\t\t\tif placeQuantity>=sliceSize:\r\n\t\t\t\tself.place_order(exchangeSegment,exchangeInstrumentID,\r\n\t\t\t\t\t\t\t\tproductType,orderType,orderSide,sliceSize,algoName, clientID, orderSock)\r\n\t\t\t\tplaceQuantity-=sliceSize\r\n\t\t\telse:\r\n\t\t\t\tself.place_order(exchangeSegment, exchangeInstrumentID,\r\n\t\t\t\t\t\t\t\t productType, orderType, orderSide, placeQuantity,algoName,clientID, orderSock)\r\n\t\t\t\tplaceQuantity = 0\r\n\t\t\ttime.sleep(waitTime)\r\n\r\n\t\tprint('All quantity placed in client: ', clientID)\r\n\t\torderSock.close()\r\n\t\tsys.exit(0)\r\n\r\n\tdef quantityCal(self, quantity):\r\n\t\tlots = floor(quantity / self.lotSize)\r\n\r\n\t\tif lots == 0:\r\n\t\t\treturn self.lotSize\r\n\t\telse:\r\n\t\t\treturn lots * self.lotSize\r\n\r\nif __name__ == '__main__':\r\n\timport secrets, sys\r\n\r\n\tauthenticationKey = secrets.token_hex(2)\r\n\tprint('Input the following authentication key in the server: ', authenticationKey)\r\n\tcheck = input('Ready to start algo? (y/n)')\r\n\tif check.upper() == 'Y':\r\n\t\t# authenticationKey = 'a12b'\r\n\r\n\t\tobj = OrderSystem()\r\n\t\tobj.placeSliceOrder('NSEFO', 48210,'MIS','MARKET','BUY',600,400,0.1, authenticationKey)\r\n\t# else:\r\n\t# \tsys.exit(0)","sub_path":"api/orderSlicer.py","file_name":"orderSlicer.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"560423903","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.layers import Input,Dense\nfrom keras.models import Model,Sequential\nfrom keras.datasets import mnist\n\n\n# In[2]:\n\n\n(X_train,_), (X_test,_)=mnist.load_data()\n\n\n# In[3]:\n\n\nX_train=X_train.astype('float32')/float(X_train.max())\nX_test=X_test.astype('float32')/float(X_test.max())\n\n\n# In[4]:\n\n\nprint(\"Training set : \",X_train.shape)\nprint(\"Testing set : \",X_test.shape)\n\n\n# In[5]:\n\n\n# Reshaping our images into matrices\nX_train=X_train.reshape((len(X_train),np.prod(X_train.shape[1:])))\nX_test=X_test.reshape((len(X_test),np.prod(X_test.shape[1:])))\nprint(\"Training set : \",X_train.shape) #The resolution has changed\nprint(\"Testing set : \",X_test.shape)\n\n\n# In[6]:\n\n\ninput_dim=X_train.shape[1]\nencoding_dim=32\ncompression_factor=float(input_dim/encoding_dim)\n \nautoencoder=Sequential()\nautoencoder.add(Dense(encoding_dim, input_shape=(input_dim,),activation='relu'))\nautoencoder.add(Dense(input_dim,activation='sigmoid'))\n \ninput_img=Input(shape=(input_dim,))\nencoder_layer=autoencoder.layers[0]\nencoder=Model(input_img,encoder_layer(input_img))\n \nautoencoder.compile(optimizer='adam', loss='binary_crossentropy')\nautoencoder.fit(X_train,X_train,epochs=50, batch_size=256, shuffle=True, validation_data=(X_test,X_test))\n\n\n# In[7]:\n\n\nnum_images=10\nnp.random.seed(42)\nrandom_test_images=np.random.randint(X_test.shape[0], size=num_images)\nencoded_img=encoder.predict(X_test)\ndecoded_img=autoencoder.predict(X_test)\n\n\n# In[8]:\n\n\n# Display the images and predictions\nplt.figure(figsize=(18,4))\n \nfor i, image_idx in enumerate(random_test_images):\n #plot input image\n ax=plt.subplot(3,num_images,i+1)\n plt.imshow(X_test[image_idx].reshape(28,28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n \n # plot encoded image\n ax = plt.subplot(3, num_images, num_images + i + 1)\n plt.imshow(encoded_img[image_idx].reshape(8, 4))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n \n # plot reconstructed image\n ax = plt.subplot(3, num_images, 2*num_images + i + 1)\n plt.imshow(decoded_img[image_idx].reshape(28, 28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n \nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"imagecompression.py","file_name":"imagecompression.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"135284603","text":"count = 0\nstudent = [\n ]\n\nwhile True:\n def append_student():\n doc_name = input(\"Введите имя: \")\n \n new_doc_dict = {\"name\": doc_name}\n if new_doc_dict in student:\n print(\"Такой документ уже есть!\")\n else:\n student.append(new_doc_dict)\n print(\"Студент добавлен\")\n append_student()\n print(student)\n\nsumma = input(\"Вопрос1: \\nЧему равно 10 + 5: \")\nif summa == \"15\":\n count = count + 5\nelif summa == \"15,0\":\n count = count + 4\nelif summa == \"пятнадцать\":\n count = count + 3\nelse:\n count = count + 2\n\nminus = input(\"Вопрос2: \\nЧему равно 10 - 5: \")\nif minus == \"5\":\n count = count + 5\nelif minus == \"5,0\":\n count = count + 4\nelif minus == \"десять\":\n count = count + 3\nelse:\n count = count + 2\n \nmultiplication = input(\"Вопрос3: \\nЧему равно 10 * 5: \")\nif multiplication == \"50\":\n count = count + 5\nelif multiplication == \"50,0\":\n count = count + 4\nelif multiplication== \"пятьдесят\":\n count = count + 3\nelse:\n count = count + 2\n\nprint(count)\n\nif 8 > count > 6:\n print(\"Оценка - 3\")\nelif count <= 6:\n print(\"Оценка - 2\")\nelif count == 8:\n print(\"Ты нарвался на дополнительный вопрос!\")\n division = input(\"Вопрос3: \\nЧему равно 2 / 2: \")\n if division == \"1\":\n print(\"Ответил на 5, итоговая оценка 3\")\n elif division == \"1,0\":\n print(\"Ответил на 4, итоговая оценка 3\")\n elif division == \"один\":\n print(\"Ответил на 3, итоговая оценка 3\")\nelif count >= 14:\n print(\"Ты нарвался на дополнительный вопрос!\")\n division = input(\"Вопрос3: \\nЧему равно 2 / 2: \")\n if division == \"1\":\n print(\"Ответил на 5, итоговая оценка 5\")\n elif division == \"1,0\":\n print(\"Ответил на 4, итоговая оценка 4\")\n elif division == \"один\":\n print(\"Ответил на 3, итоговая оценка 4\")\nelif count == 9 or 10:\n print(\"Итоговая оценка - 3\")\nelif count == 11 or 13:\n print(\"Итоговая оценка - 4\")\n","sub_path":"laba.py","file_name":"laba.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"554737156","text":"from flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom os import environ\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/restaurantcity_cart'\n# app.config['SQLALCHEMY_DATABASE_URI'] = environ.get(\"dbURL\")\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\nCORS(app)\n\nclass Cart(db.Model):\n __tablename__ = 'temp_cart'\n userid = db.Column(db.String(45), primary_key=True)\n menuId = db.Column(db.String(45), primary_key=True)\n quantity= db.Column(db.Integer, nullable=False)\n\n def __init__(self,userid, menuId, quantity):\n self.userid = userid\n self.menuId = menuId\n self.quantity = quantity\n\n def json(self):\n return {\"userid\":self.userid,\"menuId\": self.menuId, \"quantity\": self.quantity}\n \n\n@app.route(\"/cart/\",methods=['GET'])\ndef get_cart(userid):\n carts = Cart.query.filter_by(userid=userid)\n carts_json = {\"cart\":[c.json() for c in carts]}\n\n return jsonify(carts_json), 200\n\n@app.route(\"/delete-cart/\",methods=['DELETE'])\ndef delete_cart(userid):\n try:\n Cart.query.filter_by(userid=userid).delete()\n db.session.commit()\n except:\n return jsonify({\"message\": \"An error occurred deleting the cart.\"}), 500\n\n return jsonify({\"message\":\"Cart is deleted successfully\"}), 200\n\n\n@app.route(\"/delete-cart-item/&\",methods=['DELETE'])\ndef delete_cart_item(userid,menuId):\n try:\n Cart.query.filter(Cart.userid==userid,Cart.menuId==menuId).delete()\n db.session.commit()\n except Exception as e:\n print(e)\n return jsonify({\"message\": \"An error occurred deleting the item.\"}), 500\n\n return jsonify({\"message\":\"Item is deleted successfully\"}), 200\n\n@app.route(\"/add-cart/\",methods=['POST'])\ndef create_cart(userid):\n data = request.get_json()\n\n Cart.query.filter_by(userid=userid).delete()\n db.session.commit()\n \n for item_js in data['items']:\n item = Cart(userid, item_js['menuId'], int(item_js['quantity']))\n try:\n db.session.add(item) # create_cartdb.session object is the current connection of the database \n db.session.commit() # commit the change to the database \n except Exception as e:\n print(e)\n return jsonify({\"message\": \"An error occurred saving the cart.\"}), 500 # INTERNAL SERVER ERROR \n \n return data, 201\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5002, debug=True) ","sub_path":"app/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"380419738","text":"import json\nimport urllib.parse\nimport boto3\nimport os\nfrom botocore.vendored import requests\n\nprint('Loading function')\n\ns3 = boto3.client('s3')\ncomprehend = boto3.client(service_name='comprehend')\n\ndef lambda_handler(event, context):\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')\n try:\n response = s3.get_object(Bucket=bucket, Key=key)\n content_type = response['ContentType']\n if content_type == 'application/octet-stream':\n file_content = response['Body'].read().decode('utf-8')\n json_content = json.loads(file_content)\n if 'articles' in json_content:\n result = {}\n count = 0\n for id, article in json_content['articles'].items():\n headline = article['headline']\n content = article['content'].split(\"… [+\")[0]\n result[id] = process_article(content)\n count += 1\n if count >= 10:\n break\n\n result_in_json = json.dumps(result)\n save_to_s3(key, result_in_json)\n else:\n print('INVALID FILE: article is missing.')\n except Exception as e:\n print(e)\n raise e\n\ndef process_article(content):\n comprehend_result = process_with_comprehend(content)\n tone_result = analyze_tone(content)\n\n return {\n \"entities\" : comprehend_result,\n \"tones\" : tone_result\n }\n\ndef process_with_comprehend(article_content):\n report = []\n try:\n comprehend_result = comprehend.detect_entities(Text=article_content, LanguageCode='en')\n desired_entities = [\"PERSON\", \"ORGANIZATION\", \"LOCATION\"]\n for entity in comprehend_result[\"Entities\"]:\n if entity[\"Type\"] in desired_entities:\n report.append(entity)\n except Exception:\n pass\n return report\n\ndef analyze_tone(article):\n api_key = os.environ['WATSON_API_KEY']\n auth = \"apiKey:\" + api_key\n params = {\"text\": article, \"version\": \"2017-09-21\", \"sentences\": False}\n url = \"https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone\"\n\n r = requests.get(url, auth=('apiKey', api_key), params=params)\n return r.json()[\"document_tone\"][\"tones\"]\n\ndef save_to_s3(key, result):\n result_bucket = 'result-bucket-swen549'\n s3.put_object(Bucket=result_bucket, Key=key, Body=result)\n print(\"saved to s3!\")\n\ndef send_to_dashboard(result):\n # POST to Dashboard API\n print(\"Result sent to Dashboard API\")\n","sub_path":"myNewsProcessor/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"20965687","text":"# -*- coding: utf-8 -*-\n# Author: Cyrill Lippuner\n# Date: October 2018\n\"\"\"\nSoftWEAR demo program displaying the main features. This scripts executes on the\nbeagle bone. Starts a server and ADC, PWM and I2C SoftWEAR modules are polled;\nand their status is reported to the remote location.\n\"\"\"\n\nimport os # Required for clearing the system display\nimport sys # Required for get input args\nimport time # Required for controllng the sampling period\nimport threading # Threading class for the threads\nimport Config # SoftWEAR Config\nimport CommunicationModule # SoftWEAR Communication module\nimport MuxModule # SoftWEAR MUX module\nimport InputModule # SoftWEAR Input module\nimport OutputModule # SoftWEAR Output module\nimport PWMModule # SoftWEAR PWM module\nimport ADCModule # SoftWEAR ADC module\nimport I2CModule # SoftWEAR I2C module\nimport json # Serializing class. All objects sent are serialized\nfrom termcolor import colored # Color printing in the console\n\nBOARD = \"Beaglebone Green Wireless v1.0\" # Name of the Board\nSOFTWARE = \"SoftWEAR/Firmware-BeagleboneGreenWireless(v0.1)\" # Identifier of the Software\n\nLIVE_PRINT = False # Flag whether live printing should be enabled in the console\n\nPRINT_PERIODE = 0.2 # Print periode to display values of devices in terminal\nUPDATE_PERIODE = 0.01 # Update periode to refresh values\nSCAN_PERIODE = 1 # Scan periode to refresh values\n\nscanForDevices = True # Scanning enabled as default\nexit = False # Exit flag to terminate all threads\nc = None # Connection object\n\ninputList = [] # List of connected Input devices on the GPIO pins\noutputList = [] # List of connected Output devices on the GPIO pins\npwmList = [] # List of connected PWM devices on the GPIO pins\nadcList = [] # List of connected ADC devices on the Analog pins\ni2cList = [] # List of connected IMU devices on the I2C ports\npwm_list = [] # List of current PWM channels and their state\nconnectionState = \"\" # Current connection state to be displayed\nupdateDuration = 0 # Cycle duration needed to update values\nscanDuration = 0 # Cycle duration needed to scan for new devices\n\nMuxShadow = MuxModule.Mux() # Initialize the SoftWEAR Mux Module\ninput = InputModule.Input() # Initialize the SoftWEAR Input Module\noutput = OutputModule.Output() # Initialize the SoftWEAR Output Module\npwm = PWMModule.PWM() # Initialize the SoftWEAR PWM Module\nadc = ADCModule.ADC() # Initialize the SoftWEAR ADC Module\ni2c = I2CModule.I2C() # Initialize the SoftWEAR I2C Module\n\ndef inputScan():\n \"\"\"Scan for new input devices.\"\"\"\n global inputList, input\n input.scan() # Scan devices on the input pins\n inputListPrevious = inputList # Keep copy of last input devices\n inputList = [] # Reset list of connected Input list\n inputListRegister = [] # List of new devices that need to be registered\n inputListDeregister = [] # List of new devices that need to be deregistered\n\n for el1 in input.connectedDevices: # Check for connected and new devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], inputListPrevious)) > 0):\n inputList.append(el1) # Add to connected list\n else: # Device is not yet registered\n inputListRegister.append(el1) # Add to register list\n inputList.append(el1) # Add connected list\n\n for el1 in inputListPrevious: # Check for disconnected devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], inputList)) == 0):\n inputListDeregister.append(el1) # Add to deregister list\n\n return inputListRegister, inputListDeregister\n\ndef inputUpdate():\n \"\"\"Update the input devices.\"\"\"\n input.getValues()\n\ndef outputScan():\n \"\"\"Scan for new output devices.\"\"\"\n global outputList, output\n output.scan() # Scan devices on the output pins\n outputListPrevious = outputList # Keep copy of last output devices\n outputList = [] # Reset list of connected Output list\n outputListRegister = [] # List of new devices that need to be registered\n outputListDeregister = [] # List of new devices that need to be deregistered\n\n for el1 in output.connectedDevices: # Check for connected and new devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], outputListPrevious)) > 0):\n outputList.append(el1) # Add to connected list\n else: # Device is not yet registered\n outputListRegister.append(el1) # Add to register list\n outputList.append(el1) # Add connected list\n\n for el1 in outputListPrevious: # Check for disconnected devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], outputList)) == 0):\n outputListDeregister.append(el1) # Add to deregister list\n\n return outputListRegister, outputListDeregister\n\ndef outputUpdate():\n \"\"\"Update the output devices.\"\"\"\n output.getValues()\n\ndef pwmScan():\n \"\"\"Scan for new pwm devices.\"\"\"\n global pwmList, pwm\n pwm.scan() # Scan devices on the pwm pins\n pwmListPrevious = pwmList # Keep copy of last pwm devices\n pwmList = [] # Reset list of connected PWM list\n pwmListRegister = [] # List of new devices that need to be registered\n pwmListDeregister = [] # List of new devices that need to be deregistered\n\n for el1 in pwm.connectedDevices: # Check for connected and new devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], pwmListPrevious)) > 0):\n pwmList.append(el1) # Add to connected list\n else: # Device is not yet registered\n pwmListRegister.append(el1) # Add to register list\n pwmList.append(el1) # Add connected list\n\n for el1 in pwmListPrevious: # Check for disconnected devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], pwmList)) == 0):\n pwmListDeregister.append(el1) # Add to deregister list\n\n return pwmListRegister, pwmListDeregister\n\ndef pwmUpdate():\n \"\"\"Update the pwm devices.\"\"\"\n pwm.getValues()\n\ndef adcScan():\n \"\"\"Scan for new adc devices.\"\"\"\n global adcList, adc\n adc.scan() # Scan devices on the analog pins\n adcListPrevious = adcList # Keep copy of last adc devices\n adcList = [] # Reset list of connected ADC list\n adcListRegister = [] # List of new devices that need to be registered\n adcListDeregister = [] # List of new devices that need to be deregistered\n\n for el1 in adc.connectedDevices: # Check for connected and new devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], adcListPrevious)) > 0):\n adcList.append(el1) # Add to connected list\n else: # Device is not yet registered\n adcListRegister.append(el1) # Add to register list\n adcList.append(el1) # Add connected list\n\n for el1 in adcListPrevious: # Check for disconnected devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], adcList)) == 0):\n adcListDeregister.append(el1) # Add to deregister list\n\n return adcListRegister, adcListDeregister\n\n\ndef adcUpdate():\n \"\"\"Update the input devices.\"\"\"\n adc.getValues()\n\n\ndef i2cScan():\n \"\"\"Update the status of all I2C devices and saves any connect or disconnect events.\"\"\"\n global i2cList, i2c\n i2c.scan() # Scan devices on the I2C channels\n i2cListPrevious = i2cList # Keep copy of last i2c devices\n i2cList = [] # Reset list of connected I2C list\n i2cListRegister = [] # List of new devices that need to be registered\n i2cListDeregister = [] # List of new devices that need to be deregistered\n\n for el1 in i2c.connectedDevices: # Check for connected and new devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], i2cListPrevious)) > 0):\n i2cList.append(el1) # Add to connected list\n else: # Device is not yet registered\n i2cListRegister.append(el1) # Add to register list\n i2cList.append(el1) # Add connected list\n\n for el1 in i2cListPrevious: # Check for disconnected devices\n if (len(filter(lambda el2: el2['name'] == el1['name'], i2cList)) == 0):\n i2cListDeregister.append(el1) # Add to deregister list\n\n return i2cListRegister, i2cListDeregister\n\ndef i2cUpdate():\n \"\"\"Update the I2C devices.\"\"\"\n i2c.getValues()\n\ndef scanThread():\n \"\"\"Thread dedicated to scan for new devices.\"\"\"\n global c, scanForDevices, scanDuration\n while True: # Enter the infinite loop\n if not scanForDevices: # Check for scanning\n scanDuration = 0 # No scanning\n time.sleep(SCAN_PERIODE)\n continue\n startTime = time.time() # Save start time of update cycle\n\n messagesSend = [] # List of messages to send\n\n inputListRegister, inputListDeregister = inputScan() # Get the Input devices and events\n outputListRegister, outputListDeregister = outputScan() # Get the Output devices and events\n pwmListRegister, pwmListDeregister = pwmScan() # Get the PWM devices and events\n adcListRegister, adcListDeregister = adcScan() # Get the ADC devices and events\n i2cListRegister, i2cListDeregister = i2cScan() # Get the I2C devices and events\n\n\n for device in inputListDeregister: # Create input device deregister message\n messagesSend.append(json.dumps({'type': 'Deregister',\n 'name': device['name']}))\n\n\n\n for device in inputListRegister: # Create input device register message\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n\n for device in outputListDeregister: # Create output device deregister message\n messagesSend.append(json.dumps({'type': 'Deregister',\n 'name': device['name']}))\n\n\n\n for device in outputListRegister: # Create output device register message\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n\n for device in pwmListDeregister: # Create pwm device deregister message\n messagesSend.append(json.dumps({'type': 'Deregister',\n 'name': device['name']}))\n\n\n\n for device in pwmListRegister: # Create pwm device register message\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n\n for device in adcListDeregister: # Create ADC device deregister message\n messagesSend.append(json.dumps({'type': 'Deregister',\n 'name': device['name']}))\n\n\n\n for device in adcListRegister: # Create ADC device register message\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n\n for device in i2cListDeregister: # Create I2C device deregister message\n messagesSend.append(json.dumps({'type': 'Deregister',\n 'name': device['name']}))\n\n\n\n for device in i2cListRegister: # Create I2C device register message\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n\n if c.getState() == 'Connected':\n c.sendMessages(messagesSend) # Send the messages\n\n endTime = time.time() # Save end time of update cycle\n scanDuration = endTime - startTime # Calculate time used to scan for devices\n\n if (scanDuration < SCAN_PERIODE):\n time.sleep(SCAN_PERIODE - scanDuration) # Sleep until next scan period\n\n if exit: # Exit\n break;\n\n\ndef updateThread():\n \"\"\"Thread dedicated to get updated values of the devices.\"\"\"\n global c, scanForDevices, updateDuration, UPDATE_PERIODE\n while True: # Enter the infinite loop\n startTime = time.time() # Save start time of update cycle\n messagesSend = [] # List of messages to send\n messagesRecv = c.getMessages() # Get new messages\n\n inputUpdate() # Update input devices\n outputUpdate() # Update output devices\n pwmUpdate() # Update PWM devices\n adcUpdate() # Update ADC devices\n i2cUpdate() # Update I2C devices\n\n for messageString in messagesRecv:\n message = json.loads(messageString) # Parse message from string to JSON\n if message['type'] == 'DeviceList': # Create device register message for all devices\n for device in inputList:\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n for device in outputList:\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n for device in pwmList:\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n for device in adcList:\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n for device in i2cList:\n messagesSend.append(json.dumps({'type': 'Register',\n 'name': device['name'],\n 'dir': device['dir'],\n 'dim': device['dim'],\n 'about': device['about'],\n 'settings': device['settings'],\n 'mode': device['mode'],\n 'flags': device['flags'],\n 'frequency': device['frequency'],\n 'dutyFrequency': device['dutyFrequency']}))\n if message['type'] == 'Set': # Get set message for a device and check for devices\n output.setValue(message['name'], message['dim'], message['value'])\n pwm.setValue(message['name'], message['dim'], message['value'])\n i2c.setValue(message['name'], message['dim'], message['value'])\n\n if message['type'] == 'Settings': # Change settings for a device\n input.settings(message)\n output.settings(message)\n pwm.settings(message)\n adc.settings(message)\n i2c.settings(message)\n\n if message['type'] == 'Scan': # Change scan for a device\n scanForDevices = message['value']\n\n dataMessage = {'type': 'D', 'data': []} # Create data message\n for device in inputList: # Create input device data message\n dataMessage['data'].append({'name': device['name'], 'values': device['vals']})\n for device in outputList: # Create output device data message\n dataMessage['data'].append({'name': device['name'], 'values': device['vals']})\n for device in pwmList: # Create pwm device data message\n dataMessage['data'].append({'name': device['name'], 'values': device['vals']})\n for device in adcList: # Create adc device data message\n dataMessage['data'].append({'name': device['name'], 'values': device['vals']})\n for device in i2cList: # Create i2c device data message\n dataMessage['data'].append({'name': device['name'], 'values': device['vals']})\n\n if len(dataMessage['data']) > 0:\n messagesSend.append(json.dumps(dataMessage)) # Send data message\n\n if c.getState() == 'Connected':\n c.sendMessages(messagesSend) # Send the messages\n endTime = time.time() # Save end time of update cycle\n updateDuration = endTime - startTime # Calculate time used to update values\n\n if (updateDuration < UPDATE_PERIODE):\n time.sleep(UPDATE_PERIODE - updateDuration) # Sleep until next update period\n\n if exit: # Exit\n break;\n\n\ndef livePrint():\n \"\"\"Handle all the prints to the console.\"\"\"\n global connectionState # Uses the message global variables\n stringToPrint = \"\" # String to print\n stringToPrint += colored(\"****************************************************************\\n\", 'green')\n stringToPrint += colored(\"* Hardware: {} *\\n\".format(BOARD), 'green') # Display hardware information\n stringToPrint += colored(\"* Software: {} *\\n\".format(SOFTWARE), 'green') # Display software information\n stringToPrint += colored(\"* Layout: {} *\\n\".format(Config.LAYOUT), 'green') # Display layout information\n stringToPrint += colored(\"****************************************************************\\n\", 'green')\n stringToPrint += \"\\n\"\n stringToPrint += \"Connection: {}\".format(colored(connectionState, attrs=['bold', 'dark'])) # Print connection status\n stringToPrint += \"\\n\"\n stringToPrint += \"Update cycle: \" # Print update cycle time\n stringToPrint += colored(\"{:.2f} ms / {:.2f} ms\\n\".format(updateDuration * 1000, UPDATE_PERIODE * 1000), 'grey') # Print update cycle time\n if scanForDevices:\n stringToPrint += \"Scan cycle: \" # Print scan cycle time\n stringToPrint += colored(\"{:.2f} ms / {:.2f} ms\\n\".format(scanDuration * 1000, SCAN_PERIODE * 1000), 'grey') # Print scan cycle time\n else:\n stringToPrint += \"Scan cycle: -\\n\" # Print scan disabled\n\n # Print Input informations:\n stringToPrint += \"\\nConnected Inputs: {}\\n\".format(colored(len(inputList), attrs=['bold', 'dark']))\n for el in inputList: # Go through all connected Input devices\n if ('mux' in el and 'pin' in el and 'name' in el and 'about' in el and 'val' in el and 'cycle' in el):\n if el['mux'] != -1: # Muxed pin\n stringToPrint += '({}:{}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['pin']), str(el['mux']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n else: # Unmuxed pin\n stringToPrint += '({}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['pin']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n\n # Print Output informations:\n stringToPrint += \"\\nConnected Outputs: {}\\n\".format(colored(len(outputList), attrs=['bold', 'dark']))\n for el in outputList: # Go through all connected Output devices\n if ('pin' in el and 'name' in el and 'about' in el and 'val' in el and 'cycle' in el):\n stringToPrint += '({}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['pin']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n\n # Print PWM informations:\n stringToPrint += \"\\nConnected PWMs: {}\\n\".format(colored(len(pwmList), attrs=['bold', 'dark']))\n for el in pwmList: # Go through all connected PWM devices\n if ('pin' in el and 'name' in el and 'about' in el and 'val' in el and 'cycle' in el):\n stringToPrint += '({}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['pin']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n\n # Print ADC informations:\n stringToPrint += \"\\nConnected ADCs: {}\\n\".format(colored(len(adcList), attrs=['bold', 'dark']))\n for el in adcList: # Go through all connected ADC devices\n if ('mux' in el and 'pin' in el and 'name' in el and 'about' in el and 'val' in el and 'cycle' in el):\n if el['mux'] != -1: # Muxed pin\n stringToPrint += '({}:{}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['pin']), str(el['mux']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n else: # Unmuxed pin\n stringToPrint += '({}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['pin']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n\n # Print IMU informations:\n stringToPrint += \"\\nConnected I2Cs: {}\\n\".format(colored(len(i2cList), attrs=['bold', 'dark']))\n for el in i2cList: # Go through all connected I2C devices\n if ('channel' in el and 'name' in el and 'about' in el and 'val' in el and 'cycle' in el):\n stringToPrint += '(Channel {}) {}: {} / {} | {:.2f} ms\\n'.format(str(el['channel']), el['name'], colored(str(el['about']['dimMap']), 'blue'), colored(str(el['val']), 'blue'), el['cycle'] * 1000.)\n\n stringToPrint += \"\\n\\nManually break to exit!\\n\" # Print exit condition\n stringToPrint += \">> Ctrl-C\\n\" # Print exit shortcut\n os.system('clear') # Clear console output\n print(stringToPrint) # Print live data\n\ndef main():\n \"\"\"Infinite loop function, reads all devices and manages the connection.\"\"\"\n global connectionState, c, exit, LIVE_PRINT\n\n if ('live' in sys.argv or 'l' in sys.argv): # Check live plot parameter\n LIVE_PRINT = True\n # Create the communication class. Using 'with' to ensure correct termination.\n c = CommunicationModule.CommunicationConnection() # Create the communication\n c.connect() # Start communication thread\n scan = threading.Thread(target=scanThread, name=\"ScanThread\") # Create scan thread\n scan.daemon = True # Set scan thread as daemonic\n scan.start() # Start scan thread\n update = threading.Thread(target=updateThread, name=\"UpdateThread\") # Create update thread\n update.daemon = True # Set update thread as daemonic\n update.start() # Start update thread\n\n while(True): # Enter the infinite loop\n connectionState = c.getState() # Get the connection state for printing reasons\n \"\"\"Ping\"\"\"\n if c.getState() is 'Connected':\n # sendMessages = [json.dumps({'type': 'Ping','name':''})]\n # c.sendMessages(sendMessages)\n sendMessages = [json.dumps({'type': 'CycleDuration','name':'', 'values': {'update': updateDuration, 'scan': scanDuration}})]\n c.sendMessages(sendMessages)\n\n if LIVE_PRINT: # Check for live plotting\n livePrint() # Call print function\n time.sleep(PRINT_PERIODE) # Sleep until next print period\n\n # If we reach this -> something happened. Close communication channel\n exit = True\n c.stopAndFreeResources()\n\n# Just call the main function.\nmain()","sub_path":"Bidirectional_interface/Haptics/Firmware/src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":34254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"431780142","text":"#!/usr/bin/python3.8\n\n# Copyright (C) 2019 Andrew Hamilton. All rights reserved.\n# Licensed under the Artistic License 2.0.\n\n\nimport json\nimport os\nimport subprocess\nimport sys\n\n\nUSAGE = \"\"\"Make a flatpak build of eris.\n\nUsage: build-flatpak.sh \n\ne.g. # build-flatpak.sh com.github.ahamilton.eris.json eris-build flatpak-cache\n\nThe script should only be run from the root of the local eris repository.\n\"\"\"\n\n\ndef patch_manifest(manifest_path, patched_manifest_path):\n with open(manifest_path) as manifest_file:\n manifest = json.load(manifest_file)\n eris_module = manifest[\"modules\"][-1]\n eris_module[\"sources\"][0][\"url\"] = \"file://\" + os.getcwd()\n with open(patched_manifest_path, \"w\") as patched_manifest_file:\n json.dump(manifest, patched_manifest_file, indent=2)\n\n\ndef main(argv):\n if len(argv) != 4:\n print(USAGE)\n sys.exit(1)\n manifest_path, build_dir, state_dir = argv[1:4]\n patched_manifest_path = \"manifests-cache/patched-manifest.json\"\n patch_manifest(manifest_path, patched_manifest_path)\n subprocess.run([\"flatpak-builder\", build_dir, patched_manifest_path,\n \"--force-clean\", \"--state-dir\", state_dir,\n \"--disable-updates\"], check=True)\n subprocess.run([\"flatpak\", \"build\", build_dir, \"test-all\"], check=True)\n subprocess.run([\"flatpak\", \"build\", build_dir, \"eris\", \"--help\"],\n check=True)\n print(\"Build successful:\", build_dir)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"build-flatpak.py","file_name":"build-flatpak.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"178816941","text":"import os\nimport subprocess\n\nimport math\nimport sys\n\nimport util\n\nignored = [\"testResources/PrintInCall.java\", \"testResources/LoopinLoop2.java\", \"testResources/Iterations.java\"]\n\n\ndef run_test(args, path):\n cwd = os.getcwd()\n script_path = cwd + \"/run.sh\"\n\n cmd = [script_path, path, \"--args\"] + [str(i) for i in args]\n result = subprocess.run(cmd, stdout=subprocess.PIPE)\n return result.stdout.decode(\"utf-8\").strip()\n\n\ndef check_result(output, model_count, testcase_name):\n if model_count == -1:\n print(\"Crashed!\")\n return None\n json_data = util.load_results(testcase_name)\n if json_data is None:\n return None\n\n if output not in json_data[\"result\"]:\n return False\n\n expected = int(json_data[\"result\"][output])\n model_count = model_count.split(\"---\")[0].strip()\n # print(\"Expected: \" + str(expected))\n # print(\"Got: \" + model_count)\n return int(model_count) == expected\n\n\ndef parse_result(result_string, num_args):\n if result_string.strip() == \"No information leakage\":\n return \"\", math.pow(2, num_args * 3)\n\n try:\n mcs = [mc.strip() for mc in result_string.split(\"---\")]\n all_results = []\n for mc in mcs:\n (output, model_count) = result_string.split(\"# of inputs w/ the same output:\")\n output = output.strip()\n model_count = model_count.strip()\n all_results.append((output, model_count))\n except ValueError:\n (output, model_count) = (\"-1\", \"-1\")\n\n return all_results\n\n\ndef check_testcase(test_case, args):\n name = util.get_name_from_testcase_path(test_case)\n result_string = run_test(args, test_case)\n all_results = parse_result(result_string, len(args))\n\n all_correct = True\n count = 0\n for (output, model_count) in all_results:\n output = output + str(count)\n all_correct = all_correct and check_result(output, model_count, name)\n\n return all_correct\n\n\ndef test(path):\n if util.load_results(util.get_name_from_testcase_path(test_case)) is None:\n print(\"Skipping testcase: \" + path + \" -- result file not found\")\n return True\n num_param = util.load_results(util.get_name_from_testcase_path(test_case))[\"args\"]\n all_inputs = util.generate_possible_inputs(num_param, 3)\n\n print(\"Starting \" + path)\n\n fail = 0\n success = 0\n\n for args in all_inputs:\n check = check_testcase(path, args)\n if check is None:\n return False\n\n if not check:\n args = [str(i) for i in args]\n print(\"Test failed for input: \" + \" \".join(args))\n fail += 1\n else:\n success += 1\n\n print(\"Testcase \" + path + \": \" + str(success) + \" successful, \" + str(fail) + \" failed\")\n return fail == 0\n\n\nif __name__ == \"__main__\":\n print(\"Make sure all debug prints are turned off !!!\")\n test_case = sys.argv[1]\n\n successful = []\n\n if test_case == \"all\":\n for filename in os.listdir(\"testResources/\"):\n test_case = \"testResources/\" + filename\n if os.path.isdir(test_case) or test_case in ignored:\n continue\n\n res = test(test_case)\n\n if res:\n successful.append(filename)\n os.system(\"rm -r out_*\")\n\n with open(\"testResources/results/successful.txt\", 'w') as f:\n for case in successful:\n f.write(case)\n f.write(\"\\n\")\n\n if test_case == \"failed\":\n unnecessary = []\n\n with open(\"testResources/results/successful.txt\", 'r') as f:\n content = f.readlines()\n unnecessary = [x.strip() for x in content]\n\n for filename in os.listdir(\"testResources/\"):\n test_case = \"testResources/\" + filename\n\n if os.path.isdir(test_case):\n continue\n\n if test_case in unnecessary or test_case in ignored:\n continue\n\n res = test(test_case)\n\n if res:\n successful.append(filename)\n os.system(\"rm -r out_*\")\n\n with open(\"testResources/results/successful.txt\", 'a') as f:\n for case in successful:\n f.write(\"\\n\")\n f.write(case)\n\n else:\n res = test(test_case)\n if res:\n with open(\"testResources/results/successful.txt\", 'a') as f:\n f.write(\"\\n\" + test_case)","sub_path":"ifc/sdg/qifc/joana.ifc.sdg.qifc.qif_interpreter/scripts/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"614237585","text":"import bs4\nimport re\nimport os\nimport requests\nimport json\nimport datetime\nfrom typing import Iterable\n\nfrom dataPipelines.gc_crawler.requestors import MapBasedPseudoRequestor\nfrom dataPipelines.gc_crawler.exec_model import Crawler, Parser, Pager\nfrom dataPipelines.gc_crawler.data_model import Document, DownloadableItem\nfrom dataPipelines.gc_crawler.utils import abs_url\n\nfrom . import SOURCE_SAMPLE_DIR, BASE_SOURCE_URL\n\nclass OPMPager(Pager):\n \"\"\"Pager for OPM crawler\"\"\"\n\n def iter_page_links(self) -> Iterable[str]:\n yield BASE_SOURCE_URL\n\n\nclass OPMParser(Parser):\n \"\"\"Parser for OPM crawler\"\"\"\n\n def parse_docs_from_page(self, page_url: str, page_text: str) -> Iterable[Document]:\n \"\"\"Parse document objects from page of text\"\"\"\n\n base_url = 'https://www.whitehouse.gov'\n\n r = requests.get(BASE_SOURCE_URL)\n soup = bs4.BeautifulSoup(r.content, features=\"html.parser\")\n\n parsed_nums = []\n\n # get target column of list items\n parsed_docs = []\n li_list = soup.find_all('li')\n for li in li_list:\n doc_type = 'OMBM'\n doc_num = ''\n doc_name = ''\n doc_title = ''\n chapter_date = ''\n publication_date = ''\n cac_login_required = False\n pdf_url = ''\n exp_date = ''\n issuance_num = ''\n pdf_di = None\n if 'supersede' not in li.text.lower():\n a_list = li.findChildren('a')\n for a in a_list:\n link = a.get('href', None) or a.get('data-copy-href', None)\n if link.lower().endswith('.pdf'):\n if link.startswith('http'):\n pdf_url = link\n else:\n pdf_url = base_url + link.strip()\n commaTokens = a.text.strip().split(',', 1)\n spaceTokens = a.text.strip().split(' ', 1)\n if len(commaTokens) > 1 and len(commaTokens[0]) < len(spaceTokens[0]):\n doc_num=commaTokens[0]\n doc_title=re.sub(r'^.*?,', '', a.text.strip())\n doc_name=\"OMBM \" + doc_num\n elif len(spaceTokens) > 1 and len(spaceTokens[0]) < len(commaTokens[0]):\n doc_num=spaceTokens[0].rstrip(',.*')\n doc_title=spaceTokens[1]\n doc_name=\"OMBM \" + doc_num\n possible_date=li.text[li.text.find(\"(\")+1:li.text.find(\")\")]\n if re.match(pattern=r\".*, \\d{4}.*\", string=possible_date):\n publication_date=possible_date\n if pdf_url != '' and doc_num.count('-') == 2:\n pdf_di = DownloadableItem(\n doc_type='pdf',\n web_url=pdf_url\n )\n version_hash_fields = {\n \"item_currency\": pdf_url.split('/')[-1], # version metadata found on pdf links\n \"pub_date\": publication_date.strip(),\n }\n parsed_title=re.sub('\\\\\"', '', doc_title)\n parsed_num=doc_num.strip()\n if parsed_num not in parsed_nums:\n doc = Document(\n doc_name=doc_name.strip(),\n doc_title=parsed_title,\n doc_num=parsed_num,\n doc_type=doc_type.strip(),\n publication_date=publication_date,\n cac_login_required=cac_login_required,\n crawler_used=\"opm_pubs\",\n source_page_url=BASE_SOURCE_URL.strip(),\n version_hash_raw_data=version_hash_fields,\n downloadable_items=[pdf_di]\n )\n parsed_docs.append(doc)\n parsed_nums.append(parsed_num)\n return parsed_docs\n\n\nclass OPMCrawler(Crawler):\n \"\"\"Crawler for the example web scraper\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(\n *args,\n **kwargs,\n pager=OPMPager(\n starting_url=BASE_SOURCE_URL\n ),\n parser=OPMParser()\n )\n\n\nclass FakeOPMCrawler(Crawler):\n \"\"\"OPM crawler that just uses stubs and local source files\"\"\"\n\n def __init__(self, *args, **kwargs):\n with open(os.path.join(SOURCE_SAMPLE_DIR, 'dod_issuances.html')) as f:\n default_text = f.read()\n\n super().__init__(\n *args,\n **kwargs,\n pager=OPMPager(\n requestor=MapBasedPseudoRequestor(\n default_text=default_text\n ),\n starting_url=BASE_SOURCE_URL\n ),\n parser=OPMParser()\n )\n","sub_path":"dataPipelines/gc_crawler/opm_pubs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"499735430","text":"import re\n\nlines = [\n \"I. A Scandal in Bohemia\",\n \"II. The Red-Headed League\",\n \"III. A Case of Identity\",\n \"IV. The Boscombe Valley Mystery\",\n \"V. The Five Orange Pips\",\n]\npattern = re.compile(\"[IV]+\\.\\s+[A-Za-z ]{1,200}\")\nfor l in lines:\n match = re.search(pattern, l)\n if match:\n print(match.group())\n","sub_path":"python-advanced-features-master/13-regex/example-04.py","file_name":"example-04.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"481993051","text":"# from config import *\n# import os\n\nfrom statistics import mean\nimport xlrd\n# import xlwt\nfrom xlutils.copy import copy\nfrom common.log import *\nfrom gevent import monkey\nmonkey.patch_all()\nimport gevent\nimport requests\nimport json\nfrom gevent.queue import Queue\n\n\nclass ApiGeneral():\n\n # get方法\n # @classmethod # 类方法可以不实例化调用\n def get(self, url, params,**kwargs): #params是str类型,有&和=的数据\n\n print('进入get方法')\n dictdata = self.str_to_dict(params) #转换成字典\n print(dictdata)\n # print('打印传入的参数',type(url),type(params))\n try:\n resp = requests.get(url=url, params=dictdata,**kwargs) # params对应的数据是字典类型,*是列表,**是字典\n print(resp)\n except Exception as e:\n Mylog().my_log().error(e)\n print(e)\n resp='get请求失败!'\n print(resp)\n\n return resp\n\n def getd(self, url, data, **kwargs):\n print('进入get方法')\n try:\n resp = requests.get(url=url, data=data, **kwargs) # params对应的数据是字典类型,*是列表,**是字典\n print(resp)\n except Exception as e:\n Mylog().my_log().error(e)\n print(e)\n resp = 'get请求失败!'\n print(resp)\n\n return resp\n\n # post方法\n @classmethod # 类方法可以不实例化调用\n def post(self, url,**kwargs):\n # session = requests.Session().get('https://uaterp.pgl-world.com.cn')\n try:\n # resp = requests.post(url=url, data=data,**kwargs) #data应该是字典类型\n resp = requests.post(url=url, **kwargs)\n # print(resp.content)\n except Exception as e:\n Mylog().my_log().error(e)\n resp='fail'\n print(e)\n # print(resp)\n return resp\n\n\n # # 如果请求含附件\n #文件打开方式是rb,二进制,其他方式打开会报错,文件路径格式可以是\\\\,\\,/,文件\n # 可以是字典,也可以是列表,可以有多个文件同时上传,文件定义时多个元组或者键值对,\n # filename一般是代码的文件参数名,但试过如果不是也能上传成功,Content-Type是json的话,参数主是json形式的,要dumps,其他是dict(取出的是str就lodas下)\n @classmethod # 类方法可以不实例化调用 .encode('utf-8')\n def filepost(self, url,file, **kwargs):\n # with open(file, 'rb') as f:\n try:\n files = {'file': open(file, 'rb')} #先实例一个字典类型的文件对象\n rsp = requests.post(url=url,files=files, **kwargs) #不需要转换成json(json.dumps),因为是表单的数据\n # rsp = requests.post(url=url, files=f, json=json.dumps(json.loads(data)), **kwargs) # 要用json,不能用data\n # print(resp.content)\n except Exception as e:\n Mylog().my_log().error(e)\n print(e)\n # print(resp)\n return rsp\n\n # # get方法\t,有附件\n # @classmethod# 类方法可以不实例化调用\n # def get(self, url, params, cookies, file):\n # with open(file, 'a') as f:\n # jdata = self.str_to_dict(params)\n # try:\n # resp = requests.get(url=url, parms=params, cookies=cookies, files=f)\n # except Exception as e:\n # Mylog().my_log().error(e)\n # return resp\n\n # 字符串转换成字典方法\n @classmethod\n def str_to_dict(self, data):\n dict1 = {}\n for i in data.split('&'): #用&切割成两部分,形成一个列表\n key = i.split('=')[0] #第一个是键\n value = i.split('=')[1] #第二个是值\n dict1[key] = value\n return dict1\n #\n #\n # # 响应结果对比并写入结果,主要是对比code一样就通过\n def result(self, expectresult, actualresult): #两个参数传入是str\n jdate1=json.loads(expectresult)\n jdate2 = json.loads(actualresult)\n # for k in jdate1.keys():\n # if k=='code':\n # c=k\n # if k=='msg':\n # m=k\n if jdate1['code']==jdate2['code']: # 通过code和msg共同判断是否通过,可能这样的粒度有点粗,后续看情况优化\n if jdate1['msg']==jdate2['msg']:\n result_status = '1' # 通过\n else:\n result_status = '0' # 不通过\n else:\n result_status = '0' # 不通过\n return result_status\n\n #\n # # for i in actualresult:\n # # if i not in expectresult:\n # # result_status = '0' #不通过\n # # result_status = '1' # 通过\n # #\n # # else:\n # # result_status = '0' #不通过\n # # return result_status\n #\n #\n # 把结果写回excel\n #当文件打开时,运行方法会报错(或者数据写不进去!!!!!),不允许操作,所以运作时一定要关闭文件,另外重新运作,新插入数据会覆盖原有的\n def write_result(self, row, actualresult, result, tester, casefile): # 文件不用写全路径,只写文件名只可\n case_path=os.path.join(CASEPATH, casefile)\n print(case_path)\n book = xlrd.open_workbook(case_path) # 创建一个excel操作对象\n book2 =copy(book) #复制book对象 #管道作用:利用xlutils.copy函数,将xlrd.Book转为xlwt.Workbook,再用xlwt模块进行存储\n sheet = book2.get_sheet(0) # 创建一个sheet操作实例,读取的是第一个excel ,#通过get_sheet()获取的sheet有write()方法\n sheet.write(row, 13, actualresult)\n sheet.write(row, 14, result)\n sheet.write(row, 15, tester)\n\n # book2.save(case_path)\n book2.save(case_path)\n print('结果写入保存成功!')\n # print('保存后1')\n # sheet2=book.sheet_by_index(0)\n # print(sheet2.cell_value(row,12))\n # print('保存后')\n\n #通过登录动态获取cookies\n def get_cookies(self,url,params): #通过登录获取cookie供后续接口调用,由于调试项目登录接口参数是&格式的,具体按实际项目进行修改调整\n respond=self.get(url=url,params=params)\n self.cookies=respond.cookies.get_dict() #respond.cookies只会获取到一个cookiejar对象,一定要有get_dict()方法,返回dict类型\n print(self.cookies)\n print(type(self.cookies))\n self.strcookies=json.dumps(self.cookies) #由于get方法传入参数会loads成dict类型,所以传入的一定是str,所以要转换成str\n print('打印strcookies',self.strcookies)\n print(type(self.strcookies))\n return self.strcookies\n# 接口并发\nclass ConCurrent():\n # 请求成功\n pass_number=0\n # 请求失败\n fail_number=0\n # 断言失败\n assertfail=0\n # 断言通过\n assertpass=0\n # 执行时长\n run_time_list=[]\n api=ApiGeneral()\n\n # 接口请求,number:循环次数,url:接口地址,data:请求体,assertion:断言\n def concurrent(self,number,url,data,num,assertion=None,*args,**kwargs):\n print(data)\n print(type(data))\n if isinstance(data,dict):\n pass\n else:\n data = eval(data)\n print('第一次', num)\n # print('打印输入的data',data)\n for i in range(number):\n # 开始时间\n start_time=time.time()\n respond=self.api.post(url=url,data=json.dumps(data))\n # gevent.sleep(5)\n # 结束时间\n end_time = time.time()\n print(respond.content.decode('utf-8'))\n\n # 结束减去开始时间,保留四位小数\n run_time=round(end_time-start_time,4)\n self.run_time_list.append(run_time)\n if respond.status_code==200:\n self.pass_number=self.pass_number+1\n # 请求成功的进行断言\n content=eval(respond.content.decode('utf-8'))\n if assertion is not None:\n print(content['msg'],assertion)\n if assertion in content['msg']:\n self.assertpass = self.assertpass + 1\n else:\n self.assertfail = self.assertfail + 1\n else:\n # 用'0000'表示没有断言\n self.assertpass = '0000'\n self.assertfail = '0000'\n else:\n self.fail_number = self.fail_number + 1\n print('第二次', num)\n\n # threadings:线程,用户数, number:循环次数, url:地址, data:请求体, file:参数化数据文件,parameterized:是否参数化\n def concurrent_run(self,threadings,number,url,data=None,file=None,*args,**kwargs):\n if isinstance(data, dict):\n pass\n else:\n data = eval(data)\n if file is not None:\n book = xlrd.open_workbook(file) # 创建一个excel操作对象\n # print(os.path.join(CASEPATH, file))\n sheet = book.sheet_by_index(0) # 创建一个sheet操作实例,读取的是第一个excel,如果需要也可以参数化\n nnrow = sheet.nrows # 获取行数\n # 创建一个空列表,用于存放用例\n all_data = []\n # 存放最后一列,最后一列放断言\n all_data2 = []\n # print('空列表长度',len(all_case))\n # 第一行写参数名称\n firstrow=sheet.row_values(0)\n firstrow_len=len(sheet.row_values(0))\n param = list(firstrow[0:firstrow_len-1])\n # print(param)\n\n for j in range(1, nnrow):\n list1 = list(sheet.row_values(j)[0:firstrow_len-1])\n all_data.append(list1)\n # print(all_data)\n # 获取倒数第一行,是断言\n for j in range(1, nnrow):\n list1 = sheet.row_values(j)[firstrow_len-1]\n all_data2.append(list1)\n # print('断言',all_data2)\n data_list = []\n # 嵌套层不不适用参数化,只能是第一层参数\n for row,a in zip(all_data,all_data2):\n for key, value in zip(param, row):\n data[key] = value\n # 没有转换成str的情况,只会把最后一个data重复加入列表,不知道原因\n # data_list.append(data)\n l=[str(data),a]\n # l=[data,a]\n # data_list.append(str(data))\n data_list.append(l)\n\n # print('哈哈',data_list)\n print(\"请求URL: {url}\".format(url=url))\n print(\"用户数:{},循环次数: {}\".format(threadings, number))\n print(\"============== Running ===================\")\n # 参数化个数与线程数要一致,按以下代码设计,如果不一致,可能会有问题\n jobs = [gevent.spawn(self.concurrent, number=number, url=url,data=j[0],num=i,assertion=j[1]) for i, j in zip(range(threadings), data_list)]\n # jobs = [gevent.spawn(self.concurrent, number=number, url=url,data=j,num=i,) for i, j in zip(range(threadings), data_list)]\n\n else:\n print('不需要参数化')\n print(\"请求URL: {url}\".format(url=url))\n print(\"用户数:{},循环次数: {}\".format(threadings, number))\n print(\"============== Running ===================\")\n # 参数化个数与线程数要一致,以下代码如果不一致,可能会有问题\n jobs = [gevent.spawn(self.concurrent, number, url, data,i) for i in range(threadings)]\n gevent.joinall(jobs)\n # gevent.wait(jobs)\n\n print(\"\\n============== Results ===================\")\n print(\"最大: {} s\".format(str(max(self.run_time_list))))\n print(\"最小: {} s\".format(str(min(self.run_time_list))))\n print(\"平均: {} s\".format(str(round(mean(self.run_time_list), 4))))\n print(\"请求成功\", self.pass_number)\n print(\"请求失败\", self.fail_number)\n print(\"断言成功\", self.assertpass)\n print(\"断言失败\", self.assertfail)\n print(\"============== end ===================\")\n\nif __name__ == '__main__':\n dit = {\n \"jobNo\": \"202012090111\",\n \"transportMode\": \"QY\",\n \"supplierCode\": \"smp0910\",\n \"plateNumber\": \"粤B12318\",\n \"driverName\": \"测试司机18\",\n \"carType\": \"DF96\",\n \"startProvinceCode\": \"370000\",\n \"startCityCode\": \"370300\",\n \"startCountyCode\": \"370321\",\n \"endProvinceCode\": \"370000\",\n \"endCityCode\": \"370300\",\n \"endCountyCode\": \"370322\",\n \"planJobTime\": \"2019-10-11 15:00:00\",\n \"actuallyJobTime\": \"2019-10-17 15:00:00\",\n \"totalWeight\": 155,\n \"totalVolume\": 115,\n \"totalQty\": 160,\n \"operateCompanyCode\": \"PGLKY\",\n \"operateDepartCode\": \"PGLKY03\",\n \"jobStatus\": \"未完成\",\n \"detailList\": [\n {\n \"mainOrderNo\": \"DD20201207000027\",\n \"subOrderNo\": \"DD20201207000027T001\",\n \"planWorkloadWeight\": 30,\n \"actualWorkloadWeight\": 30,\n \"planWorkloadVolume\": 13,\n \"actualWorkloadVolume\": 1111,\n \"planWorkloadQty\": 1115,\n \"actualWorkloadQty\": 5,\n \"clientProductList\": [],\n \"supplierProductList\": [],\n \"jobTime\": \"2019-10-18 15:00:00\",\n \"remark\": \"测试快递运输费18\"\n },\n {\n \"mainOrderNo\": \"DD20201203000016\",\n \"subOrderNo\": \"DD20201203000016T001\",\n \"planWorkloadWeight\": 30,\n \"actualWorkloadWeight\": 30,\n \"planWorkloadVolume\": 13,\n \"actualWorkloadVolume\": 1111,\n \"planWorkloadQty\": 1115,\n \"actualWorkloadQty\": 5,\n \"clientProductList\": [],\n \"supplierProductList\": [],\n \"jobTime\": \"2019-10-18 15:00:00\",\n \"remark\": \"测试快递运输费18\"\n\n },\n {\n \"mainOrderNo\": \"DD20201207000026\",\n \"subOrderNo\": \"DD20201207000026T002\",\n \"planWorkloadWeight\": 30,\n \"actualWorkloadWeight\": 30,\n \"planWorkloadVolume\": 13,\n \"actualWorkloadVolume\": 1111,\n \"planWorkloadQty\": 1115,\n \"actualWorkloadQty\": 5,\n \"clientProductList\": [],\n \"supplierProductList\": [],\n \"jobTime\": \"2019-10-18 15:00:00\",\n \"remark\": \"测试快递运输费18\"\n\n },\n {\n \"mainOrderNo\": \"DD20201207000028\",\n \"subOrderNo\": \"DD20201207000028T001\",\n \"planWorkloadWeight\": 30,\n \"actualWorkloadWeight\": 30,\n \"planWorkloadVolume\": 13,\n \"actualWorkloadVolume\": 1111,\n \"planWorkloadQty\": 1115,\n \"actualWorkloadQty\": 5,\n \"clientProductList\": [],\n \"supplierProductList\": [],\n \"jobTime\": \"2019-10-18 15:00:00\",\n \"remark\": \"测试快递运输费18\"\n }\n ]\n }\n url11='https://uaterp.pgl-world.com.cn/api/service?method=pgl.erp.api.oms.jobOrderTp.add&appCode=pgl-erp-oss-oms&companyCode=PGLKY×tamp=2020-12-12%2016:49:00&version=1.0&sign=M2f8gkzZEzMKPgq&departCode=PGLKY03'\n # con = ConCurrent()\n # con.concurrent_run(5, 1,data=dit,url=url11,file=r'E:\\software\\Python3.8.3\\UiAuto\\file\\condata.xlsx')\n\n\n# r=ApiGeneral().post(url='https://uaterp.pgl-world.com.cn/login/ajaxDoLogin',data={\"username\":\"sybmsy\",\"password\":\"12345678\",\"captchaCode\":\"8888\"})\n# print(r.content.decode('utf-8'))","sub_path":"UiAuto/common/api_general.py","file_name":"api_general.py","file_ext":"py","file_size_in_byte":15879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"613137927","text":"\n\nimport pdb\n\nimport argparse\nimport configparser\nimport datetime\nimport json\n\n\n\n\n\ndef parse_args():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--annfile\", help=\"Path to '.xml.ann' file\", default=\"./groundtruth.xml.ann\")\n parser.add_argument(\"--outfile\", help=\"Path to output json file\", default=\"./results.xml.ann\")\n #parser.add_argument(\"--config\", help=\"Path to configuration file\", default=\"./config.txt\")\n #parser.add_argument(\"--evalfile\", help=\"Path to output file\", default=\"./evaluation.txt\")\n\n _args = parser.parse_args()\n return _args\n\n\n\n# We define this global variable so that we know what EntityTypes there are.\n# It will be appended to whenever we come across an Entity with a new EntityType.\nEntityTypes = [\"Caption\", \"Reference\"]\n\n# We should also define the configuration parameters as a global variable as well.\nargs = None\n#config = None\n\n\n\n# Reading in a BRAT .ann file.\ndef read_ann(filename):\n\n #ann_list = []\n\n ann_dict = {}\n\n conn_map = {}\n\n #pdb.set_trace()\n\n annot_count = 0\n\n continuations = \"\"\n\n # Opening the file.\n with open(filename, 'r') as f:\n line = f.readline()\n # Parsing every line in the file individually.\n while line:\n tokens = line.split()\n # We know a line is to be ignored if it starts with \"#\".\n #if tokens[0][0] == \"#\":\n # line = f.readline()\n # continue\n\n # Here's the tricky bit. I need to resume reading lines until I stop getting\n # attribute lines. I then need to use those attributes to load the character\n # range for this particular annotation into a specific dictionary, based on\n # what the Type and Num are.\n if tokens[0][0] == \"T\":\n # Read in the annotation.\n\n # Step 1: Get the character range.\n char_range = []\n start_ann = int(tokens[2])\n index = 3\n while \";\" in tokens[index]:\n i = tokens[index].split(\";\")\n #ann_list += range(start_ann, int(i[0]))\n char_range.append([ start_ann, int(i[0]) ])\n start_ann = int(i[1])\n index += 1\n #char_range += range(start_ann, int(tokens[index]))\n char_range.append([ start_ann, int(tokens[index]) ])\n\n # The rest of the tokens make up the text covered by the entity.\n text = \" \".join(tokens[index+1:])\n\n # Step 2: Handle the EntityType. This can be \"Reference\" or \"Caption\" or something else.\n entitytype = tokens[1]\n\n # Maintaining the list of EntityTypes.\n if entitytype not in EntityTypes:\n EntityTypes.append(entitytype)\n # New EntityTypes are included by default, and must be explicitly disallowed in the config file.\n #config[\"Allowed ENTITYTYPES\"][entitytype] = \"true\"\n\n # Step 3: Using the ID of the entity as a key in a dictionary to enable future attribute modification.\n id = tokens[0]\n\n ann_dict[id] = {\n \"ID\": id,\n \"EntityType\": entitytype,\n \"RefType\": None,\n \"Type\": None,\n \"Num\": None,\n \"range\": char_range,\n \"text\": text\n }\n\n # Each line that begins with \"A\" is an attribute that needs to be set.\n if tokens[0][0] == \"A\":\n\n # The ID of the entity the attribute belongs to.\n e_id = tokens[2]\n # The attribute name we're overwriting. Can be \"RefType\", \"Type\", or \"Num\".\n a_type = tokens[1]\n # The value of the attribute we're overwriting.\n a_val = tokens[3]\n\n # Special case: If We're overwriting a Num attribute, the value needs to be an integer.\n if a_type == \"Num\":\n a_val = int(a_val)\n\n # Overwriting the attribute field.\n ann_dict[e_id][a_type] = a_val\n\n # Lines that begin with \"R\" are relations / continuations.\n \n if tokens[0][0] == \"R\":\n continuations += line\n\n \"\"\"\n\n fromID = tokens[2][5:]\n toID = tokens[3][5:]\n\n conn_map[toID] = fromID\n\n while fromID in conn_map.keys():\n fromID = conn_map[fromID]\n\n #fromEntity = ann_dict[fromID]\n #toEntity = ann_dict[toID]\n\n # Append the ranges together.\n ann_dict[fromID][\"range\"] += ann_dict[toID][\"range\"]\n\n # And the texts.\n ann_dict[fromID][\"text\"] += \" \" + ann_dict[toID][\"text\"]\n\n # Since we are treating this as a single annotation, delete the 'to' entity.\n del ann_dict[toID]\n \"\"\"\n\n\n # Reading in the new line to continue the loop.\n line = f.readline()\n\n #ann_dict[\"Connected\"] = conn_map\n\n return (ann_dict, continuations)\n\n # Now that the dictionary of annotations is complete, we check each one against the configuration file.\n # We only want to include those with appropriate EntityTypes, RefTypes, and Types.\n\n #pdb.set_trace()\n\n #for key in ann_dict.keys():\n # ann = ann_dict[key]\n #if config[\"Allowed ENTITYTYPES\"][ann[\"EntityType\"]] != \"true\" or \\\n # (ann[\"RefType\"] is not None and config[\"Allowed REFTYPES\"][ann[\"RefType\"]] != \"true\") or \\\n # (ann[\"Type\"] is not None and config[\"Allowed TYPES\"][ann[\"Type\"]] != \"true\"):\n # continue\n\n # If it does not violate the configuration parameters, append it to the list of returned entities.\n # ann_list.append(ann)\n\n #return ann_list\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n # Part 1: Parse the arguments.\n\n _args = parse_args()\n\n\n\n ann_dict = read_ann(_args.annfile)\n\n with open(_args.outfile, 'w') as of:\n json.dump(ann_dict, of)\n","sub_path":"xmlConversion/ann_to_json.py","file_name":"ann_to_json.py","file_ext":"py","file_size_in_byte":6187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"542870843","text":"#!/usr/bin/env python\nimport argparse\n\nimport numpy as np\n\n\n\"\"\"\nGiven a SV vcf file, calculate the maximum Jaccard similarity between each accession and the pimps for non-overlapping\nwindows along the reference genome coordinates.\n\nOutput is a matrix. Each row is an SLL accession, and each column is the non-overlapping window. Each element is \nthe maximum Jaccard similarity of SVs in that window between that accession and the pimp accessions. \n\"\"\"\n\nparser = argparse.ArgumentParser(description='Get Jaccard similarity between SLL and a comparison group.')\nparser.add_argument(\"vcf\", metavar=\"\", type=str, help=\"SV vcf file with support vectors. Only one chromosome at a time allowed.\")\nparser.add_argument(\"chr\", metavar=\"\", type=str, help=\"Name of reference chromosome.\")\nparser.add_argument(\"species_file\", metavar=\"\", type=str, help=\"First column is the phylogenetic group (SLC, SP, GAL, CHE, or SLL), second column is the accession\")\nparser.add_argument(\"species\", metavar=\"\", type=str, default=\"SP\", help=\"Group to compare to SLL (SLC, SP, GAL, or CHE)\")\nparser.add_argument(\"fai\", metavar=\"\", type=str, help=\"Fasta index file for the reference genome\")\nparser.add_argument(\"w\", metavar=\"<100000>\", type=int, default=1000000, help=\"Introgression window size.\")\nparser.add_argument(\"-m\", metavar=\"5\", type=int, default=5, help='minimum number of SVs needed to calculate Jaccard')\n\nargs = parser.parse_args()\nvcf_file = args.vcf\nchr_used = args.chr\nfai_file = args.fai\nspecies_file = args.species_file\ncomp_species = args.species\nwindow_size = args.w\nmin_den = args.m\n\nif min_den < 2:\n raise ValueError(\"-m must be at least 2\")\n\n# Get SLL and SP accessions\n# Store in a list so their indices can be used in results matrices\nsll = []\nsp = []\nslc = []\nsg = []\nsc = []\nwith open(species_file, \"r\") as f:\n for line in f:\n species, acc = line.rstrip().split(\"\\t\")\n if species == \"SLL\":\n sll.append(acc)\n elif species == \"SP\":\n sp.append(acc)\n elif species == \"SLC\":\n slc.append(acc)\n elif species == \"GAL\":\n sg.append(acc)\n elif species == \"CHE\":\n sc.append(acc)\n else:\n raise ValueError(\"Illegal species in species file. Can only be SLL, SLC, SP, GAL, or CHE\")\n\n# Associate the list of samples with a species\ncomp_species_dict = {\"SLC\": slc, \"SP\": sp, \"GAL\": sg, \"CHE\": sc}\n\n# Get the chromosome sizes\nchr_lens = dict()\nwith open(fai_file, \"r\") as f:\n for line in f:\n header, length, x, y, z = line.rstrip().split(\"\\t\")\n chr_lens[header] = int(length)\n\n# Iterate through the VCF file and get the distances\n# Assumes only one chromosome at a time\nacc_vec = None\nn_windows = chr_lens[chr_used] // window_size\ndistances = np.zeros((len(sll), n_windows))\ncomp_max_accs = np.zeros((len(sll), n_windows), dtype=np.int32)\ncurrent_window = 0\nsupp_matrix = []\n\nwith open(vcf_file, \"r\") as f:\n for line in f:\n line = line.rstrip()\n if line.startswith(\"#\"):\n if line.startswith(\"#CHROM\"):\n acc_vec = [i.replace(\".ont.s\", \"\") for i in line.split(\"\\t\")[9:]]\n assert set(acc_vec) == set(sll + sp + slc + sg + sc)\n else:\n fields = line.split(\"\\t\")\n tags = fields[7].split(\";\")\n start = int(fields[1])\n widx = start // window_size\n\n # Get the support vector\n supp_vec = None\n for j in tags:\n if j.startswith(\"SUPP_VEC=\"):\n supp_vec = [int(i) for i in j[9:]]\n if supp_vec is None:\n raise ValueError(\"Missing 'SUPP_VEC' field\")\n\n # Build the support matrix for this window or start a new matrix for a new window\n if widx == current_window:\n supp_matrix.append(supp_vec)\n else:\n # We have moved on to the next window. Save the distances for the finished window\n sm = np.asarray(supp_matrix)\n\n # For now, I will calculate the distances in a 'for' loop. Perhaps vectorize in the future\n # Iterate over the SLLs\n t_distances = [[] for i in range(len(sll))]\n for i in range(len(sll)):\n this_acc = sll[i]\n supp_idx = acc_vec.index(this_acc)\n this_vec = sm[:, supp_idx]\n\n # Iterate over the comp species:\n for comp_acc in comp_species_dict[comp_species]:\n comp_supp_idx = acc_vec.index(comp_acc)\n this_comp_vec = sm[:, comp_supp_idx]\n if np.count_nonzero(this_comp_vec) >= min_den and np.count_nonzero(this_vec) >= min_den:\n # Get the Jaccard distance\n num = np.count_nonzero(np.logical_and(this_vec, this_comp_vec)) # Intersection\n den = np.count_nonzero(np.logical_or(this_vec, this_comp_vec)) # Union\n t_distances[i].append(num / den)\n else:\n t_distances[i].append(-1)\n\n # Find which comp sample gave the max\n t_distances_argmax = np.asarray([np.argmax(i) for i in t_distances])\n comp_max_accs[:, current_window] = t_distances_argmax\n # Get the max % shared SVs between a given SLL and each comp species sample\n t_distances = np.asarray([np.max(i) for i in t_distances])\n\n distances[:, current_window] = t_distances\n\n # Now that we have calculated the distances for the finished window, start the next one\n if widx == n_windows:\n break\n current_window = widx\n supp_matrix = []\n supp_matrix.append(supp_vec)\n\n# Write out the comparison species that gave the max\nwith open(\"comp_matrix.\" + comp_species + \".txt\", \"w\") as f:\n f.write(\"Sample\\t\" + \"\\t\".join( [str(i*window_size) for i in range(n_windows)]) + \"\\n\")\n for i in range(len(sll)):\n f.write(sll[i] + \"\\t\" + \"\\t\".join( [comp_species_dict[comp_species][j] for j in list(comp_max_accs[i, :])] ) + \"\\n\")\n\n# Print the output matrix\nprint(\"Sample\\t\" + \"\\t\".join( [str(i*window_size) for i in range(n_windows)] ))\nfor i in range(len(sll)):\n print(sll[i] + \"\\t\" + \"\\t\".join( [str(j) for j in list(distances[i, :])] ).replace(\"-1.0\", \"NA\"))","sub_path":"get_distances.py","file_name":"get_distances.py","file_ext":"py","file_size_in_byte":6525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"504661920","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 30 22:53:00 2018\n\n@author: Phil\nTO Do:\n \n -status updates on conversion\n -add this to batch_convert\n \nLog format:\n time: starting \n time: converting\n moving\n etc\n \n\n\"\"\"\n\n\nimport sys\nimport psutil\nimport time\nimport datetime\n\ndef time_to_log (log_file):\n tstr = str(datetime.datetime.now())\n with open(log_file, \"a+\") as myfile:\n myfile.write(tstr)\n\nprocs = [p for p in psutil.process_iter() if 'python' in p.name() and __file__ in p.cmdline()]\nprint(__file__)\nprint(procs)\n\nlog_file = '/home/phil/work/running_log.txt'\n\nif len(procs) > 1:\n print('Process is already running...')\n tstr = str(datetime.datetime.now())\n msg = 'Attempted launch at ' + tstr + ' and task already running. \\n'\n with open(log_file, \"a+\") as myfile:\n myfile.write(msg)\n\n sys.exit(1)\n\nprint('Process launching')\ntstr = str(datetime.datetime.now())\nmsg = 'Attempted launch at ' + tstr + '... success! \\n'\nwith open(log_file, \"a+\") as myfile:\n myfile.write(msg)\n\nfor i in range(6):\n print('Running...')\n time.sleep(60)\n","sub_path":"pid_demo.py","file_name":"pid_demo.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"647530328","text":"from openerp import models,fields,api\n\nclass Item(models.Model):\n _name = 'sewain.item'\n\n nama = fields.Char(required=True)\n harga = fields.Integer(string=\"Harga sewa per jam\", required=True)\n deskripsi = fields.Text(string=\"Keterangan\")\n peminjaman_ids = fields.One2many(\n 'sewain.peminjaman', 'item_id', string=\"Peminjaman\")\n warna = fields.Integer()","sub_path":"sewain/models/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"237309328","text":"import xxtea,base64,json\nimport urllib.parse\nfrom hashlib import sha1\nfrom hebao_import import input_data\n\"\"\"\t\t\n和包加密步骤\n接口的所有参数 => 排序json => URLEncoder json_str =>sha1 得到 messageSignStr => jsonStr + messageSignStr xxtea =>得到 jsonValue \n请求参数 reqData=jsonValue + clientId => json 请求\n-------------\n和包解密步骤\n获取到 clientId 和 reqData\nreqData xxtea=>解密 => 字符串分隔 => jsonStr + messageSignStr =>验签(jsonStr排序,URLEncoder,sha1) 得到sign => sign 对比 messageSignStr\n\"\"\"\n\n# 读取文本中的值作为参数\npath = './hebao_param.txt'\ndata = input_data()\npythonStr = data.get_data(path)\nprint('字段 %s'%pythonStr)\n\n# 排序\nlist_key = sorted(pythonStr)\n# print(list_key)\n\nlist_value =[]\nfor x in list_key:\n\tlist_value.append(pythonStr[x])\n\t# print(pythonStr[x])\n# print(list_value)\n\nsortStr = dict(zip(list_key,list_value)) \nprint('排序 %s'%sortStr)\n\n\n# 转json\njsonStr = json.dumps(sortStr)\nprint('转json %s'%jsonStr)\n\n\n# URLEncoder编码\ncodes = urllib.parse.quote(jsonStr,'utf-8')\nprint('URLEncoder编码 %s'%codes)\n\n\n# sha1加密\ns1 = sha1()\ns1.update(codes.encode())\nmessageSignStr = s1.hexdigest() # 16位密码,40位字符串\nprint('sha1加密 %s'%messageSignStr)\n\n# 字符串拼接\nmessageSignStr = jsonStr + messageSignStr\nprint('字符串拼接 %s'%messageSignStr)\n\n# xxtea加密\nkey = \"jT1kdbpWtdxQDDr9uC7/E5Hi4RaoFYg1\"\njsonValue = xxtea.encrypt(messageSignStr, key)\njsonValue = base64.b64encode(jsonValue)\njsonValue = bytes.decode(jsonValue)\nprint('xxtea加密 %s'%jsonValue)\nprint(type(jsonValue))\n","sub_path":"数据处理/加密_xxtea/dome3.py","file_name":"dome3.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"580310846","text":"\n\n#calss header\nclass _HAMMOCK():\n\tdef __init__(self,): \n\t\tself.name = \"HAMMOCK\"\n\t\tself.definitions = [u'a type of bed used especially outside, consisting of a net or long piece of strong cloth that you tie between two trees or poles so that it swings (= moves sideways through the air)']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_hammock.py","file_name":"_hammock.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"465408901","text":"from flask import Blueprint, jsonify, request\nfrom models.sasaran import Sasaran\n\nsasaran_blueprint = Blueprint('sasaran_blueprint', __name__)\n\n\n@sasaran_blueprint.route('/sasaran', methods=['GET'])\ndef index():\n message = {\n \"status\": \"success\",\n \"data\": {}\n }\n\n try:\n query_result = Sasaran().find()\n except Exception as error:\n message['status'] = error\n return message\n\n message['data'] = query_result\n return jsonify(message)\n\n\n@sasaran_blueprint.route('/sasaran/', methods=['GET'])\ndef show(id):\n message = {\n \"status\": \"success\",\n \"data\": {}\n }\n\n try:\n query_result = Sasaran().show(id)\n except Exception as error:\n message['status'] = error\n return message\n\n message['data'] = query_result\n return jsonify(message)","sub_path":"controllers/sasaran.py","file_name":"sasaran.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"284566591","text":"# This Python file uses the following encoding: utf-8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom .exceptions import BlockDoesNotExistsException\nfrom .utils import parse_time\nfrom .blockchainobject import BlockchainObject\nfrom beemapi.exceptions import ApiNotSupported\n\n\nclass Block(BlockchainObject):\n \"\"\" Read a single block from the chain\n\n :param int block: block number\n :param beem.steem.Steem steem_instance: Steem\n instance\n :param bool lazy: Use lazy loading\n :param bool only_ops: Includes only operations, when set to True (default: False)\n :param bool only_virtual_ops: Includes only virtual operations (default: False)\n\n Instances of this class are dictionaries that come with additional\n methods (see below) that allow dealing with a block and it's\n corresponding functions.\n\n When only_virtual_ops is set to True, only_ops is always set to True.\n\n Additionally to the block data, the block number is stored as self[\"id\"] or self.identifier.\n\n .. code-block:: python\n\n >>> from beem.block import Block\n >>> block = Block(1)\n >>> print(block)\n \n\n .. note:: This class comes with its own caching function to reduce the\n load on the API server. Instances of this class can be\n refreshed with ``Account.refresh()``.\n\n \"\"\"\n def __init__(\n self,\n block,\n only_ops=False,\n only_virtual_ops=False,\n full=True,\n lazy=False,\n steem_instance=None\n ):\n \"\"\" Initilize a block\n\n :param int block: block number\n :param beem.steem.Steem steem_instance: Steem\n instance\n :param bool lazy: Use lazy loading\n :param bool only_ops: Includes only operations, when set to True (default: False)\n :param bool only_virtual_ops: Includes only virtual operations (default: False)\n\n \"\"\"\n self.full = full\n self.only_ops = only_ops\n self.only_virtual_ops = only_virtual_ops\n super(Block, self).__init__(\n block,\n lazy=lazy,\n full=full,\n steem_instance=steem_instance\n )\n\n def refresh(self):\n \"\"\" Even though blocks never change, you freshly obtain its contents\n from an API with this method\n \"\"\"\n if not isinstance(self.identifier, int):\n self.identifier = int(self.identifier)\n if not self.steem.is_connected():\n return None\n self.steem.rpc.set_next_node_on_empty_reply(False)\n if self.only_ops or self.only_virtual_ops:\n if self.steem.rpc.get_use_appbase():\n try:\n ops = self.steem.rpc.get_ops_in_block({\"block_num\": self.identifier, 'only_virtual': self.only_virtual_ops}, api=\"account_history\")[\"ops\"]\n except ApiNotSupported:\n ops = self.steem.rpc.get_ops_in_block(self.identifier, self.only_virtual_ops)\n else:\n ops = self.steem.rpc.get_ops_in_block(self.identifier, self.only_virtual_ops)\n block = {'block': ops[0][\"block\"],\n 'timestamp': ops[0][\"timestamp\"],\n 'operations': ops}\n else:\n if self.steem.rpc.get_use_appbase():\n block = self.steem.rpc.get_block({\"block_num\": self.identifier}, api=\"block\")\n if block and \"block\" in block:\n block = block[\"block\"]\n else:\n block = self.steem.rpc.get_block(self.identifier)\n if not block:\n raise BlockDoesNotExistsException(str(self.identifier))\n super(Block, self).__init__(block, steem_instance=self.steem)\n\n @property\n def block_num(self):\n \"\"\"Returns the block number\"\"\"\n return self.identifier\n\n def time(self):\n \"\"\"Return a datatime instance for the timestamp of this block\"\"\"\n return parse_time(self['timestamp'])\n\n @property\n def transactions(self):\n \"\"\" Returns all transactions as list\"\"\"\n if self.only_ops or self.only_virtual_ops:\n return list()\n trxs = self[\"transactions\"]\n for i in range(len(trxs)):\n trx = trxs[i]\n trx['transaction_id'] = self['transaction_ids'][i]\n trx['block_num'] = self.block_num\n trx['transaction_num'] = i\n trxs[i] = trx\n return trxs\n\n @property\n def operations(self):\n \"\"\"Returns all block operations as list\"\"\"\n if self.only_ops or self.only_virtual_ops:\n return self[\"operations\"]\n ops = []\n trxs = self[\"transactions\"]\n for tx in trxs:\n for op in tx[\"operations\"]:\n # Replace opid by op name\n # op[0] = getOperationNameForId(op[0])\n ops.append(op)\n return ops\n\n def ops_statistics(self, add_to_ops_stat=None):\n \"\"\"Retuns a statistic with the occurance of the different operation types\"\"\"\n if add_to_ops_stat is None:\n import beembase.operationids\n ops_stat = beembase.operationids.operations.copy()\n for key in ops_stat:\n ops_stat[key] = 0\n else:\n ops_stat = add_to_ops_stat.copy()\n if self.only_ops or self.only_virtual_ops:\n for op in self[\"operations\"]:\n ops_stat[op[\"op\"][0]] += 1\n return ops_stat\n trxs = self[\"transactions\"]\n for tx in trxs:\n for op in tx[\"operations\"]:\n if isinstance(op, dict) and 'type' in op:\n op_type = op[\"type\"]\n if len(op_type) > 10 and op_type[len(op_type) - 10:] == \"_operation\":\n op_type = op_type[:-10]\n ops_stat[op_type] += 1\n else:\n ops_stat[op[0]] += 1\n return ops_stat\n\n\nclass BlockHeader(BlockchainObject):\n def refresh(self):\n \"\"\" Even though blocks never change, you freshly obtain its contents\n from an API with this method\n \"\"\"\n if not self.steem.is_connected():\n return None\n self.steem.rpc.set_next_node_on_empty_reply(False)\n if self.steem.rpc.get_use_appbase():\n block = self.steem.rpc.get_block_header({\"block_num\": self.identifier}, api=\"block\")\n if \"header\" in block:\n block = block[\"header\"]\n else:\n block = self.steem.rpc.get_block_header(self.identifier)\n if not block:\n raise BlockDoesNotExistsException(str(self.identifier))\n super(BlockHeader, self).__init__(\n block,\n steem_instance=self.steem\n )\n\n def time(self):\n \"\"\" Return a datatime instance for the timestamp of this block\n \"\"\"\n return parse_time(self['timestamp'])\n\n @property\n def block_num(self):\n \"\"\"Retuns the block number\"\"\"\n return self.identifier\n","sub_path":"beem/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"231372326","text":"import datetime\n\nfrom bs4 import BeautifulSoup\n\nfrom headlineScraper.models import Headline\nfrom headlineScraper.models import Rank\nfrom headlineScraper.models.revision import HeadlineRevision\nfrom helpers.utilities import format_url_for_site\nfrom scraper.models import NewsSite\nfrom scraper.scraper import Scraper\n\n\nclass HeadlineScraper(Scraper):\n \"\"\"\n Html scraping class.\n Uses BeautifulSoup to scrape certain sites for news headlines.\n \"\"\"\n\n def __init__(self, site: NewsSite):\n \"\"\"\n Constructor\n\n Args:\n site (NewsSite):\n The site to be scraped\n \"\"\"\n\n super(self.__class__, self).__init__(site, site.headlineTemplate)\n self.headlines = []\n self.url = site.url()\n\n def scrape(self):\n \"\"\"\n Extracts values from the html and creates headline object\n \"\"\"\n\n # Should raise exception...\n if not self.parsing_template:\n return None\n\n try:\n response = self.download()\n except:\n return None\n\n soup = BeautifulSoup(response.content, \"html.parser\")\n\n if soup:\n soup = soup.select(self.parsing_template.headline)\n\n if soup is None:\n soup = []\n\n for headline in soup:\n if not headline:\n continue\n\n skip = False\n for exclude in self.parsing_template.exclude:\n if headline.select_one(exclude):\n skip = True\n\n if not skip:\n success = self.parse(headline)\n if success:\n self.headlines.append(success)\n\n # Post processing\n for revision, headline, rank in self.headlines:\n rank.of_total = len(self.headlines)\n return self.headlines\n\n def parse(self, headline: BeautifulSoup):\n \"\"\"\n Extracts values from the html soup and creates headline object\n Args:\n headline (BeautifulSoup4):\n A headline represented as html.\n \"\"\"\n\n title = self.get_title(headline)\n url = self.get_url(headline)\n\n if not title or not url:\n return None\n\n sub_title = self.get_sub_title(headline)\n rank = Rank(placement=len(self.headlines) + 1, of_total=0)\n revision = HeadlineRevision(title=title, sub_title=sub_title, timestamp=datetime.datetime.now())\n head = Headline(news_site=self.news_site, url=url)\n return revision, head, rank\n\n def get_url(self, headline: BeautifulSoup):\n \"\"\"\n Extracts the headline url\n\n Args:\n headline (BeautifulSoup): A Headline object represented as html.\n\n Returns (str): Hopefully the headline url\n\n \"\"\"\n\n url = headline.select_one(self.parsing_template.url)\n if url:\n url = url.get('href')\n if url:\n return format_url_for_site(url, self.news_site.url())\n return url\n\n def get_title(self, headline: BeautifulSoup):\n \"\"\"\n Extracts the headline title\n\n Args:\n headline (BeautifulSoup): A Headline object represented as html.\n\n Returns (str): Hopefully the headline title\n\n \"\"\"\n return self.get_text(headline, self.parsing_template.title)\n\n def get_sub_title(self, headline: BeautifulSoup):\n \"\"\"\n Extracts the headline sub_title\n\n Args:\n headline (BeautifulSoup): A Headline object represented as html.\n\n Returns (str): Hopefully the headline sub_title\n\n \"\"\"\n if self.parsing_template.sub_title:\n return self.get_text(headline, self.parsing_template.sub_title)\n return ''\n","sub_path":"headlineScraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"594633675","text":"class Solution:\n # def jump(self, nums: List[int]) -> int:\n def jump(self, nums) -> int:\n if len(nums) <= 1: return 0\n l, r = 0, nums[0]\n times = 1\n while r < len(nums) - 1:\n times += 1\n nxt = max(i + nums[i] for i in range(l, r + 1))\n l, r = r, nxt\n return times\n\n\"\"\"\nThe idea is to maintain two pointers left and right, where left initialy set to be 0 and right set to be nums[0].\nSo points between 0 and nums[0] are the ones you can reach by using just 1 jump.\nNext, we want to find points I can reach using 2 jumps, so our new left will be set equal to right, and our new right will be set equal to the farest point we can reach by two jumps. which is:\nright = max(i + nums[i] for i in range(left, right + 1)\n\"\"\"","sub_path":"LeetCode/0045_JumpGameII/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"29122888","text":"__author__ = 'garfield'\n\n\nclass Solution:\n # @return a boolean\n def isPalindrome(self, x):\n if x < 0:\n return False\n reverse = 0\n y = x\n while y:\n reverse = reverse * 10 + y % 10\n y /= 10\n return x == reverse","sub_path":"home/issue_9.py","file_name":"issue_9.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"41352480","text":"# -*- coding: utf-8 -*-\n\nimport sys, termios, tty, os, time\nfrom Team import *\nfrom Combattant import *\nfrom Ennemi import *\nfrom Hero import *\nfrom random import *\nfrom CompetenceAttaque import *\nfrom CompetenceHeal import *\nfrom CompetenceStatut import *\nfrom CompetenceBuff import *\nfrom Empoisonne import *\nimport time\n#TODO prendre en compte l'équipement lors du calcul de degat, faire le systeme de loot\nclass Combat():\n def __init__(self, teamHero, teamEnnemi):\n self.__teamHero = teamHero #objet Team\n self.__teamEnnemi = teamEnnemi #objet Team\n self.__teamCombattantsEnnemi = [] #list de Combattants\n self.__teamCombattantsHero = [] #list de Combattants\n self.__creationCombattant()\n self.__definitionOrdrePassage()\n self.__teamHeroMorte = False\n self.__teamEnnemieMorte = False\n self.__fuiteReussi = False\n self.__tour = 1\n\n def lancerCombat(self): #la methode principale qui gere le combat\n print(\"Vous venez de vous faire agresser par : \")\n for ennemi in self.__teamCombattantsEnnemi:\n print(ennemi.getNom() + \" a \" + str(ennemi.getPV()) + \"/\" + str(ennemi.getPVmax()) + \"PV\")\n time.sleep(1.5)\n print(\"******* Tour 1 *******\")\n while (self.__teamHeroMorte == False) and (self.__teamEnnemieMorte == False) and (self.__fuiteReussi == False): #tant que l'une des 2 team n'est pas entierement morte\n if self.__isFinDeTour() == True:\n self.__tour = self.__tour+1\n print(\"******* Tour \"+str(self.__tour)+\" *******\")\n self.__resetTour() #Application des statuts\n nextCombattant = self.__getProchainCombattant()\n self.__tourCombattant(nextCombattant)\n self.__testTeamMorte()\n print(\"\")\n if self.__fuiteReussi == False:\n if self.__teamEnnemieMorte == True:\n print(\"Les ennemies ont été vaincu!!!\")\n self.__finCombat()\n time.sleep(1)\n else:\n print(\"Les heros ont été vaincu...\")\n print(\"Game Over\")\n exit(0)\n \n def __tourCombattant(self, combattant): #le tour d'un des combattants\n if combattant.isHero():\n print(\"C'est à \"+combattant.getNom()+\" d'agir!\")\n self.__choixJoueur(combattant)\n time.sleep(1.5)\n else:\n if combattant.isTeamHero():\n print(\"L'allié \"+combattant.getNom()+ \" attaque l'ennemie!\")\n else:\n print(\"L'ennemie \"+combattant.getNom()+ \" attaque!\")\n self.__choixDeLIA(combattant)\n time.sleep(1.5)\n combattant.setTourFini(True)\n \n def __choixJoueur(self, combattant):\n i=0\n choixPossible = [\"attaquer\", \"defendre\", \"utiliser competence\", \"fuir\", \"info\"]\n maxRange = len(choixPossible)\n\n ok = False #variable pour savoir si l'utilisateur a juste demandé les infos\n while ok==False:\n print(\"Que faire? (utiliser z et s pour choisir et entrée pour selectionner)\")\n ok = True\n rep = \"\"\n while rep != \"0xd\": #différent de entrée\n print(choixPossible[i])\n rep = hex(ord(self.getch())) #on récupère la touche tapé par l'utilisateur (pas besoin de faire entrée)\n if(rep == \"0x7a\"): #z\n if(i0):\n i = i-1\n else:\n i = maxRange - 1\n if (i==0): #le hero attaque\n self.__heroAttaque(combattant)\n if(i==1): #le hero se defend\n print(combattant.getNom()+\" se defend\") #TODO faire le defense\n if(i==2):\n ok = self.__heroUtiliserCompetence(combattant)\n if(i==3):\n self.__fuir(combattant)\n if(i==4):\n for hero in self.__teamCombattantsHero:\n if hero.getPV()==0:\n print(hero.getNom()+\" est décédé...\")\n else: \n print(hero.getNom()+\" a \"+str(hero.getPV())+\"/\"+str(hero.getPVmax())+\"PV, \"+str(hero.getPC())+\"/\"+str(hero.getPCmax())+\"PC, \"+str(hero.getAttaque())+\" attaque, \"+str(hero.getDefense())+\" defense, \"+str(hero.getAgilite())+\" agilité, \",end='')\n if hero.getTourfini():\n print(\"son tour est fini\")\n else:\n print(\"il n'a pas encore fini son tour\")\n print()\n for ennemi in self.__teamCombattantsEnnemi:\n if ennemi.getTourfini():\n print(ennemi.getNom()+\" a \"+str(ennemi.getPV())+\"/\"+str(ennemi.getPVmax())+\"PV, son tour est fini\")\n else:\n print(ennemi.getNom()+\" a \"+str(ennemi.getPV())+\"/\"+str(ennemi.getPVmax())+\"PV, il n'a pas encore fini son tour\")\n ok = False\n print()\n \n \n def __fuir(self, combattant):\n r = randint(1,10)\n if(r<=4):\n print(\"Fuite réussi!\")\n self.__fuiteReussi = True\n else:\n print(\"Les héros essaient de fuir mais les ennemies les rattrapent...\")\n\n def getFuiteReussi(self):\n return self.__fuiteReussi\n\n def __heroUtiliserCompetence(self, combattant):\n if (combattant.getCompetences() == 0):\n print(\"Mais le héro n'a pas de competence...\")\n else:\n print(\"Quelle competence?\")\n i = 0\n\n maxRange = len(combattant.getCompetences())\n rep = \"\"\n\n\n while rep != \"0xd\": #différent de entrée\n print(combattant.getCompetences()[i].getNom())\n rep = hex(ord(self.getch())) #on récupère la touche tapé par l'utilisateur (pas besoin de faire entrée)\n if(rep == \"0x7a\"): #z\n if(i0):\n i = i-1\n else:\n i = maxRange - 1\n if combattant.getPC()0):\n i = i-1\n else:\n i = maxRange - 1\n combattant.attaquer(self.__teamCombattantsEnnemi[i])\n if self.__teamCombattantsEnnemi[i].getPV() == 0:\n self.__teamCombattantsEnnemi.remove(self.__teamCombattantsEnnemi[i])\n\n \n def __choixDeLIA(self, combattant):\n if combattant.isTeamHero():\n teamACombattre = self.__teamCombattantsEnnemi\n saTeam = self.__teamCombattantsHero\n else:\n teamACombattre = self.__teamCombattantsHero\n saTeam = self.__teamCombattantsEnnemi\n for ennemi in teamACombattre:\n if ennemi.getPV()==0:\n teamACombattre.remove(ennemi)\n isAttaque = True\n if(combattant.getCompetences()!=None):\n i = randint(0,1) #si l'IA a une competence, elle a une chance sur deux de l'utiliser\n if(i):\n isAttaque = False\n if(isAttaque):\n i = randint(0,len(teamACombattre)-1)\n combattant.attaquer(teamACombattre[i])\n else:\n print(combattant.getNom()+\" : \"+combattant.getCompetences()[0].getDescription())\n combattant.getCompetences()[0].activerCompetence(combattant, saTeam, teamACombattre, True)\n \n def __resetTour(self):\n for combattant in self.__teamCombattantsHero:\n combattant.setTourFini(False)\n combattant.activerStatut()\n for combattant in self.__teamCombattantsEnnemi:\n combattant.setTourFini(False)\n combattant.activerStatut()\n \n def __isFinDeTour(self):\n finDeTour = True #on part du principe que c'est la fin du tour et on va essayer de prouver le contraire\n for combattant in self.__teamCombattantsHero:\n if combattant.getTourfini() == False:\n finDeTour = False\n for combattant in self.__teamCombattantsEnnemi: #et également pour les ennemies\n if combattant.getTourfini() == False:\n finDeTour = False\n return finDeTour\n \n def __creationCombattant(self):\n for personnage in self.__teamHero.getPersonnages():\n if (isinstance(personnage,Hero)):\n self.__teamCombattantsHero.append(Combattant(personnage, True,True))\n else:\n self.__teamCombattantsHero.append(Combattant(personnage, True,False)) \n for personnage in self.__teamEnnemi.getPersonnages():\n self.__teamCombattantsEnnemi.append(Combattant(personnage, False, False))\n\n def __definitionOrdrePassage(self):\n i = 1 #nb combattant avec un ordre assigné\n n = len(self.__teamCombattantsEnnemi) + len(self.__teamCombattantsHero) #nombre de combattant a assigné\n combattantSelectionne = self.__teamCombattantsEnnemi[0] #on assigne un combattant au hasard \n while i!=n+1:\n initMax = -1 #on va chercher qui a la plus grande initiative parmis les combattant qui n'ont pas encore eu un ordre assigné\n \n for combattant in self.__teamCombattantsHero:\n #print(combattant.getOrdre())\n if ((combattant.getOrdre() == -1) and (combattant.getInitiative() > initMax)):\n combattantSelectionne = combattant\n initMax = combattant.getInitiative()\n for combattant in self.__teamCombattantsEnnemi: #et également pour les ennemies\n if ((combattant.getOrdre() == -1) and (combattant.getInitiative() > initMax)):\n initMax = combattant.getInitiative()\n combattantSelectionne = combattant\n \n combattantSelectionne.setOrdre(i) #on attribut un ordre de passage à ce combattant\n i = i+1\n \n def __getProchainCombattant(self): #le prochain combattant \n nextCombattant = self.__teamCombattantsEnnemi[0]\n ordrePrio = 999\n for combattant in self.__teamCombattantsHero:\n if ((combattant.getOrdre() < ordrePrio) and (combattant.getTourfini() == False) and (combattant.getPV()!=0)):\n nextCombattant = combattant\n ordrePrio = combattant.getOrdre()\n for combattant in self.__teamCombattantsEnnemi:\n if ((combattant.getOrdre() < ordrePrio) and (combattant.getTourfini() == False)):\n nextCombattant = combattant\n ordrePrio = combattant.getOrdre()\n return nextCombattant\n \n def __testTeamMorte(self):\n test = True\n for combattant in self.__teamCombattantsHero:\n if combattant.getPV() != 0:\n test = False\n else:\n if combattant.isHero()==False:\n self.__teamCombattantsHero.remove(combattant)\n if test:\n self.__teamHeroMorte = True\n test = True\n for combattant in self.__teamCombattantsEnnemi:\n if combattant.getPV() != 0:\n test = False\n else:\n self.__teamCombattantsEnnemi.remove(combattant) #les ennemies mort ne restent pas dans les team\n if test:\n self.__teamEnnemieMorte = True\n \n def __finCombat(self):\n for combattant in self.__teamCombattantsHero:\n combattant.getPersonnage().setPV(combattant.getPV())\n combattant.getPersonnage().setPC(combattant.getPC())\n\n for ennemi in self.__teamEnnemi.getPersonnages(): #loot des ennemies\n if (ennemi.getLoot() != None):\n i=0\n for item in ennemi.getLoot():\n k = randint(0,100)\n if(k BATCH_SIZE:\n # print(\"Now Learning\")\n experiences = self.memory.sample()\n self.learn(experiences)\n\n def checkpoint(self):\n '''\n Saves the actor critic network on disk\n '''\n torch.save(self.actor.state_dict(), self.CHECKPOINT_FOLDER + 'checkpoint_actor.pth')\n torch.save(self.critic.state_dict(), self.CHECKPOINT_FOLDER + 'checkpoint_critic.pth')\n\n def load(self):\n '''\n Loads the actor critic network from disk\n '''\n self.actor.load_state_dict(torch.load(self.CHECKPOINT_FOLDER + 'checkpoint_actor.pth'))\n self.actor_target.load_state_dict(torch.load(self.CHECKPOINT_FOLDER + 'checkpoint_actor.pth'))\n self.critic.load_state_dict(torch.load(self.CHECKPOINT_FOLDER + 'checkpoint_critic.pth'))\n self.critic_target.load_state_dict(torch.load(self.CHECKPOINT_FOLDER + 'checkpoint_critic.pth'))\n\n\nclass ReplayBuffer:\n def __init__(self, action_size, buffer_size, batch_size, seed):\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n\n def add(self, state, action, reward, next_state, done):\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n\n def sample(self):\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(\n device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(\n device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n return len(self.memory)\n\nclass OUNoise:\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n\n def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):\n \"\"\"Initialize parameters and noise process.\"\"\"\n self.size = size\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu).\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n \"\"\"Update internal state and return it as a noise sample.\"\"\"\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.random.standard_normal(self.size)\n self.state = x + dx\n return self.state\n","sub_path":"DDPG_Agent.py","file_name":"DDPG_Agent.py","file_ext":"py","file_size_in_byte":6831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"255535016","text":"l, r = map(int, input().split())\nd = (r -l)%2019\nif r -l >=2018:\n print(0)\n exit(0)\nans = 2018\nfor i in range(l, l+d):\n for j in range(i+1, l+d+1):\n if (i*j)%2019 < ans:\n ans =(i*j)%2019\nprint(ans)","sub_path":"Python_codes/p02983/s790952746.py","file_name":"s790952746.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"555879642","text":"import csv\n\n\nSENSITIVE_COLUMNS = [\n \"FirstName\",\n \"Surname\",\n \"EmergencyContactPhone\",\n \"EmergencyContactName\",\n \"SalaryAccountNumber\",\n \"SalarySortCode\",\n \"UnionMembershipNumber\"\n]\n\n\ndef redact_data(data):\n return data\n\n\ndef read_csv(source):\n data = []\n with open(source, newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n data.append(row)\n return data, reader.fieldnames\n\n\ndef write_csv(data, fieldnames, destination):\n with open(destination, 'w', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(data)\n\n\nif __name__ == \"__main__\":\n csv_name_list = ['Employee']\n for csv_name in csv_name_list:\n source = f\"data/{csv_name}.csv\"\n data, fieldnames = read_csv(source)\n data = redact_data()\n destination = f\"data/{csv_name}_dev.csv\"\n write_csv(data, fieldnames, destination)\n","sub_path":"redact_data.py","file_name":"redact_data.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"552208076","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass SurveyData:\n age: int\n weight: int\n constipation: bool\n digestion: bool\n cup_of_water: int\n cold_water: str\n morning: str\n gluttony: bool\n quickly: bool\n menopause: bool\n cold_sensitive: bool\n reply_type: str\n name: str\n tel: str\n email: str\n\n def __init__(self, age: int, weight: int, constipation: bool, digestion: bool, cup_of_water: int, cold_water: str,\n morning: str, gluttony: bool, quickly: bool, menopause: bool, cold_sensitive: bool, reply_type: str,\n name: str, tel: str, email: str):\n self.age = age\n self.weight = weight\n self.constipation = constipation\n self.digestion = digestion\n self.cup_of_water = cup_of_water\n self.cold_water = cold_water\n self.morning = morning\n self.gluttony = gluttony\n self.quickly = quickly\n self.menopause = menopause\n self.cold_sensitive = cold_sensitive\n self.reply_type = reply_type\n self.name = name\n self.tel = tel\n self.email = email\n","sub_path":"goldfnd/services/survey/survey_data.py","file_name":"survey_data.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"242938921","text":"from django.db import models\nfrom django.db import models\nimport datetime\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nimport datetime\n\n\n\n# Create your models here.\n\nclass Utente(models.Model):\n user = models.OneToOneField(User, unique=True)\n fbID = models.CharField(max_length=500,default=\"FACEBOOK UID\", unique=True)\n idCell = models.CharField(max_length=500,default=\"CELL UID\", unique=True)\n linkFoto = models.CharField(max_length=200, default=\"link foto Utente\")\n #compleanno = models.DateField(default=None,blank=True, null=True)\n presenze = models.IntegerField(default=\"0\")\n\n\n def __unicode__(self): # Python 3: def __str__(self):\n return self.user.first_name\n\nclass Evento(models.Model):\n titoloSerata = models.CharField(max_length=200, default =\"TitoloSerata\")\n artisti = models.CharField(max_length=300, default=\"Nomi Artisti\")\n data = models.DateField(\"Data Evento\", unique=True)\n ora = models.TimeField(\"Ora Evento\")\n descr = models.TextField(default=\"Descrizione Evento\")\n listaBool = models.IntegerField(default=\"0\")\n userInLista = models.ManyToManyField(User, blank=True, serialize=False)\n prevenditeBool = models.IntegerField(default=\"0\")\n prezzoLista = models.IntegerField(default=\"0\")\n prezzoIntero = models.IntegerField(default=\"0\")\n prezzoDopo = models.IntegerField(default=\"0\")\n linkLocandina = models.CharField(max_length=500, default =\"LinkLocandina\")\n linkFoto = models.CharField(max_length=500, default =\"LinkFoto\")\n linkVideo = models.CharField(max_length=500, default =\"LinkVideo\")\n linkFBEvent = models.CharField(max_length=500, default =\"LinkFBEvent\")\n editTime = models.DateTimeField(default = datetime.datetime.now())\n linkFoto = models.ImageField(upload_to=\"images/\", blank=True, null=True)\n ueID = models.IntegerField(default=0)\n\n def save(self):\n self.ueID +=1\n super(Evento, self).save()\n\n def __unicode__(self): # Python 3: def __str__(self):\n return self.titoloSerata\n\n\"\"\"\nclass Devices(models.Model):\n user = models.ForeignKey(User)\n device = models.CharField(max_length=500)\n\n def __unicode__(self):\n return self.user.first_name\n\"\"\"\n","sub_path":"urbanserver/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"583726955","text":"# Copyright 2021 Katteli Inc.\n# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# to the end flag\nfrom concurrent.futures import Future as _FutureBase\n\n\nclass Future(_FutureBase):\n \"\"\"concurrent.futures.Future that\n fixes __get_result() when exception\n implements its own custom __bool__()\n \"\"\"\n\n def __get_result(self):\n if self._exception is not None:\n try:\n raise self._exception\n finally:\n # Break a reference cycle with the exception in self._exception\n self = None\n else:\n return self._result\n","sub_path":"testflows/_core/parallel/executor/future.py","file_name":"future.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"392562922","text":"__version__ = '0.5'\n__author__ = 'Tehseen Sajjad'\n\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\n\n# Some helpers and constant variables\nPARENT_H2_TEXT = 'Physical description'\nMAIN_PAGE = 'https://lotr.fandom.com'\nCHARS_PAGE_SUFFIX = 'wiki/Category:The_Silmarillion_Characters'\nCHARS_LINK_TAG_CLASS = 'category-page__member-link'\nRACE_PROPERTY_TEXT = 'Race'\nRACE_PROPERTY_TAG = 'pi-data-label pi-secondary-font'\nDATA_DUMP_FILENAME = 'Character_Races'\nNO_SIDEBAR_ENTRY = 'No Sidebar'\nTIME_FORMAT_STRING = '%a%d%b%Y%I%M'\nUNICODE_CHECKMARK = '✅'\nUNICODE_CROSS = '❎'\n\ntimestamp = datetime.now().strftime(TIME_FORMAT_STRING)\nlogfilename = f\"{timestamp}.txt\"\n\n\ndef log(type, msg):\n \"\"\"\n prints and saves log message of shape:\n [type] - msg\n \"\"\"\n logString = f\"[{type}] - {msg}\"\n print(logString)\n with open(logfilename, 'a') as logfile:\n logfile.write(logString + '\\n')\n\n\ndef has_race_property(soupPage):\n \"\"\"\n Checks if soupPage has the race property\n \"\"\"\n hasRaceProperty = bool(soupPage.find('h3', class_=RACE_PROPERTY_TAG, text=RACE_PROPERTY_TEXT))\n return hasRaceProperty\n\n\ndef get_race_from_sidebar(soup):\n race = None\n adjacent_h2 = soup.find('h2', text=PARENT_H2_TEXT)\n race = adjacent_h2.find_next('a').text\n return race\n\nif __name__ == '__main__':\n char_name_to_link_map = dict()\n character_tag_list = list()\n\n response = requests.get(f'{MAIN_PAGE}/{CHARS_PAGE_SUFFIX}')\n page = BeautifulSoup(response.content, 'lxml')\n\n # [a, a, a, a, a]\n character_tag_list = page.findAll('a', class_=CHARS_LINK_TAG_CLASS)\n for atag in character_tag_list:\n name = atag['title']\n relative_link = atag['href']\n link = f\"{MAIN_PAGE}{relative_link}\"\n char_name_to_link_map[name] = link\n \n # making a DataFrame\n\n names_list = list(char_name_to_link_map.keys())\n races_list = list()\n for name, link in char_name_to_link_map.items():\n res = requests.get(link)\n character_page = BeautifulSoup(res.content, 'lxml')\n if has_race_property(character_page):\n race = get_race_from_sidebar(character_page)\n log(UNICODE_CHECKMARK, f\"{link}:\\t{res.status_code} GOT RACE {race}\")\n else:\n race = NO_SIDEBAR_ENTRY\n log(UNICODE_CROSS, f\"{link} HAS NO SIDEBAR WITH RACE PROPERTY\")\n races_list.append(race)\n\n\n data_dict = {\n 'Name' : names_list,\n 'Race' : races_list\n }\n df = pd.DataFrame(data=data_dict)\n log(UNICODE_CHECKMARK, 'DATA SAVED TO PANDAS DATAFRAME')\n # Save the dataframe object in a pickle\n df.to_pickle(DATA_DUMP_FILENAME+'.pkl')\n log(UNICODE_CHECKMARK, f'DATA PICKLED TO {DATA_DUMP_FILENAME}.pkl')\n # Save to a csv\n df.to_csv(DATA_DUMP_FILENAME+'.csv', index=False)\n log(UNICODE_CHECKMARK, f'DATA SAVED TO {DATA_DUMP_FILENAME}.csv')","sub_path":"synchronous_run.py","file_name":"synchronous_run.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"328413713","text":"# filedetails.py\n# \n# Copyright 2015 Wangolo Joel \n# \n# This program 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 2 of the License, or\n# (at your option) any later version.\n# \n# This program 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 this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n'''\n\n\n\n\n\n\n'''\nfrom django import template\nfrom django.forms import Select, ModelChoiceField\nregister = template.Library()\nfrom django.template.defaultfilters import stringfilter\nfrom django.template.defaultfilters import filesizeformat\nimport datetime \nfrom dateutil import parser\nimport uuid\nimport textwrap\n\"\"\"\n({'content-length': '175', 'x-container-object-count': '1', 'accept-ranges': 'bytes', 'x-storage-policy': 'Policy-0', 'date': 'Tue, 08 Sep 2015 08:10:04 GMT', 'x-timestamp': '1441462269.02896', 'x-trans-id': 'tx2f5e2992b9a1468d84ce9-0055ee97da', 'x-container-bytes-used': '0', 'content-type': 'application/json; charset=utf-8'},\n[{u'bytes': 0, u'last_modified': u'2015-09-08T08:04:27.024320', \nu'hash': u'd41d8cd98f00b204e9800998ecf8427e', \nu'name': u'/home/wangolo/Music/Burn.mp3', u'content_type': u'audio/mpeg'}])\n\"\"\"\n\nGLOBAL_FORMAT = \"%Y/%m/%d\"\n\n@register.filter(name=\"format_comment\")\ndef format_comment(content):\n \"\"\"\n Detects if it has newline.\n \"\"\"\n try:\n if(content.startswith(\"#\")):\n return \"format-py format-bash format-ruby format-perl\"\n else:\n return \"format-text\"\n \n except:\n raise\n \n@register.filter(name=\"has_strings_quotations\")\ndef has_strings_quotations(content):\n try:\n if('\"' in content):\n return \"format-string-quotations\"\n elif(\"'\" in content):\n return \"format-string-quotations\"\n else:\n return \"format-false\"\n except:\n raise \n\n@register.filter(name=\"has_language_import\")\ndef has_language_import(content):\n if(\"import\" in content):\n return content.replace(\"import\", 'import', len(content))\n else:\n return content \n \n@register.filter(name=\"has_language_from\")\ndef has_language_from(content):\n if(\"from\" in content):\n return content.replace(\"from\", 'from', len(content))\n else:\n return content \n \n@register.filter(name=\"has_language_def\")\ndef has_language_def(content):\n if(\"def\" in content):\n return content.replace(\"def\", 'def', len(content))\n else:\n return content \n \n@register.filter(name=\"has_language_class\")\ndef has_language_class(content):\n if(\"class\" in content):\n return content.replace(\"class\", 'class', len(content))\n else:\n return content \n \n@register.filter(name=\"has_language_self\")\ndef has_language_self(content):\n if(\"self\" in content):\n return content.replace(\"self\", 'self', len(content))\n else:\n return content \n \n@register.filter(name=\"get_uuid\")\ndef get_uuid(content):\n name = content.get(\"name\")\n name = name.encode(\"ascii\", \"ignore\").decode(\"ascii\")\n ID = uuid.uuid3(uuid.NAMESPACE_URL, str(name) + \"d41d8cd98f00b204e9800998ecf8427e\")\n return \"x_object_get/%s\" % ID\n \n \n@register.filter(name=\"get_uuid_url\")\ndef get_uuid_url(content):\n name = content.get(\"name\")\n name = name.encode(\"ascii\", \"ignore\").decode(\"ascii\")\n ID = uuid.uuid3(uuid.NAMESPACE_URL, str(name) + \"d41d8cd98f00b204e9800998ecf8427e\")\n return \"%s\" % ID\n \n \n@register.filter(name=\"get_share_link\")\ndef get_share_link(content):\n parsed_link = content.replace(\"get\", \"share\", 1)\n return parsed_link\n \n@register.filter(name=\"get_delete_link\")\ndef get_delete_link(content):\n parsed_link = content.replace(\"get\", \"delete\", 1)\n return parsed_link\n \n@register.filter(name=\"get_trash_link\")\ndef get_trash_link(content):\n parsed_link = content.replace(\"get\", \"trash\", 1)\n return parsed_link\n \n@register.filter(name=\"get_preview_link\")\ndef get_preview_link(content):\n parsed_link = content.replace(\"get\", \"preview\", 1)\n return parsed_link\n \n@register.filter(name=\"downloadurl\")\ndef downloadurl(content):\n \"\"\"\n Generate a url for downloading this\n file.\n \"\"\"\n try:\n hashs = content.get(\"hash\")\n name = content.get(\"name\")\n \n #unique_identifier = uuid.uuid3(uuid.NAMESPACE_URL, name)\n #print \"NAME \", name, \"HASH \", hashs, \"UNIQUE \", hashs\n get = \"%s/?x_object_name=%s\" % (hashs, name)\n return get \n except:\n raise \n \n@register.filter(name=\"downloadurl_shared\")\ndef downloadurl_shared(content):\n \"\"\"\n Generate a url for downloading this\n file.\n \"\"\"\n try:\n name = content.get(\"name\")\n get = \"?x_object_name=%s\" % name\n return get \n except:\n raise \n \n@register.filter(name=\"data_id\")\ndef data_id(content):\n return content.get(\"hash\")\n \n@register.filter(name=\"detected_actiontype\")\ndef detected_actiontype(content):\n \"\"\"\n Attempt to detect the file type and then perform appropriate action.\n \"\"\"\n try:\n name = content.get(\"name\")\n if(name.endswith(\".mp3\")):\n return \"Play\"\n elif(name.endswith(\".mp4\")):\n return \"Play\"\n elif(name.endswith(\".txt\")):\n return \"Open\"\n elif(name.endswith(\".py\")):\n return \"Open\"\n elif(name.endswith(\".png\")):\n return \"Slide show\"\n else:\n return \"Preview\"\n except:\n raise \n \n@register.filter(name=\"detected_icontype\")\ndef detected_icontype(content):\n \"\"\"\n Attempt to detect the file type and then perform appropriate action.\n \"\"\"\n try:\n name = content.get(\"name\")\n if(name.endswith(\".mp3\")):\n return \"fi-play\"\n elif(name.endswith(\".mp4\")):\n return \"fi-play-video\"\n elif(name.endswith(\".txt\")):\n return \"fi-text-color\"\n elif(name.endswith(\".py\")):\n return \"fi-text-color\"\n elif(name.endswith(\".png\")):\n return \"fi-photo\"\n elif(name.endswith(\".csv\")):\n #return \"fa fa-slideshare\"\n return \"fi-page-csv\"\n else:\n return \"fi-results\"\n except:\n raise \n \n@register.filter(name=\"choose_icon\")\ndef choose_icon(content):\n try:\n name = content.get(\"name\")\n if(name.endswith(\".mp3\")):\n return \"fi-music\"\n elif(name.endswith(\".txt\")):\n return \"fa fa-file-text\"\n elif(name.endswith(\".mp4\")):\n return \"fa fa-file-video-o\"\n elif(name.endswith(\".py\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".pdf\")):\n return \"fa fa-file-pdf-o\"\n elif(name.endswith(\".zip\")):\n return \"fa fa-file-archive-o\"\n \n elif(name.endswith(\".csv\")):\n return \"fi-page-csv\"\n elif(name.endswith(\".png\")):\n return \"fa fa-file-image-o\"\n elif(name.endswith(\".jpg\")):\n return \"fa fa-file-image-o\"\n elif(name.endswith(\".jpeg\")):\n return \"fa fa-file-image-o\"\n elif(name.endswith(\".msi\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".exe\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".deb\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".iso\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".gz\")):\n return \"fi-archive\"\n \n else:\n return \"fa fa-file\"\n except:\n raise \n \n@register.filter(name=\"shared_choose_icon\")\ndef shared_choose_icon(name):\n try:\n if(name.endswith(\".mp3\")):\n return \"fi-music\"\n elif(name.endswith(\".txt\")):\n return \"fa fa-file-text\"\n elif(name.endswith(\".mp4\")):\n return \"fa fa-file-video-o\"\n elif(name.endswith(\".py\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".pdf\")):\n return \"fa fa-file-pdf-o\"\n elif(name.endswith(\".zip\")):\n return \"fa fa-file-archive-o\"\n \n elif(name.endswith(\".csv\")):\n return \"fi-page-csv\"\n elif(name.endswith(\".png\")):\n return \"fa fa-file-image-o\"\n elif(name.endswith(\".jpg\")):\n return \"fa fa-file-image-o\"\n elif(name.endswith(\".jpeg\")):\n return \"fa fa-file-image-o\"\n elif(name.endswith(\".msi\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".exe\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".deb\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".iso\")):\n return \"fa fa-file-code-o\"\n elif(name.endswith(\".gz\")):\n return \"fi-archive\"\n \n else:\n return \"fa fa-file\"\n except:\n raise \n \n@register.filter(name=\"filename\")\ndef filename(content):\n \"\"\"\n Filter returns the name of the file.\n \"\"\"\n try:\n return content.get(\"name\")\n except:\n raise \n\n@register.filter(name=\"last_modified\")\ndef last_modified(content):\n \"\"\"\n Parses and returns the loast modified date.\n \"\"\"\n try:\n date = content.get(\"last_modified\")\n parse_date = parser.parse(date)\n return parse_date.strftime(GLOBAL_FORMAT)\n except:\n raise \n#return filesizeformat(int(folder_info.get(\"x-container-bytes-used\")))\n\n@register.filter(name=\"bytes\")\ndef bytes(content):\n \"\"\"\n filter returns the bytes of the content.\n \"\"\"\n try:\n size = content.get(\"bytes\")\n if(size is not None):\n return filesizeformat(size)\n except:\n raise \n\n@register.filter(name=\"dialog_open_action\")\ndef dialog_open_action(content):\n name = content.get(\"name\")\n if(name.endswith(\".txt\")):\n return \"TextOpen\"\n else:\n return \"UnknownAction\"\n\n\n@register.filter(name=\"guess_action_url\")\ndef guess_action_url(content):\n name = content.get(\"name\")\n if(name.endswith(\".txt\")):\n return \"x_object_previewfile\"\n else:\n return \"x_object_previewfile\"\n\n\n@register.filter(name=\"detect_folder_action\")\ndef detect_folder_action(content):\n \"\"\"\n \"\"\"\n if(content == \"Pictures\"):\n return \"Begin slide show\"\n elif(content == \"Trash\"):\n return \"Empty Trash\"\n elif(content == \"Music\"):\n return \"Play Odio\"\n elif(content == \"Music\"):\n return \"Play Videos\"\n else:\n return \" Share\" \n \n@register.filter(name=\"detect_folder_action_url\")\ndef detect_folder_action_url(content):\n \"\"\"\n \"\"\"\n pass \n \n@register.filter(name=\"get_folder_icon\")\ndef get_folder_icon(content):\n \"\"\"\n \"\"\"\n pass \n\n@register.filter(name=\"detect_folder\")\ndef detect_folder(name):\n \"\"\"\n Attempt to detect the file type and then perform appropriate action.\n \"\"\"\n try:\n if(name == \"Music\"):\n return \"fa fa-music\"\n elif(name == \"Videos\"):\n return \"fi-play-video\"\n elif(name == \"Documents\"):\n return \"fi-page-doc\"\n elif(name == \"Trash\"):\n return \"fa fa-trash\"\n elif(name ==\"Downloads\"):\n return \"fi-download\"\n elif(name ==\"Pictures\"):\n return \"fi-photo\"\n elif(name ==\"Shared\"):\n return \"fi-share\"\n \n elif(name ==\"Uploads\"):\n return \"fa fa-history\"\n else:\n return \"fi-folder\"\n except:\n raise \n\n\n@register.filter(name=\"make_unsharelink\")\ndef make_unsharelink(url):\n \"\"\"\n Unshare.\n \"\"\"\n try:\n if(url):\n return url.replace(\"sharemydrive\", \"sharemydrive/endshared\", 1)\n else:\n return url \n except:\n raise \n \n\n@register.filter(name=\"file_isshared\")\ndef file_isshared(content):\n \"\"\"\n \"\"\"\n try:\n pass\n except:\n pass \n","sub_path":"Public/devs/s8website/drivedashboard/templatetags/filedetails.py","file_name":"filedetails.py","file_ext":"py","file_size_in_byte":12764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"14570728","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.utils.safestring import mark_safe\nfrom django.views.generic.base import RedirectView\n\nfrom rest_framework_extensions.routers import ExtendedDefaultRouter\nfrom rest_framework_swagger.views import get_swagger_view\n\nfrom apps.landing.views import LandingView\nfrom apps.accounts.views import UserViewSet, VerifyChangeEmail, CustomRegisterView\nfrom apps.billings.api.views import (\n BillingTypeViewSet,\n BilledActivityViewSet,\n OrganizationBilledActivity,\n)\nfrom apps.core.api.views import (\n OrganizationViewSet, FacilityViewSet, EmployeeProfileViewSet,\n ProviderTitleViewSet, ProviderRoleViewSet, ProviderSpecialtyViewSet,\n DiagnosisViewSet, MedicationViewSet, ProcedureViewSet, SymptomViewSet,\n OrganizationEmployeeViewSet, SymptomSearchViewSet, FacilityEmployeeViewSet,\n OrganizationFacilityViewSet, DiagnosisSearchViewSet, OrganizationInsuranceViewSet,\n ProviderTitleSearchViewSet, ProviderRoleSearchViewSet, NotificationViewSet,\n OrganizationAffiliatesViewSet, BillingCoordinatorViewSet,\n OrganizationBillingPractitionerViewSet, EmployeeRoleViewSet,)\nfrom apps.patients.api.views import (\n PatientProfileViewSet,\n PatientDiagnosisViewSet,\n ProblemAreaViewSet,\n PatientStatViewSet,\n PatientProcedureViewSet,\n PatientMedicationViewSet,\n PatientProfileSearchViewSet,\n PotentialPatientViewSet,\n FacilityPatientViewSet,\n EmergencyContactViewSet,\n ProspectivePatientViewSet,\n)\nfrom apps.plans.api.views import (\n ServiceAreaViewSet,\n CarePlanTemplateViewSet,\n CarePlanViewSet,\n PlanConsentViewSet,\n CareTeamMemberViewSet,\n GoalTemplateViewSet,\n GoalViewSet,\n GoalProgressViewSet,\n GoalCommentViewSet,\n InfoMessageQueueViewSet,\n InfoMessageViewSet,\n ManagerTaskTemplateByCarePlanTemplate,\n CareTeamTaskTemplateByCarePlanTemplate,\n ManagerTemplateByCarePlanTemplate,\n CareTeamTemplateByCarePlanTemplate,\n PatientByCarePlanTemplate,\n PatientTaskTemplateByCarePlanTemplate,\n AssessmentTaskTemplateByCarePlanTemplate,\n SymptomTaskTemplateByCarePlanTemplate,\n VitalTaskTemplateByCarePlanTemplate,\n TeamTaskTemplateByCarePlanTemplate,\n InfoMessageQueueByCarePlanTemplate,\n CarePlanByFacility,\n PatientCarePlanOverview,\n MessageRecipientViewSet,\n TeamMessageViewSet,\n AssessmentResultViewSet,\n SymptomByPlanViewSet,\n VitalByPlanViewSet,\n)\nfrom apps.tasks.api.views import (\n CarePlanAssessmentTemplateViewSet,\n CarePlanPatientTemplateViewSet,\n CarePlanSymptomTemplateViewSet,\n CarePlanTeamTemplateViewSet,\n CarePlanVitalTemplateViewSet,\n PatientTaskTemplateViewSet,\n PatientTaskViewSet,\n TeamTaskTemplateViewSet,\n TeamTaskViewSet,\n MedicationTaskTemplateViewSet,\n MedicationTaskViewSet,\n SymptomTaskTemplateViewSet,\n SymptomTaskViewSet,\n SymptomRatingViewSet,\n AssessmentTaskTemplateViewSet,\n AssessmentQuestionViewSet,\n AssessmentTaskViewSet,\n AssessmentResponseViewSet,\n VitalTaskTemplateViewSet,\n VitalTaskTemplateSearchViewSet,\n VitalTaskViewSet,\n VitalQuestionViewSet,\n VitalResponseViewSet,\n TodaysTasksAPIView,\n)\nfrom apps.accounts.views import ObtainAuthToken, \\\n RequestPasswordChange, ResetPassword, ValidateUserView\n\nadmin.site.site_title = admin.site.index_title = \"CareAdopt Backend\"\nadmin.site.site_header = mark_safe('\"{alt}\"/ {alt}'.format(\n img=settings.STATIC_URL + 'favicon.ico',\n alt=admin.site.site_title,\n))\n\nrouter = ExtendedDefaultRouter()\n# Accounts\nuser_routes = router.register(r'users', UserViewSet, base_name='users')\nuser_routes.register(\n r'notifications',\n NotificationViewSet,\n base_name='notifications',\n parents_query_lookups=['user']\n)\nrouter.register(r'employee_roles', EmployeeRoleViewSet, base_name='employee_roles')\n\n# Billings\nrouter.register(\n r'billed_activities',\n BilledActivityViewSet,\n base_name='billed_activities'\n)\n\nrouter.register(\n r'billing_coordinators',\n BillingCoordinatorViewSet,\n base_name='billing_coordinators'\n)\n\n# Core\n\norganization_routes = router.register(\n r'organizations',\n OrganizationViewSet,\n base_name='organizations'\n)\norganization_routes.register(\n r'billed_activities',\n OrganizationBilledActivity,\n base_name='organization-billed-activities',\n parents_query_lookups=['plan__patient__facility__organization']\n)\norganization_routes.register(\n r'employee_profiles',\n OrganizationEmployeeViewSet,\n base_name='organization-employees',\n parents_query_lookups=['organizations']\n)\norganization_routes.register(\n r'billing_practitioners',\n OrganizationBillingPractitionerViewSet,\n base_name='organization-billing-practitioners',\n parents_query_lookups=['organizations']\n)\norganization_routes.register(\n r'facilities',\n OrganizationFacilityViewSet,\n base_name='organization-facilities',\n parents_query_lookups=['organization']\n)\norganization_routes.register(\n r'insurances',\n OrganizationInsuranceViewSet,\n base_name='organization-insurances',\n parents_query_lookups=['organization']\n)\norganization_routes.register(\n r'affiliates',\n OrganizationAffiliatesViewSet,\n base_name='organization-affiliates',\n parents_query_lookups=['organization']\n)\n\nfacility_routes = router.register(\n r'facilities',\n FacilityViewSet,\n base_name='facilities'\n)\nfacility_routes.register(\n r'employee_profiles',\n FacilityEmployeeViewSet,\n base_name='facility-employees',\n parents_query_lookups=['facilities']\n)\nfacility_routes.register(\n r'patients',\n FacilityPatientViewSet,\n base_name='facility-patients',\n parents_query_lookups=['facility']\n)\nfacility_routes.register(\n r'care_plans',\n CarePlanByFacility,\n base_name='facility-care-plans',\n parents_query_lookups=['patient__facility']\n)\n\nrouter.register(\n r'employee_profiles', EmployeeProfileViewSet, base_name='employee_profiles')\nrouter.register(\n r'provider_titles/search',\n ProviderTitleSearchViewSet,\n base_name=\"provider_titles-search\"\n)\nrouter.register(r'provider_titles', ProviderTitleViewSet, base_name='provider_titles')\nrouter.register(\n r'provider_roles/search',\n ProviderRoleSearchViewSet,\n base_name=\"provider_roles-search\"\n)\nrouter.register(r'provider_roles', ProviderRoleViewSet, base_name='provider_roles')\nrouter.register(\n r'provider_specialties', ProviderSpecialtyViewSet, base_name='provider_specialties')\nrouter.register(\n r'diagnosis/search',\n DiagnosisSearchViewSet,\n base_name=\"diagnosis-search\"\n)\nrouter.register(r'diagnosis', DiagnosisViewSet, base_name='diagnosis')\nrouter.register(r'medications', MedicationViewSet, base_name='medications')\nrouter.register(r'procedures', ProcedureViewSet, base_name='procedures')\nrouter.register(\n r'symptoms/search',\n SymptomSearchViewSet,\n base_name=\"symptom-search\"\n)\nrouter.register(r'symptoms', SymptomViewSet, base_name='symptoms')\n# Patients\nrouter.register(\n r'patient_profiles/search',\n PatientProfileSearchViewSet,\n base_name='patient_profiles_search',\n)\n\npatient_routes = router.register(\n r'patient_profiles', PatientProfileViewSet, base_name='patient_profiles')\npatient_routes.register(\n r'care_plan_overview',\n PatientCarePlanOverview,\n base_name='patient-care-plan-overview',\n parents_query_lookups=['patient']\n)\npatient_routes.register(\n r'emergency_contacts',\n EmergencyContactViewSet,\n base_name='patient-emergency-contacts',\n parents_query_lookups=['patient']\n)\n\nrouter.register(r'problem_areas', ProblemAreaViewSet, base_name='problem_areas')\nrouter.register(r'prospective_patients', ProspectivePatientViewSet, base_name='prospective_patients')\n\nrouter.register(\n r'patient_diagnosis', PatientDiagnosisViewSet, base_name='patient_diagnosis')\nrouter.register(\n r'patient_stats', PatientStatViewSet, base_name='patient_stats')\nrouter.register(\n r'patient_procedures', PatientProcedureViewSet, base_name='patient_procedures')\nrouter.register(\n r'patient_medications', PatientMedicationViewSet, base_name='patient_medications')\n# Plans\nrouter.register(\n r'billing_types',\n BillingTypeViewSet,\n base_name='billing_types')\nrouter.register(\n r'service_areas',\n ServiceAreaViewSet,\n base_name='service_areas')\nrouter.register(\n r'care_plan_templates', CarePlanTemplateViewSet, base_name='care_plan_templates')\ncare_plan_template_routes = router.register(\n r'care_plan_templates',\n CarePlanTemplateViewSet,\n base_name='care_plan_templates'\n)\ncare_plan_template_routes.register(\n r'manager_task_templates',\n ManagerTaskTemplateByCarePlanTemplate,\n base_name='manager-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'care_team_task_templates',\n CareTeamTaskTemplateByCarePlanTemplate,\n base_name='care-team-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'manager_templates',\n ManagerTemplateByCarePlanTemplate,\n base_name='manager-templates-by-care-plan-templates',\n parents_query_lookups=['plan__plan_template']\n)\ncare_plan_template_routes.register(\n r'care_team_templates',\n CareTeamTemplateByCarePlanTemplate,\n base_name='care-team-templates-by-care-plan-templates',\n parents_query_lookups=['plan__plan_template']\n)\ncare_plan_template_routes.register(\n r'info_message_queues',\n InfoMessageQueueByCarePlanTemplate,\n base_name='info-message-queues-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'patients',\n PatientByCarePlanTemplate,\n base_name='patients-by-care-plan-templates',\n parents_query_lookups=['care_plans__plan_template']\n)\ncare_plan_template_routes.register(\n r'patient_task_templates',\n PatientTaskTemplateByCarePlanTemplate,\n base_name='patient-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'assessment_task_templates',\n AssessmentTaskTemplateByCarePlanTemplate,\n base_name='assessment-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'symptom_task_templates',\n SymptomTaskTemplateByCarePlanTemplate,\n base_name='symptom-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'team_task_templates',\n TeamTaskTemplateByCarePlanTemplate,\n base_name='team-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_template_routes.register(\n r'vital_task_templates',\n VitalTaskTemplateByCarePlanTemplate,\n base_name='vital-task-templates-by-care-plan-templates',\n parents_query_lookups=['plan_template']\n)\ncare_plan_routes = router.register(\n r'care_plans', CarePlanViewSet, base_name='care_plans')\ncare_plan_routes.register(\n r'assessment_results',\n AssessmentResultViewSet,\n base_name='assessment_results',\n parents_query_lookups=['plan'])\ncare_plan_routes.register(\n r'symptoms',\n SymptomByPlanViewSet,\n base_name='plan_symptoms',\n parents_query_lookups=['plan'])\ncare_plan_routes.register(\n r'vitals',\n VitalByPlanViewSet,\n base_name='vitals',\n parents_query_lookups=['plan'])\nmessage_recipient_routes = care_plan_routes.register(\n r'message_recipients',\n MessageRecipientViewSet,\n base_name='message_recipients',\n parents_query_lookups=['plan'])\nmessage_recipient_routes.register(\n r'team_messages',\n TeamMessageViewSet,\n base_name='team_messages',\n parents_query_lookups=['recipients__plan', 'recipients'])\nrouter.register(\n r'plan_consent_forms', PlanConsentViewSet, base_name='plan_consent_forms')\nrouter.register(\n r'care_team_members', CareTeamMemberViewSet, base_name='care_team_members')\nrouter.register(\n r'goal_templates', GoalTemplateViewSet, base_name='goal_templates')\nrouter.register(\n r'goals', GoalViewSet, base_name='goals')\nrouter.register(\n r'goal_progresses', GoalProgressViewSet, base_name='goal_progresses')\nrouter.register(\n r'goal_comments', GoalCommentViewSet, base_name='goal_comments')\nrouter.register(\n r'info_message_queues', InfoMessageQueueViewSet, base_name='info_message_queues')\nrouter.register(\n r'info_messages', InfoMessageViewSet, base_name='info_messages')\nrouter.register(\n r'potential_patients',\n PotentialPatientViewSet,\n base_name='potential_patients')\n\n# Tasks\nrouter.register(\n r'plan_patient_templates',\n CarePlanPatientTemplateViewSet,\n base_name='plan_patient_templates')\nrouter.register(\n r'patient_task_templates',\n PatientTaskTemplateViewSet,\n base_name='patient_task_templates')\nrouter.register(r'patient_tasks', PatientTaskViewSet, base_name='patient_tasks')\nrouter.register(\n r'team_task_templates',\n TeamTaskTemplateViewSet,\n base_name='team_task_templates')\nrouter.register(\n r'plan_team_templates',\n CarePlanTeamTemplateViewSet,\n base_name='plan_team_templates')\nrouter.register(\n r'team_tasks', TeamTaskViewSet, base_name='team_tasks')\nrouter.register(\n r'medication_task_templates',\n MedicationTaskTemplateViewSet,\n base_name='medication_task_templates')\nrouter.register(\n r'medication_tasks', MedicationTaskViewSet, base_name='medication_tasks')\nrouter.register(\n r'symptom_task_templates',\n SymptomTaskTemplateViewSet,\n base_name='symptom_task_templates')\nrouter.register(\n r'plan_symptom_templates',\n CarePlanSymptomTemplateViewSet,\n base_name='plan_symptom_templates')\nrouter.register(r'symptom_tasks', SymptomTaskViewSet, base_name='symptom_tasks')\nrouter.register(r'symptom_ratings', SymptomRatingViewSet, base_name='symptom_ratings')\nrouter.register(\n r'assessment_task_templates',\n AssessmentTaskTemplateViewSet,\n base_name='assessment_task_templates')\nrouter.register(\n r'plan_assessment_templates',\n CarePlanAssessmentTemplateViewSet,\n base_name='plan_assessment_templates')\nrouter.register(\n r'assessment_questions',\n AssessmentQuestionViewSet,\n base_name='assessment_questions')\nrouter.register(\n r'assessment_tasks', AssessmentTaskViewSet, base_name='assessment_tasks')\nrouter.register(\n r'assessment_responses',\n AssessmentResponseViewSet,\n base_name='assessment_responses')\nrouter.register(\n r'vital_task_templates/search',\n VitalTaskTemplateSearchViewSet,\n base_name=\"vital_task_templates-search\"\n)\nrouter.register(\n r'vital_task_templates',\n VitalTaskTemplateViewSet,\n base_name='vital_task_templates')\nrouter.register(\n r'plan_vital_templates',\n CarePlanVitalTemplateViewSet,\n base_name='plan_vital_templates')\nrouter.register(r'vital_tasks', VitalTaskViewSet, base_name='vital_tasks')\nrouter.register(\n r'vital_questions',\n VitalQuestionViewSet,\n base_name='vital_questions')\nrouter.register(\n r'vital_responses',\n VitalResponseViewSet,\n base_name='vital_responses')\n\nschema_view = get_swagger_view(title='CareAdopt API')\n\nurlpatterns = [\n url(r'^favicon.ico$', RedirectView.as_view(\n url=settings.STATIC_URL + 'favicon.ico')),\n\n url(\n r'^api/users/verify_change_email/',\n VerifyChangeEmail.as_view(),\n name=\"verify_change_email\"\n ),\n\n url(r'^api/', include('apps.core.api.urls')),\n url(r'^api/', include('apps.patients.api.urls')),\n url(r'^api/', include('apps.plans.api.urls')),\n\n url(r'^api/', include(router.urls)),\n url(r'^$', LandingView.as_view(), name='landing-page'),\n\n # Administration\n url(r'^admin/', admin.site.urls),\n\n # General Api\n url(r'^api-auth/', include('rest_framework.urls',\n namespace='rest_framework')),\n url(r'^api-token-auth/', ObtainAuthToken.as_view()),\n url(r'reset-password/(?P[a-zA-Z0-9-.+@_]+)/$',\n RequestPasswordChange.as_view(), name='reset-password'),\n url(r'reset/(?P[a-z0-9\\-]+)/$',\n ResetPassword.as_view(), name='reset-request'),\n url(r'validate/(?P[a-z0-9\\-]+)/$',\n ValidateUserView.as_view(), name='user-validation'),\n\n # Make sure this comes first before rest-auth URLs\n url(r'^', include('django.contrib.auth.urls')),\n\n url(r'^rest-auth/', include('rest_auth.urls')),\n url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),\n url(r'^rest-auth/add_user/', CustomRegisterView.as_view(), name='user_register'),\n\n url(r'^api/todays_tasks/', TodaysTasksAPIView.as_view(), name=\"todays_tasks\"),\n url(r'^swagger/', schema_view),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"Services/care_adopt_backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":16950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"172439974","text":"\n# coding: utf-8\n\n# In[499]:\n\nfrom sklearn import datasets\nfrom sklearn import decomposition\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\nimport seaborn as sea\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom random import randint\n\n#load data\niris = datasets.load_iris()\n\nX = iris.data\n\ndf = pd.DataFrame(X, columns = iris.feature_names)\n# 1 = setosa 2 = versicolor 3 = virginica\ndf['iris type'] = iris.target\ndf['iris type'] = np.where(df['iris type']==0, iris.target_names[0],np.where(df['iris type']==1, iris.target_names[1], iris.target_names[2]))\ndf['iris type'] = df['iris type'].astype(object)\nprint(df.head())\n\n\n# In[500]:\n\nX = df[[0,1,2,3]].values\ny = df['iris type'].values\n\n\n# In[501]:\n\n#run pca\npca = decomposition.PCA(n_components=4)\npca_data = pca.fit_transform(X)\ndf_pca = pd.DataFrame(pca_data, columns = iris.feature_names)\ndf_pca['iris type'] = df['iris type']\n\n#run lda\nlda = LDA(solver = 'eigen', n_components = 4)\nlda_data = lda.fit_transform(X,y)\ndf_lda = pd.DataFrame(lda_data, columns = iris.feature_names)\ndf_lda['iris type'] = df['iris type']\n\n\n# In[458]:\n\n#plot original points\nprplt = sea.pairplot(df, hue ='iris type')\nplt.title('Original')\nplt.show()\n\n#plot pca transformation\nprplt = sea.pairplot(df_pca, hue ='iris type')\nplt.title('PCA')\nplt.show()\n\n#plot LDA transformation\nprplt = sea.pairplot(df_lda, hue ='iris type')\nplt.title('LDA')\nplt.show()\n\n\n# In[502]:\n\n#graphing distance function for sepal lenth to sepal with as in K-NN\ndef graphdist(index,xvar,yvar,df_eq):\n dist = (((df_eq.ix[index,'sepal length (cm)']) - xvar)**2 + ((df_eq.ix[index,'sepal width (cm)']) - yvar)**2)**(1/2)\n dist = round(dist, 5)\n return(dist)\n#a distance column\ndf['distance'] = 0\ndf_pca['distance'] = 0\ndf_lda['distance'] = 0\n\n\n\n# In[503]:\n\n#picking the random point and setting it\nrndm_pt = randint(0,len(df))\nx1_df = df.ix[rndm_pt,'sepal length (cm)']\ny1_df = df.ix[rndm_pt,'sepal width (cm)']\nx1_pca = df_pca.ix[rndm_pt,'sepal length (cm)']\ny1_pca = df_pca.ix[rndm_pt,'sepal width (cm)']\nx1_lda = df_lda.ix[rndm_pt,'sepal length (cm)']\ny1_lda = df_lda.ix[rndm_pt,'sepal width (cm)']\n\nprint(df.ix[rndm_pt])\nprint(df_pca.ix[rndm_pt])\nprint(df_lda.ix[rndm_pt])\n\n\n# In[506]:\n\n#applying distance function to all dfs\n#def df_distance(xvar,yvar,df_eq,d_type):\n# for index, row in df_eq.iterrows():\n# df_eq.ix[index, 'distance'] = graphdist(index,xvar,yvar,df_eq)\n# df_eq = df_eq.sort_values(['distance'], ascending = 1)\n# return(df_eq)\n\nfor index, row in df.iterrows():\n df.ix[index, 'distance'] = graphdist(index,x1_df,y1_df,df)\ndf = df.sort_values(['distance'], ascending = 1)\n\nfor index, row in df_pca.iterrows():\n df_pca.ix[index, 'distance'] = graphdist(index,x1_pca,y1_pca,df_pca)\ndf_pca = df_pca.sort_values(['distance'], ascending = 1)\n\nfor index, row in df_lda.iterrows():\n df_lda.ix[index, 'distance'] = graphdist(index,x1_lda,y1_lda,df_lda)\ndf_lda = df_lda.sort_values(['distance'], ascending = 1)\n\n\n# In[510]:\n\ndef knn(k,df_eq):\n new_df = df_eq.head(n = k)\n flowertype = new_df['iris type'].describe()\n return(flowertype)\n\ndef knntest(i,df_eq):\n correct_count = 0\n false_count = 0\n for i in range(1,i):\n flwr = knn(i,df_eq)\n rndmptflower = df.ix[rndm_pt,'iris type']\n #print(type(flwr))\n #print(flwr['top'])\n #print(type(rndmptflower))\n #print(rndmptflower)\n if flwr['top'] == rndmptflower:\n correct_count += 1\n else:\n false_count += 1\n print(correct_count, false_count)\n print(correct_count/(correct_count+false_count))\n \n\n\n# In[511]:\n\nknntest(10,df)\n\n\n# In[512]:\n\nprint(knn(10,df))\nknntest(20,df)\n\n\n# In[513]:\n\nprint(knn(10,df_lda))\nknntest(20, df_lda)\n\n\n# In[514]:\n\nprint(knn(10,df_pca))\nknntest(20, df_pca)\n\n\n# In[ ]:\n\n\n\n","sub_path":"reduce.py","file_name":"reduce.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"612796671","text":"import shlex\nimport subprocess\nimport sys\n\n\nclass Worker:\n\n def __init__(self):\n pass\n\n def make_link(self, source, target, **kwargs):\n cmd_str = '{sudo} ln {soft} {source} {target}'.format(\n sudo='sudo' if kwargs.get('sudo') else '',\n soft='-s' if kwargs.get('soft') else '',\n source=source,\n target=target\n )\n self.execute_cmd(cmd_str)\n\n def execute_cmd(self, cmd_str, **kwargs):\n cmd_list = shlex.split(cmd_str)\n if kwargs.get('capture_output'):\n process = subprocess.Popen(cmd_list, stdout=subprocess.PIPE)\n else:\n process = subprocess.Popen(cmd_list, stdout=sys.stdout)\n if kwargs.get('wait'):\n process.wait()\n","sub_path":"os_utils.py","file_name":"os_utils.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"611517257","text":"import numpy as np\n\n# INPUT: action - dictionary with attributes of the action\n# dturn - signifying delta of steering wheel (how much to turn it this turn)\n# dmove - how far forward to move\n# occupied - a matrix of zeros and ones with ones showing spaces\n# that are occupied by either obstacles or other robots\ndef calc_move(sim_params, pos, action, occupied, add_noise=True):\n # Make sure action has the correct format\n assert 'dturn' in action\n assert 'dmove' in action\n \n # Use bike model to calculate update\n x = pos[0]\n y = pos[1]\n theta = pos[2]\n alpha = action['dturn'] \n d = action['dmove']\n L = sim_params['robot_length']\n beta = d/L * np.tan(alpha) \n if beta < 1e-4:\n x = x + d * np.cos(theta)\n y = y + d * np.sin(theta) \n else:\n R = d/beta\n cx = x - np.sin(theta) * R\n cy = y + np.cos(theta) * R\n x = cx + np.sin(theta + beta) * R\n y = cy - np.cos(theta + beta) * R\n theta = (theta + beta)%(2 * np.pi)\n \n # Look to see if target position causes a collision\n # Currently only looks at center of mass collisions - need to add perimeter collisions\n collision_x = np.floor(x)\n collision_y = np.floor(y)\n if not islegal(occupied, collision_x, collision_y) or occupied[collision_x, collision_y] == 1:\n return pos\n else:\n # Update parameters with new state\n # Add noise if robot takes stochastic actions\n pos = [x,y,theta]\n if add_noise:\n msigma = sim_params['robot_move_sigma']\n tsigma = sim_params['robot_turn_sigma']\n pos[0:2] += np.random.normal(0,msigma,2)\n pos[2] += np.random.normal(0,tsigma,1)\n return pos\n \n# Return given a map if the location (x,y) is in the grid\ndef islegal(objmap, m_pos, n_pos):\n m_max, n_max = objmap.shape;\n \n if m_pos < 0 or m_pos >= m_max or n_pos < 0 or n_pos >= n_max:\n return False\n else:\n return True\n","sub_path":"player/transition_model/bicycle.py","file_name":"bicycle.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"13965160","text":"import pandas as pd\r\n\r\n#Wczytanie pliku train:\r\ndf = pd.read_csv(\"./train.tsv\",delimiter='\\t')\r\n#Nadanie nazw kolumn:\r\nnazwyKolumn = ['Cena', 'Liczba_pokoi', 'Powierzchnia', 'Piętro', 'Lokalizacja', 'Opis']\r\ndf.columns = nazwyKolumn\r\n\r\n#Wczytanie pliku description:\r\ndescription = pd.read_csv(\"./description.csv\", sep=\",\")\r\n\r\n#Połączenie danych z dwóch tabel - opis zależny od piętra:\r\n#pd.merge(frame_1, frame_2, left_on='left_frame_kolumn_name', right_on='right_frame_kolumn_name')\r\n#plik 'train' wiersz 'Piętro' -> łączenie z plikiem 'description' wiersz 'liczba'\r\n#outer -> łączy wszystkie wiersze dla lewej i prawej tabeli danych,\r\n# wypisuje NaN, gdy nie ma zgodnych wartości w wierszach.\r\n#indicator -> ustawiony na True wypisze skąd pochodzi każdy wiersz w danych\r\njoin = pd.merge(df, description, left_on='Piętro', right_on='liczba', how='outer', indicator=True)\r\n\r\n#Zachowa wiersze w lewej tabeli:\r\n#join = pd.merge(df, description, left_on='Piętro', right_on='liczba', how='left', indicator=True)\r\n\r\n#Zapisanie wyniku do pliku out2:\r\njoin.to_csv(\"./out2.csv\")\r\n\r\nprint(join)\r\n\r\n\r\n\r\n","sub_path":"Zestaw_1/Zestaw_1.2.py","file_name":"Zestaw_1.2.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"43208715","text":"import random\nimport time\nfrom datetime import datetime, timedelta\nimport sys\nsys.path.append('/Users/nezmi/Projects/yeznable_projects')\n\nfrom LAB.Data_collection import start_selenium\nfrom LAB.Data_collection import functions_for_db\nfrom personal import id_pw_classes\n\n# 이 정보들은 숨길 필요가 있을듯 user_agent는 되도록 그때그때 바꿔주자\nroot_url = \"https://www.instagram.com/\"\nuser_agent= \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36\"\n\ninsta_class = id_pw_classes.instagram()\nID = insta_class.id_for_crawler\nPW = insta_class.pw_for_crawler\ntarget = \"kaws\"\n\nDriver = start_selenium.Driver(user_agent,root_url)\ndriver = Driver.start()\n\n# driver.find_elements_by_xpath('//*[@id=\"react-root\"]/section/main/article/div[2]/div[2]/p/a')[0].click()\ndriver.implicitly_wait(5)\ntime.sleep(5)\n\n# 로그인 정보 입력 및 로그인\ndriver.find_elements_by_name('username')[0].send_keys(ID)\ndriver.find_elements_by_name('password')[0].send_keys(PW)\ndriver.implicitly_wait(5)\ntime.sleep(6)\ndriver.find_elements_by_xpath('//*[@id=\"react-root\"]/section/main/article/div[2]/div[1]/div/form/div[4]/button/div')[0].click()\ndriver.implicitly_wait(5)\ntime.sleep(2)\nprint('Login...')\n\n# 뭔 알림 설정 취소\ndriver.find_elements_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]')[0].click()\ndriver.implicitly_wait(5)\ntime.sleep(1)\n\n# 검색창 활성화 하고 검색 입력\ndriver.find_elements_by_xpath('//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/div/div')[0].click()\ndriver.find_elements_by_xpath('//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/input')[0].send_keys(target)\ndriver.implicitly_wait(5)\ntime.sleep(4)\n\n# 검색 결과에서 가장 위에 뜬걸로 들어감\ndriver.find_elements_by_xpath('//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/div[3]/div[2]/div/a[1]/div')[0].click()\ndriver.implicitly_wait(5)\ntime.sleep(10)\nprint('Found target...')\n\n# DB에 연결해놓기\n# 로그인 정보들 숨길 필요가 있음\nmysql_user = id_pw_classes.mysql()\n\nhost = '127.0.0.1'\nuser = mysql_user.id_yeznable\npassword = mysql_user.pw_yeznable\ndb = 'KAWS_instagram'\n\nconnection = functions_for_db.get_connection(host,user,password,db)\ncursor = connection.cursor()\nprint('DB connected...')\n\n# DB 커서를 생성해서 수집되어있는 링크들을 받아옴\nquery_select_collected_links = \"SELECT link FROM posting_links\"\ncursor.execute(query_select_collected_links)\ntuple_collected_links = cursor.fetchall()\nlist_collected_links = [list(link)[0] for link in tuple_collected_links]\nprint(str(len(list_collected_links)) + ' of posting links are collected')\n\n# 마지막 포스트가 2018년 이후 포스트면 계속 돈다\nstart = True\nlist_links = []\nwhile True:\n # 페이지의 모든 링크 저장\n elements_links = driver.find_elements_by_tag_name('a')\n new_link_lists = [element.get_attribute('href') for element in elements_links]\n list_links += new_link_lists\n\n if len(set(list_links) - set(list_collected_links)) < 1:\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(4)\n continue\n\n if start == True:\n print('Collecting...')\n # 처음엔 여러번 스크롤 내림\n # 3번 이상 스크롤을 내리면 한 페이지에 나타나는 링크 수가 60개 정도로 한정되기 때문에\n for i in range(4):\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(4)\n elements_links = driver.find_elements_by_tag_name('a')\n new_link_lists = [element.get_attribute('href') for element in elements_links]\n list_links += new_link_lists\n start = False\n else:\n # 처음 이후로는 한번씩 스크롤 내림\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(10)\n # 적당히 마지막 쪽애 있는 게시물을 열어봄\n driver.implicitly_wait(10)\n driver.find_elements_by_tag_name('a')[45].click()\n time.sleep(4)\n driver.implicitly_wait(5)\n # 2017년 포스트가 나오면 지금까지 포스트들 링크를 전부 저장\n post_time = driver.find_elements_by_tag_name('time')[-1].get_attribute(\"datetime\")\n print(post_time)\n if int(post_time.split('-')[0]) < 2018:\n driver.find_element_by_xpath('/html/body/div[4]/div[3]/button').click()\n elements_links = driver.find_elements_by_tag_name('a')\n new_link_lists = [element.get_attribute('href') for element in elements_links]\n list_links += new_link_lists\n break\n driver.find_element_by_xpath('/html/body/div[4]/div[3]/button').click()\n\n list_links_ = list(set(list_links))\n list_links = [link for link in list_links if link.split('/p/')[0] == 'https://www.instagram.com']\n list_links = list(set(list_links) - set(list_collected_links))\n\n links_for_insert = [f\"('{link}')\" for link in list_links if link not in list_collected_links]\n for insert in links_for_insert:\n query_for_insert_links = f\"INSERT INTO posting_links(link) VALUES {insert};\"\n # print(query_for_insert_links)\n cursor.execute(query_for_insert_links)\n connection.commit()\n\n print(f'{len(links_for_insert)} of postings are collected')\n\n cursor.execute(query_select_collected_links)\n tuple_collected_links = cursor.fetchall()\n list_collected_links = [list(link)[0] for link in tuple_collected_links]\n\ndriver.quit()\nconnection.close()","sub_path":"데청캠/small_project/crawler/KAWS_links_since_2018_crawler.py","file_name":"KAWS_links_since_2018_crawler.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"448093495","text":"class archiveManager:\n def __init__(self, db_client):\n self.db_client = db_client\n self.cursor = db_client.cursor\n self._database_tables = {'nodes_archive': nodeArchiver(self.db_client),\n 'links_archive': linkArchiver(self.db_client),\n 'datetime_archive': datetimeArchiver(self.db_client),\n 'sensor_data_archive': sensorDataArchiver(self.db_client)}\n\n def archive_database(self):\n if self.has_nodes_for_display():\n self._archive('datetime_archive')\n self._archive('nodes_archive')\n self._archive('links_archive')\n self._archive('sensor_data_archive')\n\n def has_nodes_for_display(self):\n query = (\"\"\n \"SELECT COUNT(coordinate_set) AS node_count \"\n \"FROM nodes WHERE coordinate_set = true;\")\n\n self.cursor.execute(query)\n (node_count,) = self.cursor.fetchone()\n return (node_count > 0)\n\n def _archive(self, table):\n if table in self._database_tables:\n self._database_tables[table].archive()\n else:\n raise ValueError(\"Invalid value for table: {0}\".format(table))\n\nclass archiver:\n def __init__(self, db_client):\n self.db_client = db_client\n self.cursor = db_client.cursor\n\n def archive(self):\n raise NotImplementedError(\"no subclass implementation\")\n\nclass datetimeArchiver(archiver):\n def _new_datetime_archive_id(self):\n \"\"\"This method gets the next available id for a new data row in\n datetime_archive table.\n \"\"\"\n\n query = \"SELECT MAX(id) FROM datetime_archive;\"\n\n self.cursor.execute(query)\n\n (last_row_id,) = self.cursor.fetchone()\n if last_row_id == None:\n return 1\n else:\n return last_row_id + 1\n\n def _new_datetime_archive_data(self):\n query = \"SELECT created_at FROM nodes_present LIMIT 1;\"\n\n self.cursor.execute(query)\n\n # check if \"nodes_present\" table is empty\n if self.cursor.rowcount == 0:\n return None\n else:\n (created_at,) = self.cursor.fetchone()\n return created_at\n\n def archive(self):\n \"\"\"This method saves the date and time when the Nodes table is\n archived. It stores the new datetime of the archive in the\n Datetime_archives table.\n\n Args:\n created_at (datetime): the time when the Nodes table\n is archived.\n\n \"\"\"\n\n id = self._new_datetime_archive_id()\n data = self._new_datetime_archive_data()\n\n insert_statement = (\"INSERT INTO datetime_archive \"\n \"(id, datetime_archive) \"\n \"VALUES (%s, %s);\")\n\n # Add extra comma to the tuple (current_time,)\n self.cursor.execute(insert_statement, (id, data,))\n self.db_client.commit()\n\nclass sensorDataArchiver(archiver):\n def new_sensor_data_archive_id(self):\n query = \"SELECT MAX(id) FROM sensor_data_archive;\"\n\n self.cursor.execute(query)\n (last_row_id,) = self.cursor.fetchone()\n\n if last_row_id == None:\n return 1\n else:\n return last_row_id + 1\n\n def sensor_data_creation_date(self):\n query = \"SELECT DISTINCT(created_at) FROM sensor_data LIMIT 1;\"\n\n self.cursor.execute(query);\n (created_at,) = self.cursor.fetchone()\n\n return created_at\n\n def datetime_archive_id(self):\n query = (\"\"\n \"SELECT id FROM datetime_archive \"\n \"WHERE datetime_archive = '{}';\").format(self.sensor_data_creation_date())\n\n self.cursor.execute(query)\n (id,) = self.cursor.fetchone()\n\n return id\n\n def query_sensor_data(self):\n \"\"\"This method queries all of the node objects from the \"nodes_present\" table.\n\n \"\"\"\n query = (\"SELECT \"\n \"sensor_data.node_id, \"\n \"sensor_data.sensor_type_id, \"\n \"sensor_data.value \"\n \"FROM sensor_data;\")\n\n self.cursor.execute(query)\n\n def archive(self):\n sensor_data_archive_id = self.new_sensor_data_archive_id()\n date_created_id = self.datetime_archive_id()\n\n if date_created_id == None:\n return\n\n self.query_sensor_data()\n rows = self.cursor.fetchall()\n\n for (node_id,\n sensor_type_id,\n value,) in rows:\n\n insert_statement = (\"\"\n \"INSERT INTO sensor_data_archive \"\n \"(id, \"\n \"node_id, \"\n \"sensor_type_id, \"\n \"value, \"\n \"date_created_id) \"\n \"VALUES (\"\n \"%(id)s, \"\n \"%(node_id)s, \"\n \"%(sensor_type_id)s, \"\n \"%(value)s, \"\n \"%(date_created_id)s);\")\n\n data = {\n 'id': sensor_data_archive_id,\n 'node_id': node_id,\n 'sensor_type_id': sensor_type_id,\n 'value': value,\n 'date_created_id': date_created_id\n }\n\n sensor_data_archive_id += 1\n\n self.cursor.execute(insert_statement, data)\n\n self.db_client.commit()\n\n\nclass nodeArchiver(archiver):\n def new_nodes_archive_id(self):\n query = \"SELECT MAX(id) FROM nodes_archive;\"\n\n self.cursor.execute(query)\n (last_row_id,) = self.cursor.fetchone()\n\n if last_row_id == None:\n return 1\n else:\n return last_row_id + 1\n\n def nodes_creation_date(self):\n query = \"SELECT DISTINCT(created_at) FROM nodes_present LIMIT 1;\"\n\n self.cursor.execute(query);\n (created_at,) = self.cursor.fetchone()\n\n return created_at\n\n def datetime_archive_id(self):\n query = (\"\"\n \"SELECT id FROM datetime_archive \"\n \"WHERE datetime_archive = '{}';\").format(self.nodes_creation_date())\n\n self.cursor.execute(query)\n (id,) = self.cursor.fetchone()\n\n return id\n\n def query_nodes(self):\n \"\"\"This method queries all of the node objects from the \"nodes_present\" table.\n\n \"\"\"\n\n query = (\"SELECT \"\n \"nodes_present.node_id, \"\n \"nodes_present.x_coordinate, \"\n \"nodes_present.y_coordinate, \"\n \"nodes.coordinate_set, \"\n \"nodes_present.last_transmission, \"\n \"nodes_present.packets_sent, \"\n \"nodes_present.packets_received \"\n \"FROM nodes_present \"\n \"INNER JOIN nodes \"\n \"ON (nodes.id = nodes_present.node_id);\")\n\n self.cursor.execute(query)\n\n def archive(self):\n \"\"\"This method creates an archive of the current nodes. It first\n queries all of the nodes from the \"Nodes\" table and then it stores\n the result set to the \"Node_archives\" table\n\n \"\"\"\n nodes_archive_id = self.new_nodes_archive_id()\n date_created_id = self.datetime_archive_id()\n\n if date_created_id == None:\n return\n\n self.query_nodes()\n rows = self.cursor.fetchall()\n # After executing the query, the cursor object will contain a list\n # of tuples and each tuple represents a row in the result set\n\n for (node_id,\n x_coordinate,\n y_coordinate,\n coordinate_set,\n last_transmission,\n packets_sent,\n packets_received,) in rows:\n\n # archive only those nodes that have been already set in a location\n if coordinate_set == True:\n\n insert_statement = (\"\"\n \"INSERT INTO nodes_archive \"\n \"(id, node_id, x_coordinate, y_coordinate, \"\n \"last_transmission, packets_sent, \"\n \"packets_received, date_created_id) \"\n \"VALUES (\"\n \"%(id)s, \"\n \"%(node_id)s, \"\n \"%(x_coordinate)s, \"\n \"%(y_coordinate)s, \"\n \"%(last_transmission)s, \"\n \"%(packets_sent)s, \"\n \"%(packets_received)s, \"\n \"%(date_created_id)s);\")\n\n data = {\n 'id': nodes_archive_id,\n 'node_id': node_id,\n 'x_coordinate': x_coordinate,\n 'y_coordinate': y_coordinate,\n 'last_transmission': last_transmission,\n 'packets_sent': packets_sent,\n 'packets_received': packets_received,\n 'date_created_id': date_created_id,\n }\n\n nodes_archive_id += 1\n\n self.cursor.execute(insert_statement, data)\n\n self.db_client.commit()\n\nclass linkArchiver(archiver):\n def links_creation_date(self):\n \"\"\"This method returns the datetime when the links in the links_present\n table were created.\n \"\"\"\n query = \"SELECT DISTINCT(created_at) FROM links_present LIMIT 1;\"\n\n self.cursor.execute(query);\n (created_at,) = self.cursor.fetchone()\n\n return created_at\n\n def datetime_archive_id(self):\n \"\"\"This method returns the datetime_archive id of the datetime\n corresponding to the creation date of the links in the links_present\n table.\n \"\"\"\n query = (\"\"\n \"SELECT id FROM datetime_archive \"\n \"WHERE datetime_archive = '{}';\").format(self.links_creation_date())\n\n self.cursor.execute(query)\n (id,) = self.cursor.fetchone()\n\n return id\n\n def new_links_archive_id(self):\n \"\"\"This method queries for the last id stored in the \"links_archive\"\n table. It then returns the next id for the insertion of new data in\n \"links_archive\" table.\n\n \"\"\"\n\n query = \"SELECT MAX(id) FROM links_archive;\"\n\n self.cursor.execute(query)\n (last_row_id,) = self.cursor.fetchone()\n\n if last_row_id == None:\n return 1\n else:\n return last_row_id + 1\n\n def query_links_present(self):\n \"\"\"This method queries data from the links_present table. The data\n to be returned are the links that have their source node and\n target node fixed in location.\n \"\"\"\n query = (\"\"\n \"SELECT id, \"\n \"source_id, \"\n \"target_id, \"\n \"traffic_id, \"\n \"floor_id \"\n \"FROM links_present \"\n \"WHERE source_id \"\n \"IN (SELECT id FROM nodes WHERE coordinate_set = true) \"\n \"AND target_id \"\n \"IN (SELECT id FROM nodes WHERE coordinate_set = true);\")\n\n self.cursor.execute(query)\n\n return self.cursor.fetchall()\n\n def archive(self):\n \"\"\" This method copies the data in the \"edges_present\" table to\n \"edges_archive\" table\n\n \"\"\"\n link_archive_id = self.new_links_archive_id()\n date_created_id = self.datetime_archive_id()\n rows = self.query_links_present()\n links = []\n\n for (link_id, source_id, target_id, traffic_id, floor_id) in rows:\n insert_statement = (\"\"\n \"INSERT INTO links_archive \"\n \"(id, link_id, source_id, target_id, traffic_id, floor_id, \"\n \"date_created_id) \"\n \"VALUES ( \"\n \"%(id)s, \"\n \"%(link_id)s, \"\n \"%(source_id)s, \"\n \"%(target_id)s, \"\n \"%(traffic_id)s, \"\n \"%(floor_id)s, \"\n \"%(date_created_id)s);\")\n\n data = {\n 'id': link_archive_id,\n 'link_id': link_id,\n 'source_id': source_id,\n 'target_id': target_id,\n 'traffic_id': traffic_id,\n 'floor_id': floor_id,\n 'date_created_id': date_created_id,\n }\n\n link_archive_id += 1\n\n self.cursor.execute(insert_statement, data)\n\n self.db_client.commit()\n","sub_path":"python/db/dbArchive.py","file_name":"dbArchive.py","file_ext":"py","file_size_in_byte":12136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"272154870","text":"import numpy as np\r\nimport operator\r\nfrom collections import Counter\r\nfrom sklearn import neighbors\r\nfrom sklearn.datasets import load_breast_cancer\r\nfrom sklearn.utils import shuffle\r\n\r\nclass myKNeighborsClassifier(object):\r\n \"\"\"docstring for myKNeighborsClassifier\"\"\"\r\n def __init__(self):\r\n super(myKNeighborsClassifier, self).__init__()\r\n \r\n def auto_norm(self, data):\r\n max_val = np.max(data, axis=0)\r\n min_val = np.min(data, axis=0)\r\n range_val = max_val - min_val\r\n mean_val = np.mean(data, axis=0)\r\n norm_data = np.zeros(np.shape(data))\r\n\r\n m = data.shape[0]\r\n norm_data = data - np.tile(min_val, (m, 1))\r\n norm_data = norm_data / tile(range_val, (m, 1))\r\n\r\n return data\r\n\r\n def pre_data_init(self):\r\n data = load_breast_cancer().data\r\n target = load_breast_cancer().target\r\n\r\n # data = self.auto_norm(data)\r\n\r\n X, y = shuffle(data, target, random_state=42)\r\n X = X.astype(np.float32)\r\n y = y.reshape((-1,1))\r\n\r\n offset = int(X.shape[0] * 0.9)\r\n x_train, y_train = X[:offset], y[:offset]\r\n x_test, y_test = X[offset:], y[offset:]\r\n\r\n y_train = y_train.reshape((-1,1))\r\n y_test = y_test.reshape((-1,1))\r\n\r\n return x_train, x_test, y_train, y_test\r\n\r\n def validation(self, x_train, y_train, fold):\r\n dims = x_train.shape[1]\r\n if x_train.shape[0] % fold == 0:\r\n x_fold = []\r\n y_fold = []\r\n x_fold = np.split(x_train, fold)\r\n y_fold = np.split(y_train, fold)\r\n for i in range(fold):\r\n x_tr = np.concatenate(\r\n (np.array(x_fold)[:i], np.array(x_fold)[i+1:]),axis=0)\r\n y_tr = np.concatenate(\r\n (np.array(y_fold)[:i], np.array(y_fold)[i+1:]), axis=0)\r\n x_val = np.array(x_fold)[i]\r\n y_val = np.array(y_fold)[i]\r\n x_tr = x_tr.reshape((-1,dims))\r\n y_tr = y_tr.reshape((-1,1))\r\n yield (x_tr, y_tr, x_val, y_val)\r\n else:\r\n print(\"Attention: vary size.\")\r\n # x_fold = []\r\n # y_fold = []\r\n # offset = int(x_train.shape[0] / fold)\r\n # for i in range(fold-1):\r\n # x_fold.append(x_train[i * offset : (i + 1) * offset])\r\n # y_fold.append(y_train[i * offset : (i + 1) * offset])\r\n # x_fold.append(x_train[(fold - 1) * offset:])\r\n # y_fold.append(y_train[(fold - 1) * offset:])\r\n\r\n # for i in range(fold):\r\n # x_tr = np.concatenate(\r\n # (np.array(x_fold)[:i], np.array(x_fold)[i+1:]),axis=0)\r\n # y_tr = np.concatenate(\r\n # (np.array(y_fold)[:i], np.array(y_fold)[i+1:]), axis=0)\r\n # x_val = np.array(x_fold)[i]\r\n # y_val = np.array(y_fold)[i]\r\n # print(x_tr.shape)\r\n # x_tr = x_tr.reshape((-1,dims))\r\n # y_tr = y_tr.reshape((-1,dims))\r\n\r\n # yield (x_tr, y_tr, x_val, y_val)\r\n\r\n def distant(self, x_tr, x_test, dis_type):\r\n if dis_type == 'l2':\r\n dim_tr = x_tr.shape[0]\r\n dim_te = x_test.shape[0]\r\n dim_feature = x_tr.shape[1]\r\n\r\n # l2 = ((x - y)**2)**0.5\r\n # expand_tr = x_tr.reshape((-1, dim_te))\r\n ## calculate x - y through tile(), and the square root of sum\r\n expand_te = np.tile(x_test.reshape((dim_te,1,-1)), (1 ,dim_tr,1))\r\n expand_te = expand_te.reshape((-1, dim_feature))\r\n expand_tr = np.tile(x_tr,(dim_te,1))\r\n dist_xy = np.sum((expand_te - expand_tr)**2, axis=1)\r\n dist_mat = (dist_xy**0.5).reshape((dim_te,-1))\r\n return dist_mat\r\n\r\n if dis_type == 'cosine':\r\n # dimension of sets\r\n dim_tr = x_tr.shape[0]\r\n dim_te = x_test.shape[0]\r\n\r\n # cos = A.T.dot(B) / ((A**2)**0.5 + (B**2)**0.5)\r\n ## calculate the dot product, and the sqaure root of x and y\r\n frac_u = np.dot(x_test, x_tr.T)\r\n sub_tr = (x_tr**2).sum(axis=1).reshape((-1,1))\r\n sub_tr = np.tile(sub_tr.T**0.5,(dim_te, 1))\r\n sub_te = (x_test**2).sum(axis=1).reshape((-1,1))\r\n sub_te = np.tile(sub_te**0.5,(dim_tr))\r\n frac_d = sub_tr * sub_te\r\n return frac_u / frac_d\r\n\r\n def predict(self, x_tr, y_tr, x_test, y_test, k):\r\n dist_mat = self.distant(x_tr, x_test, 'l2')\r\n dist_k = dist_mat.argsort(axis=1)\r\n y_predict = np.array([])\r\n\r\n for sample in range(dist_k.shape[0]):\r\n class_count = {}\r\n for i in range(k):\r\n vote_label = int(y_tr[dist_k[sample][i]])\r\n class_count[vote_label] = class_count.get(vote_label, 0) + 1\r\n\r\n final_vote = sorted(class_count.items(), \r\n key=operator.itemgetter(1), reverse=True)\r\n y_predict = np.append(y_predict, final_vote[0][0])\r\n\r\n y_predict = y_predict.reshape((-1,1))\r\n return y_predict\r\n\r\n def evalation(self, y_predict, y_test):\r\n y_test = y_test.ravel()\r\n y_predict = y_predict.ravel()\r\n\r\n num_test = y_test.shape[0]\r\n outcome = y_predict - y_test\r\n outcome[outcome == -1] = 1\r\n \r\n Counter(outcome)\r\n Counter(y_predict)\r\n num_tp_tn = sum(outcome==0)\r\n num_fp = np.dot(y_predict.T, outcome)\r\n num_tp = sum(y_predict==1) - num_fp\r\n num_tn = num_tp_tn - num_tp\r\n num_fn = sum(y_predict==0) - num_tn\r\n \r\n accuracy = num_tp_tn / num_test\r\n precision = num_tp / (num_tp + num_fp)\r\n recall = num_tp / (num_tp + num_fn)\r\n \r\n return accuracy, precision, recall\r\n\r\n def manyplot(\r\n self,\r\n precision_list, \r\n precision_list01,\r\n recall_list,\r\n recall_list01,\r\n accuracy_list,\r\n accuracy_list01,\r\n ):\r\n import matplotlib.pyplot as plt\r\n fig2 = plt.figure()\r\n mypre, = plt.plot(range(5,21), accuracy_list, color='darkorange', linestyle='-')\r\n skpre, = plt.plot(range(5,21), accuracy_list01, color='lightseagreen', linestyle='--')\r\n plt.xlabel('neighbors')\r\n plt.ylabel('accuracy')\r\n plt.legend(labels=['my', 'sklearn'], loc='best')\r\n plt.savefig(\"./accuracy.jpg\")\r\n\r\n fig3 = plt.figure()\r\n mypre, = plt.plot(range(5,21), precision_list, color='darkorange', linestyle='-')\r\n skpre, = plt.plot(range(5,21), precision_list01, color='lightseagreen', linestyle='--')\r\n plt.xlabel('neighbors')\r\n plt.ylabel('precision')\r\n plt.legend(labels=['my', 'sklearn'], loc='best')\r\n plt.savefig(\"./precision.jpg\")\r\n\r\n fig4 = plt.figure()\r\n plt.plot(recall_list, precision_list,color='darkorange')\r\n plt.plot(recall_list01, precision_list01, color='lightseagreen', alpha=0.5)\r\n plt.xlabel('recall')\r\n plt.ylabel('precision')\r\n plt.legend(labels=['my', 'sklearn'], loc='best')\r\n plt.savefig(\"./Presision-Recall.jpg\")\r\n \r\n plt.show()\r\n\r\n def scatterplot(self, y_predict,y_predict01, y_test):\r\n import matplotlib.pyplot as plt \r\n fig1 = plt.figure()\r\n orginal, = plt.plot(y_test, color='darkorange', linestyle='-')\r\n ours, = plt.plot(y_predict, color='red', linestyle='-.')\r\n sklearn, = plt.plot(y_predict01, color='lightseagreen', linestyle='--')\r\n plt.legend(labels=['orginal','ours', 'sklearn'], loc='best')\r\n plt.savefig('./plot.jpg')\r\n\r\nif __name__ == '__main__':\r\n model = myKNeighborsClassifier()\r\n knn = neighbors.KNeighborsClassifier(n_neighbors=10)\r\n x_train, x_test, y_train, y_test = model.pre_data_init()\r\n \r\n \"\"\"\r\n for i, (x_tr, y_tr, x_val, y_val) in enumerate(model.validation(x_train, y_train, 4)):\r\n print(i)\r\n k = 10\r\n\r\n y_predict = model.predict(x_tr, y_tr, x_val, y_val, k)\r\n accuracy, precision, recall = model.evalation(y_predict, y_val)\r\n print('our:', accuracy, precision, recall)\r\n\r\n knn = neighbors.KNeighborsClassifier(n_neighbors=k)\r\n knn.fit(x_tr,y_tr)\r\n y_predict01 = knn.predict(x_val)\r\n accuracy01, precision01, recall01 = model.evalation(y_predict01, y_val)\r\n print('sklearn:', accuracy01, precision01, recall01)\r\n \"\"\"\r\n k = 10\r\n y_predict = model.predict(x_train, y_train, x_test, y_test, k)\r\n accuracy, precision, recall = model.evalation(y_predict, y_test)\r\n\r\n knn = neighbors.KNeighborsClassifier(n_neighbors=k)\r\n knn.fit(x_train,y_train)\r\n y_predict01 = knn.predict(x_test)\r\n accuracy01, precision01, recall01 = model.evalation(y_predict01, y_test)\r\n model.scatterplot(y_predict,y_predict01, y_test)\r\n\r\n \"\"\"\r\n precision_list = []\r\n recall_list = []\r\n accuracy_list = []\r\n\r\n precision_list01 = []\r\n recall_list01 = []\r\n accuracy_list01 = []\r\n\r\n for k in range(5,21):\r\n y_predict = model.predict(x_train, y_train, x_test, y_test, k)\r\n accuracy, precision, recall = model.evalation(y_predict, y_test)\r\n precision_list.append(precision)\r\n recall_list.append(recall)\r\n accuracy_list.append(recall)\r\n\r\n knn = neighbors.KNeighborsClassifier(n_neighbors=k)\r\n knn.fit(x_train,y_train)\r\n y_predict01 = knn.predict(x_test)\r\n accuracy01, precision01, recall01 = model.evalation(y_predict01, y_test)\r\n precision_list01.append(precision01)\r\n recall_list01.append(recall01)\r\n accuracy_list01.append(recall01)\r\n \r\n model.manyplot(\r\n precision_list, \r\n precision_list01,\r\n recall_list,\r\n recall_list01,\r\n accuracy_list,\r\n accuracy_list01,\r\n y_predict,\r\n y_predict01,\r\n y_test\r\n )\r\n \"\"\"\r\n","sub_path":"k_neighbors/k_nearest_neighbor.py","file_name":"k_nearest_neighbor.py","file_ext":"py","file_size_in_byte":10007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"79076211","text":"class FreqStack():\n\n def __init__(self):\n self.countEachNumber = {}\n self.freqNumber = {}\n self.maxFreqCount = 0\n\n def push(self, x):\n count = self.countEachNumber.get(x, 0) + 1\n self.countEachNumber[x] = count\n if self.maxFreqCount < count :\n self.maxFreqCount = count\n\n sameFreqNumbers = self.freqNumber.get(count, [])\n sameFreqNumbers.append(x)\n self.freqNumber[count] = sameFreqNumbers\n\n def pop(self):\n if self.maxFreqCount == 0 :\n return None\n if self.maxFreqCount in self.freqNumber and len(self.freqNumber.get(self.maxFreqCount)) > 0:\n sameFreqNumbers = self.freqNumber.get(self.maxFreqCount)\n maxFreqNumber = sameFreqNumbers.pop()\n count = self.countEachNumber.get(maxFreqNumber, 0)\n self.countEachNumber[maxFreqNumber] = count - 1\n return maxFreqNumber\n else :\n self.maxFreqCount -= 1\n return self.pop()\n\nstack = FreqStack()\n\nlist = [5,7,5,7,4,5]\nfor item in list :\n stack.push(item)\n\nfreq = stack.pop()\nwhile freq != None :\n print(freq)\n freq = stack.pop()","sub_path":"src/main/python/leetcode/maximum-frequency-stack.py","file_name":"maximum-frequency-stack.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"521696140","text":"import matplotlib as mpl\nmpl.use('agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nd4a=np.loadtxt(\"data/results_rscaletest-gke4_bigbat.txt\")\nd4b=np.loadtxt(\"data/results_rscaletest-gke4_nodybat_bigbat.txt\")\n\n# EmTrackMichelIS Time\nfig=plt.figure()\nax=fig.add_subplot(111)\n\nax.set_xlim(0,410)\nax.set_ylim(0,100)\nax.grid(True)\nax.errorbar(d4b[:,0], d4b[:,3], yerr=d4b[:,4], fmt='bD--', linewidth=0.8,markersize=5.5, markeredgecolor='b', fillstyle='none', capsize=3, label = \"w/ tRTis on GKE-4gpu, dyn bat Off, avg bat sz = 1720\")\nax.errorbar(d4a[:,0], d4a[:,3], yerr=d4a[:,4], fmt='rv--', linewidth=0.8,markersize=7, markeredgecolor='r', fillstyle='none', capsize=3, label = \"w/ tRTis on GKE-4gpu, dyn bat On, avg bat sz = 1720\")\nax.set(title=\"EmTrkMichelId module proc time vs # jobs (GKE-4gpu)\", xlabel=\"number of simultaneous jobs\", ylabel=\"processing time [seconds]\")\n\n#xr=[0.,310.]\n#yr=[219.4,219.4]\n#ax.plot(xr, yr, color='orange',label = \"without tRTis\",linestyle='solid',linewidth=2)\n\nax.legend()\nfig.tight_layout()\nfig.savefig(\"plot-5a_EmTrackMichelID.png\")\nfig.show()\n\n# Full Event Time\nfig2=plt.figure()\nax2=fig2.add_subplot(111)\n\nax2.set_xlim(0,410)\nax2.set_ylim(0,250)\nax2.grid(True)\nax2.errorbar(d4b[:,0], d4b[:,1], yerr=d4b[:,2], fmt='bD--', linewidth=0.8,markersize=5.5, markeredgecolor='b', fillstyle='none', capsize=3, label = \"w/ tRTis on GKE-4gpu, dyn bat Off, avg bat sz = 1720\")\nax2.errorbar(d4a[:,0], d4a[:,1], yerr=d4a[:,2], fmt='rv--', linewidth=0.8,markersize=7, markeredgecolor='r', fillstyle='none', capsize=3, label = \"w/ tRTis on GKE-4gpu, dyn bat On, avg bat sz = 1720\")\nax2.set(title=\"Full Event proc time vs # jobs (GKE-4gpu)\", xlabel=\"number of simultaneous jobs\", ylabel=\"processing time [seconds]\")\n\nax2.legend()\nfig2.tight_layout()\nfig2.savefig(\"plot-5a_FullEvent.png\")\nfig2.show()\n","sub_path":"plot-5a.py","file_name":"plot-5a.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"328689022","text":"from typing import List, Any\n\nfrom pycubexr.classes import CNode, Metric\nfrom pycubexr.classes.metric import MetricType\nfrom pycubexr.utils.exceptions import InvalidConversionInstructionError\n\n\nclass MetricValues(object):\n\n def __init__(\n self,\n *,\n metric: Metric,\n cnode_indices: List[int],\n values: List[Any]\n ):\n self.metric = metric\n self.values = values\n self.cnode_indices = cnode_indices\n assert len(self.values) % len(self.cnode_indices) == 0\n\n def num_locations(self):\n return int(len(self.values) / len(self.cnode_indices))\n\n def cnode_values(self, cnode: CNode, convert_to_exclusive: bool = False, convert_to_inclusive: bool = False):\n if convert_to_inclusive and convert_to_exclusive:\n raise InvalidConversionInstructionError()\n assert not (convert_to_inclusive and convert_to_exclusive)\n assert cnode.id in self.cnode_indices\n start_index = int(self.cnode_indices.index(cnode.id) * self.num_locations())\n end_index = start_index + self.num_locations()\n values = self.values[start_index:end_index]\n\n must_convert = ((convert_to_exclusive and self.metric.metric_type == MetricType.INCLUSIVE)\n or (convert_to_inclusive and self.metric.metric_type == MetricType.EXCLUSIVE))\n if must_convert:\n values = self._convert_values(cnode, values, to_inclusive=convert_to_inclusive)\n # Copy the list instead of returning the values to prevent the user changing the internal values\n return [value for value in values]\n\n def location_value(self, cnode: CNode, location_id: int, convert_to_inclusive=False, convert_to_exclusive=False):\n assert location_id < self.num_locations()\n return self.cnode_values(\n cnode,\n convert_to_exclusive=convert_to_exclusive,\n convert_to_inclusive=convert_to_inclusive\n )[location_id]\n\n def _convert_values(self, cnode: CNode, values: List[Any], to_inclusive: bool = True):\n # Go over all cnode children and add the metric values\n # Does NOT change the values array!\n for child_cnode in cnode.get_all_children(with_self=False):\n if child_cnode.id not in self.cnode_indices:\n continue\n values = [\n x + y if to_inclusive else x - y\n for x, y\n in zip(values, self.cnode_values(\n child_cnode,\n convert_to_inclusive=False,\n convert_to_exclusive=False)\n )\n ]\n return values\n\n def __repr__(self):\n return 'MetricValues<{}>'.format(self.__dict__)\n","sub_path":"pycubexr/classes/metric_values.py","file_name":"metric_values.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"177298417","text":"\"\"\"Test nestor_api.api.public_routes.heartbeat.\"\"\"\nfrom nestor_api.api.flask_app import create_app\n\n\ndef test_heartbeat_success():\n \"\"\"Should return a 204 without restriction.\"\"\"\n app = create_app()\n response = app.test_client().get(\"/heartbeat\")\n expected = 204\n assert (response.status_code) == expected\n","sub_path":"tests/api/public_routes/test_heartbeat.py","file_name":"test_heartbeat.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"135354136","text":"# !/usr/bin/python\n\nimport threading\nfrom uuid import uuid4\n\nfrom proton.utils import BlockingConnection\n\nROUTER_ADDRESS = \"proton+amqp://mlesko-236x.usersys.redhat.com:5672\"\n# ROUTER_ADDRESS = \"proton+amqp://mlesko-246x.usersys.redhat.com:5672\"\nADDRESS = \"pulp.address\"\nHEARTBEAT = 60\n# SLEEP_MIN = 1.9\n# SLEEP_MAX = 2.1\nTHREADS = 100\nRECEIVERS = 100\n\n\nclass ReceiverThread(threading.Thread):\n def __init__(self, _id, address=ADDRESS, domain=None):\n super(ReceiverThread, self).__init__()\n self._id = _id\n self.address = address\n self.domain = domain\n self.running = True\n self.nr = 0\n self.max = RECEIVERS\n\n def connect(self):\n self.conn = BlockingConnection(ROUTER_ADDRESS, ssl_domain=self.domain, heartbeat=HEARTBEAT)\n\n def run(self):\n self.connect()\n for x in xrange(self.max):\n name = '%s.%s' % (self.address, x)\n self.recv = self.conn.create_receiver(name, name=str(uuid4()), dynamic=False,\n options=None)\n print(\"created: \", name)\n\n\nthreads = []\n\nfor i in range(THREADS):\n threads.append(ReceiverThread(i, '%s.%s' % (ADDRESS, i)))\n threads[i].start()\n\nfor i in range(THREADS):\n threads[i].join()\n","sub_path":"examples/client/multiple_blocking_receivers.py","file_name":"multiple_blocking_receivers.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"333854751","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nAutomatically mark gait cycle events.\nBased on thresholding of marker position/velocity/acceleration.\nUses forceplate data to determine individual thresholds.\n\n@author: Jussi\n\"\"\"\n\nfrom __future__ import division, print_function\n\nimport numpy as np\nfrom scipy import signal\nfrom gp import getdata\nimport matplotlib.pyplot as plt\nimport time\n\ndef rising_zerocross(x):\n \"\"\" Return indices of rising zero crossings in sequence,\n i.e. n where x[n] >= 0 and x[n-1] < 0 \"\"\"\n x = np.array(x) # this should not hurt\n return np.where(np.logical_and(x[1:] >= 0, x[:-1] < 0))[0]+1\n\n\ndef falling_zerocross(x):\n return rising_zerocross(-x)\n\n\ndef nexus_get_marker_data(vicon, markers):\n \"\"\" From Nexus, get position, velocity and acceleration for\n specified markers.\n Returns dicts keyed with marker names followed by P, V or A.\n dict values are n x 3 matrices of vector data. \"\"\"\n if not isinstance(markers, list):\n markers = [markers]\n subjectnames = vicon.GetSubjectNames()\n if not subjectnames:\n raise ValueError('No subject defined in Nexus')\n mdata = dict()\n for marker in markers:\n x, y, z, _ = vicon.GetTrajectory(subjectnames[0], marker)\n if len(x) == 0:\n raise ValueError('Cannot get marker trajectory: %s' % marker)\n mdata[marker+'_P'] = np.array([x, y, z]).transpose()\n mdata[marker+'_V'] = np.gradient(mdata[marker+'_P'])[0]\n mdata[marker+'_A'] = np.gradient(mdata[marker+'_V'])[0]\n return mdata\n\n\ndef nexus_gaps(vicon, marker):\n \"\"\" Get gaps for a marker \"\"\"\n mP = nexus_get_marker_data(vicon, marker)[marker + '_P']\n allzero = np.logical_and(mP[:, 0] == 0, mP[:, 1] == 0, mP[:, 2] == 0)\n return np.where(allzero)[0]\n\n\ndef nexus_get_roi(vicon):\n \"\"\" Return array of frames corresponding to Nexus ROI \"\"\"\n roi = vicon.GetTrialRegionOfInterest()\n return np.arange(roi[0], roi[1])\n\n\ndef nexus_get_fp_strike_and_toeoff(vicon):\n \"\"\" Return forceplate strike and toeoff frames. \"\"\"\n FP_THRESHOLD = .02 # % of maximum force\n fp0 = getdata.forceplate(vicon)\n # try to remove forceplate noise & spikes with median filter\n ftot = signal.medfilt(fp0.forcetot, 5)\n frel = ftot/ftot.max()\n # in analog frames\n # first large force increase\n fpstrike = rising_zerocross(frel-FP_THRESHOLD)[0]\n # last force decrease\n fptoeoff = falling_zerocross(frel-FP_THRESHOLD)[-1]\n return (int(np.round(fpstrike/fp0.samplesperframe)),\n int(np.round(fptoeoff/fp0.samplesperframe)))\n\n\ndef center_frame(vicon):\n \"\"\" Return frame where subject crosses x axis of coordinate system\n (y = 0) \"\"\"\n mrkdata = nexus_get_marker_data(vicon, ['LASI', 'RASI'])\n P = (mrkdata['LASI_P'] + mrkdata['RASI_P'])/2.\n y = P[:, 1]\n zx = np.append(rising_zerocross(y), falling_zerocross(y))\n ycross = list()\n # sanity checks\n for p in zx:\n # y must be nonzero on either side of crossing (valid data)\n if p-10 > 0 and p+10 < len(y):\n if y[p-10] != 0 and y[p+10] != 0:\n # y must change sign also around p\n if np.sign(y[p-10]) != np.sign(y[p+10]):\n ycross.append(p)\n return ycross\n\n\ndef subject_ydir(vicon):\n \"\"\" Return direction of movement for subject (y derivative pos/neg) \"\"\"\n TRACK_MARKER = 'LASI'\n mrkdata = nexus_get_marker_data(vicon, TRACK_MARKER)\n P = mrkdata['LASI_P']\n ydiff = np.median(np.diff(P[:, 1])) # median of y derivative\n return 1 if ydiff > 0 else -1\n\n\ndef kinetics_available(vicon):\n \"\"\" See whether this trial has valid forceplate data (ground reaction\n forces available) for left/right side (or neither, or both).\n Uses forceplate data, gait events and marker positions.\n For now support for one forceplate only.\n May require modifications for c3d (ROI etc.)\n\n General:\n -check max total force, must correspond to subject weight\n -center of pressure must not change too much during contact time\n\n For each candidate strike:\n -1st force increase must occur around the same time as foot strike\n -max total force must occur in a window after the same strike\n -heel & toe markers must not be outside plate edges at strike time\n \"\"\"\n\n # get subject info\n subjectnames = vicon.GetSubjectNames()\n if not subjectnames:\n raise ValueError('No subject defined in Nexus')\n subjectname = subjectnames[0]\n Bodymass = vicon.GetSubjectParam(subjectname, 'Bodymass')\n # for unknown reasons, above method may return tuple or float, depending on\n # whether script is run from Nexus or from IPython outside Nexus\n if isinstance(Bodymass, tuple):\n Bodymass = Bodymass[0]\n subj_weight = Bodymass * 9.81\n\n fp0 = getdata.forceplate(vicon)\n forcetot = signal.medfilt(fp0.forcetot) # remove spikes\n\n # autodetection parameters\n F_THRESHOLD = .1 * subj_weight # rise threshold\n FMAX_REL_MIN = .8 # maximum force as % of bodyweight must exceed this\n MAX_COP_SHIFT = 300 # maximum CoP shift (in x or y dir) in mm\n # time specified in seconds -> analog frames\n FRISE_WINDOW = .05 * fp0.sfrate\n FMAX_MAX_DELAY = .95 * fp0.sfrate\n # right feet markers\n RIGHT_FOOT_MARKERS = ['RHEE', 'RTOE', 'RANK']\n # left foot markers\n LEFT_FOOT_MARKERS = ['LHEE', 'LTOE', 'LANK']\n # forceplate boundaries in world coords \n FP_YMIN = 0\n FP_YMAX = 508\n FP_XMIN = 0\n FP_XMAX = 465\n # tolerance for toeoff in y dir\n Y_TOEOFF_TOL = 20\n # ankle marker tolerance in x dir\n X_ANKLE_TOL = 20\n \n emptydi = {'context': '', 'strike': None, 'strike_v': None,\n 'toeoff': None, 'toeoff_v': None}\n\n fmax = max(forcetot)\n fmaxind = np.where(forcetot == fmax)[0][0] # first maximum\n print('kinetics_available: max force:', fmax, 'at:', fmaxind,\n 'weight:', subj_weight)\n if max(forcetot) < FMAX_REL_MIN * subj_weight:\n print('kinetics_available: insufficient max. force on plate')\n return emptydi\n # find indices where force crosses threshold\n try:\n friseind = rising_zerocross(forcetot-F_THRESHOLD)[0] # first rise\n ffallind = falling_zerocross(forcetot-F_THRESHOLD)[-1] # last fall\n except IndexError:\n print('kinetics_available: cannot detect force rise/fall')\n return emptydi\n # check shift of center of pressure during ROI; should not shift too much\n cop_roi = np.arange(friseind, ffallind)\n copx, copy = np.array(fp0.copx), np.array(fp0.copy)\n copx_shift = np.max(copx[cop_roi]) - np.min(copx[cop_roi])\n copy_shift = np.max(copy[cop_roi]) - np.min(copy[cop_roi])\n if copx_shift > MAX_COP_SHIFT or copy_shift > MAX_COP_SHIFT:\n print('kinetics_available: center of pressure shifts too much',\n '(double contact?)')\n return emptydi\n\n # check: markers inside forceplate region during strike/toeoff\n strike_fr = int(np.round(friseind / fp0.samplesperframe))\n toeoff_fr = int(np.round(ffallind / fp0.samplesperframe))\n mrkdata = nexus_get_marker_data(vicon, RIGHT_FOOT_MARKERS +\n LEFT_FOOT_MARKERS)\n kinetics = None\n ok = True\n for marker in RIGHT_FOOT_MARKERS:\n marker += '_P'\n # ankle marker gets extra tolerance in x dir\n if marker == 'RANK_P':\n FP_XMIN_ = FP_XMIN - X_ANKLE_TOL\n FP_XMAX_ = FP_XMAX + X_ANKLE_TOL\n else:\n FP_XMIN_ = FP_XMIN\n FP_XMAX_ = FP_XMAX\n ok &= np.logical_and(mrkdata[marker][:, 0] > FP_XMIN,\n mrkdata[marker][:, 0] < FP_XMAX)[strike_fr]\n ok &= np.logical_and(mrkdata[marker][:, 0] > FP_XMIN,\n mrkdata[marker][:, 0] < FP_XMAX)[toeoff_fr]\n ok &= np.logical_and(mrkdata[marker][:, 1] > FP_YMIN,\n mrkdata[marker][:, 1] < FP_YMAX)[strike_fr]\n ok &= np.logical_and(mrkdata[marker][:, 1] > FP_YMIN - Y_TOEOFF_TOL,\n mrkdata[marker][:, 1] < FP_YMAX + Y_TOEOFF_TOL)[toeoff_fr]\n if not ok:\n break\n if ok:\n kinetics = 'R'\n ok = True\n for marker in LEFT_FOOT_MARKERS:\n marker += '_P'\n print(marker)\n print(mrkdata[marker][:, 0][toeoff_fr])\n if marker == 'LANK_P':\n FP_XMIN_ = FP_XMIN - X_ANKLE_TOL\n FP_XMAX_ = FP_XMAX + X_ANKLE_TOL\n else:\n FP_XMIN_ = FP_XMIN\n FP_XMAX_ = FP_XMAX\n ok &= np.logical_and(mrkdata[marker][:, 0] > FP_XMIN_,\n mrkdata[marker][:, 0] < FP_XMAX_)[strike_fr]\n ok &= np.logical_and(mrkdata[marker][:, 0] > FP_XMIN_,\n mrkdata[marker][:, 0] < FP_XMAX_)[toeoff_fr]\n ok &= np.logical_and(mrkdata[marker][:, 1] > FP_YMIN,\n mrkdata[marker][:, 1] < FP_YMAX)[strike_fr]\n ok &= np.logical_and(mrkdata[marker][:, 1] > FP_YMIN - Y_TOEOFF_TOL,\n mrkdata[marker][:, 1] < FP_YMAX + Y_TOEOFF_TOL)[toeoff_fr]\n if not ok:\n break\n if ok:\n kinetics = 'L'\n\n if not kinetics:\n print('kinetics_available: markers off plate during strike/toeoff')\n return emptydi\n\n # kinetics ok, compute velocities at strike\n markers = RIGHT_FOOT_MARKERS if kinetics == 'R' else LEFT_FOOT_MARKERS\n footctrV = np.zeros(mrkdata[markers[0]+'_V'].shape)\n for marker in markers:\n footctrV += mrkdata[marker+'_V'] / len(markers)\n footctrv = np.sqrt(np.sum(footctrV[:, 1:3]**2, 1))\n strike_v = footctrv[int(strike_fr)]\n toeoff_v = footctrv[int(toeoff_fr)]\n print('kinetics_available: strike on %s at %d, toeoff at %d'\n % (kinetics, strike_fr, toeoff_fr))\n return {'context': kinetics, 'strike': strike_fr, 'strike_v': strike_v,\n 'toeoff': toeoff_fr, 'toeoff_v': toeoff_v}\n\n\ndef automark_events(vicon, vel_thresholds={'L_strike': None, 'L_toeoff': None,\n 'R_strike': None, 'R_toeoff': None}, context=None,\n strike_frame=None,\n events_context=(0, 1), events_nocontext=(-1, 0, 1),\n mark_window_hw=None, plot=False):\n \"\"\" Mark events based on velocity thresholding. Absolute thresholds\n can be specified as arguments. Otherwise relative thresholds will be\n calculated based on the data. Optimal results will be obtained when\n thresholds based on force plate data are available.\n\n vel_threshold gives velocity thresholds for identifying events. These\n can be obtained from forceplate data.\n\n context gives forceplate context for the trial: 'R', 'L', or None.\n \n strike_frame is the frame where forceplate contact occurs.\n\n events_context specified which events to mark for the side where forceplate\n strike occurs. For example (-1, 1) would mark one event before forceplate\n and one event after (forceplate strike event is always marked).\n events_nocontext is applied for the side where there is no forceplate\n contact.\n \n If plot=True, velocity curves and events are plotted.\n\n Before automark, run reconstruct, label and gap fill pipelines.\n \"\"\"\n\n frate = vicon.GetFrameRate()\n if not frate:\n raise Exception('Cannot get framerate from Nexus')\n\n # relative thresholds (of maximum velocity)\n REL_THRESHOLD_FALL = .2\n REL_THRESHOLD_RISE = .5\n # marker data is assumed to be in mm\n # mm/frame = 1000 m/frame = 1000/frate m/s\n VEL_CONV = 1000/frate\n # reasonable limits for peak velocity (m/s before multiplier)\n MAX_PEAK_VELOCITY = 12 * VEL_CONV\n MIN_PEAK_VELOCITY = .5 * VEL_CONV\n # reasonable limits for velocity on slope (increasing/decreasing)\n MAX_SLOPE_VELOCITY = 6 * VEL_CONV\n MIN_SLOPE_VELOCITY = .05 * VEL_CONV\n # median prefilter width\n MEDIAN_WIDTH = 3\n # right feet markers\n RIGHT_FOOT_MARKERS = ['RHEE', 'RTOE', 'RANK']\n # left foot markers\n LEFT_FOOT_MARKERS = ['LHEE', 'LTOE', 'LANK']\n # tolerance between forceplate strike (parameter) and detected event\n FP_STRIKE_TOL = 7\n\n # get subject info\n subjectnames = vicon.GetSubjectNames()\n if not subjectnames:\n raise ValueError('No subject defined in Nexus')\n subjectname = subjectnames[0]\n\n # get foot center velocity vectors and scalar velocities\n mrkdata = nexus_get_marker_data(vicon,\n RIGHT_FOOT_MARKERS+LEFT_FOOT_MARKERS)\n\n rfootctrV = np.zeros(mrkdata[RIGHT_FOOT_MARKERS[0]+'_V'].shape)\n for marker in RIGHT_FOOT_MARKERS:\n rfootctrV += mrkdata[marker+'_V'] / len(RIGHT_FOOT_MARKERS)\n rfootctrv = np.sqrt(np.sum(rfootctrV[:, 1:3]**2, 1))\n\n lfootctrV = np.zeros(mrkdata[LEFT_FOOT_MARKERS[0]+'_V'].shape)\n for marker in LEFT_FOOT_MARKERS:\n lfootctrV += mrkdata[marker+'_V'] / len(LEFT_FOOT_MARKERS)\n lfootctrv = np.sqrt(np.sum(lfootctrV[:, 1:3]**2, 1))\n\n strikes_all = {}\n toeoffs_all = {}\n\n # loop: same operations for left / right foot\n for ind, footctrv in enumerate((rfootctrv, lfootctrv)):\n this_side = 'R' if ind == 0 else 'L'\n\n # filter to scalar velocity data to suppress noise and spikes\n footctrv = signal.medfilt(footctrv, MEDIAN_WIDTH)\n\n # compute local maxima of velocity: derivative crosses zero, values ok\n vd = np.gradient(footctrv)\n vdz_ind = falling_zerocross(vd)\n inds = np.where(np.logical_and(footctrv[vdz_ind] > MIN_PEAK_VELOCITY,\n footctrv[vdz_ind] < MAX_PEAK_VELOCITY))\n maxv = np.median(footctrv[vdz_ind[inds]])\n\n if maxv > MAX_PEAK_VELOCITY:\n raise ValueError('Velocity thresholds too high, data may be noisy')\n\n # compute thresholds\n threshold_fall_ = vel_thresholds[this_side+'_strike'] or maxv * REL_THRESHOLD_FALL\n threshold_rise_ = vel_thresholds[this_side+'_toeoff'] or maxv * REL_THRESHOLD_RISE\n\n print('automark: rel. thresholds: fall: %.2f rise %.2f' % (maxv * REL_THRESHOLD_FALL, maxv * REL_THRESHOLD_RISE))\n print('automark: using fall threshold: %s=%.2f' % (this_side, threshold_fall_))\n print('automark: using rise threshold: %s=%.2f' % (this_side, threshold_rise_))\n\n # find point where velocity crosses threshold\n # strikes (velocity decreases)\n cross = falling_zerocross(footctrv - threshold_fall_)\n # exclude edges of data vector\n cross = cross[np.where(np.logical_and(cross > 0,\n cross < (len(footctrv) - 1)))]\n cind_min = np.logical_and(footctrv[cross-1] < MAX_SLOPE_VELOCITY,\n footctrv[cross-1] > MIN_SLOPE_VELOCITY)\n cind_max = np.logical_and(footctrv[cross+1] < MAX_SLOPE_VELOCITY,\n footctrv[cross+1] > MIN_SLOPE_VELOCITY)\n strikes = cross[np.logical_and(cind_min, cind_max)]\n # toeoffs (velocity increases)\n cross = rising_zerocross(footctrv - threshold_rise_)\n cross = cross[np.where(np.logical_and(cross > 0,\n cross < len(footctrv)))]\n cind_min = np.logical_and(footctrv[cross-1] < MAX_SLOPE_VELOCITY,\n footctrv[cross-1] > MIN_SLOPE_VELOCITY)\n cind_max = np.logical_and(footctrv[cross+1] < MAX_SLOPE_VELOCITY,\n footctrv[cross+1] > MIN_SLOPE_VELOCITY)\n toeoffs = cross[np.logical_and(cind_min, cind_max)]\n\n # if fp data available, mark only events around forceplate strike\n if context and strike_frame:\n strikes_ = []\n if context == this_side:\n # find event corresponding to forceplate strike\n auto_strike_ind = np.argmin(abs(strikes - strike_frame))\n if abs(strikes[auto_strike_ind] -\n strike_frame) > FP_STRIKE_TOL:\n raise ValueError('Detected strike event does not match',\n 'strike_frame')\n # add other events as required\n for fr in events_context:\n if 0 <= auto_strike_ind + fr <= len(strikes) - 1:\n strikes_.append(strikes[auto_strike_ind + fr])\n else: # opposite side\n # find the next strike following the (opposite) fp strike\n diffv = strikes - strike_frame\n nextdiff = [x for x in diffv if x > 0][0]\n closest_next_ind = np.where(diffv == nextdiff)[0][0]\n for fr in events_nocontext:\n if 0 <= closest_next_ind + fr <= len(strikes) - 1:\n strikes_ += [strikes[closest_next_ind + fr]]\n strikes = strikes_\n # else mark around 'center frame' if specified\n elif mark_window_hw:\n ctr = center_frame(vicon)\n if not ctr:\n raise ValueError('Cannot find center frame (y crossing)')\n strikes = [fr for fr in strikes if abs(fr - ctr) <= mark_window_hw]\n # mark toeoffs that are between strike events\n toeoffs = [fr for fr in toeoffs\n if any(strikes < fr) and any(strikes > fr)]\n\n # create the events in Nexus\n side_str = 'Right' if this_side == 'R' else 'Left'\n for fr in strikes:\n vicon.CreateAnEvent(subjectname, side_str,\n 'Foot Strike', fr, 0.0)\n for fr in toeoffs:\n vicon.CreateAnEvent(subjectname, side_str, 'Foot Off', fr, 0.0)\n strikes_all[this_side] = strikes\n toeoffs_all[this_side] = toeoffs\n\n # plot velocities w/ thresholds\n if plot:\n if ind == 0:\n plt.figure()\n plt.subplot(2, 1, ind+1)\n plt.plot(footctrv, 'g', label='foot center velocity ' + this_side)\n # algorithm, fixed thresholds\n plt.plot(strikes, footctrv[strikes], 'kD', markersize=10,\n label='strike')\n plt.plot(toeoffs, footctrv[toeoffs], 'k^', markersize=10,\n label='toeoff')\n plt.legend(numpoints=1)\n plt.ylim(0, maxv+10)\n plt.xlabel('Frame')\n plt.ylabel('Velocity (mm/frame)')\n plt.title('Automark ' + this_side)\n\n return (strikes_all['R'], strikes_all['L'],\n toeoffs_all['R'], toeoffs_all['L'])\n\n\nif __name__ == '__main__':\n kinetics_available(vicon)\n #vicon = getdata.viconnexus()\n #vicon.ClearAllEvents()\n #automark_events(vicon, context='R', strike_frame=143)\n \n","sub_path":"nexus_automark.py","file_name":"nexus_automark.py","file_ext":"py","file_size_in_byte":18646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"209279024","text":"import pandas as pd\nimport rdkit\nfrom rdkit import DataStructs, Chem\nfrom rdkit.Chem import MACCSkeys, Draw\nimport torch\nimport numpy as np \n\n# New Molecule\n\ndata = pd.read_csv('./data/train.txt', names=['SMILES'])\n\nfrom fast_molvae.sample import load_model\nmodel = load_model('./data/vocab.txt', './fast_molvae/vae_model/model.epoch-19').cuda()\n\nout_latent = model.encode_to_latent(data['SMILES'][3:4])\n\nsmiles = []\nlatent_space = []\n\n\nfor i in range(1):\n noise = np.random.normal(1,0.1, 56)\n noise = np.expand_dims(noise,axis = 0)\n noise = torch.from_numpy(noise).float().cuda()\n out_latent_noise=out_latent*noise\n\n z_t = out_latent_noise[0:1,0:28].cuda()\n z_mol = out_latent_noise[0:1,28:56].cuda()\n latent_space.append(out_latent_noise)\n smiles.append(model.decode(z_t, z_mol, False))\n\n\n# exporting the molecules\n\nout_df = pd.DataFrame(smiles, columns = ['SMILES'])\nout_df.to_csv('./New_mols/generated_moleculesX.txt')\n\n\n\n## Similarity tanimoto\nnew_mol = out_df['SMILES'][0]\ndata_smiles = pd.read_csv('./data/train.txt', names=['SMILES'])\n\norig_mol = data_smiles['SMILES'][3]\nfrom rdkit import DataStructs, Chem\nnew_mol_fp = Chem.RDKFingerprint(Chem.MolFromSmiles(new_mol))\n\norig_mol_fp= Chem.RDKFingerprint(Chem.MolFromSmiles(data_smiles['SMILES'][3]))\ntan_sim = DataStructs.FingerprintSimilarity(orig_mol_fp, new_mol_fp)\n\n\n# Similarity euclidean\n\ndata_latent = pd.read_csv('./latent_space/encoded_ZINC_mean.txt').drop(columns={'Unnamed: 0'})\n\n\ndef euclid(x,y):\n sqrtsum= 0\n xx = x.cpu().data.numpy()\n yy = y.cpu().data.numpy()\n for i in range(len(xx)):\n sqrtsum += (xx[0,i]-yy[0,i])**2\n EUClid = 1 / ( 1 + np.sqrt(sqrtsum))\n return EUClid\n\n\nchosen_mol = out_latent_noise\neuc_dist = euclid( torch.tensor(data_latent.iloc[3,:]).cuda().unsqueeze_(0) , chosen_mol )\n\ndata_smiles['Tanimoto_Similarity'] = tan_sim\ndata_smiles['Euclidian_distance'] = euc_list\n\ndata_smiles.to_csv('./latent_space/data_smiles_with_tanimoto_and_euclidian_to_new_mol.txt')","sub_path":"main_newmols_w_sim.py","file_name":"main_newmols_w_sim.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"20998678","text":"# -*- coding: utf-8 -*-\nfrom collections import namedtuple\n\nfrom Qt import QtCore, QtWidgets, _loadUi, QtGui\n\n\nWidgetData = namedtuple(\"WidgetData\", [\"widget\", \"metadata\"])\n\n\nclass ListWidget(QtWidgets.QWidget):\n def __init__(self, height=30):\n super(ListWidget, self).__init__()\n\n self.height = height\n self.data = list()\n self.pool = QtWidgets.QListWidget()\n self.pool.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)\n\n self.init_ui()\n\n def __getitem__(self, index):\n clean_data = list()\n for item in self.data:\n if item.widget:\n clean_data.append(item)\n return clean_data[index]\n\n def init_ui(self):\n layout = QtWidgets.QVBoxLayout()\n\n layout.addWidget(self.pool)\n\n layout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(layout)\n\n def add_item(self, item, metadata=None, height=None):\n assert isinstance(item, QtWidgets.QWidget)\n list_item = QtWidgets.QListWidgetItem()\n self.data.append(WidgetData(item, metadata))\n qsize = QtCore.QSize()\n height = height if height else self.height\n qsize.setHeight(height)\n list_item.setSizeHint(qsize)\n self.pool.addItem(list_item)\n self.pool.setItemWidget(list_item, self.data[-1].widget)\n\nclass MotionItem(QtWidgets.QWidget):\n \"\"\"\n The item widget of QListWidget in motion group box.\n Used to toggle motion info exporter of each asset in layout scene.\n \"\"\"\n def __init__(self, name, enable=True, abc_option=True, arnold_option=True):\n super(MotionItem, self).__init__()\n\n self.label = QtWidgets.QLabel(name)\n self.checkbox = QtWidgets.QCheckBox(\"Export\")\n\n self.abc_box = QtWidgets.QCheckBox('Abc')\n self.arnold_box = QtWidgets.QCheckBox('Arnold')\n for each_box in [self.abc_box, self.arnold_box]:\n each_box.setDisabled(True)\n self.abc_option = abc_option\n self.arnold_option = arnold_option\n\n if enable:\n self.checkbox.setChecked(True)\n for each_box in [self.abc_box, self.arnold_box]:\n each_box.setDisabled(False)\n each_box.setChecked(True)\n else:\n self.label.setDisabled(False)\n\n self.init_ui()\n\n def __nonzero__(self):\n return self.checkbox.isChecked()\n\n @property\n def name(self):\n return str(self.label.text())\n\n @property\n def abc_checked(self):\n return self.abc_box.isChecked()\n\n @property\n def arnold_checked(self):\n return self.arnold_box.isChecked()\n\n def checkbox_state_changed(self):\n if self.checkbox.isChecked():\n for each_box in [self.abc_box, self.arnold_box]:\n each_box.setDisabled(False)\n else:\n for each_box in [self.abc_box, self.arnold_box]:\n each_box.setDisabled(True)\n each_box.setChecked(False)\n\n def init_ui(self):\n self.checkbox.clicked.connect(self.label.setEnabled)\n self.checkbox.stateChanged.connect(self.checkbox_state_changed)\n\n layout = QtWidgets.QHBoxLayout()\n layout.addWidget(self.label)\n layout.addStretch()\n layout.addWidget(self.checkbox)\n if self.abc_option:\n layout.addWidget(self.abc_box)\n if self.arnold_option:\n layout.addWidget(self.arnold_box)\n\n self.setLayout(layout)","sub_path":"gui/basic_gui.py","file_name":"basic_gui.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"43105763","text":"import random\nimport tensorflow as tf\n\nfrom datetime import datetime\n\nfrom keras import Sequential\n\n'''\nThis class will eventually use an actual PPO implementation from tf_agents,\nbut for now, it will instead use a Sequential model with a single dense layer\nfor testing purposes.\n\nThis class reuses a lot of the logic from the RandomAI class, but will use\nthe model to select a card to play in a trick, rather than picking randomly.\nCurrently, we are planning to use a replay buffer to eventually train the model.\nThe replay buffer has not been implemented yet, so the model current doesn't \nactually learn.\n'''\n\nclass PPOAI:\n\n # Neat is a toggle I made to switch the printing between\n # \"Neat\" output (without the tensor) and\n # Not \"Neat\" output (with the tensor)\n # Neat should only be changed manually before running\n # for debugging/convenience\n neat = True\n\n def __init__(self, name, params=None):\n self.model = Sequential()\n self.model.add(tf.keras.layers.Flatten())\n self.model.add(tf.keras.layers.Dense(13, name='Output'))\n # Compile to use predict later, even though no training is done\n self.model.compile()\n\n self.name = name\n\n if params != None:\n self.print_info = params['print_info']\n else:\n self.print_info = False\n\n def Do_Action(self, observation):\n if observation['event_name'] == 'GameStart':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n elif observation['event_name'] == 'NewRound':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n elif observation['event_name'] == 'PassCards':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n\n passCards = random.sample(observation['data']['hand'], 3)\n\n if self.print_info:\n print(self.name, ' pass cards: ', passCards)\n\n return {\n \"event_name\": \"PassCards_Action\",\n \"data\": {\n 'playerName': self.name,\n 'action': {'passCards': passCards}\n }\n }\n\n elif observation['event_name'] == 'ShowPlayerHand':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n\n elif observation['event_name'] == 'PlayTrick':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n\n hand = observation['data']['hand']\n # Unchanged from RandomAI. We think starting the game with the 2 of clubs\n # should be inherent behavior and shouldn't have to be learned.\n if '2c' in hand:\n choose_card = 0\n else:\n # Since we don't do training, this is basically random\n data = tf.reshape(observation[\"tensor\"], [1,902])\n logits = self.model.predict(data)\n choose_card = tf.argmax(logits, axis=1).numpy().tolist()[0]\n\n\n if self.print_info:\n print(self.name, ' choose card: ', choose_card)\n\n return {\n \"event_name\" : \"PlayTrick_Action\",\n \"data\" : {\n 'playerName': self.name,\n 'action': choose_card\n }\n }\n elif observation['event_name'] == 'ShowTrickAction':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n elif observation['event_name'] == 'ShowTrickEnd':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n elif observation['event_name'] == 'RoundEnd':\n if self.print_info:\n if self.neat:\n self.printCleanObservation(observation)\n else:\n print(observation)\n elif observation['event_name'] == 'GameOver':\n if self.print_info:\n print(observation)\n\n # Extra method that prints out the observation without the tensor\n def printCleanObservation(self, observation):\n new = {}\n for key, value in observation.items():\n if key != 'tensor':\n new[key] = value\n print(new)","sub_path":"src/Agent/PPOAI.py","file_name":"PPOAI.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"44872729","text":"# Copyright 2017-2020 TensorHub, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport logging\nimport os\nimport subprocess\n\nfrom guild import cli\nfrom guild import click_util\nfrom guild import config\nfrom guild import run_util\nfrom guild import util\n\nfrom . import remote_impl_support\nfrom . import runs_impl\n\nlog = logging.getLogger(\"guild\")\n\nDEFAULT_DIFF_CMD = \"diff -ru\"\n\n\nclass OneRunArgs(click_util.Args):\n def __init__(self, base_args, run):\n kw = base_args.as_kw()\n kw.pop(\"runs\")\n kw[\"run\"] = run\n super(OneRunArgs, self).__init__(**kw)\n\n\ndef main(args, ctx):\n if args.remote:\n remote_impl_support.diff_runs(args)\n else:\n _main(args, ctx)\n\n\ndef _main(args, ctx):\n _validate_args(args)\n _apply_default_runs(args)\n if args.working or args.working_dir:\n _diff_working(args, ctx)\n else:\n _diff_runs(args, ctx)\n\n\ndef _validate_args(args):\n if args.working and args.working_dir:\n cli.error(\"--working and --working-dir cannot both be specified\")\n\n\ndef _apply_default_runs(args):\n if len(args.runs) == 0:\n if args.working or args.working_dir:\n args.runs = (\"1\", None)\n else:\n args.runs = (\"2\", \"1\")\n elif len(args.runs) == 1:\n if args.working or args.working_dir:\n args.runs = (args.runs[0], None)\n else:\n cli.error(\n \"diff requires two runs\\n\"\n \"Try specifying a second run or 'guild diff --help' \"\n \"for more information.\"\n )\n elif len(args.runs) > 2:\n cli.error(\n \"cannot compare more than two runs\\n\"\n \"Try specifying just two runs or 'guild diff --help' for \"\n \"more information.\"\n )\n else:\n assert len(args.runs) == 2, args\n if args.working:\n cli.error(\"cannot specify RUN2 and --working\")\n if args.working_dir:\n cli.error(\"cannot specify RUN2 and --working-dir\")\n\n\ndef _diff_working(args, ctx):\n assert len(args.runs) == 2, args\n assert args.runs[0] is not None and args.runs[1] is None, args\n run = runs_impl.one_run(OneRunArgs(args, args.runs[0]), ctx)\n run_sourcecode_dir = run.guild_path(\"sourcecode\")\n if args.working_dir:\n working_dir = os.path.join(config.cwd(), args.working_dir)\n else:\n assert args.working\n working_dir = _find_run_working_dir(run)\n if not args.path:\n _diff(\n run_sourcecode_dir, working_dir, args,\n )\n else:\n for path in args.path:\n _diff(\n os.path.join(run_sourcecode_dir, path),\n os.path.join(working_dir, path),\n args,\n )\n\n\ndef _find_run_working_dir(run):\n working_dir = util.find_apply([_opdef_sourcecode_root, _script_source,], run)\n if not working_dir:\n cli.error(\n \"cannot find working source code directory for run {run_id}\\n\"\n \"Try specifying the directory with 'guild diff {run_id} \"\n \"--working-dir DIR'.\".format(run_id=run.short_id)\n )\n return working_dir\n\n\ndef _opdef_sourcecode_root(run):\n opdef = run_util.run_opdef(run)\n if opdef:\n return os.path.join(opdef.guildfile.dir, opdef.sourcecode.root or \"\")\n return None\n\n\ndef _script_source(run):\n if run.opref.pkg_type == \"script\":\n return run.opref.pkg_name\n return None\n\n\ndef _diff_runs(args, ctx):\n assert len(args.runs) == 2, args\n assert args.runs[0] is not None and args.runs[1] is not None, args\n run1 = runs_impl.one_run(OneRunArgs(args, args.runs[0]), ctx)\n run2 = runs_impl.one_run(OneRunArgs(args, args.runs[1]), ctx)\n for path in _diff_paths(args):\n _diff(os.path.join(run1.dir, path), os.path.join(run2.dir, path), args)\n\n\ndef _diff(path1, path2, args):\n cmd_base = util.shlex_split(_diff_cmd(args))\n cmd = cmd_base + [path1, path2]\n log.debug(\"diff cmd: %r\", cmd)\n try:\n subprocess.call(cmd)\n except OSError as e:\n cli.error(\"error running '%s': %s\" % (\" \".join(cmd), e))\n\n\ndef _diff_cmd(args):\n return args.cmd or _config_diff_cmd() or _default_diff_cmd()\n\n\ndef _config_diff_cmd():\n return config.user_config().get(\"diff\", {}).get(\"command\")\n\n\ndef _default_diff_cmd():\n if util.PLATFORM == \"Linux\":\n return _find_cmd([\"meld\", \"xxdiff -r\", \"dirdiff\", \"colordiff\",])\n elif util.PLATFORM == \"Darwin\":\n return _find_cmd([\"Kaleidoscope\", \"meld\", \"DiffMerge\", \"FileMerge\",])\n else:\n return DEFAULT_DIFF_CMD\n\n\ndef _find_cmd(cmds):\n for cmd in cmds:\n if util.which(cmd.split(\" \", 1)[0]):\n return cmd\n return DEFAULT_DIFF_CMD\n\n\ndef _diff_paths(args):\n paths = []\n if args.attrs:\n paths.append(os.path.join(\".guild\", \"attrs\"))\n if args.env:\n log.warning(\"ignoring --env (already included in --attrs)\")\n if args.flags:\n log.warning(\"ignoring --flags (already included in --attrs)\")\n if args.deps:\n log.warning(\"ignoring --deps (already included in --attrs)\")\n else:\n if args.env:\n paths.append(os.path.join(\".guild\", \"attrs\", \"env\"))\n if args.flags:\n paths.append(os.path.join(\".guild\", \"attrs\", \"flags\"))\n if args.deps:\n paths.append(os.path.join(\".guild\", \"attrs\", \"deps\"))\n if args.output:\n paths.append(os.path.join(\".guild\", \"output\"))\n if args.sourcecode:\n if args.path:\n paths.extend(\n [os.path.join(\".guild\", \"sourcecode\", path) for path in args.path]\n )\n else:\n paths.append(os.path.join(\".guild\", \"sourcecode\"))\n else:\n paths.extend(args.path)\n if not paths:\n paths.append(\"\")\n return paths\n","sub_path":"guild/commands/diff_impl.py","file_name":"diff_impl.py","file_ext":"py","file_size_in_byte":6354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"440359621","text":"# Global Score to be used in any function.\nscore = 0\n# Global list of descriptions for locales\ngloblist = ['''\nLOBBY: You walk up a large staircase. You are looking around and see someone\nrunning towards you. You get scared and you decide to run towards a hallways. There are four doors,\nwhich one will you chose?\n''', '''\nSURGICAL ROOM: You find a rusty scalpel and decide to pick it up just as a precaution. There is a very off smell\nin the room that is really bugging you. You see blood on the tables, the walls and the floor. You get nervous and\nyou start to look around the room for a way out. There are four doors, which one will you chose?\n''', '''\nCAFETERIA: The first detail of the room that you notice is that the kitchen lights are on. You decide\nto go back there and you see a pot boiling on the stove. Soon, the door that you came through opens again and it's the\nfigure from before. You think to yourself, \"Holy shit, not this again.\" In the back of the kitchen there are four doors,\nwhich one will you chose?\n''', '''\nSHOWERS: There is a smell of mold and must in the air. You get an ominous feeling while your in there\nbecause two of the showers are on. Suddenly, someone starts humming a song and you get the chills. You decide you need\nto get out. There are four doors, which one will you chose?\n''', '''\nCELL AREA: You walk down a long hallway filled with what looked like jail cells. The hallway seemed to be getting longer\nbefore your very eyes. Suddenly, you hear a noise from behind you. You immediately start to run as fast as you can.\nYou feel someones presence getting closer and closer. Finally, the end of the hallway is starting to come to light.\nThere are four doors, which one will you chose?\n''', '''\nFINAL ROOM (THE LAUNDRY ROOM) You walk in and there are old clothes and towels everywhere. You start thinking to\nyourself, \"I have to find a way out of here.\" You start looking around the room and notice that someone is standing in\nthee corner. You mumble nervously, \"H-Hello?\" The person turns around and goes through you. It felt like someone just\npushed you back. You fall down, hit your head, leaving you unconscious on thee floor. You wake up in a bed in one of the\ncells and it's morning. You notice you have a white outfit on and your cell is closed. Then you finally realize, That\nentire experience was a dream. You are in the insane asylum and have been for 2 years now.\n''']\nlocationlist = [\"You are now in Lobby.\",\n\"You are now in the Surgical Room.\",\n\"You are now in the Cafe.\",\n\"You are now in the Showers.\",\n\"You are now in the Cell area.\",\n\"You are now in the Laundry room\"]\nCurrentlocale = globlist[0]\nvisitedLocations = []\n\n\n# Press Enter to Continue (Advance through the story)\ndef cont(Enter):\n input(Enter)\n\n\n# Player Customization and introduction w/t title\ndef game_custom():\n print(\"Welcome to the spine chilling adventure through the abandoned insane asylum!\")\n print()\n name_prompt = \"Please enter your name: \"\n name = input(name_prompt)\n attrib_prompt = \"Please enter your desired attribute: \"\n attribute = input(attrib_prompt)\n print()\n print(\"Welcome,\", end=\" \")\n print(name, end=\" the \")\n print(attribute, end=\"\")\n print(\"!\")\n print()\n intro = '''\nIntro: The goal of this game is to reach the end of the adventure with 150 points. Throughout the storyline,\nyou will be able to chose where to go using the directions, north, south, east, and west.\nYou start with 0 points, but with the rooms you go through, you will earn 25 points. Good Luck!\n'''\n print(intro)\n visitlocation0()\n\n\n# Score and Location title when you reach a new locale\ndef score_Locale(Locationindex):\n global score\n print()\n print(locationlist[Locationindex])\n print()\n print(\"Current Score:\", score)\n print()\n\n\n# Defined locals to visit throughout game\ndef visitlocation0():\n global score\n visitedLocations.append(\"Lobby\")\n score_Locale(0)\n print(globlist[0])\n\n\ndef visitlocation1():\n global Currentlocale\n global score\n if \"Surgical Room\" not in visitedLocations:\n score = score + 25\n visitedLocations.append(\"Surgical Room\")\n score_Locale(1)\n print(globlist[1])\n\n\ndef visitlocation2():\n global Currentlocale\n global score\n if \"Cafe\" not in visitedLocations:\n score = score + 25\n visitedLocations.append(\"Cafe\")\n score_Locale(2)\n print(globlist[2])\n\n\ndef visitlocation3():\n global Currentlocale\n global score\n if \"Showers\" not in visitedLocations:\n score = score + 25\n visitedLocations.append(\"Showers\")\n score_Locale(3)\n print(globlist[3])\n\n\ndef visitlocation4():\n global Currentlocale\n global score\n if \"Cell Area\" not in visitedLocations:\n score = score + 25\n visitedLocations.append(\"Cell Area\")\n score_Locale(4)\n print(globlist[4])\n\n\ndef visitlocation5():\n global Currentlocale\n global globlist\n global score\n if \"Final\" not in visitedLocations:\n score = score + 25\n visitedLocations.append(\"Final\")\n score_Locale(5)\n print(globlist[5])\n\n\ndef user():\n return input(\"Which way will you go? \").lower()\n\n\n# Game loop to take you to each location (THIS IS NOT CORRECT YET!)\ndef game_loop():\n while True:\n global globlist\n global Currentlocale\n global score\n usercommand = user()\n if usercommand == \"help\":\n print('''\n Directions: north, south, east, and west.\n Commands: Quit- Exits game. Help: Shows list of commands''')\n elif usercommand == \"quit\":\n break\n elif score == 100 and usercommand in [\"north\", \"south\", \"east\", \"west\"]:\n Currentlocale = globlist[5]\n visitlocation5()\n break\n elif usercommand == \"north\" or usercommand == \"south\" or usercommand == \"east\" or usercommand == \"west\":\n if Currentlocale == globlist[0]:\n if usercommand == \"north\":\n Currentlocale = globlist[1]\n visitlocation1()\n elif usercommand == \"east\":\n Currentlocale = globlist[2]\n visitlocation2()\n else:\n print(\"Uh oh! The door is locked! Chose a different direction.\")\n elif Currentlocale == globlist[1]:\n if usercommand == \"south\":\n Currentlocale = globlist[0]\n visitlocation0()\n elif usercommand == \"west\":\n Currentlocale = globlist[2]\n visitlocation2()\n else:\n print(\"Uh oh! The door is locked! Chose a different direction.\")\n elif Currentlocale == globlist[3]:\n if usercommand == \"north\":\n Currentlocale = globlist[4]\n visitlocation4()\n elif usercommand == \"west\":\n Currentlocale = globlist[2]\n visitlocation2()\n else:\n print(\"Uh oh! The door is locked! Chose a different direction.\")\n elif Currentlocale == globlist[2]:\n if usercommand == \"south\":\n Currentlocale = globlist[4]\n visitlocation4()\n elif usercommand == \"west\":\n Currentlocale = globlist[0]\n visitlocation0()\n else:\n print(\"Uh oh! The door is locked! Chose a different direction.\")\n elif Currentlocale == globlist[4]:\n if usercommand == \"north\":\n Currentlocale = globlist[3]\n visitlocation3()\n elif usercommand == \"west\":\n Currentlocale = globlist[2]\n visitlocation2()\n else:\n print(\"Uh oh! The door is locked! Chose a different direction.\")\n elif Currentlocale == globlist[5]:\n if usercommand == \"south\":\n Currentlocale = globlist[4]\n visitlocation4()\n elif usercommand == \"west\":\n Currentlocale = globlist[3]\n visitlocation3()\n else:\n print(\"Uh oh! The door is locked! Chose a different direction.\")\n\n else:\n print(\"Invalid Choice! Please type in a valid command or type \"\"Help\"\" to show valid commands.\")\n\n\n# Ending of Adventure Game\ndef end():\n Ending = \"You reached the end of this lucid story. Please play again!\"\n print()\n print(Ending)\n crs = '''\n(C) COPYRIGHT STATEMENT: THIS GAME WAS MADE BY JACOB SHAPIRO FEBRUARY 2020.\nNONE OF THIS WORK WAS USED BY ANY OTHER CODE WRITER.\nHad help from father's co-worker'''\n print()\n print(crs)\n\n\ndef main():\n Enter = \"Press enter to continue.\"\n game_custom()\n game_loop()\n end()\n\nmain()","sub_path":"Project 2.py","file_name":"Project 2.py","file_ext":"py","file_size_in_byte":9094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"278878368","text":"import API\nimport sys\n\ndef log(string):\n sys.stderr.write(\"{}\\n\".format(string))\n\ndef main():\n while True:\n if not API.wallLeft():\n log(\"turnLeft\")\n API.turnLeft()\n while API.wallFront():\n log(\"turnRight\")\n API.turnRight()\n log(\"moveForward\")\n API.moveForward()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"17999170","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport time\n\nfrom tempest.lib.cli import base\nfrom tempest.lib.common.utils import data_utils\n\nfrom manilaclient import config\n\nCONF = config.CONF\n\n\nclass OSCClientTestBase(base.ClientTestBase):\n \"\"\"Base class for OSC manila functional tests\"\"\"\n\n def _get_clients(self):\n\n return base.CLIClient(\n username=CONF.admin_username or CONF.username,\n password=CONF.admin_password or CONF.password,\n tenant_name=CONF.admin_tenant_name or CONF.tenant_name,\n uri=CONF.admin_auth_url or CONF.auth_url,\n cli_dir=CONF.manila_exec_dir,\n insecure=CONF.insecure,\n project_domain_name=(CONF.admin_project_domain_name or\n CONF.project_domain_name or None),\n project_domain_id=(CONF.admin_project_domain_id or\n CONF.project_domain_id or None),\n user_domain_name=(CONF.admin_user_domain_name or\n CONF.user_domain_name or None),\n user_domain_id=(CONF.admin_user_domain_id or\n CONF.user_domain_id or None)\n )\n\n def _get_property_from_output(self, output):\n \"\"\"Creates a dictionary from the given output\"\"\"\n obj = {}\n items = self.parser.listing(output)\n for item in items:\n obj[item['Field']] = str(item['Value'])\n return obj\n\n def _wait_for_object_status(self, object_name, object_id, status,\n timeout=CONF.build_timeout,\n interval=CONF.build_interval):\n \"\"\"Waits for a object to reach a given status.\"\"\"\n\n start_time = time.time()\n while time.time() - start_time < timeout:\n if status == self.openstack(\n '%(obj)s show -c status -f value %(id)s'\n % {'obj': object_name,\n 'id': object_id}).rstrip():\n break\n time.sleep(interval)\n else:\n self.fail(\"%s %s did not reach status %s after %d seconds.\"\n % (object_name, object_id, status, timeout))\n\n def check_object_deleted(self, object_name, object_id,\n timeout=CONF.build_timeout,\n interval=CONF.build_interval):\n \"\"\"Check that object deleted successfully\"\"\"\n\n cmd = '%s list -c ID -f value' % object_name\n start_time = time.time()\n while time.time() - start_time < timeout:\n if object_id not in self.openstack(cmd):\n break\n time.sleep(interval)\n else:\n self.fail(\"%s %s not deleted after %d seconds.\"\n % (object_name, object_id, timeout))\n\n def openstack(self, action, flags='', params='', fail_ok=False,\n merge_stderr=False):\n \"\"\"Executes openstack command for given action\"\"\"\n\n if '--os-share-api-version' not in flags:\n flags = (\n flags + '--os-share-api-version %s'\n % CONF.max_api_microversion)\n\n return self.clients.openstack(action, flags=flags, params=params,\n fail_ok=fail_ok,\n merge_stderr=merge_stderr)\n\n def listing_result(self, object_name, command):\n \"\"\"Returns output for the given command as list of dictionaries\"\"\"\n\n output = self.openstack(object_name, params=command)\n result = self.parser.listing(output)\n return result\n\n def dict_result(self, object_name, command):\n \"\"\"Returns output for the given command as dictionary\"\"\"\n\n output = self.openstack(object_name, params=command)\n result_dict = self._get_property_from_output(output)\n return result_dict\n\n def create_share(self, share_protocol=None, size=None, name=None,\n snapshot_id=None, properties=None, share_network=None,\n description=None, public=False, share_type=None,\n availability_zone=None, share_group=None,\n add_cleanup=True):\n\n name = name or data_utils.rand_name('autotest_share_name')\n # share_type = dhss_false until we have implemented\n # share network commands for osc\n share_type = share_type or 'dhss_false'\n\n cmd = ('create '\n '%(protocol)s %(size)s %(name)s %(desc)s %(public)s %(stype)s'\n % {'protocol': share_protocol or 'NFS',\n 'size': size or '1',\n 'name': '--name %s' % name,\n 'desc': '--description %s' % description,\n 'public': '--public %s' % public,\n 'stype': '--share-type %s' % share_type})\n\n if snapshot_id:\n cmd = cmd + ' --snapshot-id %s' % snapshot_id\n if properties:\n for key, value in properties.items():\n cmd = (cmd + ' --property %(key)s=%(value)s'\n % {'key': key, 'value': value})\n if share_network:\n cmd = cmd + ' --share-network %s' % share_network\n if availability_zone:\n cmd = cmd + ' --availability-zone %s' % availability_zone\n if share_group:\n cmd = cmd + ' --share-group %s' % share_group\n\n share_object = self.dict_result('share', cmd)\n self._wait_for_object_status(\n 'share', share_object['id'], 'available')\n\n if add_cleanup:\n self.addCleanup(\n self.openstack, 'share delete %s' % share_object['id']\n )\n return share_object\n","sub_path":"manilaclient/tests/functional/osc/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"291644095","text":"import tarfile, os\nfrom pandas import read_excel\nfrom mpcontribs.io.archieml.mpfile import MPFile\nfrom mpcontribs.io.core.recdict import RecursiveDict\nfrom mpcontribs.io.core.utils import clean_value\nfrom mpcontribs.users.utils import unflatten\nimport numpy as np\n\nproject = \"transparent_conductors\"\n\nfrom pymongo import MongoClient\n\nclient = MongoClient(\"mongodb+srv://\" + os.environ[\"MPCONTRIBS_MONGO_HOST\"])\ndb = client[\"mpcontribs\"]\nprint(db.contributions.count_documents({\"project\": project}))\n\n\ndef run(mpfile, sheet_name):\n\n google_sheet = \"https://docs.google.com/spreadsheets/d/1bgQAdSfyrPEDI4iljwWlkyUPt_mo84jWr4N_1DKQDUI/export?format=xlsx\"\n df = read_excel(google_sheet, sheet_name=sheet_name, header=[0, 1, 2])\n\n doping = sheet_name.split(\" \")[0]\n done = False\n for row in df.to_dict(orient=\"records\"):\n identifier = None\n data = RecursiveDict({\"doping\": doping})\n for keys, value in row.items():\n key = \".\".join(\n [\n k.replace(\"TC\", \"\").strip()\n for k in keys\n if not k.startswith(\"Unnamed:\")\n ]\n )\n if key.endswith(\"experimental doping type\"):\n key = key.replace(\"Transport.\", \"\")\n key_split = key.split(\".\")\n if len(key_split) > 2:\n key = \".\".join(key_split[1:])\n if key.endswith(\"MP link\") or key.endswith(\"range\"):\n continue\n if key.endswith(\"google scholar\"):\n key = key.replace(\".google scholar\", \"\")\n if key == \"Material.mpid\":\n if identifier is None:\n if not isinstance(value, str) and np.isnan(value):\n done = True\n break\n identifier = value.strip()\n print(identifier)\n else:\n if key == \"Material.p pretty formula\":\n key = \"formula\"\n if isinstance(value, str):\n val = value.strip()\n else:\n if isinstance(value, float) and np.isnan(value):\n continue\n if key.endswith(\")\"):\n key, unit = key.rsplit(\" (\", 1)\n unit = unit[:-1].replace(\"^-3\", \"⁻³\").replace(\"^20\", \"²⁰\")\n if \",\" in unit:\n extra_key = key.rsplit(\".\", 1)[0].lower() + \".conditions\"\n data[extra_key] = unit\n unit = \"\"\n val = clean_value(value, unit=unit)\n else:\n val = clean_value(value)\n if not val:\n continue\n clean_key = key.replace(\" for VB:CB = 4:2\", \"\").replace(\"?\", \"\").lower()\n data[clean_key] = val\n\n if done:\n break\n mpfile.add_hierarchical_data({\"data\": unflatten(data)}, identifier=identifier)\n\n\nfor sheet_name in [\"n-type TCs\", \"p-type TCs\"]:\n doping = sheet_name.split(\" \")[0]\n mpfile = MPFile()\n mpfile.max_contribs = 50\n run(mpfile, sheet_name)\n filename = f\"transparent_conductors_{doping}.txt\"\n mpfile.write_file(filename=filename)\n mpfile = MPFile.from_file(filename)\n print(len(mpfile.ids))\n\n for idx, (identifier, content) in enumerate(mpfile.document.items()):\n doc = {\"identifier\": identifier, \"project\": project, \"content\": {}}\n doc[\"content\"][\"data\"] = content[\"data\"]\n doc[\"collaborators\"] = [{\"name\": \"Patrick Huck\", \"email\": \"phuck@lbl.gov\"}]\n r = db.contributions.insert_one(doc)\n cid = r.inserted_id\n print(idx, \":\", cid)\n","sub_path":"mpcontribs-portal/mpcontribs/users/transparent_conductors/pre_submission.py","file_name":"pre_submission.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"434326205","text":"import httplib2\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.file import Storage\nfrom apiclient.discovery import build\n\nstorage = Storage('/mashupdoc/credentials')\n\nflow = flow_from_clientsecrets('/mashupdoc/client_secret.json', scope = 'https://www.googleapis.com/auth/calendar.readonly https://spreadsheets.google.com/feeds https://docs.google.com/feeds', redirect_uri = 'http://www.mashupforpi.com/auth_return')\n\nauth_uri = flow.step1_get_authorize_url()\n\ndef exchange_credentials(x):\n credentials = flow.step2_exchange(x)\n return credentials\n\ndef save_credentials(x):\n global storage\n storage.put(x)\n\ndef get_credentials():\n global storage\n credentials = storage.get()\n return credentials\n\ndef get_authorized_service():\n credentials = get_credentials() \n http = httplib2.Http()\n http = credentials.authorize(http)\n service = build('calendar', 'v3', http = http)\n return service\n","sub_path":"mashup/GOAuth2.py","file_name":"GOAuth2.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"75883362","text":"#define the board 0 fot empty spaces\nboard = [\n [ 3, 1, 6, 5, 7, 8, 0, 9, 2 ],\n [ 5, 2, 9, 0, 3, 4, 0, 6, 8 ],\n [ 4, 0, 7, 6, 2, 0, 5, 3, 1 ],\n [ 2, 6, 3, 0, 0, 0, 9, 8, 7 ],\n [ 9, 7, 0, 8, 0, 0, 1, 0, 0 ],\n [ 8, 5, 0, 7, 9, 2, 0, 0, 3 ],\n [ 1, 3, 8, 0, 4, 7, 0, 0, 6 ],\n [ 6, 0, 2, 3, 0, 1, 8, 7, 4 ],\n [ 7, 4, 5, 0, 8, 6, 3, 1, 0 ]\n]\n\n#solve board function using recursion\ndef solveSuduku(brd):\n empty = getEmpty(brd)\n if not empty:\n return True\n else:\n row, col = empty\n\n for i in range(1, 10):\n if isValid(brd, i, (row, col)):\n brd[row][col] = i\n\n if solveSuduku(brd):\n return True\n\n brd[row][col] = 0\n\n return False\n\n\n#print suduku board\ndef printBoard(brd):\n for i in range(len(brd)):\n if i % 3 == 0 and i != 0:\n print(\"ـــــــــــــــــــــــ\")\n\n for j in range(len(brd[0])):\n if j % 3 == 0 and j != 0:\n print(\" | \", end = \"\")\n\n if j == 8:\n print(brd[i][j])\n\n else:\n print(str(brd[i][j]) + \" \", end = \"\")\n\n\n#find empty spaces in the board\ndef getEmpty(brd):\n for i in range(len(brd)):\n for j in range(len(brd[0])):\n if brd[i][j] == 0:\n return (i, j) #return row and column\n return None\n\n\n#check if valid\ndef isValid(brd, num, position):\n \n #check row\n for i in range(len(brd[0])):\n if brd[position[0]][i] == num and position[1] != i:\n return False\n #check column \n for i in range(len(brd)):\n if brd[i][position[1]] == num and position[0] != i:\n return False\n\n #check squares\n horizontalSquare = position[1] // 3\n verticalSquare = position [0] // 3\n\n for i in range(verticalSquare*3, verticalSquare*3 + 3):\n for j in range(horizontalSquare*3, horizontalSquare*3 + 3):\n if brd[i][j] == num and (i, j) != position:\n return False\n \n return True\n\n\n\n#print the solution\nprint(\"Board Before Solving: \")\nprintBoard(board)\nsolveSuduku(board)\nprint(\"Board After Solving: \")\nprintBoard(board)","sub_path":"SudukuSolver.py","file_name":"SudukuSolver.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"520075270","text":"# $Id: Parameter.py,v 1.1.1.1 2008/04/20 15:03:22 elwinter Exp $\n\n#******************************************************************************\n\n# Import external modules.\n\n# Standard modules.\nimport xml.dom.minidom\n\n# Third-party modules.\n\n# Project modules.\nfrom Element import Element\n\n#******************************************************************************\n\nclass Parameter(Element):\n \"\"\"Parameter class to represent elements in ModelEditor.\n\n Data attributes:\n\n _name: (string) Name of the Parameter. Corresponds to the 'name'\n attribute of the element.\n\n _value: (float) Value of the Parameter. Corresponds to the 'value'\n attribute of the element.\n\n _scale: (float) Scale factor for the Parameter value. Corresponds\n to the 'scale' attribute of the element.\n\n _min: (float) Minimum valid value of the Parameter. If None, no\n minimum checking is performed. Corresponds to the 'min' attribute\n of the element.\n\n _max: (float) Maximum valid value of the Parameter. If None, no\n maximum checking is performed. Corresponds to the 'max' attribute\n of the element.\n\n _free: (Boolean) True if the Parameter value can be adjusted by\n the likelihood estimator, False otherwise. Corresponds to the\n 'free' attribute of the element.\n \"\"\"\n\n #--------------------------------------------------------------------------\n\n # Class constants\n\n # Define the tag name.\n _tagName = 'parameter'\n\n # Define the attribute names and default values.\n _defaults = {\n 'name' : 'parameter',\n 'value': 0.0,\n 'scale': 1.0,\n 'min' : None,\n 'max' : None,\n 'free' : False\n }\n\n # The list of field names is used by the ParameterEditor to create\n # field labels. These strings must be explicitly listed since the\n # keys() method used on the _defaults dictionary returns the\n # strings in an unpredictable order.\n _fieldNames = ['name', 'value', 'scale', 'min', 'max', 'free']\n\n #--------------------------------------------------------------------------\n\n def __init__(self,\n name = _defaults['name'],\n value = _defaults['value'],\n scale = _defaults['scale'],\n min = _defaults['min'],\n max = _defaults['max'],\n free = _defaults['free'],\n dom = None,\n *args, **kwargs):\n \"\"\"Initialize this Parameter.\n\n Parameters:\n\n self: This object.\n\n name: (string) Name of the Parameter.\n\n value: (float) Value of the Parameter.\n\n scale: (float) Scale factor for the Parameter value.\n\n min: (float) Minimum valid value of the Parameter. If None, no\n minimum checking is performed.\n\n max: (float) Maximum valid value of the Parameter. If None, no\n maximum checking is performed.\n\n free: (Boolean) True if the Parameter value can be adjusted by\n the likelihood estimator, False otherwise.\n\n dom (xml.dom.minidom.Element): DOM element to convert to this\n Parameter. If this parameter is specified, the other\n parameters are ignored.\n\n Return value:\n\n None.\n\n Description:\n\n Initialize this Parameter. All data attributes are set from\n the corresponding parameters. If a DOM element is provided,\n use the attribute nodes of that DOM element to set the data\n attributes of this Parameter.\n \"\"\"\n\n # Initialize the parent class. Do not pass the dom parameter,\n # since it will be used if needed when fromDom() is called\n # below.\n Element.__init__(self, Parameter._tagName, *args, **kwargs)\n\n # Set attributes.\n if dom:\n if isinstance(dom, xml.dom.minidom.Element):\n self.fromDom(dom)\n else:\n raise TypeError('Not a DOM element (%s)!' % dom)\n else:\n self.setName(name)\n self.setMin(min) # Set min, max before value to allow\n self.setMax(max) # range checking when setValue() is called.\n self.setValue(value)\n self.setScale(scale)\n self.setFree(free)\n\n #--------------------------------------------------------------------------\n\n def toDom(self, domDocument = None):\n \"\"\"Convert this Parameter to a xml.dom.minidom.Element.\n\n Parameters:\n\n self: This object.\n\n domDocument (xml.dom.minidom.Document): DOM document to use\n when converting this Parameter.\n\n Return value:\n\n xml.dom.minidom.Element for this Parameter.\n\n Description:\n\n Convert this Parameter to an equivalent\n xml.dom.minidom.Element in the specified DOM document. After\n the DOM element is created by the inherited toDom() method,\n the attribute nodes are set using the data attributes of this\n Parameter.\n \"\"\"\n\n # Call the inherited method.\n dom = Element.toDom(self, domDocument)\n\n # name\n dom.setAttribute('name', str(self.getName()))\n\n # value\n dom.setAttribute('value', str(self.getValue()))\n\n # scale\n dom.setAttribute('scale', str(self.getScale()))\n\n # min (skip if None)\n min = self.getMin()\n if min is not None:\n dom.setAttribute('min', str(min))\n\n # max (skip if None)\n max = self.getMax()\n if max is not None:\n dom.setAttribute('max', str(max))\n\n # free (map to XML boolean strings)\n free = self.getFree()\n free = self.booleanToXMLBoolean(free)\n dom.setAttribute('free', free)\n\n # Return the new DOM element.\n return dom\n\n def fromDom(self, dom):\n \"\"\"Initialize this Parameter from a xml.dom.minidom.Element.\n\n Parameters:\n\n self: This object.\n\n dom (xml.dom.minidom.Element): DOM element to use when\n initializing this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Use the specified DOM element as the source of the content of\n this Parameter. Set all data attributes using the\n corresponding attribute nodes of the DOM element.\n \"\"\"\n\n # Call the inherited method.\n Element.fromDom(self, dom)\n\n # name\n self.setName(dom.getAttribute('name'))\n\n # min (map empty string to None)\n min = dom.getAttribute('min')\n if min == '':\n min = None\n self.setMin(min)\n\n # max (map empty string to None)\n max = dom.getAttribute('max')\n if max == '':\n max = None\n self.setMax(max)\n\n # value (min and max set above to allow range checking).\n self.setValue(dom.getAttribute('value'))\n\n # scale\n self.setScale(dom.getAttribute('scale'))\n\n # free (map XML boolean string to True/False).\n free = dom.getAttribute('free')\n free = self.xmlBooleanToBoolean(free)\n self.setFree(free)\n\n #--------------------------------------------------------------------------\n\n def getName(self):\n \"\"\"Return the name for this Parameter.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n String containing the name for this Parameter.\n\n Description:\n\n Return the name of this Parameter.\n \"\"\"\n return self._name\n\n def setName(self, name):\n \"\"\"Set the name for this Parameter.\n\n Parameters:\n\n self: This object.\n\n name (string): New name for this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Set the name of this Parameter to the specified string. If the\n new name is invalid, raise a TypeError exception.\n \"\"\"\n if not self.validName(name):\n raise TypeError('Invalid Parameter name (%s)!' % name)\n self._name = str(name)\n\n def validName(self, name):\n \"\"\"Check a Parameter name for validity.\n\n Parameters:\n\n self: This object.\n\n name (string): Proposed name for this Parameter.\n\n Return value:\n\n True if the name is valid, otherwise False.\n\n Description:\n\n Check if the proposed new name is valid. A name is valid if\n evaluates to a non-empty string.\n \"\"\"\n if name is None:\n return False # str(None) = 'None'\n try:\n name = str(name)\n except(TypeError):\n return False\n if name == '':\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def getValue(self):\n \"\"\"Return the value for this Parameter.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n Float containing the value for this Parameter.\n\n Description:\n\n Return the value of this Parameter.\n \"\"\"\n return self._value\n\n def setValue(self, value):\n \"\"\"Set the value for this Parameter.\n\n Parameters:\n\n self: This object.\n\n value (float): New value for this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Set the value of this Parameter to the specified value. If the\n new value is invalid, raise a TypeError exception.\n \"\"\"\n if not self.validValue(value):\n raise TypeError('Invalid Parameter value (%s)!' % value)\n self._value = float(value)\n\n def validValue(self, value):\n \"\"\"Check a Parameter value for validity.\n\n Parameters:\n\n self: This object.\n\n value (float): Proposed value for this Parameter.\n\n Return value:\n\n True if the value is valid, otherwise False.\n\n Description:\n\n Return True if the value is valid, False otherwise. A value is\n valid if it evaluates to a float, and is within range of any\n existing limits.\n \"\"\"\n try:\n value = float(value)\n except:\n return False\n min = self.getMin()\n if min is not None and value < min:\n return False\n max = self.getMax()\n if max is not None and value > max:\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def getScale(self):\n \"\"\"Return the scale for this Parameter.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n Float containing the scale for this Parameter.\n\n Description:\n\n Return the scale of this Parameter.\n \"\"\"\n return self._scale\n\n def setScale(self, scale):\n \"\"\"Set the scale for this Parameter.\n\n Parameters:\n\n self: This object.\n\n scale (float): New scale for this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Set the scale of this Parameter to the specified value. If the\n new scale is invalid, raise a TypeError exception.\n \"\"\"\n if not self.validScale(scale):\n raise TypeError('Invalid Parameter scale (%s)!' % scale)\n self._scale = float(scale)\n\n def validScale(self, scale):\n \"\"\"Check a Parameter scale for validity.\n\n Parameters:\n\n self: This object.\n\n scale (float): Proposed scale for this Parameter.\n\n Return value:\n\n True if the value is valid, otherwise False.\n\n Description:\n\n Return True if the scale is valid, False otherwise. A scale is\n valid if it evaluates to a float.\n \"\"\"\n try:\n scale = float(scale)\n except:\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def getMin(self):\n \"\"\"Return the min for this Parameter.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n Float containing the min for this Parameter, or None if the\n min has not been set.\n\n Description:\n\n Return the min of this Parameter. If the min has not been set\n yet, return None.\n \"\"\"\n if hasattr(self, '_min'):\n return self._min\n else:\n return None\n\n def setMin(self, min):\n \"\"\"Set the min for this Parameter.\n\n Parameters:\n\n self: This object.\n\n min (float): New min for this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Set the min of this Parameter to the specified value. If the\n new min is invalid, raise a TypeError exception.\n \"\"\"\n if not self.validMin(min):\n raise TypeError('Invalid Parameter min (%s)!' % min)\n if min is not None:\n min = float(min)\n self._min = min\n\n def validMin(self, min):\n \"\"\"Check a Parameter min for validity.\n\n Parameters:\n\n self: This object.\n\n min (float): Proposed min for this Parameter.\n\n Return value:\n\n True if the min is valid, otherwise False.\n\n Description:\n\n Return True if the min is valid, False otherwise. A min is\n valid if it is None or evaluates to a float and is less than\n or equal to any existing max.\n \"\"\"\n if min is None:\n return True\n try:\n min = float(min)\n except:\n return False\n max = self.getMax()\n if max is not None and min > max:\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def getMax(self):\n \"\"\"Return the max for this Parameter.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n Float containing the max for this Parameter, or None if the\n max has not been set yet.\n\n Description:\n\n Return the max of this Parameter. If the max has not been set\n yet, return None.\n \"\"\"\n if hasattr(self, '_max'):\n return self._max\n else:\n return None\n\n def setMax(self, max):\n \"\"\"Set the max for this Parameter.\n\n Parameters:\n\n self: This object.\n\n max (float): New max for this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Set the max of this Parameter to the specified value. If the\n new max is invalid, raise a TypeError exception.\n \"\"\"\n if not self.validMax(max):\n raise TypeError('Invalid Parameter max (%s)!' % max)\n if max is not None:\n max = float(max)\n self._max = max\n\n def validMax(self, max):\n \"\"\"Check a Parameter max for validity.\n\n Parameters:\n\n self: This object.\n\n max (float): Proposed max for this Parameter.\n\n Return value:\n\n True if the max is valid, otherwise False.\n\n Description:\n\n Return True if the max is valid, False otherwise. A max is\n valid if it is None or evaluates to a float and is greater\n than or equal to any existing min.\n \"\"\"\n if max is None:\n return True\n try:\n max = float(max)\n except:\n return False\n min = self.getMin()\n if min is not None and max < min:\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def getFree(self):\n \"\"\"Return the free for this Parameter.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n Bool containing the free for this Parameter.\n\n Description:\n\n Return the free of this Parameter.\n \"\"\"\n return self._free\n\n def setFree(self, free):\n \"\"\"Set the free for this Parameter.\n\n Parameters:\n\n self: This object.\n\n free (bool): New free for this Parameter.\n\n Return value:\n\n None.\n\n Description:\n\n Set the free of this Parameter to the specified value. If the\n new free is invalid, raise a TypeError exception.\n \"\"\"\n if not self.validFree(free):\n raise TypeError('Invalid Parameter free (%s)!' % free)\n self._free = bool(free)\n\n def validFree(self, free):\n \"\"\"Check a Parameter free for validity.\n\n Parameters:\n\n self: This object.\n\n free (bool): Proposed free for this Parameter.\n\n Return value:\n\n True if the free is valid, otherwise False.\n\n Description:\n\n Return True if the free is valid, False otherwise. A free is\n valid if it evaluates to True or False.\n \"\"\"\n try:\n free = bool(free)\n except:\n return False\n return True\n\n#******************************************************************************\n\n# Self-test code.\n\n# If this code generates any output, an error has been found.\n\nif __name__ == '__main__':\n\n # Default constructor.\n parameter = Parameter()\n assert str(parameter) == 'Parameter(_free=False,_max=None,_min=None,_name=parameter,_scale=1.0,_tagName=parameter,_value=0.0)'\n \n # Constructor with attribute values.\n parameter = Parameter(name = 'test', value = 1.0, scale = 2.0,\n min = 0.0, max = 10.0, free = True)\n assert str(parameter) == 'Parameter(_free=True,_max=10.0,_min=0.0,_name=test,_scale=2.0,_tagName=parameter,_value=1.0)'\n\n # Convert to/from DOM object, and check the '==' and '!='\n # operators.\n domDocument = xml.dom.minidom.Document()\n dom = parameter.toDom(domDocument)\n parameterCopy = Parameter(dom = dom)\n assert parameterCopy == parameter\n assert not (parameterCopy != parameter)\n","sub_path":"Parameter.py","file_name":"Parameter.py","file_ext":"py","file_size_in_byte":17781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"261269235","text":"# -*- coding: utf-8 -*-\nfrom djangosanetesting import UnitTestCase, DatabaseTestCase\n\nfrom django.contrib.sites.models import Site\nfrom django.template import TemplateSyntaxError\n\nfrom ella.core.models import Category, Publishable\nfrom ella.core.templatetags.core import _parse_box, BoxNode, EmptyNode\nfrom ella.core.box import Box\nfrom ella.articles.models import Article\n\nfrom unit_project.test_core import create_basic_categories, create_and_place_a_publishable\n\nclass TestBoxTagParser(UnitTestCase):\n def test_parse_box_with_pk(self):\n node = _parse_box([], ['box', 'box_type', 'for', 'core.category', 'with', 'pk', '1'])\n self.assert_true(isinstance(node, BoxNode))\n self.assert_equals('box_type', node.box_type)\n self.assert_equals(Category, node.model)\n self.assert_equals(('pk', '1'), node.lookup)\n\n def test_parse_box_for_varname(self):\n node = _parse_box([], ['box', 'other_box_type', 'for', 'var_name'])\n self.assert_true(isinstance(node, BoxNode))\n self.assert_equals('other_box_type', node.box_type)\n self.assert_equals('var_name', node.var_name)\n\n def test_parse_box_with_slug(self):\n node = _parse_box([], ['box', 'box_type', 'for', 'sites.site', 'with', 'slug', '\"home\"'])\n self.assert_true(isinstance(node, BoxNode))\n self.assert_equals('box_type', node.box_type)\n self.assert_equals(Site, node.model)\n self.assert_equals(('slug', '\"home\"'), node.lookup)\n\n def test_parse_raises_on_too_many_arguments(self):\n self.assert_raises(TemplateSyntaxError, _parse_box, [], ['box', 'box_type', 'for', 'core.category', 'with', 'pk', '1', '2', 'extra'])\n\n def test_parse_raises_on_too_few_arguments(self):\n self.assert_raises(TemplateSyntaxError, _parse_box, [], ['box', 'box_type', 'for'])\n\n def test_parse_raises_on_incorrect_arguments(self):\n self.assert_raises(TemplateSyntaxError, _parse_box, [], ['box', 'box_type', 'not a for', 'core.category', 'with', 'pk', '1'])\n\n def test_parse_return_empty_node_on_incorrect_model(self):\n node = _parse_box([], ['box', 'box_type', 'for', 'not_app.not_model', 'with', 'pk', '1'])\n self.assert_true(isinstance(node, EmptyNode))\n\nclass ArticleBox(Box):\n pass\n\nclass TestPublishableBox(DatabaseTestCase):\n def setUp(self):\n super(TestPublishableBox, self).setUp()\n create_basic_categories(self)\n create_and_place_a_publishable(self)\n\n def test_box_template_path_contains_correct_content_type(self):\n publishable = Publishable.objects.get(pk=self.publishable.pk)\n article = publishable.target\n\n box_publishable = publishable.box_class(publishable, 'box_type', [])\n box_article = Box(article, 'box_type', [])\n\n template_list = [\n 'box/category/nested-category/content_type/articles.article/first-article/box_type.html',\n 'box/category/nested-category/content_type/articles.article/box_type.html',\n 'box/category/nested-category/content_type/articles.article/box.html',\n 'box/content_type/articles.article/first-article/box_type.html',\n 'box/content_type/articles.article/box_type.html',\n 'box/content_type/articles.article/box.html',\n 'box/box_type.html',\n 'box/box.html',\n ]\n\n self.assert_equals(template_list, box_publishable._get_template_list())\n self.assert_equals(template_list, box_article._get_template_list())\n\n def test_box_class_is_specific_to_subclass(self):\n publishable = Publishable.objects.get(pk=self.publishable.pk)\n Article.box_class = ArticleBox\n box = publishable.box_class(publishable, 'box_type', [])\n self.assert_equals(ArticleBox, box.__class__)\n\n","sub_path":"tests/unit_project/test_core/test_boxes.py","file_name":"test_boxes.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"393739191","text":"from simp_py import tft,lcd\nfrom random import seed, uniform\nimport time\nfrom machine import Pin\nfrom button import Button\n\nseed(int(time.time()))\n\nclass FOOD:\n global lcd\n def __init__(self):\n self.pos=[10,20]\n\n def new(self,trunk):\n x = round(uniform(1,30))\n y = round(uniform(1,20))\n while True:\n if [x,y] in trunk:\n x = round(uniform(1,30))\n y = round(uniform(1,20))\n else:\n break\n self.pos=[x,y]\n lcd.text(x*10,y*10,'*') \n\n def is_catch(self,x,y):\n if self.pos==[x,y]:\n return True\n \nclass SNAKE:\n global lcd,tft,uniform,food\n def __init__(self):\n self.trunk=[[4,10],[4,9],[4,8]]\n self.dirx=0\n self.diry=1\n food.new(self.trunk)\n self.draw()\n \n def draw(self):\n for x,y in self.trunk:\n lcd.text(x*10,y*10,'#')\n\n def go_dir(self,x,y):\n x+= self.dirx\n if x*10 > 320:\n x=0\n if x<0:\n x=32\n y+= self.diry\n if y*10 > 240:\n y=0\n if y<0:\n y=24\n \n return x,y\n\n def go_left(self):\n self.dirx=-1\n self.diry=0\n \n def go_right(self):\n self.dirx=1\n self.diry=0\n \n def go_down(self):\n self.diry=1\n self.dirx=0\n\n def go_up(self):\n self.diry=-1\n self.dirx=0\n \n def go(self):\n xt,yt = self.trunk.pop()\n lcd.textClear(xt*10,yt*10,'#')\n x,y = self.trunk[0]\n x,y = self.go_dir(x,y)\n self.trunk.insert(0,[x,y])\n if food.is_catch(x,y):\n self.trunk.append([xt,yt])\n food.new(self.trunk)\n self.draw()\n \nif __name__=='__main__':\n lcd.clear()\n food = FOOD()\n snake=SNAKE()\n \n def Apressed(v):\n global snake,tft\n print('Apressed')\n snake.go_left()\n \n def Bpressed(v):\n global snake,tft\n print('Bpressed')\n tft.on()\n if snake.diry==0:\n snake.go_up()\n else:\n if snake.diry==1:\n snake.go_up()\n else:\n snake.go_down()\n \n def Cpressed(v):\n global snake,btnA\n print('Cpressed')\n if btnA.isPressed():\n tft.off()\n snake.go_right()\n \n btnA = Button(39,Apressed,trigger=Pin.IRQ_FALLING)\n btnB = Button(38,Bpressed, trigger=Pin.IRQ_FALLING)\n btnC = Button(37,Cpressed, trigger=Pin.IRQ_FALLING)\n\n while True:\n time.sleep(0.2)\n snake.go()\n","sub_path":"simp_py_examples/course/S1806_2/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"211872784","text":"__author__ = 'Yikou'\n\ndef mymap(func, *seqs):\n return [ func(*args) for args in zip(*seqs)]\n\n# yield版本(生成器表达式)\ndef mymap2(func, *seqs):\n res = []\n for args in zip(*seqs):\n yield func(*args)\n\ndef myzip(*seqs):\n seqs = [list(S) for S in seqs]\n while all(seqs):\n yield tuple(S.pop(0) for S in seqs)\n\ndef mymapPad(*seqs, pad = None):\n seqs = [list(S) for S in seqs]\n while any(seqs):\n yield tuple((S.pop(0) if S else pad) for S in seqs)\n\n#不使用pop而是使用数组长度进行拼接\ndef mymapPad2(*seqs, pad=None):\n return [tuple((S[i] if len(S) > i else pad) for S in seqs) for i in range(max(len(S) for S in seqs))]\n\n#python3.0中会引起无限循环\ndef myzip3(*args):\n iters = map(iter, args)\n while iters:\n res = [next(i) for i in iters]\n yield tuple(res)\n\nif __name__ == '__main__':\n print(mymap(abs, [-2, -1, 0, 1, 2]))\n print(list(mymap2(abs, [-2, -1, 0, 1, 2])))\n print(mymap(pow, [1, 2, 3], [2, 3, 4, 5]))\n print(list(mymap2(pow, [1, 2, 3], [2, 3, 4, 5])))\n\n S1, S2 = 'abc', 'xyz123'\n print(list(myzip(S1, S2)))\n print(list(mymapPad(S1, S2, pad=99)))\n print(mymapPad2(S2, S1, pad=1945))\n\n # print(list(myzip3('abc', 'lmnop')))\n print(\"finished\")","sub_path":"01.Python学习手册/第20章 迭代和解析/mymap.py","file_name":"mymap.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"525803120","text":"import musdb\nimport museval\nimport functools\nimport argparse\n\n\ndef MIX(track, eval_dir=None):\n \"\"\"Mixture as Estimate\n \"\"\"\n\n # perform separtion\n estimates = {}\n for name, target in track.sources.items():\n # set accompaniment source\n estimates[name] = track.audio / len(track.sources)\n\n estimates['accompaniment'] = estimates['bass'] + \\\n estimates['drums'] + estimates['other']\n\n if eval_dir is not None:\n museval.eval_mus_track(\n track,\n estimates,\n output_dir=eval_dir,\n )\n\n return estimates\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Evaluate Mixture as Estimate'\n )\n parser.add_argument(\n '--audio_dir',\n nargs='?',\n help='Folder where audio results are saved'\n )\n\n parser.add_argument(\n '--eval_dir',\n nargs='?',\n help='Folder where evaluation results are saved'\n )\n\n args = parser.parse_args()\n\n # initiate musdb\n mus = musdb.DB()\n\n mus.run(\n functools.partial(\n MIX, eval_dir=args.eval_dir\n ),\n estimates_dir=args.audio_dir,\n subsets='test',\n parallel=True,\n cpus=2\n )\n","sub_path":"MIX.py","file_name":"MIX.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"568121752","text":"import sys\nimport math\n\n\nclass jhpbar:\n def __init__(self, steps, size=20, prefix='', postfix='', color=0):\n self.size = size\n self.steps = steps\n self.update_step = self.steps / self.size\n self.count = 0\n self.progress_bar_origin = '-' * size\n self.progress_bar = self.progress_bar_origin\n self.progress = 1\n self.prefix = prefix\n self.postfix = postfix\n self.result = self.prefix + ' ' + self.progress_bar + ' ' + self.postfix\n\n self.font_color_end = '\\033[0m'\n self.font_color = ''\n if color == 0:\n self.font_color = ''\n elif color == 1: # red\n self.font_color = '\\033[31m'\n elif color == 2: # green\n self.font_color = '\\033[32m'\n elif color == 3: # blue\n self.font_color = '\\033[34m'\n\n def update(self, count=1, prefix='', postfix=''):\n self.count += count\n if prefix != '':\n self.prefix = prefix\n if postfix != '':\n self.postfix = postfix\n self.progress = math.ceil(self.count / self.update_step)\n\n self.progress_bar = self.progress_bar_origin.replace('-', '▉', self.progress)\n\n self.result = f'{self.font_color}{self.prefix} {self.progress_bar} {self.postfix}{self.font_color_end}'\n sys.stdout.write('\\r' + self.result)\n sys.stdout.flush()\n if self.count == self.steps:\n print()\n\n def reset(self, progress=1, prefix='', postfix=''):\n self.progress = progress\n self.count = 0\n self.progress_bar = '-' * self.size\n\n if prefix != '':\n self.prefix = prefix\n if postfix != '':\n self.postfix = postfix\n\n self.result = self.prefix + ' ' + self.progress_bar + ' ' + self.postfix\n","sub_path":"pbar.py","file_name":"pbar.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"599737927","text":"import numpy as np\n\n#\n# Base Configuration Class \nclass ConfigMaskrcnn(object):\n \"\"\"Base configuration class. For custom configurations, create a\n sub-class that inherits from this one and override properties\n that need to be changed.\n \"\"\"\n def __init__(self, json_config):\n super(ConfigMaskrcnn, self).__init__()\n self.GPU_COUNT = json_config['GPU_COUNT']\n self.IMAGES_PER_GPU = json_config['IMAGES_PER_GPU']\n self.NUM_CLASSES = json_config['NUM_CLASSES']\n\n self.STEPS_PER_EPOCH = json_config['STEPS_PER_EPOCH']\n self.VALIDATION_STEPS = json_config['VALIDATION_STEPS']\n self.BACKBONE = json_config['BACKBONE']\n self.COMPUTE_BACKBONE_SHAPE = json_config['COMPUTE_BACKBONE_SHAPE']\n self.BACKBONE_STRIDES = json_config['BACKBONE_STRIDES']\n self.FPN_CLASSIF_FC_LAYERS_SIZE =json_config['FPN_CLASSIF_FC_LAYERS_SIZE']\n self.TOP_DOWN_PYRAMID_SIZE = json_config['TOP_DOWN_PYRAMID_SIZE']\n self.RPN_ANCHOR_SCALES = (\n json_config['RPN_ANCHOR_SCALES'][0],\n json_config['RPN_ANCHOR_SCALES'][1],\n json_config['RPN_ANCHOR_SCALES'][2],\n json_config['RPN_ANCHOR_SCALES'][3],\n json_config['RPN_ANCHOR_SCALES'][4])\n self.RPN_ANCHOR_RATIOS = json_config['RPN_ANCHOR_RATIOS']\n self.RPN_ANCHOR_STRIDE = json_config['RPN_ANCHOR_STRIDE']\n self.RPN_NMS_THRESHOLD = json_config['RPN_NMS_THRESHOLD']\n self.RPN_TRAIN_ANCHORS_PER_IMAGE = json_config['RPN_TRAIN_ANCHORS_PER_IMAGE']\n self.PRE_NMS_LIMIT = json_config['PRE_NMS_LIMIT']\n self.POST_NMS_ROIS_TRAINING = json_config['POST_NMS_ROIS_TRAINING']\n self.POST_NMS_ROIS_INFERENCE = json_config['POST_NMS_ROIS_INFERENCE']\n self.USE_MINI_MASK = json_config['USE_MINI_MASK']\n self.MINI_MASK_SHAPE = (json_config['MINI_MASK_SHAPE'][0],json_config['MINI_MASK_SHAPE'][1])\n self.IMAGE_RESIZE_MODE = json_config['IMAGE_RESIZE_MODE']\n self.IMAGE_MIN_DIM = json_config['IMAGE_MIN_DIM']\n self.IMAGE_MAX_DIM = json_config['IMAGE_MAX_DIM']\n self.IMAGE_MIN_SCALE = json_config['IMAGE_MIN_SCALE']\n self.IMAGE_CHANNEL_COUNT = json_config['IMAGE_CHANNEL_COUNT']\n self.MEAN_PIXEL = np.array(json_config['MEAN_PIXEL'])\n self.TRAIN_ROIS_PER_IMAGE = json_config['TRAIN_ROIS_PER_IMAGE']\n self.ROI_POSITIVE_RATIO = json_config['ROI_POSITIVE_RATIO']\n self.POOL_SIZE = json_config['POOL_SIZE']\n self.MASK_POOL_SIZE = json_config['MASK_POOL_SIZE']\n self.MASK_SHAPE = json_config['MASK_SHAPE']\n self.MAX_GT_INSTANCES = json_config['MAX_GT_INSTANCES']\n self.RPN_BBOX_STD_DEV = np.array(json_config['RPN_BBOX_STD_DEV'])\n self.BBOX_STD_DEV = np.array(json_config['BBOX_STD_DEV'])\n self.DETECTION_MAX_INSTANCES = json_config['DETECTION_MAX_INSTANCES']\n self.DETECTION_MIN_CONFIDENCE = json_config['DETECTION_MIN_CONFIDENCE']\n self.DETECTION_NMS_THRESHOLD =json_config['DETECTION_NMS_THRESHOLD']\n self.LEARNING_RATE = json_config['LEARNING_RATE']\n self.LEARNING_MOMENTUM = json_config['LEARNING_MOMENTUM']\n self.WEIGHT_DECAY =json_config['WEIGHT_DECAY']\n self.LOSS_WEIGHTS = json_config['LOSS_WEIGHTS']\n self.USE_RPN_ROIS = json_config['USE_RPN_ROIS']\n self.TRAIN_BN = json_config['TRAIN_BN']\n self.GRADIENT_CLIP_NORM = json_config['GRADIENT_CLIP_NORM']\n self.BATCH_SIZE = json_config['BATCH_SIZE'] \n self.IMAGE_SHAPE = json_config['IMAGE_SHAPE'] \n self.IMAGE_META_SIZE = json_config['IMAGE_META_SIZE']\n\n \"\"\"Base configuration class. For custom configurations, create a\n sub-class that inherits from this one and override properties\n that need to be changed.\n \"\"\"\n @staticmethod\n def create_json(count_classes, count_image_per_gpu = 1, count_gpu = 1):\n config = {}\n\n # NUMBER OF GPUs to use. When using only a CPU, this needs to be set to 1.\n config['GPU_COUNT'] = count_gpu\n\n # Number of images to train with on each GPU. A 12GB GPU can typically\n # handle 2 images of 1024x1024px.\n # Adjust based on your GPU memory and image sizes. Use the highest\n # number that your GPU can handle for best performance.\n config['IMAGES_PER_GPU'] = count_image_per_gpu\n\n # Number of classification classes (including background)\n config['NUM_CLASSES'] = count_classes \n\n # Number of training steps per epoch\n # This doesn't need to match the size of the training set. Tensorboard\n # updates are saved at the end of each epoch, so setting this to a\n # smaller number means getting more frequent TensorBoard updates.\n # Validation stats are also calculated at each epoch end and they\n # might take a while, so don't set this too small to avoid spending\n # a lot of time on validation stats.\n config['STEPS_PER_EPOCH'] = 1000\n\n # Number of validation steps to run at the end of every training epoch.\n # A bigger number improves accuracy of validation stats, but slows\n # down the training.\n config['VALIDATION_STEPS'] = 50\n\n # Backbone network architecture\n # Supported values are: resnet50, resnet101.\n # You can also provide a callable that should have the signature\n # of model.resnet_graph. If you do so, you need to supply a callable\n # to COMPUTE_BACKBONE_SHAPE as well\n config['BACKBONE'] = \"resnet101\"\n\n # Only useful if you supply a callable to BACKBONE. Should compute\n # the shape of each layer of the FPN Pyramid.\n # See model.compute_backbone_shapes\n config['COMPUTE_BACKBONE_SHAPE'] = None\n\n # The strides of each layer of the FPN Pyramid. These values\n # are based on a Resnet101 backbone.\n config['BACKBONE_STRIDES'] = [4, 8, 16, 32, 64]\n\n # Size of the fully-connected layers in the classification graph\n config['FPN_CLASSIF_FC_LAYERS_SIZE'] = 1024\n\n # Size of the top-down layers used to build the feature pyramid\n config['TOP_DOWN_PYRAMID_SIZE'] = 256\n\n \n\n # Length of square anchor side in pixels\n config['RPN_ANCHOR_SCALES'] = [32, 64, 128, 256, 512]\n\n # Ratios of anchors at each cell (width/height)\n # A value of 1 represents a square anchor, and 0.5 is a wide anchor\n config['RPN_ANCHOR_RATIOS'] = [0.5, 1, 2]\n\n # Anchor stride\n # If 1 then anchors are created for each cell in the backbone feature map.\n # If 2, then anchors are created for every other cell, and so on.\n config['RPN_ANCHOR_STRIDE'] = 1\n\n # Non-max suppression threshold to filter RPN proposals.\n # You can increase this during training to generate more propsals.\n config['RPN_NMS_THRESHOLD'] = 0.7\n\n # How many anchors per image to use for RPN training\n config['RPN_TRAIN_ANCHORS_PER_IMAGE'] = 256\n \n # ROIs kept after tf.nn.top_k and before non-maximum suppression\n config['PRE_NMS_LIMIT'] = 6000\n\n # ROIs kept after non-maximum suppression (training and inference)\n config['POST_NMS_ROIS_TRAINING'] = 2000\n config['POST_NMS_ROIS_INFERENCE'] = 1000\n\n # If enabled, resizes instance masks to a smaller size to reduce\n # memory load. Recommended when using high-resolution images.\n config['USE_MINI_MASK'] = True #TODO are these even still used? since we always scale to 1024x1024??\n config['MINI_MASK_SHAPE'] = [56, 56] # (height, width) of the mini-mask\n \n # Input image resizing\n # Generally, use the \"square\" resizing mode for training and predicting\n # and it should work well in most cases. In this mode, images are scaled\n # up such that the small side is = IMAGE_MIN_DIM, but ensuring that the\n # scaling doesn't make the long side > IMAGE_MAX_DIM. Then the image is\n # padded with zeros to make it a square so multiple images can be put\n # in one batch.\n # Available resizing modes:\n # none: No resizing or padding. Return the image unchanged.\n # square: Resize and pad with zeros to get a square image\n # of size [max_dim, max_dim].\n # pad64: Pads width and height with zeros to make them multiples of 64.\n # If IMAGE_MIN_DIM or IMAGE_MIN_SCALE are not None, then it scales\n # up before padding. IMAGE_MAX_DIM is ignored in this mode.\n # The multiple of 64 is needed to ensure smooth scaling of feature\n # maps up and down the 6 levels of the FPN pyramid (2**6=64).\n # crop: Picks random crops from the image. First, scales the image based\n # on IMAGE_MIN_DIM and IMAGE_MIN_SCALE, then picks a random crop of\n # size IMAGE_MIN_DIM x IMAGE_MIN_DIM. Can be used in training only.\n # IMAGE_MAX_DIM is not used in this mode.\n config['IMAGE_RESIZE_MODE'] = \"square\"\n config['IMAGE_MIN_DIM'] = 800\n config['IMAGE_MAX_DIM'] = 1024\n # Minimum scaling ratio. Checked after MIN_IMAGE_DIM and can force further\n # up scaling. For example, if set to 2 then images are scaled up to double\n # the width and height, or more, even if MIN_IMAGE_DIM doesn't require it.\n # However, in 'square' mode, it can be overruled by IMAGE_MAX_DIM.\n config['IMAGE_MIN_SCALE'] = 0\n # Number of color channels per image. RGB = 3, grayscale = 1, RGB-D = 4\n # Changing this requires other changes in the code. See the WIKI for more\n # details: https://github.com/matterport/Mask_RCNN/wiki\n config['IMAGE_CHANNEL_COUNT'] = 3\n\n # Image mean (RGB)\n config['MEAN_PIXEL'] = [123.7, 116.8, 103.9]\n\n # Number of ROIs per image to feed to classifier/mask heads\n # The Mask RCNN paper uses 512 but often the RPN doesn't generate\n # enough positive proposals to fill this and keep a positive:negative\n # ratio of 1:3. You can increase the number of proposals by adjusting\n # the RPN NMS threshold.\n config['TRAIN_ROIS_PER_IMAGE'] = 200\n\n # Percent of positive ROIs used to train classifier/mask heads\n config['ROI_POSITIVE_RATIO'] = 0.33\n\n # Pooled ROIs\n config['POOL_SIZE'] = 7\n config['MASK_POOL_SIZE'] = 14\n\n # Shape of output mask\n # To change this you also need to change the neural network mask branch\n config['MASK_SHAPE'] = [28, 28]\n\n # Maximum number of ground truth instances to use in one image\n config['MAX_GT_INSTANCES'] = 100\n\n # Bounding box refinement standard deviation for RPN and final detections.\n config['RPN_BBOX_STD_DEV'] = [0.1, 0.1, 0.2, 0.2]\n config['BBOX_STD_DEV'] = [0.1, 0.1, 0.2, 0.2]\n\n # Max number of final detections\n config['DETECTION_MAX_INSTANCES'] = 100\n\n # Minimum probability value to accept a detected instance\n # ROIs below this threshold are skipped\n config['DETECTION_MIN_CONFIDENCE'] = 0.7\n\n # Non-maximum suppression threshold for detection\n config['DETECTION_NMS_THRESHOLD'] = 0.3\n\n # Learning rate and momentum\n # The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes\n # weights to explode. Likely due to differences in optimizer\n # implementation.\n config['LEARNING_RATE'] = 0.001\n config['LEARNING_MOMENTUM'] = 0.9\n\n # Weight decay regularization\n config['WEIGHT_DECAY'] = 0.0001\n\n # Loss weights for more precise optimization.\n # Can be used for R-CNN training setup.\n config['LOSS_WEIGHTS'] = {\n \"rpn_class_loss\": 1.,\n \"rpn_bbox_loss\": 1.,\n \"mrcnn_class_loss\": 1.,\n \"mrcnn_bbox_loss\": 1.,\n \"mrcnn_mask_loss\": 1.\n }\n\n # Use RPN ROIs or externally generated ROIs for training\n # Keep this True for most situations. Set to False if you want to train\n # the head branches on ROI generated by code rather than the ROIs from\n # the RPN. For example, to debug the classifier head without having to\n # train the RPN.\n config['USE_RPN_ROIS'] = True\n\n # Train or freeze batch normalization layers\n # None: Train BN layers. This is the normal mode\n # False: Freeze BN layers. Good when using a small batch size\n # True: (don't use). Set layer in training mode even when predicting\n config['TRAIN_BN'] = False # Defaulting to False since batch size is often small\n\n # Gradient norm clipping\n config['GRADIENT_CLIP_NORM'] = 5.0\n\n #processing\n config['BATCH_SIZE'] = config['IMAGES_PER_GPU'] * config['GPU_COUNT']\n if config['IMAGE_RESIZE_MODE'] == \"crop\":\n config['IMAGE_SHAPE'] = [config['IMAGE_MIN_DIM'], config['IMAGE_MIN_DIM'], config['IMAGE_CHANNEL_COUNT']]\n else:\n config['IMAGE_SHAPE'] = [config['IMAGE_MAX_DIM'], config['IMAGE_MAX_DIM'], config['IMAGE_CHANNEL_COUNT']]\n\n config['IMAGE_META_SIZE'] = 1 + 3 + 3 + 4 + 1 + config['NUM_CLASSES']\n return config","sub_path":"src/network_builder/mrcnn/config_maskrcnn.py","file_name":"config_maskrcnn.py","file_ext":"py","file_size_in_byte":13228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"517373665","text":"import Sensors\r\nimport Commands\r\nimport Managers\r\nfrom MqttClient import MqttClient\r\nimport Logger\r\nimport multiprocessing\r\nfrom consts import *\r\n\r\n\r\nclass Monitor():\r\n\r\n def __init__(self, config, globalConfig, commandManager, sensorManager, monitor_id=1):\r\n self.config = config\r\n self.globalConfig = globalConfig\r\n self.monitor_id = monitor_id\r\n self.commandManager = commandManager\r\n self.sensorManager = sensorManager\r\n self.Setup()\r\n\r\n def Setup(self):\r\n # Setip logger\r\n self.logger = Logger.Logger(self.globalConfig, self.monitor_id)\r\n self.Log(Logger.LOG_INFO, 'Starting')\r\n # Setup MQTT client\r\n self.mqttClient = MqttClient(self.config, self.logger)\r\n\r\n self.LoadSensors()\r\n self.LoadCommands()\r\n\r\n def LoadSensors(self):\r\n # From configs I read sensors list and I give the names to the sensors manager which will initialize them\r\n # and will keep trace of who is the mqtt_client and the logger of the sensor\r\n # self.sensorManager.PostInitializeSensors()\r\n if CONFIG_SENSORS_KEY in self.config:\r\n sensorsToAdd = self.config[CONFIG_SENSORS_KEY]\r\n for sensor in sensorsToAdd:\r\n self.sensorManager.LoadSensor(\r\n sensor, self.monitor_id, self.config, self.mqttClient, self.config['send_interval'], self.logger)\r\n # Some need post-initialize configuration\r\n self.sensorManager.PostInitializeSensors()\r\n # All configurations must go above\r\n\r\n def LoadCommands(self):\r\n # From configs I read commands list and I give the names to the commands manager which will initialize them\r\n # and will keep trace of who is the mqtt_client and the logger of the command\r\n if CONFIG_COMMANDS_KEY in self.config:\r\n commandsToAdd = self.config[CONFIG_COMMANDS_KEY]\r\n for command in commandsToAdd:\r\n self.commandManager.LoadCommand(\r\n command, self.monitor_id, self.config, self.mqttClient, self.logger)\r\n\r\n # Some need post-initialize configuration\r\n self.commandManager.PostInitializeCommands()\r\n # All configurations must go above\r\n\r\n def Log(self, messageType, message):\r\n self.logger.Log(messageType, 'Main', message)\r\n","sub_path":"Monitor.py","file_name":"Monitor.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"508626742","text":"import reports\nimport datetime\n\nline0 = \"Number of games: %s\" % (reports.count_games(\"game_stat.txt\"))\nline1 = \"Is there a game from %s? %s\" % (2004, reports.decide(\"game_stat.txt\", 2004))\nline2 = \"The latest game on the list is: %s\" % (reports.get_latest(\"game_stat.txt\"))\nline3 = \"There is %s game with the genre %s\" % (reports.count_by_genre(\"game_stat.txt\", \"RPG\"), \"RPG\")\nline4 = \"The %s game is in the %d-th line.\" % (\"The Sims 3\", reports.get_line_number_by_title(\"game_stat.txt\", \"The Sims 3\"))\nline5 = str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\"))\ntext_list = [line0, line1, line2, line3, line4, line5]\nwith open(\"export.txt\", \"w\") as answertext:\n for k in range(len(text_list)):\n answertext.writelines(text_list[k]+\"\\n\")\n","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"442353716","text":"try:\r\n from ace_logger import Logging\r\n logging = Logging()\r\nexcept:\r\n import logging \r\n logger=logging.getLogger() \r\n logger.setLevel(logging.DEBUG) \r\n\r\n\r\n\r\nimport json\r\nimport os\r\nfrom db_utils import DB \r\n\r\ntry:\r\n from BusinessRules import BusinessRules\r\nexcept:\r\n from .BusinessRules import BusinessRules\r\n\r\n\r\n# one configuration\r\ndb_config = {\r\n 'host': os.environ['HOST_IP'],\r\n 'user': os.environ['LOCAL_DB_USER'],\r\n 'password': os.environ['LOCAL_DB_PASSWORD'],\r\n 'port': os.environ['LOCAL_DB_PORT']\r\n}\r\n\r\ndef to_DT_data(parameters):\r\n \"\"\"Amith's processing for parameters\"\"\"\r\n output = []\r\n try:\r\n for param_dict in parameters:\r\n print(param_dict) \r\n if param_dict['column'] == 'Add_on_Table':\r\n output.append({'table': param_dict['table'],'column': param_dict['column'],'value': param_dict['value']})\r\n # Need to add a function to show this or tell Kamal check if its addon table and parse accordingly\r\n else: \r\n output.append({'table': param_dict['table'],'column': param_dict['column'],'value': param_dict['value']})\r\n except:\r\n print(\"Error in to_DT_data()\")\r\n traceback.print_exc()\r\n return []\r\n try:\r\n output = [dict(t) for t in {tuple(d.items()) for d in output}]\r\n except:\r\n print(\"Error in removing duplicate dictionaries in list\")\r\n traceback.print_exc()\r\n pass\r\n return output\r\n\r\ndef get_data_sources(tenant_id, case_id, column_name, master=False):\r\n \"\"\"Helper to get all the required table data for the businesss rules to apply\r\n \"\"\"\r\n get_datasources_query = \"SELECT * from `data_sources`\"\r\n db_config['tenant_id'] = tenant_id\r\n business_rules_db = DB('business_rules', **db_config)\r\n data_sources = business_rules_db.execute(get_datasources_query)\r\n\r\n\r\n # sources\r\n sources = json.loads(list(data_sources[column_name])[0])\r\n \r\n \r\n data = {}\r\n for database, tables in sources.items():\r\n db = DB(database, **db_config)\r\n for table in tables:\r\n if master:\r\n query = f\"SELECT * from `{table}`\"\r\n try:\r\n df = db.execute(query)\r\n except:\r\n df = db.execute_(query)\r\n \r\n data[table] = df.to_dict(orient='records')\r\n else:\r\n query = f\"SELECT * from `{table}` WHERE case_id = %s\"\r\n params = [case_id]\r\n df = db.execute(query, params=params)\r\n if not df.empty:\r\n data[table] = df.to_dict(orient='records')[0]\r\n else:\r\n data[table] = {}\r\n \r\n \r\n case_id_based_sources = json.loads(list(data_sources['case_id_based'])[0])\r\n \r\n return data\r\n \r\ndef get_rules(tenant_id, group):\r\n \"\"\"Get the rules based on the stage, tenant_id\"\"\"\r\n db_config['tenant_id'] = tenant_id\r\n business_rules_db = DB('business_rules', **db_config)\r\n get_rules_query = \"SELECT * from `sequence_rule_data` where `group` = %s\"\r\n params = [group]\r\n rules = business_rules_db.execute(get_rules_query, params=params)\r\n return rules\r\n\r\ndef update_tables(case_id, tenant_id, updates):\r\n \"\"\"Update the values in the database\"\"\"\r\n db_config['tenant_id'] = tenant_id\r\n extraction_db = DB('extraction', **db_config) # only in ocr or process_queue we are updating\r\n queue_db = DB('queues', **db_config) # only in ocr or process_queue we are updating\r\n \r\n for table, colum_values in updates.items():\r\n if table == 'ocr':\r\n extraction_db.update(table, update=colum_values, where={'case_id':case_id})\r\n if table == 'process_queue':\r\n queue_db.update(table, update=colum_values, where={'case_id':case_id})\r\n return \"UPDATED IN THE DATABASE SUCCESSFULLY\"\r\n\r\ndef run_chained_rules(case_id, tenant_id, chain_rules, start_rule_id=None, updated_tables=False, trace_exec=None, rule_params=None):\r\n \"\"\"Execute the chained rules\"\"\"\r\n \r\n # get the mapping of the rules...basically a rule_id maps to a rule\r\n rule_id_mapping = {}\r\n for ind, rule in chain_rules.iterrows():\r\n rule_id_mapping[rule['rule_id']] = [rule['rule_string'], rule['next_if_sucess'], rule['next_if_failure'], rule['stage'], rule['description'], rule['data_source']]\r\n logging.info(f\"\\n rule id mapping is \\n{rule_id_mapping}\\n\")\r\n \r\n # evaluate the rules one by one as chained\r\n # start_rule_id = None\r\n if start_rule_id is None:\r\n if rule_id_mapping.keys():\r\n start_rule_id = list(rule_id_mapping.keys())[0]\r\n trace_exec = []\r\n rule_params = {}\r\n \r\n # if start_rule_id then. coming from other service \r\n # get the existing trace and rule params data\r\n db_config['tenant_id'] = tenant_id\r\n business_rules_db = DB('business_rules', **db_config)\r\n rule_data_query = \"SELECT * from `rule_data` where `case_id`=%s\"\r\n params = [case_id]\r\n df = business_rules_db.execute(rule_data_query, params=params)\r\n try:\r\n trace_exec = json.loads(list(df['trace_data'])[0])\r\n logging.info(f\"\\nexistig trace exec is \\n{trace_exec}\\n\")\r\n except Exception as e:\r\n logging.info(f\"no existing trace data\")\r\n logging.info(f\"{str(e)}\")\r\n trace_exec = []\r\n \r\n try:\r\n rule_params = json.loads(list(df['rule_params'])[0])\r\n logging.info(f\"\\nexistig rule_params is \\n{rule_params}\\n\")\r\n except Exception as e:\r\n logging.info(f\"no existing rule params data\")\r\n logging.info(f\"{str(e)}\")\r\n rule_params = {}\r\n \r\n # usually master data will not get updated...for every rule\r\n master_data_tables = get_data_sources(tenant_id, case_id, 'master', master=True)\r\n \r\n logging.info(f\"\\nStart rule id got is {start_rule_id}\\n \")\r\n while start_rule_id != \"END\":\r\n # get the rules, next rule id to be evaluated\r\n rule_to_evaluate, next_if_sucess, next_if_failure, stage, description, data_source = rule_id_mapping[str(start_rule_id)] \r\n \r\n logging.info(f\"\\nInside the loop \\n rule_to_evaluate {rule_to_evaluate}\\n \\\r\n \\nnext_if_sucess {next_if_sucess}\\n \\\r\n \\nnext_if_failure {next_if_failure}\\n \")\r\n \r\n # update the data_table if there is any change\r\n case_id_data_tables = get_data_sources(tenant_id, case_id, 'case_id_based')\r\n master_updated_tables = {} \r\n if updated_tables:\r\n master_updated_tables = get_data_sources(tenant_id, case_id, 'updated_tables')\r\n # consolidate the data into data_tables\r\n data_tables = {**case_id_data_tables, **master_data_tables, **master_updated_tables} \r\n \r\n # evaluate the rule\r\n rules = [json.loads(rule_to_evaluate)] \r\n BR = BusinessRules(case_id, rules, data_tables)\r\n BR.tenant_id = tenant_id\r\n decision = BR.evaluate_rule(rules[0])\r\n \r\n logging.info(f\"\\n got the decision {decision} for the rule id {start_rule_id}\")\r\n logging.info(f\"\\n updates got are {BR.changed_fields}\")\r\n \r\n updates = {}\r\n # update the updates if any\r\n if BR.changed_fields:\r\n updates = BR.changed_fields\r\n update_tables(case_id, tenant_id, updates)\r\n\r\n \r\n # update the trace_data\r\n trace_exec.append(start_rule_id)\r\n\r\n logging.info(f\"\\n params data used from the rules are \\n {BR.params_data}\\n\")\r\n # update the rule_params\r\n trace_dict = {\r\n str(start_rule_id):{\r\n 'description' : description if description else 'No description available in the database',\r\n 'output' : \"\",\r\n 'input' : to_DT_data(BR.params_data['input'])\r\n }\r\n }\r\n rule_params.update(trace_dict)\r\n # update the start_rule_id based on the decision\r\n if decision:\r\n start_rule_id = next_if_sucess\r\n else:\r\n start_rule_id = next_if_failure\r\n logging.info(f\"\\n next rule id to execute is {start_rule_id}\\n\")\r\n \r\n \r\n # off by one updates...\r\n trace_exec.append(start_rule_id)\r\n \r\n # store the trace_exec and rule_params in the database\r\n update_rule_params_query = f\"INSERT INTO `rule_data`(`id`, `case_id`, `rule_params`) VALUES ('NULL',%s,%s) ON DUPLICATE KEY UPDATE `rule_params`=%s\"\r\n params = [case_id, json.dumps(rule_params,default=str), json.dumps(rule_params,default=str)]\r\n business_rules_db.execute(update_rule_params_query, params=params)\r\n \r\n update_trace_exec_query = f\"INSERT INTO `rule_data` (`id`, `case_id`, `trace_data`) VALUES ('NULL',%s,%s) ON DUPLICATE KEY UPDATE `trace_data`=%s\"\r\n params = [case_id, json.dumps(trace_exec), json.dumps(trace_exec)]\r\n business_rules_db.execute(update_trace_exec_query, params=params)\r\n \r\n logging.info(\"\\n Applied chained rules successfully\")\r\n return 'Applied chained rules successfully'\r\n\r\ndef run_group_rules(case_id,tenant_id, rules, data):\r\n \"\"\"Run the rules\"\"\"\r\n rules = [json.loads(rule) for rule in rules] \r\n BR = BusinessRules(case_id, rules, data)\r\n BR.tenant_id = tenant_id\r\n updates = BR.evaluate_business_rules()\r\n \r\n logging.info(f\"\\n updates from the group rules are \\n{updates}\\n\")\r\n return updates\r\n\r\ndef apply_business_rule(case_id, function_params, tenant_id, start_rule_id=None):\r\n \"\"\"Run the business rules based on the stage in function params and tenant_id\r\n Args:\r\n case_id: Unique id that we pass\r\n function_params: Parameters that we get from the configurations\r\n tenant_id: Tenant on which we have to apply the rules\r\n Returns:\r\n \"\"\"\r\n try:\r\n stage = function_params['stage'][0]\r\n logging.debug(f'Running business rules after {stage}')\r\n except:\r\n pass\r\n updates = {} # keep a track of updates that are being made by business rules\r\n try:\r\n # get the stage from the function_parameters...As of now its first ele..\r\n # need to make generic or key-value pairs\r\n logging.info(f\"\\n case_id {case_id} \\nfunction_params {function_params} \\ntenant_id {tenant_id}\\n\")\r\n \r\n # get the rules\r\n rules = get_rules(tenant_id, stage)\r\n \r\n # get the mapping of the rules...basically a rule_id maps to a rule.\r\n # useful for the chain rule evaluations\r\n rule_id_mapping = {}\r\n for ind, rule in rules.iterrows():\r\n rule_id_mapping[rule['rule_id']] = [rule['rule_string'], rule['next_if_sucess'], rule['next_if_failure'], rule['stage'], rule['description'], rule['data_source']]\r\n\r\n # making it generic takes to take a type parameter from the database..\r\n # As of now make it (all others or chained) only\r\n is_chain_rule = '' not in rule_id_mapping\r\n \r\n # get the required table data on which we will be applying business_rules \r\n case_id_data_tables = get_data_sources(tenant_id, case_id, 'case_id_based') \r\n master_data_tables = get_data_sources(tenant_id, case_id, 'master', master=True)\r\n \r\n # consolidate the data into data_tables\r\n data_tables = {**case_id_data_tables, **master_data_tables} \r\n \r\n logging.info(f\"\\ndata got from the tables is\\n\")\r\n logging.info(data_tables)\r\n \r\n updates = {}\r\n # apply business rules\r\n if is_chain_rule:\r\n run_chained_rules(case_id, tenant_id, rules, start_rule_id)\r\n else:\r\n updates = run_group_rules(case_id, tenant_id, list(rules['rule_string']), data_tables)\r\n \r\n # update in the database, the changed fields eventually when all the stage rules were got\r\n update_tables(case_id, tenant_id, updates)\r\n \r\n # return the updates for viewing\r\n return {'flag': True, 'message': 'Applied business rules successfully.', 'updates':updates}\r\n except Exception as e:\r\n logging.exception('Something went wrong while applying business rules. Check trace.')\r\n return {'flag': False, 'message': 'Something went wrong while applying business rules. Check logs.', 'error':str(e)}\r\n","sub_path":"apply_business_rule.py","file_name":"apply_business_rule.py","file_ext":"py","file_size_in_byte":12407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"50333878","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nclass Mos_search(unittest.TestCase):\n\n def setUp(self):\n # придумать как развернуть на весь экран\n self.driver = webdriver.Chrome()\n\n def test_go_search(self):\n driver = self.driver\n driver.maximize_window()\n driver.get(\"http://www.mos.ru\")\n #self.assertIn(\"Официальный сайт Мэра Москвы\", driver.title)\n driver.find_element_by_class_name('mos-layout-icon-search_black').click()\n driver.find_element_by_xpath('//*[@id=\"mos-header\"]/div[1]/div/div[1]/div[3]/div/div[4]/div/form/div/span/input[2]').send_keys(\"Собянин\")\n # Поиск по Xpath - работающий вариант, можно улучшить. Копать в том, как работать с динамическими элементами. \n # search = driver.find_element_by_tag_name('input')\n driver.find_element_by_class_name('mos-layout-icon-search_black').click()\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME,'wdg-mayor')))\n\n def tearDown(self):\n self.driver.close()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"selenium/mos_search.py","file_name":"mos_search.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"257853227","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\n# Dependencies\nimport pandas as pd\n\n\n# In[6]:\n\n\n# save file path to variable\nbudget_csv = \"Resources/budget_data.csv\"\n\n\n# In[7]:\n\n\n# read with pandas\nbudget_df = pd.read_csv(budget_csv)\nbudget_df.head()\n\n\n# In[10]:\n\n\n#The total number of months included in the dataset\nlen(budget_df)\n\n\n# In[11]:\n\n\n# The net total amount of \"Profit/Losses\" over the entire period\nbudget_df[\"Profit/Losses\"].sum()\n\n\n# In[18]:\n\n\n#The average of the changes in \"Profit/Losses\" over the entire period\ndifferences=[]\nprevious = 0\nfor index,row in budget_df.iterrows():\n # print(row[\"Profit/Losses\"])\n change = row[\"Profit/Losses\"] - previous\n previous = row[\"Profit/Losses\"]\n if index >0:\n differences.append(change)\naverage = sum(differences)/len(differences)\naverage\n\n\n# In[19]:\n\n\n# The greatest increase in profits (date and amount) over the entire period\nmax(differences)\n\n\n# In[20]:\n\n\n# The greatest decrease in losses (date and amount) over the entire period\nmin(differences)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Pybank1/analysis/PyBank.py","file_name":"PyBank.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"255746826","text":"from .seemblock import SeemBlock\nfrom .readblock import ReadBlock\nfrom .writeblock import WriteBlock\n\nfrom flor import flags\n\n\nclass SkipBlock(SeemBlock):\n @staticmethod\n def step_into(block_name: str, probed=None):\n if flags.NAME is not None:\n raise RuntimeError(\"SkipBlock missing dynamic linking\")\n return True\n\n @staticmethod\n def end(*args, values=None):\n if flags.NAME is not None:\n raise RuntimeError(\"SkipBlock missing dynamic linking\")\n\n @staticmethod\n def bind():\n block = ReadBlock if flags.REPLAY else WriteBlock\n SkipBlock.step_into = block.step_into # type: ignore\n SkipBlock.end = block.end\n","sub_path":"flor/skipblock/abstract.py","file_name":"abstract.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"464782501","text":"import os\nimport urllib.parse\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom openpyxl import Workbook\n\nfrom spider.entity.weibo import Weibo\n\n\ndef crawl(keyword):\n weibo_list = []\n pagenum = 1\n\n while pagenum <= 100:\n request_url = 'http://weibo.cn/search/mblog?hideSearchFrame=&keyword=' + urllib.parse.quote(\n keyword) + '&page=' + str(pagenum)\n print(request_url)\n headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36',\n 'Origin': 'http://weibo.cn',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Host': 'weibo.cn',\n 'Upgrade-Insecure-Requests': 1\n }\n\n cookies = dict(\n cookies_are='_T_WM=c61fcaec8e7119726d0f5d4fe7d00ce1; ALF=1473913528; SCF=AuZECCAFKUmhknQibDNIlAc9ej8a-g-rDLUCcRVI6Gurm0wSX1z_jCh4ipu6yIxIkBYeJKf6z2ktnOlz0inxKSw.; SUB=_2A256tuwhDeTxGeRK6FUY8SfFwz-IHXVWWPRprDV6PUJbktAKLW-ikW0FCqYxNFv0-Jzz2AyAlHJHs6zUmQ..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFA5TwRz43RBDwVNEW_BoS35JpX5o2p5NHD95QESheN1K241Kn0Ws4Dqcj1PEH8SE-4eb-4e8veUHYt; SUHB=0TPUMrVP0rS8gS; SSOLoginState=1471323249')\n\n response = requests.get(request_url, headers=headers, cookies=cookies)\n if response.status_code == 200:\n html = response.text\n soup = BeautifulSoup(html, 'html.parser')\n print(html)\n divs = soup.find_all('div', class_='c')\n for i in range(3, len(divs) - 2):\n # print(divs[i])\n try:\n username = divs[i].a.text\n userurl = divs[i].a['href']\n content = divs[i].find_all('span', class_='ctt')[0].text\n all_a = divs[i].find_all('a')\n\n for each_a in all_a:\n if each_a['href'].startswith('http://weibo.cn/attitude'):\n like = each_a.text\n elif each_a['href'].startswith('http://weibo.cn/repost'):\n repost = each_a.text\n elif each_a['href'].startswith('http://weibo.cn/comment'):\n comment = each_a.text\n else:\n pass\n # like = all_a[len(all_a) - 4].text\n # repost = all_a[len(all_a) - 3].text\n # comment = all_a[len(all_a) - 2].text\n date_and_device = divs[i].find_all('span', class_='ct')[0].text\n # date_and_device = divs[i].find_all('span', class_='ct')[0].text.split(\" \")\n # date = date_and_device[len(date_and_device) - 3] + date_and_device[len(date_and_device) - 2]\n # device = date_and_device[len(date_and_device) - 1]\n\n print(\n 'Username : ' + username + '; Userurl : ' + userurl + '; content ' + content + '; like : ' + like + '; repost : ' + repost + '; comment : ' + comment + '; date_and_device : ' + date_and_device)\n weibo = Weibo(username, userurl, content, like, repost, comment, date_and_device)\n weibo_list.append(weibo)\n except:\n pass\n else:\n print('ERROR!' + str(response.status_code))\n # time.sleep(3)\n pagenum += 1\n\n return weibo_list\n\n\ndef out_excel(filedir, filename, sheetname, weibo_list):\n if not os.path.isdir(filedir):\n os.mkdir(filedir)\n\n filepath = filedir + os.path.sep + filename + '.xlsx'\n wb = Workbook()\n ws = wb.active\n # ws.print_options.verticalCentered = True\n # ws.print_options.horizontalCentered = True\n ws.title = sheetname\n ws.cell(row=1, column=1).value = '用户名'\n ws.cell(row=1, column=2).value = '用户URL'\n ws.cell(row=1, column=3).value = '微博内容'\n ws.cell(row=1, column=4).value = '赞'\n ws.cell(row=1, column=5).value = '转发'\n ws.cell(row=1, column=6).value = '评论'\n ws.cell(row=1, column=7).value = '日期与来源'\n\n rownum = 2\n\n for each_weibo in weibo_list:\n ws.cell(row=rownum, column=1).value = each_weibo.username\n ws.cell(row=rownum, column=2).value = each_weibo.userurl\n ws.cell(row=rownum, column=3).value = each_weibo.content\n ws.cell(row=rownum, column=4).value = each_weibo.like\n ws.cell(row=rownum, column=5).value = each_weibo.repost\n ws.cell(row=rownum, column=6).value = each_weibo.comment\n ws.cell(row=rownum, column=7).value = each_weibo.date_and_device\n rownum += 1\n\n wb.save(filepath)\n print('Excel generates successfully......')\n\n\nif __name__ == '__main__':\n weibo_list = crawl('王宝强')\n out_excel('D:/', '微博-王宝强', '王宝强', weibo_list)\n","sub_path":"spider/weibo/weibo_spider.py","file_name":"weibo_spider.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"367481698","text":"# N is the size of the 2D matrix N*N\nN = 9\n\ndef printing(arr):\n\tfor i in range(N):\n\t\tfor j in range(N):\n\t\t\tprint(arr[i][j], end = \" \")\n\t\tprint()\n\t\t\ndef valid(grid, row, col, num):\n\n\tfor x in range(9):\n\t\tif grid[row][x] == num:\n\t\t\treturn False\n\n\tfor x in range(9):\n\t\tif grid[x][col] == num:\n\t\t\treturn False\n\n\tstartRow = row - row % 3\n\tstartCol = col - col % 3\n\tfor i in range(3):\n\t\tfor j in range(3):\n\t\t\tif grid[i + startRow][j + startCol] == num:\n\t\t\t\treturn False\n\treturn True\n\ndef solveSudoku(grid, row, col):\n\n\tif (row == N - 1 and col == N):\n\t\treturn True\n\t\n\tif col == N:\n\t\trow += 1\n\t\tcol = 0\n\n\tif grid[row][col] > 0:\n\t\treturn solveSudoku(grid, row, col + 1)\n\tfor num in range(1, N + 1, 1):\n\t\n\t\tif valid(grid, row, col, num):\n\t\t\n\t\t\tgrid[row][col] = num\n\n\t\t\tif solveSudoku(grid, row, col + 1):\n\t\t\t\treturn True\n\n\t\t\n\t\tgrid[row][col] = 0\n\treturn False\n\n# 0 means unassigned cells\ngrid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],\n\t\t[5, 2, 0, 0, 0, 0, 0, 0, 0],\n\t\t[0, 8, 7, 0, 0, 0, 0, 3, 1],\n\t\t[0, 0, 3, 0, 1, 0, 0, 8, 0],\n\t\t[9, 0, 0, 8, 6, 3, 0, 0, 5],\n\t\t[0, 5, 0, 0, 9, 0, 6, 0, 0],\n\t\t[1, 3, 0, 0, 0, 0, 2, 5, 0],\n\t\t[0, 0, 0, 0, 0, 0, 0, 7, 4],\n\t\t[0, 0, 5, 2, 0, 6, 3, 0, 0]]\n\nif (solveSudoku(grid, 0, 0)):\n\tprinting(grid)\nelse:\n\tprint(\"no solution exists \")\n\n\n","sub_path":"SudokuSolver.py","file_name":"SudokuSolver.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"348330227","text":"# -*- coding: utf-8 -*-\n\nfrom futuquant import *\nfrom . import data_strategy\n\n\nclass TickerTest(TickerHandlerBase):\n \"\"\" 获取逐笔推送数据 \"\"\"\n def on_recv_rsp(self, rsp_pb):\n \"\"\"数据响应回调函数\"\"\"\n ret_code, content = super(TickerTest, self).parse_rsp_pb(rsp_pb)\n if ret_code != RET_OK:\n print(\"* TickerTest: error, msg: %s\" % content)\n return RET_ERROR, content\n # print(\"* TickerTest\\n\", content)\n data_strategy.detect_and_send(content)\n return RET_OK, content\n\n\ndef quote_test(code_list, host, port):\n quote_ctx = OpenQuoteContext(host, port)\n print(\"Server lim.app:%s connected...\" % port)\n # 设置异步回调接口\n quote_ctx.set_handler(TickerTest())\n quote_ctx.start()\n\n ret, msg = quote_ctx.subscribe(code_list, SubType.TICKER)\n if ret != RET_OK:\n return ret, msg\n print(quote_ctx.query_subscription())\n return RET_OK, \"\"\n\n\n","sub_path":"futuquant/examples/app/stock_alarm/data_acquisition.py","file_name":"data_acquisition.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"469705464","text":"# This is code to record the audio file\r\n\r\nimport speech_recognition as sr\r\n\r\nprint(\"Hello python \" , sr.__version__)\r\n\r\nr = sr.Recognizer()\r\n\r\nharvard = sr.AudioFile('harvard.wav')\r\n\r\nwith harvard as source:\r\n audio = r.record(source)\r\n r.recognize_google(audio)","sub_path":"Read.py","file_name":"Read.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"632068688","text":"#!/usr/bin/python\n# coding:utf-8\n\nfrom spyne import Application, rpc, ServiceBase\nfrom spyne import Integer, Unicode, Array, ComplexModel, Iterable, String\nfrom spyne.protocol.soap import Soap11\nfrom spyne.server.wsgi import WsgiApplication\nfrom wsgiref.simple_server import make_server\nfrom ShangYi.jsMethod import JsService\n\n\nclass Person(ComplexModel):\n name = Unicode\n age = Integer\n\n\nclass HelloWorldService(ServiceBase):\n @rpc(Unicode, Integer, _returns=Iterable(Unicode))\n def say_hello(self, name, times):\n for i in range(times):\n yield \"Hello %s, It's the %s time to meet you.\" % (name, i + 1)\n\n @rpc(Array(Person), _returns=Iterable(Unicode))\n def say_hello_1(self, persons):\n print('-------say_hello_1()--------')\n if not persons:\n yield 'None'\n for person in persons:\n print('name is : %s, age is %s.' % (person.name, person.age))\n yield 'name is : %s, age is %s.' % (person.name, person.age)\n\n\nclass HelloWorldService2(ServiceBase):\n @rpc(Array(String), _returns=Iterable(Unicode))\n def say_hello_2(self, persons):\n if not persons:\n yield 'None'\n\n for person in persons:\n yield person\n\n\n\napplication = Application([HelloWorldService, HelloWorldService2, JsService],\n 'http://shangyi.weiliang.webservice',\n in_protocol=Soap11(validator='lxml'),\n out_protocol=Soap11())\nwsgi_application = WsgiApplication(application)\n\nif __name__ == '__main__':\n import logging\n host = '192.168.81.136'\n port = 8000\n logfilename='shangyiservice.log'\n logging.basicConfig(level=logging.DEBUG, filename=logfilename, format=\n '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')\n logging.getLogger('spyne.application.server').setLevel(logging.DEBUG)\n logging.info(\"listening to http://%s:%s\" % (host,port))\n logging.info(\"wsdl is at: http://%s:%s/?wsdl\" % (host,port) )\n server = make_server(host, port, wsgi_application)\n server.serve_forever()\n","sub_path":"shangyi_service.py","file_name":"shangyi_service.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"575889769","text":"import asyncio\nimport logging\nimport os\nimport uvloop\n\nfrom autobrowser import (\n run_automation,\n SingleBrowserDriver,\n MultiBrowserDriver,\n build_automation_config,\n)\n\ntry:\n uvloop.install()\nexcept Exception:\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\nlogger = logging.getLogger(\"autobrowser\")\nlogger.setLevel(logging.DEBUG)\n\n\nasync def run_driver() -> int:\n loop = asyncio.get_event_loop()\n if os.environ.get(\"BROWSER_HOST\"):\n logger.info(\"run_driver: using SingleBrowserDriver\")\n driver = SingleBrowserDriver(conf=build_automation_config(), loop=loop)\n else:\n logger.info(\"run_driver: using MultiBrowserDriver\")\n driver = MultiBrowserDriver(conf=build_automation_config(), loop=loop)\n return await driver.run()\n\n\nif __name__ == \"__main__\":\n run_automation(run_driver())\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"542402648","text":"import hashlib\nimport requests\nimport json\nimport sqlite3\n\ndef main_api():\n\n\tpublic = '09f373fcfa768e430d222371bb8fa72b'\n\tprivate = '938bec35fe455307d428886cfb9053c448604669'\n\tts = '1'\n\thash = hashlib.md5((ts + private + public).encode()).hexdigest()\n\n\tbase = 'http://gateway.marvel.com/v1/public/'\n\tcaracter = requests.get(base + 'characters',\n\t\t\t\t\t\t\tparams={'apikey': public, 'ts': ts, 'hash' : hash, 'name': 'hulk'}).json()\n\tnombre = (caracter ['data']['results'][0]['name'])\t\n\tdescription = (caracter ['data']['results'][0]['description'])\n\n\tcon = sqlite3.connect(\"/home/ec2-user/API/bd\")\n\tcursor = con.cursor()\n\tcursor.execute('''CREATE TABLE IF NOT EXISTS MARVEL\n\t\t\t\t\t(NOMBRE TEXT NOT NULL, \n\t\t\t\t\t DESCRIPTION TEXT NOT NULL)''')\n\tcursor.execute('''INSERT INTO MARVEL (NOMBRE, DESCRIPTION) VALUES (?,?)''', (nombre, description))\n\tcon.commit() #los cambios se guardan\n\tcursor.execute('''SELECT * FROM MARVEL''')\n\tprint(cursor.fetchall()) #muestro por pantalla\n\tcon.close()\n\nif __name__ == '__main__':\n\tmain_api()","sub_path":"LLAMAR_apiMarvel.py","file_name":"LLAMAR_apiMarvel.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"52874430","text":"# -*- coding:utf-8 -*-\n\nRESOURCES_BASE_PATH = './resources/revoke'\n\n# ==========================================\n\nbot_qq = 123456\n# 屏蔽群 例:[12345678, 87654321]\nblockGroupNumber = []\n# 服务器配置\nhost = 'http://127.0.0.1'\nport = 8888\n\nmax_info_length = 341\n\n# ==========================================\n\nimport util.db.sql as op\nimport time\nfrom iotbot import Action\n\ntry:\n import ujson as json\nexcept:\n import json\n\n\ndef receive_events(ctx: dict):\n if ctx['CurrentPacket']['Data']['EventName'] == 'ON_EVENT_GROUP_REVOKE' and \\\n ctx['CurrentPacket']['Data']['EventData']['UserID'] != bot_qq:\n action = Action(bot_qq,\n port=port,\n host=host)\n msg_set = ctx['CurrentPacket']['Data']['EventData']\n msg_seq = msg_set['MsgSeq']\n msg_group_id = msg_set['GroupID']\n msg_revoke = op.find_group_msg_by_msg_seq(msg_seq, msg_group_id)[0]\n print(msg_revoke)\n if msg_revoke is None:\n print('db.find returns null result')\n return\n if msg_revoke[\"msg_type\"] == 'TextMsg':\n msg = \"棒棒冰发现 \" + msg_revoke[\"from_nickname\"] + \" 撤回了消息:\\n\\n\"\n action.send_group_text_msg(msg_revoke[\"from_group_id\"], msg + msg_revoke[\"content\"])\n if msg_revoke[\"msg_type\"] == 'PicMsg':\n msg = \"棒棒冰发现 \" + msg_revoke[\"from_nickname\"] + \" 撤回了图片:\\n\\n\"\n msg_content = msg_revoke[\"content\"] if msg_revoke[\"content\"] is not None else \"\"\n action.send_group_text_msg(msg_revoke[\"from_group_id\"], msg + msg_content)\n pics = json.loads(msg_revoke[\"pics\"])\n for pic_id in pics:\n pic_content = op.find_img_by_id(pic_id)[0]\n action.send_group_pic_msg(\n msg_revoke[\"from_group_id\"],\n fileMd5=pic_content['FileMd5'],\n picBase64Buf=pic_content['ForwordBuf']\n )\n time.sleep(0.8)\n","sub_path":"plugins/bot_revoke.py","file_name":"bot_revoke.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"194528487","text":"from django.contrib import admin\nfrom app import models\nfrom utils.log import log\nfrom copy import deepcopy\n# Register your models here.\n\ndef register_admin(model):\n \"\"\"Turn admin.site.register into a decorator.\"\"\"\n def wrapper(klass):\n admin.site.register(model, klass)\n return klass\n return wrapper\n\n@admin.register(models.sensor)\nclass SensorAdmin(admin.ModelAdmin):\n list_display = ('name','type','units','mean','std')\n list_filter = ('type',)\n search_fields = ['name']\n\n#def reset_nodesim(modeladmin, request, queryset):\n# for qs in queryset:\n# \tpass\n\n#def stop_nodesim(modeladmin, request, queryset):\n# for qs in queryset:\n# \tpass\n\n#def start_nodesim(modeladmin, request, queryset):\n# for qs in queryset:\n# \tpass\n\ndef copy_simnode(modeladmin, request, queryset):\n for qs in queryset:\n simnode = deepcopy(qs)\n simnode.name = \"%s (copy)\" % qs.name\n simnode.pk = None\n simnode.save()\n simnode.sensors.add(*qs.sensors.all())\n\n@admin.register(models.sim_node)\nclass SimNodeAdmin(admin.ModelAdmin):\n list_display = ('name','devicealias','measurement_count')\n\n search_fields = ['devicealias']\n search_fields = ['name']\n filter_horizontal = ('sensors',)\n\n actions = [copy_simnode]\n\nclass TagInline(admin.TabularInline):\n model = models.tag\n\n@admin.register(models.node)\nclass NodeAdmin(admin.ModelAdmin):\n list_display = ('name','active','long','lat','sourcetype','devicealias','notes')\n list_filter = ('active','sourcetype')\n search_fields = ['name']\n inlines = [\n TagInline,\n ]\n readonly_fields = ('ph_chart', 'temperature_chart','conductivity_chart','turbidity_chart','orp_chart','odo_chart')\n fieldsets = [\n ('Node', { 'fields': [ 'active', 'name', 'long', \\\n 'lat', 'devicealias', 'sourcetype','commtype','deviceaddress','hostip','proxy_url','notes' ]}), \\\n ('Ph', { 'fields': [ 'ph_chart', ]}),\n ('Temperature', { 'fields': [ 'temperature_chart', ]}),\n\n ('Conductivity', { 'fields': [ 'conductivity_chart', ]}),\n ('Turbidity', { 'fields': [ 'turbidity_chart', ]}),\n ('Oxygen Reduction Potential', { 'fields': [ 'orp_chart', ]}),\n ('Dissolved Oxygen', { 'fields': [ 'odo_chart', ]}),\n ]\n\n class Media:\n js = (\"js/node.js\",)\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"479658938","text":"class Solution:\r\n def maxProfit(self, prices):\r\n \"\"\"\r\n :type prices: List[int]\r\n :rtype: int\r\n \"\"\"\r\n if not prices:\r\n return 0\r\n\r\n # Used to keep track of the global min\r\n # as we find it\r\n lowest_so_far = prices[0]\r\n profit = 0\r\n\r\n for i, v in enumerate(prices):\r\n if i == 0:\r\n continue\r\n\r\n if v < lowest_so_far:\r\n # Update the global min as we find it\r\n lowest_so_far = v\r\n else:\r\n # Compute the max profit for every entry\r\n # as the max of the current profit and the\r\n # current stock price - the global min\r\n profit = max(profit, v - lowest_so_far)\r\n\r\n return profit\r\n","sub_path":"best-time-to-buy-and-sell-stock.py","file_name":"best-time-to-buy-and-sell-stock.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"262495389","text":"import numpy as np\n\nfrom FUNCS import FNS, RK4\nfrom PTSS import PtssJoint as ptssjnt\nfrom PTSS import PtssSpatial as ptssspt\nfrom PTSS import Ptss as ptss\nfrom EYES import EyeVar, EyeFun\n\n\n# variable class for Column Module\nclass ColVar:\n def __init__(self, num_deg):\n self.num_deg = num_deg\n self.ppc = self.Parietal(num_deg)\n self.mtc = self.Motor()\n self.spc = self.SpinalCord()\n self.cbm = self.Cerebellum()\n\n class Parietal:\n def __init__(self, num_deg):\n self.num_deg = num_deg\n\n self.spt_targ = 1 / 2 * np.ones((2, 3, 2))\n self.spt_pres = 1 / 2 * np.ones((2, 3, 2))\n self.tpv = 1 / 2 * np.ones((2, 2, 2))\n self.ppv = 1 / 2 * np.ones((2, 2, 2))\n\n self.dv_erg = np.zeros((2, 2, 2))\n self.trk_prog = -1\n\n self.ltm_mot_spt = np.zeros((2, num_deg, num_deg, 3, 2))\n self.dv_mot_spt = np.zeros((2, 3, 2))\n self.sv_mot_spt = 1 / 2 * np.ones((2, 3, 2))\n self.sptmp_mot_spt = np.zeros((2, num_deg, num_deg))\n\n self.ltm_spt_mot = np.zeros((2, num_deg, num_deg, num_deg, 2, 2))\n self.dv_spt_mot = np.zeros((2, 2, 2))\n self.sv_spt_mot = np.zeros((2, 2, 2))\n self.sptmp_spt_mot = np.zeros((2, num_deg, num_deg, num_deg))\n\n self.mot_spt_est = np.zeros((2, 3, 2))\n self.spt_mot_est = np.zeros((2, 2, 2))\n\n class Motor:\n def __init__(self):\n self.opv = 1 / 2 * np.ones((2, 2, 2))\n self.sfv = 1 / 2 * np.ones((2, 2, 2))\n self.ifv = 1 / 2 * np.ones((2, 2, 2))\n self.ofpv = np.zeros((2, 2, 2))\n\n ones = np.ones(2)\n zeros = np.zeros(2)\n one_zero = np.array((ones, zeros))\n weights = np.array([one_zero, one_zero])\n self.weights = weights\n self.speed_mod = 1\n\n class SpinalCord:\n def __init__(self):\n self.alpha_moto = np.zeros((2, 2, 2))\n self.stat_gamma = np.zeros((2, 2, 2))\n self.dynm_gamma = np.zeros((2, 2, 2))\n self.renshaw = np.zeros((2, 2, 2))\n self.ia_int = np.zeros((2, 2, 2))\n self.prim_spin = np.zeros((2, 2, 2))\n self.seco_spin = np.zeros((2, 2, 2))\n self.extra_mus = np.zeros((2, 2, 2))\n self.stat_intra = np.zeros((2, 2, 2))\n self.dynm_intra = np.zeros((2, 2, 2))\n\n self.equi_leng = np.array([((15.52, 15.52), (15.52, 15.52)), ((12.53, 12.53), (10.20, 10.20))])\n self.mus_leng = np.array([((15.52, 15.52), (15.52, 15.52)), ((12.53, 12.53), (10.20, 10.20))])\n self.mus_derv = np.zeros((2, 2, 2))\n self.mus_inert = 1 * np.ones((2, 2))\n self.mus_forc = np.zeros((2, 2, 2))\n self.ext_forc = np.zeros((2, 2, 2))\n\n self.mus_insert = np.zeros((2, 2, 2, 3))\n\n self.ang_posn = np.zeros((2, 2))\n self.ang_velo = np.zeros((2, 2))\n self.ang_plot = np.zeros((2, 2))\n\n class Cerebellum:\n def __init__(self):\n self.granule = np.zeros((2, 2, 2))\n self.golgi = np.zeros((2, 2, 2))\n self.purkinje = np.ones((2, 2, 2))\n self.olivary = np.zeros((2, 2, 2))\n self.climb = np.zeros((2, 2, 2))\n self.basket = np.zeros((2, 2, 2))\n self.nuclear = np.zeros((2, 2, 2))\n self.rubral = np.zeros((2, 2, 2))\n self.mtm_purkj = np.ones((2, 2, 2))\n\n\n# method class for Column Module\nclass ColFun:\n def __init__(self, ColVar):\n self.Col = ColVar\n self.FNS = FNS()\n self.RK4 = RK4()\n self.ste_size = 0.01\n self.num_deg = self.Col.num_deg\n self.ptssspt = ptssspt(self.num_deg, self.num_deg, self.num_deg)\n self.ptssjnt = ptssjnt(self.num_deg, self.num_deg)\n self.ptss = ptss(self.num_deg, self.num_deg)\n\n # model ParietalCortex for learning present representation\n def ParietalMot(self):\n num = self.num_deg\n step = self.ste_size\n ptss = self.ptssjnt\n FNS = self.FNS\n RK4 = self.RK4\n\n spt_pres = self.Col.ppc.spt_pres\n ltm = self.Col.ppc.ltm_mot_spt\n tran_ltm = np.transpose(ltm, (0, 3, 4, 1, 2))\n sv_spt = self.Col.ppc.sv_mot_spt\n col = self.Col.ppc.ppv\n parse = FNS.parse_axial(col, num)\n\n # reset non-dynamic maps to zero\n self.Col.ppc.sptmp_mot_spt = np.zeros((2, num, num))\n\n # sample present representation of column\n for l in range(2):\n b_max, a_max = parse[l]\n bound = ptss.ptssjnt_bound(b_max, a_max, num, num)\n\n for b in bound[0]:\n for a in bound[1]:\n self.Col.ppc.ltm_mot_spt[l][b][a] = \\\n RK4.rk4(ltm[l][b][a], 0 * ptss.ptssjnt_gradient(b, a, b_max, a_max) *\n (-0.1 * ltm[l][b][a] + spt_pres[l]), step)\n\n self.Col.ppc.sptmp_mot_spt[l][b][a] = ptss.ptssjnt_gradient(b, a, b_max, a_max)\n\n sptmp = self.Col.ppc.sptmp_mot_spt\n pres_est = np.array([[[np.sum(sptmp[l] * tran_ltm[l][k][n])\n for n in range(2)] for k in range(3)] for l in range(2)])\n rev_est = np.array([FNS.rev_mus(pres_est[l], 'spt') for l in range(2)])\n self.Col.ppc.sv_mot_spt = pres_est / (pres_est + rev_est + 0.01)\n\n # check learning of present representation\n self.Col.ppc.mot_spt_est = sv_spt - spt_pres\n\n # model ParietalCortex for learning motor command\n def ParietalSpat(self):\n step = self.ste_size\n num = self.num_deg\n ptts = self.ptssspt\n RK4 = self.RK4\n FNS = self.FNS\n col = self.Col.ppc.ppv\n opv = self.Col.mtc.opv\n rev_opv = FNS.rev_mus(opv, 'col')\n net_prim = FNS.thresh_fn(FNS.diff_mus(self.Col.spc.prim_spin, 'axial'), 0.0)\n rev_prim = FNS.rev_mus(net_prim, 'col')\n spt_targ = self.Col.ppc.spt_targ\n\n dv_mot = self.Col.ppc.dv_spt_mot\n sv_mot = self.Col.ppc.sv_spt_mot\n\n dv_spt = self.Col.ppc.dv_mot_spt\n spt_pres = self.Col.ppc.sv_mot_spt\n\n parse_spt = FNS.parse_targ(dv_spt, num, 'col')\n\n ltm_mot = self.Col.ppc.ltm_spt_mot\n tran_ltm_mot = np.transpose(ltm_mot, (0, 4, 5, 1, 2, 3))\n\n targ = self.Col.ppc.tpv\n pres = col\n old_prog = self.Col.ppc.trk_prog\n erg = self.Col.ppc.dv_erg\n\n\n # reset non-dynamic maps to zero\n self.Col.ppc.sptmp_spt_mot = np.zeros((2, num, num, num))\n\n # ____________________________________________________________________________________________________________\n # sample motor command\n\n \"\"\"\n self.Col.ppc.dv_mot_spt = spt_targ - spt_pres\n \n for l in range(2):\n a_max, b_max, r_max = parse_spt[l]\n bound = ptts.ptssspt_bound(a_max, b_max, r_max, num, num, num)\n\n for a in bound[0]:\n for b in bound[1]:\n for r in bound[2]:\n self.Col.ppc.ltm_spt_mot[l][a][b][r] = \\\n RK4.rk4(ltm_mot[l][a][b][r], -0 * dv_mot[l] *\n (-0.0 * ltm_mot[l][a][b][r] +\n ptts.ptssspt_gradient(a, b, r, a_max, b_max, r_max)), step)\n\n self.Col.ppc.sptmp_spt_mot[l][a][b][r] = ptts.ptssspt_gradient(a, b, r, a_max, b_max, r_max)\n\n sptmp = self.Col.ppc.sptmp_spt_mot\n col_est = np.array([[[np.sum(sptmp[l] * tran_ltm_mot[l][m][n])\n for n in range(2)] for m in range(2)] for l in range(2)])\n\n self.Col.ppc.dv_spt_mot = 1 * col_est + targ - col\n\n # check learning of motor command\n self.Col.ppc.spt_mot_est = col_est + dv_mot\n\n # for coordination only\n self.Col.ppc.tpv = (1 / 2 + -1 * col_est)\n\n self.Col.ppc.sv_spt_mot = targ - col\n\n\n self.Col.ppc.ppv = RK4.rk4(col,\n (1 - col) * (1 * opv + 1 * rev_prim) - col * (1 * rev_opv + 1 * net_prim), step)\n \"\"\"\n # ____________________________________________________________________________________________________________\n # learn limb movement using endogenous random generator\n\n\n self.Col.ppc.sv_spt_mot = targ - col\n \n self.Col.ppc.ppv = RK4.rk4(col,\n (1 - col) * (1 * opv + 1 * rev_prim) - col * (1 * rev_opv + 1 * net_prim), step)\n\n\n dv_err = (targ - pres) * self.Col.mtc.weights\n cond = FNS.cond_fn(dv_err[0], 0.1)\n\n # check motor program\n if FNS.delta_fn(cond, 1) == 1:\n new_prog = (old_prog + 1) % 2\n self.Col.ppc.trk_prog = new_prog\n\n if new_prog == 0:\n\n self.Col.ppc.dv_erg = FNS.rand_prog('col')\n\n else:\n self.Col.ppc.dv_erg = FNS.rev_mus(erg, 'col')\n \n next = self.Col.ppc.dv_erg\n self.Col.ppc.tpv = 1/2 + next\n\n\n # model MotorCortex\n def Motor(self):\n FNS = self.FNS\n RK4 = self.RK4\n step = self.ste_size\n prim_spin = FNS.thresh_fn(self.Col.spc.prim_spin, 0)\n rev_spin = FNS.rev_mus(prim_spin, 'col')\n seco_spin = FNS.thresh_fn(self.Col.spc.seco_spin, 0)\n net_spin = FNS.thresh_fn(prim_spin - seco_spin, 0)\n rev_net = FNS.rev_mus(net_spin, 'col')\n col = self.Col.ppc.ppv\n rev_col = FNS.rev_mus(col, 'col')\n sv_mot = FNS.thresh_fn(self.Col.ppc.sv_spt_mot, 0.0)\n rev_sv = FNS.rev_mus(sv_mot, 'col')\n opv = FNS.thresh_fn(self.Col.mtc.opv, 0)\n ofpv = FNS.thresh_fn(self.Col.mtc.ofpv, 0)\n sfv = FNS.thresh_fn(self.Col.mtc.sfv, 0)\n ifv = FNS.thresh_fn(self.Col.mtc.ifv, 0)\n nucle = FNS.thresh_fn(self.Col.cbm.nuclear, 0)\n rev_nucle = FNS.rev_mus(nucle, 'col')\n GO = self.Col.mtc.speed_mod\n\n # compute movement command\n self.Col.mtc.opv = RK4.rk4(opv,\n (1 - opv) * (GO * sv_mot + 1 * col) - opv * (GO * rev_sv + 1 * rev_col), step)\n\n self.Col.mtc.sfv = RK4.rk4(sfv, (1 - sfv) * (1 * prim_spin) - sfv * (1 * rev_spin), step)\n\n self.Col.mtc.ifv = RK4.rk4(ifv, (1 - ifv) * (1 * net_spin + nucle) - ifv * (1 * rev_net + rev_nucle), step)\n\n self.Col.mtc.ofpv = RK4.rk4(ofpv, -2 * ofpv + (opv + sfv + ifv), step)\n\n\n # model SpinalCord for musculoskeletal variables\n def SpinalSkel(self):\n step = self.ste_size\n RK4 = self.RK4\n FNS = self.FNS\n neck_insert, pelvic_insert = self.Col.spc.mus_insert\n ang_velo = self.Col.spc.ang_velo\n ang_posn = self.Col.spc.ang_posn\n old_neck_len, old_pelvic_len = self.Col.spc.mus_leng\n equi_leng = self.Col.spc.equi_leng\n mus_forc = self.Col.spc.mus_forc\n diff_forc = FNS.cutoff_fn(FNS.diff_force(mus_forc, 'axial'), 0.0)\n extra_mus = FNS.thresh_fn(self.Col.spc.extra_mus, 0)\n inert = self.Col.spc.mus_inert\n\n # compute joint angles\n self.Col.spc.ang_velo = RK4.rk4(ang_velo, (1 / inert) * (diff_forc - 5 * ang_velo), step)\n self.Col.spc.ang_posn = RK4.rk4(ang_posn, 1 * ang_velo, step)\n self.Col.spc.ang_plot = FNS.angle_bound(FNS.bound_fn(1 * ang_posn, 1), 'col')\n\n new_neck_pos = neck_insert\n new_neck_len = FNS.mus_len(new_neck_pos, 'axial')\n new_neck_derv = FNS.mus_derv(old_neck_len, new_neck_len, step, 'axial')\n\n self.Col.spc.mus_leng[0] = new_neck_len\n self.Col.spc.mus_derv[0] = new_neck_derv\n\n new_pelvic_pos = pelvic_insert\n new_pelvic_len = FNS.mus_len(new_pelvic_pos, 'axial')\n new_pelvic_derv = FNS.mus_derv(old_pelvic_len, new_pelvic_len, step, 'axial')\n\n self.Col.spc.mus_leng[1] = new_pelvic_len\n self.Col.spc.mus_derv[1] = new_pelvic_derv\n\n new_len = np.array((new_neck_len, new_pelvic_len))\n self.Col.spc.mus_forc = FNS.thresh_fn(1 * extra_mus + 1 * FNS.col_mus(new_len - equi_leng), 0)\n\n\n # model SpinalCord for neural variables\n def SpinalCore(self):\n\n #for PAN02.py\n FNS = self.FNS\n ofpv = 1 * FNS.thresh_fn(self.Col.mtc.ofpv, 0)\n\n # ____________________________________________________________________________________________________________\n\n step = self.ste_size\n FNS = self.FNS\n RK4 = self.RK4\n GO = self.Col.mtc.speed_mod\n sv_mot = FNS.thresh_fn(self.Col.ppc.sv_spt_mot, 0.0)\n rev_sv = FNS.rev_mus(sv_mot, 'col')\n opv = self.Col.mtc.opv\n ia_int = FNS.thresh_fn(self.Col.spc.ia_int, 0)\n rev_ia_int = FNS.rev_mus(ia_int, 'col')\n alpha_moto = FNS.thresh_fn(self.Col.spc.alpha_moto, 0)\n renshaw = FNS.thresh_fn(self.Col.spc.renshaw, 0)\n rev_renshaw = FNS.rev_mus(renshaw, 'col')\n prim_spin = FNS.thresh_fn(self.Col.spc.prim_spin, 0)\n seco_spin = FNS.thresh_fn(self.Col.spc.seco_spin, 0)\n rubral = FNS.thresh_fn(self.Col.cbm.rubral, 0)\n mus_leng = self.Col.spc.mus_leng\n mus_derv = self.Col.spc.mus_derv\n mus_forc = FNS.thresh_fn(self.Col.spc.mus_forc, 0.0)\n stat_gamma = FNS.thresh_fn(self.Col.spc.stat_gamma, 0)\n dynm_gamma = FNS.thresh_fn(self.Col.spc.dynm_gamma, 0)\n stat_intra = FNS.thresh_fn(self.Col.spc.stat_intra, 0)\n dynm_intra = FNS.thresh_fn(self.Col.spc.dynm_intra, 0)\n equi_leng = self.Col.spc.equi_leng\n stat_input = FNS.thresh_fn(stat_intra + 1 * FNS.col_mus(mus_leng - equi_leng), 0)\n dynm_input = FNS.thresh_fn(FNS.diff_mus(dynm_intra, 'axial') + 1 * FNS.col_mus(mus_derv), 0)\n extra_mus = FNS.thresh_fn(self.Col.spc.extra_mus, 0)\n\n big_size = 1 + 5 * ofpv\n med_size = 0.1 + 0.5 * alpha_moto\n sma_size = 0.01 + 0.05 * ofpv\n\n # process movement command\n self.Col.spc.ia_int = \\\n RK4.rk4(ia_int, 0.5 * (10 - ia_int) * (ofpv + prim_spin) -\n ia_int * (1 + renshaw + rev_ia_int), step)\n\n self.Col.spc.alpha_moto = \\\n RK4.rk4(alpha_moto, (5 * big_size - alpha_moto) * (ofpv + rubral + prim_spin) -\n (alpha_moto + 1) * (0.5 + renshaw + rev_ia_int), step)\n\n self.Col.spc.renshaw = \\\n RK4.rk4(renshaw, (5 * big_size - renshaw) * (med_size * alpha_moto) -\n renshaw * (1 + rev_renshaw + 5 * rubral), step)\n\n self.Col.spc.extra_mus = \\\n RK4.rk4(extra_mus, (big_size - extra_mus) * (sma_size * alpha_moto) -\n sma_size * extra_mus - mus_forc, step)\n\n self.Col.spc.stat_gamma = \\\n RK4.rk4(stat_gamma, (2 - stat_gamma) * (1.0 * opv) -\n (1 + stat_gamma) * (0.1 + 0.2 * FNS.sigmoid_fn(renshaw, 0.2, 1)), step)\n\n self.Col.spc.stat_intra = RK4.rk4(stat_intra, -1 * stat_intra + (2 - stat_intra) * stat_gamma, step)\n\n self.Col.spc.dynm_gamma = \\\n RK4.rk4(dynm_gamma, (5 - dynm_gamma) * (1 * GO * sv_mot) -\n (2 + dynm_gamma) * (0.1 + GO * rev_sv + 0.5 * FNS.sigmoid_fn(renshaw, 0.2, 1)), step)\n\n self.Col.spc.dynm_intra = RK4.rk4(dynm_intra, -5 * dynm_intra + (2 - dynm_intra) * dynm_gamma, step)\n\n self.Col.spc.prim_spin = RK4.rk4(prim_spin, -2 * prim_spin + (1 - prim_spin) * (stat_input + dynm_input), step)\n\n self.Col.spc.seco_spin = RK4.rk4(seco_spin, -2 * seco_spin + (1 - seco_spin) * stat_input, step)\n\n # model Cerebellum\n def Cerebellum(self):\n step = self.ste_size\n FNS = self.FNS\n RK4 = self.RK4\n GO = self.Col.mtc.speed_mod\n sv_mot = self.Col.ppc.sv_spt_mot\n granule = FNS.thresh_fn(self.Col.cbm.granule, 0)\n golgi = FNS.thresh_fn(self.Col.cbm.golgi, 0)\n basket = FNS.thresh_fn(self.Col.cbm.basket, 0)\n prim_spin = FNS.thresh_fn(self.Col.spc.prim_spin, 0)\n seco_spin = FNS.thresh_fn(self.Col.spc.seco_spin, 0)\n net_spin = FNS.thresh_fn(prim_spin - seco_spin, 0)\n climb = FNS.thresh_fn(self.Col.cbm.climb, 0)\n olive = FNS.thresh_fn(self.Col.cbm.olivary, 0)\n purkj = FNS.thresh_fn(self.Col.cbm.purkinje, 0)\n rev_purkj = FNS.rev_mus(purkj, 'col')\n nuclear = FNS.thresh_fn(self.Col.cbm.nuclear, 0)\n rubral = FNS.thresh_fn(self.Col.cbm.rubral, 0)\n mtm = self.Col.cbm.mtm_purkj\n\n self.Col.cbm.granule = \\\n RK4.rk4(granule, -2 * granule + (1 - granule) * (0.1 + 1 * GO * sv_mot) - (0.5 + granule) * golgi, step)\n\n self.Col.cbm.golgi = RK4.rk4(golgi, -golgi + (2 - golgi) * (1 * GO * sv_mot * granule), step)\n\n self.Col.cbm.basket = RK4.rk4(basket, -basket + (2 - basket) * granule, step)\n\n self.Col.cbm.mtm_purkj = RK4.rk4(mtm, 0.01 * granule * ((1 - mtm) - 10 * climb * mtm), step)\n\n self.Col.cbm.purkinje = \\\n RK4.rk4(purkj, -2 * purkj +\n (1 - purkj) * (10 * granule * mtm + 1 * climb + FNS.sigmoid_fn(purkj, 0.2, 2) + 0.5) -\n (0.5 + purkj) * (0.5 * rev_purkj + 1 * basket), step)\n\n self.Col.cbm.climb = \\\n RK4.rk4(climb, -climb + (1 - climb) * (climb + 10 * net_spin) - (0.5 + climb) * (10 * olive), step)\n\n self.Col.cbm.olivary = RK4.rk4(olive, -0.1 * olive + climb, step)\n\n\n self.Col.cbm.nuclear = \\\n RK4.rk4(nuclear, -2 * nuclear + (1 - nuclear) * (0.1 + 10 * net_spin) - (0.5 + nuclear) * 2 * purkj, step)\n\n self.Col.cbm.rubral = RK4.rk4(rubral, -0.1 * rubral + nuclear, step)\n\n\n\n\n\n\n\n","sub_path":"COLM.py","file_name":"COLM.py","file_ext":"py","file_size_in_byte":17559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"396447168","text":"import requests\nimport time\nimport random\nimport json\nfrom util import *\n\n# base_url = \"https://lambda-treasure-hunt.herokuapp.com/api/adv/\"\n\n# auth_header = {\"Authorization\": \"Token 724b204984aee234274039fae647bc65240d399e\"}\n\n# reverse = {\"n\": \"s\", \"s\": \"n\", \"e\": \"w\", \"w\": \"e\"}\ncompleted = set()\n\npath_graph = {}\nnames = {}\n\n\ndef save():\n with open(\"path-graph.json\", \"w\", encoding=\"utf8\") as f:\n json.dump(path_graph, f)\n with open(\"room-names.json\", \"w\", encoding=\"utf8\") as f:\n json.dump(names, f)\n\n\ndef add_to_graph(room):\n path_graph[room[\"room_id\"]] = dict(zip(room[\"exits\"], [\"?\"] * len(room[\"exits\"])))\n names[room[\"title\"]] = room[\"room_id\"]\n save()\n\n\ndef connect_rooms(current, last, direction):\n path_graph[current[\"room_id\"]][reverse[direction]] = last[\"room_id\"]\n path_graph[last[\"room_id\"]][direction] = current[\"room_id\"]\n save()\n\n\nresponse = requests.get(f\"{base_url}init/\", headers=auth_header)\ncurrent_room = response.json()\nadd_to_graph(current_room)\n\nstarting_path = [current_room]\n\ntime.sleep(current_room[\"cooldown\"])\n\nresponse = requests.post(\n f\"{base_url}move/\",\n json={\"direction\": \"w\", \"next_room_id\": \"1\"},\n headers=auth_header,\n)\nshop = response.json()\n\nadd_to_graph(shop)\nconnect_rooms(current=shop, last=current_room, direction=\"w\")\ntime.sleep(shop[\"cooldown\"])\n\nresponse = requests.post(\n f\"{base_url}move/\",\n json={\"direction\": \"e\", \"next_room_id\": \"0\"},\n headers=auth_header,\n)\nhome = response.json()\ntime.sleep(home[\"cooldown\"])\n\nstarting_direction = random.choice([\"n\", \"s\", \"e\"])\n\nresponse = requests.post(\n f\"{base_url}move/\", json={\"direction\": starting_direction}, headers=auth_header\n)\nnext_room = response.json()\nstarting_path.append(next_room)\nadd_to_graph(next_room)\n\ntime.sleep(next_room[\"cooldown\"])\n\nconnect_rooms(current=next_room, last=current_room, direction=starting_direction)\n\nprint(starting_direction)\n# with open(\"path-graph.pkl\", \"rb\") as f:\n# print(json.load(f))\n\ns = Stack()\ns.push([next_room])\n\ndirection = starting_direction\n\nwhile s.size() > 0:\n current_path = s.pop()\n room = current_path[-1]\n\n room_exits = path_graph[room[\"room_id\"]]\n if \"?\" in room_exits.values():\n possible_exits = [key for key, value in room_exits.items() if value == \"?\"]\n else:\n possible_exits = [key for key in room_exits.keys()]\n possible_exits.remove(reverse[direction])\n\n direction = random.choice(possible_exits)\n\n response = requests.post(\n f\"{base_url}move/\", json={\"direction\": direction}, headers=auth_header\n )\n next_room = response.json()\n print(f'{next_room[\"messages\"][0]} to {next_room[\"title\"]}: {next_room[\"cooldown\"]} items: {next_room[\"items\"]}')\n\n if next_room[\"room_id\"] not in path_graph.keys():\n add_to_graph(next_room)\n connect_rooms(current=next_room, last=room, direction=direction)\n\n if len(path_graph) == 500:\n break\n\n time.sleep(next_room[\"cooldown\"])\n\n if len(next_room[\"exits\"]) == 1 or \"?\" not in path_graph[next_room['room_id']].values():\n # set the return path back to a room that has unexplored exit\n q = Queue()\n q.enqueue([next_room[\"room_id\"]])\n\n return_path = []\n visited = []\n while q.size() > 0:\n retrace = q.dequeue()\n back_room = retrace[-1]\n\n if \"?\" in path_graph[back_room].values():\n return_path = retrace\n break\n\n if back_room not in visited:\n visited.append(back_room)\n\n possible_directions = [\n key for key, value in path_graph[back_room].items() if value != \"?\"\n ]\n\n # if len(retrace) > 1 and len(possible_directions) > 1:\n # possible_directions.remove(reverse[retrace[-2][1]])\n # direction = random.choice(possible_directions)\n\n # retrace[-1][1] = direction\n\n for direction in possible_directions:\n copy_retrace = retrace[:]\n back_next = path_graph[back_room][direction]\n # if \"?\" in path_graph[back_next[0]].values():\n # return_path = retrace\n # break\n copy_retrace.append(back_next)\n q.enqueue(copy_retrace)\n\n print(return_path)\n\n for i in range(len(return_path) - 1):\n cur_room_id = return_path[i]\n next_room_id = return_path[i + 1]\n step = [key for key, value in path_graph[cur_room_id].items() if value == next_room_id]\n response = requests.post(\n f\"{base_url}move/\",\n json={\"direction\": step[0], \"next_room_id\": f\"{next_room_id}\"},\n headers=auth_header,\n )\n\n new_room = response.json()\n\n for message in new_room[\"messages\"]:\n print(message)\n print(f'You can move in {new_room[\"cooldown\"]} seconds')\n\n next_room = new_room\n time.sleep(new_room[\"cooldown\"])\n print(f'Length of graph {len(path_graph)}')\n # break\n\n copy_path = current_path[:]\n copy_path.append(next_room)\n s.push(copy_path)\n","sub_path":"scriptsapp/traverse.py","file_name":"traverse.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"339094421","text":"import os\nfrom pymongo import MongoClient\nimport pprint\nfrom deepdiff import DeepDiff\nfrom diff_Outputter import print_diff\nfrom diff_Outputter import print_test_name\nfrom mongo_cleanup_function import cleanup\n\ntest_name = \"

Vanilla Test Results:

\\n\"\nwas_printed = False\n\nTHIS_FOLDER = os.path.dirname(os.path.abspath(__file__))\ndefault_file_location = os.path.join(THIS_FOLDER, 'testResult.html')\n\nend_date = '2019-05-29'\nend_date_str = \"filters.vanilla.\" + end_date\n\n\ndef mongo_compare_vanilla(MONGO_DB_TEST, MONGO_DB_REFERENCE, COLLECTION_TEST, COLLECTION_REFERENCE, mongo_list, MONGO_HOST_CONNECT):\n SHOULD_NOT_FAIL = True\n global was_printed\n\n cash_position = {\"filters.tracking.type\": \"CashPosition\"}\n position_holding = {\"filters.tracking.type\": \"PositionHolding\"}\n private_equity = {\"filters.tracking.type\": \"PrivateEquityHolding\"}\n client_type = {\"filters.tracking.type\": \"Client\"}\n account_type = {\"filters.tracking.type\": \"Account\"}\n\n # db.getCollection('tracking').find({})\n client = MongoClient(MONGO_HOST_CONNECT, 27017)\n db_test = client[MONGO_DB_TEST]\n collection = db_test[COLLECTION_TEST]\n db_reference = client[MONGO_DB_REFERENCE]\n collection_reference = db_reference[COLLECTION_REFERENCE]\n\n # Getting all names of documents by Type in reference\n # tracking_collection_ref = collection_reference.find({\"type\": \"CashPosition\"}) # .sort()\n form_reference = collection_reference.count_documents({})\n print(\"Documents found in Reference: \" + str(form_reference))\n from_test = collection.count_documents({})\n print(\"Documents found in Test: \" + str(from_test))\n index = 0\n for entry_type in mongo_list:\n tracking_collection_ref = collection_reference.find(entry_type)\n for ref_document in tracking_collection_ref:\n test_id = \"Test Document Not Found\"\n ref_id = \"Reference Document Not Found\"\n index += 1\n if entry_type == cash_position:\n test_document = collection.find_one({\"filters.tracking.type\": ref_document[\"filters\"][\"tracking\"][\"type\"],\n \"filters.tracking.reporting_currency\": ref_document[\"filters\"][\"tracking\"][\"reporting_currency\"],\n \"filters.tracking.currency_split_type\": ref_document[\"filters\"][\"tracking\"][\"currency_split_type\"],\n \"filters.tracking.name\": ref_document[\"filters\"][\"tracking\"][\"name\"],\n \"filters.tracking.analytics_table_type\": ref_document[\"filters\"][\"tracking\"][\"analytics_table_type\"],\n \"filters.tracking.parent_portfolio.name\": ref_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"name\"]\n })\n\n elif entry_type == position_holding:\n test_document = collection.find_one({\"filters.tracking.type\": ref_document[\"filters\"][\"tracking\"][\"type\"],\n \"filters.tracking.name\": ref_document[\"filters\"][\"tracking\"][\"name\"],\n \"filters.tracking.reporting_currency\": ref_document[\"filters\"][\"tracking\"][\"reporting_currency\"],\n \"filters.tracking.analytics_table_type\": ref_document[\"filters\"][\"tracking\"][\"analytics_table_type\"],\n \"filters.tracking.position.name\": ref_document[\"filters\"][\"tracking\"][\"position\"][\"name\"],\n # \"filters.tracking.parent_portfolio.sleeve.firm_provided_key\": ref_document['filters']['tracking']['parent_portfolio']['sleeve']['firm_provided_key']\n })\n elif entry_type == private_equity:\n test_document = collection.find_one({\"filters.tracking.type\": ref_document[\"filters\"][\"tracking\"][\"type\"],\n \"filters.tracking.name\": ref_document[\"filters\"][\"tracking\"][\"name\"],\n \"filters.tracking.reporting_currency\": ref_document[\"filters\"][\"tracking\"][\"reporting_currency\"],\n \"filters.tracking.position.name\": ref_document[\"filters\"][\"tracking\"][\"position\"][\"name\"]\n })\n # db.getCollection('tracking').find({\"filters.tracking.parent_portfolio.sleeve.account.client.firm_provided_key\": \"AA120A\", \"filters.tracking.type\": \"Client\", \"filters.tracking.reporting_currency\": \"CAD\"})\n elif entry_type == client_type:\n test_document = collection.find_one({\"filters.tracking.type\": ref_document[\"filters\"][\"tracking\"][\"type\"],\n \"filters.tracking.reporting_currency\": ref_document[\"filters\"][\"tracking\"][\"reporting_currency\"],\n \"filters.tracking.parent_portfolio.sleeve.account.client.firm_provided_key\": ref_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"][\"firm_provided_key\"],\n })\n\n # Isolate testable portion of Client Type to vanilla (filters.vanilla.2019-05-29.parent_portfolio.sleeve.account.client)\n test_temp_vanilla = test_document[\"filters\"][\"vanilla\"][\"2019-05-29\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"]\n ref_temp_vanilla = ref_document[\"filters\"][\"vanilla\"][\"2019-05-29\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"]\n del test_document[\"filters\"][\"vanilla\"][\"2019-05-29\"]\n del ref_document[\"filters\"][\"vanilla\"][\"2019-05-29\"]\n test_document[\"filters\"][\"vanilla\"] = test_temp_vanilla\n ref_document[\"filters\"][\"vanilla\"] = ref_temp_vanilla\n # db.getCollection('tracking').find({\"filters.tracking.parent_portfolio.sleeve.account.firm_provided_key\": \"AA120A\", \"filters.tracking.type\": \"Client\", \"filters.tracking.reporting_currency\": \"CAD\"})\n elif entry_type == account_type:\n test_document = collection.find_one({\"filters.tracking.type\": ref_document[\"filters\"][\"tracking\"][\"type\"],\n \"filters.tracking.reporting_currency\": ref_document[\"filters\"][\"tracking\"][\"reporting_currency\"],\n \"filters.tracking.parent_portfolio.sleeve.account.firm_provided_key\": ref_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"firm_provided_key\"],\n })\n # with open(\"Output.txt\", mode=\"a+\") as outputable:\n # print(index, file=outputable)\n # print(ref_document[\"filters\"][\"tracking\"][\"type\"], file=outputable)\n # print(test_document[\"filters\"][\"tracking\"][\"type\"], file=outputable)\n # print(ref_document[\"filters\"][\"tracking\"][\"reporting_currency\"], file=outputable)\n # print(test_document[\"filters\"][\"tracking\"][\"reporting_currency\"], file=outputable)\n # print(ref_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"][\"display_name\"], file=outputable)\n # print(test_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"][\"display_name\"], file=outputable)\n # print(ref_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"][\"firm_provided_key\"], file=outputable)\n # print(test_document[\"filters\"][\"tracking\"][\"parent_portfolio\"][\"sleeve\"][\"account\"][\"client\"][\"firm_provided_key\"], file=outputable)\n # print(ref_document[\"_id\"], file=outputable)\n # print(test_document[\"_id\"], file=outputable)\n\n test_temp_vanilla = test_document[\"filters\"][\"vanilla\"][\"2019-05-29\"][\"parent_portfolio\"][\"sleeve\"][\"account\"]\n ref_temp_vanilla = ref_document[\"filters\"][\"vanilla\"][\"2019-05-29\"][\"parent_portfolio\"][\"sleeve\"][\"account\"]\n del test_document[\"filters\"][\"vanilla\"][\"2019-05-29\"]\n del ref_document[\"filters\"][\"vanilla\"][\"2019-05-29\"]\n test_document[\"filters\"][\"vanilla\"] = test_temp_vanilla\n ref_document[\"filters\"][\"vanilla\"] = ref_temp_vanilla\n else:\n test_document = None\n print(\"No Test document with these parameters:\" + str(ref_document))\n\n # # Brakes Test to check Output - filters.vanilla.2019-05-29.SpotBasicPerfValuesCumulReturn\n # ref_document[\"filters\"][\"vanilla\"][end_date][\"SpotBasicPerfValuesCumulReturn\"] = 0.21354641\n\n # Deletes the dynamic keys from the test (They are not comparable)\n if test_document is not None:\n test_id = test_document[\"_id\"]\n ref_id = ref_document[\"_id\"]\n try:\n test_document = cleanup(test_document, entry_type)\n ref_document = cleanup(ref_document, entry_type)\n\n except KeyError or TypeError:\n print(\"Tracking not found in the tested Position:\" + str(KeyError))\n\n diff = DeepDiff(ref_document, test_document, significant_digits=4, ignore_order=True,\n report_repetition=False, ignore_type_in_groups=[(int, float)])\n\n if diff != {}:\n out_test_name = \"ObjectId: \" + str(test_id)\n out_ref_name = \"ObjectId: \" + str(ref_id)\n print_test_name(test_name, was_printed)\n print_test_name(str(db_test) + \" VS \" + str(db_reference) + \"
\\n\", False)\n print_test_name(out_test_name + \" VS \" + out_ref_name, False)\n was_printed = True\n print_diff(diff)\n SHOULD_NOT_FAIL = False\n\n print(index)\n print(\"Vanilla Test Finished.\")\n return SHOULD_NOT_FAIL\n\n\n\n\n","sub_path":"step_verification/mongo_compare_vanilla.py","file_name":"mongo_compare_vanilla.py","file_ext":"py","file_size_in_byte":10288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"322593966","text":"\nimport app_greynoise_declare\n\nfrom splunktaucclib.rest_handler.endpoint import (\n field,\n validator,\n RestModel,\n MultipleModel,\n)\nfrom splunktaucclib.rest_handler import admin_external, util\nfrom splunk_aoblib.rest_migration import ConfigMigrationHandler\n\nfrom greynoise_account_validation import GreyNoiseAPIValidation, GreyNoiseScanDeployment\n\nutil.remove_http_proxy_env_vars()\n\n\nfields_logging = [\n field.RestField(\n 'loglevel',\n required=False,\n encrypted=False,\n default='INFO',\n validator=None\n )\n]\nmodel_logging = RestModel(fields_logging, name='logging')\n\n\nfields_parameters = [\n field.RestField(\n 'api_key',\n required=True,\n encrypted=True,\n default=None,\n validator=GreyNoiseAPIValidation()\n )\n]\nmodel_parameters = RestModel(fields_parameters, name='parameters')\n\nfields_scan_deployment = [\n field.RestField(\n 'ip_indexes',\n required=True,\n encrypted=False,\n default='main',\n validator=validator.String(\n min_len=1, \n max_len=8192, \n )\n ),\n field.RestField(\n 'cim_ip_fields',\n required=True,\n encrypted=False,\n default=None,\n validator=validator.String(\n min_len=1, \n max_len=8192, \n )\n ),\n field.RestField(\n 'enable_ss',\n required=False,\n encrypted=False,\n default=None,\n validator=GreyNoiseScanDeployment()\n ),\n field.RestField(\n 'other_ip_fields',\n required=False,\n encrypted=False,\n default=None,\n validator=None\n ),\n field.RestField(\n 'scan_start_time',\n required=True,\n encrypted=False,\n default=None,\n validator=None\n ),\n field.RestField(\n 'force_enable_ss',\n required=False,\n encrypted=False,\n default=None,\n validator=None\n )\n]\nmodel_scan_deployment = RestModel(fields_scan_deployment, name='scan_deployment')\n\nendpoint = MultipleModel(\n 'app_greynoise_settings',\n models=[\n model_logging, \n model_parameters,\n model_scan_deployment\n ],\n)\n\n\nif __name__ == '__main__':\n admin_external.handle(\n endpoint,\n handler=ConfigMigrationHandler,\n )\n","sub_path":"bin/app_greynoise_rh_settings.py","file_name":"app_greynoise_rh_settings.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"221602486","text":"import os\nimport tools\nimport sad\nimport feat\n\ndef run_bic(attr):\n path = tools.set_path()\n sadname = attr['sad']\n featname = attr['mfcc']\n bicname = attr['bic']\n command = '%s/sbic --segmentation=%s --label=speech %s %s'\n exe_cmd = command%(path['audioseg'],sadname,featname,bicname)\n os.system(exe_cmd)\n return\n\n\nif __name__=='__main__':\n wavname = '/Users/navidshokouhi/Downloads/unimaquarie/projects/ami_sample/amicorpus/ES2002a/audio/ES2002a.Mix-Headset.wav'\n basename = tools.gen_uid(wavname)\n sadname = './%s_sad.txt'%(basename)\n featname = './%s.mfc'%(basename)\n bicname = './%s_bic.txt'%(basename)\n attr = {'audio':wavname,\n 'sad':sadname,\n 'mfcc':featname,\n 'bic':bicname}\n sad.run_sad(attr)\n feat.run_mfcc(attr)\n run_bic(attr)\n \n","sub_path":"code/bic.py","file_name":"bic.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"120975069","text":"\"\"\"\nShow plotting caustics using different methods.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport MulensModel as mm\n\n\ns = 1.2\nq = 0.5\nn_points = 200\n\ncolor = np.linspace(0., 1., n_points)\n\n# First, we use standard procedure to plot the caustic. You will see that\n# the points are distributed non-uniformly, i.e., the density is higher\n# near cusps. We also add color to indicate order of plotting.\n# It turns out to be a complicated shape.\ncaustic = mm.Caustics(s=s, q=q)\ncaustic.plot(c=color, n_points=n_points)\nplt.axis('equal')\nplt.colorbar()\nplt.title('standard plotting')\n\n# Second, we use uniform sampling. The density of points is constant.\n# Here the color scale indicates x_caustic values.\nplt.figure()\nsampling = mm.UniformCausticSampling(s=s, q=q)\npoints = [sampling.caustic_point(c) for c in color]\nx = [p.real for p in points]\ny = [p.imag for p in points]\nplt.scatter(x, y, c=color)\nplt.axis('equal')\nplt.colorbar()\nplt.title('uniform sampling plotting')\n\nplt.show()\n\n","sub_path":"examples/example_14_caustic_plotting.py","file_name":"example_14_caustic_plotting.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"391721838","text":"import json\nimport logging\nfrom pathlib import Path\nimport re\nimport subprocess\nfrom subprocess import CalledProcessError\nimport sys\nimport traceback\nfrom typing import List, Dict, Union\nimport uuid\n\nimport geopyspark as gps\nfrom geopyspark import TiledRasterLayer, LayerType\nimport pkg_resources\nfrom py4j.java_gateway import JavaGateway\nfrom py4j.protocol import Py4JJavaError\n\nfrom openeo.error_summary import ErrorSummary\nfrom openeo.internal.process_graph_visitor import ProcessGraphVisitor\nfrom openeo.util import ensure_dir\nfrom openeo_driver import backend\nfrom openeo_driver.backend import ServiceMetadata, BatchJobMetadata\nfrom openeo_driver.errors import JobNotFinishedException, JobNotStartedException\nfrom openeo_driver.utils import parse_rfc3339\nfrom openeogeotrellis.configparams import ConfigParams\nfrom openeogeotrellis.geotrellis_tile_processgraph_visitor import GeotrellisTileProcessGraphVisitor\nfrom openeogeotrellis.GeotrellisImageCollection import GeotrellisTimeSeriesImageCollection\nfrom openeogeotrellis.job_registry import JobRegistry\nfrom openeogeotrellis.layercatalog import get_layer_catalog\nfrom openeogeotrellis.service_registry import InMemoryServiceRegistry, ZooKeeperServiceRegistry, AbstractServiceRegistry\nfrom openeogeotrellis.utils import kerberos\nfrom openeogeotrellis.utils import normalize_date\n\nlogger = logging.getLogger(__name__)\n\n\nclass GpsSecondaryServices(backend.SecondaryServices):\n \"\"\"Secondary Services implementation for GeoPySpark backend\"\"\"\n\n def __init__(self, service_registry: AbstractServiceRegistry):\n self.service_registry = service_registry\n\n def service_types(self) -> dict:\n return {\n \"WMTS\": {\n \"configuration\": {\n \"version\": {\n \"type\": \"string\",\n \"description\": \"The WMTS version to use.\",\n \"default\": \"1.0.0\",\n \"enum\": [\n \"1.0.0\"\n ]\n }\n },\n # TODO?\n \"process_parameters\": [],\n \"links\": [],\n }\n }\n\n def list_services(self) -> List[ServiceMetadata]:\n return list(self.service_registry.get_metadata_all().values())\n\n def service_info(self, service_id: str) -> ServiceMetadata:\n return self.service_registry.get_metadata(service_id)\n\n def remove_service(self, service_id: str) -> None:\n self.service_registry.stop_service(service_id)\n\n\nclass GeoPySparkBackendImplementation(backend.OpenEoBackendImplementation):\n\n def __init__(self):\n # TODO: do this with a config instead of hardcoding rules?\n self._service_registry = (\n InMemoryServiceRegistry() if ConfigParams().is_ci_context\n else ZooKeeperServiceRegistry()\n )\n\n super().__init__(\n secondary_services=GpsSecondaryServices(service_registry=self._service_registry),\n catalog=get_layer_catalog(service_registry=self._service_registry),\n batch_jobs=GpsBatchJobs(),\n )\n\n def health_check(self) -> str:\n from pyspark import SparkContext\n sc = SparkContext.getOrCreate()\n count = sc.parallelize([1, 2, 3]).map(lambda x: x * x).sum()\n return 'Health check: ' + str(count)\n\n def file_formats(self) -> dict:\n return {\n \"input\": {\n \"GeoJSON\": {\n \"gis_data_type\": [\"vector\"]\n }\n },\n \"output\": {\n \"GTiff\": {\n \"title\": \"GeoTiff\",\n \"gis_data_types\": [\"raster\"],\n },\n \"CovJSON\": {\n \"gis_data_types\": [\"other\"], # TODO: also \"raster\", \"vector\", \"table\"?\n },\n \"NetCDF\": {\n \"gis_data_types\": [\"other\"], # TODO: also \"raster\", \"vector\", \"table\"?\n },\n },\n }\n\n def load_disk_data(self, format: str, glob_pattern: str, options: dict, viewing_parameters: dict) -> object:\n if format != 'GTiff':\n raise NotImplementedError(\"The format is not supported by the backend: \" + format)\n\n date_regex = options['date_regex']\n\n if glob_pattern.startswith(\"hdfs:\"):\n kerberos()\n\n from_date = normalize_date(viewing_parameters.get(\"from\", None))\n to_date = normalize_date(viewing_parameters.get(\"to\", None))\n\n left = viewing_parameters.get(\"left\", None)\n right = viewing_parameters.get(\"right\", None)\n top = viewing_parameters.get(\"top\", None)\n bottom = viewing_parameters.get(\"bottom\", None)\n srs = viewing_parameters.get(\"srs\", None)\n band_indices = viewing_parameters.get(\"bands\")\n\n sc = gps.get_spark_context()\n\n gateway = JavaGateway(eager_load=True, gateway_parameters=sc._gateway.gateway_parameters)\n jvm = gateway.jvm\n\n extent = jvm.geotrellis.vector.Extent(float(left), float(bottom), float(right), float(top)) \\\n if left is not None and right is not None and top is not None and bottom is not None else None\n\n pyramid = jvm.org.openeo.geotrellis.geotiff.PyramidFactory.from_disk(glob_pattern, date_regex) \\\n .pyramid_seq(extent, srs, from_date, to_date)\n\n temporal_tiled_raster_layer = jvm.geopyspark.geotrellis.TemporalTiledRasterLayer\n option = jvm.scala.Option\n levels = {pyramid.apply(index)._1(): TiledRasterLayer(LayerType.SPACETIME, temporal_tiled_raster_layer(\n option.apply(pyramid.apply(index)._1()), pyramid.apply(index)._2())) for index in\n range(0, pyramid.size())}\n\n image_collection = GeotrellisTimeSeriesImageCollection(\n pyramid=gps.Pyramid(levels),\n service_registry=self._service_registry,\n metadata={}\n )\n\n return image_collection.band_filter(band_indices) if band_indices else image_collection\n\n def visit_process_graph(self, process_graph: dict) -> ProcessGraphVisitor:\n return GeotrellisTileProcessGraphVisitor().accept_process_graph(process_graph)\n\n def summarize_exception(self, error: Exception) -> Union[ErrorSummary, Exception]:\n if isinstance(error, Py4JJavaError):\n java_exception = error.java_exception\n\n while java_exception.getCause() is not None and java_exception != java_exception.getCause():\n java_exception = java_exception.getCause()\n\n java_exception_class_name = java_exception.getClass().getName()\n java_exception_message = java_exception.getMessage()\n\n no_data_found = (java_exception_class_name == 'java.lang.AssertionError'\n and \"Cannot stitch empty collection\" in java_exception_message)\n\n is_client_error = java_exception_class_name == 'java.lang.IllegalArgumentException' or no_data_found\n summary = \"Cannot construct an image because the given boundaries resulted in an empty image collection\" if no_data_found else java_exception_message\n\n return ErrorSummary(error, is_client_error, summary)\n\n return error\n\n\nclass GpsBatchJobs(backend.BatchJobs):\n\n def __init__(self):\n super().__init__()\n self._output_root_dir = Path(\"/data/projects/OpenEO/\")\n\n def _parse_job_info(self, job_info: dict) -> BatchJobMetadata:\n status = job_info.get(\"status\")\n if status == \"submitted\":\n status = \"created\"\n return BatchJobMetadata(\n id=job_info[\"job_id\"],\n process=json.loads(job_info[\"specification\"]),\n status=status,\n created=parse_rfc3339(job_info[\"created\"]) if \"created\" in job_info else None\n )\n\n def create_job(self, user_id: str, job_specification: dict, api_version: str) -> BatchJobMetadata:\n job_id = str(uuid.uuid4())\n with JobRegistry() as registry:\n job_info = registry.register(\n job_id=job_id, user_id=user_id,\n api_version=api_version, specification=job_specification\n )\n return BatchJobMetadata(\n id=job_id, process=job_specification, status=job_info[\"status\"],\n created=parse_rfc3339(job_info[\"created\"])\n )\n\n def get_job_info(self, job_id: str, user_id: str) -> BatchJobMetadata:\n with JobRegistry() as registry:\n job_info = registry.get_job(job_id, user_id)\n return self._parse_job_info(job_info)\n\n def get_user_jobs(self, user_id: str) -> List[BatchJobMetadata]:\n with JobRegistry() as registry:\n return [\n self._parse_job_info(job_info)\n for job_info in registry.get_user_jobs(user_id)\n ]\n\n def _get_job_output_dir(self, job_id: str) -> Path:\n return ensure_dir(self._output_root_dir / job_id)\n\n def start_job(self, job_id: str, user_id: str):\n from pyspark import SparkContext\n\n with JobRegistry() as registry:\n job_info = registry.get_job(job_id, user_id)\n api_version = job_info.get('api_version')\n\n current_status = job_info['status']\n if current_status in ['queued', 'running']:\n return\n elif current_status != 'created':\n # TODO: is this about restarting a job?\n registry.mark_ongoing(job_id, user_id)\n registry.set_application_id(job_id, user_id, None)\n registry.set_status(job_id, user_id, 'created')\n\n spec = json.loads(job_info.get('specification'))\n extra_options = spec.get('job_options', {})\n\n driver_memory = extra_options.get(\"driver-memory\", \"22G\")\n executor_memory = extra_options.get(\"executor-memory\", \"5G\")\n\n kerberos()\n\n output_dir = self._get_job_output_dir(job_id)\n input_file = output_dir / \"in\"\n # TODO: how support multiple output files?\n output_file = output_dir / \"out\"\n log_file = output_dir / \"log\"\n\n with input_file.open('w') as f:\n f.write(job_info['specification'])\n\n conf = SparkContext.getOrCreate().getConf()\n principal, key_tab = conf.get(\"spark.yarn.principal\"), conf.get(\"spark.yarn.keytab\")\n\n script_location = pkg_resources.resource_filename('openeogeotrellis.deploy', 'submit_batch_job.sh')\n\n args = [script_location, \"OpenEO batch job {j} user {u}\".format(j=job_id, u=user_id),\n str(input_file),\n str(output_file),\n str(log_file)]\n\n if principal is not None and key_tab is not None:\n args.append(principal)\n args.append(key_tab)\n else:\n args.append(\"no_principal\")\n args.append(\"no_keytab\")\n if api_version:\n args.append(api_version)\n else:\n args.append(\"0.4.0\")\n\n args.append(driver_memory)\n args.append(executor_memory)\n\n try:\n output_string = subprocess.check_output(args, stderr=subprocess.STDOUT, universal_newlines=True)\n except CalledProcessError as e:\n logger.exception(e)\n logger.error(e.stdout)\n logger.error(e.stderr)\n raise e\n\n try:\n # note: a job_id is returned as soon as an application ID is found in stderr, not when the job is finished\n logger.info(output_string)\n application_id = self._extract_application_id(output_string)\n print(\"mapped job_id %s to application ID %s\" % (job_id, application_id))\n\n registry.set_application_id(job_id, user_id, application_id)\n except _BatchJobError as e:\n traceback.print_exc(file=sys.stderr)\n # TODO: why reraise as CalledProcessError?\n raise CalledProcessError(1, str(args), output=output_string)\n\n @staticmethod\n def _extract_application_id(stream) -> str:\n regex = re.compile(r\"^.*Application report for (application_\\d{13}_\\d+)\\s\\(state:.*\", re.MULTILINE)\n match = regex.search(stream)\n if match:\n return match.group(1)\n else:\n raise _BatchJobError(stream)\n\n def get_results(self, job_id: str, user_id: str) -> Dict[str, str]:\n job_info = self.get_job_info(job_id=job_id, user_id=user_id)\n if job_info.status != 'finished':\n raise JobNotFinishedException\n return {\n \"out\": str(self._get_job_output_dir(job_id=job_id))\n }\n\n def get_log_entries(self, job_id: str, user_id: str, offset: str) -> List[dict]:\n # will throw if job doesn't match user\n job_info = self.get_job_info(job_id=job_id, user_id=user_id)\n if job_info.status in ['created', 'queued']:\n raise JobNotStartedException\n\n log_file = self._get_job_output_dir(job_id) / \"log\"\n with log_file.open('r') as f:\n log_file_contents = f.read()\n # TODO: provide log line per line, with correct level?\n return [\n {\n 'id': \"0\",\n 'level': 'error',\n 'message': log_file_contents\n }\n ]\n\n def cancel_job(self, job_id: str, user_id: str):\n with JobRegistry() as registry:\n application_id = registry.get_job(job_id, user_id)['application_id']\n # TODO: better logging of this kill.\n subprocess.run(\n [\"yarn\", \"application\", \"-kill\", application_id],\n timeout=20,\n check=True,\n )\n\n\nclass _BatchJobError(Exception):\n pass\n\n","sub_path":"openeogeotrellis/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":13798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"199158996","text":"import csv\nfrom statistics import mean\nimport openpyxl\nfrom openpyxl.chart import LineChart,Reference\nimport sqlite3\n\nfp = open('CCTV_in_Seoul.csv',encoding='utf-8')\nrd = csv.reader(fp)\n\nitem = []\ndata = []\ncnt = 0\n# for n in rd:\n# data.append(n)\nfor name,numNow,num2013,num2014,num2015,num2016 in rd:\n if cnt == 0:\n cnt += 1\n item.append((name,numNow,num2013,num2014,num2015,num2016))\n else:\n data.append((name,int(numNow),int(num2013),int(num2014),int(num2015),int(num2016)))\nfp.close()\n\nprint(data)\ncnt = 0\n# 1. CCTV 소계 mean\nCCTV_numNow_mean = mean( [n[1] for n in data if type(n[1])==int] )\nprint(\"CCTV 소계 mean: \",CCTV_numNow_mean)\n# 2. CCTV 소계 max의 기관명 및 소계\nCCTV_numNow_max = max(data, key=lambda v:v[1])\nprint(\"CCTV 소계 max의 기관명과 소계: %s, %d\"%(CCTV_numNow_max[0], CCTV_numNow_max[1]))\n# 3. CCTV 소계 가장 많은 top 5의 기관명 및 소계\ndata = sorted(data,key=lambda v:v[1],reverse=True)\nprint(\"CCTV 소계 Top5의 기관명과 소계: \")\nfor n in data:\n print(\" %s %d\"%(n[0], n[1]))\n cnt += 1\n if cnt == 5:\n break\n# 4. 기관별 CCTV 소계에 대한 라인차트를 엑셀에 그리시오\nwb = openpyxl.Workbook()\nws = wb.active\nws.append((\"기관명\",\"소계\",\"2013년도 이전\",\"2014\",\"2015\",\"2016\"))\nfor n in data:\n ws.append(n)\n\nchart = LineChart()\nchartData = Reference(ws, min_col=2,min_row=2,max_row=ws.max_row)\ncategory = Reference(ws, min_col=1,min_row=1,max_row=ws.max_row)\nchart.add_data(chartData,titles_from_data=True)\nchart.set_categories(category)\nchart.title = \"기관 별 CCTV 소계\"\nchart.x_axis.title = \"기관명\"\nchart.y_axis.title = \"CCTV 소계\"\nws.add_chart(chart, 'H1')\nwb.save('CCTV_chart.xlsx')\n\n#5. 2013년도 대비 CCTV 증가율을 기관 별로 출력하시오.\nprint(\"2013년도 대비 CCTV 증가율\")\nprint(\"=\"*20)\nfor n in data:\n print(\"%s %.1f\"%(n[0], n[2]/(n[3]+n[4]+n[5])))\n\n# 6. CCTV DB의 CCTV 테이블에 기관명 소계를 저장하시오.\n# try:\n# sql = \"create table if not exists\" \\\n# \"CCTV(name varchar(20), numNow int)\"\n# db = sqlite3.connect('CCTV.db') # 데이터베이스 만들어주기\n# db.execute(sql)\n# db.close()\n# print(\"create success\")\n# except Exception as err:\n# print(\"에러\",err)\n#\n# try:\n# sql = \"insert into CCTV(name, num) \" \\\n# \"values(?,?)\" # SQL에서는 \"은 안씀 '만 쓰자!\n# db = sqlite3.connect('CCTV.db')\n# db.execute(sql, data)\n# db.commit()\n# db.close()\n# print(\"insert success\")\n# except Exception as err:\n# print(\"에러\",err)\n","sub_path":"Python/pythonTest_class/BackUp/3일차/김나리/Day3_assignment.py","file_name":"Day3_assignment.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"143464874","text":"#!/usr/bin/python3\n#\n# A tiny little script that tests some basic kombu functions\n# A learning exercise only, not a test bed\n# Kombu documentation is, well a tad lacking in places\n#\n# The goal, create a queue, and put a few messages on it.\n#\n# Use another script to try find and examine that queue.\n\nfrom kombu import Connection, Queue, Exchange, Producer, Consumer\n\nURL = \"pyamqp://CoGs:ManyTeeth@localhost/CoGs\"\n\nxname = \"kombu.test.exchange\"\nqname = \"kombu.test.queue\"\nrkey = \"kombu.test.queue.routing.key\"\n\nwith Connection(URL) as conn:\n # Connection is lazy. Force a connection now.\n conn.connect()\n c = conn.connection\n laddr = c.sock.getsockname()\n raddr = c.sock.getpeername()\n c.name = f\"{laddr[0]}:{laddr[1]} -> {raddr[0]}:{raddr[1]}\"\n c.name_short = f\"{laddr[0]}:{laddr[1]}\"\n\n print(f'Connection: {c.name_short}')\n\n # Create a channel on the conection and log it in the RabbitMQ webmonitor format \n ch = c.channel()\n ch.name = f'{c.name} ({ch.channel_id})'\n ch.name_short = f'{c.name_short} ({ch.channel_id})'\n\n print(f'Channel: {ch.name_short}')\n \n x = Exchange(xname, channel=ch)\n x.declare() # Makes the exchange appears on the RabbitMQ web monitor\n\n q = Queue(exchange=x, channel=ch, routing_key=rkey)\n q.declare() # Makes the queue appears on the RabbitMQ web monitor\n\n x=1\n\n \n","sub_path":"kombu_tests/find_queue_and_check.py","file_name":"find_queue_and_check.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"84894403","text":"import pygame, random, math\n\n# Modulo para el trafico\ndef rot_center(image,rect,angle):\n \"\"\"Esta funcion controla la rotacion de la imagen y el bloque que\n representan al vehiculo dummy\"\"\"\n rot_image = pygame.transform.rotate(image, angle)\n rot_rect = rot_image.get_rect(center=rect.center)\n return rot_image, rot_rect\n\nclass Dummy(pygame.sprite.Sprite):\n \"\"\"Esta es la clase para los drones\"\"\"\n def __init__(self, angle, x, y):\n \"\"\"Aqui se definen varios atributos como la velocidad, el angulo, la imagen\n y la magnitud de los giros\"\"\"\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(\"Image/Trafico.png\")\n self.rect = self.image.get_rect()\n self.image_orig = self.image\n self.speed = 2\n self.direction = angle\n self.steering = 90\n self.x = x\n self.y = y\n\n def steerleft(self):\n \"\"\"Giros hacia la izquierda\"\"\"\n self.direction = self.direction+self.steering\n if self.direction > 360:\n self.direction = 0+90\n self.image, self.rect = rot_center(self.image_orig,self.rect,self.direction)\n\n def steerright(self):\n \"\"\"Giros hacia la derecha\"\"\"\n self.direction = self.direction-self.steering\n if self.direction < 0:\n self.direction = 360-90\n self.image, self.rect = rot_center(self.image_orig,self.rect,self.direction)\n\n def update(self,last_x, last_y):\n \"\"\"Movimiento de los drones\"\"\"\n if self.direction == 0 or self.direction == 360:\n self.x = self.x\n self.y = self.y - self.speed\n self.rect.x = self.x\n self.rect.y = self.y\n if self.direction == 90:\n self.x = self.x + self.speed\n self.y = self.y\n self.rect.x = self.x\n self.rect.y = self.y\n if self.direction == 180:\n self.x = self.x\n self.y = self.y + self.speed\n self.rect.x = self.x\n self.rect.y = self.y\n if self.direction == 270:\n self.x = self.x - self.speed\n self.y = self.y\n self.rect.x = self.x\n self.rect.y = self.y\n","sub_path":"Intro y Taller Progra- TEC/Proyectos/achacon-proyecto2/trafico.py","file_name":"trafico.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"257127974","text":"import discord\nfrom discord.ext import commands\nimport random\nimport pandas as pd\nimport asyncio\nimport youtube_dl\nimport os\n\n\nvalue = random.randint(1,10)\n\n\n\n\n# bot for the code\n#client = discord.Client()\n\nclient = commands.Bot(command_prefix = '--')\n\n@client.command(name= 'version')\nasync def version(context):\n \n \n myEmb = discord.Embed(title = \"Current Version\",description = \"Bot is in Version 1.0\", color = 0xff0000)\n myEmb.add_field(name = \"Version Code:\", value = \"v1.0.0\", inline = False)\n myEmb.add_field(name = \"Date Released\", value = \"July 18th, 2020\", inline = False)\n myEmb.set_footer(text = \"This is a sample footer\")\n myEmb.set_author(name = \"Rayo Belihomji\")\n await context.message.channel.send(embed = myEmb)\n\n\n\n@client.event\nasync def on_disconnect():\n general_channel = client.get_channel(796908083393331230)\n\n await general_channel.send('Bye')\n\n\n#Kick a person command\n@client.command(name= 'kick', pass_context = True) \n@commands.has_permissions(kick_members = True)\n\nasync def kick(context, member: discord.Member):\n await member.kick()\n await context.send('User ' + member.display_name + ' has been kicked.')\n\n\n@client.command(name = 'ban', pass_context = True) \n@commands.has_permissions(kick_members = True)\n\nasync def ban(context, member: discord.Member,*, reason = None):\n await member.ban(reason = reason)\n await context.send('User ' + member.display_name + ' has been banned.')\n\n\n\n\n\n@client.event\n#predefined name\nasync def on_ready():\n # Do stuff...\n print(value)\n if value == 3:\n \n await client.change_presence(status = discord.Status.do_not_disturb, activity = discord.Game('Black Opps 2'))\n\n else:\n\n general_channel = client.get_channel(796908083393331230)\n\n await general_channel.send('hello')\n\n \n\n\n@client.event\nasync def on_message(message):\n\n if message.content == 'what is the version':\n general_channel = client.get_channel(796908083393331230)\n \n myEmb = discord.Embed(title = \"Current Version\",description = \"Bot is in Version 1.0\", color = 0xff0000)\n myEmb.add_field(name = \"Version Code:\", value = \"v1.0.0\", inline = False)\n myEmb.add_field(name = \"Date Released\", value = \"July 18th, 2020\", inline = False)\n myEmb.set_footer(text = \"This is a sample footer\")\n myEmb.set_author(name = \"Rayo Belihomji\")\n await general_channel.send(embed = myEmb)\n\n # send DM after work\n if message.content == 'send a DM':\n \n await message.author.send('This is a DM. Have a great day')\n\n\n #await general_channel.send(embed = myEmb)\n if message.content == \"Append\":\n\n #Add row tht contains message\n df = pd.read_csv('/Users/rayobelihomji/Discord Bot/output.csv', index_col = 0)\n df = df.append({\"A\": 'This is the message I want to append'},ignore_index = True)\n df.to_csv('/Users/rayobelihomji/Discord Bot/output.csv')\n\n await client.process_commands(message)\n\n\n\n# Plays songs From the API\n\n@client.command()\n\nasync def play(ctx, url : str):\n ##convert the url\n song = os.path.isfile(\"song.mp3\")\n\n try:\n if song:\n os.remove(\"song.mp3\")\n\n except PermissionError:\n await ctx.send(\"Wait for song to end or use stop command\")\n return\n\n \n voiceChan = discord.utils.get(ctx.guild.voice_channels, name = 'General')\n await voiceChan.connect()\n voice = discord.utils.get(client.voice_clients, guild = ctx.guild)\n\n\n ''' \n if not voice.is_connected():\n await voiceChan.connect()\n '''\n #options of the youtube video\n ydl_op = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec' : 'mp3',\n 'preferredquality' : '192',\n\n }],\n }\n with youtube_dl.YoutubeDL(ydl_op) as ydl:\n ydl.download([url])\n\n for file in os.listdir(\"./\"):\n if file.endswith(\".mp3\"):\n os.rename(file,\"song.mp3\")\n\n voice.play(discord.FFmpegPCMAudio(\"song.mp3\"))\n\n\n\n\n@client.command()\n\nasync def leave(ctx):\n voice = discord.utils.get(client.voice_clients, guild = ctx.guild)\n\n if voice.is_connected():\n await voice.disconnect()\n\n \n \n else:\n await ctx.send(\"Bot is not connected\")\n\n\n@client.command()\n\nasync def pause(ctx):\n voice = discord.utils.get(client.voice_clients, guild = ctx.guild)\n\n if voice.is_playing():\n voice.pause()\n\n else:\n await ctx.send(\"No audio is playing\")\n\n\n@client.command()\n\nasync def resume(ctx):\n voice = discord.utils.get(client.voice_clients, guild = ctx.guild)\n\n if voice.is_paused():\n voice.resume()\n\n else:\n await ctx.send(\"audio is not paused\")\n\n\n@client.command()\n\nasync def stop(ctx):\n\n voice = discord.utils.get(client.voice_clients, guild = ctx.guild)\n\n voice.stop()\n\n\n\n\n# Run on server (Can regenerate token)\n\nclient.run('Token ID')\n\n\n\n\n\n","sub_path":"my_bot.py","file_name":"my_bot.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"61896754","text":"import streamlit as st\nimport requests\nfrom spacy import displacy\nimport itertools\nfrom sciwing.tokenizers.word_tokenizer import WordTokenizer\n\nst.sidebar.title(\"SciWING Demo\")\nst.sidebar.markdown(\"---\")\n\n\nst.title(\"Citation String Parsing - Neural Parscit\")\nst.markdown(\n \"Neural Parscit is a citation parsing module. A citation string contains many information \"\n \"like the author, the title of the publication, the conference/journal the publication is \"\n \"submitted to, the year of publication. The Neural Parscit module is a Bidirectional LSTM model \"\n \"with CRF Sequence tagging module that extracts information from a citation. The trained model \"\n \"on SciWING also includes an Elmo Embedder along with a Glove embeddings and character \"\n \"level embeddings\"\n)\n\ncitation_selected = st.selectbox(\n label=\"Select a citation\",\n options=[\n \"Calzolari, N. (1982) Towards the organization of lexical definitions on a database structure. In E. Hajicova (Ed.), COLING '82 Abstracts, Charles University, Prague, pp.61-64.\",\n \"Caraballo, S.A. (1999) Automatic construction of a hypernym-labeled noun hierarchy. In Proceedings of the 37th Annual Meeting of the Association for Computational Linguistics (ACL'99), College Park, Maryland, pp. 120-126.\",\n ],\n)\n\nst.markdown(\"---\")\ntext_citation = st.text_input(label=\"Enter a citation string\", value=citation_selected)\nparse_citation_clicked = st.button(\"Parse Citation\")\n\nif parse_citation_clicked:\n citation_selected = text_citation\n\n\nresponse = requests.get(f\"http://localhost:8000/parscit/{citation_selected}\")\njson = response.json()\ntext = json[\"text_tokens\"]\ntags = json[\"tags\"].split()\n\n# tokenize the text using white space\ntokenizer = WordTokenizer(tokenizer=\"spacy-whitespace\")\ndoc = tokenizer.nlp(\" \".join(text))\n\n# start index of every token\ntoken_indices = [token.idx for token in doc]\n\n# get start end index of every word\nstart_end_indices = itertools.zip_longest(\n token_indices, token_indices[1:], fillvalue=len(\" \".join(text))\n)\nstart_end_indices = list(start_end_indices)\n\n\nHTML_WRAPPER = \"\"\"
{}
\"\"\"\nents = []\nfor tag, (start_idx, end_idx) in zip(tags, start_end_indices):\n ents.append({\"start\": start_idx, \"end\": end_idx, \"label\": tag})\n\n# colors\nunique_colors = [\n \"#49483E\",\n \"#F92672\",\n \"#A6E22E\",\n \"#FD971F\",\n \"#66D9EF\",\n \"#AE81FF\",\n \"#A1EFE4\",\n \"#F8F8F2\",\n]\ncolors_iter = itertools.cycle(unique_colors)\nunique_tags = list(set(tags))\ncolors = {tag.upper(): next(colors_iter) for tag in unique_tags}\noptions = {\"ents\": [tag.upper() for tag in unique_tags], \"colors\": colors}\nex = [{\"text\": \" \".join(text), \"ents\": ents, \"title\": \"Entities\"}]\n\nhtml = displacy.render(ex, style=\"ent\", manual=True, options=options, page=False)\nhtml = html.replace(\"\\n\", \" \")\nst.write(HTML_WRAPPER.format(html), unsafe_allow_html=True)\n","sub_path":"sciwing/app/ner_demo.py","file_name":"ner_demo.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"503738074","text":"\"\"\"empty message\n\nRevision ID: 658de397b180\nRevises: cfba03d1e0e6\nCreate Date: 2019-06-11 11:08:25.168161\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '658de397b180'\ndown_revision = 'cfba03d1e0e6'\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport polylogyx.database\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('default_filters',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('filters', postgresql.JSONB(), nullable=True),\n sa.Column('platform', sa.String(), nullable=False),\n sa.Column('apply_by_default', sa.Boolean(), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('updated_at', sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('default_query',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('sql', sa.String(), nullable=False),\n sa.Column('interval', sa.Integer(), nullable=True),\n sa.Column('platform', sa.String(), nullable=True),\n sa.Column('version', sa.String(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.Column('value', sa.String(), nullable=True),\n sa.Column('removed', sa.Boolean(), nullable=False),\n sa.Column('shard', sa.Integer(), nullable=True),\n sa.Column('status', sa.Boolean(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('default_query')\n op.drop_table('default_filters')\n # ### end Alembic commands ###\n","sub_path":"plgx-esp-ui/migrations/versions/dafault_filter_query.py","file_name":"dafault_filter_query.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"10048829","text":"# 2443.py\n# 2018.05.25\n\nimport sys\n\nn = int(sys.stdin.readline())\nfor i in range(n):\n\tprint(' '*i + '*'*(2*n-1 - 2*i))\n\n# f 문자열 포매팅을 사용하면 너무 지저분 해진다.\n# 공백은 0부터 시작해서 n-1까지 가면된다.\n# 별은 2*n - 1개로 시작해서 line마다 두개씩 줄어들면 된다.","sub_path":"2000/2443.py","file_name":"2443.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"134356081","text":"# Implements a 3PL IRT model\n# TODO: Set a type variable for the IRT for 1PL, 2PL, and 3PL models\n# 1PL can have an additional routine for sampling beta more efficiently\n# Fit method will call whatever appropriate fit construct given the type\n\nimport numpy as np\nfrom scipy.stats import norm\nfrom time import time\n\n# Brief model description:\n# User observes a term t and has to decide if it is a key term or not\n# User has a bias and variance that affects this observation\n\n# Model equations:\n# mu_i ~ N(mu_mu, tau_mu), tau_i ~ Gamma(alpha_tau, beta_tau) [user]\n# t_j ~ N(mu_t, tau_t) [term]\n# T_ij ~ N(t_j + mu_i, tau_i) [observation by user i of term j]\n# Y_ij = (T_ij > 0) [observation in data, equiv to probit model on T_ij]\n\ndefault_params = {'mu_mu': 0, 'tau_mu': .2,\n 'mu_t': 0, 'tau_t': .2,\n 'alpha_tau': 1, 'beta_tau': 1,\n 'T': 10000, 'burnin': 1000, 'thinning': 1}\n\nclass TermDenoiser(object):\n def __init__(self, **kwargs):\n self.__dict__ = default_params\n allowed_keys = default_params.keys()\n self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys)\n\n def truncnorm(self, a_t, b_t, mu_t, sigma_t):\n # Create the mask matrix for dealing with missing data (nans)\n C = np.isnan(a_t) + np.isnan(b_t) + np.isnan(mu_t) + np.isnan(sigma_t)\n idx = np.where(~C)\n a = a_t[idx]\n b = b_t[idx]\n mu = mu_t[idx]\n sigma = sigma_t[idx]\n O = np.nan * np.zeros(C.shape)\n\n N = np.prod(np.array(mu).shape)\n alpha = (a - mu) / sigma\n beta = (b - mu) / sigma\n Phi_alpha = norm.cdf(alpha)\n Phi_beta = norm.cdf(beta)\n U = np.random.rand(N)\n out = norm.ppf(Phi_alpha + U * (Phi_beta - Phi_alpha)) * sigma + mu\n out[np.isinf(out)] = 0 # Instability correction for corner cases (converges in limit)\n\n # If any elements in out are nan . . . if so set to mu\n nan_idx = np.where(np.isnan(out))\n out[nan_idx] = mu[nan_idx]\n O[idx] = out\n\n # Return the final result\n return O\n\n def setup_mcmc_samples(self):\n # Set up the dataframes for saving off samples\n N = self.N\n Q = self.Q\n\n samples_to_save = int((self.T - self.burnin) / self.thinning)\n self.LL = np.zeros(self.T)\n self.T_mcmc = np.zeros((N, Q, samples_to_save))\n self.mu_mcmc = np.zeros((N, samples_to_save))\n self.t_mcmc = np.zeros((Q, samples_to_save))\n self.tau_mcmc = np.zeros((N, samples_to_save))\n\n def save_samples(self, T, mu, tau, t, iteration):\n idx = int((iteration - self.burnin) / self.thinning)\n # self.T_mcmc[:, :, idx:idx + 1] = T\n self.mu_mcmc[:, idx:idx + 1] = mu\n self.t_mcmc[:, idx:idx + 1] = t\n self.tau_mcmc[:, idx:idx + 1] = tau\n\n def sample_T(self, mu, t, tau, Y):\n # Configure the limits based on the values in Y\n A = np.zeros(Y.shape)\n B = np.zeros(Y.shape)\n Q = Y.shape[0]\n N = Y.shape[1]\n eta = np.tile(mu.T, (Q, 1)) + np.tile(t, (1, N))\n Sigma = 1/np.sqrt(np.tile(tau.T, (Q, 1)))\n A[Y == 0] = -np.inf\n B[Y == 1] = np.inf\n A[np.isnan(Y)] = np.nan\n B[np.isnan(Y)] = np.nan\n T = self.truncnorm(A, B, eta, Sigma)\n T[np.isnan(Y)] = np.nan\n return T\n\n def sample_mu(self, T, t, tau):\n tau_matrix = np.tile(tau.T, (self.Q, 1))\n tau_matrix[np.isnan(T)] = np.nan\n T_prime = T - np.tile(t, (1, self.N))\n T_prime = T_prime * tau_matrix\n S_tau = np.nansum(tau_matrix, axis=0, keepdims=True)\n mean = (np.nansum(T_prime, axis=0, keepdims=True) / (S_tau + self.tau_mu))\n var = 1.0 / (self.tau_mu + S_tau)\n mu_out = np.sqrt(var) * np.random.randn(1, self.N) + mean\n return mu_out.T\n\n def sample_t(self, T, mu, tau):\n tau_matrix = np.tile(tau.T, (self.Q, 1))\n tau_matrix[np.isnan(T)] = np.nan\n T_prime = T - np.tile(mu.T, (self.Q, 1))\n T_prime = T_prime * tau_matrix\n S_alpha = np.nansum(tau_matrix, axis=1, keepdims=True)\n mean = (np.nansum(T_prime, axis=1, keepdims=True) / (S_alpha + self.tau_t))\n var = 1.0 / (self.tau_t + S_alpha)\n t_out = np.sqrt(var) * np.random.randn(self.Q, 1) + mean\n return t_out\n\n def sample_tau(self, T, mu, t):\n Zhat = T - np.tile(mu.T, (self.Q, 1)) - np.tile(t, (1, self.N))\n D2 = Zhat ** 2 / 2\n N_obs = np.sum(~np.isnan(Zhat), axis=0)\n alpha_hat = self.alpha_tau + N_obs / 2\n beta_hat = self.beta_tau + np.nansum(D2, axis=0)\n out = np.random.gamma(alpha_hat, 1/beta_hat, self.N)\n out.shape = (self.N, 1)\n return out\n\n\n def fit(self, data, mu_init=None, t_init=None, tau_init=None):\n self.data = data # A numpy array of size Q (terms) x N (users)\n self.Q, self.N = data.shape\n \n # Initialize model parameters parameters according to priors\n if (mu_init is None):\n mu = np.sqrt(1/self.tau_mu) * np.random.randn(self.N, 1) + self.mu_mu\n else:\n mu = mu_init\n if (t_init is None):\n t = np.sqrt(1/self.tau_t) * np.random.randn(self.Q, 1) + self.mu_t\n else:\n t = t_init\n if (tau_init is None):\n tau = np.random.gamma(self.alpha_tau, 1 / self.beta_tau, size=(self.N, 1))\n else:\n tau = tau_init\n\n\n # Initialize the state variables\n self.setup_mcmc_samples()\n\n # Run the chain\n for tt in range(0, self.T):\n if ((tt + 1) % 1000 == 0):\n print(\"\\tIter: \" + str(tt + 1))\n\n # Compute log liklihood\n # self.LL[t] = self.compute_LL(data, theta, alpha, beta, gamma)\n\n # Sample T\n T = self.sample_T(mu, t, tau, data)\n if np.isinf(T).any():\n print(\"SCREAM T\")\n\n # Sample mu\n mu = self.sample_mu(T, t, tau)\n if np.isinf(T).any():\n print(\"SCREAM MU\")\n\n\n # Sample t\n t = self.sample_t(T, mu, tau)\n if np.isinf(T).any():\n print(\"SCREAM t\")\n\n\n # Sample tau\n tau = self.sample_tau(T, mu, t)\n if np.isinf(T).any():\n print(\"SCREAM tau\")\n\n\n # Save off values if t>burnin\n if (tt >= self.burnin) & (((tt - self.burnin) % self.thinning) == 0):\n self.save_samples(T, mu, tau, t, tt)\n\n def generate_synthetic_data(self, Q, N):\n # N participants responding to Q tasks, outcome is one of K discrete labels\n # Final matrices are N x Q\n\n # Generate the participant parameters\n mu = np.sqrt(1/self.tau_mu) * np.random.randn(N, 1) + self.mu_mu\n tau = np.random.gamma(self.alpha_tau, 1/self.beta_tau, size=(N, 1))\n\n # Generate the task parameters\n # Prior on C is dirichlet but we can just generate the label from a DU\n t = np.sqrt(1/self.tau_t) * np.random.randn(Q, 1) + self.mu_t\n\n # Generate T matrix of observed latent quantities\n T = np.tile(mu.T, (Q, 1)) + np.tile(t, (1, N))\n T = T + 1 / np.sqrt(np.tile(tau.T, (Q, 1))) * np.random.randn(Q, N)\n\n # Generate the actual observations\n Y = T > 0\n Y = Y.astype(float)\n\n return Y, T, mu, tau, t\n\n","sub_path":"scripts/term_denoiser/term_denoiser.py","file_name":"term_denoiser.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"290092510","text":"#!/bin/python\nimport time\nimport sys\nimport json\nimport keyring\nimport HttpGetter \n\nhg = HttpGetter.HttpGetter()\nsoup = hg.get(\"https://leetcode.com/\")\n\ntoken = soup.input.attrs['value']\nhg.data = {\n 'csrfmiddlewaretoken': token,\n 'login': 'eskibear',\n 'password': keyring.get_password('leetcode', 'eskibear')\n}\nsoup = hg.post(\"https://leetcode.com/accounts/login/\")\n\nhg.data={}\nsoup = hg.get(\"https://leetcode.com/profile/\")\n\n\n#choose question\nquestion_src = sys.argv[1] \nquestion = question_src.split(\"/\")[-1].split(\".\")[0]\nquestion_url = \"https://leetcode.com/problems/\"+question+\"/\"\nhg.data = {}\nsoup = hg.get(question_url)\n\n#submit\nfields = [ \"csrfmiddlewaretoken\", \"question_id\", \"judge_type\", \"data_input\"]\ndata = {} \nfor f in fields:\n data[f] = soup.find(\"input\",attrs={'name': f}).attrs['value']\ndata['lang'] = \"cpp\"\n# read code\n# CAUTION: nasty way to find first `class Solution{ };' block\ndata['typed_code'] = \"\"\nwith open(question_src) as lines:\n for line in lines:\n if line.strip() == \"class Solution {\":\n data['typed_code']+=line\n break;\n for line in lines:\n data['typed_code']+=line\n if line.rstrip() == \"};\":\n break;\nhg.data = data\nhg.headers.update({\n 'X-CSRFToken': data['csrfmiddlewaretoken'],\n 'X-Requested-With': 'XMLHttpRequest'\n })\n\nsoup = hg.post(question_url+\"submit/\")\nsubmission_id = json.loads(hg.lastresp.text)['submission_id']\n# check\nhg.data = {}\ncheck_url = \"https://leetcode.com/submissions/detail/\"+str(submission_id)+\"/check/\"\nwhile True:\n soup = hg.get(check_url) \n feedbacks = json.loads(hg.lastresp.text)\n if feedbacks['state'] == 'SUCCESS':\n break;\n time.sleep(2)\nif feedbacks[\"run_success\"] and feedbacks['total_correct']==feedbacks['total_testcases']:\n print( \"\\033[01;36m{}\\033[00m\".format(\"===AC===\"))\nelse:\n print(\"\\033[01;31m{}\\033[00m\".format(\"===FAIL===\"))\nfor k, v in feedbacks.items():\n print('\\033[01;33m{:<20s}\\033[00m: \\033[01;33m{}\\033[00m'.format(k, v))\n\n\n\n","sub_path":"tool/submit_cc.py","file_name":"submit_cc.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"331987735","text":"import pygame\nfrom script.hero import *\nfrom pygame.locals import *\n\n\nclass Enemy(Hero):\n def __init__(self, name, hp, attract, defense, local, path):\n super().__init__(name, hp, attract, defense, local)\n self.image = pygame.transform.scale2x(pygame.image.load(\"resource\\{}.png\".format(path)))\n\n def hp_line(self):\n super().hp_line()\n self.player_information()\n hp_percentage = self.hp / self.hp_max\n self.hp_band = pygame.Surface([500, 10])\n if self.hp >= 0:\n hp_band = pygame.Surface([500 * hp_percentage, 10])\n hp_band.fill([220, 100, 100])\n self.hp_band.blit(hp_band, (0, 0))\n self.hp_rect = Rect((570, 10), (500, 10))\n\n def attract(self, attract):\n self.hp = self.hp - (attract - self.defense)\n pygame.mixer.music.load(r\"resource\\cat_bit.wav\")\n pygame.mixer.music.play()\n self.update()\n\n def player_information(self):\n txt = pygame.font.Font(r\"resource\\XBS.ttf\", 22)\n text = txt.render(\n \"{} 攻击力:{} 防御力:{} 血量 {}|{}\".format(self.name, self.attraction, self.defense, self.hp, self.hp_max),\n True, [200, 200, 200], [100, 100, 100])\n self.txt_band = pygame.Surface([600, 50])\n self.txt_band.fill([100, 100, 100])\n self.txt_band.blit(text, [100, 22])\n self.txt_rect = Rect((480, 0), (600, 50))\n\n def move(self, x, y):\n self.head_direction(x, y)\n if self.rect.centerx == x and self.rect.centery == y:\n pass\n else:\n if self.rect.centerx == x:\n dx = 0\n else:\n dx = (self.rect.centerx - x) / abs(self.rect.centerx - x)\n if self.rect.centery == y:\n dy = 0\n else:\n dy = (self.rect.centery - y) / abs(self.rect.centery - y)\n self.rect.centerx += -dx\n self.rect.centery += -dy\n\n def update(self):\n self.hp_line()\n if self.hp <= 0:\n self.kill()\n hp_percent = self.hp/self.hp_max\n self.attraction = int(-3*self.attract_init*(hp_percent**2) + 4*self.attract_init)\n\n\nclass Enemy_group(Hero_group):\n def update(self, *args):\n super().update()\n\n","sub_path":"script/enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"261509242","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom Tencent.items import TencentItem, TencentDetailItem\nimport scrapyd\n\n\nclass TencentSpider(CrawlSpider):\n name = 'tencent3'\n allowed_domians = ['tencent.com']\n start_urls = ['https://hr.tencent.com/position.php?keywords=python&tid=0&lid=2156&start=0']\n count = 0\n # rules 提取规则\n rules = (\n # 先提取列表页\n Rule(LinkExtractor(allow='start=\\d+'), callback='parse_list', follow=True),\n\n # 提取详情页\n Rule(LinkExtractor(allow='position_detail.php'), callback='parse_detail', follow=False),\n\n )\n\n # 解析列表页的数据\n def parse_list(self, response):\n\n # 解析 tr 列表\n tr_list = response.xpath('//tr[@class=\"even\"] | //tr[@class=\"odd\"]')\n\n for tr in tr_list:\n item = TencentItem()\n item['work_name'] = tr.xpath('./td[1]/a/text()').extract_first()\n item['work_type'] = tr.xpath('./td[2]/text()').extract_first()\n item['work_count'] = tr.xpath('./td[3]/text()').extract_first()\n item['work_place'] = tr.xpath('./td[4]/text()').extract_first()\n item['work_time'] = tr.xpath('./td[5]/text()').extract_first()\n\n # 将 解析完毕的数据 --引擎--管道\n yield item\n\n # 解析详情页的数据\n def parse_detail(self, response):\n # ul 2个\n ul_list = response.xpath('//ul[@class=\"squareli\"]')\n\n item = TencentDetailItem()\n item['work_duty'] = \"\".join(ul_list[0].xpath('./li/text()').extract())\n item['work_requir'] = \"\".join(ul_list[1].xpath('./li/text()').extract())\n\n # 将 解析完毕的数据 --引擎--管道\n yield item\n","sub_path":"scrapy_pro/learn05/Tencent(样例)/Tencent/spiders/tencent3.py","file_name":"tencent3.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"77340223","text":"from django.conf.urls import url, include\n\nfrom corehq.apps.api.urls import CommCareHqApi\nfrom corehq.apps.zapier.api.v0_5 import (\n ZapierXFormInstanceResource,\n ZapierCustomFieldCaseResource,\n ZapierCustomTriggerFieldFormResource\n)\nfrom corehq.apps.zapier.views import SubscribeView, UnsubscribeView\n\nhq_api = CommCareHqApi(api_name='v0.5')\nhq_api.register(ZapierXFormInstanceResource())\nhq_api.register(ZapierCustomTriggerFieldFormResource())\nhq_api.register(ZapierCustomFieldCaseResource())\n\nurlpatterns = [\n url(r'^subscribe/$', SubscribeView.as_view(), name=SubscribeView.urlname),\n url(r'^unsubscribe/$', UnsubscribeView.as_view(), name=UnsubscribeView.urlname),\n url(r'^api/', include(hq_api.urls)),\n]\n","sub_path":"corehq/apps/zapier/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"60726328","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import GridSearchCV \nimport sklearn.metrics as metrics\n\ndef main():\n \n tests = ['LABEL_BaseExcess', 'LABEL_Fibrinogen', 'LABEL_AST', 'LABEL_Alkalinephos', 'LABEL_Bilirubin_total',\n 'LABEL_Lactate', 'LABEL_TroponinI', 'LABEL_SaO2',\n 'LABEL_Bilirubin_direct', 'LABEL_EtCO2', 'LABEL_Sepsis']\n\n features_train = pd.read_csv('data/train_engineered_4.csv')\n labels_train = pd.read_csv('data/train_labels.csv')\n features_predict = pd.read_csv('data/test_engineered_4.csv')\n\n # uncomment to compute sempsis only\n #tests = ['LABEL_Sepsis']\n\n # set reduced_size to reduce batch size\n reduced_size = len(features_predict)\n #reduced_size = 800\n\n prediction = pd.DataFrame(features_predict['pid']).iloc[0:reduced_size,:]\n metrics_summary = pd.DataFrame(columns=tests)\n hyperparams = pd.DataFrame(columns=tests)\n\n for label in tests:\n X_train = np.array(features_train)[0:reduced_size]\n y_train = np.array(labels_train[label])[0:reduced_size]\n X_predict = np.array(features_predict)[0:reduced_size]\n\n # # split into test and validation for hyperparameter tuning\n # X_train, X_test, y_train, y_test = train_test_split( \n # X_train, y_train, \n # test_size = 0.20, random_state = 101)\n # print('X_train: ', np.shape(X_train))\n # print('X_test: ', np.shape(X_test))\n # print('y_train: ', np.shape(y_train))\n # print('y_test: ', np.shape(y_test))\n\n # scaling data\n scaler = MinMaxScaler()\n X_train = scaler.fit_transform(X_train)\n # X_test = scaler.transform(X_test)\n X_predict = scaler.fit_transform(X_predict)\n\n model = SVC(gamma='auto', kernel='rbf', C=1, probability=True, class_weight='balanced')\n\n print()\n print('learning : ', label)\n model.fit(X_train, y_train)\n\n # print('predicting : ', label)\n # predicted_label = model.predict_proba(X_test)\n # metrics_default = metrics.roc_auc_score(np.array(y_test), np.array(predicted_label[:,1]))\n # print('metrics ROC : ', label)\n # print(metrics_default)\n\n ##################\n # defining parameter range \n # param_grid = {'C': [0.1, 1, 10, 100, 1000],\n # 'kernel': ['rbf'],\n # 'probability': [True],\n # 'class_weight': ['balanced']} \n \n # grid = GridSearchCV(SVC(), param_grid, refit = True, verbose = 3, scoring='roc_auc') \n \n # # fitting the model for grid search \n # grid.fit(X_train, y_train)\n\n # print()\n # print('best parameter after tuning : ')\n # print(grid.best_params_) \n # print()\n # print('model after hyper-parameter tuning ')\n # print(grid.best_estimator_)\n # hyperparams[label] = [grid.best_estimator_.C, grid.best_estimator_.gamma]\n \n # # predicting on the test set to get a notion of the metrics\n # grid_predictions = grid.predict_proba(X_test) \n # # print classification report \n # metrics_grid = metrics.roc_auc_score(np.array(y_test), np.array(grid_predictions[:,1]))\n # print()\n # print('metrics ROC : ', label)\n # print(metrics_grid)\n # metrics_summary[label] = [metrics_grid]\n ###################\n\n #predict on the provided test set\n y_predicted = model.predict_proba(X_predict)\n # y_predicted = grid.predict_proba(X_predict)\n prediction[label] = y_predicted[:,1]\n\n print()\n print('hyperparams:')\n print(hyperparams)\n\n print()\n print('metrics of all labels:')\n print(metrics_summary)\n print(metrics_summary.mean(axis=1))\n\n print(prediction)\n # prediction.to_csv('prediction_tests.csv', index=False, float_format='%.3f')\n\n return prediction\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Roland/task2/scripts/t2_prediction_tests.py","file_name":"t2_prediction_tests.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"480825138","text":"# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-; coding: utf-8 -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"test command datalad run-procedure\n\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nimport os.path as op\nimport sys\n\nfrom datalad.cmd import Runner\nfrom datalad.utils import (\n chpwd,\n quote_cmdlinearg,\n swallow_outputs,\n)\nfrom datalad.tests.utils import (\n eq_,\n ok_file_has_content,\n with_tree,\n with_tempfile,\n assert_raises,\n assert_repo_status,\n assert_true,\n assert_false,\n assert_in_results,\n assert_not_in_results,\n skip_if,\n OBSCURE_FILENAME,\n on_windows,\n known_failure_windows,\n skip_if_on_windows,\n)\nfrom datalad.distribution.dataset import Dataset\nfrom datalad.support.exceptions import (\n CommandError,\n InsufficientArgumentsError,\n)\nfrom datalad.api import run_procedure\nfrom datalad import cfg\n\n\n@with_tempfile(mkdir=True)\ndef test_invalid_call(path):\n with chpwd(path):\n # ^ Change directory so that we don't fail with an\n # InvalidGitRepositoryError if the test is executed from a git\n # worktree.\n\n # needs spec or discover\n assert_raises(InsufficientArgumentsError, run_procedure)\n res = run_procedure('unknown', on_failure='ignore')\n assert_true(len(res) == 1)\n assert_in_results(res, status=\"impossible\")\n\n\n@known_failure_windows #FIXME\n@with_tree(tree={'README.md': 'dirty'})\ndef test_dirty(path):\n ds = Dataset(path).create(force=True)\n # must fail, because README.md is to be modified, but already dirty\n assert_raises(CommandError, ds.run_procedure, 'cfg_yoda')\n # make sure that was the issue\n # save to git explicitly to keep the test simple and avoid unlocking...\n ds.save('README.md', to_git=True)\n ds.run_procedure('cfg_yoda')\n assert_repo_status(ds.path)\n\n\n@skip_if(cond=on_windows and cfg.obtain(\"datalad.repo.version\") < 6)\n@with_tree(tree={\n 'code': {'datalad_test_proc.py': \"\"\"\\\nimport sys\nimport os.path as op\nfrom datalad.api import save, Dataset\n\nwith open(op.join(sys.argv[1], 'fromproc.txt'), 'w') as f:\n f.write('hello\\\\n')\nsave(dataset=Dataset(sys.argv[1]), path='fromproc.txt')\n\"\"\"}})\n@with_tempfile\ndef test_procedure_discovery(path, super_path):\n with chpwd(path):\n # ^ Change directory so that we don't fail with an\n # InvalidGitRepositoryError if the test is executed from a git\n # worktree.\n ps = run_procedure(discover=True)\n # there are a few procedures coming with datalad, needs to find them\n assert_true(len(ps) > 2)\n # we get three essential properties\n eq_(\n sum(['procedure_type' in p and\n 'procedure_callfmt' in p and\n 'path' in p\n for p in ps]),\n len(ps))\n\n # set up dataset with registered procedure (c&p from test_basics):\n ds = Dataset(path).create(force=True)\n ds.run_procedure('cfg_yoda')\n # configure dataset to look for procedures in its code folder\n ds.config.add(\n 'datalad.locations.dataset-procedures',\n 'code',\n where='dataset')\n ds.save(op.join('.datalad', 'config'))\n\n # run discovery on the dataset:\n ps = ds.run_procedure(discover=True)\n\n # still needs to find procedures coming with datalad\n assert_true(len(ps) > 2)\n # we get three essential properties\n eq_(\n sum(['procedure_type' in p and\n 'procedure_callfmt' in p and\n 'path' in p\n for p in ps]),\n len(ps))\n # dataset's procedure needs to be in the results\n assert_in_results(ps, path=op.join(ds.path, 'code', 'datalad_test_proc.py'))\n # a subdir shouldn't be considered a procedure just because it's \"executable\"\n assert_not_in_results(ps, path=op.join(ds.path, 'code', 'testdir'))\n\n # make it a subdataset and try again:\n # first we need to save the beast to make install work\n ds.save()\n super = Dataset(super_path).create()\n super.install('sub', source=ds.path)\n\n ps = super.run_procedure(discover=True)\n # still needs to find procedures coming with datalad\n assert_true(len(ps) > 2)\n # we get three essential properties\n eq_(\n sum(['procedure_type' in p and\n 'procedure_callfmt' in p and\n 'path' in p\n for p in ps]),\n len(ps))\n # dataset's procedure needs to be in the results\n assert_in_results(ps, path=op.join(super.path, 'sub', 'code',\n 'datalad_test_proc.py'))\n\n if not on_windows: # no symlinks\n import os\n # create a procedure which is a broken symlink, but recognizable as a\n # python script:\n os.symlink(op.join(super.path, 'sub', 'not_existent'),\n op.join(super.path, 'sub', 'code', 'broken_link_proc.py'))\n # broken symlink at procedure location, but we can't tell, whether it is\n # an actual procedure without any guess on how to execute it:\n os.symlink(op.join(super.path, 'sub', 'not_existent'),\n op.join(super.path, 'sub', 'code', 'unknwon_broken_link'))\n\n ps = super.run_procedure(discover=True)\n # still needs to find procedures coming with datalad and the dataset\n # procedure registered before\n assert_true(len(ps) > 3)\n assert_in_results(ps, path=op.join(super.path, 'sub', 'code',\n 'broken_link_proc.py'),\n state='absent')\n assert_in_results(\n ps,\n path=op.join(super.path, 'sub', 'code',\n 'unknwon_broken_link'),\n state='absent')\n\n\n@skip_if(cond=on_windows and cfg.obtain(\"datalad.repo.version\") < 6)\n@with_tree(tree={\n 'code': {'datalad_test_proc.py': \"\"\"\\\nimport sys\nimport os.path as op\nfrom datalad.api import save, Dataset\n\nwith open(op.join(sys.argv[1], 'fromproc.txt'), 'w') as f:\n f.write('{}\\\\n'.format(sys.argv[2]))\nsave(dataset=Dataset(sys.argv[1]), path='fromproc.txt')\n\"\"\"}})\ndef test_configs(path):\n\n # set up dataset with registered procedure (c&p from test_basics):\n ds = Dataset(path).create(force=True)\n ds.run_procedure('cfg_yoda')\n # configure dataset to look for procedures in its code folder\n ds.config.add(\n 'datalad.locations.dataset-procedures',\n 'code',\n where='dataset')\n\n # 1. run procedure based on execution guessing by run_procedure:\n ds.run_procedure(spec=['datalad_test_proc', 'some_arg'])\n # look for traces\n ok_file_has_content(op.join(ds.path, 'fromproc.txt'), 'some_arg\\n')\n\n # 2. now configure specific call format including usage of substitution config\n # for run:\n ds.config.add(\n 'datalad.procedures.datalad_test_proc.call-format',\n u'%s {script} {ds} {{mysub}} {args}' % quote_cmdlinearg(sys.executable),\n where='dataset'\n )\n ds.config.add(\n 'datalad.run.substitutions.mysub',\n 'dataset-call-config',\n where='dataset'\n )\n # TODO: Should we allow for --inputs/--outputs arguments for run_procedure\n # (to be passed into run)?\n ds.unlock(\"fromproc.txt\")\n # run again:\n ds.run_procedure(spec=['datalad_test_proc', 'some_arg'])\n # look for traces\n ok_file_has_content(op.join(ds.path, 'fromproc.txt'), 'dataset-call-config\\n')\n\n # 3. have a conflicting config at user-level, which should override the\n # config on dataset level:\n ds.config.add(\n 'datalad.procedures.datalad_test_proc.call-format',\n u'%s {script} {ds} local {args}' % quote_cmdlinearg(sys.executable),\n where='local'\n )\n ds.unlock(\"fromproc.txt\")\n # run again:\n ds.run_procedure(spec=['datalad_test_proc', 'some_arg'])\n # look for traces\n ok_file_has_content(op.join(ds.path, 'fromproc.txt'), 'local\\n')\n\n # 4. get configured help message:\n r = ds.run_procedure('datalad_test_proc', help_proc=True,\n on_failure='ignore')\n assert_true(len(r) == 1)\n assert_in_results(r, status=\"impossible\")\n\n ds.config.add(\n 'datalad.procedures.datalad_test_proc.help',\n \"This is a help message\",\n where='dataset'\n )\n\n r = ds.run_procedure('datalad_test_proc', help_proc=True)\n assert_true(len(r) == 1)\n assert_in_results(r, message=\"This is a help message\", status='ok')\n\n\n@known_failure_windows\n@with_tree(tree={\n 'code': {'datalad_test_proc.py': \"\"\"\\\nimport sys\nimport os.path as op\nfrom datalad.api import save, Dataset\n\nwith open(op.join(sys.argv[1], sys.argv[2]), 'w') as f:\n f.write('hello\\\\n')\nsave(dataset=Dataset(sys.argv[1]), path=sys.argv[2])\n\"\"\"}})\ndef test_spaces(path):\n \"\"\"\n Test whether args with spaces are correctly parsed.\n \"\"\"\n ds = Dataset(path).create(force=True)\n ds.run_procedure('cfg_yoda')\n # configure dataset to look for procedures in its code folder\n ds.config.add(\n 'datalad.locations.dataset-procedures',\n 'code',\n where='dataset')\n # 1. run procedure based on execution guessing by run_procedure:\n ds.run_procedure(spec=['datalad_test_proc', 'with spaces', 'unrelated'])\n # check whether file has name with spaces\n ok_file_has_content(op.join(ds.path, 'with spaces'), 'hello\\n')\n\n\n@known_failure_windows\n@with_tree(tree={OBSCURE_FILENAME:\n {\"code\": {\"just2args.py\": \"\"\"\nimport sys\nprint(sys.argv)\n# script, dataset, and two others\nassert len(sys.argv) == 4\n\"\"\"}}})\ndef test_quoting(path):\n ds = Dataset(op.join(path, OBSCURE_FILENAME)).create(force=True)\n # Our custom procedure fails if it receives anything other than two\n # procedure arguments (so the script itself receives 3). Check a few cases\n # from the Python API and CLI.\n ds.config.add(\"datalad.locations.dataset-procedures\", \"code\",\n where=\"dataset\")\n with swallow_outputs():\n ds.run_procedure(spec=[\"just2args\", \"with ' sing\", 'with \" doub'])\n with assert_raises(CommandError):\n ds.run_procedure(spec=[\"just2args\", \"still-one arg\"])\n\n runner = Runner(cwd=ds.path)\n runner.run(\n \"datalad run-procedure just2args \\\"with ' sing\\\" 'with \\\" doub'\")\n with assert_raises(CommandError):\n runner.run(\"datalad run-procedure just2args 'still-one arg'\")\n\n\n@skip_if_on_windows\n@with_tree(tree={\n # \"TEXT\" ones\n 'empty': '', # we have special rule to treat empty ones as text\n # check various structured files - libmagic might change its decisions which\n # can effect git-annex. https://github.com/datalad/datalad/issues/3361\n 'JSON': \"\"\"\\\n{\n \"name\": \"John Smith\",\n \"age\": 33\n}\n\"\"\",\n 'YAML': \"\"\"\\\n--- # The Smiths\n- {name: John Smith, age: 33}\n- name: Mary Smith\n age: 27\n\"\"\",\n 'MARKDOWN': \"\"\"\\\n# Title\n\n## Section1\n\nWhen the earth was flat\n\n## Section2\n\"\"\",\n # BINARY ones\n '0blob': '\\x00',\n 'emptyline': '\\n', # libmagic: \"binary\" \"application/octet-stream\"\n})\ndef test_text2git(path):\n # Test if files being correctly annexed in a ds configured with text2git.\n TEXT_FILES = ('JSON', 'YAML', 'MARKDOWN', 'empty')\n BINARY_FILES = ('0blob', 'emptyline')\n\n ds = Dataset(path).create(force=True)\n ds.run_procedure('cfg_text2git')\n ds.save(path=TEXT_FILES + BINARY_FILES, message=\"added all files\")\n assert_repo_status(ds.path)\n\n # check that text files are not annexed\n for f in TEXT_FILES:\n assert_false(ds.repo.is_under_annex(f))\n # and trivial binaries - annexed\n for f in BINARY_FILES:\n assert_true(ds.repo.is_under_annex(f))\n","sub_path":"datalad/interface/tests/test_run_procedure.py","file_name":"test_run_procedure.py","file_ext":"py","file_size_in_byte":11861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"207366123","text":"#coding=utf-8\r\nimport requests\r\nfrom lxml import etree\r\n\r\n\r\ndef get_cities():\r\n headers={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\r\n 'Accept-Encoding':'gzip, deflate',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',\r\n 'Cache-Control': 'max-age=0',\r\n 'Connection': 'keep-alive',\r\n 'Cookie': 'KKOM_b949_saltkey=E9cDg2XR; KKOM_b949_lastvisit=1532757396; KKOM_b949_CITYPINYIN=shenzhen; KKOM_b949_440300_airpressure=1007; KKOM_b949_lastact=1532761057%09portal.php%09diaochang; Hm_lvt_33b44eaa652bf7aa2fca0c2031abe3ba=1532761075; Hm_lpvt_33b44eaa652bf7aa2fca0c2031abe3ba=1532761075',\r\n 'Host': 'www.haodiaoyu.com',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}\r\n\r\n response=requests.get(url='http://www.haodiaoyu.com/diaochang/',headers=headers)\r\n content=response.text\r\n\r\n tree=etree.HTML(content)\r\n nodes=tree.xpath('//div[@class=\"city-names\"]/a/@href')\r\n city_names=[]\r\n for i in nodes:\r\n \tcity_name=i.replace('./diaochang/','')\r\n \tcity_name=city_name.replace('/','')\r\n \tcity_names.append(city_name)\r\n return city_names\r\n\r\nif __name__ == '__main__':\r\n\r\n city_names=get_cities()\r\n print(city_names)\r\n\r\n\r\n\r\n\r\n","sub_path":"我能站在河边钓上一整天的鱼/diaochang/diaochang/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"166193327","text":"import socket, time, struct\nfrom wiiu_rop_utils import *\n\nrop = WiiU_ROP_Utils(1)\n\ndef calc_addr(idx):\n\treturn (0x4D120000 + (idx *4))\n\ndef _byteswap_long(i):\n return struct.unpack(\"I\", i))[0]\n\ndef GX2WaitForVsync():\n\trop.tiny_call(ROP_GX2WaitForVsync)\n\n# ROP CHAIN -------------------------------------------------------------------------------\n\nKERNEL_SYSCALL_TABLE_1 = 0xFFE84C70\nKERNEL_SYSCALL_TABLE_2 = 0xFFE85070\nKERNEL_SYSCALL_TABLE_3 = 0xFFE85470\nKERNEL_SYSCALL_TABLE_4 = 0xFFEAAA60\nKERNEL_SYSCALL_TABLE_5 = 0xFFEAAE60\n\ndriver_name_idx = 488\npm4_packets_idx = 472\nmem_patches = driver_name_idx + 3\nkernel_stuff = mem_patches + 2\n\npm4_pkt1 = calc_addr(pm4_packets_idx)\ndrv_name = calc_addr(driver_name_idx)\n\n# patch the kernel heap so the next allocation ends in userland\nrop.DCFlushRange(pm4_pkt1, 0x40)\nrop.tiny_call(ROP_GX2DirectCallDisplayList, pm4_pkt1, 32)\nrop.GX2Flush()\nGX2WaitForVsync()\nGX2WaitForVsync()\n\n# write our fake kernel heap metadata\nrop.write32(0x1F200014 + 0x00, 0x105F0000)\nrop.write32(0x1F200014 + 0x04, 0xFFFFFFB4)\nrop.call_func(ROP_memset, 0x1F200014 + 0x08, 0xFFFFFFFF, 8)\nrop.DCFlushRange(0x1F200014, 32)\nrop.tiny_call(0x020003A0 - 0xFE3C00)\n\n# register an OSDriver into userland\nrop.OSDriver_Register(drv_name, 6)\n\n# patch memory addr table\nrop.write32(0x105F0000 + 0x44, 0xFFEAB7A0 + (0x12*4))\nrop.OSDriver_CopyToSaveArea(drv_name, 6, calc_addr(mem_patches), 8)\n\n# patch syscalls\n\nrop.write32(0x105F0000 + 0x44, KERNEL_SYSCALL_TABLE_1 + (0x25*4))\nrop.OSDriver_CopyToSaveArea(drv_name, 6, calc_addr(kernel_stuff), 4)\n\nrop.write32(0x105F0000 + 0x44, KERNEL_SYSCALL_TABLE_2 + (0x25*4))\nrop.OSDriver_CopyToSaveArea(drv_name, 6, calc_addr(kernel_stuff), 4)\n\nrop.write32(0x105F0000 + 0x44, KERNEL_SYSCALL_TABLE_3 + (0x25*4))\nrop.OSDriver_CopyToSaveArea(drv_name, 6, calc_addr(kernel_stuff), 4)\n\nrop.write32(0x105F0000 + 0x44, KERNEL_SYSCALL_TABLE_4 + (0x25*4))\nrop.OSDriver_CopyToSaveArea(drv_name, 6, calc_addr(kernel_stuff), 4)\n\nrop.write32(0x105F0000 + 0x44, KERNEL_SYSCALL_TABLE_5 + (0x25*4))\nrop.OSDriver_CopyToSaveArea(drv_name, 6, calc_addr(kernel_stuff), 4)\n\n# patch kernel next driver ptr\nrop.write32(0x105F0000 + 0x44, 0xFFEAB530)\nrop.OSDriver_CopyToSaveArea(drv_name, 6, 0x105F0000 + 0x48, 4)\n\n# reset kernel heap next index\nrop.tiny_call(ROP_GX2DirectCallDisplayList, pm4_pkt1 + 0x20, 32)\nGX2WaitForVsync()\nGX2WaitForVsync()\n\nrop.tiny_call(ROP_Restart, 0, 0)\nrop.append(ROP_OSExitThread)\n\n# end of ROP CHAIN ------------------------------------------------------------------------\n\n# placing our data -----------------------------------------------------------------------\n\ncurr_idx = len(rop.rop_payload) + 1\ntmp_addr = calc_addr(curr_idx)\nwhile calc_addr(curr_idx) != ((tmp_addr + 0x20) & ~0x1F):\n\trop.append(0)\n\tcurr_idx = len(rop.rop_payload)\n\n# pm4_pkt1 - patch kernel heap\nrop.append(make_pm4_type3_packet_header(0x3D, 4))\nrop.append(0x1B800000 + 8)\nrop.append((1 << 18) | (0 << 17) | (0 << 16) | 0)\nrop.append(_byteswap_long(0x02000000))\nrop.append(0)\nrop.append(0x80000000)\nrop.append(0x80000000)\nrop.append(0x80000000)\n\n# pm4_pkt2 - patch kernel heap\nrop.append(make_pm4_type3_packet_header(0x3D, 4))\nrop.append(0x1B800000 + 8)\nrop.append((1 << 18) | (0 << 17) | (0 << 16) | 0)\nrop.append(0)\nrop.append(0)\nrop.append(0x80000000)\nrop.append(0x80000000)\nrop.append(0x80000000)\n\n# driver name - \"DRVHAX\"\nrop.append(0x44525648)\nrop.append(0x41580000)\n\nrop.append(0)\n\nrop.append(0x10000000)\nrop.append(0x28305800)\n\nrop.append(0xfff09e44)\nrop.append(0xfff09e44)\n\n# done placing our data -------------------------------------------------------------------\n\n\n\n\n\n\n# debug stuff and padding\n\nfor i in range(len(rop.rop_payload)):\n\tprint(\"%3d: %08X\" %(i,rop.rop_payload[i]))\n\n\nprint(\"\")\nprint(\"drv_name: \" + str(rop.rop_payload.index(0x44525648)))\nprint(\"pkt_idxs: \" + str(rop.rop_payload.index(make_pm4_type3_packet_header(0x3D, 4))))\nprint(\"patches: \" + str(rop.rop_payload.index(0x28305800) - 1))\nprint(\"\")\nprint(\"packet addr: \" + hex(pm4_pkt1))\nprint(\"driver name: \" + hex(drv_name))\nprint(kernel_stuff)\nprint(\"\")\nprint(hex(len(rop.rop_payload)*4))\n\nfor i in range(2560 - len(rop.rop_payload)):\n\tif i >= 0:\n\t\trop.append(0xF5A5A5A5)\n\n\nrop_packet = struct.pack(\">%iI\" %len(rop.rop_payload), *rop.rop_payload)\nprint(\"\")\ninput(\"Press ENTER to continue\")\n\n\n\n# socket server\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind(('0.0.0.0', 12345))\ns.listen(1)\nconn = s.accept()\nprint('Connected by ', conn[1])\nconn[0].send(rop_packet)","sub_path":"stage0.py","file_name":"stage0.py","file_ext":"py","file_size_in_byte":4560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"113792040","text":"import string\nimport requests\nimport json\nimport json5\nimport base64\nimport traceback\nfrom functools import lru_cache\nfrom collections import OrderedDict\nfrom secrets import token_hex\nfrom kombu_helper import put_message, visible_messages\nimport slack_sdk as slack\nfrom airflow.hooks.base_hook import BaseHook\nfrom bot_info import slack_token, botid, workerid, broker_url, slack_notification_channel\nfrom airflow_api import update_slack_connection, set_variable\nfrom kombu_helper import drain_messages, peek_message\n\n\ndef clear_queues():\n drain_messages(broker_url, \"seuronbot_payload\")\n drain_messages(broker_url, \"seuronbot_cmd\")\n\n\n@lru_cache(maxsize=1)\ndef extract_command(text):\n cmd = text.replace(workerid, \"\").replace(botid, \"\")\n cmd = cmd.translate(str.maketrans('', '', string.punctuation))\n cmd = cmd.lower()\n return \"\".join(cmd.split())\n\n\ndef send_message(msg_payload, client=None, context=None):\n output_queue = \"jupyter-output-queue\"\n if msg_payload[\"text\"]:\n if visible_messages(broker_url, output_queue) < 100:\n put_message(broker_url, output_queue, msg_payload)\n\n try:\n send_slack_message(msg_payload, client, context)\n except Exception:\n pass\n\n\ndef send_slack_message(msg_payload, client=None, context=None):\n if client is None:\n client = slack.WebClient(slack_token, timeout=300)\n\n slack_info = fetch_slack_thread()\n\n if context:\n slack_info = context\n\n if \"workername\" in msg_payload:\n slack_workername = msg_payload[\"workername\"]\n else:\n slack_workername = workerid\n\n if msg_payload.get(\"notification\", False):\n text = msg_payload[\"text\"]\n slack_channel = slack_notification_channel\n slack_thread = None\n else:\n text = f\"<@{slack_info['user']}>, {msg_payload['text']}\"\n slack_channel = slack_info[\"channel\"]\n slack_thread = slack_info.get(\"thread_ts\", slack_info.get(\"ts\", None))\n\n if msg_payload.get(\"attachment\", None) is None:\n client.chat_postMessage(\n username=slack_workername,\n channel=slack_channel,\n thread_ts=slack_thread,\n reply_broadcast=msg_payload.get(\"broadcast\", False),\n text=text\n )\n else:\n attachment = msg_payload[\"attachment\"]\n client.files_upload(\n username=slack_workername,\n channels=slack_channel,\n thread_ts=slack_thread,\n title=attachment['title'],\n filetype=attachment['filetype'],\n content=base64.b64decode(attachment['content']),\n initial_comment=text\n )\n\n\ndef replyto(msg, reply, workername=workerid, broadcast=False):\n msg_payload = {\n \"text\": reply,\n \"broadcast\": broadcast,\n \"workername\": workername,\n }\n\n if msg.get(\"from_jupyter\", False):\n send_message(msg_payload, context=None)\n else:\n send_message(msg_payload, context=msg)\n\n\ndef update_slack_thread(msg):\n payload = {\n 'user': msg['user'],\n 'channel': msg['channel'],\n 'thread_ts': msg['thread_ts'] if 'thread_ts' in msg else msg['ts']\n }\n update_slack_connection(payload, slack_token)\n\n\ndef fetch_slack_thread():\n SLACK_CONN_ID = \"Slack\"\n slack_extra = json.loads(BaseHook.get_connection(SLACK_CONN_ID).extra)\n return slack_extra\n\n\ndef create_run_token(msg):\n token = token_hex(16)\n set_variable(\"run_token\", token)\n jupyter_msg = f\"use `cancel run {token}` to cancel the current run\"\n put_message(broker_url, \"jupyter-output-queue\", {\"text\": jupyter_msg})\n\n try:\n sc = slack.WebClient(slack_token, timeout=300)\n if 'user' in msg:\n userid = msg['user']\n else:\n slack_info = fetch_slack_thread()\n userid = slack_info[\"user\"]\n\n reply_msg = \"use `{}, cancel run {}` to cancel the current run\".format(workerid, token)\n sc.chat_postMessage(\n channel=userid,\n text=reply_msg\n )\n except Exception:\n pass\n\n\ndef download_file(msg):\n if \"files\" in msg:\n # only use the first file:\n file_info = msg[\"files\"][0]\n private_url = file_info[\"url_private_download\"]\n filetype = file_info[\"pretty_type\"]\n response = requests.get(private_url, headers={'Authorization': 'Bearer {}'.format(slack_token)})\n\n if response.status_code == 200:\n return filetype, response.content.decode(\"ascii\", \"ignore\")\n else:\n return None, None\n elif msg.get(\"from_jupyter\", False) and msg.get(\"attachment\", None):\n attachment = {\n 'title': 'Script sent by jupyter',\n 'filetype': 'python',\n 'content': msg[\"attachment\"],\n }\n msg_payload = {\n \"text\": \"Use python script from jupyter cell\",\n \"attachment\": attachment,\n }\n send_message(msg_payload)\n return \"python\", base64.b64decode(attachment[\"content\"].encode(\"utf-8\")).decode(\"utf-8\")\n else:\n replyto(msg, \"You need to upload a parameter file with this message\")\n return None, None\n\n\ndef download_json(msg):\n filetype, content = download_file(msg)\n if not content:\n return None\n if filetype.lower() == \"python\":\n scope = {}\n try:\n exec(content, scope)\n if \"submit_parameters\" not in scope or not callable(scope[\"submit_parameters\"]):\n return None\n payloads = scope['submit_parameters']()\n except:\n replyto(msg, \"Cannot execute the `submit_parameters` function in the script\")\n replyto(msg, \"{}\".format(traceback.format_exc()))\n #upload_param(msg, payloads)\n return payloads\n else: #if filetype == \"JavaScript/JSON\":\n try:\n json_obj = json5.loads(content, object_pairs_hook=OrderedDict)\n except (ValueError, TypeError) as e:\n replyto(msg, \"Cannot load the json file: {}\".format(str(e)))\n return None\n return json_obj\n\n\ndef upload_param(msg, param):\n attachment = {\n \"title\": \"Pipeline parameters\",\n \"filetype\": \"javascript\",\n \"content\": base64.b64encode(json.dumps(param, indent=4).encode(\"utf-8\")).decode(\"utf-8\"),\n }\n msg_payload = {\n \"text\": \"current parameters\",\n \"attachment\": attachment,\n }\n send_message(msg_payload, context=msg)\n\n\ndef guess_run_type(param):\n if \"WORKER_IMAGE\" in param:\n return \"seg_run\"\n elif \"CHUNKFLOW_IMAGE\" in param:\n return \"inf_run\"\n else:\n return None\n\n\ndef latest_param_type():\n json_obj = peek_message(broker_url, \"seuronbot_payload\")\n if isinstance(json_obj, list):\n param = json_obj[0]\n else:\n param = json_obj\n\n if param:\n return guess_run_type(param)\n else:\n return None\n","sub_path":"slackbot/bot_utils.py","file_name":"bot_utils.py","file_ext":"py","file_size_in_byte":6897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"514061649","text":"import cv2 as cv2\nimport numpy as np\n\nfrom cellularAutomataV1 import GameOfLife\n\n#%%\n\nwidth = 200\nheight = 100\n\nstep = 0\n\n\nca_grid = GameOfLife(width, height)\nca_grid.randomSeed(0.55)\n\ncv2.namedWindow(\"Cells\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Cells', 800, 400)\n\n\nwhile(True):\n cv2.imshow(\"Cells\", ca_grid.cells)\n \n ca_grid.update()\n \n # cv2.waitKey(0)\n \n if cv2.waitKey(1) == ord('q'):\n break\n \n step += 1\n \n # if(step == 25):\n # step = 0\n # ca_grid.setChMatrixRandom()\n ","sub_path":"test_Game of Life.py","file_name":"test_Game of Life.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"285713443","text":"from collections import Counter\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def findFrequentTreeSum(self, root):\n if not root: return []\n l = []\n def ts(r): \n if not r: return 0\n r.val += ts(r.left) + ts(r.right)\n l.append(r.val)\n return r.val\n ts(root)\n c = Counter(l)\n mc = c.most_common(1)[0][1]\n print(mc)\n return [x for x in c if c[x] == mc]\n\nt = TreeNode(5)\nt.left = TreeNode(2)\nt.right = TreeNode(-5)\nprint(Solution().findFrequentTreeSum(t))\nt = TreeNode(5)\nt.left = TreeNode(2)\nt.right = TreeNode(-3)\nprint(Solution().findFrequentTreeSum(t))\n","sub_path":"leetcode/python/508_most-frequent-subtree-sum.py","file_name":"508_most-frequent-subtree-sum.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"21173136","text":"import base64\nimport datetime\nimport io\nimport logging\nimport time\nimport traceback\nimport urllib.parse\n\nimport django.db\nimport django.utils.timezone\nfrom channels.db import database_sync_to_async\nfrom channels.generic.websocket import AsyncJsonWebsocketConsumer, WebsocketConsumer\nfrom django.conf import settings\nfrom django.core.signing import Signer, BadSignature\nfrom django.shortcuts import reverse\n\nimport otree.bots.browser\nimport otree.channels.utils as channel_utils\nimport otree.session\nfrom otree.channels.utils import get_chat_group\nfrom otree.common import get_models_module\nfrom otree.export import export_wide, export_app\nfrom otree.models import Participant\nfrom otree.models_concrete import (\n CompletedGroupWaitPage,\n CompletedSubsessionWaitPage,\n ChatMessage,\n WaitPagePassage,\n)\nfrom otree.models_concrete import ParticipantRoomVisit, BrowserBotsLauncherSessionCode\nfrom otree.room import get_room_dict\nfrom otree.session import SESSION_CONFIGS_DICT\nfrom otree.views.admin import CreateSessionForm\n\n\nlogger = logging.getLogger(__name__)\n\nALWAYS_UNRESTRICTED = 'ALWAYS_UNRESTRICTED'\nUNRESTRICTED_IN_DEMO_MODE = 'UNRESTRICTED_IN_DEMO_MODE'\n\n\nclass InvalidWebSocketParams(Exception):\n '''exception to raise when websocket params are invalid'''\n\n\nclass _OTreeAsyncJsonWebsocketConsumer(AsyncJsonWebsocketConsumer):\n \"\"\"\n This is not public API, might change at any time.\n \"\"\"\n\n def clean_kwargs(self, **kwargs):\n '''\n subclasses should override if the route receives a comma-separated params arg.\n otherwise, this just passes the route kwargs as is (usually there is just one).\n The output of this method is passed to self.group_name(), self.post_connect,\n and self.pre_disconnect, so within each class, all 3 of those methods must\n accept the same args (or at least take a **kwargs wildcard, if the args aren't used)\n '''\n return kwargs\n\n def group_name(self, **kwargs):\n raise NotImplementedError()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.cleaned_kwargs = self.clean_kwargs(**self.scope['url_route']['kwargs'])\n group_name = self.group_name(**self.cleaned_kwargs)\n self.groups = [group_name] if group_name else []\n\n unrestricted_when = ''\n\n # there is no login_required for channels\n # so we need to make our own\n # https://github.com/django/channels/issues/1241\n async def connect(self):\n\n AUTH_LEVEL = settings.AUTH_LEVEL\n\n auth_required = (\n (not self.unrestricted_when)\n and AUTH_LEVEL\n or self.unrestricted_when == UNRESTRICTED_IN_DEMO_MODE\n and AUTH_LEVEL == 'STUDY'\n )\n\n if auth_required and not self.scope['user'].is_staff:\n msg = 'rejected un-authenticated access to websocket path {}'.format(\n self.scope['path']\n )\n # print(msg)\n logger.error(msg)\n # consider also self.accept() then send error message then self.close(code=1008)\n # this only affects otree core websockets.\n else:\n # need to accept no matter what, so we can at least send\n # an error message\n await self.accept()\n await self.post_connect(**self.cleaned_kwargs)\n\n async def post_connect(self, **kwargs):\n pass\n\n async def disconnect(self, message, **kwargs):\n await self.pre_disconnect(**self.cleaned_kwargs)\n\n async def pre_disconnect(self, **kwargs):\n pass\n\n async def receive_json(self, content, **etc):\n await self.post_receive_json(content, **self.cleaned_kwargs)\n\n async def post_receive_json(self, content, **kwargs):\n pass\n\n\nclass BaseWaitPage(_OTreeAsyncJsonWebsocketConsumer):\n unrestricted_when = ALWAYS_UNRESTRICTED\n kwarg_names: list\n\n def clean_kwargs(self):\n d = parse_querystring(self.scope['query_string'])\n kwargs = {}\n for k in self.kwarg_names:\n kwargs[k] = int(d[k])\n return kwargs\n\n async def wait_page_ready(self, event=None):\n await self.send_json({'status': 'ready'})\n\n async def pre_disconnect(self, session_pk, participant_id, **kwargs):\n\n await create_waitpage_passage(\n participant_id=participant_id, session_pk=session_pk, is_enter=False\n )\n\n\nclass SubsessionWaitPage(BaseWaitPage):\n\n kwarg_names = ('session_pk', 'page_index', 'participant_id')\n\n def group_name(self, session_pk, page_index, participant_id):\n return channel_utils.subsession_wait_page_name(session_pk, page_index)\n\n def completion_exists(self, **kwargs):\n return CompletedSubsessionWaitPage.objects.filter(**kwargs).exists()\n\n async def post_connect(self, session_pk, page_index, participant_id):\n if await database_sync_to_async(self.completion_exists)(\n page_index=page_index, session_id=session_pk\n ):\n await self.wait_page_ready()\n await create_waitpage_passage(\n participant_id=participant_id, session_pk=session_pk, is_enter=True\n )\n\n\nclass GroupWaitPage(BaseWaitPage):\n\n kwarg_names = SubsessionWaitPage.kwarg_names + ('group_id_in_subsession',)\n\n def group_name(\n self, session_pk, page_index, group_id_in_subsession, participant_id\n ):\n return channel_utils.group_wait_page_name(\n session_pk, page_index, group_id_in_subsession\n )\n\n def completion_exists(self, **kwargs):\n return CompletedGroupWaitPage.objects.filter(**kwargs).exists()\n\n async def post_connect(\n self, session_pk, page_index, group_id_in_subsession, participant_id\n ):\n if await database_sync_to_async(self.completion_exists)(\n page_index=page_index,\n id_in_subsession=group_id_in_subsession,\n session_id=session_pk,\n ):\n await self.wait_page_ready()\n await create_waitpage_passage(\n participant_id=participant_id, session_pk=session_pk, is_enter=True\n )\n\n\nclass GroupByArrivalTime(_OTreeAsyncJsonWebsocketConsumer):\n\n unrestricted_when = ALWAYS_UNRESTRICTED\n\n def clean_kwargs(self):\n d = parse_querystring(self.scope['query_string'])\n return {\n 'app_name': d['app_name'],\n 'session_pk': int(d['session_pk']),\n 'participant_id': int(d['participant_id']),\n 'page_index': int(d['page_index']),\n 'player_id': int(d['player_id']),\n }\n\n def group_name(self, app_name, player_id, page_index, session_pk, participant_id):\n gn = channel_utils.gbat_group_name(session_pk, page_index)\n return gn\n\n def is_ready(self, *, app_name, player_id, page_index, session_pk):\n models_module = get_models_module(app_name)\n group_id_in_subsession = (\n models_module.Group.objects.filter(player__id=player_id)\n .values_list('id_in_subsession', flat=True)\n .get()\n )\n\n return CompletedGroupWaitPage.objects.filter(\n page_index=page_index,\n id_in_subsession=int(group_id_in_subsession),\n session_id=session_pk,\n ).exists()\n\n async def post_connect(\n self, app_name, player_id, page_index, session_pk, participant_id\n ):\n if await database_sync_to_async(self.is_ready)(\n app_name=app_name,\n player_id=player_id,\n page_index=page_index,\n session_pk=session_pk,\n ):\n await self.gbat_ready()\n await create_waitpage_passage(\n participant_id=participant_id, session_pk=session_pk, is_enter=True\n )\n\n async def gbat_ready(self, event=None):\n await self.send_json({'status': 'ready'})\n\n async def pre_disconnect(\n self, app_name, player_id, page_index, session_pk, participant_id\n ):\n await create_waitpage_passage(\n participant_id=participant_id, session_pk=session_pk, is_enter=False\n )\n\n\nclass DetectAutoAdvance(_OTreeAsyncJsonWebsocketConsumer):\n\n unrestricted_when = ALWAYS_UNRESTRICTED\n\n def clean_kwargs(self):\n d = parse_querystring(self.scope['query_string'])\n return {\n 'participant_code': d['participant_code'],\n 'page_index': int(d['page_index']),\n }\n\n def group_name(self, page_index, participant_code):\n return channel_utils.auto_advance_group(participant_code)\n\n def page_should_be_on(self, participant_code):\n try:\n return (\n Participant.objects.filter(code=participant_code)\n .values_list('_index_in_pages', flat=True)\n .get()\n )\n except Participant.DoesNotExist:\n return\n\n async def post_connect(self, page_index, participant_code):\n # in case message was sent before this web socket connects\n page_should_be_on = await database_sync_to_async(self.page_should_be_on)(\n participant_code\n )\n if page_should_be_on is None:\n await self.send_json({'error': 'Participant not found in database.'})\n elif page_should_be_on > page_index:\n await self.auto_advanced()\n\n async def auto_advanced(self, event=None):\n await self.send_json({'auto_advanced': True})\n\n\nclass BaseCreateSession(_OTreeAsyncJsonWebsocketConsumer):\n def group_name(self, **kwargs):\n return None\n\n async def send_response_to_browser(self, event: dict):\n raise NotImplemented\n\n async def create_session_then_send_start_link(\n self, use_browser_bots, **session_kwargs\n ):\n\n try:\n session = await database_sync_to_async(otree.session.create_session)(\n **session_kwargs\n )\n if use_browser_bots:\n await database_sync_to_async(otree.bots.browser.initialize_session)(\n session_pk=session.pk, case_number=None\n )\n except Exception as e:\n\n # full error message is printed to console (though sometimes not?)\n error_message = 'Failed to create session: \"{}\"'.format(e)\n traceback_str = traceback.format_exc()\n await self.send_response_to_browser(\n dict(error=error_message, traceback=traceback_str)\n )\n raise\n\n session_home_view = (\n 'MTurkCreateHIT' if session.is_mturk() else 'SessionMonitor'\n )\n\n await self.send_response_to_browser(\n {'session_url': reverse(session_home_view, args=[session.code])}\n )\n\n\nclass CreateDemoSession(BaseCreateSession):\n\n unrestricted_when = UNRESTRICTED_IN_DEMO_MODE\n\n async def send_response_to_browser(self, event: dict):\n await self.send_json(event)\n\n async def post_receive_json(self, form_data: dict):\n session_config_name = form_data['session_config']\n config = SESSION_CONFIGS_DICT.get(session_config_name)\n if not config:\n msg = f'Spil type \"{session_config_name}\" eksiterer ikke.'\n await self.send_json({'validation_errors': msg})\n return\n\n num_participants = config['num_demo_participants']\n use_browser_bots = config.get('use_browser_bots', False)\n\n await self.create_session_then_send_start_link(\n session_config_name=session_config_name,\n use_browser_bots=use_browser_bots,\n num_participants=num_participants,\n is_demo=True,\n )\n\n\nclass CreateSession(BaseCreateSession):\n\n unrestricted_when = None\n\n def group_name(self, **kwargs):\n return 'create_session'\n\n async def post_receive_json(self, form_data: dict):\n form = CreateSessionForm(data=form_data)\n if not form.is_valid():\n await self.send_json({'validation_errors': form.errors})\n return\n\n session_config_name = form.cleaned_data['session_config']\n is_mturk = form.cleaned_data['is_mturk']\n\n config = SESSION_CONFIGS_DICT[session_config_name]\n\n num_participants = form.cleaned_data['num_participants']\n if is_mturk:\n num_participants *= settings.MTURK_NUM_PARTICIPANTS_MULTIPLE\n\n edited_session_config_fields = {}\n\n for field in config.editable_fields():\n html_field_name = config.html_field_name(field)\n old_value = config[field]\n\n # to allow concise unit tests, we can simply omit any fields we don't\n # want to change. this allows us to write more concise\n # unit tests.\n # EXCEPT for boolean fields -- omitting\n # it means we turn it off.\n # ideally we could interpret omitted boolean fields as unchanged\n # and False as unchecked, but HTML & serializeArray omits\n # unchecked checkboxes from form data.\n\n if isinstance(old_value, bool):\n new_value = bool(form_data.get(html_field_name))\n if old_value != new_value:\n edited_session_config_fields[field] = new_value\n else:\n new_value_raw = form_data.get(html_field_name, '')\n if new_value_raw != '':\n # don't use isinstance because that will catch bool also\n if type(old_value) is int:\n # in case someone enters 1.0 instead of 1\n new_value = int(float(new_value_raw))\n else:\n new_value = type(old_value)(new_value_raw)\n if old_value != new_value:\n edited_session_config_fields[field] = new_value\n\n use_browser_bots = edited_session_config_fields.get(\n 'use_browser_bots', config.get('use_browser_bots', False)\n )\n\n # if room_name is missing, it will be empty string\n room_name = form.cleaned_data['room_name'] or None\n\n await self.create_session_then_send_start_link(\n session_config_name=session_config_name,\n num_participants=num_participants,\n is_demo=False,\n is_mturk=is_mturk,\n edited_session_config_fields=edited_session_config_fields,\n use_browser_bots=use_browser_bots,\n room_name=room_name,\n )\n\n if room_name:\n await channel_utils.group_send_wrapper(\n type='room_session_ready',\n group=channel_utils.room_participants_group_name(room_name),\n event={},\n )\n\n async def send_response_to_browser(self, event: dict):\n '''\n Send to a group instead of the channel only,\n because if the websocket disconnects during creation of a large session,\n (due to temporary network error, etc, or Heroku H15, 55 seconds without ping)\n the user could be stuck on \"please wait\" forever.\n the downside is that if two admins create sessions around the same time,\n your page could automatically redirect to the other admin's session.\n '''\n [group] = self.groups\n await channel_utils.group_send_wrapper(\n type='session_created', group=group, event=event\n )\n\n async def session_created(self, event):\n await self.send_json(event)\n\n\nclass RoomAdmin(_OTreeAsyncJsonWebsocketConsumer):\n\n unrestricted_when = None\n\n def group_name(self, room):\n return channel_utils.room_admin_group_name(room)\n\n def get_list(self, **kwargs):\n\n # make it JSON serializable\n return list(\n ParticipantRoomVisit.objects.filter(**kwargs).values_list(\n 'participant_label', flat=True\n )\n )\n\n async def post_connect(self, room):\n room_object = get_room_dict()[room]\n now = time.time()\n stale_threshold = now - 15\n present_list = await database_sync_to_async(self.get_list)(\n room_name=room_object.name, last_updated__gte=stale_threshold\n )\n\n await self.send_json(\n {'status': 'load_participant_lists', 'participants_present': present_list}\n )\n\n # prune very old visits -- don't want a resource leak\n # because sometimes not getting deleted on WebSocket disconnect\n very_stale_threshold = now - 10 * 60\n await database_sync_to_async(self.delete_old_visits)(\n room_name=room_object.name, last_updated__lt=very_stale_threshold\n )\n\n def delete_old_visits(self, **kwargs):\n ParticipantRoomVisit.objects.filter(**kwargs).delete()\n\n async def roomadmin_update(self, event):\n del event['type']\n await self.send_json(event)\n\n\nclass RoomParticipant(_OTreeAsyncJsonWebsocketConsumer):\n\n unrestricted_when = ALWAYS_UNRESTRICTED\n\n def clean_kwargs(self):\n d = parse_querystring(self.scope['query_string'])\n d.setdefault('participant_label', '')\n return d\n\n def group_name(self, room_name, participant_label, tab_unique_id):\n return channel_utils.room_participants_group_name(room_name)\n\n def create_participant_room_visit(self, **kwargs):\n ParticipantRoomVisit.objects.create(**kwargs)\n\n async def post_connect(self, room_name, participant_label, tab_unique_id):\n if room_name in get_room_dict():\n room = get_room_dict()[room_name]\n else:\n # doesn't get shown because not yet localized\n await self.send_json({'error': 'Invalid room name \"{}\".'.format(room_name)})\n return\n if await database_sync_to_async(room.has_session)():\n await self.room_session_ready()\n else:\n try:\n await database_sync_to_async(self.create_participant_room_visit)(\n participant_label=participant_label,\n room_name=room_name,\n tab_unique_id=tab_unique_id,\n last_updated=time.time(),\n )\n except django.db.IntegrityError:\n # possible that the tab connected twice\n # without disconnecting in between\n # because of WebSocket failure\n # tab_unique_id is unique=True,\n # so this will throw an integrity error.\n # 2017-09-17: I saw the integrityerror on macOS.\n # previously, we logged this, but i see no need to do that.\n pass\n await channel_utils.group_send_wrapper(\n type='roomadmin_update',\n group=channel_utils.room_admin_group_name(room_name),\n event={'status': 'add_participant', 'participant': participant_label},\n )\n\n def delete_visit(self, **kwargs):\n ParticipantRoomVisit.objects.filter(**kwargs).delete()\n\n def visit_exists(self, **kwargs):\n return ParticipantRoomVisit.objects.filter(**kwargs).exists()\n\n async def pre_disconnect(self, room_name, participant_label, tab_unique_id):\n\n if room_name in get_room_dict():\n room = get_room_dict()[room_name]\n else:\n # doesn't get shown because not yet localized\n await self.send_json({'error': 'Invalid room name \"{}\".'.format(room_name)})\n return\n\n # should use filter instead of get,\n # because if the DB is recreated,\n # the record could already be deleted\n await database_sync_to_async(self.delete_visit)(\n participant_label=participant_label,\n room_name=room_name,\n tab_unique_id=tab_unique_id,\n )\n\n event = {'status': 'remove_participant'}\n if room.has_participant_labels():\n if await database_sync_to_async(self.visit_exists)(\n participant_label=participant_label, room_name=room_name\n ):\n return\n # it's ok if there is a race condition --\n # in JS removing a participant is idempotent\n event['participant'] = participant_label\n admin_group = channel_utils.room_admin_group_name(room_name)\n\n await channel_utils.group_send_wrapper(\n group=admin_group, type='roomadmin_update', event=event\n )\n\n async def room_session_ready(self, event=None):\n await self.send_json({'status': 'session_ready'})\n\n\nclass BrowserBotsLauncher(_OTreeAsyncJsonWebsocketConsumer):\n\n # OK to be unrestricted because this websocket doesn't create the session,\n # or do anything sensitive.\n unrestricted_when = ALWAYS_UNRESTRICTED\n\n def group_name(self, session_code):\n return channel_utils.browser_bots_launcher_group(session_code)\n\n async def send_completion_message(self, event):\n # don't need to put in JSON since it's just a participant code\n await self.send(event['text'])\n\n\nclass BrowserBot(_OTreeAsyncJsonWebsocketConsumer):\n\n unrestricted_when = ALWAYS_UNRESTRICTED\n\n def group_name(self):\n return 'browser_bot_wait'\n\n def session_exists(self):\n return BrowserBotsLauncherSessionCode.objects.exists()\n\n async def post_connect(self):\n if await database_sync_to_async(self.session_exists)():\n await self.browserbot_sessionready()\n\n async def browserbot_sessionready(self, event=None):\n await self.send_json({'status': 'session_ready'})\n\n\nclass ChatConsumer(_OTreeAsyncJsonWebsocketConsumer):\n\n unrestricted_when = ALWAYS_UNRESTRICTED\n\n def clean_kwargs(self, params):\n\n signer = Signer(sep='/')\n try:\n original_params = signer.unsign(params)\n except BadSignature:\n raise InvalidWebSocketParams\n\n channel, participant_id = original_params.split('/')\n\n return {'channel': channel, 'participant_id': int(participant_id)}\n\n def group_name(self, channel, participant_id):\n return get_chat_group(channel)\n\n def _get_history(self, channel):\n return list(\n ChatMessage.objects.filter(channel=channel)\n .order_by('timestamp')\n .values('nickname', 'body', 'participant_id')\n )\n\n async def post_connect(self, channel, participant_id):\n\n history = await database_sync_to_async(self._get_history)(channel=channel)\n\n # Convert ValuesQuerySet to list\n # but is it ok to send a list (not a dict) as json?\n await self.send_json(history)\n\n async def post_receive_json(self, content, channel, participant_id):\n\n # in the Channels docs, the example has a separate msg_consumer\n # channel, so this can be done asynchronously.\n # but i think the perf is probably good enough.\n # moving into here for simplicity, especially for testing.\n nickname_signed = content['nickname_signed']\n nickname = Signer().unsign(nickname_signed)\n body = content['body']\n\n chat_message = dict(nickname=nickname, body=body, participant_id=participant_id)\n\n [group] = self.groups\n await channel_utils.group_send_wrapper(\n type='chat_sendmessages', group=group, event={'chats': [chat_message]}\n )\n\n await database_sync_to_async(self._create_message)(\n participant_id=participant_id, channel=channel, body=body, nickname=nickname\n )\n\n def _create_message(self, **kwargs):\n ChatMessage.objects.create(**kwargs)\n\n async def chat_sendmessages(self, event):\n chats = event['chats']\n await self.send_json(chats)\n\n\nclass ExportData(_OTreeAsyncJsonWebsocketConsumer):\n\n '''\n I load tested this locally with sqlite/redis and:\n - large files up to 22MB (by putting long text in LongStringFields)\n - thousands of participants/rounds, 111000 rows and 20 cols in excel file.\n '''\n\n unrestricted_when = None\n\n async def post_receive_json(self, content: dict):\n '''\n if an app name is given, export the app.\n otherwise, export all the data (wide).\n don't need time_spent or chat yet, they are quick enough\n '''\n\n file_extension = content['file_extension']\n app_name = content.get('app_name')\n\n if file_extension == 'xlsx':\n mime_type = (\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"\n )\n IOClass = io.BytesIO\n else:\n mime_type = 'text/csv'\n IOClass = io.StringIO\n\n iso_date = datetime.date.today().isoformat()\n with IOClass() as fp:\n if app_name:\n await database_sync_to_async(export_app)(\n app_name, fp, file_extension=file_extension\n )\n file_name_prefix = app_name\n else:\n await database_sync_to_async(export_wide)(\n fp, file_extension=file_extension\n )\n file_name_prefix = 'all_apps_wide'\n data = fp.getvalue()\n\n file_name = f'{file_name_prefix}_{iso_date}.{file_extension}'\n\n if file_extension == 'xlsx':\n data = base64.b64encode(data).decode('utf-8')\n\n content.update(file_name=file_name, data=data, mime_type=mime_type)\n # this doesn't go through channel layer, so it is probably safer\n # in terms of sending large data\n await self.send_json(content)\n\n def group_name(self, **kwargs):\n return None\n\n\nclass NoOp(WebsocketConsumer):\n pass\n\n\ndef parse_querystring(query_string) -> dict:\n '''it seems parse_qs omits keys with empty values'''\n return {k: v[0] for k, v in urllib.parse.parse_qs(query_string.decode()).items()}\n\n\nasync def create_waitpage_passage(*, participant_id, session_pk, is_enter):\n await database_sync_to_async(_create_waitpage_passage)(\n participant_id=participant_id, session_pk=session_pk, is_enter=is_enter\n )\n\n\ndef _create_waitpage_passage(*, participant_id, session_pk, is_enter):\n '''if the session was deleted, this would raise'''\n try:\n WaitPagePassage.objects.create(\n participant_id=participant_id,\n session_id=session_pk,\n is_enter=is_enter,\n epoch_time=time.time(),\n )\n except:\n pass\n\n","sub_path":"otree/channels/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":26191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"347682374","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/12/15 15:49\n# @Author : Python12_秋\n# @Email : 793630871@qq.com\n# @File : A_13_LogList_test_case.py\n# @Software : PyCharm\n# @Explain : 投资人流水记录接口测试用例\n\nfrom ddt import ddt,data,unpack\nfrom common.http_requests_01 import HttpRequest\nfrom common.http_reading_excel_01 import DoExcel\nfrom common import http_path\nfrom common.Http_config import Reading\nfrom common.http_log import HttpLog\nfrom common.regular_expression import Regular\nfrom common.mysql import MysqlUtill\nimport unittest\nimport json\nfrom common.common_user import Login\n#创建日志对象,装载日志\nmy_log = HttpLog()\n#创建取配置对象\ncon = Reading(http_path.config_path_control)\n#获取需要的执行的测试用例ID\nconfig = con.get('CASE','button')\n#读取配置文件里面的URL地址\nconfig_url = con.get('URL','url_date')\n#读取测试数据,实例化测试数据对象\nexcel_date = DoExcel(http_path.case_path,config)\n#充值\nexcel_date_getFinanceLogList = excel_date.get_case('getFinanceLogList')\n\ncookies=None\n@ddt\nclass HttpCase(Login):\n#class HttpCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n Login().test_login() #固定投资用户登录\n def setUp(self):\n global sql,Income_record\n sql = con.get('SQL','Income_record')\n Income_record = MysqlUtill().get_fetch_one(sql)\n if Income_record is None:\n my_log.info(\"初始化数据--》投资人还未进行投资或者充值\")\n # 加 * 号,去掉一层外套\n @data(*excel_date_getFinanceLogList)\n #@unpack\n def test_http_case(self,i):\n global cookies # 声明全局变量\n #对excel里面的正则进行替换\n date = Regular().regular(i.request_data) # 正则参数替换\n my_log.info('正在执行地{0}条用例; 用例名称:{1}; 用例说明:{2}; 用例接口:{3}'.\n format(i.case_id, i.case_name,i.case_rept,i.api_name))\n my_log.info('================检查url====================')\n my_log.info('url:{}'.format(config_url+i.url))\n my_log.info('================检查request_data====================')\n my_log.info('request_data:{}'.format(i.request_data))\n my_log.info('================检查替换后的request_data====================')\n my_log.info('request_data:{}'.format(date))\n my_log.info('================检查method====================')\n my_log.info('method:{}'.format(i.mathod))\n my_log.info('================检查api_name====================')\n my_log.info('api_name:{}'.format(i.api_name))\n my_log.info('================检查预期结果expected_data====================')\n my_log.info('expected_data:{}'.format(i.expected_data))\n res = HttpRequest(config_url+i.url,json.loads(date),i.mathod,cookies)\n my_log.info('实际结果:{}'.format(res.get_json()))\n # 当cookie不为空时,改变全局变量的值\n if res.get_cookies():\n cookies = res.get_cookies()\n my_log.info('=================开始断言==================')\n try:\n #断言判断实际结果与期望结果是否一致\n self.assertEqual(json.loads(i.expected_data)['code'],json.loads(res.get_text())['code'])\n Testresult = 'pass'\n if json.loads(res.get_text())['code'] == '10001': # 查询成功,进行数据库校验\n recroed = MysqlUtill().get_fetch_one(sql)\n try:\n if recroed is None:\n my_log.info(\"数据库校验-->投资人还未进行投资或者充值\")\n elif recroed['Id'] == Income_record['Id'] :\n my_log.info(\"数据库校验-->查询成功,最新记录ID:{}\".format(recroed['Id']))\n elif Income_record is None and recroed is not None:\n my_log.info(\"数据库校验-->查询成功,最新记录ID:{}\".format(recroed['Id']))\n except Exception as e:\n my_log.info(\"数据库校验-->查询成功异常{}\".format(e))\n raise e\n else: #查询失败\n my_log.info(\"数据库校验-->查询失败!!!\")\n\n except Exception as e:\n Testresult = 'failed'\n my_log.error('断言错误:{0}'.format(e))\n raise e\n finally:\n my_log.info('resultd的值是:{0}'.format(Testresult))\n my_log.info('=================结束断言==================')\n #写入实际结果actual和result值\n excel_date.write_by_case_id(sheet_name='getFinanceLogList', case_id=i.case_id,\n actual=res.get_text(), result=Testresult)\n\n# if __name__ == '__main__':\n# unittest.main()\n","sub_path":"Interface_API/A_13_LogList_test_case.py","file_name":"A_13_LogList_test_case.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"272199378","text":"#! /bin/python3\n\nimport tweepy\nimport os\nfrom datetime import datetime as dt\nfrom math import floor\nimport pandas as pd\n# import matplotlib.pyplot as plt\n\nfrom get_api import get_api\n\n\ndef follower_factory(username='', api=None):\n\n # set destination directory for charts\n destination_dir = '../charts/follower_factory/'\n if not os.path.exists(destination_dir):\n os.markdir(destination_dir)\n\n #get screen name as username\n user_data = api.get_user(username)\n username = user_data.screen_name\n follower_count = user_data.followers_count\n print(f'User @{username} has {follower_count} followers to inspect...')\n\n today = f'{dt.now().year}{dt.now().month:02}{dt.now().day:02}'\n\n\n\n\n\n\n\n\ndef main():\n\n\n\n api = get_api(1)\n username = 'samgutentag'\n follower_factory(username=username, api=get_api(-1))\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/follower_factory/follower_factory.py","file_name":"follower_factory.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"618024993","text":"# -*- coding: utf-8 -*-\nimport datetime\nimport re\nfrom html import escape\n\n\nTAG_TYPE_OPEN = 1\nTAG_TYPE_CLOSE = 2\nTAG_TYPE_SINGLETON = 3\n\n\ndef render_tag(*args, **kwargs):\n \"\"\"Wrap one or more strings with tag format, larger-then and smaller-then sign.\n >>> render_tag('hello')\n u''\n >>> render_tag('hello', type_=TAG_TYPE_SINGLETON)\n u''\n >>> render_tag('a', 'b', 'c', type_=TAG_TYPE_OPEN)\n u''\n \"\"\"\n args = [x for x in args if not (x is None or (isinstance(x, str) and x.strip()==''))]\n if len(args) == 0:\n raise NameError(\"Tag must have at least one string input!\")\n\n type_ = kwargs.get('type_', TAG_TYPE_OPEN)\n if type_ == TAG_TYPE_OPEN:\n template = '<{}>'\n elif type_ == TAG_TYPE_CLOSE:\n template = ''\n elif type_ == TAG_TYPE_SINGLETON:\n template = '<{} />'\n else:\n raise ValueError('{} is not a valid type of tag.'.format(type_))\n return template.format(' '.join(args))\n\ndef validate_key(key):\n pattern = '^[a-zA-Z_:]$'\n for char in key:\n if ord(char) < 128:\n if not re.match(pattern, char):\n raise ValueError('Invalid character in attribute name.')\n pattern = '^[_.0-9a-zA-Z_:]$'\n\ndef html_param(k, v):\n \"\"\"Provide a very flexible way to create a pair of attribute-vlaue pair or just attribute.\"\"\"\n partial = lambda key, value: '{}=\"{}\"'.format(key, escape(value, quote=True))\n validate_key(k)\n if v is None:\n return k\n elif v is True:\n return partial(k, k)\n elif isinstance(v, str):\n return partial(k, v)\n elif isinstance(v, list):\n return partial(k, ' '.join(v))\n elif isinstance(v, dict):\n return partial(k, ' '.join([key for key, value in list(v.items()) if value]))\n elif isinstance(v, (int, float)):\n return partial(k, str(v))\n elif isinstance(v, datetime.datetime):\n return partial(k, v.isoformat())\n else:\n raise ValueError('Unknown value is used in html parameters.')\n\n\ndef html_params(attributes):\n return ' '.join([html_param(k, v) for k, v in list(attributes.items()) if v is not False])\n","sub_path":"html_node/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"441297774","text":"\"\"\"\nCRestricted Boltzmann Machines (CRBM) Implementation in Tensorflow\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport scipy.io as sio\nfrom xrbm.utils import tfutils\nfrom xrbm.utils import costs as costs\nfrom .abstract_model import AbstractRBM\n\nclass CRBM(AbstractRBM):\n 'Conditional Restricted Boltzmann Machines (CRBM)'\n\n def __init__(self, num_vis, num_cond, num_hid, vis_type='binary',\n activation=tf.nn.sigmoid, name='CRBM'):\n \"\"\"\n The CRBM Constructor\n\n Parameters\n ----------\n num_vis: int\n number of visible input units\n num_cond: int\n number of condition units\n num_hid: int\n number of hidden units\n vis_type: string\n the type of the visible units (`binary` or `gaussian`)\n activation: callable f(h)\n a function reference to the activation function of the hidden units\n name: string\n the name of the object (used for Tensorflow's scope)\n \"\"\"\n super(CRBM, self).__init__(num_vis, num_hid, vis_type, activation, name)\n\n # Model Params\n self.num_cond = num_cond\n\n # Weights\n self.W = None\n self.A = None\n self.B = None\n\n # Biases\n self.vbias = None\n self.hbias = None\n\n # Learning params\n self.model_params = None\n self.wu = None\n self.au = None\n self.bu = None\n self.vbu = None\n self.hbu = None\n\n with tf.variable_scope(self.name):\n self.create_placeholders_variables()\n\n def create_placeholders_variables(self):\n \"\"\"\n Creates \n \"\"\"\n with tf.variable_scope(self.name):\n self.sp_hidden_means = tf.get_variable(name='sp_hidden_means',\n shape=[self.num_hid],\n initializer=tf.constant_initializer(0.2))\n\n self.input_data = tfutils.data_variable((None, self.num_vis),'input_data')\n self.cond_data = tfutils.data_variable((None, self.num_cond),'condition_data')\n\n with tf.variable_scope('params'):\n self.W = tfutils.weight_variable([self.num_vis, self.num_hid], 'main_weights')\n self.A = tfutils.weight_variable([self.num_cond, self.num_vis], 'c2v_weights')\n self.B = tfutils.weight_variable([self.num_cond, self.num_hid], 'c2h_weights')\n self.vbias = tfutils.bias_variable([self.num_vis], 'vbias')\n self.hbias = tfutils.bias_variable([self.num_hid], 'hbias')\n\n self.model_params = [self.W, self.A, self.B, self.vbias, self.hbias]\n\n with tf.variable_scope('updates'):\n self.wu = tfutils.weight_variable([self.num_vis, self.num_hid], 'main_weights')\n self.au = tfutils.weight_variable([self.num_cond, self.num_vis], 'c2v_weights')\n self.bu = tfutils.weight_variable([self.num_cond, self.num_hid], 'c2h_weights')\n\n self.vbu = tfutils.bias_variable([self.num_vis], 'vbias', initializer=tf.constant_initializer(0.0))\n self.hbu = tfutils.bias_variable([self.num_hid], 'hbias', initializer=tf.constant_initializer(-0.1)) \n\n\n def sample_h_from_vc(self, visible, cond, n=-1): \n \"\"\"\n Get a sample of hidden units, given a tensor of visible and condition units configuations\n\n Parameters\n ----------\n visible: tensor\n a tensor of visible units configurations\n \n cond: tensor\n a tensor of condition units configurations\n \n Returns\n -------\n bottom_up: tensor\n a tensor containing the bottom up contributions before activation\n \n h_prob_means: tensor\n a tensor containing the mean probabilities of the hidden units activations\n\n h_samples: tensor\n a tensor containing a bernoulli sample generated from the mean activations\n \"\"\" \n with tf.variable_scope('sampling_hv'):\n bottom_up = (tf.matmul(visible, self.W) + # visible to hidden \n tf.matmul(cond, self.B) + # condition to hidden\n self.hbias) # static hidden biases\n\n h_probs_means = self.activation(bottom_up)\n h_samples = tfutils.sample_bernoulli(h_probs_means, n)\n\n return bottom_up, h_probs_means, h_samples\n\n def sample_v_from_hc(self, hidden, cond, n=-1):\n \"\"\"\n Get a sample of visible units, given a tensor of hidden and condition units configuations\n\n Parameters\n ----------\n hidden: tensor\n a tensor of hidden units configurations\n\n cond: tensor\n a tensor of condition units configurations\n \n Returns\n -------\n top_bottom: tensor\n a tensor containing the top bottom contributions\n \n v_probs_means: tensor\n a tensor containing the mean probabilities of the visible units\n\n v_samples: tensor\n a tensor containing a sample of visible units generated from the top bottom contributions\n \"\"\" \n with tf.variable_scope('sampling_vh'):\n contributions = (tf.matmul(hidden, tf.transpose(self.W)) + # hidden to visible\n tf.matmul(cond, self.A) + # condition to visible\n self.vbias) # static visible biases\n\n v_probs_means = self.activation(contributions)\n\n if self.vis_type == 'binary': \n v_samples = tfutils.sample_bernoulli(v_probs_means, n)\n elif self.vis_type == 'gaussian':\n v_samples = contributions # using means instead of sampling, as in Taylor et al\n\n\n return contributions, v_probs_means, v_samples\n\n def gibbs_sample_hvh(self, h_samples0, cond, n):\n \"\"\"\n Runs a cycle of gibbs sampling, started with an initial hidden units activations\n\n Used for training\n\n Parameters\n ----------\n h_samples0: tensor\n a tensor of initial hidden units activations\n \n cond: tensor\n a tensor of condition units configurations\n\n Returns\n -------\n v_probs_means: tensor\n\n v_samples: tensor\n visible samples\n h_probs_means: tensor\n a tensor containing the mean probabilities of the hidden units activations\n h_samples: tensor\n a tensor containing a bernoulli sample generated from the mean activations\n \"\"\" \n with tf.variable_scope('sampling_hvh'):\n # v from h\n top_bottom, v_probs_means, v_samples = self.sample_v_from_hc(h_samples0, cond, n)\n\n # h from v\n bottom_up, h_probs_means, h_samples = self.sample_h_from_vc(v_samples, cond, n)\n\n return v_probs_means, v_samples, h_probs_means, h_samples\n\n def gibbs_sample_hvh_condcont(self, h_samples0, condontA, condontB, n):\n \"\"\"\n Runs a cycle of gibbs sampling, started with an initial hidden units activations\n\n Uses pre-computed contributions from condition units to both hidden and visible units\n\n Parameters\n ----------\n h_samples0: tensor\n a tensor of initial hidden units activations\n \n condontA: tensor\n a tensor of contributions from condition to visible units\n\n condontB: tensor\n a tensor of contributions from condition to hidden units\n\n Returns\n -------\n v_probs_means: tensor\n\n v_samples: tensor\n visible samples\n h_probs_means: tensor\n a tensor containing the mean probabilities of the hidden units activations\n h_samples: tensor\n a tensor containing a bernoulli sample generated from the mean activations\n \"\"\" \n with tf.variable_scope('sampling_hvh'):\n # v from h\n contributions_to_vis = (tf.matmul(h_samples0, tf.transpose(self.W)) + # hidden to visible\n condontA + # condition to visible\n self.vbias) # static visible biases\n\n v_probs_means = self.activation(contributions_to_vis)\n\n if self.vis_type == 'binary': \n v_samples = tfutils.sample_bernoulli(v_probs_means, n)\n elif self.vis_type == 'gaussian':\n v_samples = contributions_to_vis # using means instead of sampling, as in Taylor et al\n\n\n # h from v \n contributions_to_hid = (tf.matmul(v_samples, self.W) + # visible to hidden \n condontB + # condition to hidden\n self.hbias) # static hidden biases\n\n h_probs_means = self.activation(contributions_to_hid)\n h_samples = tfutils.sample_bernoulli(h_probs_means, n)\n\n\n return v_probs_means, v_samples, h_probs_means, h_samples\n \n def gibbs_sample_vhv(self, v_samples0, cond, n):\n \"\"\"\n Runs a cycle of gibbs sampling, started with an initial visible and condition units configurations\n\n Parameters\n ----------\n v_samples0: tensor\n a tensor of initial visible units configuration\n \n cond: tensor\n a tensor of condition units configurations\n\n Returns\n -------\n v_probs_means: tensor\n\n v_samples: tensor\n visible samples\n h_probs_means: tensor\n a tensor containing the mean probabilities of the hidden units activations\n h_samples: tensor\n a tensor containing a bernoulli sample generated from the mean activations\n \"\"\" \n with tf.variable_scope('sampling_vhv'):\n # h from v\n bottom_up, h_probs_means, h_samples = self.sample_h_from_vc(v_samples0, cond, n)\n\n # v from h\n top_bottom, v_probs_means, v_samples = self.sample_v_from_hc(h_samples, cond, n)\n\n return v_probs_means, v_samples, h_probs_means, h_samples\n\n def inference(self, input_data, cond_data, cd_k=1, sparse_target=0, sparse_cost=0, sparse_decay=0):\n \"\"\"\n Defines the tensorflow operations for inference\n\n Parameters\n ----------\n input_data: tensor\n the input (batch) data tensor\n cond_data: tensor\n the condition data tensor\n cd_k=1: int, default 1\n the number of CD steps for gibbs sampling\n sparse_target: float, default 0\n the sparsity target\n sparse_cost: float, default 0\n the sparsity cost\n sparse_decay: float, default 0\n the sparsity weight decay\n\n Returns\n -------\n v_probs_means: tensor\n a tensor containing the mean probabilities of the visible units\n chain_end: tensor\n the last visible samples generated in the gibbs cycles\n sparse_grad: tensor\n the sparisity gradients\n current_activations_mean_props: tensor\n the mean activation of the hidden units\n \"\"\"\n\n with tf.variable_scope('inference'):\n ### positive phase\n # bottom-up - initialze the network with training data\n \n _, h_probs_means1, h_samples1 = self.sample_h_from_vc(input_data, cond=cond_data, n=self.batch_size)\n\n chain_data = h_samples1\n\n # calculate the sparsity term\n current_activations_mean_props = tf.reduce_mean(h_probs_means1, reduction_indices=0)\n\n self.sp_hidden_means = sparse_decay * current_activations_mean_props + (1 - sparse_decay) * self.sp_hidden_means\n sparse_grad = sparse_cost * (sparse_target - self.sp_hidden_means)\n \n current_activations_mean_props = h_probs_means1\n sparse_grad = 0\n\n # v_samples = tf.stop_gradient(v_samples)\n\n condcontA = tf.matmul(cond_data, self.A)\n condcontB = tf.matmul(cond_data, self.B)\n for k in range(cd_k): #TODO: this has to be more efficient since cond_data does not change\n v_probs_means, v_samples, h_probs_means, h_samples = self.gibbs_sample_hvh_condcont(chain_data, \n condcontA,\n condcontB,\n self.batch_size)\n chain_data = h_samples\n\n ### update\n chain_end = v_samples\n\n return v_probs_means, chain_end, sparse_grad, current_activations_mean_props\n\n def train_step(self, visible_data, cond_data, learning_rate,\n momentum=0, wdecay=0, cd_k=1,\n sparse_target=0, sparse_cost=0, sparse_decay=0):\n \"\"\"\n Defines the operations needed for a training step of a CRBM\n\n Parameters\n ----------\n visible_data: tensor\n the input (batch) data tensor\n cond_data: tensor\n the condition data tensor\n learning_rate: float\n the learning rate\n momentum: float, default 0\n the momentum value\n wdecay: float, default 0\n the weight decay value\n cd_k: int, default 1\n the number of CD steps for gibbs sampling\n sparse_target: float, default 0\n the sparsity target\n sparse_cost: float, default 0\n the sparsity cost\n sparse_decay: float, default 0\n the sparsity weight decay\n\n Returns\n -------\n rec_cost: float\n the reconstruction cost for this step\n new_params: list of tensors\n the updated model parameters\n updates: list of tensors\n the value of updates for each model parameter\n \"\"\"\n learning_rateW = learning_rate\n learning_rateA = learning_rate * 0.01 # it's a hack, the autoregressive weights often need a smaller lr\n learning_rateB = learning_rate\n\n with tf.variable_scope('train_step'):\n ## inference\n (chain_end_probs_means, \n chain_end, \n sparse_grad, \n current_activations_mean_props) = self.inference(visible_data, cond_data, \n cd_k, sparse_target, sparse_cost, sparse_decay)\n\n ## update\n # get the cost using free energy\n cost = self.get_cost(visible_data, cond_data, chain_end)\n\n # calculate the gradients using tf\n grad_params = tf.gradients(ys=cost, xs=self.model_params)\n\n # compose the update values, incorporating weight decay, momentum, and sparsity terms\n wu_ = self.wu.assign(momentum * self.wu - (grad_params[0] - sparse_grad - wdecay * self.W) * learning_rateW)\n au_ = self.au.assign(momentum * self.au - (grad_params[1] - wdecay * self.A) * learning_rateA)\n bu_ = self.bu.assign(momentum * self.bu - (grad_params[2] - wdecay * self.B) * learning_rateB)\n vbu_ = self.vbu.assign(momentum * self.vbu - grad_params[3] * learning_rate)\n hbu_ = self.hbu.assign(momentum * self.hbu - (grad_params[4] - sparse_grad) * learning_rate)\n\n updates = [wu_, au_, bu_, vbu_, hbu_]\n\n # ops to update the parameters\n w_ = self.W.assign_add(self.wu)\n a_ = self.A.assign_add(self.au)\n b_ = self.B.assign_add(self.bu)\n vb_ = self.vbias.assign_add(self.vbu)\n hb_ = self.hbias.assign_add(self.hbu)\n\n # we need to return the new params so that tf considers them in the graph\n new_params_ops = [w_, a_, b_, vb_, hb_]\n\n ## evaluate the reconstruction capability of the model\n rec_cost = self.get_reconstruction_cost(visible_data, chain_end_probs_means)\n\n return rec_cost, new_params_ops, updates, current_activations_mean_props #TODO: Remove\n\n def get_cost(self, v_sample, cond, chain_end):\n \"\"\"\n Calculates the free-energy cost between two data tensors, used for calcuating the gradients\n \n Parameters\n ----------\n v_sample: tensor\n the tensor A\n cond: tensor\n the condition tensor\n chain_end: tensor\n the tensor B\n\n Returns\n -------\n cost: float\n the cost\n \"\"\"\n\n with tf.variable_scope('fe_cost'):\n cost = tf.reduce_mean(self.free_energy(v_sample, cond)\n - self.free_energy(chain_end, cond), reduction_indices=0)\n return cost\n\n def get_reconstruction_cost(self, input_data, recon_means):\n \"\"\"\n Calculates the reconstruction cost between input data and reconstructed data\n \n Parameters\n ----------\n input_data: tensor\n the input data tensor\n recon_means: tensor\n the reconstructed data tensor\n\n Returns\n -------\n cost: float\n the reconstruction cost\n \"\"\"\n cost = costs.cross_entropy(input_data, recon_means)\n # cost = costs.mse(input_data, recon_means)\n return cost\n\n def free_energy(self, v_sample, cond): #TODO: change \n \"\"\"\n Calcuates the free-energy of a given visible tensor\n\n Parameters\n ----------\n v_sample: tensor\n the visible units tensor\n cond: tensor\n the condition units tensor\n\n Returns\n -------\n e: float\n the free energy\n \"\"\"\n with tf.variable_scope('free_energy'):\n bottom_up = (tf.matmul(v_sample, self.W) + # visible to hidden \n tf.matmul(cond, self.B) + # condition to hidden\n self.hbias) # static hidden biases\n \n vbias_n_cond = self.vbias + tf.matmul(cond, self.A)\n\n if self.vis_type == 'binary':\n v = - tf.matmul(v_sample, tf.expand_dims(vbias_n_cond,1), name='bin_visible_term')\n elif self.vis_type == 'gaussian':\n v = tf.reduce_sum(0.5 * tf.square(v_sample - vbias_n_cond), reduction_indices=1, name='gauss_visible_term') \n\n h = - tf.reduce_sum(tf.log(1 + tf.exp(bottom_up)), reduction_indices=1, name='hidden_term')\n\n return tf.transpose(tf.transpose(v) + tf.transpose(h)) \n \n def make_prediction(self, cond, init, num_gibbs=20):\n \"\"\"\n Generate (predict) the visible units configuration given the conditions\n\n Parameters\n ---------- \n cond: tensor\n the condition units tensor\n init: tensor\n the configuation to initialize the visible units with\n num_gibbs: int, default 20\n the number of gibbs sampling cycles\n\n Returns\n -------\n sample: tensor\n the predicted visible units\n hsample: tensor\n the hidden units activations\n \"\"\"\n\n # gibbs\n for k in range(num_gibbs): #TODO: this has to be more efficient since cond_data does not change\n vmean, sample, hmean, hsample = self.gibbs_sample_vhv(init, cond, 1)\n init = sample\n \n # mean-field approximation as suggested by Taylor\n _, vmean, sample = self.sample_v_from_hc(hmean, cond, 1)\n\n return sample, hsample\n\n\n def train(self, sess, input_data, cond_data, training_epochs, batch_size=100, learning_rate=0.1,\n snapshot_dir='./logs/', snapshot_freq=0, cd_k=1,\n momentum=0, wdecay=0, sparse_target=0, sparse_cost=0, sparse_decay=0):\n \"\"\"\n Creates mini-batches and trains the CRBM for the given number of epochs\n\n Parameters\n ----------\n input_data: tensor\n the input data tensor\n cond_data: tensor\n the condition data tensor\n training_epochs: float\n the number of training epochs\n batch_size: int\n the size of each mini batch\n learning_rate: float, default 0.1\n the learning rate\n snapshot_dir: string, default logs\n the directory to store model snapshots and logs\n snapshot_freq: int, default 100\n the frequency of the epochs to save a model snapshot\n cd_k: int, default 1\n the number of CD steps for gibbs sampling\n momentum: float, default 0\n the momentum value\n wdecay: float, default 0\n the weight decay value\n sparse_target: float, default 0\n the sparsity target\n sparse_cost: float, default 0\n the sparsity cost\n sparse_decay: float, default 0\n the sparsity weight decay\n\n Returns\n -------\n W: array_like\n the numpy visble-hidden weight matrix\n A: array_like\n the numpy condition to visible weight matrix\n B: array_like\n the numpy condition to hidden weight matrix\n vbias: array_like\n the numpy visible biases\n hbias: array_like\n the numpy hidden biases\n \"\"\"\n\n self.batch_size = batch_size\n \n # Make batches\n batch_idxs = np.random.permutation(range(len(input_data)))\n n_batches = len(batch_idxs) // batch_size\n \n # Define train ops \n train_op = self.train_step(self.input_data,\n self.cond_data, \n learning_rate, \n momentum, \n wdecay, \n cd_k=cd_k,\n sparse_target=sparse_target, \n sparse_cost=sparse_cost, \n sparse_decay=sparse_decay)\n \n saver = tf.train.Saver()\n\n # Run everything in tf \n for epoch in range(training_epochs):\n epoch_cost = 0\n epoch_h_means = 0;\n\n for batch_i in range(n_batches):\n # Get just minibatch amount of data\n idxs_i = batch_idxs[batch_i * batch_size:(batch_i + 1) * batch_size]\n \n # Add noise to the past, Gaussian with std 1\n cd_noise = cond_data[idxs_i] + np.random.normal(0, 1, [batch_size, self.num_cond])\n\n # Create the feed for the batch data\n feed = feed_dict={self.input_data: input_data[idxs_i],\n self.cond_data: cd_noise}\n\n # Run the training step\n (rec_cost, new_params, updates, h_means) = sess.run(train_op, feed_dict=feed)\n\n # Add up the cost\n epoch_cost += rec_cost\n epoch_h_means += h_means\n \n epoch_cost = epoch_cost/n_batches\n print('Epoch %i / %i | cost = %f | lr = %f | momentum = %f | sparse cost = %f'%\n (epoch+1, training_epochs, epoch_cost, learning_rate, momentum, sparse_cost))\n \n if snapshot_freq != 0 and (epoch+1) % snapshot_freq == 0: \n save_path = saver.save(sess, '%s%s_ep%i_model.ckpt' % (snapshot_dir, self.name, (epoch+1)))\n\n return self.W.eval(session=sess), self.A.eval(session=sess), self.B.eval(session=sess), self.vbias.eval(session=sess), self.hbias.eval(session=sess)\n","sub_path":"xrbm/models/crbm.py","file_name":"crbm.py","file_ext":"py","file_size_in_byte":23981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"97072304","text":"from __future__ import print_function\n\nimport mysql.connector\nfrom mysql.connector import errorcode\n\n\nclass Init_Data():\n DB_NAME = 'vzplmanager'\n TABLES = {}\n TABLES['record'] = (\n \"CREATE TABLE `record` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `body` varchar(128) NOT NULL,\"\n \" `partment` varchar(128) NOT NULL,\"\n \" `eventtype` varchar(128) NOT NULL,\"\n \" `step` varchar(128),\"\n \" `create_time` datetime NOT NULL,\"\n \" PRIMARY KEY (`id`)\"\n \") ENGINE=InnoDB\")\n\n TABLES['permission'] = (\n \"CREATE TABLE `permission` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `account` varchar(128) NOT NULL,\"\n \" `value` varchar(128) NOT NULL,\"\n \" PRIMARY KEY (`id`)\"\n \") ENGINE=InnoDB\")\n\n TABLES['user'] = (\n \"CREATE TABLE `user` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `username` varchar(128) NOT NULL,\"\n \" `account` varchar(128) NOT NULL,\"\n \" `partment` varchar(256) NOT NULL,\"\n \" `create_time` datetime NOT NULL,\"\n \" PRIMARY KEY (`id`)\"\n \") ENGINE=InnoDB\")\n\n TABLES['part'] = (\n \"CREATE TABLE `part` (\"\n \" `id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `partment` varchar(128) NOT NULL,\"\n \" `count` varchar(128) NOT NULL,\"\n \" `extra_count` varchar(128) NOT NULL,\"\n \" PRIMARY KEY (`id`)\"\n \") ENGINE=InnoDB\")\n\n TABLES['account'] = (\n \"CREATE TABLE `account` (\"\n \" `_id` int(11) NOT NULL AUTO_INCREMENT,\"\n \" `account` varchar(128) NOT NULL,\"\n \" `email` varchar(128) NOT NULL,\"\n \" `password` varchar(128) NOT NULL,\"\n \" `last_login` datetime NOT NULL,\"\n \" `author` varchar(256) NOT NULL,\"\n \" PRIMARY KEY (`_id`)\"\n \") ENGINE=InnoDB\")\n\n def create_database(self, cursor):\n try:\n cursor.execute(\n \"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'\".format(self.DB_NAME))\n except mysql.connector.Error as err:\n print(\"Failed creating database: {}\".format(err))\n exit(1)\n\n\n def delete(self):\n cnx = mysql.connector.connect(user='root', password='qwer1234',\n host='127.0.0.1')\n cursor = cnx.cursor()\n\n try:\n cursor.execute('drop database ' + self.DB_NAME + ';')\n except mysql.connector.Error as err:\n print(err)\n\n cnx.commit()\n cursor.close()\n cnx.close()\n\n\n def init(self):\n cnx = mysql.connector.connect(user='root', password='qwer1234',\n host='127.0.0.1')\n cursor = cnx.cursor()\n try:\n cnx.database = self.DB_NAME\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_BAD_DB_ERROR:\n self.create_database(cursor)\n cnx.database = self.DB_NAME\n else:\n print(err)\n exit(1)\n\n for name, ddl in self.TABLES.items():\n try:\n print(\"Creating table {}: \".format(name), end='')\n cursor.execute(ddl)\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\n print(\"already exists.\")\n else:\n print(err.msg)\n else:\n print(\"OK\")\n\n\n","sub_path":"com/org/sql/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"16896802","text":"\"\"\"\nDask Cluster Manager\n\"\"\"\n\n\nimport os\nimport sys\nimport logging\nlogging.getLogger(\"tornado.application\").setLevel(logging.CRITICAL)\nlogging.getLogger(\"distributed.utils\").setLevel(logging.CRITICAL)\nimport time\nimport distributed\nimport pilot.job.slurm\nimport pilot.job.ec2\n\nfrom urllib.parse import urlparse\n\n#from pilot.job.slurm import Service, Job\n#from pilot.job.ec2 import Service, Job\n\nclass Manager():\n\n def __init__(self, jobid, working_directory):\n self.jobid = jobid\n print(\"{}{}\".format(self.jobid, working_directory))\n self.working_directory = os.path.join(working_directory, jobid)\n self.myjob = None # SAGA Job\n self.local_id = None # Local Resource Manager ID (e.g. SLURM id)\n try:\n os.makedirs(self.working_directory)\n except:\n pass\n\n\n # Dask 1.20\n def submit_job(self,\n resource_url=\"fork://localhost\",\n number_of_nodes=1,\n number_cores=1,\n cores_per_node=1,\n spmd_variation=None,\n queue=None,\n walltime=None,\n project=None,\n reservation=None,\n config_name=\"default\",\n extend_job_id=None,\n pilot_compute_description=None\n ):\n try:\n # create a job service for SLURM LRMS or EC2 Cloud\n url_schema = urlparse(resource_url).scheme\n js = None\n if url_schema.startswith(\"slurm\"):\n js = pilot.job.slurm.Service(resource_url)\n elif url_schema.startswith(\"ec2\"):\n js = pilot.job.ec2.Service(resource_url) \n else:\n print(\"Unsupported URL Schema: %s \"%resource_url)\n return\n \n # environment, executable & arguments\n executable = \"python\"\n arguments = [\"-m\", \"pilot.plugins.dask.bootstrap_dask\", \" -p \", str(cores_per_node)]\n if \"dask_cores\" in pilot_compute_description:\n arguments = [\"-m\", \"pilot.plugins.dask.bootstrap_dask\", \" -p \", \n str(pilot_compute_description[\"dask_cores\"])]\n \n if extend_job_id!=None:\n arguments = [\"-m\", \"pilot.plugins.dask.bootstrap_dask\", \"-j\", extend_job_id]\n logging.debug(\"Run %s Args: %s\"%(executable, str(arguments)))\n \n jd ={\n \"executable\": executable,\n \"arguments\": arguments,\n \"working_directory\": self.working_directory,\n \"output\": \"dask_job_%s.stdout\"%self.jobid,\n \"error\": \"dask_job_%s.stderr\"%self.jobid,\n \"number_of_nodes\": number_of_nodes,\n \"cores_per_node\": cores_per_node,\n \"project\": project,\n \"reservation\": reservation,\n \"queue\": queue,\n \"walltime\": walltime,\n \"pilot_compute_description\" : pilot_compute_description\n }\n self.myjob = js.create_job(jd)\n self.myjob.run()\n self.local_id = self.myjob.get_id()\n print(\"**** Job: \" + str(self.local_id) + \" State : %s\" % (self.myjob.get_state()))\n return self.myjob\n except Exception as ex:\n print(\"An error occurred: %s\" % (str(ex)))\n\n def wait(self):\n while True:\n state = self.myjob.get_state()\n logging.debug(\"**** Job: \" + str(self.local_id) + \" State: %s\" % (state))\n if state.lower()==\"running\":\n logging.debug(\"looking for Dask startup state at: %s\"%self.working_directory)\n if self.is_scheduler_started():\n for i in range(5):\n try:\n print(\"init distributed client\")\n c=self.get_context()\n #c.scheduler_info()\n print(str(c.scheduler_info()))\n c.close()\n \n return\n except IOError as e:\n print(\"Dask Client Connect Attempt {} failed\".format(i))\n time.sleep(5)\n elif state == \"Failed\":\n break\n time.sleep(6)\n \n def cancel(self):\n c=self.get_context()\n c.run_on_scheduler(lambda dask_scheduler=None: dask_scheduler.close() & sys.exit(0))\n \n def submit_compute_unit(function_name):\n pass\n \n def get_context(self, configuration=None):\n \"\"\"Returns Dask Client for Scheduler\"\"\"\n details=self.get_config_data()\n if details is not None:\n print(\"Connect to Dask: %s\"%details[\"master_url\"])\n client = distributed.Client(details[\"master_url\"])\n return client\n return None\n \n \n def get_jobid(self):\n return self.jobid\n \n \n def get_config_data(self):\n if not self.is_scheduler_started():\n logging.debug(\"Scheduler not started\")\n return None\n master_file = os.path.join(self.working_directory, \"dask_scheduler\")\n # print master_file\n master = \"localhost\"\n counter = 0\n while os.path.exists(master_file) == False and counter < 600:\n time.sleep(2)\n counter = counter + 1\n\n with open(master_file, 'r') as f:\n master = f.read()\n \n master_host = master.split(\":\")[0]\n details = {\n \"master_url\": \"tcp://%s:8786\" % master_host,\n \"web_ui_url\": \"http://%s:8787\" % master_host,\n }\n return details\n\n\n def print_config_data(self):\n details = self.get_config_data()\n print(\"Dask Scheduler: %s\"%details[\"master_url\"])\n\n \n def is_scheduler_started(self):\n logging.debug(\"Results of scheduler startup file check: %s\"%str(os.path.exists(os.path.join(self.working_directory, \"dask_scheduler\"))))\n return os.path.exists(os.path.join(self.working_directory, \"dask_scheduler\"))\n","sub_path":"pilot/plugins/dask/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"536754705","text":"def find (r):\n res=[]\n for a in range(1,2*r):\n for b in range(1,2*r):\n if a*a+b*b<=4*r*r:\n x=[]\n x.append(a)\n x.append(b)\n x.sort()\n if not x in res:\n res.append(x)\n return len(res)\nn=int(input())\nfor i in range(n):\n a=int(input())\n print(find(a))","sub_path":"Code/CodeRecords/2592/60829/279363.py","file_name":"279363.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"26857969","text":"from io import BytesIO\n\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\nfrom xhtml2pdf import pisa\n\nfrom django.contrib import messages\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.urls import reverse_lazy\nfrom django.views.generic.base import View\nfrom django.db import transaction\nfrom product.mixins import CartMixin\nfrom product.models import Category\nfrom .forms import OrderForm\nfrom .models import Order\n\n\nclass CheckoutView(LoginRequiredMixin, CartMixin, View):\n \"\"\"Показ форми замовлення\"\"\"\n login_url = reverse_lazy(\"login\")\n\n def get(self, request, *args, **kwargs):\n form = OrderForm(request.POST or None)\n context = {\n 'form': form,\n 'cart': self.cart,\n 'categories': Category.objects.all()\n }\n return render(request, 'order/checkout.html', context)\n\n\nclass MakeOrderView(CartMixin, View):\n \"\"\"Замовлення*\"\"\"\n @transaction.atomic\n def post(self, request, *args, **kwargs):\n form = OrderForm(request.POST or None)\n if form.is_valid():\n order = form.save(commit=False)\n order.customer = self.customer\n order.first_name = form.cleaned_data['first_name']\n order.last_name = form.cleaned_data['last_name']\n order.phone = form.cleaned_data['phone']\n order.address = form.cleaned_data['address']\n order.type_order = form.cleaned_data['type_order']\n order.order_date = form.cleaned_data['order_date']\n order.save()\n self.cart.in_order = True\n self.cart.save()\n self.calc_quantity_in_stock(self.cart.products.all())\n order.cart = self.cart\n order.save()\n self.customer.order.add(order)\n return redirect('print')\n messages.error(self.request, 'Дата не може бути раніше сьогоднішньої')\n return redirect('checkout')\n\n def calc_quantity_in_stock(self, cart_products):\n for i in cart_products:\n i.product.quantity_in_stock -= i.count\n i.product.save()\n\n\ndef render_pdf_view(request):\n order = Order.objects.filter(customer__user=request.user).last()\n template_path = 'order/receipt.html'\n context = {'order': order}\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"report.pdf\"'\n template = get_template(template_path)\n html = template.render(context)\n pisa_status = pisa.CreatePDF(BytesIO(html.encode(\"UTF-8\")), dest=response)\n print(pisa_status)\n if pisa_status.err:\n return HttpResponse('We had some errors
' + html + '
')\n return response\n\n\ndef print_receipt_or_not(request):\n return render(request, 'order/o.html')\n\n\nclass PrintReceiptView(CartMixin, View):\n \"\"\"Print receipt\"\"\"\n def get(self, request, *args, **kwargs):\n data = {\n \"categories\": Category.objects.all(),\n \"cart\": self.cart\n }\n return render(request, 'order/o.html', data)\n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"293468519","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport pymc3 as pm\nimport theano\nimport theano.tensor as T\n\n\n\ndef plot_coef(model, X):\n \n \"\"\"\n Plots the coefficients of a linear model\n\n Parameters\n ----------\n \n model : pymc3_models linear model object\n \n \n X : X dataframe used to train the model\n shape [num_training_samples, num_pred]\n\n \"\"\"\n \n \n coefs = model.summary.reset_index().rename(columns = {'index' : 'coef'})\n ypa_ci = np.array(list(zip(-coefs['hpd_2.5'] + coefs['mean'], \n coefs['hpd_97.5'] - coefs['mean']))).T\n\n\n # Correct order coefficients are returned\n coef = ['intercept']\n for i in X.columns:\n coef.append(i)\n coef.append('sigma')\n coefs['coef'] = coef\n coefs = coefs.sort_values('mean')\n plt.figure(figsize = (12, 8))\n ax = plt.errorbar('mean', 'coef', xerr=ypa_ci, data=coefs, fmt='ko', \n capthick=2, capsize=10, label=None)\n plt.title('Coefficient Effect Size')\n plt.axvline(0)\n return ax\n\n","sub_path":"pymc3_models/models/plot_coef.py","file_name":"plot_coef.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"223084609","text":"from functools import partial\nfrom math import sqrt\nimport tensorflow as tf\nfrom tensorflow import constant as const\nfrom tensorflow.nn import embedding_lookup as lookup\nfrom layers.nsc_sentence_layer import nsc_sentence_layer\nfrom layers.nsc_document_layer import nsc_document_layer\n\n\ndef var(name, shape, initializer):\n return tf.get_variable(name, shape=shape, initializer=initializer)\n\n\nclass AMHNSC(object):\n def __init__(self, args, wrd_emb):\n self.max_doc_len = args['max_doc_len']\n self.max_sen_len = args['max_sen_len']\n self.cls_cnt = args['cls_cnt']\n self.embedding = args['embedding']\n self.emb_dim = args['emb_dim']\n self.hidden_size = args['hidden_size']\n self.usr_cnt = args['usr_cnt']\n self.prd_cnt = args['prd_cnt']\n self.doc_cnt = args['doc_cnt']\n self.sen_hop_cnt = args['sen_hop_cnt']\n self.doc_hop_cnt = args['doc_hop_cnt']\n self.l2_rate = args['l2_rate']\n self.convert_flag = ''\n self.debug = args['debug']\n self.lambda1 = args['lambda1']\n self.lambda2 = args['lambda2']\n self.lambda3 = args['lambda3']\n self.embedding_lr = args['embedding_lr']\n\n self.best_dev_acc = .0\n self.best_test_acc = .0\n self.best_test_rmse = .0\n\n # initializers for parameters\n self.w_init = tf.contrib.layers.xavier_initializer()\n self.b_init = tf.initializers.zeros()\n self.e_init = tf.contrib.layers.xavier_initializer()\n\n self.wrd_emb = wrd_emb\n self.usr_emb = var('usr_emb', [self.usr_cnt, self.emb_dim],\n self.e_init)\n self.prd_emb = var('prd_emb', [self.prd_cnt, self.emb_dim],\n self.e_init)\n self.embeddings = [self.wrd_emb, self.usr_emb, self.prd_emb]\n\n def build(self, input_map):\n transform = partial(\n tf.layers.dense,\n use_bias=False,\n kernel_initializer=self.w_init,\n bias_initializer=self.b_init)\n dense = partial(\n tf.layers.dense,\n kernel_initializer=self.w_init,\n bias_initializer=self.b_init)\n lstm_cell = partial(\n tf.nn.rnn_cell.LSTMCell,\n self.hidden_size // 2,\n forget_bias=0.,\n initializer=self.w_init)\n\n def pad_context(context, input_x):\n \"\"\" padding content with context embedding \"\"\"\n tiled_context = transform(context, self.emb_dim)\n tiled_context = tf.tile(tiled_context[:, None, None, :],\n [1, self.max_doc_len, 1, 1])\n input_x = tf.reshape(\n input_x,\n [-1, self.max_doc_len, self.max_sen_len, self.emb_dim])\n input_x = tf.concat([tiled_context, input_x], axis=2)\n input_x = tf.reshape(input_x,\n [-1, self.max_sen_len + 1, self.emb_dim])\n return input_x\n\n # get the inputs\n with tf.variable_scope('inputs'):\n usrid, prdid, input_x, input_y, sen_len, doc_len, docid = \\\n (input_map['usr'], input_map['prd'],\n input_map['content'], input_map['rating'],\n input_map['sen_len'], input_map['doc_len'],\n input_map['docid'])\n\n usr = lookup(self.usr_emb, usrid)\n prd = lookup(self.prd_emb, prdid)\n input_x = lookup(self.wrd_emb, input_x)\n\n nscua_input_x = pad_context(usr, input_x)\n nscpa_input_x = pad_context(prd, input_x)\n\n sen_len = tf.where(\n tf.equal(sen_len, 0), tf.zeros_like(sen_len), sen_len + 1)\n self.max_sen_len += 1\n\n # build the process of model\n sen_embs, doc_embs = [], []\n sen_cell_fw = lstm_cell()\n sen_cell_bw = lstm_cell()\n for scope, identities, input_x, attention_type in zip(\n ['user_block', 'product_block'], [[usr], [prd]],\n [nscua_input_x, nscpa_input_x], ['additive', 'additive']):\n with tf.variable_scope(scope):\n sen_emb = nsc_sentence_layer(\n input_x,\n self.max_sen_len,\n self.max_doc_len,\n sen_len,\n identities,\n self.hidden_size,\n self.emb_dim,\n self.sen_hop_cnt,\n bidirectional_lstm=True,\n lstm_cells=[sen_cell_fw, sen_cell_bw],\n auged=True,\n attention_type=attention_type)\n sen_embs.append(sen_emb)\n\n sen_embs = tf.concat(sen_embs, axis=-1)\n\n # padding doc with user and product embeddings\n doc_aug_usr = transform(usr, 2 * self.hidden_size)\n nscua_sen_embs = tf.concat([doc_aug_usr[:, None, :], sen_embs], axis=1)\n doc_aug_prd = transform(prd, 2 * self.hidden_size)\n nscpa_sen_embs = tf.concat([doc_aug_prd[:, None, :], sen_embs], axis=1)\n # none_sen_embs = tf.pad(sen_embs, [[0, 0], [1, 0], [0, 0]])\n self.max_doc_len += 1\n doc_len = doc_len + 1\n\n doc_cell_fw = lstm_cell()\n doc_cell_bw = lstm_cell()\n for scope, identities, input_x, attention_type in zip(\n ['user_block', 'product_block'], [[usr], [prd]],\n [nscua_sen_embs, nscpa_sen_embs], ['additive', 'additive']):\n with tf.variable_scope(scope):\n doc_emb = nsc_document_layer(\n input_x,\n self.max_doc_len,\n doc_len,\n identities,\n self.hidden_size,\n self.doc_hop_cnt,\n bidirectional_lstm=True,\n lstm_cells=[doc_cell_fw, doc_cell_bw],\n auged=True,\n attention_type=attention_type)\n doc_embs.append(doc_emb)\n\n with tf.variable_scope('result'):\n doc_emb = tf.concat(doc_embs, axis=1, name='dhuapa_output')\n logit = dense(doc_emb, self.cls_cnt)\n return logit\n","sub_path":"layers/amhnsc.py","file_name":"amhnsc.py","file_ext":"py","file_size_in_byte":6112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"363964792","text":"from datetime import datetime\n\nimport altair as alt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import Ridge, RidgeCV\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import KFold\nfrom sklearn import metrics\n# import peak_engines\n\nX, y = load_boston(return_X_y=True)\nresult = load_boston()\n# model = peak_engines.RidgeRegressionModel(normalize=True, grouping_mode=\"none\")\n\n# start = datetime.now()\n# model.fit(X, y)\n# print(f\"{datetime.now()-start} seconds\")\n\n# print(\"alpha =\", model.regularization_)\n# for i in model.alpha_:\n# print(np.log(i))\n# np.argsort(model.alpha_)\n# # groups 0 (x <-100): 8, 7\n# # 1 (-100 < x < -3): 4, 9, 0, 10, 12\n# # 2 (-3 < x < 0): 1, 5, 11, 3\n# # 3 (x > 0): 6, 2\n# yhat = model.predict(X)\n# metrics.mean_squared_error(yhat, y)\n\n# model = peak_engines.RidgeRegressionModel(\n# normalize=True, num_groups=2\n# )\n# model.fit(X, y)\n# print(\"alpha =\", model.regularization_)\n\ngrouper1 = np.zeros(13)\ngrouper1[[4, 9, 0, 10, 12]] = 1\ngrouper1[[1, 5, 11, 3]] = 2\ngrouper1[[6, 2]] = 3\ngrouper1 = grouper1.astype(\"int\").tolist()\n# model = peak_engines.RidgeRegressionModel(normalize=True, grouper=lambda X, y: grouper1)\n# model.fit(X, y)\n# print(\"alpha =\", model.regularization_)\n\nskridge = RidgeCV()\nstart = datetime.now()\nskridge.fit(X, y)\nprint(f\"{datetime.now()-start} seconds\")\nskyhat = skridge.predict(X)\nmetrics.mean_squared_error(skyhat, y)\n# mse: 21.89840819759002\n\nkf = KFold(506)\nresult = list(kf.split(X))\n\n\ndef benchmark(type, n_fold=8, **kwargs):\n \"\"\"\n benchmark of models\n \"\"\"\n if type == \"fast_ridge\":\n if kwargs:\n # model = peak_engines.RidgeRegressionModel(normalize=True, **kwargs)\n pass\n else:\n # model = peak_engines.RidgeRegressionModel(\n # normalize=True, grouping_mode=\"none\"\n # )\n pass\n elif type == \"ridge\":\n model = Ridge(normalize=True)\n elif type == \"ridgecv\":\n model = RidgeCV(normalize=True)\n else:\n raise ValueError(\"Undefined type.\")\n scores = []\n modeltime = []\n for train_index, test_index in result:\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n start = datetime.now()\n model.fit(X_train, y_train)\n time_span = (datetime.now() - start).microseconds\n modeltime.append(time_span)\n yhat = model.predict(X_test)\n scores.append(metrics.mean_squared_error(yhat, y_test))\n return pd.DataFrame({\"mse\": scores, \"time\": modeltime})\n\n\nfr_df = benchmark(\"fast_ridge\", n_fold=8, score=\"loocv\")\nfr_df.describe() # 33.46049333430216, gcv: 31.64\nalt.Chart(fr_df).mark_point().encode(x=\"mse\", y=\"time\")\n\nfr_df = benchmark(\"fast_ridge\", n_fold=8)\nfr_df.describe() # 2-group: 31.85, 'all': 31.62\nalt.Chart(fr_df).mark_point().encode(x=\"mse\", y=\"time\")\n# for multi-group, gcv is worse\n\nfor i in range(1, 9):\n fr_df = benchmark(\"fast_ridge\", n_fold=8, num_groups=i)\n print(f\"{i} groups: loss {fr_df['mse'].mean()}\")\n\n\n# given number of groups\nfor i in range(2, 13):\n fr_df = benchmark(\"fast_ridge\", n_fold=8, num_groups=i)\n print(fr_df[\"mse\"].mean())\n# 2 is best 31.58\n\nfr_df = benchmark(\"fast_ridge\", n_fold=8, grouper=lambda X, y: grouper1)\nfr_df.describe() # 31.16\nalt.Chart(fr_df).mark_point().encode(x=\"mse\", y=\"time\")\n\nr_df = benchmark(\"ridge\", 8)\nr_df.describe() # 36.65282989796395\nalt.Chart(r_df).mark_point().encode(x=\"mse\", y=\"time\")\n\nrcv_df = benchmark(\"ridgecv\", 8)\nrcv_df.describe() # 30.449386520871208\n# 30.17\n# mse: 24.2155\n","sub_path":"player-rl/boston/ridge.py","file_name":"ridge.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"206448124","text":"from typing import List\n\nfrom fastapi import APIRouter, HTTPException\nfrom tortoise.contrib.fastapi import HTTPNotFoundError\nfrom tortoise.exceptions import DoesNotExist\n\nfrom api.models.pydantic.status import Status\nfrom api.models.tortoise.fiche_action import FicheAction_Pydantic, FicheAction, FicheActionIn_Pydantic\n\nrouter = APIRouter(prefix='/v1/fiche_action')\n\n\n@router.post(\"/{epci_id}\", response_model=FicheAction_Pydantic)\nasync def write_epci_fiche_action(epci_id: str, fiche_action: FicheActionIn_Pydantic):\n if epci_id != fiche_action.epci_id:\n raise HTTPException(status_code=400, detail=\"epci_id mismatch\")\n\n query = FicheAction.filter(epci_id=epci_id, uid=fiche_action.uid)\n\n if query.exists():\n await query.delete()\n\n fiche_action_obj = await FicheAction.create(**fiche_action.dict(exclude_unset=True))\n return await FicheAction_Pydantic.from_tortoise_orm(fiche_action_obj)\n\n\n@router.get(\"/{epci_id}/all\", response_model=List[FicheAction_Pydantic])\nasync def get_all_epci_actions_status(epci_id: str):\n query = FicheAction.filter(epci_id=epci_id)\n return await FicheAction_Pydantic.from_queryset(query)\n\n\n@router.get(\n \"/{epci_id}/{uid}\", response_model=FicheAction_Pydantic,\n responses={404: {\"model\": HTTPNotFoundError}}\n)\nasync def get_fiche_action(epci_id: str, uid: str):\n query = FicheAction.get(epci_id=epci_id, uid=uid)\n try:\n return await FicheAction_Pydantic.from_queryset_single(query)\n except DoesNotExist as error:\n raise HTTPException(status_code=404, detail=f\"fiche_action {epci_id}/{uid} not found\")\n\n\n@router.delete(\n \"/{epci_id}/{uid}\", response_model=Status,\n responses={404: {\"model\": HTTPNotFoundError}}\n)\nasync def delete_fiche_action(epci_id: str, uid: str):\n query = FicheAction.filter(epci_id=epci_id, uid=uid)\n deleted_count = await query.delete()\n if not deleted_count:\n raise HTTPException(status_code=404, detail=f\"fiche_action /{epci_id}/{uid} not found\")\n return Status(message=f\"Deleted fiche_action /{epci_id}/{uid}\")\n","sub_path":"api/routers/fiche_action.py","file_name":"fiche_action.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"35786373","text":"import requests\nimport json\nimport time\nfrom Token import access_token\n\n\nclass User:\n def __init__(self, access_token):\n self.access_token = access_token\n self.friends = []\n self.id_socials = []\n self.socials = set()\n self.groups_of_friends = []\n self.socials_of_friends = set()\n self.info_list = []\n self.info_dict = {}\n\n def api_get(self, method_name, p):\n params = {'access_token': access_token, 'v': 5.102}\n params.update(p)\n resp = requests.get(\n f'https://api.vk.com/method/{method_name}',\n params=params).json()\n if 'response' in resp:\n return resp['response']\n elif 'error' in resp and resp['error']['error_code'] == 6:\n time.sleep(2)\n return self.api_get(method_name, p)\n\n def input_user_id(self):\n self.short_name = input('Введите id или короткое имя (screen name) пользователя: ')\n if not self.short_name.isdigit():\n self.short_name = self.get_id()\n\n def get_id(self):\n try:\n self.id = self.api_get('users.get', {'user_ids': self.short_name})[0]['id']\n except KeyError:\n return 'Пользователь не найден!'\n\n def get_friends(self):\n self.friends = self.api_get('friends.get', {'user_ids': self.short_name})['items']\n print('Получаем список друзей')\n\n def get_socials(self):\n self.id_socials = self.api_get('groups.get', {'user_id': self.short_name})['items']\n print('Получаем список сообществ')\n\n def get_socials_of_friends(self):\n user_socials = set(self.id_socials)\n for friend in self.friends:\n self.groups_of_friends = requests.get(\n 'https://api.vk.com/method/groups.get',\n params={\n 'user_id': friend,\n 'access_token': access_token,\n 'v': 5.102\n }\n )\n if 'response' in self.groups_of_friends.json():\n for items in self.groups_of_friends.json()['response']['items']:\n self.socials.add(items)\n self.socials_of_friends = user_socials.difference(self.socials)\n print('.')\n elif 'error' in self.groups_of_friends.json() and self.groups_of_friends.json()['error']['error_code'] == 6:\n time.sleep(2)\n return self.get_socials_of_friends()\n\n def get_members_of_group(self, id):\n self.id = id\n response = self.api_get('groups.getMembers', {'group_id': id})\n print('Получаем количество человек в каждой группе')\n return response['count']\n\n def get_name_of_group(self):\n for group in self.socials_of_friends:\n response = self.api_get('groups.getById', {'group_ids': group})\n print('Получаем названия групп')\n self.info_dict = {'name': response[0]['name'],\n 'id': response[0]['id'],\n 'member_count': self.get_members_of_group(group)}\n self.info_list.append(self.info_dict)\n\n def write_to_json(self):\n with open('result.json', 'w') as file:\n print('Записываем результат в файл json')\n json.dump(self.info_list, file, indent=4, ensure_ascii=False)\n\n def main(self):\n self.input_user_id()\n self.get_id()\n self.get_friends()\n self.get_socials()\n self.get_socials_of_friends()\n self.get_name_of_group()\n self.write_to_json()\n\nuser1 = User(access_token)\nif __name__ == '__main__':\n user1.main()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"319697351","text":"import numpy as np\nimport copy\n\nclass Utils:\n \n def dE_dnet(loss, y):\n _loss = copy.copy(loss)\n _loss[y] = - (1 - _loss[y])\n return _loss\n\n def ReLU_X(X):\n res = copy.copy(X)\n for x in np.nditer(res, op_flags=['readwrite']):\n x[...] = 1 if x > 0 else 0\n return res\n\n def X_ReLU(conv, pool, pool_size, strides):\n \n _conv = copy.copy(conv) \n\n for z in range(len(_conv)):\n for i in range(0, len(_conv[z]) - pool_size[0] + 1, strides[0]):\n for j in range(0, len(_conv[z][i]) - pool_size[1] + 1, strides[1]):\n for k in range(pool_size[0]):\n for l in range(pool_size[1]):\n if(_conv[z][i + k][j + l] == pool[z][i//strides[0]][j//strides[1]]):\n _conv[z][i + k][j + l] = 1\n else:\n _conv[z][i + k][j + l] = 0\n return np.array(_conv)\n\n def constant_mult_matrix(conv, pool, pool_size, strides):\n _conv = conv.tolist()\n count = 0\n \n for z in range(len(_conv)):\n for i in range(0, len(_conv[z]) - pool_size[0] + 1, strides[0]):\n for j in range(0, len(_conv[z][i]) - pool_size[1] + 1, strides[1]):\n for k in range(pool_size[0]):\n for l in range(pool_size[1]):\n temp = _conv[z][i + k][j + l] * pool[count]\n # print(\"=> \" + str((z, i+k, j+l)) + \" \" + str(count) + \" \" + str(temp))\n _conv[z][i + k][j + l] = temp\n count += 1\n # print(np.array(_conv))\n return _conv\n\n def biases_correction(weights):\n res = []\n for i in range(len(weights)):\n sum = 0\n for j in range(len(weights[i])):\n for k in range(len(weights[i][j])):\n sum += weights[i][j][k]\n res.append(sum)\n return res\n\n def convolution(matrix, weights, strides):\n height = len(matrix)\n width = len(matrix[0])\n\n conv = []\n\n for z in range(len(weights)):\n temp2 = []\n for i in range(0, height - len(weights[z]) + 1, strides[0]):\n temp1 = []\n \n for j in range(0, width - len(weights[z][i]) + 1, strides[1]):\n sum = 0\n for k in range(len(weights[z])):\n for l in range(len(weights[z][i])):\n sum += matrix[i + k][j + l] * weights[z][k][l]\n temp1.append(sum)\n temp2.append(temp1)\n conv.append(temp2)\n\n return np.array(conv)\n\n\nclass Pooling:\n def __init__(\n self,\n pool_mode,\n name=\"pooling\",\n pool_size=(2, 2),\n pool_strides=None,\n pool_padding=(0, 0),\n ):\n self._name = name\n\n self._pool_mode = pool_mode\n self._pool_strides = pool_strides if (pool_strides\n is not None) else pool_size\n self._pool_padding = pool_padding\n self._pool_size = pool_size\n\n self._neurons = []\n self._nets = []\n\n self._input_shape = None\n self._output_shape = None\n\n self._dE_do = None\n\n @property\n def output_size(self):\n return self._output_shape\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n @property\n def neurons(self):\n return self._neurons\n\n @property\n def nets(self):\n return self._nets\n\n @nets.setter\n def nets(self, nets):\n self._nets = nets\n\n @property\n def input_size(self):\n return self._input_shape\n \n @input_size.setter\n def input_size(self, shape):\n self._input_shape = shape\n\n def init_layer(self):\n height = self._input_shape[1]\n width = self._input_shape[2]\n\n if (width % self._pool_strides[1] != 0):\n width += self._pool_strides[1] - (width % self._pool_strides[1])\n\n if (height % self._pool_strides[0] != 0):\n height += self._pool_strides[0] - (height % self._pool_strides[0])\n\n self._output_shape = (None, width // self._pool_size[1],\n height // self._pool_size[0], self._input_shape[3])\n\n def add_auto_padding(self, matrix):\n height = len(matrix)\n width = len(matrix[0])\n\n left_padding = 0\n right_padding = 0\n\n up_padding = 0\n down_padding = 0\n\n if (width % self._pool_strides[1] != 0):\n for i in range(self._pool_strides[1] -\n (width % self._pool_strides[1])):\n if (i % 2 == 0):\n right_padding += 1\n else:\n left_padding += 1\n\n if (height % self._pool_strides[0] != 0):\n for i in range(self._pool_strides[0] -\n (height % self._pool_strides[0])):\n if (i % 2 == 0):\n down_padding += 1\n else:\n up_padding += 1\n\n for i in range(height):\n matrix[i] += [0] * right_padding\n for _ in range(left_padding):\n matrix[i].insert(0, 0)\n\n for _ in range(up_padding):\n matrix.insert(0, [0] * len(matrix[0]))\n\n for _ in range(down_padding):\n matrix.append([0] * len(matrix[0]))\n\n return matrix\n\n def add_padding(self, matrix):\n height = len(matrix)\n width = len(matrix[0])\n\n left_padding = self._pool_padding[1]\n right_padding = self._pool_padding[1]\n\n up_padding = self._pool_padding[0]\n down_padding = self._pool_padding[0]\n\n for i in range(height):\n matrix[i] += [0] * right_padding\n for j in range(left_padding):\n matrix[i].insert(0, 0)\n\n for _ in range(up_padding):\n matrix.insert(0, [0] * len(matrix[0]))\n\n for _ in range(down_padding):\n matrix.append([0] * len(matrix[0]))\n\n return matrix\n\n def max_pooling(self, matrix):\n matrix = self.add_auto_padding(matrix)\n matrix = self.add_padding(matrix)\n\n height = len(matrix)\n width = len(matrix[0])\n\n pooled = []\n\n for i in range(0, height - self._pool_size[0] + 1,\n self._pool_strides[0]):\n temp1 = []\n for j in range(0, width - self._pool_size[1] + 1,\n self._pool_strides[1]):\n max = matrix[i][j]\n for k in range(self._pool_size[0]):\n for l in range(self._pool_size[1]):\n if (matrix[i + k][j + l] > max):\n max = matrix[i + k][j + l]\n temp1.append(max)\n pooled.append(temp1)\n\n return pooled\n\n def average_pooling(self, matrix):\n\n matrix = self.add_auto_padding(matrix)\n matrix = self.add_padding(matrix)\n\n height = len(matrix)\n width = len(matrix[0])\n\n pooled = []\n\n for i in range(0, height - self._pool_size[0] + 1,\n self._pool_strides[0]):\n temp1 = []\n for j in range(0, width - self._pool_size[1] + 1,\n self._pool_strides[1]):\n sum = 0\n for k in range(self._pool_size[0]):\n for l in range(self._pool_size[1]):\n sum += matrix[i + k][j + l]\n temp1.append(sum / (self._pool_size[0] * self._pool_size[1]))\n pooled.append(temp1)\n\n return pooled\n\n def pooling(self, matrix):\n\n self.nets = matrix\n\n if (self._pool_mode == \"max\"):\n res = [self.max_pooling(matrix[i]) for i in range(len(matrix))]\n elif self._pool_mode == \"average\":\n res = [self.average_pooling(matrix[i]) for i in range(len(matrix))]\n else:\n raise Exception(\"Undefined pooling mode!\")\n\n self._neurons = res\n ","sub_path":"neuralnetwork/layers/pooling.py","file_name":"pooling.py","file_ext":"py","file_size_in_byte":8233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"558840681","text":"# Import useful libraries\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nfrom skimage.measure import compare_ssim as ssim\nimport matplotlib as mpl\nfrom mpl_toolkits import mplot3d\nimport csv\nimport os\nimport datetime\n\nstamp = datetime.datetime.now().microsecond # Stamp for figure title\n\nplt.close() # Close any previous matplotlib.pyplot windows\n\nn = 20\ns = n * 2 + 1 # Length of square sides\n\nsquarethickness = 3\n\n# Set up folder structure and read/write paths\ncwd = os.getcwd()\nscriptfolder = 'python_scripts'\nframefolder1 = 'frames'\nframefolder2 = 'clear_background'\nhomefolder = cwd[:-len(scriptfolder)]\nreadlocation = os.path.join(homefolder, framefolder1, framefolder2)\nreadlocation_input = homefolder\ninputfile = 'input.csv'\noutputfolder1 = 'output'\noutputfolder2 = 'figs'\nwritelocation = os.path.join(homefolder, outputfolder1, outputfolder2)\nwritelocation_output = os.path.join(homefolder, outputfolder1)\noutputfile = 'output.csv'\n\n# Define find element function for column\ndef findelements(inputlist, Duplicate=False):\n outputlist = []\n for element in inputlist:\n if element.startswith('#'):\n continue\n elif element == '':\n continue\n else:\n outputlist.append(element)\n if not Duplicate:\n if len(outputlist) == 1:\n return outputlist[0]\n else:\n print('Error: Elements in input column =/= 1')\n else:\n if len(outputlist) == 2:\n return outputlist\n elif len(outputlist) == 1:\n return outputlist[:1]\n else:\n print('Error: Elements in input column =/= 2 or 1')\n\n# Define find file name column function\ndef findfilelist(objecttype, distance):\n filelist = ''\n if objecttype == 'airplanes':\n if distance == 'close':\n filelist = row[4]\n else:\n filelist = row[5]\n elif objecttype == 'bats':\n if distance == 'close':\n filelist = row[6]\n else:\n filelist = row[7]\n elif objecttype == 'birds':\n if distance == 'close':\n filelist = row[8]\n else:\n filelist.append(row[9])\n elif objecttype == 'insects':\n if distance == 'close':\n filelist = row[10]\n return filelist\n\n# Set up empty lists to hold data from input file\nobjecttype1_ = []\nobjecttype2_ = []\ndistance1_ = []\ndistance2_ = []\nfilename1_ = []\nfilename2_ = []\nframe1_ = []\nframe2_ = []\n\n# Read object type, distance, and frame columns\nwith open(os.path.join(readlocation_input, inputfile), newline='') as csvfile:\n inputreader = csv.reader(csvfile)\n for row in inputreader:\n objecttype1_.append(row[0])\n distance1_.append(row[1])\n objecttype2_.append(row[2])\n distance2_.append(row[3])\n\n frame1_.append(row[11])\n frame2_.append(row[12])\n\n# Find object type, distance, and frame from columns\nobjecttype1 = findelements(objecttype1_)\nobjecttype2 = findelements(objecttype2_)\ndistance1 = findelements(distance1_)\ndistance2 = findelements(distance2_)\nframe1 = findelements(frame1_)\nframe2 = findelements(frame2_)\n\n# Read file name columns\nwith open(os.path.join(readlocation_input, inputfile), newline='') as csvfile:\n inputreader = csv.reader(csvfile)\n for row in inputreader:\n filename1_.append(findfilelist(objecttype1, distance1))\n filename2_.append(findfilelist(objecttype2, distance2))\n\n# Find file names from columns\nif filename1_ == filename2_:\n filenames_ = findelements(filename1_, Duplicate=True)\n if len(filenames_) == 2:\n filename1 = filenames_[0]\n filename2 = filenames_[1]\n else:\n filename1 = filenames_[0]\n filename2 = filenames_[0]\nelse:\n filename1 = findelements(filename1_)\n filename2 = findelements(filename2_)\n\n## Print results\n# print(objecttype1, distance1, filename1, frame1, objecttype2, distance2, filename2, frame2)\n\nextension = '.jpg'\n\n# Set up frame read paths\nreadpath1 = os.path.join(readlocation, objecttype1, distance1, filename1, 'frame%s%s' % (frame1, extension))\nreadpath2 = os.path.join(readlocation, objecttype2, distance2, filename2, 'frame%s%s' % (frame2, extension))\n\n# Set window names\nframeTitle1 = 'Video ' + filename1 + ', Frame ' + frame1\nwindow1Name = frameTitle1\nwindow2Name = frameTitle1 + ', Rotated'\nframeTitle2 = 'Video ' + filename2 + ', Frame ' + frame2\nwindow3Name = frameTitle2\nwindow4Name = frameTitle2 + ', Rotated'\n\n# Set up variables for click event 1\ndrawLine1 = False\nxi1, yi1 = 0, 0\nxf1, yf1 = 0, 0\n\n# Set up variables for click event 3\ndrawLine2 = False\nxi2, yi2 = 0, 0\nxf2, yf2 = 0, 0\n\nref_location1 = [] # Empty list to hold click locations on Frame 1\nref_location2 = [] # Empty list to hold click locations on Frame 2\n\n# Click event 1 - to find rotation angle\ndef click_event1(event, x, y, flags, param):\n global xi1, yi1, xf1, yf1, drawLine1\n if event == cv2.EVENT_LBUTTONDOWN:\n drawLine1 = True\n xi1, yi1 = x, y\n if event == cv2.EVENT_LBUTTONUP:\n if drawLine1:\n drawLine1 = False\n xf1, yf1 = x, y\n\n# Click event 2 - to find region of interest\ndef click_event2(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n ref_location1.append((x, y))\n\n# Click event 3 - to find rotation angle\ndef click_event3(event, x, y, flags, param):\n global xi2, yi2, xf2, yf2, drawLine2\n if event == cv2.EVENT_LBUTTONDOWN:\n drawLine2 = True\n xi2, yi2 = x, y\n if event == cv2.EVENT_LBUTTONUP:\n if drawLine2:\n drawLine2 = False\n xf2, yf2 = x, y\n\n# Click event 3 - to find region of interest\ndef click_event4(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n ref_location2.append((x, y))\n\n# Define angle finding function\ndef find_angle(xi, yi, xf, yf):\n if xi == xf:\n angle_deg = 90.0\n else:\n det = (yf - yi) / (xf - xi)\n angle_rad = np.arctan(det)\n angle_deg = angle_rad * (180 / np.pi)\n return angle_deg\n\n# Define image rotating function\ndef rotate(image_name, a_found, instance):\n global yi1, yf1, yi2, yf2\n\n if instance == 1:\n yi = yi1\n yf = yf1\n elif instance == 2:\n yi = yi2\n yf = yf2\n else:\n print('\\nError: Unexpected image rotation instance.\\n')\n \n Acute = True\n sign = 1.0\n\n rows, cols = image_name.shape[:2]\n \n a_rad = a_found * (np.pi / 180)\n rot_angle_rad = np.pi/2 + a_rad\n\n if yi < yf:\n Acute = False\n\n if a_found < 0:\n if not Acute:\n sign = -1.0\n rot_angle_rad = np.pi/2 - a_rad\n else:\n if Acute:\n sign = -1.0\n rot_angle_rad = np.pi/2 - a_rad\n \n if Acute:\n r = int(rows*np.cos(rot_angle_rad) + cols*np.sin(rot_angle_rad))\n c = int(cols*np.cos(rot_angle_rad) + rows*np.sin(rot_angle_rad))\n else:\n r = int(cols*np.cos(rot_angle_rad - np.pi/2) + rows*np.sin(rot_angle_rad - np.pi/2))\n c = int(rows*np.cos(rot_angle_rad - np.pi/2) + cols*np.sin(rot_angle_rad - np.pi/2))\n \n rot_angle_deg = rot_angle_rad * (180 / np.pi)\n\n M = cv2.getRotationMatrix2D((cols//2, rows//2), sign * rot_angle_deg, 1)\n M[0,2] += (c - cols) / 2\n M[1,2] += (r - rows) / 2\n \n return cv2.warpAffine(image_name, M, (c, r)), sign * rot_angle_deg\n\n# Define FFT function\ndef takedft(img_name):\n dft = cv2.dft(np.float32(img_name), flags = cv2.DFT_COMPLEX_OUTPUT)\n dft_shift = np.fft.fftshift(dft)\n magnitude_spectrum = np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))\n return dft, dft_shift, magnitude_spectrum\n\n# Show original frame 1\nimg1 = cv2.imread(readpath1)\ncv2.namedWindow(window1Name)\ncv2.setMouseCallback(window1Name, click_event1)\ncv2.imshow(window1Name, img1)\ncv2.waitKey(0) & 0xFF\n\n# Find rotation angle from clicked points\nfound_angle1 = find_angle(xi1, yi1, xf1, yf1)\n\n# print('\\nClick in the middle of the bat and press any key to progress. The region of interest coordinates will be saved as your last click.\\n')\n\n# Rotate frame 1 and show rotated version\nimg1_rotated = rotate(img1, found_angle1, 1)[0]\nimg1_rotangle = rotate(img1, found_angle1, 1)[1]\ncv2.namedWindow(window2Name)\ncv2.setMouseCallback(window2Name, click_event2)\ncv2.imshow(window2Name, img1_rotated)\ncv2.waitKey(0) & 0xFF\n\n# Coordinates of last clicked region\nroi1_x = ref_location1[-1][0]\nroi1_y = ref_location1[-1][1]\n\n# print('\\nPress any keys to progress.\\n')\n\n# Convert rotated frame 1 to grayscale and clone\nclone_img1_rotated_gray = cv2.cvtColor(img1_rotated, cv2.COLOR_BGR2GRAY)\nimg1_rotated_gray = cv2.cvtColor(img1_rotated, cv2.COLOR_BGR2GRAY)\n\n# Show grayscale rotated frame 1 with square\ncv2.rectangle(img1_rotated_gray, (roi1_x - n, roi1_y - n), (roi1_x + n, roi1_y + n), (0, 0, 0), squarethickness)\ncv2.imshow(window2Name, img1_rotated_gray)\ncv2.waitKey(0) & 0xFF\n\n# Crop frame 1 around last clicked location\nroi1 = clone_img1_rotated_gray[(roi1_y - n):(roi1_y + n + 1), (roi1_x - n):(roi1_x + n + 1)]\n\n# Read in original frame 2\nimg2 = cv2.imread(readpath2)\ncv2.namedWindow(window3Name)\ncv2.setMouseCallback(window3Name, click_event3)\ncv2.imshow(window3Name, img2)\ncv2.waitKey(0) & 0xFF\n\n# Find rotation angle from clicked points\nfound_angle2 = find_angle(xi2, yi2, xf2, yf2)\n\n# Rotate image and show rotated version\nimg2_rotated = rotate(img2, found_angle2, 2)[0]\nimg2_rotangle = rotate(img2, found_angle2, 2)[1]\ncv2.namedWindow(window4Name)\ncv2.setMouseCallback(window4Name, click_event4)\ncv2.imshow(window4Name, img2_rotated)\ncv2.waitKey(0) & 0xFF\n\n# print('\\nClick in the middle of the bat and press any key to progress. The region of interest coordinates will be saved as your last click.\\n')\n\n# Coordinates of last clicked region\nroi2_x = ref_location2[-1][0]\nroi2_y = ref_location2[-1][1]\n\n# print('\\nPress any keys to progress.\\n')\n\n# Convert rotated frame 2 to grayscale and clone\nclone_img2_rotated_gray = cv2.cvtColor(img2_rotated, cv2.COLOR_BGR2GRAY)\nimg2_rotated_gray = cv2.cvtColor(img2_rotated, cv2.COLOR_BGR2GRAY)\n\n# Show grayscale rotated frame 2 with square\ncv2.rectangle(img2_rotated_gray, (roi2_x - n, roi2_y - n), (roi2_x + n, roi2_y + n), (0, 0, 0), squarethickness)\ncv2.imshow(window4Name, img2_rotated_gray)\ncv2.waitKey(0) & 0xFF\n\n# Crop frame 2 around same location\nroi2 = clone_img2_rotated_gray[(roi2_y - n):(roi2_y + n + 1), (roi2_x - n):(roi2_x + n + 1)]\n\ncv2.destroyAllWindows()\n\n# Take FFT and extract magnitude spectrum of cropped images\ntakedft_roi1 = takedft(roi1)\nmag_spect_roi1 = takedft_roi1[2]\ntakedft_roi2 = takedft(roi2)\nmag_spect_roi2 = takedft_roi2[2]\n\n# Correlate FFTs\ncorrelation = signal.correlate2d(mag_spect_roi1, mag_spect_roi2, fillvalue=0)\n\n#Correlate FFTs to themselves and extract value results\nauto1 = signal.correlate2d(mag_spect_roi1, mag_spect_roi1, fillvalue=0)\nauto2 = signal.correlate2d(mag_spect_roi2, mag_spect_roi2, fillvalue=0)\n\nauto1_value = auto1[2*n][2*n]\nauto2_value = auto2[2*n][2*n]\n\n# Calculate SSIM of FFTs\navg_ssim, ssim_image = ssim(mag_spect_roi1, mag_spect_roi2, full=True)\n\n# Image similarity results (at center, where FFTs are aligned)\nssim_value = ssim_image[n][n]\nccorr_value = correlation[2*n][2*n]\n\n# Use template matching to find normalized cross-correlation\ntemplate_matched = cv2.matchTemplate(mag_spect_roi1, mag_spect_roi2, cv2.TM_CCORR_NORMED)\nnccorr_value = np.amax(template_matched)\n\n# Normalized correlation value (to average of auto-correlation values)\nccorr_value_handnorm = ccorr_value / ((auto1_value + auto2_value) / 2.0)\n\n## Show results\n\ntitlefontsize = 12\nsubtitlefontsize = 10\nfigrows = 3\nfigcolumns = 4\n\n# Set up grayscale normalization conditions\nNormalization1 = True\nNormalization2 = True\n\nif Normalization1:\n norm1 = mpl.colors.Normalize(vmin = 0, vmax = 255)\nelse:\n norm1 = None\n\nif Normalization2:\n plottop = 14.0\n norm2 = mpl.colors.Normalize(vmin = 0, vmax = plottop)\nelse:\n plottop = None\n norm2 = None\n\nplt.figure(1, figsize=(figcolumns*3, figrows*3))\nplt.suptitle('%s, Frame %s vs. %s, Frame %s\\n%s' % (filename1, frame1, filename2, frame2, stamp), fontsize = titlefontsize)\n\nplt.subplot(figrows, figcolumns, 1)\nplt.cla()\nplt.imshow(img1_rotated_gray, cmap='gray', norm=norm1)\nplt.title('%s, Frame %s' % (filename1, frame1), fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 2)\nplt.cla()\nplt.imshow(roi1, cmap='gray', norm=norm1)\nplt.title('ROI', fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 3)\nplt.cla()\nplt.imshow(mag_spect_roi1, cmap='gray', norm=norm2)\nplt.title('FFT of ROI', fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nax1 = plt.subplot(figrows, figcolumns, 4, projection='3d')\nplt.cla()\nX1, Y1 = np.meshgrid(range(s), range(s))\nZ1 = mag_spect_roi1\nmplot3d.Axes3D.plot_surface(ax1, X1, Y1, Z1, cmap='gray', norm=norm2)\nplt.title('FFT of ROI, 3D', fontsize = subtitlefontsize)\nmplot3d.Axes3D.set_zlim3d(ax1, bottom=0.0, top=plottop)\nmplot3d.Axes3D.set_zticks(ax1, [])\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 5)\nplt.cla()\nplt.imshow(img2_rotated_gray, cmap='gray', norm=norm1)\nplt.title('%s, Frame %s' % (filename2, frame2), fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 6)\nplt.cla()\nplt.imshow(roi2, cmap='gray', norm=norm1)\nplt.title('ROI', fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 7)\nplt.cla()\nplt.imshow(mag_spect_roi2, cmap='gray', norm=norm2)\nplt.title('FFT of ROI', fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nax2 = plt.subplot(figrows, figcolumns, 8, projection='3d')\nplt.cla()\nX2, Y2 = np.meshgrid(range(s), range(s))\nZ2 = mag_spect_roi2\nmplot3d.Axes3D.plot_surface(ax2, X2, Y2, Z2, cmap='gray', norm=norm2)\nplt.title('FFT of ROI, 3D', fontsize = subtitlefontsize)\nmplot3d.Axes3D.set_zlim3d(ax2, bottom=0.0, top=plottop)\nmplot3d.Axes3D.set_zticks(ax2, [])\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 9)\nplt.cla()\nplt.imshow(correlation, cmap='gray')\nplt.title('Correlation Image of FFTs', fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 10)\nplt.cla()\nplt.text(0.05, 0.75, 'Correlation = %s' % round(ccorr_value, 4))\nplt.text(0.05, 0.5, 'Hand-Normalized = %s' % round(ccorr_value_handnorm, 4))\nplt.text(0.05, 0.25, 'Normalized = %s' % round(nccorr_value, 4))\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 11)\nplt.cla()\nplt.imshow(ssim_image, cmap='gray')\nplt.title('SSIM Image of FFTs', fontsize = subtitlefontsize)\nplt.xticks([])\nplt.yticks([])\n\nplt.subplot(figrows, figcolumns, 12)\nplt.cla()\nplt.text(0.25, 0.5, 'SSIM = %s' % round(ssim_value, 4))\nplt.xticks([])\nplt.yticks([])\n\nplt.show()\n\n# Create output figure title\nfigextension = '.jpg'\nfigtitle = '%s_%s_%s_%s_%s%s' % (filename1, frame1, filename2, frame2, stamp, figextension)\n\nWriteFile = True\n\n## Write results to csv output file\nif WriteFile:\n with open(os.path.join(writelocation_output, outputfile), mode='a', newline='') as csvfile:\n outputwriter = csv.writer(csvfile)\n outputwriter.writerow([figtitle, '', objecttype1, distance1, filename1, frame1,\n objecttype2, distance2, filename2, frame2, '',\n ccorr_value, ccorr_value_handnorm, nccorr_value, ssim_value, '',\n img1_rotangle, roi1_x, roi1_y, img2_rotangle, roi2_x, roi2_y])\n plt.savefig(os.path.join(writelocation, figtitle))\n print (figtitle)\nelse:\n print ('Figure not saved')\n\nprint ('Done')","sub_path":"python_scripts/practice/compare_two_ffts.py","file_name":"compare_two_ffts.py","file_ext":"py","file_size_in_byte":16609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"580606250","text":"class Date:\n\n def __init__(self,day=0, month=0, year=0):\n self.day=day\n self.month = month\n self.year = year\n\n @classmethod\n def from_string(cls, date_as_string):\n day, month, year = map(int,date_as_string.split('-'))\n my_date = cls(day, month, year)\n return my_date\n\n @staticmethod\n def is_date_valid(date_as_string):\n day, month, year = map(int, date_as_string.split('-'))\n return day <= 31 and month <= 12 and year <= 3999\n\n\nif __name__ == '__main__':\n my_date = Date.from_string('11-09-2012')\n print(my_date.day, my_date.month,my_date.year)\n is_date = Date.is_date_valid('13-13-2012')\n print(is_date)\n","sub_path":"PythonProjects/教程练习/静态函数,类函数,成员函数.py","file_name":"静态函数,类函数,成员函数.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"297067246","text":"# Copyright (c) 2015 App Annie Inc. All rights reserved.\n\nfrom tests.qa.cases.intelligence.usage.utility import UsageEstimationMixin\nfrom tests.qa.constants.constants import UsageKpiType, Devices\nfrom tests.qa.constants.usage_constants import USAGE_API_MARKETS\nfrom tests.qa.services.intelligence.usage.android import UsageAndroidService\nfrom tests.qa.services.intelligence.usage.ios import UsageIOSService\n\n\nclass UsageAPIMixin(UsageEstimationMixin):\n\n ANDROID_KPI_TYPES = [\n UsageKpiType.USAGE_PENETRATION,\n UsageKpiType.ACTIVE_USER,\n UsageKpiType.SESSION_PER_USER,\n UsageKpiType.SESSION_DURATION,\n UsageKpiType.AVG_TIME_PER_USER,\n UsageKpiType.AVG_ACTIVE_DAYS,\n UsageKpiType.PERCENTAGE_ACTIVE_DAYS,\n UsageKpiType.SHARE_CATEGORY_TIME,\n UsageKpiType.AVG_MB_PER_USER,\n UsageKpiType.AVG_MB_PER_SESSION,\n UsageKpiType.SHARE_CATEGORY_SESSION,\n UsageKpiType.SHARE_CATEGORY_MB,\n UsageKpiType.PERCENTAGE_MB_WIFI,\n UsageKpiType.INSTALL_PENETRATION,\n UsageKpiType.OPEN_RATE,\n UsageKpiType.TOTAL_TIME,\n ]\n\n IOS_US_KPI_TYPES = [\n UsageKpiType.ACTIVE_USER,\n UsageKpiType.SESSION_PER_USER,\n UsageKpiType.SESSION_DURATION,\n UsageKpiType.AVG_TIME_PER_USER,\n UsageKpiType.TOTAL_TIME,\n UsageKpiType.USAGE_PENETRATION,\n UsageKpiType.TOTAL_SESSION,\n UsageKpiType.INSTALL_PENETRATION,\n UsageKpiType.OPEN_RATE,\n ]\n\n @staticmethod\n def get_api_market_from_device(device):\n return {\n Devices.IPHONE: USAGE_API_MARKETS[0],\n Devices.IPAD: USAGE_API_MARKETS[0],\n Devices.IOS: USAGE_API_MARKETS[0],\n\n Devices.ANDROID: USAGE_API_MARKETS[1],\n Devices.ANDROID_PHONE: USAGE_API_MARKETS[1],\n Devices.ANDROID_TABLET: USAGE_API_MARKETS[1],\n }.get(device, device)\n\n def get_usage_service(self, device):\n return {\n USAGE_API_MARKETS[0]: UsageIOSService,\n USAGE_API_MARKETS[1]: UsageAndroidService,\n }[self.get_api_market_from_device(device)]\n\n def get_selected_app(self, device):\n return {\n USAGE_API_MARKETS[0]: 284882215, # Facebook\n USAGE_API_MARKETS[1]: 20600003083946, # Boom Beach\n }[self.get_api_market_from_device(device)]\n\n @staticmethod\n def is_percentage_kpi_type(kpi_type):\n return kpi_type in [\n UsageKpiType.INSTALL_PENETRATION,\n UsageKpiType.OPEN_RATE,\n UsageKpiType.USAGE_PENETRATION,\n UsageKpiType.PERCENTAGE_ACTIVE_DAYS,\n UsageKpiType.SHARE_CATEGORY_TIME,\n ]\n\n def format_api_percentage_change(self, raw_percentage, kpi_type):\n if self.is_percentage_kpi_type(kpi_type):\n return round(float(raw_percentage), 2) if raw_percentage != 'n/a' else None\n else:\n return int(round(float(raw_percentage))) if raw_percentage != 'n/a' else None\n","sub_path":"tests/qa/cases/intelligence/api/usage/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"350945389","text":"import argparse\nimport os\nimport json\nimport numpy as np\nfrom tqdm import tqdm\nimport torch\nfrom torch.optim import SGD\nimport torch.utils.data\nimport torchvision.transforms as T\nimport torchvision.datasets as datasets\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport torch.nn.functional as F\nimport torchnet as tnt\nfrom torchnet.engine import Engine\nimport sys\nsys.path.insert(0, '../')\nfrom torch.backends import cudnn\ncudnn.benchmark = True\nimport utils\nfrom nested_dict import nested_dict\n\n# Model options\nparser = argparse.ArgumentParser(description='Wide Residual Networks')\nparser.add_argument('--model', default='model_resnet', type=str)\nparser.add_argument('--depth', default=16, type=int)\nparser.add_argument('--width', default=8, type=float)\nparser.add_argument('--dropout', default=0.3, type=float)\nparser.add_argument('--level', default=None, type=int)\nparser.add_argument('--dataset', default='STL10', type=str)\nparser.add_argument('--dataroot', default='data/stl/', type=str)\nparser.add_argument('--fold', default=-1, type=int)\nparser.add_argument('--dtype', default='float', type=str)\nparser.add_argument('--groups', default=1, type=int)\nparser.add_argument('--nthread', default=1, type=int)\nparser.add_argument('--seed', default=1, type=int)\n\n# Training options\nparser.add_argument('--batch_size', default=32, type=int)\nparser.add_argument('--lr', default=0.1, type=float)\nparser.add_argument('--epochs', default=1000, type=int, metavar='N')\nparser.add_argument('--weight_decay', default=0.0005, type=float)\nparser.add_argument('--nesterov', action='store_true', default=False)\nparser.add_argument('--epoch_step', default='[300,400,600,800]', type=str,\n help='json list with epochs to drop lr on')\nparser.add_argument('--lr_decay_ratio', default=0.2, type=float)\nparser.add_argument('--resume', default='', type=str)\nparser.add_argument('--note', default='', type=str)\n\n# Device options\nparser.add_argument('--cuda', action='store_true')\nparser.add_argument('--save', default='model&log', type=str, help='save model and logs in this folder')\nparser.add_argument('--ngpu', default=1, type=int, help='no of GPUs to use for training')\nparser.add_argument('--gpu_id', default='0', type=str, help='CUDA_VISIBLE_DEVICES ids')\n\n\ndef cast(params, dtype='float'):\n if isinstance(params, dict):\n return {i: cast(j, dtype) for i,j in params.items()}\n else:\n return getattr(params.cuda() if torch.cuda.is_available() else params, dtype)()\n \ndef flatten(params):\n return {'.'.join(i): j for i, j in nested_dict(params).items_flat() if j is not None}\n \ndef tensor_dict_print(params):\n kmax = max(len(key) for key in params.keys())\n for i, (key, v) in enumerate(params.items()):\n print(str(i).ljust(5), key.ljust(kmax + 3), str(tuple(v.shape)).ljust(23), torch.typename(v), v.requires_grad)\n \ndef download_data(opt, train):\n transform = T.Compose([\n T.ToTensor(),\n T.Normalize(np.array([125.3, 123.0, 113.9]) / 255.0,\n np.array([63.0, 62.1, 66.7]) / 255.0)\n ])\n if train:\n transform = T.Compose([\n T.Pad(12, padding_mode='reflect'),\n T.RandomHorizontalFlip(),\n T.RandomCrop(96),\n transform\n ])\n return datasets.STL10(opt.dataroot, split=\"train\" if train else \"test\", download=True, transform=transform)\n\ndef model_resnet(depth, width, num_classes, dropout, level=None):\n assert (depth - 4) % 6 == 0, 'depth should be 6n+4'\n assert level is None or level in [2, 3], 'level should be 2, 3 or None'\n n = (depth - 4) // 6\n widths = [int(v * width) for v in (16, 32, 64)]\n\n def gen_harmonic_params(ni, no, k, normalize=False, level=None, linear=False):\n nf = k**2 if level is None else level * (level+1) // 2\n paramdict = {'conv': utils.dct_params(ni, no, nf) if linear else utils.conv_params(ni*nf, no, 1)}\n if normalize and not linear:\n paramdict.update({'bn': utils.bnparams(ni*nf, affine=False)})\n return paramdict\n\n def gen_block_params(ni, no):\n return {\n 'harmonic0': gen_harmonic_params(ni, no, k=3, normalize=False, level=level, linear=True),\n 'harmonic1': gen_harmonic_params(no, no, k=3, normalize=False, level=level, linear=True),\n 'bn0': utils.bnparams(ni),\n 'bn1': utils.bnparams(no),\n 'convdim': utils.conv_params(ni, no, 1) if ni != no else None,\n }\n\n def gen_group_params(ni, no, count):\n return {'block%d' % i: gen_block_params(ni if i == 0 else no, no)\n for i in range(count)}\n\n flat_params = cast(flatten({\n 'dct0': utils.dct_filters(n=3, groups=3),\n 'dct': utils.dct_filters(n=3, groups=int(width)*64, expand_dim=0, level=level),\n 'harmonic0': gen_harmonic_params(3, 16, k=3, normalize=True, level=None),\n 'group0': gen_group_params(16, widths[0], n),\n 'group1': gen_group_params(widths[0], widths[1], n),\n 'group2': gen_group_params(widths[1], widths[2], n),\n 'bn': utils.bnparams(widths[2]),\n 'fc': utils.linear_params(widths[2], num_classes),\n }))\n\n utils.set_requires_grad_except_bn_(flat_params)\n\n def harmonic_block(x, params, base, mode, stride=1, padding=1):\n y = F.conv2d(x, params['dct0'], stride=stride, padding=padding, groups=x.size(1))\n if base + '.bn.running_mean' in params:\n y = utils.batch_norm(y, params, base + '.bn', mode, affine=False)\n z = F.conv2d(y, params[base + '.conv'], padding=0)\n return z\n\n def lin_harmonic_block(x, params, base, mode, stride=1, padding=1):\n filt = torch.sum(params[base + '.conv'] * params['dct'][:x.size(1), ...], dim=2)\n y = F.conv2d(x, filt, stride=stride, padding=padding)\n return y\n\n def block(x, params, base, mode, stride):\n o1 = F.relu(utils.batch_norm(x, params, base + '.bn0', mode), inplace=True)\n y = lin_harmonic_block(o1, params, base + '.harmonic0', mode, stride=stride, padding=1)\n o2 = F.relu(utils.batch_norm(y, params, base + '.bn1', mode), inplace=True)\n if dropout > 0:\n o2 = F.dropout(o2, p=dropout, training=mode, inplace=False)\n z = lin_harmonic_block(o2, params, base + '.harmonic1', mode, stride=1, padding=1)\n if base + '.convdim' in params:\n return z + F.conv2d(o1, params[base + '.convdim'], stride=stride)\n else:\n return z + x\n\n def group(o, params, base, mode, stride):\n for i in range(n):\n o = block(o, params, '%s.block%d' % (base,i), mode, stride if i == 0 else 1)\n return o\n\n def f(input, params, mode):\n x = harmonic_block(input, params, 'harmonic0', mode, stride=2, padding=1)\n g0 = group(x, params, 'group0', mode, 1)\n g1 = group(g0, params, 'group1', mode, 2)\n g2 = group(g1, params, 'group2', mode, 2)\n o = F.relu(utils.batch_norm(g2, params, 'bn', mode))\n o = F.avg_pool2d(o, 12, 1, 0)\n o = o.view(o.size(0), -1)\n o = F.linear(o, params['fc.weight'], params['fc.bias'])\n return o\n\n return f, flat_params\n \ndef main():\n opt = parser.parse_args()\n print('parsed options:', vars(opt))\n epoch_step = json.loads(opt.epoch_step)\n log_step = 5\n if opt.fold >= 0 and opt.fold <= 9:\n log_step *= 5\n epoch_step = [ep*5 for ep in epoch_step]\n opt.epochs *= 5\n \n num_classes = 10\n\n torch.manual_seed(opt.seed)\n os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu_id\n\n def create_iterator(mode):\n if opt.fold < 0 or opt.fold > 9:\n return DataLoader(download_data(opt, mode), opt.batch_size, shuffle=mode,\n num_workers=opt.nthread, pin_memory=torch.cuda.is_available())\n if mode:\n folds = np.loadtxt('fold_indices.txt', dtype=np.int64)\n fold = folds[opt.fold]\n fold = torch.from_numpy(fold)\n return DataLoader(download_data(opt, mode), opt.batch_size, sampler=SubsetRandomSampler(fold) if mode else None,\n num_workers=opt.nthread, pin_memory=torch.cuda.is_available())\n\n train_loader = create_iterator(True)\n test_loader = create_iterator(False)\n\n kwargs = {}\n if not opt.level is None:\n kwargs.update({'level': opt.level})\n f, params = model_resnet(opt.depth, opt.width, num_classes, opt.dropout, **kwargs)\n def create_optimizer(opt, lr):\n print('creating optimizer with lr = ', lr)\n return SGD([v for v in params.values() if v.requires_grad], lr, momentum=0.9, weight_decay=opt.weight_decay, nesterov=opt.nesterov)\n\n optimizer = create_optimizer(opt, opt.lr)\n\n epoch = 0\n if opt.resume != '':\n state_dict = torch.load(opt.resume)\n epoch = state_dict['epoch']\n params_tensors = state_dict['params']\n for k, v in params.items():\n if k in params_tensors:\n v.data.copy_(params_tensors[k])\n optimizer.load_state_dict(state_dict['optimizer'])\n\n print('\\nParameters:')\n tensor_dict_print(params)\n\n n_parameters = sum(p.numel() for p in params.values() if p.requires_grad)\n print('\\nTotal number of parameters:', n_parameters)\n\n meter_loss = tnt.meter.AverageValueMeter()\n classacc = tnt.meter.ClassErrorMeter(accuracy=True)\n timer_train = tnt.meter.TimeMeter('s')\n timer_test = tnt.meter.TimeMeter('s')\n\n if not os.path.exists(opt.save):\n os.mkdir(opt.save)\n\n def h(sample):\n inputs = cast(sample[0], opt.dtype)\n targets = cast(sample[1], 'long')\n y = utils.data_parallel(f, inputs, params, sample[2], list(range(opt.ngpu))).float()\n return F.cross_entropy(y, targets), y\n\n def log(t, state):\n torch.save(dict(params={k: v for k, v in params.items() if k.find('dct') == -1}, epoch=t['epoch'], \n optimizer=state['optimizer'].state_dict()), os.path.join(opt.save, 'model.pt7'))\n z = vars(opt).copy()\n z.update(t)\n with open(os.path.join(opt.save, 'log.txt'), 'a') as flog:\n flog.write('json_stats: ' + json.dumps(z) + '\\n')\n print(z)\n\n def on_sample(state):\n state['sample'].append(state['train'])\n\n def on_forward(state):\n loss = float(state['loss'])\n classacc.add(state['output'].data, state['sample'][1])\n meter_loss.add(loss)\n if state['train']:\n state['iterator'].set_postfix(loss=loss)\n\n def on_start(state):\n state['epoch'] = epoch\n\n def on_start_epoch(state):\n classacc.reset()\n meter_loss.reset()\n timer_train.reset()\n state['iterator'] = tqdm(train_loader, dynamic_ncols=True)\n epoch = state['epoch'] + 1\n if epoch in epoch_step:\n lr = state['optimizer'].param_groups[0]['lr']\n state['optimizer'] = create_optimizer(opt, lr * opt.lr_decay_ratio)\n\n def on_end_epoch(state):\n if state['epoch'] % log_step == 0:\n train_loss = meter_loss.value()\n train_acc = classacc.value()\n train_time = timer_train.value()\n meter_loss.reset()\n classacc.reset()\n timer_test.reset()\n\n with torch.no_grad():\n engine.test(h, test_loader)\n\n test_acc = classacc.value()[0]\n print(log({\n \"train_loss\": train_loss[0],\n \"train_acc\": train_acc[0],\n \"test_loss\": meter_loss.value()[0],\n \"test_acc\": test_acc,\n \"epoch\": state['epoch'],\n \"train_time\": train_time,\n \"test_time\": timer_test.value(),\n }, state))\n print('==> id: %s (%d/%d), test_acc: \\33[91m%.2f\\033[0m' %\n (opt.save, state['epoch'], opt.epochs, test_acc))\n\n engine = Engine()\n engine.hooks['on_sample'] = on_sample\n engine.hooks['on_forward'] = on_forward\n engine.hooks['on_start_epoch'] = on_start_epoch\n engine.hooks['on_end_epoch'] = on_end_epoch\n engine.hooks['on_start'] = on_start\n engine.train(h, train_loader, opt.epochs, optimizer)\n\n\nif __name__ == '__main__':\n main()","sub_path":"Harmonic_Network/Model_Stl_final.py","file_name":"Model_Stl_final.py","file_ext":"py","file_size_in_byte":12233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"443302765","text":"from django.urls import path\n\nfrom .views import index, by_rubric, BbCreateView, BbDetailView, BbEditView, BbDeleteView\n#app_name = 'bboard'\nurlpatterns = [\n path('/', by_rubric, name='by_rubric'),\n path('add/', BbCreateView.as_view(), name='add'),\n path('detail//', BbDetailView.as_view(), name = 'detail'),\n path('izmenit//', BbEditView.as_view(), name = 'update'),\n path('udalit//', BbDeleteView.as_view(), name = 'ddd'),\n path('', index, name='index'),\n]\n","sub_path":"bboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"221011883","text":"import numpy as np\nfrom scipy import signal as sig\nfrom timeit import default_timer as timer\nimport time\n\n\nclass _SimCtx():\n def __init__(self):\n self.name = \"Sim\"\n\n\nFLOAT = np.float64\nCOMPLEX = np.complex128\n\n\nclass SimPlutoSdr():\n def __init__(self, P, alpha, desiredBandwidth):\n self.ctx = _SimCtx()\n\n # RX Information\n self.sampling_frequency = P * desiredBandwidth / (1 + alpha)\n self.rx_lo_freq = 2400.0\n self.rx_bandwidth = 20.0\n self.rx_decimation = 0.0\n self.rx_gain = 10.0\n\n # TX Information\n self.tx_lo_freq = 2400.0\n self.tx_bandwidth = 20.0\n self.tx_interpolation = 0.0\n self.tx_gain = -10.0\n\n # Simulate Buffer\n self._buffer = np.zeros(2**18)\n # Timer used to simulate sampling frequency\n self._lastRead = 0\n self.no_bits = 12\n\n def raw2complex(self, data):\n \"\"\"return a scaled complex float version of the raw data\"\"\"\n # convert to float64, view performs an in place recast of the data\n # from SO 5658047\n # are the #bits available from some debug attr?\n # scale for 11 bits (signed 12)\n iq = 2**-(self.no_bits - 1) * data.astype(FLOAT)\n return iq.view(COMPLEX)\n\n def complex2raw(self, data, no_bits):\n iq = np.round((2**(no_bits - 1)) * data.view(FLOAT)).astype(np.int16)\n return iq\n\n def writeTx(self, data, raw=False):\n rawData = np.array([])\n if len(data) > 0:\n maxBeforeClipping = 15\n dataMax = data.max()\n while np.abs(2**maxBeforeClipping * dataMax > 2**14):\n maxBeforeClipping -= 1\n \n rawData = self.complex2raw(data, maxBeforeClipping + 1) if not raw else data\n # Simulated Channel\n t0 = 0 # channel delay\n A = 2**self.no_bits # channel gain\n h = A * np.append(np.zeros(t0, dtype=int), [1])\n\n r = sig.convolve(data, h)\n r = r + 0.4 * np.random.randn(len(r)) # add in noise\n # makes tx cyclical til buffer max size\n repeats = 1.0 * len(self._buffer) / len(r)\n r = np.tile(r, int(np.ceil(repeats)))\n self._buffer = r[0:len(self._buffer)]\n else:\n r = np.zeros(len(self._buffer))\n self._buffer = r[0:len(self._buffer)]\n\n return len(data), rawData\n\n def readRx(self, num_samples, raw=False):\n a = np.zeros(num_samples, complex)\n if num_samples > len(self._buffer):\n a[0:len(self._buffer)] = self._buffer\n else:\n a = self._buffer[0:num_samples]\n\n lastRead = self._lastRead\n self._lastRead = timer()\n\n # simulate the remaining time required\n # to collect the requested samples\n timeForSamples = (num_samples / self.sampling_frequency / 1e6)\n if self._lastRead - lastRead < timeForSamples:\n time.sleep(timeForSamples - (self._lastRead - lastRead))\n\n return a / (2**self.no_bits - 1)","sub_path":"gui/plutoDevice/SimPlutoSdr.py","file_name":"SimPlutoSdr.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"545837698","text":"#!/usr/bin/env python3\n\nimport numpy.random as random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef markov_pi(N, delta): \n x, y = 1.0, 1.0\n n_hits = 0\n for i in range(N):\n del_x, del_y = random.uniform(-delta, delta), random.uniform(-delta, delta)\n if abs(x + del_x) < 1.0 and abs(y + del_y) < 1.0:\n x, y = x + del_x, y + del_y\n if (x**2 + y**2) < 1.0:\n n_hits += 1\n return n_hits\n\nn_runs = 500\n\nsigmasqs = []\nn_trials_list = []\ndeltas = np.array([0.062, 0.125, 0.25, 1., 2., 4.])\npi_est = 0.0\n\nfigure = 1\n\nfor delta in deltas:\n for poweroftwo in range(4, 13):\n n_trials = 2**poweroftwo\n sigmasq = 0.0\n for run in range(n_runs):\n pi_est = 4.0*markov_pi(n_trials, delta)/float(n_trials)\n sigmasq += (pi_est - np.pi)**2\n sigmasqs.append(np.sqrt(sigmasq/n_runs))\n n_trials_list.append(n_trials)\n plt.figure(num=figure, figsize=[15, 10], dpi=450)\n plt.subplot(121)\n plt.plot(n_trials_list, sigmasqs, 'o')\n plt.xscale('log')\n plt.yscale('log')\n plt.xlabel('Number of trials')\n plt.ylabel('root mean square deviation')\n plt.grid(True)\n plt.title(\"Markov Multirun of pi: root mean square with delta = {0}\".format(delta))\n \n plt.subplot(122)\n plt.plot(n_trials_list, [1.642/np.sqrt(x) for x in n_trials_list], 'x')\n plt.xscale('log')\n plt.yscale('log')\n plt.xlabel('Number of trials')\n plt.ylabel(r'$\\frac{1.642}{\\sqrt{N_{trials}}}$')\n plt.grid(True)\n plt.title(r'$\\frac{1.642}{\\sqrt{N_{trials}}}$')\n\n plt.savefig(\"markov_rms_deviation{0}.png\".format(figure))\n plt.close()\n\n figure += 1\n \n n_trials_list = []\n sigmasqs = []\n","sub_path":"Tarea1/Markov Pi Multirun/markov_pi_multirun.py","file_name":"markov_pi_multirun.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"361065316","text":"#!/usr/bin/python3\nn, m = map(int, input().split())\na = [ list(map(int, input().split())) for _ in range(n) ]\nfor row in a :\n print(''.join(list(map(lambda x : '.#'[x > 0], row))))\n\nmw = max(map(max, a))\nassert mw > 0\nprint('')\n\nmat = [[' '] * m for _ in range(mw)]\nfor i in range(m) :\n mv = 0\n for j in range(n) :\n mv = max(mv, a[j][i])\n for j in range(mw) :\n mat[j][i] = '.#'[j < mv]\nfor row in reversed(mat) :\n print(''.join(row))\n\nprint('')\n\nmat = [[' '] * n for _ in range(mw)]\nfor i in range(n) :\n mv = 0\n for j in range(m) :\n mv = max(mv, a[i][j])\n for j in range(mw) :\n mat[j][i] = '.#'[j < mv]\nfor row in reversed(mat) :\n print(''.join(row))\n\n","sub_path":"view/src/std-py3.py","file_name":"std-py3.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"24599756","text":"import networkx as nx\nimport pandas as pd\nfrom pymongo import MongoClient\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nimport numpy as np\nimport math\nfrom matplotlib import pyplot as plt\nimport sys\nsys.path.append('..')\nsys.path.append('/usr/lib/graphviz/python/')\nsys.path.append('/usr/lib64/graphviz/python/')\n\nclass ingredienteCategoria:\n def __init__(self, ingrediente, category):\n self.nome = ingrediente\n self.dicCategoria = category\n\n def setIngredient(self, ingrediente):\n self.nome = ingrediente\n\n def setCategoria(self, dic):\n self.dicCategoria = dic\n\n def getIngrediente(self):\n return self.nome\n\n def getCategoria(self):\n return self.dicCategoria\n\ndef calculaScore(dataframeIN, i):\n\n score1 = math.log(float(dataframeIN.loc[i, \"numberOfEvaluations\"]) + 1.0, 10)\n\n if (type(dataframeIN.loc[i, \"peopleWhoMade\"]) != int):\n score2 = (math.log(1.0, 10))\n else:\n score2 = (math.log(float(dataframeIN.loc[i, \"peopleWhoMade\"]) + 1.0, 10))\n\n score3 = ((float(dataframeIN.loc[i, \"numberOfStars\"])) + 1.0) * (\n (float(dataframeIN.loc[i, \"numberOfStars\"])) + 1.0)\n score = (score3 + (score2 + score1))\n print(\"Score: \"+ str(score))\n\n return score\n\ndef filtraIngredientes(ingredients,stopWords):\n wordsFiltered = []\n for sent in sent_tokenize(str(ingredients)):\n words = word_tokenize(sent)\n filtered_sentence = [w for w in words if not w in stopWords]\n\n for i in range(len(filtered_sentence)):\n if len(filtered_sentence[i]) > 3 or filtered_sentence[i] == \"rum\" or filtered_sentence[i] == \"sal\":\n filtered_sentence[i].replace(filtered_sentence[i], \"\").replace(\"\\'\", \"\")\n wordsFiltered.append(filtered_sentence[i])\n return wordsFiltered\n\ndef criaListaCategorias(ingrediente, category, listaCategoria):\n dicionario = dict(listaCategoria)\n novoIngrediente = ingredienteCategoria(ingrediente, category)\n dicionario = novoIngrediente.getCategoria()\n dicionario[category] = dicionario[category] + 1\n novoIngrediente.setCategoria(dicionario)\n\ndef criaListaIngredientes(listIngredients, dicFinalIngredients, id):\n for i in range(len(listIngredients)):\n ingrediente = listIngredients[i].replace(\"Á\", \"á\").replace(\"A\", \"a\").replace(\"B\", \"b\").\\\n replace(\"C\", \"c\").replace(\"F\", \"f\").replace(\"M\", \"m\").replace(\"N\", \"n\").replace(\"O\", \"o\").\\\n replace(\"Ó\", \"ó\").replace(\"P\", \"p\").replace(\"Q\", \"q\").replace(\"R\", \"r\").replace(\"S\", \"s\").replace(\"V\", \"v\").\\\n replace(\"'s\", \"s\").replace(\"cloves\", \"clove\").replace(\"peppers\", \"pepper\").replace(\"olives\", \"olive\").\\\n replace(\"tomatoes\", \"tomato\"). replace(\"'Water\", \"water\")\n\n if ingrediente not in dicFinalIngredients:\n receitas = []\n receitas.append(id)\n dicFinalIngredients[ingrediente] = receitas\n else:\n receitas = dicFinalIngredients[ingrediente]\n receitas.append(id)\n dicFinalIngredients[ingrediente] = receitas\n\ndef criaNos(grafoUSA, dicFinalIngredients):\n indice = 0\n for i in dicFinalIngredients:\n if(len(dicFinalIngredients[i]) > 11):\n grafoUSA.add_node(indice, ingredient=i, qtdadeReceitas=len(dicFinalIngredients[i]))\n indice = indice +1\n\n print(\"NUMERO DE NÓS: \" + str(indice))\n return len(grafoUSA)\n\n# Calcula a quantidade, não é qualitativo!\ndef calculaReceitasComuns(ingre1, ingre2, dicFinal):\n qtdade = 0\n list1Ingre1 = dicFinal[ingre1]\n list1Ingre2 = dicFinal[ingre2]\n for m in list1Ingre1:\n for n in list1Ingre2:\n if m == n:\n qtdade = qtdade + 1\n return qtdade\n\ndef criaLinks(grafoUSA, tam ,dicFinal):\n count = 0\n for m in range(0, tam):\n for j in range(0, tam):\n if(grafoUSA.nodes[m]['ingredient'] != grafoUSA.nodes[j]['ingredient'] and grafoUSA.has_edge(m,j) == False):\n pA = int(grafoUSA.nodes[m]['qtdadeReceitas'])/7794\n pB = int(grafoUSA.nodes[j]['qtdadeReceitas'])/7794\n pAB = (calculaReceitasComuns(grafoUSA.nodes[m]['ingredient'], grafoUSA.nodes[j]['ingredient'], dicFinal))/7794\n if pB != 0 and pA != 0 and pAB != 0:\n PMI = math.log(pAB/(pA*pB))\n if PMI >= 0.0:\n grafoUSA.add_edge(m, j, weight=PMI)\n count = count + 1\n print(str(PMI))\n\n print(\"NUMERO DE ARESTAS: \" + str(count))\n #return pmiList\n\ndef salvaGrafo(grafoUSA):\n nx.drawing.nx_pydot.write_dot(grafoUSA, \"grafoINDIA-BAIXO.dot\")\n #nx.write_gml(grafoUSA, \"grafoUSA.gml\")\n\ndef criaHistograma(pmiList):\n data = pmiList\n\n bins = np.linspace(math.ceil(min(data)),\n math.floor(max(data)),\n 20) # fixed number of bins\n\n plt.xlim([min(data) - 5, max(data) + 5])\n\n plt.hist(data, bins=bins, alpha=0.5)\n plt.title('PMI distribution')\n plt.xlabel('variable X (20 evenly spaced bins)')\n plt.ylabel('count')\n\n plt.show()\n\ndef calculaCentralidade(grafoUSA):\n dicCentralidade = nx.algorithms.centrality.degree_centrality(grafoUSA)\n for item in dicCentralidade:\n print(dicCentralidade[item])\n\n return dicCentralidade\n\ndef defineTops(dicionario):\n top50 = open(\"top100-INDIA-alto.txt\", \"a\")\n top = 0\n for item in sorted(dicionario, key=dicionario.get, reverse=True):\n if(top < 150):\n top = top + 1\n print(grafoUSA.nodes[item]['ingredient'])\n top50.write(str(grafoUSA.nodes[item]['ingredient']) + \": \" + str(dicionario[item]) + \"\\n\")\n\n# \"main\" a partir daqui\nclient = MongoClient()\ndb = client['AllrecipesDB']\ndataframeIN = pd.DataFrame(list(db.recipesFormated.find({\"id\": \"5\"}))) #pega somente os dados dos USA\ngrafoUSA = nx.Graph()\nstopWords = set(stopwords.words('english'))\n\nstopWords.update([\"'xc2xbd\",\"tbsp\",\"'75g\",\"spoon\",\"pinch\", \"juice\", \"gravy\", \"chopped\", \"2\", \"2\" \"cups\", \"soup\", \"can\",\n \"box\", \"box\", \"tea\", \"'50g\", \"'250ml\", \"'225ml\",\n \"teeth\", \"taste\", \"wine\", \" 2, 2, 3, 4, 5, 6, cream, kingdom, ml, kg, g, tooth, / 2 \",\" 2/3 \",\" 1/4 \",\n \"Gems\",\"Fresh\",\"Extract\",\"Ready\",\"Strong\",\"Environment \",\"Temperature\",\"Biscuit\", \"package\",\n \"flavor\", \"any\", \"boiling\", \"melted\", \"cans\", \"200g\", \"juice\", \"rasps\", \"3/4\",\n \"'150\", \"250\", \"450 \", \"170\", \"gelatin\", \"biscuits\", \"slices\", \"ripe\", \"full\", \"optional\", \"average\",\n \"raw\", \"chemical\", \"optional\", \"same\", \"measure\", \"liters\", \"sticks\", \"grated\",\"roasted\",\n \"decorate\", \"liter\", \"confectioner\", \"cream\", \"fat\", \"dye\", \"food\", \"packaging\", \"concentrate\",\"ice cream\",\n \"cow\", \"pulp\", \"fresh\", \"some\", \"'syrup\", \"1kg\", \"cupcake\", \"syrup\", \"red\",\"green\", \"see\", \"vegetable\",\n \"miscellaneous\", \"pellets\", \"cut\", \"crushed\",\"ground\",\"gut\", \"total\", \"pie\", \"toast\", \"strips\",\n \"'200ml'\", \"30g\", \"50g\", \"Yellow\", \"yellow\", \"bitter\", \"crumpled\",\"kneaded\",\"american\", \"softened\", \"angel\",\n \"trimmed\", \"about\", \"arboreal\", \"wings\", \"roast\", \"baked\", \"bales\", \"bar\", \"base\", \"baste\",\n \"beat\", \"beats\", \"beaten\", \"milkshakes\",\"head\", \"heads\", \"hair\", \"cabins\", \"goat\", \"each\", \"boxes\",\n \"caracelinho\", \"caramelizar\", \"lump\", \"cores\", \"house\", \"bark\", \"peels\", \"fence\",\"clear\", \"cover\", \"bought\",\n \"length\", \"common\", \"conch\", \"frozen\", \"frozen\", \"preserves\", \"consistency\", \"cup\",\"cut\", \"thigh\", \"thigh\",\n \"cooked\",\"cooking\", \"creamy\", \"candied\", \"raw\", \"cubes\", \"cube\", \"cuisine\", \"short\", \"decoration\",\n \" smoked \", \"peeled\", \"thawed\", \"deglazed\", \"shredded\", \"dehydrated\", \"dessicated\", \"diet\", \"disc\",\n \"divided\", \"sweet\", \"hard\", \"bread\",\"drained\", \"brushed\", \"dark\",\"crushed\", \"squeezed\", \"sliced\", \"made\",\n \"boiling\",\"fine\", \"finally\", \"firm\", \"flakes\", \"flower\", \"flowers\", \"florets\",\"French\", \"fresh\", \"form\",\n \"cold\", \"fry\", \"fruit\", \"cattle\", \"bottle\", \"ice\",\"germ\", \"gum\", \"buds\", \"drops\", \"grams\", \"large\",\n \"Greek\", \"thick\", \"roughly\", \"hour\", \"colorless\", \"English\", \"integer\", \"italian\", \"washed\", \"vegetables\",\n \"lightly\", \"light\",\"clean\", \"blender\", \"liquid\", \"flat\",\"wood\", \"mature\", \"thin\", \"hands\", \"mary\",\"medium\",\n \"half\", \"half-bitter\", \"mint\", \"best\", \"Mexican\", \"mines\", \"crumb\", \"crushed\", \"other\", \"kids\", \"mix\", \"warm\",\n \"natural\", \"needed\", \"snow\",\"packs\", \"straw\", \"sticks\", \"screw\", \"paris\", \"part\", \"parts\", \"raisins\", \"paste\",\n \"pectin\", \"pieces\", \"chest\", \"breasts\", \"peeled\", \"skin\", \"sifted\", \"penne\", \"small\",\"chopped\", \"spicy\", \"brush\",\n \"can\", \"sprinkle\", \"point\", \"pot\", \"little\", \"plate\", \"precooked\", \"preference\",\"black\", \"ready\", \"protein\",\n \"handful\", \"quality\", \"how much\", \"rooms\", \"four\", \"hot\",\"root\", \"grated\",\"branches\",\"shallow\", \"ripped\",\n \"recipe\", \"stuffed\", \"filling\",\"dried\", \"selective\", \"semi-skimmed\", \"separated\", \"serve\", \"leftovers\",\n \"dessert\", \"soluble\", \"assorted\",\"soft\", \"sufficient\", \"tablet\", \"tablets\", \"stem\", \"stalks\", \"size\",\n \"seasoning\", \"tempered\",\"spices\", \"type\", \"strips\", \"glass\", \"fresh\", \"tablespoons\", \"powder\",\n \"cups\",\"pounds\",\"boneless\",\"skinless\",\"teapoon\",\"white\",\"minced\",\"ounce\",\"pata\",\"diced\",\"pound\",\"all-purpose\",\n \"teaspoons\",\"breat\",\"halve\", \"teaspoon\", \"tablespoon\", \"halved\", \"leaves\", \"freshly\", \"ounces\", \"bunch\",\n \"coarsely\", \"quartered\", \"thinly\", \"finely\", \"rinsed\", \"crumbled\", \"removed\", \"baby\", \"bell\", \"pitted\",\n \"Italian\", \"broth\", \"extra-virgin\", \"cubed\", \"packages\", \"halves\", \"juiced\", \"1-inch\", \"uncooked\",\n \"mixed\", \"toasted\", \"'Dressing\", \"spray\", \"seeded\", \"'cooking\", \"inch\", \"plain\", \"1/2-inch\", \"container\",\n \"cored\", \"whole\"])\n\nmaisUma = []\nfor i in range(99,999):\n maisUma.append(\"'\"+str(i))\n maisUma.append(\"'\"+str(i)+\"g\")\nstopWords.update(maisUma)\n\ningredientsDictionary = []\ndicFinal = dict(ingredientsDictionary)\n\n#12167\nfor i in range(0,967):\n if(calculaScore(dataframeIN, i) >= 35.0):\n ingredients = dataframeIN.loc[i, \"ingredients\"]\n criaListaIngredientes(filtraIngredientes(ingredients, stopWords), dicFinal, dataframeIN.loc[i, \"_id\"])\n\ngraphSize = criaNos(grafoUSA, dict(dicFinal))\ncriaLinks(grafoUSA, graphSize, dicFinal)\ndefineTops(calculaCentralidade(grafoUSA))\n#salvaGrafo(grafoUSA)\n\n","sub_path":"grafoIndia-PMI.py","file_name":"grafoIndia-PMI.py","file_ext":"py","file_size_in_byte":10790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"555866735","text":"import requests\nimport json\nimport pprint\n\ndireccion = \"Rivadav 6300\"\nlocalidad = 'caba'\nprint(direccion + ', ' + localidad)\n\ndireccion_formato = requests.utils.quote(direccion + ', ' + localidad)\nprint(direccion_formato)\n\nurl = 'http://servicios.usig.buenosaires.gob.ar\\\n/normalizar/?geocodificar=True&direccion=' + direccion_formato\nprint(url)\n\ndir_normalizada = json.loads(requests.get(url).text)\npprint.pprint(dir_normalizada)","sub_path":"Clase 8/api_extraccion.py","file_name":"api_extraccion.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"612856917","text":"'''thesaurus.py\r\nAuthor: AJS 12/2017 To use, enter a command prompt in the same directory where\r\nthis file lives and use the following syntax\r\n>> python thesaurus.py lookupword'''\r\n\r\nimport requests\r\nimport re\r\nimport sys\r\nimport os\r\nos.system('cls') # Clear command prompt window\r\n\r\n# Use command line argument if possible, otherwise default input is \"good\" for\r\n# testing.\r\ntry:\r\n word = sys.argv[1]\r\nexcept:\r\n word = 'good'\r\n\r\n# Request the synonyms for the specified word\r\nversion = 2\r\nwith open('thesaurus_api.key', 'r') as f:\r\n apikey = f.read()\r\nfmt = ''\r\n\r\nurl = 'http://words.bighugelabs.com/api/{}/{}/{}/{}'.format(version, apikey, word, fmt)\r\nr = requests.get(url)\r\nassert r.status_code in [200, 303], (\r\n \"Error getting response from URL: {}\\n\\nStatus Code was {}\".format(\r\n url, r.status_code))\r\n\r\n# WPrint all of the listed synonyms\r\nprint(\"\\nSynonyms for \\\"{}\\\" are:\\n\".format(word))\r\nprint(r.text)\r\n","sub_path":"thesaurus.py","file_name":"thesaurus.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"253952905","text":"import sys\nsys.path[:0] = '../../'\nimport datetime as dt\nfrom machine_learner import *\nfrom simple_order_gen import *\nfrom technical_features import *\nimport classify as cl\n\nsymbol = sys.argv[1]\nfeatures_string = sys.argv[2]\n\ndef parse_features_string(str):\n strParts = str[1:-1].split(' ')\n retHash = {}\n features = []\n for x in strParts:\n key, val = x.split('=')\n if key[:4] == 'feat':\n features.append(val)\n else:\n retHash[key] = float(val)\n feature_hash = {}\n for y in features:\n name, val = y.split(':')\n if feature_hash.has_key(name):\n feature_hash[name].append(int(val))\n else: \n feature_hash[name] = [int(val)]\n retHash['features'] = feature_hash\n return retHash\n\nargs = parse_features_string(features_string)\n\nlearn_start_date = dt.datetime(2004,9,1)\nlearn_end_date = dt.datetime(2011,1,1)\n\nnow = dt.datetime.now()\ntoday = dt.datetime(now.year, now.month, now.day)\nstock_period = StockPeriod(symbol, dt.datetime(2000,1,1), today)\n\nmlearn = MachineLearner(symbol,\n classifier = cl.BuySellClassifier(threshold = args['threshold'], days = args['days_return']),\n feature_gen = lambda x: TechnicalFeatures(stock_period, args[\"features\"]))\n\nmlearn.learn_period(learn_start_date, learn_end_date)\npredictions = mlearn.predict_period(dt.datetime(2012,1,1), dt.datetime(2013,1,1))\norders = SimpleOrderGen(predictions, mlearn.sp, 6, 10000)\n\norders.print_orders()\n","sub_path":"mach_learn_trade/examples/orders_for_config.py","file_name":"orders_for_config.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"129222192","text":"import re \r\n#Allows z to be first character and last as long as there is a z in the middle\r\nword = input(\"Enter a word with a 'z' in it: \")\r\n#[^zZ] means can't be a z\r\npat = '[^zZ\\W\\d\\s_]+[zZ][^zZ\\W\\d\\s_]+'\r\n#pat = '\\Bz\\B' # allows numbers and spaces\r\n\r\nif (re.search(pat, word)):\r\n\tprint(\"found a Z\")\r\nelse:\r\n\tprint(\"bad\")","sub_path":"Exercise 2/Exercise2_3.py","file_name":"Exercise2_3.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"651799914","text":"import os\n#connections credentials\n\nDB_URL = os.environ['DB_URL']\n#entities properties\nACTOR_FIELDS = ['id', 'name', 'gender', 'date_of_birth']\nMOVIE_FIELDS = ['id', 'name', 'year', 'genre']\n\n#date of birth format\nDATE_FORMAT = '%d.%m.%Y'\n","sub_path":"Module7_DB_and_Flask/app/settings/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"261712797","text":"import os\nimport logging\nimport logging.handlers\n\n\ndef initialize_logger():\n logging_file_path = os.path.expanduser(\"~\")+\"/.sixfab/\"\n \n if not os.path.exists(logging_file_path):\n os.mkdir(logging_file_path)\n\n logger = logging.getLogger(\"agent\")\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(\"%(asctime)s %(levelname)-8s %(message)s\")\n log_file_handler = logging.handlers.TimedRotatingFileHandler(filename=logging_file_path+\"agent-log\", when=\"midnight\", backupCount=3)\n log_file_handler.setFormatter(formatter)\n\n logger.addHandler(log_file_handler)\n\n return logger","sub_path":"core/helpers/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"535713983","text":"# Read n nrs from keyboard and return them.\ndef getInput():\n\tprint('How many numbers?');\n\tcount = input(); \n\tcount = int(count);\n\n\tnumbers = [];\n\ti = 0;\n\twhile i < count:\n\t\tprint('Enter a number!');\n\t\tnumber = input();\n\t\tnumber = int(number);\n\t\tnumbers.append(number);\n\t\ti += 1;\n\n\treturn numbers;\n\n# Take a bunch of numbers. Sum up the even and odd ones separately. Print result.\ndef printEvenAndOddSums(numbers):\n\toddSum = 0;\n\tevenSum = 0;\n\tfor i in numbers:\n\t\tif (i%2 == 0):\n\t\t\tevenSum += i;\n\t\t\tcontinue;\n\t\toddSum += i;\n\n\tprint('Odd sum is: ' + str(oddSum));\n\tprint('Even sum is: ' + str(evenSum));\n\n#input = getInput();\n#printEvenAndOddSums(input);","sub_path":"intro-to-programming/py/lab2_py/print_even_and_odd_sums.py","file_name":"print_even_and_odd_sums.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"75256412","text":"import numpy as np\nimport pandas as pd\nimport xlrd\n\n\ndef read_csv_file(filepath, filename):\n # 读取csv格式文件,以列表方式存储\n data = []\n try:\n data = pd.read_csv(filepath + \"/\" + filename, header=None, encoding=\"unicode_escape\", error_bad_lines=False)\n except FileNotFoundError:\n print(\"file not found:\", filepath + \"/\" + filename)\n else:\n data = np.array(data).tolist()\n finally:\n return data\n\n\ndef read_xls_file(filepath, filename):\n # 读取excel格式文件,以列表方式存储\n try:\n workbook = xlrd.open_workbook(filepath + r\"/\" + filename)\n except FileNotFoundError:\n print(\"file not found:\", filepath + \"/\" + filename)\n return []\n else:\n sheets = []\n for sheet in range(len(workbook.sheets())):\n Data_sheet = workbook.sheets()[sheet] # 通过索引获取\n rowNum = Data_sheet.nrows # sheet行数\n colNum = Data_sheet.ncols # sheet列数\n\n # 获取所有单元格的内容\n list = []\n for i in range(rowNum):\n rowlist = []\n for j in range(colNum):\n rowlist.append(Data_sheet.cell_value(i, j))\n list.append(rowlist)\n\n sheets.append(list)\n return sheets\n\n\nif __name__ == '__main__':\n sheets = read_csv_file(\"../../../inputdata/告警\", \"text_train.csv\")\n print(sheets)\n sheets = read_xls_file(\"../../../inputdata/告警\", \"传输性能数据.xlsx\")\n print(len(sheets))\n sheets = read_xls_file(\"../../../inputdata/告警\", \"动环告警.xls\")\n print(len(sheets))\n","sub_path":"com/chinamobile/cq/read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"582614862","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport time\nimport random\n\n\n\nfrom opencage.geocoder import OpenCageGeocode\nkey = 'b005c18631444cbaad9d3b3dd81ad710'\ngeocoder = OpenCageGeocode(key)\n\ncountry = 'India'\n\ndata = pd.read_csv('india.csv')\ndata = data.drop(['Both sexes'], axis=1)\ndata['Density'] = data['4761865'] / 4761865\n\nlatitude_list = []\nlongitude_list = []\n\nfor index, row in data.iterrows():\n\tstate = row['State']\n\tquery = str(state) + ',' + str(country)\n\tresult = geocoder.geocode(query)\n\tlati = result[0]['geometry']['lat']\n\tlongi = result[0]['geometry']['lng']\n\tlatitude_list.append(lati)\n\tlongitude_list.append(longi)\n\tprint(str(lati) + ' ' + str(longi))\n\ttime.sleep(2)\n\ndata['Latitude'] = latitude_list\ndata['Longitude'] = longitude_list\n\ndata.to_csv(r'/home/sagar/Desktop/ModifiedData.csv', index=False, header=True)\n\n# -----------------------End of data cleaning------------------------------\n\n# I've genrated the data needed, now gonna use the ModifiedData.csv for rest of the program\n\n#-------------------------Generating the heatmap -------------------------------------\n\n\nmodData = pd.read_csv('ModifiedData.csv')\n\n\nmodData = modData.rename(columns={\"4761865\": \"Population\"})\n\nNumberOfClients = 2500\n\nclients = []\ncounty = []\nlatituteCl = []\nlongitudeCl = []\naffected = []\n\nsigma = 0.14\n\n\ndef makeDataForState(numberOfPeople):\n\n for i in range(len(numberOfPeople)):\n for j in range(numberOfPeople[i]):\n state = modData.loc[i, 'State']\n clientName = 'client' + str(j) + str(state)\n lati = modData.loc[i, 'Latitude']\n longi = modData.loc[i, 'Longitude']\n newlati = np.random.normal(lati, sigma)\n newlongi = np.random.normal(longi, sigma)\n affectedcorona = random.choice(range(2))\n\n clients.append(clientName)\n county.append(state)\n latituteCl.append(newlati)\n longitudeCl.append(newlongi)\n affected.append(affectedcorona)\n\n\nnumberOfPeople = (modData['Density'] * NumberOfClients).astype(int)\nnumberOfPeople = numberOfPeople.tolist()\n\nmakeDataForState(numberOfPeople)\n\nclientDict = {\n 'Client': clients,\n 'County': county,\n 'Latitude': latituteCl,\n 'Longitude': longitudeCl,\n 'Affected': affected\n}\n\nclientData = pd.DataFrame(clientDict)\n\nclientData.plot(kind='scatter', x='Longitude', y='Latitude',\n alpha=0.5, c='Affected', cmap=plt.get_cmap(\"jet\"), colorbar=True)\nplt.show()\n","sub_path":"python_covid/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"227036023","text":"import sys, socket, atexit, random\n\n# Fråga inte varför jag gjorde det här....\n\n\ncolor_beg = \"\\033[{}m\"\ncolor_end = \"\\033[0m\"\n\ndef color_text(s, color = 96):\n\treturn color_beg.format(color) + s + color_end\n\n\nclass TwitchBot:\n\n\tdef __init__(self, channel):\n\t\tself.channel = channel\n\t\tself.ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.server = \"irc.twitch.tv\"\n\t\tself.port = 6667\n\t\tself.username = \"word2vec\"\n\t\tself.password = \"dongsquad420\"\n\t\tself.oauth = \"oauth:6l56ia2c26md4c6mmnp7rmuec48yvh\"\n\t\tself.out_file = None\n\t\tatexit.register(self.close)\n\n\tdef connect(self):\n\t\tself.ircsock.connect((self.server, self.port))\n\t\tself.ircsock.send(bytes(\"PASS \" + self.oauth + \"\\n\", 'UTF-8'))\n\t\tself.ircsock.send(bytes(\"NICK \" + self.username + \"\\n\", 'UTF-8'))\n\t\tself.ircsock.send(bytes(\"JOIN #\" + self.channel + \"\\n\", 'UTF-8'))\n\t\tprint(color_text(\"Trying to connect...\"))\n\n\tdef close(self):\n\t\tif self.out_file is not None:\n\t\t\tif not self.out_file.closed:\n\t\t\t\tself.out_file.close()\n\t\tself.ircsock.send(bytes(\"PART #\" + self.channel + \"\\n\", 'UTF-8'))\n\t\tself.ircsock.send(bytes(\"QUIT\" + \"\\n\", 'UTF-8'))\n\t\tprint(\"Closing Twitchchat\")\n\t\tprint(\"Chat saved to cancer.txt\")\n\n\t\n\tdef start(self):\n\t\tif self.ircsock is None:\n\t\t\tprint(\"Not connected!\")\n\t\t\treturn\n\t\tmsg = \"\"\n\t\tuser = \"\"\n\t\tchat_msg = \"\"\t\t\n\t\trand = 0\n\n\t\tfor i in range(0, 2):\n\t\t\tmsg = self.ircsock.recv(2048)\n\t\t\tmsg = msg.decode(\"UTF-8\")\n\n\t\tprint(color_text(\"Connected to \" + self.channel + \"!\"))\n\n\t\twhile True:\n\t\t\tmsg = self.ircsock.recv(2048)\n\t\t\tmsg = msg.decode(\"UTF-8\")\n\t\t\tif msg.find(\"PING \") != -1:\n\t\t\t\tself.ircsock.send(bytes(\"PONG tmi.twitch.tv\" + \"\\n\", 'UTF-8'))\n\t\t\t\tprint(color_text(\"Pong sent to server\"))\t\t\t\t\n\t\t\t\tcontinue\t\n\t\t\telif msg.find(\"word2vec\") != -1:\n\t\t\t\tcontinue\t\t\n\t\n\t\t\tmsg = msg.strip(\"\\n\\r\")\n\t\t\t\n\t\t\tuser = msg[1:msg.find(\"!\")]\n\t\t\tchat_msg = msg[msg[1:].find(\":\") + 2:]\n\n\n\t\t\tself.out_file = open(\"cancer.txt\", \"a\")\n\t\t\tself.out_file.write(chat_msg + \"\\n\")\n\t\t\tself.out_file.close()\n\t\t\t\n\t\t\trand = random.randrange(91, 98)\n\t\t\t\n\t\t\tprint(color_text(user, rand) + \": \" + color_text(chat_msg, rand))\n\n\t\ndef main():\n\tprint(color_text(\"Welcome to cancer\"))\n\tprint(color_text(\"Safest way to exit program : ctrl-c\"))\n\t\t\t\n\tchannel = input(\"Enter channel name :\")\n\tbot = TwitchBot(channel)\n\tbot.connect()\n\tbot.start()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"twitchchat.py","file_name":"twitchchat.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"212048423","text":"'''\nCreated on Dec 23, 2016\n\n@author: Atri\n'''\nimport sys\nimport maya.OpenMaya as OpenMaya\nimport maya.OpenMayaMPx as OpenMayaMPx\n\nnodeName = \"wheelNode\"\nnodeID = OpenMaya.MTypeId(0x100fff)\n\nclass wheelNode(OpenMayaMPx.MPxNode):\n \n inRadius = OpenMaya.MObject()\n inTranslate = OpenMaya.MObject()\n outRotate = OpenMaya.MObject()\n \n def __init__(self):\n OpenMayaMPx.MPxNode.__init__(self)\n \n def compute(self,plug,dataBlock):\n '''\n rotate = translate/(2*3.14*radius)*(-360)\n '''\n \n if plug == wheelNode.outRotate :\n dataHandleTraslate = dataBlock.inputValue(wheelNode.inTranslate)\n dataHandleRadius = dataBlock.inputValue(wheelNode.inRadius)\n \n inRadiusVal = dataHandleRadius.asFloat()\n inTranslateVal = dataHandleTraslate.asFloat()\n \n outRotate = float(inTranslateVal)/float(2*3.14*inRadiusVal)*(-360)\n dataHandleRotate = dataBlock.outputValue(wheelNode.outRotate)\n dataHandleRotate.setFloat(outRotate)\n dataBlock.setClean(plug)\n \n else :\n return OpenMaya.kUnknownParameter\n \n \n \n\ndef nodeCreator():\n return OpenMayaMPx.asMPxPtr(wheelNode())\n \n\ndef nodeInitializer():\n mFnAttr = OpenMaya.MFnNumericAttribute()\n \n wheelNode.inRadius = mFnAttr.create(\"radius\",'r',OpenMaya.MFnNumericData.kFloat,0.0)\n mFnAttr.setReadable(1)\n mFnAttr.setStorable(1)\n mFnAttr.setWritable(1)\n mFnAttr.setKeyable(1)\n \n wheelNode.inTranslate = mFnAttr.create(\"translate\",'t',OpenMaya.MFnNumericData.kFloat,0.0)\n mFnAttr.setReadable(1)\n mFnAttr.setStorable(1)\n mFnAttr.setWritable(1)\n mFnAttr.setKeyable(1)\n \n wheelNode.outRotate = mFnAttr.create(\"rotate\",'rot',OpenMaya.MFnNumericData.kFloat)\n mFnAttr.setReadable(1)\n mFnAttr.setStorable(0)\n mFnAttr.setWritable(0)\n mFnAttr.setKeyable(0)\n \n \n wheelNode.addAttribute(wheelNode.inRadius)\n wheelNode.addAttribute(wheelNode.inTranslate)\n wheelNode.addAttribute(wheelNode.outRotate)\n \n wheelNode.attributeAffects(wheelNode.inRadius,wheelNode.outRotate)\n wheelNode.attributeAffects(wheelNode.inTranslate,wheelNode.outRotate)\n \n \ndef initializePlugin(mobject):\n mplugin = OpenMayaMPx.MFnPlugin(mobject,'Atri Dave','1.0')\n try:\n mplugin.registerNode( nodeName, nodeID,nodeCreator,nodeInitializer )\n except:\n sys.stderr.write( \"Failed to register command: %s\\n\" % nodeName )\n raise\n\n# Uninitialize the script plug-in\ndef uninitializePlugin(mobject):\n mplugin = OpenMayaMPx.MFnPlugin(mobject)\n try:\n mplugin.deregisterNode( nodeID )\n except:\n sys.stderr.write( \"Failed to unregister command: %s\\n\" % nodeName )","sub_path":"MayaPythonAPIPlugins/MayaPythonAPIPlugins/wheelNode.py","file_name":"wheelNode.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"327832293","text":"\nimport logging, sys\nimport zope.event\n\nconsole = logging.StreamHandler( sys.stdout )\nconsole.setLevel( logging.DEBUG )\nevt_log = logging.getLogger('bungeni')\nevt_log.setLevel( logging.DEBUG )\nevt_log.addHandler( console )\n\nfilter_events = [\n 'Registered',\n 'BeforeTraverseEvent',\n 'ContainerModifiedEvent',\n 'BeforeUpdateEvent',\n 'EndRequestEvent',\n 'AuthenticatedPrincipalCreated',\n ]\n\ndef eventLog( event ):\n if event.__class__.__name__ in filter_events:\n return\n evt_log.info( \"Event %r\"%(event))\n\nzope.event.subscribers.append( eventLog )\n","sub_path":"bungeni.main/trunk/bungeni/core/eventlog.py","file_name":"eventlog.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"580562465","text":"#!/usr/bin/env python2\n\nfrom Crypto.PublicKey import RSA\nimport StringIO\nimport random\nimport string\n\nimport unittest\nimport cryptfile\n\n\nclass TestCryptFile(unittest.TestCase):\n def setUp(self):\n self.key = RSA.generate(2048)\n def testCrypto(self):\n randomLength = 400\n text = ''.join(random.choice(string.ascii_uppercase)\n for _ in range(randomLength))\n output = StringIO.StringIO()\n cryptFile = cryptfile.Writer(self.key, output)\n cryptFile.write(text)\n input = StringIO.StringIO(output.getvalue())\n cryptFile = cryptfile.Reader(self.key, input)\n self.assertEquals(cryptFile.read(), text)\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cryptfile_test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"281573665","text":"# text preprocessing before being used in application\n\nimport re\nfrom collections import Counter\n\ndef get_voc_freq(book_title):\n '''\n Manually removed some text preambles that were not part of\n the text.\n\n :book_title: args 1 the name of the book_title\n :returns: a dict with words as keys and freqs as values.\n '''\n\n # the re handles getting only the words\n mob_words = re.findall(r'\\w+', open(book_title).read().lower())\n\n # counter of words (vocabulary distribution)\n c = Counter(mob_words)\n\n # sort and change to a dictionary\n c_sorted = dict(c.most_common(len(c)))\n\n return c_sorted\n\n\ndef get_voc(book_title):\n\t\"\"\"\n\tRemoves nothing, not even punctiation\n\t\"\"\"\n\tc = open(\"quixote.txt\").read().lower().split()\n\treturn set(c)\n\n\ndef read_freqs(text_f):\n\t\"\"\"\n\n\tThese are frequencies obtained via\n\tthe perl script\n\t\"\"\"\n\tf = open(text_f).read().split(\"\\n\")\n\t# remove last character which is a space\n\t# now the count matches with what wc gets\n\tdel f[-1]\n\tf = [int(x) for x in f]\n\tf.sort(reverse=True)\n\t\n\treturn f","sub_path":"code/text_process.py","file_name":"text_process.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"300289992","text":"\"\"\"\nThis file defiens some constants,\nthat are used by all over the place.\n\"\"\"\n\nGTFS_HEADERS = {\n \"agency.txt\": [\"agency_id\", \"agency_name\", \"agency_url\", \"agency_timezone\", \"agency_lang\"],\n \n \"stops.txt\": [\"stop_id\", \"stop_code\", \"stop_name\", \"stop_lat\", \"stop_lon\"],\n \n \"routes.txt\": [\"agency_id\", \"route_id\", \"route_short_name\", \"route_long_name\",\n \"route_type\", \"route_color\", \"route_text_color\"],\n \n \"calendar_dates.txt\": [\"service_id\", \"date\", \"exception_type\"],\n \n \"translations.txt\": [\"trans_id\", \"lang\", \"translation\"]\n \n #\"fare_attributes.txt\": [\"agency_id\", \"fare_id\", \"price\", \"currency_type\",\n # \"payment_method\", \"transfers\"],\n \n #\"fare_rules.txt\": [\"fare_id\", \"contains_id\"],\n}\n\nGTFS_HEADERS_TRAIN = GTFS_HEADERS.copy()\nGTFS_HEADERS_TRAIN.update({\n \"trips.txt\": [\"route_id\", \"trip_id\", \"service_id\", \"trip_short_name\",\n \"trip_headsign\", \"direction_id\", \"direction_name\",\n \"block_id\", \"train_realtime_id\"],\n \n \"stop_times.txt\": [\"trip_id\", \"stop_sequence\", \"stop_id\",\n \"platform\", \"arrival_time\", \"departure_time\",],\n\n \"stops.txt\": [\"stop_id\", \"stop_code\", \"stop_name\", \"stop_lat\", \"stop_lon\",\n \"location_type\", \"parent_station\"],\n})\n\nGTFS_HEADERS_BUS = GTFS_HEADERS.copy()\nGTFS_HEADERS_BUS.update({\n \"trips.txt\": [\"route_id\", \"trip_id\", \"service_id\", \"trip_headsign\",\n \"wheelchair_accessible\", \"trip_pattern_id\"],\n \n \"stop_times.txt\": [\"trip_id\", \"stop_sequence\", \"stop_id\",\n \"arrival_time\", \"departure_time\",\n \"pickup_type\", \"drop_off_type\"],\n})\n\nSEPARATE_STOPS = {\n \"Waseda\", \"Kuramae\", \"Nakanobu\",\n \"Suidobashi\", \"HongoSanchome\",\n \"Ryogoku\", \"Kumanomae\"\n}\n\nALERT_EFFECTS = {\n \"運転見合わせ\": 1, \"運転被約\": 2, \"遅延\": 3, \"運行情報あり\": 6, \"お知らせ\": 6, \"直通運転中止\": 1,\n}\n\nALERT_CAUSES = {\n \"車両点検\": 9, \"車輪空転\": 3, \"大雨\": 8, \"大雪\": 8, \"地震\": 6, \"線路に支障物\": 6, \"シカと衝突\": 6,\n \"接続待合せ\": 3, \"異音の確認\": 3, \"架線点検\": 3, \"踏切に支障物\": 6, \"架線に支障物\": 6, \"事故\": 6,\n}\n\nADDITIONAL_ENGLISH = {\n \"循環\": \"Loop\",\n}\n\nGET_TIMEOUT = 30\n\nHEADER = r\"\"\"\n| _____ _ ____ _____ _____ ____ |\n| |_ _|__ | | ___ _ ___ / ___|_ _| ___/ ___| |\n| | |/ _ \\| |/ / | | |/ _ \\| | _ | | | |_ \\___ \\ |\n| | | (_) | <| |_| | (_) | |_| | | | | _| ___) | |\n| |_|\\___/|_|\\_\\\\__, |\\___/ \\____| |_| |_| |____/ |\n| |___/ |\n\"\"\"\n","sub_path":"src/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"296113921","text":"import tensorflow as tf\nimport numpy as np\nimport os\n#from D2_car.car_env import CarEnv\nfrom car_env import CarEnv\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nimport getch\n\nkeys = {'a': -1,'d': 0,'w':1}\n\ndef record_user(dir='./saved_data'):\n sarsa_pairs = []\n print(\"press + to save\")\n esc = False\n while not esc:\n done = False\n _last_obs = env.reset()\n while not done:\n env.render()\n action = None\n while action is None:\n keys_pressed = getch.getch()\n if keys_pressed is '+':\n esc = True\n break\n\n pressed = [x for x in keys if x in keys_pressed]\n action = keys[pressed[0]] if len(pressed) > 0 else None\n\n if esc:\n print(\"ENDING\")\n done = True\n break\n\n obs, reward, done = env.step(action)\n\n sarsa = (_last_obs, action)\n _last_obs = obs\n sarsa_pairs.append(sarsa)\n print(sarsa)\n\n if esc:\n break\n\n print(\"SAVING\")\n sarsa_pairs = np.array(sarsa_pairs)\n with open(os.path.join(dir, 'data.npy'), 'wb') as f:\n np.save(f, sarsa_pairs)\n\n print('Done')\n\ndef process_data(dir='./saved_data'):\n states, actions = [], []\n with open('./saved_data/data.npy', 'rb') as f:\n data = np.load(f,allow_pickle=True)\n shard_states, unprocessed_actions = zip(*data)\n shard_states = [x.flatten() for x in shard_states]\n\n # Add the shard to the dataset\n states.extend(shard_states)\n actions.extend(unprocessed_actions)\n\n states = np.asarray(states, dtype=np.float32)\n actions = np.asarray(actions)\n\n print('states:{}, actions:{}'.format(np.shape(states), np.shape(actions)))\n\n num_bins = 25\n samples_per_bin = 250# 200\n hist, bins = np.histogram(actions, num_bins)\n center = (bins[:-1] + bins[1:]) * 0.5\n plt.bar(center, hist, width=0.05)\n plt.plot((np.min(actions), np.max(actions)), (samples_per_bin, samples_per_bin))\n print('total data:', len(data))\n plt.show()\n\n remove_list = []\n for j in range(num_bins):\n list_ = []\n for i in range(len(actions)):\n if actions[i] >= bins[j] and actions[i] <= bins[j + 1]:\n list_.append(i)\n list_ = shuffle(list_)\n list_ = list_[samples_per_bin:]\n remove_list.extend(list_)\n\n print('removed:', len(remove_list))\n actions = np.delete(actions, remove_list)\n states = np.delete(states, remove_list, axis=0)\n print('actions remaining:{}, states:{}'.format(np.shape(actions),np.shape(states)))\n\n hist, _ = np.histogram(actions, (num_bins))\n plt.bar(center, hist, width=0.05)\n plt.plot((np.min(actions), np.max(actions)), (samples_per_bin, samples_per_bin))\n plt.show()\n\n return states, actions\n\ndef create_model():\n state_ph = tf.placeholder(tf.float32, shape=[None, 5])\n\n with tf.variable_scope(\"layer1\"):\n hidden = tf.layers.dense(state_ph, 128, activation=tf.nn.relu)\n\n with tf.variable_scope(\"layer2\"):\n hidden = tf.layers.dense(hidden, 128, activation=tf.nn.relu)\n\n with tf.variable_scope(\"layer3\"):\n logits = tf.layers.dense(hidden, 3)\n\n with tf.variable_scope(\"output\"):\n action = tf.argmax(input=logits, axis=1)\n\n return state_ph, action, logits\n\ndef create_training(logits):\n label_ph = tf.placeholder(tf.int32, shape=[None])\n\n with tf.variable_scope(\"loss\"):\n onehot_labels = tf.one_hot(indices=tf.cast(label_ph, tf.int32), depth=3)\n\n loss = tf.losses.softmax_cross_entropy(\n onehot_labels=onehot_labels, logits=logits)\n loss = tf.reduce_mean(loss)\n\n tf.summary.scalar('loss', loss)\n\n with tf.variable_scope(\"training\"):\n optimizer = tf.train.AdamOptimizer(learning_rate=1e-3)\n train_op = optimizer.minimize(loss=loss)\n\n return train_op, loss, label_ph\n\ndef run_main():\n state_data, action_data = process_data()\n\n x, model, logits = create_model()\n train, loss, labels = create_training(logits)\n\n sess = tf.Session()\n\n # Create summaries\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter('./logs', sess.graph)\n\n sess.run(tf.global_variables_initializer())\n\n tick = 0\n while True:\n done = False\n obs = env.reset()\n while not done:\n env.render()\n\n if tick<1500:#train\n #batch_index = np.random.choice(len(state_data), 64)\n #state_batch, action_batch = state_data[batch_index], action_data[batch_index]\n\n # Train the model.\n _, cur_loss, cur_summaries = sess.run([train, loss, merged], feed_dict={\n x: state_data,\n labels: action_data\n })\n print(\"Loss: {}\".format(cur_loss))\n train_writer.add_summary(cur_summaries, tick)\n else:\n print('Testing--')\n print()\n\n action = sess.run(model, feed_dict={x: [obs.flatten()]})[0]\n\n obs, reward, done = env.step(action)\n\n tick += 1\n\nif __name__ == '__main__':\n DISCRETE_ACTION = True\n env = CarEnv(discrete_action=DISCRETE_ACTION)\n\n #record_user()\n\n run_main()","sub_path":"D2_car/Learn_user.py","file_name":"Learn_user.py","file_ext":"py","file_size_in_byte":5359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"342407303","text":"from app.packages.utils import get_economist_weekly_url\n\nfrom app.packages.feeds.EconomistWeeklyFeed import EconomistWeeklyFeed\nfrom app.packages.feeds.FierceFeed import FierceFeed\n\nfrom app.packages.parsers import get_parser\n\nimport datetime\n\nfeed_map = {\n\tget_economist_weekly_url(): EconomistWeeklyFeed,\n\t'http://www.fiercecable.com': FierceFeed,\n\t'http://www.fiercewireless.com': FierceFeed,\n\t'http://www.fiercetelecom.com': FierceFeed\n}\n\ndef iter_values():\n\tfor url, Feed in feed_map.items():\n\t\tfeed = Feed(url)\n\t\tfor d in feed.iter_values():\n\t\t\tyield d\n\ndef iter_urls():\n\treturn None\n\nif __name__ == \"__main__\":\n\tfor val in iter_values():\n\t\tparser = get_parser(val['parser_id'])\n\t\tif parser is None:\n\t\t\traise\n\t\telse:\n\t\t\tcontinue\n","sub_path":"app/packages/feeds/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"636186276","text":"# Author:丁泽盛\r\n# data:2020/10/5 13:00\r\n\r\nimport sys\r\nimport pygame\r\n\r\ndef run_game():\r\n\r\n pygame.init() #初始化游戏背景设置\r\n screen = pygame.display.set_mode((900, 600))#创建显示窗口\r\n pygame.display.set_caption('Alien Invasion')\r\n bg_color = (230, 9, 0)\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n sys.exit()\r\n screen.fill(bg_color)\r\n pygame.display.flip()\r\n\r\nrun_game()\r\n","sub_path":"py_game.py","file_name":"py_game.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"578273428","text":"import os\nimport sys\nimport numpy as np\nfrom mrcnn import visualize\nimport mdf as coco\nROOT_DIR = os.path.abspath(\"./\")\nsys.path.append(ROOT_DIR)\nconfig = coco.CocoConfig()\nCOCO_DIR = \"./coco_mdf\"\n# Load dataset\ndataset = coco.CocoDataset()\ndataset.load_coco(COCO_DIR, \"train\")\ndataset.prepare()\n\nprint(\"Image Count: {}\".format(len(dataset.image_ids)))\nprint(\"Class Count: {}\".format(dataset.num_classes))\nfor i, info in enumerate(dataset.class_info):\n print(\"{:3}. {:50}\".format(i, info['name']))\n# Load and display random samples\nimage_ids = np.random.choice(dataset.image_ids, 20)\nprint(image_ids)\nfor image_id in image_ids:\n image = dataset.load_image(image_id)\n mask, class_ids = dataset.load_mask(image_id)\n print(mask.shape)\n visualize.display_top_masks(image, mask, class_ids, dataset.class_names)","sub_path":"inspect_data.py","file_name":"inspect_data.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"225879961","text":"# search.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n\"\"\"\nIn search.py, you will implement generic search algorithms which are called by\nPacman agents (in searchAgents.py).\n\"\"\"\n\nimport util\nfrom util import Stack\nfrom util import Queue\nfrom util import PriorityQueue\n\nclass SearchProblem:\n \"\"\"\n This class outlines the structure of a search problem, but doesn't implement\n any of the methods (in object-oriented terminology: an abstract class).\n\n You do not need to change anything in this class, ever.\n \"\"\"\n\n def getStartState(self):\n \"\"\"\n Returns the start state for the search problem.\n \"\"\"\n util.raiseNotDefined()\n\n def isGoalState(self, state):\n \"\"\"\n state: Search state\n\n Returns True if and only if the state is a valid goal state.\n \"\"\"\n util.raiseNotDefined()\n\n def getSuccessors(self, state):\n \"\"\"\n state: Search state\n\n For a given state, this should return a list of triples, (successor,\n action, stepCost), where 'successor' is a successor to the current\n state, 'action' is the action required to get there, and 'stepCost' is\n the incremental cost of expanding to that successor.\n \"\"\"\n util.raiseNotDefined()\n\n def getCostOfActions(self, actions):\n \"\"\"\n actions: A list of actions to take\n\n This method returns the total cost of a particular sequence of actions.\n The sequence must be composed of legal moves.\n \"\"\"\n util.raiseNotDefined()\n\n\ndef tinyMazeSearch(problem):\n \"\"\"\n Returns a sequence of moves that solves tinyMaze. For any other maze, the\n sequence of moves will be incorrect, so only use this for tinyMaze.\n \"\"\"\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s, s, w, s, w, w, s, w]\n\ndef depthFirstSearch(problem):\n \"\"\"\n Search the deepest nodes in the search tree first.\n\n Your search algorithm needs to return a list of actions that reaches the\n goal. Make sure to implement a graph search algorithm.\n\n To get started, you might want to try some of these simple commands to\n understand the search problem that is being passed in:\n\n print \"Start:\", problem.getStartState()\n print \"Is the start a goal?\", problem.isGoalState(problem.getStartState())\n print \"Start's successors:\", problem.getSuccessors(problem.getStartState())\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n # A stack data structure is used search the deepest nodes first\n next_node_stack = Stack() # Stack to store next node to visit\n next_path_stack = Stack() # Stack to store next path\n visited = [] # list to contain node that have been visited\n dfs_path = [] # list to contain the dfs path sequence\n\n # set current state to start state\n current_state = problem.getStartState() \n \n # iterate until the goal state is reached\n while not problem.isGoalState(current_state):\n # if the current state has not been visited \n if current_state not in visited:\n # add current state to list of visited nodes\n visited.append(current_state)\n # iterate through all neighouring nodes\n for neighour in problem.getSuccessors(current_state):\n # neighbour has not been visited\n if(neighour[0] not in visited): \n # push neighbour node and path list to top of stack\n next_node_stack.push(neighour[0])\n next_path_stack.push([dfs_path+[neighour[1]]])\n \n # to go deep first we pop next node and path from top of stack\n current_state = next_node_stack.pop()\n dfs_path = next_path_stack.pop()[0]\n\n return dfs_path\n\n\ndef breadthFirstSearch(problem):\n \"\"\"Search the shallowest nodes in the search tree first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n\n # A queue data structure is used search the shallowest nodes first\n next_node_queue = Queue() # Queue to store next node to visit\n next_path_queue = Queue() # Queue to store next path\n visited = [] # list to contain node that have been visited\n bfs_path = [] # list to contain the bfs path sequence\n\n # set current state to start state\n current_state = problem.getStartState() \n \n # iterate until the goal state is reached\n while not problem.isGoalState(current_state):\n # if the current state has not been visited \n if current_state not in visited:\n # add current state to list of visited nodes\n visited.append(current_state)\n # iterate through all neighouring nodes\n for neighour in problem.getSuccessors(current_state):\n # neighbour has not been visited\n if(neighour[0] not in visited): \n # push neighbour node and path list to front of queue\n next_node_queue.push(neighour[0])\n next_path_queue.push([bfs_path+[neighour[1]]])\n \n # to go deep first we pop next node and path from end of queue\n current_state = next_node_queue.pop()\n bfs_path = next_path_queue.pop()[0]\n\n return bfs_path\n \n\ndef uniformCostSearch(problem):\n \"\"\"Search the node of least total cost first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n\n # A priority queue data structure is used search the deepest nodes first\n next_node_queue = PriorityQueue() # PQueue to store next node to visit\n next_path_queue = PriorityQueue() # PQueue to store next path\n visited = [] # list to contain node that have been visited\n ucs_path = [] # list to contain the bfs path sequence\n\n # set current state to start state\n current_state = problem.getStartState() \n \n # iterate until the goal state is reached\n while not problem.isGoalState(current_state):\n # if the current state has not been visited \n if current_state not in visited:\n # add current state to list of visited nodes\n visited.append(current_state)\n # iterate through all neighouring nodes\n for neighbour in problem.getSuccessors(current_state):\n # neighbour has not been visited\n if(neighbour[0] not in visited):\n # get cost of path containing this neighbour \n cost = problem.getCostOfActions(ucs_path+[neighbour[1]])\n # push neighbour node and path list to queue based on cost\n next_node_queue.push(neighbour[0], cost)\n next_path_queue.push([ucs_path+[neighbour[1]]], cost)\n \n # to go deep first we pop next node and path from end of queue\n current_state = next_node_queue.pop()\n ucs_path = next_path_queue.pop()[0]\n\n return ucs_path\n\n\ndef nullHeuristic(state, problem=None):\n \"\"\"\n A heuristic function estimates the cost from the current state to the nearest\n goal in the provided SearchProblem. This heuristic is trivial.\n \"\"\"\n return 0\n\ndef aStarSearch(problem, heuristic=nullHeuristic):\n \"\"\"Search the node that has the lowest combined cost and heuristic first.\"\"\"\n \"*** YOUR CODE HERE ***\"\n\n # A priority queue data structure is used search the deepest nodes first\n next_node_queue = PriorityQueue() # PQueue to store next node to visit\n next_path_queue = PriorityQueue() # PQueue to store next path\n visited = [] # list to contain node that have been visited\n astar_path = [] # list to contain the bfs path sequence\n\n # set current state to start state\n current_state = problem.getStartState() \n \n # iterate until the goal state is reached\n while not problem.isGoalState(current_state):\n # if the current state has not been visited \n if current_state not in visited:\n # add current state to list of visited nodes\n visited.append(current_state)\n # iterate through all neighouring nodes\n for neighbour in problem.getSuccessors(current_state):\n # neighbour has not been visited\n if(neighbour[0] not in visited):\n # get cost of path containing this neighbour plus the heuristc based on the new node\n cost = problem.getCostOfActions(astar_path+[neighbour[1]]) + heuristic(neighbour[0], problem)\n # push neighbour node and path list to queue based on cost\n next_node_queue.push(neighbour[0], cost)\n next_path_queue.push([astar_path+[neighbour[1]]], cost)\n \n # to go deep first we pop next node and path from end of queue\n current_state = next_node_queue.pop()\n astar_path = next_path_queue.pop()[0]\n\n return astar_path\n\n\n# Abbreviations\nbfs = breadthFirstSearch\ndfs = depthFirstSearch\nastar = aStarSearch\nucs = uniformCostSearch\n","sub_path":"search/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":9575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"346162956","text":"import logging\nimport os\n\nfrom cryptography.fernet import Fernet\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom shhh.api import api\nfrom shhh.extensions import db, scheduler\n\n\ndef register_blueprints(app):\n \"\"\"Register application blueprints.\"\"\"\n app.register_blueprint(api)\n\n\ndef create_app(env=os.environ.get(\"FLASK_ENV\")):\n \"\"\"Application factory.\"\"\"\n logging.basicConfig(\n level=logging.INFO,\n format=(\"[%(asctime)s] [sev %(levelno)s] [%(levelname)s] \"\n \"[%(name)s]> %(message)s\"),\n datefmt=\"%a, %d %b %Y %H:%M:%S\")\n\n # Disable werkzeug logging under WARNING.\n logging.getLogger(\"werkzeug\").setLevel(logging.WARNING)\n\n app = Flask(__name__)\n\n app.logger.info(f\"Loading env {env}\")\n configurations = {\n \"dev-local\": \"shhh.config.DefaultConfig\",\n \"testing\": \"shhh.config.TestConfig\",\n \"dev-docker\": \"shhh.config.DockerConfig\",\n \"heroku\": \"shhh.config.HerokuConfig\",\n \"production\": \"shhh.config.ProductionConfig\",\n }\n app.config.from_object(\n configurations.get(env, \"shhh.config.ProductionConfig\"))\n\n db.init_app(app)\n scheduler.init_app(app)\n\n with app.app_context():\n register_blueprints(app)\n db.create_all()\n scheduler.start()\n\n from shhh import views\n\n return app\n","sub_path":"shhh/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"227073549","text":"import astropy.io.fits as fits\nimport numpy as np\nfrom astropy import wcs\nimport os\nimport ci_reduce.common as common\n\ndef nominal_tan_wcs(telra, teldec, extname):\n # Create a new WCS object. The number of axes must be set\n # from the start\n\n par = common.ci_misc_params()\n\n fname = os.path.join(os.environ[par['etc_env_var']],\n par['headers_dummy_filename'])\n\n h = fits.getheader(fname, extname=extname)\n\n h['CRVAL1'] = telra\n h['CRVAL2'] = teldec\n\n w = wcs.WCS(h)\n\n return w\n\ndef ccd_center_radec(_wcs):\n y_pixel_center = 515.5 # need to double check this relative to convention\n x_pixel_center = 1023.5 # need to double check this relative to convention\n\n ra, dec = _wcs.all_pix2world(x_pixel_center, y_pixel_center, 0)\n\n return ra, dec\n","sub_path":"py/ci_reduce/ci_wcs.py","file_name":"ci_wcs.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"282314722","text":"#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu\" at 13:52, 28/01/2021 %\n# %\n# Email: nguyenthieu2102@gmail.com %\n# Homepage: https://www.researchgate.net/profile/Nguyen_Thieu2 %\n# Github: https://github.com/thieu1995 %\n# ------------------------------------------------------------------------------------------------------%\n\nfrom sklearn.model_selection import ParameterGrid\nfrom time import time\nfrom pathlib import Path\nfrom copy import deepcopy\nfrom config import Config, OptExp, OptParas\nimport optimizer\nfrom utils.io_util import load_tasks, load_nodes\nfrom utils.experiment_util import *\n\n\ndef inside_loop(my_model, n_trials, n_timebound, epoch, fe, end_paras):\n for n_tasks in OptExp.N_TASKS:\n tasks = load_tasks(f'{Config.INPUT_DATA}/tasks_{n_tasks}.json')\n problem = deepcopy(my_model['problem'])\n problem[\"tasks\"] = tasks\n problem[\"n_tasks\"] = n_tasks\n problem[\"shape\"] = [len(problem[\"clouds\"]) + len(problem[\"fogs\"]), n_tasks]\n\n for pop_size in OptExp.POP_SIZE:\n for lb, ub in zip(OptExp.LB, OptExp.UB):\n parameters_grid = list(ParameterGrid(my_model[\"param_grid\"]))\n for paras in parameters_grid:\n opt = getattr(optimizer, my_model[\"class\"])(problem=problem, pop_size=pop_size, epoch=epoch,\n func_eval=fe, lb=lb, ub=ub, verbose=OptExp.VERBOSE, paras=paras)\n solutions, g_best, g_best_dict, training_info = opt.train()\n if Config.TIME_BOUND_KEY:\n path_results = f'{Config.RESULTS_DATA}/{n_timebound}s/task_{n_tasks}/{Config.METRICS}/{my_model[\"name\"]}/{n_trials}'\n else:\n path_results = f'{Config.RESULTS_DATA}/no_time_bound/task_{n_tasks}/{Config.METRICS}/{my_model[\"name\"]}/{n_trials}'\n Path(path_results).mkdir(parents=True, exist_ok=True)\n name_paras = f'{epoch}_{pop_size}_{end_paras}'\n save_experiment_results_multi(solutions, g_best, g_best_dict, training_info, name_paras, path_results)\n if Config.VISUAL_SAVING:\n save_visualization_results_multi(solutions, my_model[\"name\"], name_paras, path_results)\n\n\ndef setting_and_running(my_model):\n print(f'Start running: {my_model[\"name\"]}')\n for n_trials in range(OptExp.N_TRIALS):\n if Config.TIME_BOUND_KEY:\n for n_timebound in OptExp.TIME_BOUND_VALUES:\n if Config.MODE == \"epoch\":\n for epoch in OptExp.EPOCH:\n end_paras = f\"{epoch}\"\n inside_loop(my_model, n_trials, n_timebound, epoch, None, end_paras)\n elif Config.MODE == \"fe\":\n for fe in OptExp.FE:\n end_paras = f\"{fe}\"\n inside_loop(my_model, n_trials, n_timebound, None, fe, end_paras)\n else:\n if Config.MODE == \"epoch\":\n for epoch in OptExp.EPOCH:\n end_paras = f\"{epoch}\"\n inside_loop(my_model, n_trials, None, epoch, None, end_paras)\n elif Config.MODE == \"fe\":\n for fe in OptExp.FE:\n end_paras = f\"{fe}\"\n inside_loop(my_model, n_trials, None, None, fe, end_paras)\n\n\nif __name__ == '__main__':\n starttime = time()\n clouds, fogs, peers = load_nodes(f'{Config.INPUT_DATA}/nodes_2_8_5.json')\n problem = {\n \"clouds\": clouds,\n \"fogs\": fogs,\n \"peers\": peers,\n \"n_clouds\": len(clouds),\n \"n_fogs\": len(fogs),\n \"n_peers\": len(peers),\n }\n\n models = [\n {\"name\": \"NSGA-II\", \"class\": \"BaseNSGA_II\", \"param_grid\": OptParas.NSGA_II, \"problem\": problem},\n {\"name\": \"NSGA-III\", \"class\": \"BaseNSGA_III\", \"param_grid\": OptParas.NSGA_III, \"problem\": problem},\n {\"name\": \"MO-SSA\", \"class\": \"BaseMO_SSA\", \"param_grid\": OptParas.MO_SSA, \"problem\": problem},\n {\"name\": \"MO-ALO\", \"class\": \"BaseMO_ALO\", \"param_grid\": OptParas.MO_ALO, \"problem\": problem},\n ]\n for my_md in models:\n setting_and_running(my_md)\n print('That took: {} seconds'.format(time() - starttime))\n\n","sub_path":"test_mo_alo.py","file_name":"test_mo_alo.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"22272329","text":"import sys\nimport matplotlib.pyplot as plt\nimport scipy\nimport math\nimport json\nfrom scipy import pi, log, log10, array, sqrt, stats\nfrom matplotlib import rc\nimport database\nimport statefuncs\n\noutput = \"pdf\"\n\nrc('font', **{'family': 'serif', 'serif': ['Computer Modern']})\nrc('text', usetex=True)\n\ndef main(argv):\n args = \" \"\n if len(argv) < 4:\n print(argv[0], args)\n return -1\n\n gList = [float(x) for x in argv[1].split(\",\")]\n Emax = float(argv[2])\n L = float(argv[3])\n\n plt.figure(1)\n params = {'legend.fontsize': 8}\n plt.rcParams.update(params)\n\n basis = statefuncs.Basis(m=1, L=L, Emax=Emax, k=1)\n\n ydata = []\n\n for g in gList:\n db = database.Database()\n exactQuery = {\"ren\":\"raw\", \"k\":1}\n approxQuery = {\"g\":g, \"Emax\":Emax, \"L\":L}\n eigv = db.getObjList(\"eigv\", exactQuery=exactQuery, approxQuery=approxQuery)[0]\n\n # Select only basis coefficients with 2 particles\n vacuumEigv = eigv[0]\n wf = array([vacuumEigv[i] for i in range(len(vacuumEigv)) if basis[i].occN()==2])\n\n # Normalization: multiply 2 particles at rest by sqrt(2)\n # Takes into account normalization of states and Bose symmetry\n # XXX check the normalization\n wf[0] = wf[0]*sqrt(2)\n\n # Since the wave function will be O(g^2) in the perturbative limit, rescale by this parameter\n wf = wf/g**2\n\n # Change sign to compare wave functions\n if wf[0]<0:\n wf = -wf\n\n klist = array(range(len(wf)))*(2*pi)/L\n plt.plot(klist,wf, label=\"g={:.3f}\".format(g))\n # linewidth=0.7,\n # dashes = [3,2], marker='.', markersize=3, color=evenColor, label=label(\"raw\"))\n ydata.extend(wf)\n\n data = scipy.column_stack((klist,wf))\n scipy.savetxt(\"data2p.csv\",data.reshape(1,data.size),delimiter=\",\")\n\n # plt.figure(1, figsize=(4., 2.5), dpi=300, facecolor='w', edgecolor='w')\n # #plt.xlim(min(xList)-0.01, max(xList)+0.01)\n plt.title(\"L={:.1f}, Emax={:.1f}\".format(L,Emax))\n plt.xlabel(r\"$k$\")\n plt.ylabel(r\"$\\psi(k)/g^2$\")\n plt.ylim(min(ydata)-0.01,max(ydata)+0.01)\n plt.xlim(min(klist),max(klist))\n # plt.ylabel(r\"$\\Lambda$\")\n plt.legend(loc='upper right', prop={'size':10})\n plt.savefig(\"wf_L={:.0f}_Emax={:.0f}.{:s}\".format(L,Emax,output))\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"2partWF.py","file_name":"2partWF.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"236810890","text":"# CrunchBase API! #\n# need to download requests (I believe pip install requests)\n# simple get requests to the api.crunchbase site, we can get a lot more info but this is a nice start #\n# To use: get an instance of the class and load the company, after that you can call the other functions to get info #\n\nimport requests, time, json, os, traceback\n##import sys\n\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n\nclass CBHandler:\n ## init the CrunchBase class with our keys ##\n def __init__(self):\n self.APIKey = \"\";\n self.baseURL = \"https://api.crunchbase.com/v/3/\";\n self.properties = None\n self.relationships = None\n self.type = None\n self.uuid = None\n self.current_page = None\n\n\n ## NOTE: I integrated pulling information from specific company json pages along with the overall json\n ## page in this function because through testing with time trails this way was found to extract\n ## data faster than looping through extracting information from the general page and then extracting information\n ## from the company specific pages\n ## This will get all the companies Crunchbase has\n ## todo: add sql commands to add them to the databas\n\n def GetAllCompanies(self, startPage=1):\n num_added = 0\n start_time = time.time()\n last_call = time.time() - 1.8\n page = startPage\n\n #control to only gather competitor information (since Umar is already pulling/has pulled all of the other information)\n #use so as to not have to rewrite code, reducing redundancy etc.\n GetCompetitorsControl = True\n\n self.current_page = requests.get(\"%s/%s?user_key=%s\" % (self.baseURL, \"organizations\", self.APIKey)).json();\n # We need to do this once first to get the total number of pages in crunch bases organizations end point\n pages = self.current_page[\"data\"][\"paging\"][\"number_of_pages\"]\n items_per_page = self.current_page[\"data\"][\"paging\"][\"items_per_page\"]\n\n #use this to make sure we don't excede rate limit\n def fix_call_rate(start_time, cycle_time):\n delta_time = time.time() - start_time\n\n if cycle_time - delta_time >= 0:\n time.sleep(cycle_time-delta_time)\n return time.time()\n else:\n return time.time() + cycle_time - delta_time\n\n\n def GetEmployeeRange(companyPage):\n return {\"num_employees_min\":companyPage[\"data\"][\"properties\"][\"num_employees_min\"], \"num_employees_max\":companyPage[\"data\"][\"properties\"][\"num_employees_max\"]}\n\n def GetCategories(companyPage):\n return companyPage[\"data\"][\"relationships\"][\"categories\"][\"items\"]\n\n\n ## NOTE: will begin to write as if SQL commands are in function, make comments for Umar about each variable etc (get rid of dictionary)\n def GetFundingRoundInfo(companyPage):\n nonlocal last_call\n if companyPage[\"data\"][\"relationships\"][\"funding_rounds\"][\"paging\"][\"total_items\"] == 0:\n return []\n else:\n #list that will hold lists of investors for each of the different rounds of investment\n #can extrapolate all non-duplicate investors for a company from here\n fundingRoundsInfoList = []\n fundingRoundList = companyPage[\"data\"][\"relationships\"][\"funding_rounds\"][\"items\"]\n\n for fundingRound in fundingRoundList:\n apiPath = fundingRound[\"properties\"][\"api_path\"]\n fundingInfo = {}\n\n #get type of round i.e. Series A, Seed etc. --> stored in roundType\n if fundingRound[\"properties\"][\"funding_type\"] == \"venture\" and fundingRound[\"properties\"][\"series\"] != None:\n fundingInfo[\"roundType\"] = \"Series \" + fundingRound[\"properties\"][\"series\"]\n else:\n fundingInfo[\"roundType\"] = fundingRound[\"properties\"][\"funding_type\"].title()\n\n fundingInfo[\"date\"] = fundingRound[\"properties\"][\"announced_on\"]\n fundingInfo[\"amount\"] = fundingRound[\"properties\"][\"money_raised_usd\"]\n\n #generate list of investors\n last_call = fix_call_rate(last_call, 1)\n fundingRoundPage = requests.get(\"%s/%s/investments?user_key=%s\" % (self.baseURL, apiPath, self.APIKey)).json()\n investorList = []\n if fundingRoundPage[\"data\"][\"paging\"][\"total_items\"] == 1:\n investorsInRound = fundingRoundPage[\"data\"][\"item\"]\n if investorsInRound[\"relationships\"][\"investors\"][0][\"type\"] == \"Organization\":\n investorList.append({\"type\":investorsInRound[\"relationships\"][\"investors\"][0][\"type\"], \"name\":investorsInRound[\"relationships\"][\"investors\"][0][\"properties\"][\"name\"]})\n else:\n investorList.append({\"type\":investorsInRound[\"relationships\"][\"investors\"][0][\"type\"], \"name\":investorsInRound[\"relationships\"][\"investors\"][0][\"properties\"][\"first_name\"] + \" \" + investorsInRound[\"relationships\"][\"investors\"][0][\"properties\"][\"last_name\"]})\n elif fundingRoundPage[\"data\"][\"paging\"][\"total_items\"] > 1:\n for investor in fundingRoundPage[\"data\"][\"items\"]:\n for investorActual in investor[\"relationships\"][\"investors\"]: #believe there's only one element in list always but looping just incase\n if investorActual[\"type\"] == \"Organization\":\n investorList.append({\"type\":investorActual[\"type\"], \"name\":investorActual[\"properties\"][\"name\"]})\n else:\n investorList.append({\"type\":investorActual[\"type\"], \"name\":investorActual[\"properties\"][\"first_name\"] + \" \" + investorActual[\"properties\"][\"last_name\"]})\n fundingInfo[\"investors\"] = list({i[\"name\"]:i for i in investorList}.values()) #pick only unique investors\n\n fundingRoundsInfoList.append(fundingInfo)\n\n return fundingRoundsInfoList\n\n\n def GetAcquisitions(companyPage, permaLink):\n nonlocal last_call\n acquisitionList =[]\n\n if companyPage[\"data\"][\"relationships\"][\"acquisitions\"][\"paging\"][\"total_items\"] == 1:\n last_call = fix_call_rate(last_call, 1)\n acquisitionPageOfCompany = requests.get(\"%s/organizations/%s/acquisitions?user_key=%s\" % (self.baseURL, permaLink, self.APIKey)).json()\n acquisitionItem = acquisitionPageOfCompany[\"data\"][\"item\"]\n specificList = {}\n specificList['acquiree'] = acquisitionItem[\"relationships\"][\"acquiree\"][\"properties\"][\"name\"]\n specificList['price'] = acquisitionItem[\"properties\"][\"price_usd\"]\n specificList['payment_type'] = acquisitionItem[\"properties\"][\"payment_type\"]\n specificList['announced_on'] = acquisitionItem[\"properties\"][\"announced_on\"]\n specificList['completed_on'] = acquisitionItem[\"properties\"][\"completed_on\"]\n specificList['acquirer'] = acquisitionItem[\"relationships\"][\"acquirer\"][\"properties\"][\"name\"] #perhaps take permalink?\n acquisitionList.append(specificList)\n\n elif companyPage[\"data\"][\"relationships\"][\"acquisitions\"][\"paging\"][\"total_items\"] > 1:\n last_call = fix_call_rate(last_call, 1)\n acquisitionPageOfCompany = requests.get(\"%s/organizations/%s/acquisitions?user_key=%s\" % (self.baseURL, permaLink, self.APIKey)).json()\n numberOfPages = acquisitionPageOfCompany[\"data\"][\"paging\"][\"number_of_pages\"]\n\n for page in range(1, numberOfPages+1):\n last_call = fix_call_rate(last_call, 1)\n acquisitionPageOfCompany = requests.get(\"%s/organizations/%s/acquisitions?user_key=%s&page=%s\" % (self.baseURL, permaLink, self.APIKey, page)).json()\n\n for acquisitionItem in acquisitionPageOfCompany[\"data\"][\"items\"]:\n specificList = {}\n specificList['acquiree'] = acquisitionItem[\"relationships\"][\"acquiree\"][\"properties\"][\"name\"]\n specificList['price'] = acquisitionItem[\"properties\"][\"price_usd\"]\n specificList['payment_type'] = acquisitionItem[\"properties\"][\"payment_type\"]\n specificList['announced_on'] = acquisitionItem[\"properties\"][\"announced_on\"]\n specificList['completed_on'] = acquisitionItem[\"properties\"][\"completed_on\"]\n specificList['acquirer'] = acquisitionItem[\"relationships\"][\"acquirer\"][\"properties\"][\"name\"] #perhaps take permalink?\n acquisitionList.append(specificList)\n\n return acquisitionList\n\n #returns a list of all of the competitors of the company with permalink permaLink\n #goes hand in hand with GetCompetitorsControl boolean\n def GetCompetitors(companyPage, permaLink):\n nonlocal last_call\n competitorList = []\n\n if companyPage[\"data\"][\"relationships\"][\"competitors\"][\"paging\"][\"total_items\"] == 1:\n last_call = fix_call_rate(last_call, 1)\n competitorPage = requests.get(\"%s/organizations/%s/competitors?user_key=%s\" % (self.baseURL, permaLink, self.APIKey)).json();\n competitorList.append(competitorPage[\"data\"][\"item\"][\"properties\"][\"name\"])\n\n elif companyPage[\"data\"][\"relationships\"][\"competitors\"][\"paging\"][\"total_items\"] > 1:\n last_call = fix_call_rate(last_call, 1)\n competitorPage = requests.get(\"%s/organizations/%s/competitors?user_key=%s\" % (self.baseURL, permaLink, self.APIKey)).json();\n numberOfPages = competitorPage[\"data\"][\"paging\"][\"number_of_pages\"]\n\n for page in range(1, numberOfPages+1):\n last_call = fix_call_rate(last_call, 1)\n competitorPage = requests.get(\"%s/organizations/%s/competitors?user_key=%s&page=%s\" % (self.baseURL, permaLink, self.APIKey, page)).json();\n\n for competitor in competitorPage[\"data\"][\"items\"]:\n competitorList.append(competitor[\"properties\"][\"name\"])\n\n return competitorList\n\n #NOTE: integrating Marco's code here to extract data in bulk\n\n def GetFoundedDate(companyPage):\n return companyPage[\"data\"][\"properties\"][\"founded_on\"]\n\n def GetFounders(companyPage):\n\n founderList = []\n\n for founder in companyPage[\"data\"][\"relationships\"][\"founders\"][\"items\"]:\n founderList.append(founder[\"properties\"][\"first_name\"] + \" \" + founder[\"properties\"][\"last_name\"])\n\n return founderList\n\n def GetNumberFounders(companyPage):\n return len(companyPage[\"data\"][\"relationships\"][\"founders\"][\"items\"])\n\n def GetFunding(companyPage):\n return companyPage[\"data\"][\"properties\"][\"total_funding_usd\"]\n\n # Now we go through every page\n while (page <= pages):\n\n #save page number so we can restart\n fileName = current_dir + \"/page_num.dat\"\n with open(fileName, 'w') as file:\n file.write(str(page))\n\n while (True):\n\n try:\n last_call = fix_call_rate(last_call, 1)\n self.current_page = requests.get(\"%s/%s?user_key=%s&page=%s\" % (self.baseURL, \"organizations\", self.APIKey, page)).json();\n pages = self.current_page[\"data\"][\"paging\"][\"number_of_pages\"]\n except Exception as e:\n traceback.print_exc()\n print(\"%s/%s?user_key=%s&page=%s\" % (self.baseURL, \"organizations\", self.APIKey, page))\n try:\n\n print(self.current_page)\n except:\n print(\"printing current_page page did not work\")\n\n time.sleep(10)\n else:\n break\n\n # Now go through all the companies in the items list\n for company in self.current_page[\"data\"][\"items\"]:\n ## add what ever you want to the database ##\n ## here are some examples of things you can get from this list: ##\n while(True):\n try:\n self.permaLink = company[\"properties\"][\"permalink\"]\n self.organizationType = company[\"properties\"][\"primary_role\"]\n last_call = fix_call_rate(last_call, 1)\n self.companyPage = requests.get(\"%s/%s/%s?user_key=%s\" % (self.baseURL, \"organizations\", self.permaLink, self.APIKey)).json();\n\n #if haven't pulled all companies yet, execute (I know you have, branched just so as to not have to pull the same information again)\n if not GetCompetitorsControl:\n\n company_data = company[\"properties\"]\n company_data[\"Categories\"] = GetCategories(self.companyPage)\n company_data[\"Id\"] = company[\"uuid\"]\n company_data[\"PermaLink\"] = self.permaLink\n company_data[\"Founded\"] = GetFoundedDate(self.companyPage)\n company_data[\"Founders\"] = GetFounders(self.companyPage)\n company_data[\"num_employees\"] = GetEmployeeRange(self.companyPage)\n company_data[\"total_funding\"] = GetFunding(self.companyPage)\n company_data[\"acquisitions\"] = GetAcquisitions(self.companyPage, self.permaLink)\n company_data[\"funding_rounds\"] = GetFundingRoundInfo(self.companyPage)\n\n #not sure if a dictionary and this format is the most efficient method of extracting the data for you, but it's what came to mind\n companyCompetitors = {}\n companyCompetitors[company[\"properties\"][\"name\"]] = GetCompetitors(self.companyPage, self.permaLink)\n\n num_added += 1\n rate = '{:.0f}'.format(num_added/(time.time()-start_time)*3600) + \"/hour\"\n percent = '{:>10}'.format('{:.0f}'.format(100*page/pages) + \"%\")\n\n #same idea as first 'if not' above\n if not GetCompetitorsControl:\n status = str(num_added) + \". Added \" + str(company_data['name'])\n\n status = str(num_added) + \". Added \" + str(company[\"properties\"][\"name\"])\n\n with open(current_dir + \"/companies.dat\", 'a') as file:\n\n #same idea as first 'if not' above\n if not GetCompetitorsControl:\n file.write(json.dumps(company_data, separators=(',', ':')) + \"\\n\")\n\n file.write(json.dumps(companyCompetitors, separators=(',', ':')) + \"\\n\")\n try:\n print ('{:<100}'.format(status) + \" \" + rate + percent)\n except Exception as e:\n print (e)\n print (\"Name has unsupported chars so can't print to screen.\")\n print (\"Don't worry its been added to the file anyway\")\n\n except Exception as e:\n traceback.print_exc()\n print(\"%s/%s/%s?user_key=%s\" % (self.baseURL, \"organizations\", self.permaLink, self.APIKey))\n try:\n print(self.companyPage)\n except:\n print(\"printing company page did not work\")\n\n time.sleep(10)\n else:\n break\n page +=1\n\n\n def LoadCompany(self, company):\n current_company = requests.get(\"%s/%s/%s?user_key=%s\" % (self.baseURL, \"organizations\", company, self.APIKey)).json()\n self.properties = current_company[\"data\"][\"properties\"]\n self.relationships = current_company[\"data\"][\"relationships\"]\n self.type = current_company[\"data\"][\"type\"]\n self.uuid = current_company[\"data\"][\"uuid\"]\n return\n\n def GetName(self):\n return self.properties[\"name\"]\n\n\n def GetType(self):\n return self.type\n\n\n def GetUUID(self):\n return self.uuid\n\n\n def GetSiteUrl(self, site): #apparently not needed since can parse from json file with all companies...\n\n for item in self.relationships[\"websites\"][\"items\"]:\n\n if item[\"properties\"][\"website_type\"] == site:\n return item[\"properties\"][\"url\"]\n\n return \"n/a\"\n\n\n# EXAMPLE OF HOW I USE GET ALL COMPANIES #\nif __name__ == \"__main__\":\n print(\"Finding All Companies!\")\n myHandle = CBHandler()\n myHandle.GetAllCompanies(1)\n print(\"done.\")\n\n# EXAMPLE OF HOW I USE LOAD COMPANY #\n#\n# if __name__ == \"__main__\":\n# print(\"Start\")\n# myHandle = CBHandler()\n#\n# while True:\n# n = input(\"Search User!\\n\")\n# try:\n# myHandle.LoadCompany(n)\n# print(\"Name:\", myHandle.GetName())\n# print(\"Type:\", myHandle.GetType())\n# print(\"UUID:\", myHandle.GetUUID())\n# print(\"Founded Date:\", myHandle.GetFoundedDate())\n# print(\"Number of Founders:\", myHandle.GetNumberFounders())\n# print(\"All Founders:\", myHandle.GetFounders())\n# print(\"Funding:\", myHandle.GetFunding())\n# print(\"Website:\", myHandle.GetSiteUrl(\"homepage\"))\n# print(\"Twitter:\", myHandle.GetSiteUrl(\"twitter\"))\n# print(\"Facebook:\", myHandle.GetSiteUrl(\"facebook\"))\n# print(\"Linkedin:\", myHandle.GetSiteUrl(\"linkedin\"))\n# print(\"Employee Range:\", myHandle.GetEmployeeRange())\n# except Exception as e:\n# print(\"Error:\", e)\n","sub_path":"CrunchBaseAPI.py","file_name":"CrunchBaseAPI.py","file_ext":"py","file_size_in_byte":18275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"454693999","text":"# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nimport os\nfrom azure.cli.testsdk import ScenarioTest\nfrom azure.cli.testsdk import ResourceGroupPreparer\nfrom .example_steps import step_private_link_resource_list\nfrom .example_steps import step_private_link_scope_create\nfrom .example_steps import step_private_link_scope_update\nfrom .example_steps import step_private_link_scope_show\nfrom .example_steps import step_private_link_scope_list\nfrom .example_steps import step_private_link_scope_list2\nfrom .example_steps import step_private_link_scope_update_tag\nfrom .example_steps import step_private_endpoint_connection_update\nfrom .example_steps import step_private_endpoint_connection_list\nfrom .example_steps import step_private_endpoint_connection_show\nfrom .example_steps import step_private_endpoint_connection_delete\nfrom .example_steps import step_private_link_scope_delete\nfrom .. import (\n try_manual,\n raise_if,\n calc_coverage\n)\n\n\nTEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))\n\n\n# Env setup_scenario\n@try_manual\ndef setup_scenario(test):\n pass\n\n\n# Env cleanup_scenario\n@try_manual\ndef cleanup_scenario(test):\n pass\n\n\ndef test_private_link(test):\n rand_string = test.create_random_name('', 5)\n test.kwargs.update({\n 'machine': 'testMachine',\n 'rg': 'az-sdk-test-' + rand_string,\n 'scope': 'scope-' + rand_string,\n 'vnet': 'vnet-' + rand_string,\n 'subnet': 'subnet-' + rand_string,\n 'private_endpoint': 'pe-' + rand_string,\n 'private_endpoint_connection': 'pec-' + rand_string,\n 'location': 'eastus2euap',\n 'customScriptName': 'custom-' + rand_string,\n })\n\n # Prepare network\n test.cmd('az group create -n {rg} -l {location}',\n checks=test.check('name', '{rg}'))\n\n # Prepare network\n test.cmd('az network vnet create -n {vnet} -g {rg} -l {location} --subnet-name {subnet}',\n checks=test.check('length(newVNet.subnets)', 1))\n test.cmd('az network vnet subnet update -n {subnet} --vnet-name {vnet} -g {rg} '\n '--disable-private-endpoint-network-policies true',\n checks=test.check('privateEndpointNetworkPolicies', 'Disabled'))\n\n # Create a private link scope\n test.cmd('az connectedmachine private-link-scope create '\n '--location \"{location}\" '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[\n test.check('name','{scope}'),\n test.check('properties.publicNetworkAccess','Disabled')\n ])\n\n # Update the private link scope\n test.cmd('az connectedmachine private-link-scope update '\n '--location \"{location}\" '\n '--tags Tag1=\"Value1\" '\n '--public-network-access Enabled '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[\n test.check('name','{scope}'),\n test.check('properties.publicNetworkAccess','Enabled')\n ])\n\n # Test private link scope list \n test.cmd('az connectedmachine private-link-scope list '\n '--resource-group \"{rg}\"',\n checks=[\n test.check('length(@)', 1)\n ])\n\n # Private link scope update tag\n test.cmd('az connectedmachine private-link-scope update-tag '\n '--tags Tag1=\"Value1\" Tag2=\"Value2\" '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[\n test.check('length(tags)', 2)\n ])\n\n # Private link scope show\n private_link_scope = test.cmd('az connectedmachine private-link-scope show --scope-name {scope} -g {rg}').get_output_in_json()\n test.kwargs['scope_id'] = private_link_scope['id']\n\n # Test private link resource list\n test.cmd('az connectedmachine private-link-resource list --scope-name {scope} -g {rg}', checks=[\n test.check('length(@)', 1)\n ])\n\n result = test.cmd('az network private-endpoint create -g {rg} -n {private_endpoint} --vnet-name {vnet} --subnet {subnet} --private-connection-resource-id {scope_id} '\n '--connection-name {private_endpoint_connection} --group-id hybridcompute').get_output_in_json()\n test.assertTrue(test.kwargs['private_endpoint'].lower() in result['name'].lower())\n\n connection_list = test.cmd('az connectedmachine private-endpoint-connection list '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"').get_output_in_json()\n test.kwargs['private_endpoint_connection_name'] = connection_list[0]['name']\n\n test.cmd('az connectedmachine private-endpoint-connection update '\n '--connection-state description=\"Rejected by AZ CLI test\" status=\"Rejected\" '\n '--name \"{private_endpoint_connection_name}\" '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[\n test.check('name', '{private_endpoint_connection_name}'),\n test.check('properties.privateLinkServiceConnectionState.description', 'Rejected by AZ CLI test'),\n test.check('properties.privateLinkServiceConnectionState.status', 'Rejected')\n ])\n\n test.cmd('az connectedmachine private-endpoint-connection show '\n '--name \"{private_endpoint_connection_name}\" '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[\n test.check('name', '{private_endpoint_connection_name}'),\n test.check('properties.privateLinkServiceConnectionState.description', 'Rejected by AZ CLI test'),\n test.check('properties.privateLinkServiceConnectionState.status', 'Rejected')\n ])\n \n test.cmd('az connectedmachine private-endpoint-connection delete -y '\n '--name \"{private_endpoint_connection_name}\" '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[])\n \n test.cmd('az connectedmachine private-endpoint-connection list '\n '--resource-group \"{rg}\" '\n '--scope-name \"{scope}\"',\n checks=[\n test.check('length(@)', 0)\n ])\n \n\n# Testcase: Scenario\n@try_manual\ndef call_scenario(test):\n setup_scenario(test)\n test_private_link(test)\n cleanup_scenario(test)\n\n\n# Test class for Scenario\n@try_manual\nclass PrivateLinkAndPrivateEndpointConnectionScenarioTest(ScenarioTest):\n def __init__(self, *args, **kwargs):\n super(PrivateLinkAndPrivateEndpointConnectionScenarioTest, self).__init__(*args, **kwargs)\n def test_PrivateLinkAndPrivateEndpointConnection_Scenario(self):\n call_scenario(self)\n calc_coverage(__file__)\n raise_if()\n","sub_path":"src/connectedmachine/azext_connectedmachine/tests/latest/test_PrivateLinkAndPrivateEndpointConnection_scenario.py","file_name":"test_PrivateLinkAndPrivateEndpointConnection_scenario.py","file_ext":"py","file_size_in_byte":7214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"286670276","text":"import logging\nfrom Database.db_connector import connection_object\nimport logging\nlog = logging.getLogger(__name__)\n\n\ndef insert(name, category, etime, quantity, mtime, sname):\n try:\n connection = connection_object()\n with connection.cursor() as cursor:\n sql = 'insert into inventory_data(Name, Category, expire_time, Quantity, manufacturing_date, image) values(%s, %s, %s, %s, %s, %s)'\n cursor.execute(sql, (name, category, etime, quantity, mtime, sname))\n logging.info(name)\n connection.commit()\n return \"Done\"\n except Exception as e:\n log.warning(e)\n log.warning(\"error in sql in insert \")\n\n\n","sub_path":"inventory/Database/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"554350071","text":"__AUTHOR__ = 'Reverier Xu'\n\nimport re\n\nproperties = {\n 'name': '小端序拆分',\n 'categories': '二进制工具',\n 'input': {0: '输入'},\n 'output': {0: '拆分结果'},\n 'properties': {\n '前缀': str,\n '单位长度': str\n }\n}\n\ndefaults = {\n '前缀': '0x',\n '单位长度': '2'\n}\n\n\ndef main(inp, settings):\n forehead = settings['前缀']\n step = int(settings['单位长度'])\n inputs = inp[0]\n if len(inputs) % 2 != 0:\n inputs = '0' + inputs\n inputs = cut_text(inputs, step)\n out = ''\n inputs.reverse()\n for i in inputs:\n out += forehead + i\n return {0: out}\n\n\ndef cut_text(text, length):\n text_arr = re.findall('.{' + str(length) + '}', text)\n text_arr.append(text[(len(text_arr) * length):])\n return text_arr\n","sub_path":"Modules/DataFlow/LittleEndianTranslateModule.py","file_name":"LittleEndianTranslateModule.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"49583492","text":"\"\"\"\n\n\tDesc: Bot to crawl onto linkedin and send out invitations to\n\t\t users based on search criteria. To be used for educational\n\t\t purposes when developing crawlers dealing with hidden elements.\n\"\"\"\n# sound\nimport subprocess\nimport time\n\nimport numpy as np\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom bs4 import BeautifulSoup\nimport requests\n\nimport re\n\n# GLOBAL VALUES USED IN SCRIPT\n#url = \"https://www.welcometothejungle.com/fr/jobs#signin?ref=header\"\nurl = \"https://www.welcometothejungle.com/fr/jobs?page=1&configure%5Bfilters%5D=website.reference%3Awttj_fr&configure%5BhitsPerPage%5D=30&aroundQuery=France&refinementList%5Boffice.country_code%5D%5B%5D=FR&refinementList%5Bcontract_type_names.fr%5D%5B%5D=CDI&refinementList%5Bcontract_type_names.fr%5D%5B%5D=Stage&query=%22data%20analyst%22&range%5Bexperience_level_minimum%5D%5Bmin%5D=0&range%5Bexperience_level_minimum%5D%5Bmax%5D=1\"\nurl_2 = 'https://www.welcometothejungle.com/fr/companies/kapten/jobs/data-analyst-h-f-cdi-paris_levallois-perret_KAPTE_8m2plWg'\nbase_search_URL = 'https://www.welcometothejungle.com/fr/jobs?query=%22Data%20Analyst%22'\n\n\n# SCRAPPER CLASS AND IT'S METHODS\nclass WTTScrapper():\n\n def __init__(self):\n '''Init bot'''\n self.driver = webdriver.Chrome(ChromeDriverManager().install())\n self.driver.wait = WebDriverWait(self.driver, 1)\n\n\n def MainPage(self):\n '''Go the the first page'''\n self.driver.get(url)\n\n def Click(self, pos):\n '''Click on the link'''\n self.driver.find_elements_by_class_name(\"ais-Hits-item\")[pos].click()\n\n def GetText(self):\n #data = self.driver.page_source\n data = requests.get(self.driver.current_url)\n #data = requests.get(\"https://www.welcometothejungle.com/fr/companies/jellysmack/jobs/data-analyst-h-f-corse_corte\")\n soup = BeautifulSoup(data.text, 'html.parser',from_encoding=\"utf-8\")\n h1 = soup.find(\"div\", {\"class\": \"sc-11obzva-1 czRmi\"})\n h2 = h1.findAll(\"div\", {\"class\": \"sc-11obzva-1 czRmi\"})\n h3 = h2[2]\n f = open('results.txt', 'a')\n f.write(h3.get_text())\n f.write('\\n')\n f.close()\n\nL = WTTScrapper()\nL.MainPage()\nL.Click(1)\nL.GetText()","sub_path":"old/WTT_bot.py","file_name":"WTT_bot.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"488722342","text":"import sublime, sublime_plugin\nimport os, sys, re\n\n# import modules in current directory\ndist_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, dist_dir)\n\n# Python 2/3 compatible\nimport chardet, pystache\n\ntry:\n\t# Python 3 (ST3)\n\tfrom urllib.request import Request, urlopen\n\tfrom urllib.error import URLError\n\tfrom urllib.parse import urlencode\nexcept ImportError:\n\t# Python 2 (ST2)\n\tfrom urllib2 import Request, URLError, urlopen\n\tfrom urllib import urlencode\n\ndef preemptive_imports():\n\t\"\"\" needed to ensure ability to import these classes later within functions, due to the way ST2 loads plug-in modules \"\"\"\n\tfrom chardet import universaldetector\npreemptive_imports()\n\nclass LookupWithGoogleAndLinkCommand(sublime_plugin.TextCommand):\n\n\tdef get_link_with_title(self, phrase):\n\t\ttry:\n\t\t\turl = \"http://www.google.com/search?%s&btnI=I'm+Feeling+Lucky\" % urlencode({'q': phrase})\n\t\t\treq = Request(url, headers={'User-Agent' : \"Sublime Text 2 Hyperlink Helper\"})\n\t\t\tf = urlopen(req)\n\t\t\turl = f.geturl()\n\t\t\tcontent = f.read()\n\t\t\tdecoded_content = content.decode(chardet.detect(content)['encoding'])\n\t\t\ttitle = re.search(r\"([^<>]*)\", decoded_content, re.I).group(1)\n\t\t\ttitle = title.strip()\n\t\t\treturn url, title, phrase\n\t\texcept URLError as e:\n\t\t\tsublime.error_message(\"Error fetching Google search result: %s\" % str(e))\n\t\t\treturn None\n\n\tdef run(self, edit):\n\t\tnonempty_sels = []\n\n\t\t# set aside nonempty selections\n\t\tfor s in reversed(self.view.sel()):\n\t\t\tif not s.empty():\n\t\t\t\tnonempty_sels.append(s)\n\t\t\t\tself.view.sel().subtract(s)\n\n\t\t# expand remaining (empty) selections to words\n\t\tself.view.run_command(\"expand_selection\", {\"to\": \"word\"})\n\n\t\t# add nonempty selections back in\n\t\tfor s in nonempty_sels:\n\t\t\tself.view.sel().add(s)\n\t\t\n\t\t# apply the links\n\t\tfor s in reversed(self.view.sel()):\n\t\t\tif not s.empty():\n\t\t\t\ttxt = self.view.substr(s)\n\t\t\t\tlink = self.get_link_with_title(txt)\n\t\t\t\tif not link:\n\t\t\t\t\tcontinue\n\t\t\t\tself.view.replace(edit, s, pystache.render(self.view.settings().get('hyperlink_helper_link_format'), {'url': link[0], 'title?': {'title': link[1]}, 'input': link[2]}))\n","sub_path":"lookup_with_google_and_link.py","file_name":"lookup_with_google_and_link.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"515011732","text":"from io import BytesIO, StringIO\n\n\ndef encode(string, binary):\n return string.encode() if binary else string\n\n\ndef tofile(arr, f, binary=True, sep=\"\"):\n if binary:\n if isinstance(f, BytesIO):\n f.write(arr.tobytes())\n else:\n arr.tofile(f, sep=sep)\n\n else:\n if isinstance(f, StringIO):\n f.write(\" \".join(str(x) for x in arr.ravel()))\n else:\n arr.tofile(f, sep=sep)\n","sub_path":"src/meshio/vtk/_common.py","file_name":"_common.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"281348958","text":"# -*- coding: UTF-8 -*- \nimport urllib.request, http.client, json, time, datetime\nimport os\nimport settings\nimport django\nimport sys\nimport time\nimport tushare as ts\nfrom dateutil.relativedelta import relativedelta\n# 300875\n# CJMZQXCYQMHPKLNP\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nos.environ['DJANGO_SETTINGS_MODULE'] = 'gjsicence.settings' \ndjango.setup()\n\nfrom server.models import Stock, FinancialStatement, IncomeStatement, BalanceStatement, CashFlowStatement, FinancialAnalytical\ntarget_date_list = [\"20151231\", \"20161231\", \"20171231\", \"20181231\", \"20191231\",]\ndate_list = [\"20111231\",\"20121231\",\"20131231\",\"20141231\",\"20151231\", \"20161231\", \"20171231\", \"20181231\", \"20191231\", ]\nstock_list = Stock.objects.all()\n\nfor stock in stock_list:\n\tprint(stock.symbol)\n\tsymbol = stock.symbol\n\t# symbol = \"002567\"\n\tres = FinancialAnalytical.objects.filter(\n\t\tstock_code=symbol,\n\t\t# publish_date=datetime.datetime(int(target[0:4]), int(target[4:6]), int(target[6:8]))\n\t)\n\tif res.exists():\n\t\tana_data = CashFlowStatement.objects.filter(\n\t\t\tstock_code=symbol,\n\t\t\t# publish_date=datetime.datetime(int(date[0:4]), int(date[4:6]), int(date[6:8]))\n\t\t)\n\t\tfor r in res:\n\t\t\tpub_date = r.publish_date\n\t\t\tprint(pub_date)\n\t\t\tsum_act = 0\n\t\t\tsum_pay = 0\n\t\t\tinventories_start = 0\n\t\t\tinventories_end = 0\n\t\t\tfor i in range(0, 5):\n\t\t\t\tcash_statement = CashFlowStatement.objects.filter(\n\t\t\t\t\tstock_code=symbol,\n\t\t\t\t\tpublish_date=pub_date - relativedelta(years=i)\n\t\t\t\t)\n\t\t\t\t\n\t\t\t\tcash_statement = cash_statement[0]\n\t\t\t\tcash_data = json.loads(json.loads(cash_statement.statement_content))\n\t\t\t\ttry:\n\t\t\t\t\tn_cashflow_act = cash_data[\"n_cashflow_act\"][\"0\"] if cash_data[\"n_cashflow_act\"][\"0\"] else 0\n\t\t\t\t\tc_pay_acq_const_fiolta = cash_data[\"c_pay_acq_const_fiolta\"][\"0\"] if cash_data[\"c_pay_acq_const_fiolta\"][\"0\"] else 0\n\t\t\t\t\tn_recp_disp_fiolta = cash_data[\"n_recp_disp_fiolta\"][\"0\"] if cash_data[\"n_recp_disp_fiolta\"][\"0\"] else 0\n\t\t\t\t\tif i == 0:\n\t\t\t\t\t\tbalance_statement = BalanceStatement.objects.filter(\n\t\t\t\t\t\t\tstock_code=symbol,\n\t\t\t\t\t\t\tpublish_date=pub_date - relativedelta(years=i)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif balance_statement:\n\t\t\t\t\t\t\tinventories_end = json.loads(json.loads(balance_statement[0].statement_content))[\"inventories\"][\"0\"]\n\t\t\t\t\t\t\tinventories_end = inventories_end if inventories_end else 0\n\t\t\t\t\tif i == 4:\n\t\t\t\t\t\tbalance_statement = BalanceStatement.objects.filter(\n\t\t\t\t\t\t\tstock_code=symbol,\n\t\t\t\t\t\t\tpublish_date=pub_date - relativedelta(years=i)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif balance_statement:\n\t\t\t\t\t\t\tinventories_start = json.loads(json.loads(balance_statement[0].statement_content))[\"inventories\"][\"0\"]\n\t\t\t\t\t\t\tinventories_start = inventories_start if inventories_start else 0\n\t\t\t\t\t# decr_inventories = cash_data[\"decr_inventories\"][\"0\"]\n\t\t\t\t\tc_pay_dist_dpcp_int_exp = cash_data[\"c_pay_dist_dpcp_int_exp\"][\"0\"] if cash_data[\"c_pay_dist_dpcp_int_exp\"][\"0\"] else 0\n\t\t\t\t\tsum_act += (n_cashflow_act)\n\t\t\t\t\tsum_pay += (c_pay_acq_const_fiolta - n_recp_disp_fiolta + c_pay_dist_dpcp_int_exp)\t\n\t\t\t\texcept KeyError:\n\t\t\t\t\tcontinue\n\t\t\tscore_data = FinancialStatement.objects.filter(\n\t\t\t\tstock_code=symbol,\n\t\t\t\tpublish_date=pub_date\n\t\t\t)\n\t\t\t\n\t\t\tscore_data = FinancialStatement.objects.filter(\n\t\t\t\tstock_code=symbol,\n\t\t\t\tpublish_date=pub_date\n\t\t\t)\n\t\t\t\n\t\t\tROIC_score = score_data[0].ROIC_score\n\t\t\tROA_score = score_data[0].ROA_score\n\t\t\tEM_score = score_data[0].EM_score\n\t\t\tcash_flow_score = score_data[0].cash_flow_score\n\t\t\tdept_paying_score = score_data[0].dept_paying_score\n\t\t\t\n\t\t\tr.cash_adequancy_ratio = sum_act / (sum_pay + inventories_end - inventories_start)\n\t\t\tr.roic_score = ROIC_score\n\t\t\tr.roa_score = ROA_score\n\t\t\tr.em_score = EM_score\n\t\t\tr.cash_flow_score = cash_flow_score\n\t\t\tr.dept_paying_score = r.dept_paying_score\n\t\t\tr.save()\n\n\t\t\n\t\t","sub_path":"gjsicence/yundang.py","file_name":"yundang.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"492529644","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('defcdb', '0034_auto_20161220_1254'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='area',\n name='settlement_construction_shape',\n field=models.ManyToManyField(verbose_name='Settlement building shape', blank=True, to='defcdb.DC_area_constructionshape', help_text='Shape of the building.'),\n ),\n migrations.AlterField(\n model_name='area',\n name='settlement_construction_type',\n field=models.ManyToManyField(verbose_name='Settlement building type', blank=True, to='defcdb.DC_area_constructiontype', help_text='Method used for fabricating the buildings.'),\n ),\n ]\n","sub_path":"defcdb/migrations/0035_auto_20171102_1012.py","file_name":"0035_auto_20171102_1012.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"476945233","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 29 19:58:42 2020\n\n@author: Philippine\n\"\"\"\n\nfrom scipy.io import wavfile\nimport numpy as np\n\ndelta = 44100 #fréquence d'échantillonnage\n\n#Question e\n\ndef s1(t): #La440\n return(np.sin(2*np.pi*440*t))\n \ndef s2(t): #Si un ton plus haut que le La440\n return(np.sin(2*np.pi*440*2**(1/6)*t))\n\ndef s(t): #Signal non fondu\n return(s1(t)+s2(t))\n\ndef a(t): \n if 0<=t<=1:\n return(t)\n else:\n return(1)\n\ndef s_mix(t): #signal fondu au début\n return(a(t)*(s1(t)+s2(t)))\n \ndef u_mix(v,maximum, minimum): #fonction pour renvoyer des entiers quand on code en 16 bits signés\n a =((2**16)-1)/(maximum-minimum)\n b = -(a/2)*(maximum+minimum)-1/2\n return (int(a*v+b)) \n\ndef remplissage_array_mix_mono(sig,freq_ech,t,recadrage):\n data=np.ndarray((freq_ech*t,),dtype=np.int16)\n signaux = []\n for step in range(freq_ech*t): \n temps=step/freq_ech\n signal=sig(temps)\n signaux.append(signal)\n minimum=min(signaux)\n maximum=max(signaux)\n i=0\n for signal in signaux:\n data[i]=recadrage(signal,maximum, minimum)\n i+=1\n return(data)\n\ndata_mix_mono_fondu = remplissage_array_mix_mono(s_mix,delta,3,u_mix) \n\nwavfile.write('LaSiMonoFonduDeb.wav',delta,data_mix_mono_fondu) #création du fichier wav 'LaSiMonoFonduDeb.wav', en fréquence 44100, pendant 3 secondes\n\n#Question f\n\ndef param(wav_fname): #Fonction permettant de rendre la fréquence d'échantillonnage et\n samplerate, data = wavfile.read(wav_fname) #la durée d'un fichier .wav ainsi que le tableau de nombre associé\n d = data.shape[0] / samplerate\n return(samplerate,d,data)\n\n\n#Question g\n \ndef amplitude_fondu_fin(t,d): #Fonction amplitude permettant de diminuer le volume du signal d'entrée sur la dernière seconde \n if 0<=t<=d-1:\n return(1)\n else:\n return(d-t)\n \ndef data_modif(file): #Fonction modifiant le signal d'entré (vecteur de nombre) pour le fondre sur la dernière seconde\n samplerate, d, data = param(file)\n fondue = np.ndarray((samplerate*int(d),),dtype = np.int16)\n for i in range(samplerate*int(d)):\n fondue[i] = data[i] * amplitude_fondu_fin(i/samplerate,d)\n return(fondue)\n \nfile = 'LaSiMono.wav' #fichier à lire puis 'fondre'\ndata_fondu = data_modif(file)\n\nwavfile.write('LaSiMonoFonduFin.wav',delta,data_fondu) #création du fichier wav 'LaSiMonoFonduFin.wav', en fréquence 44100\n #pendant 3 secondes (temps du fichier en entrée)\n","sub_path":"TP2_wav_son_modif/TP2_ex1_suite.py","file_name":"TP2_ex1_suite.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"157885000","text":"# Задание-2:\n# Напишите функцию, округляющую полученное произвольное десятичное число\n# до кол-ва знаков (кол-во знаков передается вторым аргументом).\n# Округление должно происходить по математическим правилам (0.6 --> 1, 0.4 --> 0).\n# Для решения задачи не используйте встроенные функции и функции из модуля math.\ndef my_round(number, digits):\n n_dig = int(digits)\n x = 10 ** n_dig\n str_num = str(number * x)\n if len(str_num) >= n_dig:\n a = int(str_num[-2])\n b = int(str_num[-1])\n if a >= 5:\n str_num = int(number * x + 1)\n int_num = str_num / x\n if a < 5:\n if b >= 5:\n str_num = int(number * x + 1)\n int_num = str_num / x\n if b < 5:\n str_num = int(number * x)\n int_num = str_num / x\n\n return int_num\n\n\nprint(my_round(2.1234567, 5))\nprint(my_round(2.1999967, 5))\nprint(my_round(2.9999967, 5))","sub_path":"home_work1.3/easy2.py","file_name":"easy2.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"601342285","text":"from __future__ import unicode_literals\nfrom prompt_toolkit.buffer import Buffer\nfrom prompt_toolkit.application.current import get_app\nfrom prompt_toolkit.search_state import SearchState\nfrom prompt_toolkit.document import Document\nfrom prompt_toolkit.enums import SearchDirection\n\n\nclass ModalBuffer(Buffer):\n last_working_index = -1\n last_search_direction = None\n last_search_history = None\n search_history = []\n\n def _change_prompt_mode(self, index, redraw=True):\n if index < len(self.history.modes):\n app = get_app()\n if app.mp.prompt_mode in app.mp.top_level_modes:\n mode = self.history.modes[index]\n if mode and mode in app.mp.top_level_modes:\n app.mp.prompt_mode = mode\n if redraw:\n app._redraw()\n\n def _is_end_of_buffer(self):\n return self.cursor_position == len(self.text)\n\n def _is_last_history(self):\n return self.working_index == len(self._working_lines) - 1\n\n def reset(self, document=None, append_to_history=False):\n self.last_search_history = None\n self.search_history = []\n super(ModalBuffer, self).reset(document, append_to_history)\n\n def history_forward(self, count=1):\n if len(self.text) == 0 and self._is_last_history() and self.last_working_index >= 0:\n self.go_to_history(self.last_working_index)\n self.history_search_text = \"\"\n self.last_working_index = -1\n\n super(ModalBuffer, self).history_forward(count)\n self._change_prompt_mode(self.working_index)\n\n def history_backward(self, count=1):\n super(ModalBuffer, self).history_backward(count)\n self._change_prompt_mode(self.working_index)\n\n def _search(self, search_state, include_current_position=False, count=1):\n \"\"\"\n A clone of the original _search function from prompt_toolkit with\n history_search_no_duplicates enhancement.\n \"\"\"\n assert isinstance(search_state, SearchState)\n assert isinstance(count, int) and count > 0\n\n text = search_state.text\n direction = search_state.direction\n ignore_case = search_state.ignore_case()\n\n # modified by rice\n if direction != self.last_search_direction:\n self.last_search_history = None\n self.search_history = []\n\n # modified by rice\n no_duplicates = get_app().mp.history_search_no_duplicates and count == 1\n\n def search_once(working_index, document):\n \"\"\"\n Do search one time.\n Return (working_index, document) or `None`\n \"\"\"\n if direction == SearchDirection.FORWARD:\n # Try find at the current input.\n new_index = document.find(\n text, include_current_position=include_current_position,\n ignore_case=ignore_case)\n\n if new_index is not None:\n return (working_index,\n Document(document.text, document.cursor_position + new_index))\n else:\n # No match, go forward in the history. (Include len+1 to wrap around.)\n # (Here we should always include all cursor positions, because\n # it's a different line.)\n for i in range(working_index + 1, len(self._working_lines) + 1):\n i %= len(self._working_lines)\n\n # modified by rice\n if not no_duplicates or self._working_lines[i] not in self.search_history:\n document = Document(self._working_lines[i], 0)\n new_index = document.find(text, include_current_position=True,\n ignore_case=ignore_case)\n if new_index is not None:\n return (i, Document(document.text, new_index))\n else:\n # Try find at the current input.\n new_index = document.find_backwards(\n text, ignore_case=ignore_case)\n\n if new_index is not None:\n return (working_index,\n Document(document.text, document.cursor_position + new_index))\n else:\n # No match, go back in the history. (Include -1 to wrap around.)\n for i in range(working_index - 1, -2, -1):\n i %= len(self._working_lines)\n\n # modified by rice\n if not no_duplicates or self._working_lines[i] not in self.search_history:\n document = Document(self._working_lines[i], len(self._working_lines[i]))\n new_index = document.find_backwards(\n text, ignore_case=ignore_case)\n if new_index is not None:\n return (i, Document(document.text, len(document.text) + new_index))\n\n # Do 'count' search iterations.\n working_index = self.working_index\n document = self.document\n for _ in range(count):\n result = search_once(working_index, document)\n if result:\n working_index, document = result\n\n # modified by rice\n if result:\n working_index, document = result\n self.last_search_direction = direction\n self.last_search_history = self._working_lines[working_index]\n self._change_prompt_mode(result[0], redraw=False)\n return (working_index, document.cursor_position)\n else:\n self.last_search_direction = None\n self.last_search_history = None\n self.search_history = []\n return None\n\n def apply_search(self, *args, **kwargs):\n super(ModalBuffer, self).apply_search(*args, **kwargs)\n if self.last_search_history and self.last_search_history not in self.search_history:\n self.search_history.append(self.last_search_history)\n\n def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n if not self._is_last_history() and self._is_end_of_buffer():\n self.history_backward()\n self.cursor_position = len(self.text)\n else:\n super(ModalBuffer, self).auto_up(count, go_to_start_of_line_if_history_changes)\n\n def auto_down(self, count=1, go_to_start_of_line_if_history_changes=False):\n if not self._is_last_history() and self._is_end_of_buffer():\n self.history_forward()\n self.cursor_position = len(self.text)\n else:\n super(ModalBuffer, self).auto_down(count, go_to_start_of_line_if_history_changes)\n\n def append_to_history(self):\n app = get_app()\n if app.mp.add_history:\n mode = app.mp.prompt_mode\n if self.text and \\\n (not len(self.history) or self.history[-1] != self.text or\n mode != self.history.modes[-1]):\n self.history.append(self.text)\n","sub_path":"rice/modalbuffer.py","file_name":"modalbuffer.py","file_ext":"py","file_size_in_byte":7171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"8974921","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 3 16:40:58 2016\n\n@author: ben\n\nNumber of routes: 1366\nTime: Time: 0.0003 seconds\n\n\"\"\"\n\n\n\nimport time\nimport math\nimport numpy\n\nstart = time.time()\n\ndef sum_digits(n):\n s = 0\n while n:\n s += n % 10\n n //= 10\n return s\n\na = 2**1000\na = sum_digits(a)\n\n \nprint(\"Number of routes: \" + str(a))\n\nelapsed = (time.time() - start) \nprint(\"Time: \" + str(round(elapsed,4)) + \" seconds\")\n","sub_path":"p16.py","file_name":"p16.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"45066516","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport datetime\n\nfrom django.conf.urls import patterns, include, url\n\nfrom .views import Calendar\nfrom .views import TagCreate, TagDelete\nfrom .views import EventCreate, EventDetail, EventUpdate, EventDelete\nfrom .views import EventPageCreate, EventPageDetail, EventPageUpdate, EventPageDelete\n\n\nurlpatterns = patterns(\n '',\n # Calendar\n url(r'^$', Calendar.as_view(),\n {'year': str(datetime.datetime.now().year), 'month': str(datetime.datetime.now().month)},\n name='calendar_base'),\n url(r'^(?P\\d+)-(?P\\d+)/$', Calendar.as_view(), name='calendar'),\n\n # Tag\n url(r'^tag/create/$', TagCreate.as_view(), name='tag_create'),\n url(r'^tag/(?P\\d+)/delete/$', TagDelete.as_view(), name='tag_delete'),\n\n # Event\n url(r'^event/create/$', EventCreate.as_view(), name='event_create'),\n url(r'^event/(?P\\d+)/$', EventDetail.as_view(), name='event_detail'),\n url(r'^event/(?P\\d+)/update/$', EventUpdate.as_view(), name='event_update'),\n url(r'^event/(?P\\d+)/delete/$', EventDelete.as_view(), name='event_delete'),\n\n # Event page\n url(r'^events/(?P[-\\w]+)/$', EventPageDetail.as_view(), name='eventpage_detail'),\n url(r'^eventpage/create/$', EventPageCreate.as_view(), name='eventpage_create'),\n url(r'^eventpage/(?P\\d+)/update/$', EventPageUpdate.as_view(), name='eventpage_update'),\n url(r'^eventpage/(?P\\d+)/delete/$', EventPageDelete.as_view(), name='eventpage_delete'))\n","sub_path":"EinVerCMS/calendarevent/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"420997082","text":"# -*- coding: utf-8 -*-\nimport os\nimport requests\nfrom flask import Blueprint, current_app, g, jsonify\n# from .. import tbclient\n\nmain = Blueprint('main', __name__)\n\n\n@main.before_request\ndef before():\n g.version = current_app.config['version']\n g.tensorboard_folder = current_app.config['tensorboard_folder']\n g.tensorboard_url = current_app.config['tensorboard_url']\n\n\n@main.route(\"/\", methods=['GET'], strict_slashes=False)\n@main.route(\"/health\", methods=['GET'], strict_slashes=False)\ndef health():\n response = requests.get(g.tensorboard_url + '/data/logdir')\n\n if response.status_code != 200:\n return \"Tensorboard server not responding at {}\".format(g.tensorboard_url)\n\n response = response.json()\n if response.get(\"logdir\") != g.tensorboard_folder:\n message = \"Tensorboard running in an incorrect folder ({}) instead of {}\"\\\n .format(response.get(\"logdir\"), g.tensorboard_folder)\n return message, 400\n\n message = \"Tensorboard running at '{}' in folder '{}'\"\\\n .format(g.tensorboard_url, g.tensorboard_folder)\n return jsonify({\n 'health': 'OK',\n 'version': g.version,\n 'message': message,\n 'tensorboard': {\n 'logdir': g.tensorboard_folder,\n 'address': g.tensorboard_url,\n }\n })\n","sub_path":"flaskapp/lapiz/blueprints/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"377742762","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nsys.path.insert(0, '../../../lib')\n\nimport rospy\nimport tf\nimport tf2_ros\nimport math\nimport numpy\nimport timeit\nfrom collections import Counter\n\nimport tf2_geometry_msgs\nfrom std_msgs.msg import Empty\nfrom geometry_msgs.msg import Pose, PoseStamped, Twist, TransformStamped, Point, Quaternion, Vector3\nfrom nav_msgs.msg import Odometry\nfrom gazebo_msgs.msg import ModelState\n\nimport functions\n\nclass SimWithANN():\n\n def __init__(self):\n\n # Note: by using Gazebo's set model state, I am unable to auto-update turtlbot's\n # tf. Therefore, I'll have to roll my own turtlebot's robot frame\n\n # NOTE: It is in fact possible to reset odometry. However, having the TurtleBot\n # keep track of its own frame internally is the more rigorous way to\n # simulate.\n\n self.TWIST_SOURCES = [\"/turtlebot0/cmd_vel_mux/input/navi\",\n \"/turtlebot0/cmd_vel_mux/input/safety_controller\",\n \"/turtlebot0/cmd_vel_mux/input/switch\",\n \"/turtlebot0/cmd_vel_mux/input/teleop\"]\n\n self.MODEL_NAME_DRIFT = \"mobile_base1\"\n self.MODEL_NAME_NODRIFT = \"mobile_base3\"\n\n self.REFRESH_RATE = 0.1 # in seconds\n\n self.totalTime = 0.0\n\n # Init this node\n rospy.init_node(\"SimulateTurtleBotANN\", anonymous=False)\n rospy.on_shutdown(self.shutdown)\n\n # Create static transform broadcaster\n self.broadcaster = tf2_ros.StaticTransformBroadcaster()\n\n # Create publisher to gazebo's set_model_state\n self.modelStatePublisher = rospy.Publisher(\"/gazebo/set_model_state\",\n ModelState,\n queue_size=10)\n\n # Load the ANNs\n self.mx = functions.my_load_model(\"../../../ann_training/final_anns/my_model_x.h5\")\n self.my = functions.my_load_model(\"../../../ann_training/final_anns/my_model_y.h5\")\n self.mt = functions.my_load_model(\"../../../ann_training/final_anns/my_model_theta.h5\")\n self.mz = functions.my_load_model(\"../../../ann_training/final_anns/my_model_endAngZ.h5\")\n\n # For some reason, if I don't test first, the ANNs will bug out and\n # refuse to predict later.\n test = numpy.array([[0.,0.,0.]])\n print(self.mx.predict(test,batch_size=1,verbose=1))\n print(self.my.predict(test,batch_size=1,verbose=1))\n print(self.mt.predict(test,batch_size=1,verbose=1))\n print(self.mz.predict(test,batch_size=1,verbose=1))\n\n # Subscribe to reset topic\n rospy.Subscriber(\"/my_reset_ann_bot\",\n Empty,\n self.reset_callback)\n\n # Subscribe to bot0's Twist\n for x in self.TWIST_SOURCES:\n rospy.Subscriber(x, Twist, self.twist_callback)\n\n # Init robot internal state \n self.timer = None\n self.reset_callback(None)\n\n rospy.loginfo(\"SimWithANN has started up\")\n\n rospy.spin()\n\n def odom_callback(self, data):\n self.lastOdom = data\n\n def twist_callback(self, data):\n x = round(data.linear.x, 2)\n z = round(data.angular.z,2)\n\n if (self.lastCmdLinX == None or\n self.lastCmdAngZ == None or\n self.refreshStart == None):\n self.lastCmdLinX = x\n self.lastCmdAngZ = z\n self.refreshStart = rospy.Time.now()\n self.refreshEnd = rospy.Time.now()\n self.totalTime = 0.0\n elif self.refreshEnd == None:\n self.refreshEnd = rospy.Time.now()\n elif (x == self.lastCmdLinX and z == self.lastCmdAngZ):\n self.refreshEnd = rospy.Time.now()\n else:\n print(\"\")\n print(\"End cmd segment (\" + str(self.lastCmdLinX) + \",\" + str(self.lastCmdAngZ) + \")\")\n print(\"Time of cmd segment: \" + str(self.totalTime))\n print(\"\")\n self.totalTime = 0.0\n self.timer.shutdown()\n self.refresh()\n self.lastCmdLinX = x\n self.lastCmdAngZ = z\n self.refreshStart = rospy.Time.now()\n self.refreshEnd = rospy.Time.now()\n self.timer = rospy.Timer(rospy.Duration.from_sec(self.REFRESH_RATE),\n self.timer_callback)\n\n def timer_callback(self, event):\n if (self.lastCmdLinX == None or\n self.lastCmdAngZ == None or\n self.internalAngZ_drift == None or\n self.refreshStart == None or\n self.refreshEnd == None):\n return\n else:\n self.refresh()\n self.refreshStart = rospy.Time.now()\n self.refreshEnd = rospy.Time.now()\n\n def refresh(self):\n t0 = timeit.default_timer()\n\n secs = self.REFRESH_RATE\n\n self.totalTime = self.totalTime + secs\n\n print(\"\")\n print(\"duration: \" + str(secs) + \"s\")\n\n # Get the pose change from ANN\n input_to_ANN = numpy.array([\n [self.lastCmdLinX,self.lastCmdAngZ,self.internalAngZ_drift]\n ])\n\n print(input_to_ANN)\n\n deltaX = self.mx.predict(input_to_ANN, batch_size=1, verbose=1)\n deltaY = self.my.predict(input_to_ANN, batch_size=1, verbose=1)\n deltaTheta = self.mt.predict(input_to_ANN, batch_size=1, verbose=1)\n endAngZ = self.mz.predict(input_to_ANN, batch_size=1, verbose=1)\n\n print(\"Pred result: (\" + str(deltaX) + \",\" +\n str(deltaY) + \",\" +\n str(deltaTheta) + \",\" +\n str(endAngZ) + \")\")\n\n input_to_ANN = numpy.array([\n [self.lastCmdLinX,self.lastCmdAngZ,self.lastCmdAngZ]\n ])\n\n print(input_to_ANN)\n\n deltaX_nodrift = self.mx.predict(input_to_ANN, batch_size=1, verbose=1)\n deltaY_nodrift = self.my.predict(input_to_ANN, batch_size=1, verbose=1)\n deltaTheta_nodrift = self.mt.predict(input_to_ANN, batch_size=1, verbose=1)\n\n print(\"Pred result: (\" + str(deltaX_nodrift) + \",\" +\n str(deltaY_nodrift) + \",\" +\n str(deltaTheta_nodrift) + \")\")\n\n # DRIFT\n ## delta X,Y in terms of world frame orientation\n originalHeading = tf.transformations.euler_from_quaternion((self.internalPose_drift.orientation.x,\n self.internalPose_drift.orientation.y,\n self.internalPose_drift.orientation.z,\n self.internalPose_drift.orientation.w ))[2]\n transformedDelta = self.transform(deltaX.tolist()[0][0], deltaY.tolist()[0][0], -1 * originalHeading)\n transformedDelta = transformedDelta.tolist()\n transformedDeltaX = transformedDelta[0][0]\n transformedDeltaY = transformedDelta[1][0]\n newOrientation = tf.transformations.quaternion_from_euler(0,0,originalHeading + deltaTheta)\n # print(newOrientation)\n newPose = Pose(Point(self.internalPose_drift.position.x + transformedDeltaX,\n self.internalPose_drift.position.y + transformedDeltaY,\n 0),\n Quaternion(newOrientation[0],\n newOrientation[1],\n newOrientation[2],\n newOrientation[3]))\n\n # Publish the new pose to gazebo\n model_state = ModelState()\n model_state.model_name = self.MODEL_NAME_DRIFT\n model_state.twist = Twist()\n model_state.pose = newPose\n\n\n # Update the internal state\n self.internalPose_drift = newPose\n self.internalAngZ_drift = endAngZ\n\n # Update the odom frame - robot frame transform\n # self.publish_world_robot_transform()\n\n # Publish new model state to Gazebo\n self.modelStatePublisher.publish(model_state)\n\n\n\n # NODRIFT\n ## delta X,Y in terms of world frame orientation\n originalHeading = tf.transformations.euler_from_quaternion((self.internalPose_nodrift.orientation.x,\n self.internalPose_nodrift.orientation.y,\n self.internalPose_nodrift.orientation.z,\n self.internalPose_nodrift.orientation.w ))[2]\n transformedDelta = self.transform(deltaX_nodrift.tolist()[0][0], deltaY_nodrift.tolist()[0][0], -1 * originalHeading)\n transformedDelta = transformedDelta.tolist()\n transformedDeltaX = transformedDelta[0][0]\n transformedDeltaY = transformedDelta[1][0]\n newOrientation = tf.transformations.quaternion_from_euler(0,0,originalHeading + deltaTheta_nodrift)\n # print(newOrientation)\n newPose = Pose(Point(self.internalPose_nodrift.position.x + transformedDeltaX,\n self.internalPose_nodrift.position.y + transformedDeltaY,\n 0),\n Quaternion(newOrientation[0],\n newOrientation[1],\n newOrientation[2],\n newOrientation[3]))\n\n # Publish the new pose to gazebo\n model_state = ModelState()\n model_state.model_name = self.MODEL_NAME_NODRIFT\n model_state.twist = Twist()\n model_state.pose = newPose\n\n # Update the internal state\n self.internalPose_nodrift = newPose\n\n # Update the odom frame - robot frame transform\n # self.publish_world_robot_transform()\n\n # Publish new model state to Gazebo\n self.modelStatePublisher.publish(model_state)\n\n t1 = timeit.default_timer()\n print(\"refresh took \" + str(t1 - t0) + \" seconds\")\n\n def reset_callback(self,data):\n # Shut down the old timer\n if self.timer is not None:\n self.timer.shutdown()\n\n # Internal robot pose\n self.internalPose_drift = Pose(Point(2,0,0),Quaternion(0,0,0,1))\n self.internalPose_nodrift = Pose(Point(2,4,0),Quaternion(0,0,0,1))\n\n # Internal robot AngZ\n self.internalAngZ_drift = 0\n\n # Publish pose to Gazebo\n model_state = ModelState()\n model_state.model_name = self.MODEL_NAME_DRIFT\n model_state.twist = Twist()\n model_state.pose = self.internalPose_drift\n self.modelStatePublisher.publish(model_state)\n\n model_state.model_name = self.MODEL_NAME_NODRIFT\n model_state.pose = self.internalPose_nodrift\n self.modelStatePublisher.publish(model_state)\n\n # Reset the internal command memory\n self.reset_internal_command_tracker()\n\n # Start a new timer\n self.timer = rospy.Timer(rospy.Duration.from_sec(self.REFRESH_RATE),\n self.timer_callback)\n\n #print(\"\")\n #print(\"RESET. Total time: \" + str(self.totalTime))\n #print(\"\")\n\n def reset_internal_command_tracker(self):\n self.lastCmdLinX = 0\n self.lastCmdAngZ = 0\n self.refreshStart = None\n self.refreshEnd = None\n\n def publish_world_robot_transform(self):\n # Publish the current robot1 pose as a static transform from bot0 world frame \n curr_robot_frame = TransformStamped()\n curr_robot_frame.header.stamp = rospy.Time.now()\n curr_robot_frame.header.frame_id = self.BOT0_WORLD_FRAME\n curr_robot_frame.child_frame_id = self.MY_BOT1_ROBOT_FRAME\n curr_robot_frame.transform.translation = Vector3(self.internalPose.position.x,\n self.internalPose.position.y,\n self.internalPose.position.z)\n curr_robot_frame.transform.rotation = self.internalPose.orientation\n self.broadcaster.sendTransform(curr_robot_frame)\n\n def makeTransformMatrix(self, heading):\n result = numpy.matrix([[ math.cos(heading), math.sin(heading)],\n [-math.sin(heading), math.cos(heading)] ])\n return(result)\n\n\n def transform(self, xCoord, yCoord, heading):\n # print(\"xCoord: \" + str(xCoord))\n # print(\"yCoord: \" + str(yCoord))\n # print(\"heading: \" + str(heading))\n transform_matrix = self.makeTransformMatrix(heading)\n coords = numpy.matrix([[xCoord],\n [yCoord] ])\n # print(\"tf mat:\")\n # print(transform_matrix)\n # print(\"coord:\")\n # print(coords)\n result = numpy.dot(transform_matrix, coords)\n return(result)\n\n def shutdown(self):\n rospy.loginfo(\"SimWithANN shutting down\")\n\nif __name__ == '__main__':\n try:\n SimWithANN()\n except Exception as e:\n rospy.loginfo(\"Exception: SimWithANN\")\n rospy.loginfo(str(e))\n","sub_path":"demos/robot_movement_simulator/acceleration_effects/SimANN_DriftAndNoDrift.py","file_name":"SimANN_DriftAndNoDrift.py","file_ext":"py","file_size_in_byte":13204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"160074007","text":"import json\nimport requests\n\nfrom base import Manager as Base\n\n\nclass Manager(Base):\n \"\"\"\n Manage Node resources.\n \"\"\"\n\n def create(self, register=False, **kwargs):\n \"\"\"\n Create a node.\n \"\"\"\n register = \"true\" if register is True else \"false\"\n response = requests.post(\n \"{}/docker/node?register={}\".format(self.target, register),\n data=json.dumps(kwargs),\n headers=self.headers\n )\n return response.json()\n","sub_path":"tsuruclient/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"368951295","text":"\nimport math\nfrom ROOT import *\n\nfname_in = TFile(\"getunfold-pi0pipi-cms.root\", 'r')\nhist = fname_in.Get(\"h_mb_evt_hadm_eff3bin\")\n\nwith open(\"det_eff.txt\", 'w') as f:\n for idx_m in range(hist.GetNbinsX() + 1):\n m = hist.GetXaxis().GetBinCenter(idx_m)\n r = hist.GetBinContent(idx_m)\n e = hist.GetBinError(idx_m)\n f.write(\"%f %f %f\\n\" % (m, r, e))\n\nfname_in.Close()\n\n\n\n","sub_path":"notes/det_eff/dump_det_eff_hist.py","file_name":"dump_det_eff_hist.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"216417688","text":"from django.core.management.base import BaseCommand\n\nfrom demo.seed_data import seed_database\n\n\nclass Command(BaseCommand):\n help = 'Seed developer database with mocked data'\n\n def add_arguments(self, parser):\n parser.add_argument('--verbose', default=False, action='store_true')\n\n def handle(self, *args, **options):\n self.stdout.write('Seeding database with data')\n try:\n seed_database()\n except Exception as e:\n if options['verbose']:\n raise e\n else:\n self.stdout.write(\n 'Hit an database error. There\\'s probably data currently'\n ' in the local db. skipping.'\n )\n self.stdout.write(\n 'Finished! user/password for demo user admin/admin'\n )\n","sub_path":"corpora/demo/management/commands/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"634012185","text":"import os.path\nimport shutil\nimport sys\nimport tempfile\nfrom collections import namedtuple\nfrom contextlib import contextmanager\n\nimport boto3\nimport yaml\nfrom distutils.util import strtobool\nfrom ModestMaps.Core import Coordinate\nfrom tilequeue.command import make_config_from_argparse\nfrom tilequeue.command import tilequeue_batch_enqueue\nfrom tilequeue.tile import deserialize_coord\nfrom tilequeue.tile import serialize_coord\n\nfrom utils.tiles import BoundingBoxTileCoordinatesGenerator\nfrom utils.tiles import S3TileVerifier\nfrom utils.tiles import TileCoordinatesGenerator\n\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir)\n\n\n# this struct exists to be passed into tilequeue's tilequeue_batch_enqueue\n# command. it replicates the expected arguments, which would normally come\n# from argparse. we only use the 'config' and 'file' parts of it, but the\n# others need to exist to avoid AttributeError.\nBatchEnqueueArgs = namedtuple('BatchEnqueueArgs', 'config tile file pyramid')\n\n\ndef all_tiles_at(zoom):\n \"\"\"\n Generate all the coordinates at a given zoom level.\n \"\"\"\n\n max_coord = 2 ** zoom\n for x in range(max_coord):\n for y in range(max_coord):\n yield Coordinate(zoom=zoom, column=x, row=y)\n\n\ndef missing_tiles(missing_bucket, rawr_bucket, date_prefix, region,\n key_format_type, config, group_by_zoom,\n tile_coords_generator, tile_verifier):\n from make_meta_tiles import MissingTileFinder\n if bool(tile_coords_generator):\n return {c for c in tile_coords_generator.generate_tiles_coordinates([group_by_zoom])}\n else:\n present = set()\n finder = MissingTileFinder(\n missing_bucket, rawr_bucket, date_prefix, date_prefix, region,\n key_format_type, config, group_by_zoom, tile_coords_generator,\n tile_verifier)\n with finder.present_tiles() as present_file:\n with open(present_file) as fh:\n for line in fh:\n coord = deserialize_coord(line)\n if coord.zoom == group_by_zoom:\n present.add(coord)\n\n missing = set(all_tiles_at(group_by_zoom)) - set(present)\n return missing\n\n\n@contextmanager\ndef missing_jobs(missing_bucket, rawr_bucket, date_prefix, region, config,\n group_by_zoom=10, queue_zoom=7, key_format_type='prefix-hash',\n tile_coords_generator=None, tile_verifier=None):\n \"\"\"\n Write and yield file containing a z/x/y coordinate for each job (at the\n job zoom) corresponding to a missing tile (at the tile zoom) in the bucket.\n\n Cleans up the temporary directory after the yielded-to code returns.\n \"\"\"\n\n tiles = missing_tiles(\n missing_bucket, rawr_bucket, date_prefix, region, key_format_type,\n config, group_by_zoom, tile_coords_generator, tile_verifier)\n\n # the rawr tiles of `group_by_zoom` is actually built by AWS batch jobs of\n # `queue_zoom` so we need to do a zoomTo here to find the corresponding jobs\n job_coords = {coord.zoomTo(queue_zoom).container() for coord in tiles}\n\n if bool(tile_coords_generator):\n print('[make_rawr_tiles] Going to rebuild %d tiles by (%d jobs)' %\n (len(tiles), len(job_coords)))\n else:\n print('[make_rawr_tiles] Missing %d tiles (%d jobs)' %\n (len(tiles), len(job_coords)))\n\n tmpdir = tempfile.mkdtemp()\n try:\n missing_file = os.path.join(tmpdir, 'missing_jobs.txt')\n\n with open(missing_file, 'w') as fh:\n for coord in sorted(job_coords):\n fh.write(serialize_coord(coord) + '\\n')\n if tile_verifier is not None:\n tile_verifier.generate_tile_coords_rebuild_paths_rawr([coord],\n group_by_zoom)\n\n yield missing_file\n\n finally:\n shutil.rmtree(tmpdir)\n\n\ndef wc_line(filename):\n \"\"\"\n Returns a count of the number of lines in the file, similar to the command\n line utility `wc -l`.\n \"\"\"\n\n with open(filename, 'r') as fh:\n count = sum(1 for _ in fh)\n return count\n\n\ndef head_lines(filename, n_lines):\n \"\"\"\n Returns an array of the first n_lines lines of filename, similar to the command\n line utility `head -n`.\n \"\"\"\n\n sample = []\n\n with open(filename, 'r') as fh:\n try:\n for _ in range(n_lines):\n sample.append(next(fh).strip())\n except StopIteration:\n pass\n\n return sample\n\n\ndef any_jobs_with_status(batch, job_queue, status):\n \"\"\"\n Returns True if there are any jobs in the queue with the same status.\n \"\"\"\n\n response = batch.list_jobs(\n jobQueue=job_queue, jobStatus=status, maxResults=1)\n return len(response['jobSummaryList']) > 0\n\n\ndef wait_for_jobs_to_finish(job_queue, wait_time=300):\n \"\"\"\n Wait until there are no jobs in the queue with a non-finished status.\n\n By \"non-finished\" we mean anything that is running, or could potentially\n run, so. When there are no jobs in any of these statuses, we know that all\n the jobs we submitted have either succeeded or failed, and we can check S3\n to find out if we need to re-run anything.\n \"\"\"\n\n import time\n\n batch = boto3.client('batch')\n\n jobs_remaining = True\n while jobs_remaining:\n jobs_remaining = False\n for status in ('SUBMITTED', 'PENDING', 'RUNNABLE', 'STARTING',\n 'RUNNING'):\n if any_jobs_with_status(batch, job_queue, status):\n jobs_remaining = True\n print('[%s] Still have jobs left in queue %s.' % (time.ctime(),\n job_queue))\n time.sleep(wait_time)\n break\n print('[%s] All jobs finished (either SUCCEEDED or FAILED)' % (time.ctime()))\n\n\ndef make_rawr_tiles(rawr_config_file, missing_config_file, missing_bucket,\n rawr_bucket, region, date_prefix, retry_attempts,\n key_format_type='prefix-hash',\n tile_coords_generator=None, tile_verifier=None):\n # type: (str, str, str, str, str, str, int, str, TileCoordinatesGenerator, S3TileVerifier) -> None\n \"\"\"\n Finds out which jobs need to be run to have a complete RAWR tiles bucket,\n runs them and waits for them to complete. If the bucket still isn't\n complete, repeats until it is complete or the given number of retries is\n exceeded.\n \"\"\"\n\n assert os.path.isfile(rawr_config_file), rawr_config_file\n with open(rawr_config_file) as fh:\n config = yaml.load(fh.read())\n queue_zoom = config['batch']['queue-zoom']\n # Zoom level at which tiles are saved -- not the same thing as the zoom level jobs are run at!\n group_by_zoom = config['rawr']['group-zoom']\n logging_config = config['logging']['config']\n assert os.path.isfile(logging_config), logging_config\n job_queue = config['batch']['job-queue']\n\n for attempt in range(retry_attempts):\n tiles_generator = tile_coords_generator if attempt == 0 else None\n with missing_jobs(\n missing_bucket, rawr_bucket, date_prefix, region,\n missing_config_file, group_by_zoom, queue_zoom, key_format_type,\n tiles_generator, tile_verifier\n ) as missing_file:\n num_missing = wc_line(missing_file)\n if num_missing == 0:\n print('[make_rawr_tiles] Successfully generated all the RAWR '\n 'tiles after '\n '%d re-enqueues!' % (attempt))\n return\n\n args = BatchEnqueueArgs(rawr_config_file, None, missing_file, None)\n with open(args.config) as fh:\n cfg = make_config_from_argparse(fh)\n tilequeue_batch_enqueue(cfg, args)\n\n wait_for_jobs_to_finish(job_queue)\n\n tiles = missing_tiles(missing_bucket, rawr_bucket, date_prefix, region,\n key_format_type, config, group_by_zoom,\n None, None)\n\n print('[make_rawr_tiles] Ran %d times, but still have %d missing tiles. '\n 'Good luck!' %\n (retry_attempts, len(tiles)))\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser('Render missing RAWR tiles')\n parser.add_argument('bucket', help='Bucket with RAWR tiles in')\n parser.add_argument('date_prefix', help='Date prefix in bucket')\n parser.add_argument('--retries', default=5, type=int, help='Number '\n 'of times to retry enqueueing the remaining jobs '\n 'before giving up.')\n parser.add_argument('--config', default='enqueue-rawr-batch.config.yaml',\n help='Configuration file written out by make_tiles.py')\n parser.add_argument('--key-format-type', default='prefix-hash',\n help=\"Key format type, either 'prefix-hash' or \"\n \"'hash-prefix', controls whether the S3 key is \"\n 'prefixed with the date or hash first.')\n parser.add_argument('--region', help='AWS region. If not provided, then '\n 'the AWS_DEFAULT_REGION environment variable must be '\n 'set.')\n parser.add_argument('--missing-config',\n default='enqueue-missing-meta-tiles-write.config.yaml',\n help='Configuration file for missing tile enumeration '\n 'written out by make_tiles.py')\n parser.add_argument('missing_bucket', help='Bucket to store tile '\n 'enumeration logs in while calculating missing tiles.')\n parser.add_argument('--use-tile-coords-generator', type=lambda x: bool(strtobool(x)), nargs='?',\n const=True, default=False)\n parser.add_argument('--tile-coords-generator-bbox', type=str, help='Comma separated coordinates of a bounding box '\n 'min_x, min_y, max_x, max_y')\n\n args = parser.parse_args()\n assert args.key_format_type in ('prefix-hash', 'hash-prefix')\n assert args.bucket\n assert args.missing_bucket\n\n region = args.region or os.environ.get('AWS_DEFAULT_REGION')\n if region is None:\n import sys\n print('[make_rawr_tiles] ERROR: Need environment variable '\n 'AWS_DEFAULT_REGION to be set.')\n sys.exit(1)\n\n generator = None\n tile_verifier = None\n if args.use_tile_coords_generator:\n bboxes = args.tile_coords_generator_bbox.split(',')\n assert len(\n bboxes) == 4, 'Seed config: custom bbox {} does not have exactly four elements!'.format(bboxes)\n min_x, min_y, max_x, max_y = list(map(float, bboxes))\n assert min_x < max_x, 'Invalid bbox. X: {} not less than {}'.format(\n min_x, max_x)\n assert min_y < max_y, 'Invalid bbox. Y: {} not less than {}'.format(\n min_y, max_y)\n generator = BoundingBoxTileCoordinatesGenerator(min_x=min_x,\n min_y=min_y,\n max_x=max_x,\n max_y=max_y)\n\n tile_verifier = S3TileVerifier(args.date_prefix,\n args.key_format_type,\n args.bucket,\n '',\n 'rawr_s3_paths.csv',\n '',\n '')\n\n print('[make_rawr_tiles] Rebuild using bbox: ' +\n args.tile_coords_generator_bbox)\n\n make_rawr_tiles(args.config, args.missing_config, args.missing_bucket,\n args.bucket, region, args.date_prefix, args.retries,\n args.key_format_type,\n generator, tile_verifier)\n\n if tile_verifier is not None:\n tile_verifier.verify_tiles_rebuild_time('rawr')\n","sub_path":"batch-setup/make_rawr_tiles.py","file_name":"make_rawr_tiles.py","file_ext":"py","file_size_in_byte":12198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"259993136","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom stompy.spatial import field\nfrom stompy.model.delft import dfm_grid\nfrom stompy.plot import plot_utils\n\n\n## \n\n# This one seems like it should just be the Alviso-only grid, but plots as the\n# combined...\n#g=dfm_grid.DFMGrid('/home/rusty/models/grids/mick_alviso_v4_net.nc/mick_alviso_v4_net.nc')\n\ng=dfm_grid.DFMGrid('/media/hpc/opt/data/delft/lsb_combined/grids/alviso2012_net.nc')\n\ng.add_cell_field('depth',g.interp_node_to_cell(g.nodes['depth']))\n\n## \n\ndem=field.GdalGrid('tiles_5m_20170501/merged_5m.tif')\n\n\n## \n\nclip=(576264.,597495.,4122205.,4154848.)\n\n## \n\nplt.figure(1).clf()\n\nfig,(ax,ax2)=plt.subplots(1,2,num=1,sharex=True,sharey=True)\n\nimg=dem.plot(ax=ax,interpolation='nearest',aspect='auto')\n\n#coll=g.plot_cells(values=g.cells['depth'],lw=0,ax=ax2,clip=clip)\ncoll=g.contourf_node_values(g.nodes['depth'],np.linspace(-1.2,2.5,20),\n extend='both')\n\n\ncax=fig.add_axes([0.93,0.1,0.02,0.4])\n\ncbar=plot_utils.cbar(img,cax=cax,extras=[coll],ax=ax2,label='Bed elev. (m NAVD88)')\n\nplt.setp([coll,img], clim=[-1.2,2.5])\n\nax.axis('equal')\n\nfig.subplots_adjust(left=0.05)\nax.axis( (587196.,592615.,4139820.,4146642.) )\n\n# z01: used the full grid, already merged\n# fig.savefig('compare_to_alviso_grid_z02.png')\n\n## \n\nreload(unstructured_grid)\nreload(dfm_grid)\n","sub_path":"compare_to_alviso_grid.py","file_name":"compare_to_alviso_grid.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"494818500","text":"import rdflib\nimport os\nfrom .logic import And\nfrom .error import ExtensionError\nfrom rdfscript.core import Uri, Value\nfrom sbol_rdf_identifiers import identifiers\n\nsbolns = Uri('http://sbols.org/v3#')\n\n\nclass SBOL3:\n '''\n Extension which checks all SBOL objects contained in a triplepack\n have SBOL compliant URIs, and if not, attempts to modify the\n triples such that they are.\n\n Creates a single SBOLCompliant extension for each named SBOL\n object (subject) in the triplepack and 'ANDs' them together. The\n extension returns successful if all the SBOL objects in the\n triplepack have SBOL compliant URIs, or can be modified to have\n them. Otherwise fails and raises Exception.\n\n Note: the And extension is short-circuiting TODO: decide if this\n is the desired behaviour for SBOLIdentity\n '''\n\n def __init__(self):\n pass\n\n def run(self, triplepack,env):\n subjects = list(triplepack.subjects)\n ids = get_identifier_uris(triplepack._paths)\n identifiers.swap_version(\"sbol_3\")\n for i in range(len(subjects)):\n SBOLCompliant(subjects[i]).run(triplepack, subjects)\n \n validate(subjects,ids,triplepack)\n\n return triplepack\n\n\nclass SBOLCompliant:\n '''\n Extension to check a single subject, naming an SBOL object, has an\n SBOL compliant URI, and if not, attempts to modify triplepack such\n that they are.\n '''\n def __init__(self, for_subject):\n self.subject = for_subject\n\n def run(self, triplepack, subjects):\n parent = get_SBOL_parent(triplepack, self.subject)\n # Everything has a display id\n if not triplepack.search((self.subject, identifiers.predicates.display_id, None)):\n new_displayId = self.subject.split()[-1]\n \n triplepack.add((self.subject, identifiers.predicates.display_id, Value(new_displayId)))\n # Everything has a Version\n if get_SBOL_version(triplepack, self.subject) is None:\n #Set default version of 1.\n triplepack.add((self.subject, identifiers.predicates.version, Value(\"1\")))\n\n\n\n if parent is not None:\n # its a child\n if not triplepack.has(parent, identifiers.predicates.persistent_identity):\n SBOLCompliant(parent).run(triplepack, subjects)\n\n # parent uri might have changed!!!\n parent = get_SBOL_parent(triplepack, self.subject)\n\n # then use the parents details\n set_childs_persistentIdentity(triplepack, parent, self.subject)\n set_childs_version(triplepack, parent, self.subject)\n\n elif not is_SBOL_Compliant(triplepack, self.subject):\n if get_SBOL_persistentIdentity(triplepack, self.subject) is None:\n pId = Uri(self.subject.uri)\n triplepack.add((self.subject, identifiers.predicates.persistent_identity, pId))\n\n\n new_id = set_identity(triplepack, self.subject)\n subjects[subjects.index(self.subject)] = new_id\n\n return triplepack\n\n\ndef validate(subjects,identifiers, triplepack):\n '''\n Built-in validator to made checks on the graph to ensure Valid SBOL.\n '''\n template_predicates = {Uri(sbolns.uri + predicate) for predicate in\n [\n 'hasInteraction',\n 'hasInterface',\n 'hasParticipation',\n 'hasConstraint',\n 'hasLocation',\n 'hasFeature',\n 'hasVariableComponent']}\n\n symbols_table = triplepack.bindings\n\n for subject in subjects:\n triples = triplepack.search((subject,None,None))\n for s,p,o in triples:\n if p in template_predicates and o not in subjects:\n print(s,p,o)\n raise SBOLComplianceError(f\"Unknown Parameter for {s}\")\n\n return\n\n\ndef get_identifier_uris(paths):\n name = \"identifiers.shb\"\n identifier_path = None\n for path in paths:\n for root, dirs, files in os.walk(path):\n if name in files:\n identifier_path = os.path.join(root, name)\n break\n if identifier_path is None:\n raise FileNotFoundError(f\"Can't find file {name} for SBOL identifier extension\")\n\n identifiers = {}\n data = open(identifier_path,\"r\")\n lines = data.readlines()[1:]\n cur_template_types = []\n cur_template_property = \"\"\n for line in lines:\n if \"=\" not in line and \"#\" not in line:\n continue\n else:\n line = line.replace(\" \", \"\").replace(\"\\n\",\"\")\n if line[0] == \"#\":\n template_types = line.split(\"(\")[1].split(\")\")[0].split(\",\")\n template_property = line.split(\")\")[1]\n for template_type in template_types:\n if template_type not in identifiers.keys():\n identifiers[template_type]= {}\n identifiers[template_type][template_property] = []\n cur_template_types = template_types\n cur_template_property = template_property\n\n if line[0] != \"#\" and \"=\" in line:\n name = line.split(\"=\")[0]\n for cur_template_type in cur_template_types:\n identifiers[cur_template_type][cur_template_property].append(name)\n \n data.close()\n return identifiers\n\ndef is_SBOL_Compliant(triplepack, uri):\n version = get_SBOL_version(triplepack, uri)\n dId = get_SBOL_displayId(triplepack, uri)\n pId = get_SBOL_persistentIdentity(triplepack, uri)\n\n compliant = dId is not None and pId is not None\n compliant = compliant and uri.uri == pId.uri + \"/\" + str(version.value)\n if is_SBOL_TopLevel(triplepack, uri):\n compliant = compliant and pId.split()[-1] == dId.value\n return compliant\n\n\ndef set_identity(triplepack, uri):\n version = get_SBOL_version(triplepack, uri)\n if version is not None:\n pid = get_SBOL_persistentIdentity(triplepack, uri)\n new_id = Uri(pid.uri + '/' + str(version.value))\n triplepack.replace_with_type(uri, new_id, identifiers.predicates.persistent_identity)\n else:\n new_id = get_SBOL_persistentIdentity(triplepack, uri)\n triplepack.replace_with_type(uri, new_id, identifiers.predicates.persistent_identity)\n return new_id\n\n\ndef set_childs_persistentIdentity(triplepack, parent, child):\n parents_pId = get_SBOL_persistentIdentity(triplepack, parent)\n childs_dId = get_SBOL_displayId(triplepack, child)\n childs_pId = Uri(parents_pId.uri + '/' + childs_dId.value)\n triplepack.set(child, identifiers.predicates.persistent_identity, childs_pId)\n\n\ndef set_childs_version(triplepack, parent, child):\n parents_version = get_SBOL_version(triplepack, parent)\n if parents_version is not None:\n triplepack.set(child, identifiers.predicates.version, parents_version)\n\n\ndef get_possible_SBOL_types(triplepack, uri):\n '''\n Return the possible SBOL object types based on the RDF.type\n property attached to uri.\n\n '''\n return {o for (s, p, o) in triplepack.search((uri, identifiers.predicates.rdf_type, None))}\n\n\ndef is_SBOL_TopLevel(triplepack, uri):\n '''\n Checks if SBOL object named by uri is a TopLevel SBOL object.\n '''\n the_types = get_possible_SBOL_types(triplepack, uri)\n return any([t in identifiers.objects.top_levels for t in the_types])\n\n\ndef get_SBOL_parent(triplepack, child):\n '''\n Search the triplepack for the unique parent of the child, that is,\n the unique subject that is related to the child by one of the\n ownership predicates, or by the component predicate if the parent\n is a ComponentDefinition\n\n If more than one parent is found or the child is not a TopLevel\n SBOL object and no parent is found, an SBOLComplianceError is\n raised.\n\n If the child is an SBOL TopLevel object, then None is returned. \n '''\n possible_parents = set()\n\n for predicate in identifiers.predicates.ownership_predicates:\n possible_parents |= {s for (s, p, o)\n in triplepack.search((None, predicate, child))}\n\n possible_parents |= {s for (s, p, o)\n in triplepack.search((None, identifiers.predicates.has_feature, child))\n if identifiers.objects.component in get_possible_SBOL_types(triplepack, s)\n and identifiers.objects.sequence_feature not in get_possible_SBOL_types(triplepack, s)}\n\n if child in possible_parents:\n raise SBOLComplianceError(f'{child} is its own possible parent, likely due to being a property of itself')\n # at this point we should have the parent/s\n if len(possible_parents) > 1:\n raise SBOLComplianceError(f\"{child} has multiple SBOL parents\\n\" +\n f\"Which are:\\n\" +\n f\"{','.join(map(str, possible_parents))}\")\n\n \n elif not possible_parents and not is_SBOL_TopLevel(triplepack, child):\n raise SBOLComplianceError(f\"{child} is an orphaned SBOL child\")\n\n elif possible_parents and is_SBOL_TopLevel(triplepack, child):\n raise SBOLComplianceError(f\"{child} is a TopLevel SBOL object\\n\" +\n f\"But has parents:\\n\" +\n f\"{','.join(map(str, possible_parents))}\")\n\n parent = possible_parents.pop() if possible_parents else None\n return parent\n\n\ndef get_SBOL_version(triplepack, uri):\n matches = {o for (s, p, o)\n in triplepack.search((uri, identifiers.predicates.version, None))}\n if len(matches) > 1:\n raise SBOLComplianceError(f\"{uri} has multiple version's.\")\n elif not matches:\n return None\n else:\n return matches.pop()\n\n\ndef get_SBOL_persistentIdentity(triplepack, uri):\n matches = {o for (s, p, o)\n in triplepack.search((uri, identifiers.predicates.persistent_identity, None))}\n if len(matches) > 1:\n raise SBOLComplianceError(f\"{uri} has multiple persistentIdentity's.\")\n elif not matches:\n return None\n else:\n return matches.pop()\n\n\ndef get_SBOL_displayId(triplepack, uri):\n matches = {o for (s, p, o) in triplepack.search((uri, identifiers.predicates.display_id, None))}\n if len(matches) > 1:\n raise SBOLComplianceError(f\"{uri} has multiple displayId's.\")\n elif not matches:\n return None\n else:\n return matches.pop()\n\n\nclass SBOLComplianceError(ExtensionError):\n\n def __init__(self, helpful_message):\n self._type = 'SBOL2 Compliant URI error'\n self._helpful_message = helpful_message\n\n def __str__(self):\n return ExtensionError.__str__(self) + format(\" %s\\n\" % self._helpful_message)\n\n def simplified_error_message(self):\n return f'{self._helpful_message}'\n\n","sub_path":"extensions/sbol3.py","file_name":"sbol3.py","file_ext":"py","file_size_in_byte":10885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"171274752","text":"import pdb\nimport math\n\nimport numpy as np\n\ndef iterative_matrix_multiply(matrix_a, matrix_b):\n\t'''\n\tImplements an iterative algorithm to multiply two matrices.\n\tThis should have a worst case running time of O(n^3).\n\t'''\n\n\tC = np.zeros((A.shape[0], B.shape[1]))\n\n\tcolumn_count = 0\n\tfor row in range(A.shape[0]):\n\t\trow_count = 0\n\t\tfor column in range(B.shape[1]):\n\t\t\ti = 0\n\t\t\tj = 0\n\t\t\ttotal = 0\n\t\t\twhile i < A[row_count].shape[1]:\n\t\t\t\ttotal += A[row_count, i] * B.T[column_count, j]\n\t\t\t\ti += 1\n\t\t\t\tj += 1\n\t\t\tC[row_count, column_count] = total\n\t\t\trow_count += 1\n\t\tcolumn_count += 1\n\n\treturn C","sub_path":"multiplication/iterative_matrix_mult.py","file_name":"iterative_matrix_mult.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"108116017","text":"# Copyright 2019 The TensorFlow Authors All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# This file is modified for module usage.\n\"\"\"Inference demo for YAMNet.\"\"\"\nfrom __future__ import division, print_function\n\nimport os\nimport sys\nimport urllib\n\nimport numpy as np\nimport resampy\nimport soundfile as sf\nimport tensorflow as tf\n\nfrom .. import params\nfrom . import yamnet as yamnet_model\nfrom ..audio import Audio\n\ndirectory = os.path.dirname(os.path.abspath(__file__))\n\n\ndef predict(audio: Audio):\n\n graph = tf.Graph()\n with graph.as_default():\n yamnet = yamnet_model.yamnet_frames_model(params)\n if not os.path.exists('yamnet.h5'):\n url = 'https://storage.googleapis.com/audioset/yamnet.h5'\n urllib.request.urlretrieve(url, f'{directory}/yamnet.h5')\n yamnet.load_weights(f'{directory}/yamnet.h5')\n\n if not os.path.exists('yamnet_class_map.csv'):\n url = 'https://raw.githubusercontent.com/tensorflow/models/master/research/audioset/yamnet/yamnet_class_map.csv'\n urllib.request.urlretrieve(url)\n yamnet_classes = yamnet_model.class_names(\n f'{directory}/yamnet_class_map.csv')\n\n # Decode the WAV file.\n wav_data, sr = audio.wave.astype(np.int16), audio.sr\n assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype\n waveform = wav_data / 32768.0 # Convert to [-1.0, +1.0]\n\n # Convert to mono and the sample rate expected by YAMNet.\n if len(waveform.shape) > 1:\n waveform = np.mean(waveform, axis=1)\n if sr != params.SAMPLE_RATE:\n waveform = resampy.resample(waveform, sr, params.SAMPLE_RATE)\n\n # Predict YAMNet classes.\n # Second output is log-mel-spectrogram array (used for visualizations).\n # (steps=1 is a work around for Keras batching limitations.)\n with graph.as_default():\n scores, _ = yamnet.predict(np.reshape(waveform, [1, -1]), steps=1)\n # Scores is a matrix of (time_frames, num_classes) classifier scores.\n # Average them along time to get an overall classifier output for the clip.\n prediction = np.mean(scores, axis=0)\n # Report the highest-scoring classes and their scores.\n top5_i = np.argsort(prediction)[::-1][:5]\n\n return yamnet_classes[top5_i], prediction[top5_i]","sub_path":"wipctv/yamnet/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"166546480","text":"from clientprotocol.jsonvalidators_client import (parse_dictionary, parse_static_list, to_structure_dictionary_values)\n\n\n#\n# Request\n#\n\nclass Request(object):\n def to_structure(self):\n name = type(self).__name__\n inner = self.to_inner_structure()\n if type(inner) is dict:\n inner = to_structure_dictionary_values(inner)\n return [name, inner]\n\n def to_inner_structure(self):\n raise NotImplementedError\n\n @staticmethod\n def parse_structure(data):\n data = parse_static_list(data, 2)\n name, data = data\n if _Request_class_map.get(name) is None:\n msg = \"invalid request: \" + name\n raise ValueError(msg)\n return _Request_class_map[name].parse_inner_structure(data)\n\n @staticmethod\n def parse_inner_structure(data):\n raise NotImplementedError\n\n\nclass GetVersions(Request):\n def __init__(self):\n pass\n\n @staticmethod\n def parse_inner_structure(data):\n data = parse_dictionary(data)\n return GetVersions()\n\n def to_inner_structure(self):\n return {\n }\n\n\nclass GetUsers(Request):\n def __init__(self):\n pass\n\n @staticmethod\n def parse_inner_structure(data):\n data = parse_dictionary(data)\n return GetUsers()\n\n def to_inner_structure(self):\n return {\n }\n\n\ndef _init_Request_class_map():\n classes = [\n GetVersions,\n GetUsers,\n\n\n ]\n class_map = {}\n for c in classes:\n class_map[c.__name__] = c\n return class_map\n\n_Request_class_map = _init_Request_class_map()\n\n\n#\n# Response\n#\nclass Response(object):\n def to_structure(self):\n name = type(self).__name__\n inner = self.to_inner_structure()\n if type(inner) is dict:\n inner = to_structure_dictionary_values(inner)\n return [name, inner]\n\n def to_inner_structure(self):\n raise NotImplementedError\n\n @staticmethod\n def parse_structure(data):\n data = parse_static_list(data, 2)\n name, data = data\n if _Response_class_map.get(name) is None:\n msg = \"invalid request: \" + name\n raise ValueError(msg)\n return _Response_class_map[name].parse_inner_structure(data)\n\n @staticmethod\n def parse_inner_structure(data):\n raise NotImplementedError\n\n\nclass GetVersionsSuccess(Response):\n def __init__(\n self, unit_details_version, user_details_version,\n compliance_applicability_version, compliance_history_version,\n reassign_history_version\n ):\n self.unit_details_version = unit_details_version\n self.user_details_version = user_details_version\n self.compliance_applicability_version = compliance_applicability_version\n self.compliance_history_version = compliance_history_version\n self.reassign_history_version = reassign_history_version\n\n @staticmethod\n def parse_inner_structure(data):\n data = parse_dictionary(\n data, [\n \"unit_details_version\", \"user_details_version\",\n \"compliance_applicability_version\",\n \"compliance_history_version\",\n \"reassign_history_version\"\n ]\n )\n unit_details_version = data.get(\"unit_details_version\")\n\n user_details_version = data.get(\"user_details_version\")\n compliance_applicability_version = data.get(\n \"compliance_applicability_version\")\n compliance_history_version = data.get(\"compliance_history_version\")\n reassign_history_version = data.get(\"reassign_history_version\")\n return GetVersionsSuccess(\n unit_details_version, user_details_version,\n compliance_applicability_version, compliance_history_version,\n reassign_history_version\n )\n\n def to_inner_structure(self):\n return {\n \"unit_details_version\": self.unit_details_version,\n \"user_details_version\": self.user_details_version,\n \"compliance_applicability_version\": self.compliance_applicability_version,\n \"compliance_history_version\": self.compliance_history_version,\n \"reassign_history_version\": self.reassign_history_version\n }\n\n\nclass GetUsersList(object):\n def __init__(\n self, user_id, user_name\n ):\n self.user_id = user_id\n self.user_name = user_name\n\n @staticmethod\n def parse_structure(data):\n data = parse_dictionary(\n data, [\n \"user_id\", \"user_name\"\n ]\n )\n user_id = data.get(\"user_id\")\n user_name = data.get(\"user_name\")\n return GetUsersList(\n user_id, user_name\n )\n\n def to_structure(self):\n return {\n \"user_id\": self.user_id,\n \"user_name\": self.user_name\n }\n\n\nclass GetUsersSuccess(Response):\n def __init__(self, user_list):\n self.user_list = user_list\n\n @staticmethod\n def parse_inner_structure(data):\n data = parse_dictionary(data, [\"user_list\"])\n user_list = data.get(\"user_list\")\n\n return GetUsersSuccess(user_list)\n\n def to_inner_structure(self):\n return self.user_list\n\n\ndef _init_Response_class_map():\n classes = [\n\n GetVersionsSuccess,\n GetUsersSuccess,\n ]\n class_map = {}\n for c in classes:\n class_map[c.__name__] = c\n return class_map\n\n_Response_class_map = _init_Response_class_map()\n\n#\n# RequestFormat\n#\n\nclass RequestFormat(object):\n def __init__(self, session_token, request):\n self.session_token = session_token\n self.request = request\n\n @staticmethod\n def parse_structure(data):\n data = parse_dictionary(data, [\"session_token\", \"request\"])\n session_token = data.get(\"session_token\")\n request = data.get(\"request\")\n request = Request.parse_structure(request)\n return RequestFormat(session_token, request)\n\n def to_structure(self):\n return {\n \"session_token\": self.session_token,\n \"request\": Request.to_structure(self.request)\n }\n","sub_path":"Client-src-server/clientprotocol/clientmobile.py","file_name":"clientmobile.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"463683361","text":"#!/usr/bin/env python3\n\nimport functools\n\n\ndef branches(coord, shape):\n bs = []\n # print(coord)\n x, y = coord\n xbound, ybound = shape\n if x + 1 < xbound:\n bs.append((x + 1, y))\n if y + 1 < ybound:\n bs.append((x, y + 1))\n return bs\n # return [(x + 1 if x + 1 < xbound else x, y), (x, y + 1 if y + 1 < ybound else y)]\n # if x < xbound:\n\n\n@functools.lru_cache(maxsize=None)\ndef numPaths(shape, coord=(0, 0)):\n bs = branches(coord, shape)\n # print(len(bs))\n # print(xbound,ybound)\n xbound, ybound = shape\n if len(bs) == 0:\n # print(xbound, ybound)\n # print()\n return 1\n else:\n return sum([numPaths(shape, i) for i in bs])\n # rules\n\n\ndef main():\n gridWidth = 20\n gridHeight = 20\n\n # print([numPaths((i,i)) for i in range(15)])\n print(numPaths((gridWidth + 1, gridHeight + 1)))\n\nif __name__ == '__main__':\n main()\n","sub_path":"euler_015/Christopher D Chen/euler_015.py","file_name":"euler_015.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"238368069","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 19 17:29:02 2019\r\n\r\n@author: Li Xiang\r\n\r\ngoto:#finetune where we finetune based on the trained model\r\n\r\n \r\nrun train_elmo first(get original model) and then run this file(finetune and validate)\r\n\r\n\"\"\"\r\n\r\nimport sys\r\nimport numpy as np\r\nimport sys\r\nimport h5py\r\nimport func_elmo\r\nimport func_eval\r\nfrom sklearn import svm\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_predict\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nimport math\r\nfrom copy import deepcopy\r\n\r\n#-------------------set params for different purpose--------------------\r\n\r\n#cur_exp_param in ['cpu','ram','hd','gpu','screen']\r\n#cur_sent_embd_type in ['max','ave','concat']\r\n\r\n#hd,gpu,screen not directly available \r\n#cur_exp_param='cpu'#['cpu','ram','hd','gpu','screen']\r\n#cur_sent_embd_type='max'#['max','ave','concat']\r\n#classifier_type='mlp'#'svm''mlp''rnn'\r\n#K=5 #top K results for evaluation\r\n#difference_percent=0.2\r\n\r\n#----------------------------end parm setting-------------------------\r\n\r\nif(cur_sent_embd_type=='concat'):\r\n cur_word_dimen=2048\r\nelif(cur_sent_embd_type=='max' or cur_sent_embd_type=='ave' ):\r\n cur_word_dimen=1024\r\n\r\n#-----------------------------prepare train/test set----------------------------\r\n\r\ntest_asin_list=func_elmo.get_useful_asins(exp_param=cur_exp_param)\r\n\r\nasin_map_gene_reviews={}\r\nfor _asin in test_asin_list:\r\n review_embd=func_elmo.get_gener_review_embedding(emb_type=cur_sent_embd_type,asin=_asin)\r\n if(review_embd is not None):\r\n asin_map_gene_reviews[_asin]=review_embd\r\n\r\nasin_map_labels=func_elmo.get_sorted_label_list(exp_param=cur_exp_param)\r\n\r\n#sys.exit(0)\r\n\r\n#append reviews embeddings into sample\r\nsample = np.zeros(shape=(1,cur_word_dimen))\r\n\r\ny=[]\r\nfor _asin in asin_map_gene_reviews:\r\n sample=np.concatenate((sample,asin_map_gene_reviews[_asin]),axis=0)\r\n for i in range(asin_map_gene_reviews[_asin].shape[0]):\r\n y.append(asin_map_labels[_asin])\r\nsample=sample[1:]\r\n\r\nX=sample\r\n#change the random labels in y from 0 to N\r\nif(y[0]!=[]):\r\n all_labels=sorted(list(set(y[0])))\r\nnew_map_ylabel={}\r\nfor i in range(len(all_labels)):\r\n new_map_ylabel[all_labels[i]]=i\r\ny_new=[]\r\nfor each_all_labels in y:\r\n y_new.append(list(map(lambda x : new_map_ylabel[x],each_all_labels)))\r\ny_array=np.array(y_new)\r\n\r\n#y_col_count is the total label count\r\ny_col_count=y_array.shape[1]\r\n\r\nXgen_train, Xgen_test, ygen_train_all_labels, ygen_test_all_labels = \\\r\n train_test_split(X, y_array, test_size=0.5, random_state=30)\r\n\r\nygen_train=np.array(ygen_train_all_labels)[:,0].tolist()\r\nygen_test=np.array(ygen_test_all_labels)[:,0].tolist()\r\n\r\nsys.exit(0)\r\n#set(y_top_K[:,0])\r\n\r\n#--------finetune based on trained model \r\nif(classifier_type=='mlp'): \r\n finetune_classifier=MLPClassifier(hidden_layer_sizes=(100,100), max_iter=500, alpha=0.0001,\r\n solver='adam', verbose=0, random_state=21)\r\nif(classifier_type=='svm'): \r\n# finetune_classifier=OneVsRestClassifier(svm.SVC(kernel='linear', C=1, probability=True, random_state=0))\r\n finetune_classifier = OneVsRestClassifier(linear_model.SGDClassifier(max_iter=500, tol=1e-3,random_state=21))\r\n\r\n\r\n#get the original classifier's hidden layer's params \r\n#and get rid of the classification layer's param\r\n#refer to this url: https://stackoverflow.com/questions/45134834/fine-tuning-vs-retraining\r\nif(classifier_type=='mlp'): \r\n new_coefs=classifier.coefs_[:2]\r\n if(cur_exp_param=='cpu'):\r\n# new_coefs.append(np.random.rand(100, 23))\r\n new_coefs.append(np.zeros((100, 23)))\r\n if(cur_exp_param=='ram'):\r\n new_coefs.append(np.random.rand(100, 6))\r\n if(cur_exp_param=='hd'):\r\n new_coefs.append(np.random.rand(100, 11))\r\n if(cur_exp_param=='gpu'):\r\n new_coefs.append(np.random.rand(100, 8))\r\n if(cur_exp_param=='screen'):\r\n new_coefs.append(np.random.rand(100, 9))\r\n \r\n \r\n finetune_classifier.coefs_=new_coefs\r\n finetune_classifier.fit(Xgen_train,ygen_train)\r\n\r\n#copy the params, retrain by 50% generated data to finetune the params\r\nif(classifier_type=='svm'): \r\n# finetune_classifier.coef_=classifier.coef_\r\n finetune_classifier=deepcopy(classifier)\r\n finetune_classifier.fit(Xgen_train,ygen_train)\r\n \r\n#---------------finetune end---------------\r\n\r\nif(classifier_type=='svm'):\r\n #note that in svm predict_proba is inconsistent with predict function\r\n #use decision_function-->consistent\r\n y_pred_proba = finetune_classifier.decision_function(Xgen_test)#return inverse of distance\r\n\r\nif(classifier_type=='mlp'):\r\n y_pred_proba = finetune_classifier.predict_proba(Xgen_test)\r\n \r\nall_labels=finetune_classifier.classes_\r\n\r\n\r\nif(cur_exp_param=='cpu'):\r\n K=10\r\ny_top_K=[]\r\n#--pick out the max probability labels(by sorting predict_proba or decision_function)\r\n#--note this may be different in rnn\r\nif(classifier_type=='mlp' or classifier_type=='svm'):\r\n for each_proba in y_pred_proba:\r\n sort_proba_index = each_proba.argsort()\r\n #sort all_labels in descending order\r\n sorted_arr1 = all_labels[sort_proba_index[::-1]]\r\n y_top_K.append(sorted_arr1[:K])\r\ny_top_K=np.array(y_top_K)\r\n\r\n#sys.exit(0)\r\n\r\n\r\nprint(\"\\ncomponent type: {} \\nemddeing: {} \\nclassifier: {}\\n\"\\\r\n .format(cur_exp_param,cur_sent_embd_type,classifier_type))\r\n\r\nprint('ndcg:')\r\ni = 0\r\nndcgs = []\r\nlabels_to_eval=np.array(ygen_test_all_labels)#[:,:math.ceil(difference_percent*y_col_count)]\r\n \r\nif(cur_exp_param=='cpu'):\r\n K=10\r\n# this means we use 20% price difference (top4) as correct label \r\n labels_to_eval=np.array(ygen_test_all_labels)[:,:4]\r\nelse:\r\n# this means we only use the top 1 as the correct label\r\n labels_to_eval=np.array(ygen_test_all_labels)[:,:1]\r\n \r\nwhile i < K:\r\n \r\n y_pred = y_top_K[:, 0:i+1]\r\n i = i+1\r\n\r\n ndcg_i = func_eval._NDCG_score(y_pred,labels_to_eval)\r\n ndcgs.append(ndcg_i)\r\n\r\n print(ndcg_i)\r\n\r\n\r\nprint(\"precision:\")\r\ni = 0\r\nprecisions = []\r\nlabels_to_eval=np.array(ygen_test_all_labels)[:,:math.ceil(difference_percent*y_col_count)]\r\n \r\nwhile i < K:\r\n \r\n y_pred = y_top_K[:, 0:i+1]\r\n i = i+1\r\n\r\n precision = func_eval._precision_score(y_pred,labels_to_eval)\r\n precisions.append(precision)\r\n\r\n print(precision)\r\n\r\nprint(\"recall:\")\r\n\r\ni = 0\r\nrecalls = []\r\nwhile i < K:\r\n \r\n y_pred = y_top_K[:, 0:i+1]\r\n\r\n i = i+1 \r\n# labels_to_eval=np.array(y_test_all_labels)[:,:math.ceil(difference_percent*y_col_count)]\r\n recall = func_eval.new_recall(y_pred, labels_to_eval)\r\n recalls.append(recall)\r\n\r\n print(recall)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Experiments/Elmo/val_test_elmo.py","file_name":"val_test_elmo.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"579545125","text":"import bpy\r\nbpy.types.Scene.bf_author = \"Gillan\"\r\nbpy.types.Scene.bf_category = \"Grading\"\r\nbpy.types.Scene.bf_description = \"Warmest ignite your image.\"\r\nScene = bpy.context.scene\r\nTree = Scene.node_tree\r\n\r\nNode_G = bpy.data.node_groups.new(\"Warmest\", type='COMPOSITE')\r\n\r\nNode_1 = Node_G.nodes.new('COLORBALANCE')\r\nNode_1.correction_method = 'LIFT_GAMMA_GAIN'\r\nNode_1.inputs['Fac'].default_value = 0.5\r\nNode_1.lift = [1.160, 0.842, 0.807]\r\nNode_1.gamma = [1.165, 0.932, 0.879]\r\nNode_1.gain = [1.160, 1.075, 0.934]\r\n\r\nNode_G.inputs.new(\"Source\", 'RGBA')\r\nNode_G.outputs.new(\"Result\", 'RGBA')\r\nNode_G.links.new(Node_G.inputs[0], Node_1.inputs[1])\r\nNode_G.links.new(Node_G.outputs[0], Node_1.outputs[0])\r\n\r\nTree.nodes.new(\"GROUP\", group = Node_G)\r\n","sub_path":"scripts/addons_extern/compositing_preset/presets/compositing/WARMEST.py","file_name":"WARMEST.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"277973746","text":"import math\nfrom itertools import accumulate\nfrom typing import Any, Dict, List\n\nfrom ee.clickhouse.client import sync_execute\nfrom ee.clickhouse.queries.trends.util import parse_response\nfrom posthog.constants import TRENDS_CUMULATIVE, TRENDS_DISPLAY_BY_VALUE\nfrom posthog.models.cohort import Cohort\nfrom posthog.models.filters.filter import Filter\n\n\nclass ClickhouseTrendsFormula:\n def _label(self, filter: Filter, item: List, team_id: int) -> str:\n if filter.breakdown:\n if filter.breakdown_type == \"cohort\":\n if item[2] == 0:\n return \"all users\"\n return Cohort.objects.get(team=team_id, pk=item[2]).name\n return item[2]\n return \"Formula ({})\".format(filter.formula)\n\n def _run_formula_query(self, filter: Filter, team_id: int):\n letters = [chr(65 + i) for i in range(0, len(filter.entities))]\n queries = []\n params: Dict[str, Any] = {}\n for idx, entity in enumerate(filter.entities):\n sql, entity_params, _ = self._get_sql_for_entity(filter, entity, team_id) # type: ignore\n sql = sql.replace(\"%(\", \"%({}_\".format(idx))\n entity_params = {\"{}_{}\".format(idx, key): value for key, value in entity_params.items()}\n queries.append(sql)\n params = {**params, **entity_params}\n\n breakdown_value = (\n \", sub_A.breakdown_value\"\n if filter.breakdown_type == \"cohort\"\n else \", trim(BOTH '\\\"' FROM sub_A.breakdown_value)\"\n )\n is_aggregate = filter.display in TRENDS_DISPLAY_BY_VALUE\n\n sql = \"\"\"SELECT\n {date_select}\n arrayMap(({letters_select}) -> {formula}, {selects})\n {breakdown_value}\n FROM ({first_query}) as sub_A\n {queries}\n \"\"\".format(\n date_select=\"'' as date,\" if is_aggregate else \"sub_A.date,\",\n letters_select=\", \".join(letters),\n formula=filter.formula, # formula is properly escaped in the filter\n # Need to wrap aggregates in arrays so we can still use arrayMap\n selects=\", \".join(\n [\n (\"[sub_{}.data]\" if is_aggregate else \"sub_{}.data\").format(letters[i])\n for i in range(0, len(filter.entities))\n ]\n ),\n breakdown_value=breakdown_value if filter.breakdown else \"\",\n first_query=queries[0],\n queries=\"\".join(\n [\n \"FULL OUTER JOIN ({query}) as sub_{letter} ON sub_A.breakdown_value = sub_{letter}.breakdown_value \".format(\n query=query, letter=letters[i + 1]\n )\n for i, query in enumerate(queries[1:])\n ]\n )\n if filter.breakdown\n else \"\".join(\n [\" CROSS JOIN ({}) as sub_{}\".format(query, letters[i + 1]) for i, query in enumerate(queries[1:])]\n ),\n )\n result = sync_execute(sql, params)\n response = []\n for item in result:\n additional_values: Dict[str, Any] = {\n \"label\": self._label(filter, item, team_id),\n }\n if is_aggregate:\n additional_values[\"data\"] = []\n additional_values[\"aggregated_value\"] = item[1][0]\n else:\n additional_values[\"data\"] = [\n round(number, 2) if not math.isnan(number) and not math.isinf(number) else 0.0 for number in item[1]\n ]\n if filter.display == TRENDS_CUMULATIVE:\n additional_values[\"data\"] = list(accumulate(additional_values[\"data\"]))\n additional_values[\"count\"] = float(sum(additional_values[\"data\"]))\n response.append(parse_response(item, filter, additional_values))\n return response\n","sub_path":"ee/clickhouse/queries/trends/formula.py","file_name":"formula.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"293367712","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn.metrics import confusion_matrix\nfrom modelIO import saveTo\n# what is useful anyway?\ndef niche(z):\n jerk=(lambda x:pd.read_csv(x))\n x0,y=jerk('canonical0.csv'),jerk('canonical1.csv')\n x=x0.iloc[:,:].values\n y0=y.iloc[:,z].values\n#print(x)\n\n x0_train, x0_test, y0_train, y0_test = train_test_split(x, y0, test_size = 0.2)\n\n sc = StandardScaler()\n x0_train = sc.fit_transform(x0_train)\n x0_test = sc.transform(x0_test)\n\n classifier = Sequential()\n classifier.add(Dense(units = 6, kernel_initializer = 'uniform',activation = 'relu', input_dim = 10))\n# i have counted this.\n classifier.add(Dense(units = 6, kernel_initializer = 'uniform',activation = 'relu'))\n classifier.add(Dense(units = 1, kernel_initializer = 'uniform',activation = 'sigmoid'))\n\n# fuck you deeplearning!\n classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n classifier.fit(x0_train, y0_train, batch_size = 10, epochs = 50)\n\n y0_pred = classifier.predict(x0_test)\n y0_pred = (y0_pred > 0.5)\n\n new_prediction = classifier.predict(sc.transform\n (np.array([[3,50.666666666666664,8.013876853447538,2,35.666666666666664,8.5,45,62,45,62]])))\n new_prediction = (new_prediction > 0.5)\n\n cm = confusion_matrix(y0_test, y0_pred)\n print (cm)\n saveTo(classifier,\"conv\"+str(z))\n","sub_path":"multilingual/convolution/superHot.py","file_name":"superHot.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"41003312","text":"\nfrom numpy import *\nimport numpy as np\nimport operator\n\n\ndef createDataset():\n group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])\n labels = ['A', 'A', 'B', 'B']\n return group, labels\n\n\ndef classify0(inX, dataSet, labels, k):\n '''\n 简单进行kNN分类, 用欧氏距离计算距离\n :param inX: 输入数据的向量\n :param dataSet: 已有数据集\n :param labels: 已有数据集对应的标签\n :param k: 取 topK\n :return:\n '''\n dataSetSize = dataSet.shape[0]\n diffMat = tile(inX, (dataSetSize, 1)) - dataSet # tile函数将inX进行重复, 横向dataSetSize次重复, 纵向不重复(与dataSet作减法)\n sqDiffMat = diffMat**2 # 平方处理\n sqDistances = sqDiffMat.sum(axis=1) # axis=1 是每一行求和. axis=0是每一列求和.\n distances = sqDistances ** 0.5 # 得到输入数据与dataSet中每一项的距离\n sortedDistIndicies = np.argsort(distances) # 对距离进行排序\n classCount = {} # 创建一个map,记录topK的标签和count\n for i in range(k):\n voteIlabel = labels[sortedDistIndicies[i]]\n classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1\n sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) # 排序类别字典\n return sortedClassCount[0][0]\n\n\n# 约会网站配对\ndef file2matrix(filename):\n '''\n 将文件转换为矩阵\n :param filename:\n :return:\n '''\n labelMap = {'largeDoses': 3, 'smallDoses': 2, 'didntLike': 1}\n with open(filename, 'r', encoding='utf-8') as f:\n arrayOLines = f.readlines()\n numberOfLines = len(arrayOLines)\n returnMat = zeros((numberOfLines, 3)) # 创建返回的矩阵 (n x 3的矩阵)\n classLabelVector = []\n index = 0\n for line in arrayOLines:\n line = line.strip()\n listFromLine = line.split('\\t')\n returnMat[index, :] = listFromLine[0:3]\n index += 1\n classLabelVector.append(labelMap.get(listFromLine[-1])) # 标签数组\n return returnMat, classLabelVector # 返回矩阵和标签\n\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\ndef showDatingData(filename):\n '''\n 用Matplotlib绘图\n :param filename:\n :return:\n '''\n datingDataMat,datingLabels = file2matrix(filename)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 15.0*array(datingLabels), 15.0*array(datingLabels))\n plt.show()\n\n\ndef autoNorm(dataSet):\n '''\n 归一化处理, 飞行里程数和玩游戏的时间,在数值上差距很大,这样就非常影响最终距离的计算. 需要进行归一化\n 最常用的归一化方法: newValue = (oldValue - min)/ (max-min)\n :param dataSet:\n :return:\n '''\n minVals = dataSet.min(0) # 按列取最小值, 返回每列最小值组成的向量.\n maxVals = dataSet.max(0)\n ranges = maxVals - minVals\n normDataSet = zeros(shape(dataSet))\n m = dataSet.shape[0] # 行数\n normDataSet = dataSet - tile(minVals, (m, 1)) # 重复minVals, 行重复m次, 列重复1次.\n normDataSet = normDataSet/tile(ranges, (m, 1))\n return normDataSet, ranges, minVals\n\n\ndef datingClassTest():\n hoRatio = 0.10 # 测试数据的比例\n datingDataMat,datingLabels = file2matrix('datingTestSet.txt') # 加载数据源\n normMat, ranges, minVals = autoNorm(datingDataMat) # 归一化\n m = normMat.shape[0] # 获取行数\n numTestVecs = int(m * hoRatio) # 获取测试的行数\n errorCount = 0.0 # 错误率\n for i in range(numTestVecs):\n classifierResult = classify0(normMat[i, :],\n normMat[numTestVecs:m, :], # 测试数据之外的 90% 作为模型的数据(训练数据)\n datingLabels[numTestVecs:m], 3)\n print(\"the classifier came back with: %d, the real answer is : %d\" % (classifierResult, datingLabels[i]))\n if classifierResult != datingLabels[i]:\n errorCount += 1.0\n print(\"the total error rate is : %f\" %(errorCount/float(numTestVecs)))\n\n\n\ndef classifyPerson():\n '''\n 约会分类器的可用系统, 用户输入数据, 完成预测\n :return:\n '''\n resultList = ['not at all', 'in small doses', 'in large doses']\n percentTats = float(input(\"percentage of time spent playing video games?\"))\n ffMiles = float(input(\"frequent flier miles earned per year?\"))\n iceCream = float(input(\"liters of ice cream consumed per year?\"))\n datingDataMat, datingLables = file2matrix('datingTestSet.txt')\n normMat, ranges, minVals = autoNorm(datingDataMat)\n inArr = array([ffMiles, percentTats, iceCream])\n classifierResult = classify0((inArr-minVals)/ranges, normMat, datingLables, 3)\n print(\"You will probably like this person: \", resultList[classifierResult - 1])\n\n\n'''\n以下算法用KNN进行图像识别, 识别0-9数字\n'''\n\n\ndef img2vector(filename):\n '''\n 将每一个图像(32*32)转换成1*1024的向量\n :param filename: 输入已转化数字文件的路径\n :return: 1 x 1024的向量\n '''\n returnVect = zeros((1,1024))\n with open(filename, 'r', encoding=\"UTF-8\") as fr:\n for i in range(32):\n lineStr = fr.readline()\n for j in range(32):\n returnVect[0, 32*i + j] = int(lineStr[j])\n return returnVect\n\n\nif __name__ == '__main__':\n # dataSet, labels = createDataset()\n # print(classify0([0, 0], dataSet, labels, 3))\n datingFile = 'datingTestSet.txt'\n # datingDataMat, datingLabels = file2matrix(datingFile)\n # showDatingData(datingFile)\n\n # 测试模型\n # datingClassTest()\n\n # 实际应用\n classifyPerson()\n\n\n # print('123')\n\n","sub_path":"src/com/mininglamp/nlp/ch2/kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"160859616","text":"import json\nimport math\nimport os\nimport warnings\nfrom concurrent.futures import ProcessPoolExecutor, as_completed, wait\nfrom datetime import datetime\n\nimport cartopy.crs as ccrs\nimport matplotlib as mpl\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport netCDF4\nimport numpy as np\nimport numpy.ma as ma\nimport pandas as pd\nfrom cartopy.io import LocatedImage, PostprocessedRasterSource\nfrom cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER\nfrom matplotlib import gridspec\nfrom matplotlib.colors import LightSource, rgb2hex\nfrom matplotlib.legend_handler import HandlerPatch\nfrom matplotlib.offsetbox import AnchoredText\nfrom matplotlib.patches import Circle, Ellipse, Rectangle\nfrom matplotlib.ticker import NullFormatter\nfrom matplotlib.transforms import Bbox\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom obspy.imaging.beachball import beach\nfrom pyproj import Geod\nfrom scipy import interpolate, stats\n\nfrom GetData import AbstractFaultProcess\nfrom scalebar import dist_func_complete, scale_bar\nfrom utils import *\n\nwarnings.filterwarnings(\"ignore\")\n\nGMRT_BATHY_GRID = \"/mnt/disk6/pshi/otfloc2/bathy\"\n\n\nclass PlotProcedure(AbstractFaultProcess):\n\n def __init__(self, name):\n super().__init__(name)\n with open(os.path.join(self.dir, \"mt.json\")) as fp:\n self.fm = json.load(fp)\n\n for i in range(2, 5):\n self.config[\"adjust\"].setdefault(str(i), {\"lat\": 0.0, \"lon\": 0.0})\n\n\n def plotTimeSpaceLayout(self, overWrite=True):\n output = os.path.join(self.dir, \"layout.pdf\")\n\n if not overWrite and os.path.isfile(output):\n return\n\n clipped_date_post1950 = datetime(1949, 6, 1)\n clipped_date_post1995 = datetime(1994, 12, 31)\n clipped_date_post1990 = datetime(1989, 12, 31)\n\n rotatediff = 90 - self.df[\"strike\"].iloc[0] % 180\n if rotatediff > 0:\n rotlon0 = self.df[\"Longitude\"].iloc[0] - 90\n rotlat0 = 90 - rotatediff\n else:\n rotlon0 = self.df[\"Longitude\"].iloc[0] + 90\n rotlat0 = 90 + rotatediff\n rotatedpole = ccrs.RotatedPole(rotlon0, rotlat0, 0.0)\n\n dfMerged = pd.read_csv(os.path.join(self.dir, \"catalog-merged.csv\"))\n\n figsize = (10, 8)\n fig = plt.figure(figsize=figsize)\n grid = gridspec.GridSpec(5, 2, height_ratios=[1, 1, 1, 1, 1], width_ratios=[1, 1])\n ax0 = fig.add_subplot(grid[:, 0])\n ax2 = fig.add_subplot(grid[3:, -1], projection=rotatedpole)\n ax1 = fig.add_subplot(grid[0:2, -1], projection=rotatedpole)\n ax3 = fig.add_subplot(grid[2, -1])\n plt.subplots_adjust(hspace=0.12, wspace=0.05)\n\n # axes width match up with rotated pole projection\n # https://stackoverflow.com/questions/15480113/force-aspect-ratio-for-a-map\n ax1.set_adjustable('datalim')\n ax2.set_adjustable('datalim')\n\n extent0 = self.config[\"extent\"]\n extent = setExtentByRatio(extent0, angle=90 - self.df[\"strike\"].iloc[0] % 180)\n ax1.set_extent(extentZoom(extent, np.abs(rotatediff)), crs=ccrs.PlateCarree())\n ax2.set_extent(extentZoom(extent, np.abs(rotatediff)), crs=ccrs.PlateCarree())\n ax0pos = ax0.get_position().bounds\n ax1pos = ax1.get_position().bounds\n ax2pos = ax2.get_position().bounds\n\n if self.name == \"\":\n for x in [ax1, ax2]:\n x.add_wms(\n # wms=\"https://www.gmrt.org/services/mapserver/wms_merc?\",\n wms=\"https://www.gebco.net/data_and_products/gebco_web_services/2019/mapserv?\",\n layers=[\"GEBCO_2019_Grid\"],\n )\n else:\n def getBathymetryFromGMRTByExtent(name):\n f = netCDF4.Dataset(os.path.join(GMRT_BATHY_GRID, name + \".grd\"))\n x_range = f.variables[\"x_range\"][:]\n y_range = f.variables[\"y_range\"][:]\n dims = f.variables[\"dimension\"][:]\n xx = np.linspace(x_range[0], x_range[1], dims[0])\n yy = np.linspace(y_range[0], y_range[1], dims[1])\n zz = f.variables[\"z\"][:]\n # zz = -np.abs(zz) # wrong GMRT data perhaps\n zz = np.reshape(zz, (dims[1], dims[0]))\n return xx, yy, zz, [x_range[0], x_range[1], y_range[0], y_range[1]]\n\n bathylon, bathylat, bathyelv, bathyextent = getBathymetryFromGMRTByExtent(name)\n maxelv, minelv = np.nanmin(bathyelv), np.nanmax(bathyelv)\n elvmaxnorm = maxelv + (minelv - maxelv) * 1.1\n dx = bathylon[len(bathylon)//2] - bathylon[len(bathylon)//2-1]\n dy = bathylat[len(bathylat)//2] - bathylat[len(bathylat)//2-1]\n dy = 111200 * dy\n dx = 111200 * dx * np.cos(np.radians(np.nanmean(bathylat))) # dx vary with latitude\n ls = LightSource(azdeg=self.df[\"strike\"].values[0]-45.0, altdeg=45)\n cmapBathy = plt.cm.get_cmap(\"YlGnBu_r\")\n origin = \"upper\"\n shade_data = np.where(np.isnan(bathyelv.data), 0.0, bathyelv.data)\n z = ls.shade(\n shade_data, # nan val corrupt lightsource\n cmap=cmapBathy, vert_exag=50.0, dx=dx, dy=dy, blend_mode=\"overlay\", fraction=1.0,\n vmin=maxelv, vmax=elvmaxnorm)\n ax1.get_position().bounds\n ax2.get_position().bounds\n ax2.imshow(z, extent=bathyextent, origin=origin, transform=ccrs.PlateCarree(), cmap=cmapBathy, interpolation='nearest')\n ax1.imshow(z, extent=bathyextent, origin=origin, transform=ccrs.PlateCarree(), cmap=cmapBathy, interpolation='nearest')\n\n gl = ax1.gridlines(draw_labels=True, color='black', alpha=0.5, linestyle='--', zorder=1, x_inline=False, y_inline=False)\n gl.ylabels_left = False\n gl.ylabels_right = True\n gl.xlabels_top = True\n gl.xlabels_bottom = False\n gl.xlocator = mticker.MaxNLocator(4)\n gl.ylocator = mticker.MaxNLocator(4)\n\n gl = ax2.gridlines(draw_labels=True, color='black', alpha=0.5, linestyle='--', zorder=1, x_inline=False, y_inline=False)\n gl.ylabels_left = False\n gl.ylabels_right = True\n gl.xlabels_top = False\n gl.xlabels_bottom = True\n gl.xlocator = mticker.MaxNLocator(4)\n gl.ylocator = mticker.MaxNLocator(4)\n\n scale_bar(ax1, (0.80, 0.10), self.config[\"ruler\"], color='black', angle=0, text_offset=0.015)\n xdist = dist_func_complete(ax1, [0.0, 0.5], [1.0, 0.5])\n ratio = self.config[\"ruler\"] / xdist * 1e3\n ax0.plot([0.8, 0.8 + ratio], [datetime(1952, 1, 1), datetime(1952, 1, 1)], lw=3.0, color=\"k\")\n ax0.text(0.8 + ratio / 2, datetime(1953, 1, 1), s=f\"{self.config['ruler']:.0f} km\" ,horizontalalignment='center', verticalalignment='center')\n\n ax0.set_ylim(bottom=clipped_date_post1950, top=datetime(2022, 1, 1))\n ax0.set_xlim(left=0, right=1)\n ax0.xaxis.set_major_formatter(NullFormatter())\n ax0.xaxis.set_ticks_position('none')\n ax0.set_xticklabels([])\n ax0.set_ylabel(\"Time\")\n ax0.yaxis.set_major_locator(mdates.YearLocator(10))\n ax0.yaxis.set_major_formatter(mdates.DateFormatter('%Y'))\n ax0.grid(True, which=\"major\", axis=\"x\")\n ax0.set_xlabel(\"Scaled Along Strike Position\")\n ax0.tick_params(labelbottom=True, labeltop=True)\n\n ax3.set_xticklabels([])\n ax3.set_xlim(left=0, right=1)\n ax3.set_xticks([])\n ax3.yaxis.tick_right()\n ax3.yaxis.set_label_position('right')\n ax3.set_xlabel(\"Scaled Along Strike Position\", labelpad=2.0, fontsize=\"x-small\")\n\n def full_extent(ax, pad=0.0):\n # https://stackoverflow.com/questions/14712665/matplotlib-subplot-background-axes-face-labels-colour-or-figure-axes-coor\n \"\"\"Get the full extent of an axes, including axes labels, tick labels, and\n titles.\"\"\"\n # For text objects, we need to draw the figure first, otherwise the extents\n # are undefined.\n ax.figure.canvas.draw()\n items = ax.get_xticklabels() + ax.get_yticklabels()\n items += [ax, ax.title]\n items += [ax.xaxis.get_label()]\n bbox = Bbox.union([item.get_window_extent() for item in items])\n return bbox.expanded(1.0 + pad, 1.0 + pad)\n\n # cax = ax1.inset_axes([0.635, 0.18, 0.3, 0.034])\n # cax.set_facecolor([1, 1, 1, 0.65])\n # cbar = fig.colorbar(im, cax=cax, orientation=\"horizontal\", extend='both', shrink=0.9)\n # cax.patch.set_facecolor('black')\n # cbar.ax.set_xlabel('Water Depth (m)')\n # cbar.ax.xaxis.set_major_locator(mticker.LinearLocator(numticks=3))\n # extentBg = full_extent(cax)\n # extentBg = extentBg.transformed(ax1.transAxes.inverted())\n # rect = Rectangle([extentBg.xmin, extentBg.ymin], extentBg.width, extentBg.height,\n # facecolor=[1.0, 1.0, 1.0, 0.65], edgecolor='none', zorder=3, # notice zorder is per-axis, not global\n # transform=ax1.transAxes)\n # ax1.patches.append(rect)\n\n at = AnchoredText(f\"{self.name} | {self.df['Vpl (mm/yr)'].iloc[0]:.0f} mm/yr | {self.df['Length (km)'].iloc[0]:.0f} km\", loc='upper right', frameon=True,)\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n ax1.add_artist(at)\n\n def _get_ax_scale_ratio(xlim, ylim, xspan, yspan):\n return ((ylim[1] - ylim[0]) / yspan) / ((xlim[1] - xlim[0]) / xspan) * figsize[0] / figsize[1]\n\n ax0scaleratio = _get_ax_scale_ratio(ax0.get_xlim(), ax0.get_ylim(), ax0.get_position().bounds[2], ax0.get_position().bounds[3])\n ax1scaleratio = _get_ax_scale_ratio(ax1.get_xlim(), ax1.get_ylim(), ax1.get_position().bounds[2], ax1.get_position().bounds[3])\n beachballSizeFunc = lambda x: (x - 3.0) / 70 # notice here xlim [0, 1]\n beachballSizeOnMapFunc = lambda x: beachballSizeFunc(x) * (ax1.get_xlim()[1] - ax1.get_xlim()[0])\n # https://stackoverflow.com/questions/14827650/pyplot-scatter-plot-marker-size/47403507#47403507\n # https://stackoverflow.com/questions/48172928/scale-matplotlib-pyplot-axes-scatter-markersize-by-x-scale/48174228#48174228\n sqrtsizeinpoint = ax0.get_window_extent().width / (ax0.get_xlim()[1] - ax0.get_xlim()[0]) * 72 / fig.dpi\n\n # scaling of scatter plot\n normalization = 12\n dftmp = dfMerged.copy()\n lats = dftmp[\"lat\"].to_numpy() + np.array([self.config[\"adjust\"].get(str(x), {'lat': 0, 'lon': 0})['lat'] for x in dftmp[\"group\"]])\n lons = dftmp[\"lon\"].to_numpy() + np.array([self.config[\"adjust\"].get(str(x), {'lat': 0, 'lon': 0})['lon'] for x in dftmp[\"group\"]])\n dftmp['lat'] = lats\n dftmp['lon'] = lons\n dftmp = dftmp[(dftmp['lat'] >= extent0[2]) & (dftmp['lat'] <= extent0[3]) & (dftmp['lon'] >= extent0[0]) & (dftmp['lon'] <= extent0[1])]\n dftmp['time'] = pd.to_datetime(dftmp['time'])\n dftmp = dftmp[dftmp['time'] > datetime(1990, 1, 1,)]\n dftmp['istransform'] = dftmp['id'].apply(lambda x: isTransform(self.fm[x]['np1']))\n dftmp = dftmp[dftmp['istransform']]\n if dftmp.shape[0] == 0:\n mmag = dfMerged[\"mag\"].max()\n else:\n dftmp = dftmp[dftmp['group'] != -1]\n mmag = dftmp[\"mag\"].max()\n if np.isnan(mmag):\n mmag = dfMerged[\"mag\"].max()\n normalization *= (5.6 ** (mmag - 3)) / (5.6 ** (6.1 - 3))\n\n # beachballSizePt2x = lambda x: (x - 3.0) * 5 / sqrtsizeinpoint\n beachballSizePt2x = lambda x: 5.6 ** (x - 3.0) / normalization / sqrtsizeinpoint\n # beachballSizePt2x = lambda x: np.sqrt(10 ** (x * 3/2)) / 3e3 / sqrtsizeinpoint\n beachballSizePt2xOnMap = lambda x: beachballSizePt2x(x) * (ax1.get_xlim()[1] - ax1.get_xlim()[0])\n\n def _get_fm_fc_(eid, isrelocated=True):\n np1 = self.fm[str(eid)][\"np1\"]\n bcc = \"tab:red\" if isrelocated else \"silver\"\n if eid in anchors:\n bcc = \"darkgoldenrod\"\n if np.isnan(self.fm[str(eid)][\"np1\"][0]):\n if np.isnan(self.fm[str(eid)][\"mt\"][0]):\n _fm = [1.0, 1.0, 1.0, 0.0, 0.0, 0.0] # mimic scatter solid circle\n bcc = \"lightpink\" if isrelocated else \"white\"\n else:\n # _fm = fms[str(self.df.id.iloc[0])][\"mt\"] # not use, need rotation matrix\n pass\n else:\n _fm = self.fm[str(eid)][\"np1\"]\n\n if len(_fm) != 6:\n _fm[0] += rotatediff\n return _fm, bcc\n\n def transform_t_day(t: str):\n _t = datetime.fromisoformat(t)\n _days = (_t - datetime(1970, 1, 1)).days + 1\n return _t, _days\n\n def transform_xy_xyproj(proj, x, y):\n xy = proj.transform_points(ccrs.PlateCarree(), np.array([x]), np.array([y]))[0]\n return xy[0], xy[1]\n\n def transform_xyproj_xyr(ax, xp, yp):\n return ax.transLimits.transform((xp, yp))\n\n def _add_beachball(r, isrelocated, fc=\"tab:red\", forcedot=False):\n _t, _days = transform_t_day(r.time)\n _mag = r.mag\n if isrelocated:\n x, y = r.lon + self.config[\"adjust\"][str(r.group)][\"lon\"], r.lat + self.config[\"adjust\"][str(r.group)][\"lat\"]\n _zorder = 5\n _alpha = 1.0\n else:\n x, y = r.lon, r.lat\n _zorder = 2\n _alpha = 0.5\n xp, yp = transform_xy_xyproj(rotatedpole, x, y)\n xr, yr = transform_xyproj_xyr(ax1, xp, yp)\n if x < extent0[0] or x > extent0[1] or y < extent0[2] or y > extent0[3] or _t <= clipped_date_post1950:\n return\n widthbc0 = (beachballSizePt2x(_mag), beachballSizePt2x(_mag) * ax0scaleratio)\n widthbc1 = (beachballSizePt2xOnMap(_mag), beachballSizePt2xOnMap(_mag) * ax1scaleratio)\n _fm, bcc = _get_fm_fc_(r.id, isrelocated)\n bc0 = beach(_fm, alpha=_alpha, linewidth=1.0, facecolor=bcc, bgcolor=\"white\", xy=(xr, _days), width=widthbc0, zorder=_zorder)\n ax0.add_collection(bc0)\n bc1 = beach(_fm, alpha=_alpha, linewidth=1.0, facecolor=bcc, bgcolor=\"white\", xy=(xp, yp), width=widthbc1, zorder=_zorder)\n ax1.add_collection(bc1)\n if isrelocated:\n ax2.scatter(x, y, s=3**2, fc=bcc, ec=\"k\", transform=ccrs.PlateCarree())\n\n adjust = self.config[\"adjust\"]\n anchors = set()\n for k in adjust:\n if \"anchor\" in adjust[k]:\n rr = dfMerged[dfMerged[\"id\"] == adjust[k][\"anchor\"][\"id\"]]\n anchors.add(adjust[k][\"anchor\"][\"id\"])\n adjust[k][\"lon\"] = adjust[k][\"anchor\"][\"lon\"] - rr.lon.values[0]\n adjust[k][\"lat\"] = adjust[k][\"anchor\"][\"lat\"] - rr.lat.values[0]\n print(f\"adjust: {rr.group.values[0]}, lat: {adjust[k]['lat']}, lon: {adjust[k]['lon']}\")\n\n for r in dfMerged.itertuples():\n _add_beachball(r, r.group != -1)\n\n attempt = datetime(1990, 1, 1) # cutoff of attempting relocation\n ax0.plot([0, 1], [attempt, attempt], linestyle=\"--\", color=\"lightcoral\")\n magcutoff = self.config[\"magCutOff\"]\n ax0.text(0.02, datetime(1991, 6, 1), f\"Relocate \\nMw$\\geq${magcutoff:.1f}\", color=\"lightcoral\", backgroundcolor=(0.9, 0.9, 0.9, 0.5), zorder=6)\n\n def momentHist(func=momentAlongStrikeEllipsoid):\n xs, mws = [], [] # all event after 1950\n xs2, mws2 = [], [] # all event after 1995/1990\n xs3, mws3 = [], [] # all relocated event\n for r in dfMerged.iloc[::-1].itertuples():\n fm = self.fm[str(r.id)][\"np1\"]\n if not isTransform(fm):\n continue\n\n if r.group == -1:\n x, y = r.lon, r.lat\n else:\n x, y = r.lon + self.config[\"adjust\"][str(r.group)][\"lon\"], r.lat + self.config[\"adjust\"][str(r.group)][\"lat\"]\n\n if x < extent0[0] or x > extent0[1] or y < extent0[2] or y > extent0[3]:\n continue\n # pass\n\n xp, yp = transform_xy_xyproj(rotatedpole, x, y)\n xr, _ = transform_xyproj_xyr(ax1, xp, yp)\n xs.append(xr); mws.append(r.mag)\n if datetime.fromisoformat(r.time) >= clipped_date_post1990:\n xs2.append(xr); mws2.append(r.mag)\n if r.group != -1:\n xs3.append(xr); mws3.append(r.mag)\n\n xdist = dist_func_complete(ax1, [0.0, 0.5], [1.0, 0.5]) / 1000 # km\n arr, rr = func(xdist, xs, mws)\n arr2, rr2 = func(xdist, xs2, mws2)\n arr3, rr3 = func(xdist, xs3, mws3)\n ax3.plot(rr, arr / (2020-1950) / 1e13, color=\"cadetblue\", label=\"since 1950\")\n # ax3.plot(rr2, arr2 / (2020-1990) / 1e13, color=\"royalblue\", label=\"since 1990\")\n ax3.plot(rr3, arr3 / (2020-1990) / 1e13, color=\"deeppink\", label=\"relocated only\") # relocate attempt after 1990\n ax3.legend(\n loc=\"upper center\", ncol=3, title=\"$E_{\\mathrm{year}}[ \\Sigma (M_{0}/L) ]$\",\n # bbox_to_anchor=(0.5, 0.99),\n fontsize='xx-small', title_fontsize=\"xx-small\")\n ax3.set_ylabel(\"Unit Moment Rate\\n($ 10 ^{13} \\cdot \\mathrm{N} \\;/ \\;\\mathrm{yr}$)\")\n\n if \"edge\" in self.config:\n li = self.config[\"edge\"][\"l\"]\n ri = self.config[\"edge\"][\"r\"]\n edges = []\n for x in [li, ri]:\n xp, yp = transform_xy_xyproj(rotatedpole, x[1], x[0])\n xr, _ = transform_xyproj_xyr(ax1, xp, yp)\n edges.append(xr)\n if edges[0] > edges[1]:\n edges.reverse()\n\n # rect = Rectangle((edges[0], 0), edges[1] - edges[0], 1, transform=ax3.transAxes, fc=\"lightgray\", alpha=0.6)\n # ax3.add_patch(rect)\n thrd = 0.1\n peak = np.max(arr3) / (2020-1990) / 1e13\n creepPct = creepPercentage(arr3 / (2020-1990), rr3, edges[0], edges[1], thrd)\n creepIndex, shape = creepMask(arr3 / (2020-1990), rr3, edges[0], edges[1], thrd)\n creepPct1950 = creepPercentage(arr / (2020-1950), rr, edges[0], edges[1], thrd)\n creepIndex1950, shape1950 = creepMask(arr / (2020-1950), rr, edges[0], edges[1], thrd)\n\n # plot 1950 or relocated\n rrp, cpidx = rr, creepIndex1950\n # rrp, cpidx = rr3, creepIndex\n for x in cpidx:\n rect = Rectangle((rrp[x[0]], 0), rrp[x[1]] - rrp[x[0]], 1, transform=ax3.transAxes, fc=\"lightgray\", alpha=0.6)\n ax3.add_patch(rect)\n\n self.config[\"creepPercentage\"] = creepPct\n self.config[\"creepPercentage1950\"] = creepPct1950\n self.updateConfig()\n ax3.text(0.725, 0.9, f\"CSF = {creepPct:.2f}|{creepPct1950:.2f}\", transform=ax3.transAxes, ha=\"left\", va=\"center\", fontsize=9)\n\n expected = self.df[\"At\"] * 1e6 * 3e10 * self.df[\"Vpl (mm/yr)\"] / 1e3 / self.df[\"Length (km)\"] / 1e3\n expected /= 1e13\n if not np.isnan(expected.values[0]):\n ax3.plot([0.0, 1.0], [expected, expected], linestyle=\":\", color=\"forestgreen\", linewidth=1.0)\n ax3.text(0.9, expected, \"$\\dot{M}_{E}$\", color=\"forestgreen\")\n\n with open(os.path.join(self.dir, \"umrr.json\"), \"w\") as fp:\n d = {\n \"relocated\": {\n \"x\": list(rr3), \"y\": list(arr3 / (2020-1990) / 1e13),\n \"index\": [int(y) for x in creepIndex for y in x],\n },\n \"1950\": {\n \"x\": list(rr), \"y\": list(arr / (2020-1950) / 1e13),\n },\n \"At\": expected.values[0],\n }\n json.dump(d, fp, indent=4)\n ax3.set_ylim(bottom=0)\n\n momentHist()\n\n ls = []\n if mmag < 5.8:\n magLengendSize = [5.0, 5.3, 5.6]\n elif mmag < 6.3:\n magLengendSize = [5.0, 5.5, 6.0]\n elif mmag < 6.8:\n magLengendSize = [5.5, 6.0, 6.5]\n else:\n magLengendSize = [6.0, 6.5, 7.0]\n\n magLengendSize = [mmag - 1, mmag - 0.5, mmag]\n magLengendLabel = [f\"{x:.1f}\" for x in magLengendSize]\n for i in range(len(magLengendSize)):\n l = ax0.scatter([],[], ec=\"gray\", fc=\"white\", s=(beachballSizePt2x(magLengendSize[i])*sqrtsizeinpoint)**2)\n ls.append(l)\n leg = ax0.legend(\n ls, magLengendLabel, ncol=3, frameon=True, borderpad=0.4, bbox_to_anchor=(0.5, 1.0),\n loc=\"lower center\", title=\"Mw\", fancybox=True, labelspacing=1.0, framealpha=1.0,\n handletextpad=1.2, borderaxespad=1.2, fontsize='small', title_fontsize=\"small\")\n\n for t, x in zip([\"A\", \"B\", \"C\", \"D\"], [ax0, ax1, ax3, ax2]):\n loc = \"upper left\"\n at = AnchoredText(t, loc=loc, frameon=True,)\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n x.add_artist(at)\n\n if self.name == \"Gofar\":\n ax2.text(0.3, 0.55, \"G3\", transform=ax2.transAxes, color=\"Purple\", backgroundcolor=\"white\")\n ax2.text(0.56, 0.62, \"G2\", transform=ax2.transAxes, color=\"Purple\", backgroundcolor=\"white\")\n ax2.text(0.76, 0.70, \"G1\", transform=ax2.transAxes, color=\"Purple\", backgroundcolor=\"white\")\n\n sub_ax = fig.add_axes([ax2pos[0]-0.01, ax2pos[1], 0.10, 0.10], projection=ccrs.NearsidePerspective(self.df[\"Longitude\"].iloc[0], self.df[\"Latitude\"].iloc[0]))\n sub_ax.set_adjustable(\"datalim\")\n sub_ax.stock_img()\n sub_ax.scatter(self.df[\"Longitude\"].iloc[0], self.df[\"Latitude\"].iloc[0], s=50, marker=\"*\", c=\"orange\")\n\n fig.savefig(output, dpi=600, bbox_inches=\"tight\")\n plt.close(fig)\n\ndef plotting(name):\n f = PlotProcedure(name.strip())\n f.plotTimeSpaceLayout()\n\nif __name__ == \"__main__\":\n\n names = dfFaults[\"Name\"].to_list()\n for i, name in enumerate(names):\n print(f\"{i + 1}/{len(names)}: {name}\")\n f = PlotProcedure(name.strip())\n f.plotTimeSpaceLayout()\n\n # parallel plotting does not correctly render figures\n # with ProcessPoolExecutor(max_workers=2) as executor:\n # futures = []\n # for i, name in enumerate(names):\n # print(f\"{i + 1}/{len(names)}: {name}\")\n # futures.append(executor.submit(plotting, name))\n # wait(futures)\n","sub_path":"src/PlotResults.py","file_name":"PlotResults.py","file_ext":"py","file_size_in_byte":22832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"445752159","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom IPython import embed\n\ndef compute_pixel_acc(pred, label, fg_only=True):\n '''\n pred: BHW\n label: BHW\n '''\n assert pred.shape == label.shape\n if fg_only:\n valid = (label > 0)\n acc_sum = (valid * (pred == label)).sum()\n valid_sum = valid.sum()\n acc = float(acc_sum) / (valid_sum + 1e-10)\n return acc, valid_sum\n else:\n acc_sum = (pred == label).sum()\n acc = float(acc_sum) / (np.prod(pred.shape))\n return acc, 0\n\ndef compute_binary_precision(pred, label):\n '''\n pred: BHW\n label: BHW\n '''\n assert pred.shape == label.shape\n tp = np.logical_and(pred == 1, label == 1).sum()\n fp = np.logical_and(pred == 1, label == 0).sum()\n return tp * 1.0 / (tp + fp + 1e-15)\n\ndef compute_binary_recall(pred, label):\n '''\n pred: BHW\n label: BHW\n '''\n assert pred.shape == label.shape\n tp = np.logical_and(pred == 1, label == 1).sum()\n fn = np.logical_and(pred == 0, label == 1).sum()\n return tp * 1.0 / (tp + fn + 1e-15)\n\ndef compute_iou(pred_map, label_map, num_classes, fg_only=True, ignore_mask=True):\n \"\"\"\n Param\n - ignore_mask: set to True if there are targets to be ignored. Pixels whose value equal to 255\n are excluded from benchmarking.\n \"\"\"\n pred_map = np.asarray(pred_map).copy()\n label_map = np.asarray(label_map).copy()\n\n assert pred_map.shape == label_map.shape\n\n if ignore_mask:\n valid_idx = (label_map != -1)\n pred_map = pred_map[valid_idx]\n label_map = label_map[valid_idx]\n\n # When computing intersection, all pixels that are not\n # in the intersection are masked with zeros.\n # So we add 1 to the existing mask so that background pixels can be computed\n pred_map += 1\n label_map += 1\n\n # Compute area intersection:\n intersection = pred_map * (pred_map == label_map)\n (area_intersection, _) = np.histogram(\n intersection, bins=num_classes, range=(1, num_classes))\n\n # Compute area union:\n (area_pred, _) = np.histogram(pred_map, bins=num_classes, range=(1, num_classes))\n (area_lab, _) = np.histogram(label_map, bins=num_classes, range=(1, num_classes))\n area_union = area_pred + area_lab - area_intersection\n\n if fg_only:\n # Remove first bg channel\n return np.sum(area_intersection[1:]) / (np.sum(area_union[1:]) + 1e-10)\n else:\n return np.sum(area_intersection) / np.sum(area_union)\n","sub_path":"modules/utils/semantic_metric.py","file_name":"semantic_metric.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"491682971","text":"# Hard version of memory game (10x10)\n\"\"\"\nChanges:\n1. Changed 8x8 to 10x10\n2. Added more images\n3. Randomized which image would appear at the end\n4. Raised numbers allowed in game\n5. Changed font size to not overstep on other tiles\n\"\"\"\n\nfrom random import *\nfrom turtle import *\nfrom time import *\nfrom sys import *\nfrom freegames import path\nimport os\n\n#This holds the value of the current working directory for easier file referencing\ncwd = os.path.dirname(os.path.realpath(__file__))\n\n#Creating the picture and tile objects\nimage_dic = {} #Making a random image to appear when doing puzzle\nimage_dic['car'] = path(cwd + '/car.gif')\nimage_dic['dino'] = path(cwd + '/dinosaur.gif')\nimage_dic['house'] = path(cwd + '/house.gif')\nimage_dic['dog'] = path(cwd + '/dog.gif')\nimage_dic['nova'] = path(cwd + '/supernova.gif')\nimage = choice(list(image_dic.values()))\ntiles = list(range(50)) * 2\nstate = {'mark': None}\nhide = [True] * 100\n\n#Creating a square plus its size components\ndef square(x, y):\n \"Draw white square with black outline at (x, y).\"\n up()\n goto(x, y)\n down()\n color('black', 'white')\n begin_fill()\n for count in range(4):\n forward(40)\n left(90)\n end_fill()\n\n#Indexes of each tile (1-100)\ndef index(x, y):\n \"Convert (x, y) coordinates to tiles index.\"\n return int((x + 200) // 40 + ((y + 200) // 40) * 10)\n\n#How many tiles\ndef xy(count):\n \"Convert tiles count to (x, y) coordinates.\"\n return (count % 10) * 40 - 200, (count // 10) * 40 - 200\n\n#Lets the user tap on tiles and reveal numbers, and give error if out of scope of tiles\ndef tap(x, y):\n \"Update mark and hidden tiles based on tap.\"\n spot = index(x, y)\n mark = state['mark']\n\n if mark is None or mark == spot or tiles[mark] != tiles[spot]:\n state['mark'] = spot #if you click somewhere outside the boxes get error\n else:\n hide[spot] = False\n hide[mark] = False\n state['mark'] = None\n\n#Drawing the images and tiles\ndef draw():\n \"Draw image and tiles.\"\n clear()\n goto(0, 0)\n shape(image)\n stamp()\n\n for count in range(100):\n if hide[count]:\n x, y = xy(count)\n square(x, y)\n\n mark = state['mark']\n#Out of bounds error\n if mark is not None and hide[mark]:\n x, y = xy(mark)\n up()\n goto(x + 2, y)\n color('black')\n write(tiles[mark], font=('Arial', 22, 'normal'))\n\n update()\n ontimer(draw, 100)\n#Shuffling of tile numbers and creating the viewer\nshuffle(tiles)\nsetup(420, 420, 370, 0)\naddshape(image)\nhideturtle()\ntracer(False)\nonscreenclick(tap)\ndraw()\ndone()\n","sub_path":"freegames/memory_hard.py","file_name":"memory_hard.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"247003188","text":"from set import HashSet\nimport unittest\n\nclass SetTest(unittest.TestCase):\n\n def test_init(self):\n elements = ['A', 'B', 'C']\n set = HashSet(elements)\n assert set.size is 3\n\n def test_size(self):\n elements = ['A', 'B', 'C', 'D', 'E']\n set = HashSet(elements)\n assert set.size is 5\n\n def test_contains(self):\n elements = ['P', 'C', 'X', 'U']\n set = HashSet(elements)\n assert set.contains('P') is True\n assert set.contains('C') is True\n assert set.contains('U') is True\n assert set.contains('D') is False\n assert set.contains('J') is False\n\n def test_add(self):\n elements = ['J', 'K']\n set = HashSet(elements)\n set.add('P')\n set.add('E')\n with self.assertRaises(KeyError):\n set.add('K') # Element already exists\n with self.assertRaises(KeyError):\n set.add('E') # Element already exists\n assert set.size is 4\n assert set.contains('P') is True\n assert set.contains('E') is True\n\n def test_remove(self):\n elements = ['U', '8', 'Q', 'D']\n set = HashSet(elements)\n with self.assertRaises(KeyError):\n set.remove('K') # Element doesn't exist\n with self.assertRaises(KeyError):\n set.remove('0') # Element doesn't exist\n set.remove('U')\n set.remove('Q')\n assert set.contains('U') is False\n assert set.contains('Q') is False\n with self.assertRaises(KeyError):\n set.remove('Q') # Element doesn't exist anymore\n\n def test_union(self):\n elements = ['A', 'C', 'D', 'F']\n elements2 = ['A', 'B', 'D', 'F', 'G', 'H']\n elements3 = ['C', 'Y', 'T', 'A']\n set = HashSet(elements)\n set2 = HashSet(elements2)\n set3 = HashSet(elements3)\n self.assertCountEqual(set.union(set2).hash.values(), ['A', 'B', 'C', 'D', 'F', 'G', 'H']) # Ignore item order\n self.assertCountEqual(set.union(set3).hash.values(), ['A', 'C', 'D', 'F', 'T', 'Y']) # Ignore item order\n\n def test_intersection(self):\n elements = ['0', 'B', 'C', 'K']\n elements2 = ['0', 'D', 'E', 'C', 'Y', 'K']\n elements3 = ['B', 'D', 'P', 'K', 'G', '9']\n set = HashSet(elements)\n set2 = HashSet(elements2)\n set3 = HashSet(elements3)\n self.assertCountEqual(set.intersection(set2).hash.values(), ['0', 'C', 'K']) # Ignore item order\n self.assertCountEqual(set.intersection(set3).hash.values(), ['B', 'K']) # Ignore item order\n\n def test_difference(self):\n elements = ['4', '7', '8', '9', '0']\n elements2 = ['4', '5', '6', '10', '8', '9']\n elements3 = ['1', '3', '5', '7', '0']\n set = HashSet(elements)\n set2 = HashSet(elements2)\n set3 = HashSet(elements3)\n self.assertCountEqual(set.difference(set2).hash.values(), ['7', '0']) # Ignore item order\n self.assertCountEqual(set.difference(set3).hash.values(), ['4', '8', '9']) # Ignore item order\n\n def test_is_subset(self):\n elements = ['Y', 'C', 'D']\n elements2 = ['C', 'G', 'U', 'D', 'T', 'Y']\n elements3 = ['P', 'H', 'Y', 'D', 'E', 'F']\n set = HashSet(elements)\n set2 = HashSet(elements2)\n set3 = HashSet(elements3)\n assert set.is_subset(set2) is True\n assert set.is_subset(set3) is False\n assert set2.is_subset(set3) is False\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Code/set_test.py","file_name":"set_test.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"424579564","text":"\"\"\"Multithreading workers for the vcd.\"\"\"\n\nimport logging\nimport threading\nimport time\nimport webbrowser\n\nfrom queue import Queue\n\nfrom ._requests import DownloaderError\nfrom .links import BaseLink\nfrom .subject import Subject\nfrom .time_operations import seconds_to_str\nfrom .utils import getch\n\n\nclass Worker(threading.Thread):\n \"\"\"Special worker for vcd multithreading.\"\"\"\n\n def __init__(self, queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.logger = logging.getLogger(__name__)\n self.queue: Queue = queue\n self.status = 'idle'\n self.timestamp = None\n self.current_object = None\n self.active = True\n\n def to_log(self, integer=False):\n color = 'black'\n exec_time = 0\n status_code = 0\n\n if self.timestamp is not None:\n exec_time = time.time() - self.timestamp\n\n if exec_time < 30:\n color = 'green'\n status_code = 1\n elif 30 <= exec_time < 60:\n color = \"orange\"\n status_code = 2\n elif 60 <= exec_time < 90:\n color = \"red\"\n status_code = 3\n else:\n color = \"magenta\"\n status_code = 4\n\n status = f'{self.name}: {self.status} - '\n\n if status_code == 4:\n status += f'[{seconds_to_str(exec_time, integer=integer)}] '\n\n if isinstance(self.current_object, BaseLink):\n status += f'{self.current_object.subject.name} → {self.current_object.name}'\n elif isinstance(self.current_object, Subject):\n status += f'{self.current_object.name}'\n elif isinstance(self.current_object, str):\n status += self.current_object\n else:\n status += 'None'\n\n status += ''\n\n return (status, status_code)\n\n # noinspection PyUnresolvedReferences\n def run(self):\n \"\"\"Runs the thread\"\"\"\n while self.active:\n self.status = 'idle'\n self.logger.info('Worker %r ready to continue working', self.name)\n anything = self.queue.get()\n self.timestamp = time.time()\n self.logger.debug('%d items left in queue (%d unfinished tasks)', self.queue.qsize(),\n self.queue.unfinished_tasks)\n\n self.status = 'working'\n self.current_object = anything\n\n if isinstance(anything, BaseLink):\n self.logger.debug('Found Link %r, processing', anything.name)\n try:\n anything.download()\n except FileNotFoundError as ex:\n self.logger.exception('FileNotFoundError in url %s (%r)', anything.url, ex)\n except DownloaderError as ex:\n self.logger.exception('DownloaderError in url %s (%r)', anything.url, ex)\n\n self.logger.info('Worker %r completed work of Link %r', self.name, anything.name)\n self.queue.task_done()\n\n elif isinstance(anything, Subject):\n self.logger.debug('Found Subject %r, processing', anything.name)\n try:\n anything.find_links()\n except DownloaderError as ex:\n self.logger.exception('DownloaderError in subject %s (%r)', anything.name, ex)\n\n self.logger.info('Worker %r completed work of Subject %r', self.name, anything.name)\n self.queue.task_done()\n elif anything is None:\n self.logger.info('Closing thread, received None')\n self.logger.info('%d unfinished tasks', self.queue.unfinished_tasks)\n self.current_object = None\n self.timestamp = None\n return\n elif anything == 'killed':\n self.status = 'killed'\n break\n\n self.logger.info('%d unfinished tasks', self.queue.unfinished_tasks)\n self.current_object = None\n self.timestamp = None\n\n # if self.status == 'killed':\n self.timestamp = None\n self.current_object = 'Dead thread'\n\n for thread in threading.enumerate():\n if isinstance(thread, Worker):\n self.queue.put('killed')\n thread.status = 'killed'\n thread.active = 0\n\n while True:\n foo = self.queue.get()\n if not foo:\n break\n self.queue.task_done()\n\n exit()\n\n\nclass Killer(threading.Thread):\n def __init__(self, queue):\n super().__init__(name='Killer', daemon=True)\n self.queue = queue\n self.status = 'online'\n\n def to_log(self, *args, **kwargs):\n output = f'{self.name}: {self.status}'\n return (output, 0)\n\n def run(self):\n print('Killer ready')\n while True:\n try:\n char = getch()\n real = char.decode().lower()\n except UnicodeError:\n continue\n\n if real in ('q', 'k'):\n print('Exiting')\n\n for thread in threading.enumerate():\n if isinstance(thread, Worker):\n thread.active = False\n thread.status = 'killed'\n\n self.status = 'commited suicide'\n exit(1)\n\n if real in ('w', 'o'):\n print('Opening status server')\n chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\n webbrowser.get(chrome_path).open_new('localhost')\n\n\ndef start_workers(queue, nthreads=20, no_killer=False):\n \"\"\"Starts the wokers.\n\n Args:\n queue (Queue): queue to manage the workers's tasks.\n nthreads (int): number of trheads to start.\n\n Returns:\n\n \"\"\"\n\n thread_list = []\n\n if no_killer is False:\n killer = Killer(queue)\n killer.start()\n thread_list.append(killer)\n else:\n print('Killer not started')\n\n for i in range(nthreads):\n thread = Worker(queue, name=f'W-{i + 1:02d}', daemon=True)\n thread.logger.debug('Started worker named %r', thread.name)\n thread.start()\n thread_list.append(thread)\n\n return thread_list\n","sub_path":"vcd/_threading.py","file_name":"_threading.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"268900428","text":"\n\nfrom xai.brain.wordbase.adjectives._fierce import _FIERCE\n\n#calss header\nclass _FIERCER(_FIERCE, ):\n\tdef __init__(self,): \n\t\t_FIERCE.__init__(self)\n\t\tself.name = \"FIERCER\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"fierce\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_fiercer.py","file_name":"_fiercer.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"441304729","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n' augmentation script '\n\n__author__ = 'Zhuzhen Li'\n\nimport cv2 as cv\nimport numpy as np\nimport imageio\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nfrom imgaug import parameters as iap\nfrom matplotlib.pyplot import *\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport random\nimport os, shutil\nfrom shutil import copyfile\nfrom distutils.dir_util import copy_tree\nimport xml.etree.ElementTree as ET\nimport pdb\nimport shutil\n\n# global variables setting\ninput_height=128\ninput_width=96\nlist_size = 32\nbatch_size = 8\n# red_range = (1, random.randint(1,200))\n# blue_range = (1, random.randint(1,200))\n# green_range = (1, random.randint(1,200))\nred_range = (1, 200)\nblue_range = (1, 200)\ngreen_range = (1, 200)\nresize_height= (0.3,0.5)\nresize_width= (0.3,0.5)\nsuperpixel_p = (0.1, 0.25)\nsuperpixel_n = (32, 128)\ngau_blur_size = (0.0, 3.0)\navg_blur_size = (2, 3)\nmed_blur_size = (3, 5)\nsharpen_alpha=(0.0, 0.2)\nsharpen_lightness=(0.0, 2.0)\nemboss_alpha= (0.0, 0.2)\nemboss_strength=(0.2, 0.4)\nadd_size = (-20, 20)\nadd_per_channel_size = 0.2\ngaussian_noise=(0, 0.02*255)\nmultiply_scale= (0.9, 1.1)\ndropout_p=(0, 0.2)\ncoarse_dropout = 0.02\ncontrast_normal_scale = (0, 1)\nspnoise= (0.3, 300)\naffine_translate_x=(-0.05, 0.05)\naffine_translate_y=(-0.05, 0.05)\naffine_rotate=(-30, 30)\naffine_shear = (-2, 2)\npiecewise_affine_scale= (0.01, 0.02)\nelastic_alpha = (0,0.5)\nelastic_sigma = 0.01\nsample = 128\n\ndef coloring (digit):\n image_name = '00'+ str(digit)+ '000'+\".jpg\"\n # Load and display\n image = imageio.imread(image_name)\n # image = cv.resize(image, (input_width,input_height), interpolation=cv.INTER_CUBIC)\n# print(\"Original:\", image.shape)\n# ia.imshow(image)\n\n images = np.array([image for _ in range(sample)], dtype=np.uint8)\n seq_color= iaa.Sequential([iaa.WithChannels(0, iaa.Add(red_range)),\n iaa.WithChannels(1, iaa.Add(green_range)),\n iaa.WithChannels(2, iaa.Add(blue_range))\n ], random_order=True)\n \n images_color_aug = seq_color(images=images)\n# ia.imshow(ia.draw_grid(images_color_aug, cols=sample/8, rows=8))\n return images_color_aug\n\ndef trans (images_color_aug):\n #ia.seed(1)\n seq = iaa.Sequential([iaa.Resize({\"height\": resize_height , \"width\": resize_width }),\n iaa.Affine(translate_percent={\"x\": affine_translate_x, \"y\": affine_translate_y}),\n iaa.Affine(rotate=affine_rotate),\n iaa.Affine(shear=affine_shear),\n iaa.PiecewiseAffine(scale=piecewise_affine_scale),\n iaa.ElasticTransformation(alpha=elastic_alpha, sigma=elastic_sigma)\n ], random_order=True)\n \n images_trans_aug = seq(images=images_color_aug)\n# ia.imshow(ia.draw_grid(images_trans_aug, cols=sample/8, rows=8))\n return images_trans_aug\n\n\ndef distortion (images_trans_aug):\n #ia.seed(1)\n seq = iaa.Sequential([# iaa.Superpixels(p_replace=superpixel_p, n_segments=superpixel_n),\n iaa.GaussianBlur(sigma=gau_blur_size),\n iaa.AverageBlur(k=avg_blur_size),\n iaa.MedianBlur(k=med_blur_size),\n iaa.Sharpen(alpha=sharpen_alpha, lightness=sharpen_lightness),\n iaa.Emboss(alpha=emboss_alpha, strength=emboss_strength),\n # iaa.Add(add_size, per_channel= add_per_channel_size),\n iaa.AdditiveGaussianNoise(scale=gaussian_noise, per_channel=0.2),\n # iaa.Multiply(multiply_scale, per_channel=0.2),\n # iaa.Dropout(p=dropout_p, per_channel=0.2),\n # iaa.CoarseDropout(0.1, size_percent=coarse_dropout, per_channel=0.2)\n ], random_order=True)\n images_aug = seq(images=images_trans_aug)\n# ia.imshow(ia.draw_grid(images_aug, cols=sample/8, rows=8))\n return images_aug\n\n\n\ndef create_dir():\n os.chdir('./VOC2007')\n os.getcwd()\n \n # Create directory\n dirName = 'JPEGImages'\n \n try:\n # Create target Directory\n os.mkdir(dirName)\n print(\"Directory\" , dirName , \" Successfully Created \")\n \n except FileExistsError:\n filesToRemove = [os.path.join(dirName, f) for f in os.listdir(dirName)]\n for f in filesToRemove :\n os.remove(f)\n print(\"Directory\" , dirName , \"already exists, empty the existing directory.\")\n\n\n\ndef save (images_aug, digit):\n path = './'\n # load images to directory\n for i in range (sample):\n index = i + 1\n if index < 10:\n index = '00' + str(index)\n elif index < 100:\n index = '0' + str(index)\n else:\n index = str(index)\n filename = '00' + str(digit) + index +\".jpg\"\n # resize before save\n images_aug[i] = cv.resize(images_aug[i], (300,400), interpolation=cv.INTER_CUBIC)\n cv.imwrite(os.path.join(path, filename), images_aug[i])\n\n\n\nif __name__=='__main__':\n create_dir()\n os.chdir(\"./../\")\n \n digit_dir = './digit'\n des_dir = './VOC2007/JPEGImages'\n copy_tree(digit_dir, des_dir)\n print(\" Successully copy the original images to\", des_dir)\n\n os.chdir(des_dir)\n for i in range (10):\n augmentation = distortion(trans(coloring(i)))\n save(augmentation, i)\n\n # check if successful generate:\n number_of_files = len([item for item in os.listdir(\"./\") if os.path.isfile(os.path.join(\"./\",item))])\n if number_of_files != (sample * 10 + 10 + 1) :\n print (\"Error occurs in image augmentation, please double check!\")\n print (number_of_files-1, \"files in\", des_dir)\n","sub_path":"augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"371414417","text":"# coding = 'utf-8'\nimport numpy as np\nimport pandas as pd\nfrom time import time\nimport tm\n\ndef target_mean_v1(data, y_name, x_name):\n result = np.zeros(data.shape[0])\n for i in range(data.shape[0]):\n groupby_result = data[data.index != i].groupby([x_name], as_index=False).agg(['mean', 'count'])\n result[i] = groupby_result.loc[groupby_result.index == data.loc[i, x_name], (y_name, 'mean')]\n return result\n\n\ndef target_mean_v2(data, y_name, x_name):\n result = np.zeros(data.shape[0]) # 行数\n value_dict = dict()\n count_dict = dict()\n for i in range(data.shape[0]):\n # 第 i 行\n if data.loc[i, x_name] not in value_dict.keys():\n value_dict[data.loc[i, x_name]] = data.loc[i, y_name]\n count_dict[data.loc[i, x_name]] = 1\n else:\n value_dict[data.loc[i, x_name]] += data.loc[i, y_name]\n count_dict[data.loc[i, x_name]] += 1\\\n\n for i in range(data.shape[0]):\n result[i] = (value_dict[data.loc[i, x_name]] - data.loc[i, y_name]) / (count_dict[data.loc[i, x_name]] - 1)\n\n return result\n\n\ndef main():\n size = 100000\n print(f'{size} test data start in {time()}, please wait.')\n y = np.random.randint(2, size=(size, 1))\n x = np.random.randint(10, size=(size, 1))\n data = pd.DataFrame(np.concatenate([y, x], axis=1), columns=['y', 'x'])\n\n start_2 = time()\n target_mean_v2(data, 'y', 'x')\n end_2 = time()\n print(f'v2 is the python version, use time: {end_2 - start_2}')\n\n start_3 = time()\n tm.target_mean_v3(data, 'y', 'x')\n end_3 = time()\n print(f'v3 is the version showed by Mr.Wang, use time: {end_3 - start_3}')\n\n start_4 = time()\n tm.target_mean_v4(data, 'y', 'x')\n end_4 = time()\n print(f'v4 is my job, use time: {end_4 - start_4}')\n\nif __name__ == '__main__':\n main()\n","sub_path":"machine/week2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"224812801","text":"from tensorpack.callbacks import Callback\nfrom tensorpack.tfutils.common import get_global_step_var\nfrom tensorflow.contrib.model_pruning.python import pruning\n\n\nclass PruningCallback(Callback):\n '''\n Tensorpack callback for pruning.\n '''\n def __init__(self, param_dict):\n '''\n Convert parameter dict to parameter string.\n '''\n self.param_dict = param_dict\n\n def _setup_graph(self):\n '''\n '''\n default_dict = {\n 'name': 'model_pruining',\n 'begin_pruning_step': 0,\n 'end_pruning_step': 34400,\n 'target_sparsity': 0.31,\n 'pruning_frequency': 344,\n 'sparsity_function_begin_step': 0,\n 'sparsity_function_end_step': 34400,\n 'sparsity_function_exponent': 2,\n }\n for k, v in self.param_dict.items():\n if k in default_dict:\n default_dict[k] = v\n\n param_list = ['{}={}'.format(k, v) for k, v in default_dict.items()]\n # param_list = [\n # \"name=cifar10_pruning\",\n # \"begin_pruning_step=1000\",\n # \"end_pruning_step=20000\",\n # \"target_sparsity=0.9\",\n # \"sparsity_function_begin_step=1000\",\n # \"sparsity_function_end_step=20000\"\n # ]\n\n PRUNE_HPARAMS = \",\".join(param_list)\n pruning_hparams = pruning.get_pruning_hparams().parse(PRUNE_HPARAMS)\n self.p = pruning.Pruning(pruning_hparams, global_step=get_global_step_var())\n self.p.add_pruning_summaries()\n self.mask_update_op = self.p.conditional_mask_update_op()\n\n def _trigger_step(self):\n self.trainer.sess.run(self.mask_update_op)\n","sub_path":"pruning/pruning_callback.py","file_name":"pruning_callback.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"436043122","text":"from sage.all import *\n# from sage.rings.all import *\n# from sage.structure.all import *\n# from sage.rings.finite_rings.finite_field_constructor import *\n# # from sage.rings.finite_rings.finite_field_constructor.PolynomialRing import *\n# from sage.rings.polynomial import *\nfrom Encoder.sflash_record import *\nfrom mi_decoder import MIDecoder\nfrom Utils import utils\nimport base64\n\nheader = '-----BEGIN SFLASH PRIVATE KEY BLOCK-----\\n'\nfooter = '\\n-----END SFLASH PRIVATE KEY BLOCK-----'\nclass SflashDecoder(MIDecoder):\n\n\tdef decodePublicKey(self, file):\n\t\tpubRecord = SflashPublicRecord()\n\t\tencoded = \"\"\n\t\tlines = file.readlines()\n\t\tfor i in xrange(1, len(lines) - 1):\n\t\t\tencoded += lines[i]\n\t\tdecoded = pubRecord.decode(self.encoding, base64.b64decode(encoded))\n\t\tp = int(decoded[0][0].prettyPrint())\n\t\tbaseField = int(decoded[0][1].prettyPrint())\n\t\tn = int(decoded[0][2].prettyPrint())\n\t\tself.writeFile(p, baseField, n)\n\t\tload(\"polys.sage\")\n\t\tvars = self.getVars(K)\n\t\tpolySize = ((n+1)*(n+2)*baseField / 2)\n\t\tpolynomials = bin(int(decoded[0][3].prettyPrint(), 10))[2:]\n\t\tres = polySize - (len(polynomials) % polySize)\n\t\t# Fill with zeros binary string\n\t\tif(res != polySize):\n\t\t\tfor i in range(res):\n\t\t\t\tpolynomials = \"0\" + polynomials\n\t\tPolySet = self.decodePolynomials(polynomials, n + 1, len(polynomials) / (((n+1)*(n+2)*baseField)/2), vars, k, baseField, K)\n\t\treturn PolySet\n\n\tdef getVars(self, K):\n\t\tvars = []\n\t\tvars.append(1)\n\t\tfor i in range(K.ngens()):\n\t\t\tvars.append(K.gens()[i])\n\t\treturn vars\n\n\tdef decodePolynomials(self, polynomials, n, m, vars, F, d, K):\n \tbinSize = ((n * (n + 1)) / 2) * d\n\t PolySet = []\n\t pol = []\n\t for i in range(m):\n\t pol.append(0)\n\t PolySet = vector(K, pol)\n\t x = F.gen()\n\t for i in range(m):\n\t polynomial = polynomials[i*binSize:(i*binSize) + binSize]\n\t z = 0\n\t poly = 0\n\t for j in range(n):\n\t for k in xrange(j, n):\n\t index = d*z\n\t coef = polynomial[index:index + d]\n\t z += 1\n\t coefficient = 0\n\t for l in range(d-1):\n\t if coef[l] == \"1\":\n\t coefficient += x**((d - 1)-l)\n\t if coef[d-1] == \"1\":\n\t coefficient += 1\n\t poly += coefficient * (vars[j] * vars[k])\n\t #PolySet.append(poly)\n\t PolySet[i] = poly\n\t return PolySet\n\n\tdef writeFile(self, p, baseField, n):\n\t\tf = open(\"polys.sage\", \"w\")\n\t\tf.write(\"R. = GF(\" + str(p) + \")[]\\n\")\n\t\tf.write(\"k. = GF(\" + str(p) + \"**\" + str(baseField) + \", GF(\" + str(p) + \")['X'].irreducible_element(\" + str(baseField) + \"))\\n\")\n\t\tf.write(\"K = PolynomialRing(k, \\\"x\\\", \" + str(n) + \", order='deglex')\")\n\t\tf.close()\n\n\tdef generateAffine(self, affine, n, p, baseField, k):\n\t\tS = []\n\t\ts = []\n\t\tz = 0\n\t\tfor i in range(n):\n\t\t\tS.append([])\n\t\t\tfor j in range(n):\n\t\t\t\tindex = z*baseField\n\t\t\t\tz += 1\n\t\t\t\tpoly = int(affine[index:index + baseField], 2)\n\t\t\t\tif(baseField > 1):\n\t\t\t\t\tS[i].append(k.fetch_int(poly))\n\t\t\t\telse:\n\t\t\t\t\tS[i].append(poly)\n\t\tfor i in range(n):\n\t\t\tindex = z*baseField\n\t\t\tz += 1\n\t\t\tpoly = int(affine[index:index + baseField], 2)\n\t\t\tif(baseField > 1):\n\t\t\t\ts.append(k.fetch_int(poly))\n\t\t\telse:\n\t\t\t\ts.append(poly)\n\t\treturn S, s\n\n\tdef fillZeros(self, p, size):\n\t\tdif = size - len(p)\n\t\tfor i in range(dif):\n\t\t\tp = \"0\" + p\n\t\treturn p\n\n\tdef decodePrivateKey(self, file):\n\t\tprivRecord = SflashPrivateRecord()\n\t\tencoded = \"\"\n\t\tlines = file.readlines()\n\t\tfor i in xrange(1, len(lines) - 1):\n\t\t\tencoded += lines[i]\n\t\tdecoded = privRecord.decode(self.encoding, base64.b64decode(encoded))\n\t\tp = int(decoded[0][0].prettyPrint())\n\t\tbaseField = int(decoded[0][1].prettyPrint())\n\t\ttheta = int(decoded[0][2].prettyPrint())\n\t\tn = int(decoded[0][3].prettyPrint())\n\t\tself.writeFile(p, baseField, n)\n\t\tload(\"polys.sage\")\n\t\tS, s = self.generateAffine(self.fillZeros(bin(int(decoded[0][4].prettyPrint()))[2:], ((n*n) + n) * baseField), n, p, baseField, k)\n\t\tm = int(decoded[0][5].prettyPrint())\n\t\tT, t = self.generateAffine(self.fillZeros(bin(int(decoded[0][6].prettyPrint()))[2:], ((m*m) + m) * baseField), n, p, baseField, k)\n\t\treturn n, S, s, m, T, t, p, baseField, theta\n","sub_path":"encoding/Decoder/sflash_decoder.py","file_name":"sflash_decoder.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"177502033","text":"import verbose as v\n\n__author__ = 'Yaacov'\n\nverbose_msg = True\n\n\nclass Combatant:\n \"\"\"Common base class for all combatants\"\"\"\n def __init__(self, combat, attacks_list={}, name=\"\", max_hits=30, hits=30, status=\"Normal\", max_PP=0, PP=0, AT=1,\n DB_melee=0, DB_ranged=0, max_exhpts=40, exhpts=40, init_bonus=0, constitution=50):\n self.combat = combat\n if name:\n self.name = name\n else:\n self.name = \"Orc \" + str(combat.num_of_combatants)\n self.max_hits = max_hits\n self.hits = hits\n self.status = status\n self.max_PP = max_PP\n self.PP = PP\n self.attacks_list = attacks_list\n self.AT = AT\n self.DB_melee = DB_melee\n self.DB_ranged = DB_ranged\n self.max_exhpts = max_exhpts\n self.exhpts = exhpts\n self.initiative_bonus = init_bonus\n self.current_action = None\n self.stun_no_parry_ends_at = 0\n self.stun_ends_at = 0\n self.must_parry_ends_at = 0\n self.initiative_loss_ends_at = 0\n self.constitution = constitution\n self.time_of_death = None\n\n def __str__(self):\n return self.name\n\n def update_info(self, name, max_hits, hits, status, max_PP, PP, AT, DB_melee, DB_ranged, max_exhpts, exhpts, init_bonus):\n self.name = name\n self.max_hits = max_hits\n self.hits = hits\n self.status = status\n self.max_PP = max_PP\n self.PP = PP\n self.AT = AT\n self.DB_melee = DB_melee\n self.DB_ranged = DB_ranged\n self.max_exhpts = max_exhpts\n self.exhpts = exhpts\n self.initiative_bonus = init_bonus\n\n def add_attack(self, attack):\n self.attacks_list[attack.name]= attack\n\n def get_attack(self, name):\n return self.attacks_list[name]\n\n def get_attack_names(self):\n return list(self.attacks_list.keys())\n\n def update_status(self):\n if self.hits > 0:\n if self.stun_no_parry_ends_at > self.combat.time:\n self.status = \"Stunned, No Parry\"\n elif self.stun_ends_at > self.combat.time:\n self.status = \"Stunned\"\n elif self.must_parry_ends_at > self.combat.time:\n self.status = \"Must Parry\"\n else:\n self.status = \"\"\n hit_percentage = float(self.hits) / float(self.max_hits)\n i = 0\n while hit_percentage > self.combat.hits_statuses[i][0]:\n i += 1\n self.status = self.status + \"/\" + self.combat.hits_statuses[i][1]\n elif self.hits > -self.constitution:\n self.status = \"Unconscious\"\n elif self.hits <= -self.constitution:\n self.status = \"Dead\"\n","sub_path":"combatant.py","file_name":"combatant.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"91396926","text":"#!/usr/local/bin/python3\n#A couple ways to define an object\n\nclass MediaObj(object):\n #pass is used when a statement is required syntactically\n #but you do not want any command or code to execute\n pass\n\nclass Media(object):\n #constructor\n def __init__(self):\n self.url = \"\"\n self.titlefull = \"\"\n self.type = \"\"\n self.rel = \"\"\n\n #to string method\n def __str__(self):\n return self.url + \"\\n\" + self.titlefull + \"\\n\" + self.type + \"\\n\" + self.rel\n \n #display method\n def display(self):\n print(\"\\n Title : \"+ self.titlefull)\n print(\"\\n Url : \"+ self.url)\n print(\"\\n Type : \"+ self.type)\n print(\"\\n Rel : \"+ self.rel)\n\n #property initializer\n def setFromLink(self,link):\n self.rel = link.attrib['rel']\n self.type = link.attrib['type']\n self.url = link.attrib['href']\n return\n","sub_path":"xml_parser/mediaobj.py","file_name":"mediaobj.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"583787241","text":"# coding: utf-8\n#\n# Copyright 2017 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Decorators to provide authorization across the site.\"\"\"\n\nfrom core.domain import rights_manager\nfrom core.domain import role_services\nimport feconf\n\n\ndef check_activity_accessible(\n user_id, user_actions, activity_type, activity_id):\n \"\"\"Returns a boolean to signify whether given activity is accessible\n by the user or not.\n\n Args:\n user_id: str. Id of the given user.\n user_actions: list(str). List of actions given user can perform.\n activity_id: str. Id of the given activity.\n activity_type: str. Signifies whether activity is exploration or\n collection.\n\n Returns:\n bool. Whether the given activity can be accessed.\n \"\"\"\n if activity_type == feconf.ACTIVITY_TYPE_EXPLORATION:\n if activity_id in feconf.DISABLED_EXPLORATION_IDS:\n return False\n\n activity_rights = (\n rights_manager.get_exploration_rights(activity_id, strict=False)\n if activity_type == feconf.ACTIVITY_TYPE_EXPLORATION\n else rights_manager.get_collection_rights(activity_id, strict=False))\n\n action_play_public = (\n role_services.ACTION_PLAY_ANY_PUBLIC_EXPLORATION\n if activity_type == feconf.ACTIVITY_TYPE_EXPLORATION\n else role_services.ACTION_PLAY_ANY_PUBLIC_COLLECTION)\n\n action_play_private = (\n role_services.ACTION_PLAY_ANY_PRIVATE_EXPLORATION\n if activity_type == feconf.ACTIVITY_TYPE_EXPLORATION\n else role_services.ACTION_PLAY_ANY_PRIVATE_COLLECTION)\n\n if activity_rights is None:\n return False\n elif activity_rights.status == rights_manager.ACTIVITY_STATUS_PUBLIC:\n return bool(action_play_public in user_actions)\n elif activity_rights.status == rights_manager.ACTIVITY_STATUS_PRIVATE:\n return bool(\n (action_play_private in user_actions) or\n (user_id in activity_rights.viewer_ids) or\n (user_id in activity_rights.owner_ids) or\n (user_id in activity_rights.editor_ids) or\n activity_rights.viewable_if_private)\n\n\ndef can_play_exploration(handler):\n \"\"\"Decorator to check whether user can play given exploration.\"\"\"\n\n def test_can_play(self, exploration_id, **kwargs):\n if check_activity_accessible(\n self.user_id, self.actions, feconf.ACTIVITY_TYPE_EXPLORATION,\n exploration_id):\n return handler(self, exploration_id, **kwargs)\n else:\n raise self.PageNotFoundException\n\n return test_can_play\n\n\ndef can_play_collection(handler):\n \"\"\"Decorator to check whether user can play given collection.\"\"\"\n\n def test_can_play(self, collection_id, **kwargs):\n if check_activity_accessible(\n self.user_id, self.actions, feconf.ACTIVITY_TYPE_COLLECTION,\n collection_id):\n return handler(self, collection_id, **kwargs)\n else:\n raise self.PageNotFoundException\n\n return test_can_play\n\n\ndef can_download_exploration(handler):\n \"\"\"Decorator to check whether user can download given exploration.\n If a user is authorized to play given exploration, they can download it.\n \"\"\"\n\n def test_can_download(self, exploration_id, **kwargs):\n if check_activity_accessible(\n self.user_id, self.actions, feconf.ACTIVITY_TYPE_EXPLORATION,\n exploration_id):\n return handler(self, exploration_id, **kwargs)\n else:\n raise self.PageNotFoundException\n\n return test_can_download\n\n\ndef can_view_exploration_stats(handler):\n \"\"\"Decorator to check whether user can view exploration stats.\n If a user is authorized to play given exploration, they can view its stats.\n \"\"\"\n\n def test_can_view_stats(self, exploration_id, **kwargs):\n if check_activity_accessible(\n self.user_id, self.actions, feconf.ACTIVITY_TYPE_EXPLORATION,\n exploration_id):\n return handler(self, exploration_id, **kwargs)\n else:\n raise self.PageNotFoundException\n\n return test_can_view_stats\n","sub_path":"core/domain/acl_decorators.py","file_name":"acl_decorators.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"429101695","text":"import logging\nimport pprint\nimport sys\nimport os\nimport socket\nimport pprint\nfrom gunicorn import glogging\n\nfrom flask import request\n\nclass RequestFormatter(logging.Formatter):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def format(self, record):\n try:\n record.url = request.url\n except:\n record.url = \"EMPTY_URL\"\n\n record.hostname = socket.gethostname()\n record.base_hostname = os.getenv(\"BASE_HOSTNAME\", \"EMPTYHOST\")\n\n try:\n record.remote_addr = request.remote_addr\n except:\n record.remote_addr = \"-\"\n\n return super(RequestFormatter, self).format(record)\n\ndef setup_logging(app):\n\n from flask.logging import default_handler\n\n #This is imported by gunicorn, it needs to be top level\n request_log_formatter = RequestFormatter(\n '[%(asctime)s] [%(base_hostname)s:%(hostname)s:%(process)3d] [%(levelname)-7s] [%(remote_addr)-15s] %(url)s :: %(pathname)s:%(lineno)d %(message)s'\n )\n\n\n default_handler.setFormatter(request_log_formatter)\n if not 'pytest' in sys.modules:\n app.logger.error(\"Startup test-error message\")\n app.logger.info(\"app.config:\\n\" + pprint.pformat(app.config))\n\n\nclass CustomLogger(glogging.Logger):\n \"\"\"Custom logger for Gunicorn log messages.\"\"\"\n\n def setup(self, cfg):\n \"\"\"Configure Gunicorn application logging configuration.\"\"\"\n super().setup(cfg)\n\n \"\"\"\n TODO override the date format to ISOsomething standard...\n \"\"\"\n #general_fmt = r\"%(asctime)s [%(process)3d] [%(levelname)-7s] %(message)s\"\n #Gunicorn 'access' somehow has a very different requestion context. So the ip getting is left out, it is inserted by access below\n general_formatter = RequestFormatter(\n '[%(asctime)s] [%(base_hostname)s:%(hostname)s:%(process)3d] [%(levelname)-7s] %(message)s'\n )\n #print(self.cfg.access_log_format)\n #self.cfg.access_log_format = general_fmt\n\n # Override Gunicorn's `error_log` configuration.\n self._set_handler( self.error_log, cfg.errorlog, general_formatter )\n\n #Push the general format at our the access formatter, which will publish specialised messages\n self._set_handler( self.access_log, cfg.accesslog, general_formatter )\n\n\n def access(self, resp, req, environ, request_time):\n \"\"\" See http://httpd.apache.org/docs/2.0/logs.html#combined\n for format details\n \"\"\"\n #print(\"Access got; resp: {}, req: {} environ: {}, request_time: {}\".format( resp, req, environ, request_time ) )\n #print(\"access log format is: {}\".format( self.cfg.access_log_format ))\n\n if not (self.cfg.accesslog or self.cfg.logconfig or\n self.cfg.logconfig_dict or\n (self.cfg.syslog and not self.cfg.disable_redirect_access_to_syslog)):\n return\n\n # wrap atoms:\n # - make sure atoms will be test case insensitively\n # - if atom doesn't exist replace it by '-'\n safe_atoms = self.atoms_wrapper_class(self.atoms(resp, req, environ,\n request_time))\n\n #original access log format:\n #%(h)s %(l)s %(u)s %(t)s \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"\n \"\"\"\n %(h)s remote_addr 192.168.176.1\n %(l)s (literally a dash) -\n %(u) getuser or '-' -\n %(t)s now : [04/Jun/2019:16:21:53 +1000]\n %(r)s \"request_method, raw_uri, server_protocol\" : \"POST /underwriting/_dash-update-component HTTP/1.1\"\n %(s)s status 204\n %(b)s resp.sent 0\n %(f)s http_referer \"http://localhost:8007/underwriting/fleet/home\"\n %(a)s useragent \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36\"\n \"\"\"\n #To match the general fmt: time, [processpid] [levelname] message\n #access_log_format = \"%(t)s %(h)s [%(p)s] [INFO] %(r)s %(s)s %(b)s %(f)s %(a)s\"\n #Because we're using the general formatter wrapping this:\n #access_log_format = \"[%(h)-15s] %(r) %(s)s %(b)s %(f)s %(a)s\"\n access_log_format = \"[%(h)-15s] %(r)s %(s)s %(b)s %(f)s %(a)s\"\n\n try:\n self.access_log.info( access_log_format, safe_atoms)\n except:\n self.error(traceback.format_exc())\n\n","sub_path":"manju2/devops_takehome1/src/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"562303393","text":"#Lists Class Exercises\r\n#Improving a piece of code\r\n\r\n# Program to search for a name in a list\r\n\r\nNamesList = ['Jim', 'Bob', 'Alison', 'Jo', 'James']\r\n\r\nElementSought = input('Enter the name you are searching for : ')\r\nFound = False\r\nindex = 0\r\nfor ThisElement in NamesList:\r\n if ThisElement == ElementSought:\r\n Found = True\r\n if Found == False:\r\n index = index + 1\r\nif Found:\r\n print('{0} was in element {1} in the list'.format(ElementSought, index))\r\nelse:\r\n print('Not found')\r\n","sub_path":"Exercises Task 1.py","file_name":"Exercises Task 1.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"190649957","text":"# Copyright 2015 Mirantis Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport contextlib\nimport time\n\nfrom cloudferrylib.base.action import action\nfrom cloudferrylib.utils import utils as utl\nfrom cloudferrylib.os.identity.keystone import KeystoneIdentity\nfrom cloudferrylib.os.compute.nova_compute import NovaCompute\nfrom cloudferrylib.os.network.neutron import NeutronNetwork\nfrom cloudferrylib.os.image.glance_image import GlanceImage\nfrom cloudferrylib.os.storage.cinder_storage import CinderStorage\nfrom keystoneclient.openstack.common.apiclient import exceptions as ks_exc\nfrom novaclient import exceptions as nova_exc\nfrom glanceclient import exc as glance_exc\nfrom neutronclient.common import exceptions as neutron_exc\nfrom cinderclient import exceptions as cinder_exc\nfrom cloudferrylib.base import exception\n\nLOG = utl.get_log(__name__)\n\n\nclass CheckCloud(action.Action):\n def __init__(self, init, cloud=None):\n super(CheckCloud, self).__init__(init, cloud)\n\n @contextlib.contextmanager\n def create_tenant(self, ks_client, tenant_name):\n LOG.info(\"Creating %s tenant.\", tenant_name)\n tenant_id = ks_client.create_tenant(tenant_name)\n try:\n yield tenant_id\n finally:\n LOG.info(\"Deleting previously created tenant.\")\n ks_client.delete_tenant(tenant_id)\n\n @contextlib.contextmanager\n def create_flavor(self, nv_client, flavor):\n LOG.info(\"Creating %s flavor.\", flavor['name'])\n flavor_id = nv_client.create_flavor(**flavor)\n try:\n yield flavor_id\n finally:\n LOG.info(\"Deleting previously created flavor.\")\n nv_client.delete_flavor(flavor_id)\n\n @contextlib.contextmanager\n def create_network(self, nt_client, network):\n LOG.info(\"Creating %s network.\", network['network']['name'])\n net_id = \\\n nt_client.neutron_client.create_network(network)['network']['id']\n try:\n yield net_id\n finally:\n LOG.info(\"Deleting %s network.\", network['network']['name'])\n nt_client.neutron_client.delete_network(net_id)\n\n @contextlib.contextmanager\n def create_subnet(self, nt_client, subnet_info):\n LOG.info(\"Creating %s subnet.\", subnet_info['subnet']['name'])\n subnet_id = \\\n nt_client.neutron_client.create_subnet(subnet_info)['subnet']['id']\n try:\n yield\n finally:\n LOG.info(\"Deleting %s subnet\", subnet_info['subnet']['name'])\n nt_client.neutron_client.delete_subnet(subnet_id)\n\n @contextlib.contextmanager\n def create_image(self, gl_client, image_info):\n LOG.info(\"Creating %s image.\", image_info['name'])\n image = gl_client.create_image(**image_info)\n try:\n yield image\n finally:\n LOG.info(\"Deleting %s image.\", image_info['name'])\n gl_client.delete_image(image.id)\n\n @contextlib.contextmanager\n def create_volume(self, cn_client, volume_info):\n LOG.info(\"Creating %s volume.\", volume_info['display_name'])\n volume = cn_client.create_volume(**volume_info)\n try:\n yield\n finally:\n LOG.info(\"Deleting %s volume.\", volume_info['display_name'])\n cn_client.delete_volume(volume.id)\n\n @contextlib.contextmanager\n def create_instance(self, nv_client, instance_info):\n LOG.info(\"Creating %s instance.\", instance_info['name'])\n instance_id = nv_client.nova_client.servers.create(**instance_info)\n nv_client.wait_for_status(instance_id, nv_client.get_status, 'active',\n timeout=300)\n try:\n yield\n finally:\n LOG.info(\"Deleting instance.\")\n nv_client.nova_client.servers.delete(instance_id)\n self.wait_for_instance_to_be_deleted(nv_client=nv_client,\n instance_id=instance_id,\n timeout=300)\n\n @classmethod\n def wait_for_instance_to_be_deleted(cls, nv_client, instance_id,\n timeout=60):\n try:\n delay = 1\n while timeout > delay:\n nv_client.nova_client.servers.get(instance_id)\n LOG.info(\"Instance still exist, waiting %s sec\", delay)\n time.sleep(delay)\n delay *= 2\n except nova_exc.NotFound:\n LOG.info(\"Instance successfuly deleted.\")\n\n def run(self, **kwargs):\n \"\"\"Check write access to cloud.\"\"\"\n\n ks_client = KeystoneIdentity(config=self.cloud.cloud_config,\n cloud=self.dst_cloud)\n nv_client = NovaCompute(config=self.cloud.cloud_config,\n cloud=self.dst_cloud)\n nt_client = NeutronNetwork(config=self.cloud.cloud_config,\n cloud=self.dst_cloud)\n gl_client = GlanceImage(config=self.cloud.cloud_config,\n cloud=self.dst_cloud)\n cn_client = CinderStorage(config=self.cloud.cloud_config,\n cloud=self.dst_cloud)\n\n adm_tenant_name = self.cloud.cloud_config.cloud.tenant\n adm_tenant_id = ks_client.get_tenant_id_by_name(adm_tenant_name)\n\n err_message = 'Failed to create object in the cloud'\n unique = str(int(time.time()))\n tenant_name = 'tenant_%s' % unique\n flavor = {\n 'name': 'flavor_%s' % unique,\n 'is_public': True,\n 'ram': '1',\n 'vcpus': '1',\n 'disk': '1',\n 'ephemeral': '1',\n 'swap': '1',\n 'rxtx_factor': '1'\n }\n\n image_info = {\n 'name': 'image_%s' % unique,\n 'container_format': 'bare',\n 'disk_format': 'qcow2',\n 'is_public': True,\n 'protected': False,\n 'owner': adm_tenant_id,\n 'size': 4,\n 'properties': {'user_name': 'test_user_name'},\n 'data': 'test'\n }\n\n private_network_info = {\n 'network': {\n 'tenant_id': '',\n 'admin_state_up': False,\n 'shared': False,\n 'name': 'private_net_%s' % unique,\n 'router:external': False\n }\n }\n\n shared_network_info = {\n 'network': {\n 'tenant_id': adm_tenant_id,\n 'admin_state_up': True,\n 'shared': True,\n 'name': 'shared_net_%s' % unique,\n 'router:external': True\n }\n }\n\n subnet_info = {\n 'subnet': {\n 'name': 'subnet_%s' % unique,\n 'network_id': '',\n 'cidr': '192.168.1.0/24',\n 'ip_version': 4,\n 'tenant_id': '',\n }\n }\n\n volume_info = {\n 'availability_zone': 'nova',\n 'display_description': None,\n 'size': 1,\n 'display_name': 'volume_%s' % unique,\n 'volume_type': None\n }\n\n try:\n with self.create_tenant(ks_client, tenant_name) as tenant_id, \\\n self.create_flavor(nv_client, flavor) as flavor_id, \\\n self.create_image(gl_client, image_info) as image:\n\n private_network_info['tenant_id'] = tenant_id\n subnet_info['subnet']['tenant_id'] = tenant_id\n\n with self.create_network(nt_client, private_network_info) as\\\n private_network_id, \\\n self.create_network(nt_client, shared_network_info):\n\n subnet_info['subnet']['network_id'] = private_network_id\n nics = [{'net-id': private_network_id}]\n\n with self.create_subnet(nt_client, subnet_info), \\\n self.create_volume(cn_client, volume_info):\n instance_info = {\n 'name': 'test_vm_%s' % unique,\n 'image': image.id,\n 'flavor': flavor_id,\n 'nics': nics\n }\n with self.create_instance(nv_client, instance_info):\n pass\n\n except (ks_exc.ClientException, nova_exc.ClientException,\n cinder_exc.ClientException, glance_exc.ClientException,\n neutron_exc.NeutronClientException):\n LOG.error(err_message)\n raise exception.AbortMigrationError(err_message)\n","sub_path":"cloudferrylib/os/actions/check_cloud.py","file_name":"check_cloud.py","file_ext":"py","file_size_in_byte":9168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"435795215","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 12 10:32:42 2020\n\n@author: pierre\n\"\"\"\nfrom os import listdir, makedirs\nfrom os import path\n\nimport subprocess\nimport tempfile\nimport pickle\n\nfrom skimage.external.tifffile import imread, imsave\nfrom skimage.segmentation import join_segmentations\nfrom skimage.measure import label, regionprops\n\nfrom skimage.color import label2rgb\nfrom numpy.random import randint\n\nfrom random import shuffle\nfrom pathlib import Path\n\n\ndef shuffle_ret(l):\n shuffle(l)\n return l\n\ndef log(m, f):\n f.write(m + \"\\n\")\n print(m)\n\n\nprog_bin = \"/home/pierre/cam/ilastik-1.3.3post3-Linux/run_ilastik.sh\"\nprog_ch1_params = [\"--headless\",\n \"--project=/mnt/data/mosab/data/batch1/inhib/batch1_inhib_train_C2.ilp\",\n \"--output_format=multipage tiff\",\n \"--export_source=Simple Segmentation\"]\n\nprog_ch2_params = [\"--headless\",\n \"--project=/mnt/data/mosab/data/batch1/inhib/batch1_inhib_train_C3.ilp\",\n \"--output_format=multipage tiff\",\n \"--export_source=Simple Segmentation\"]\n\n\n#\"C:/pierre/data\"\nin_base_dir = \"/mnt/data/mosab/data\" #replace by the path to the folder\n#containing the data\n\n#C:/pierre/analysis\nout_base_dir = \"/mnt/data/mosab/analysis2\" #replace by the path to the folder\n #where you want the output files\n #to be generated\nbatch = 1 #replace batch number here\nsyn_type = \"inhib\" #or \"inhib\"\ngenerate_RGB = True #whether or not to generate RGB images of\n #detected synapses\nforce = False #re-run already generated files\n\nassert(syn_type in [\"excit\", \"inhib\"])\n\nbase_dir = \"{}/batch{}/{}\".format(in_base_dir, batch, syn_type)\nout_dir = \"{}/batch{}/{}\".format(out_base_dir, batch, syn_type)\n\nchan_names = {\"inhib\": {0: \"pv\", 1: \"geph\", 2: \"vgat\"},\n \"excit\": {0: \"pv\", 1: \"psd95\", 2: \"vglut\"}}\n\n\nran = [False, False, False]\n\nexp_dirs = listdir(base_dir)\n\nprint(\"Processing: batch{}: {}\".format(batch, syn_type))\n\n\nexp_dirs = listdir(base_dir)\nfor cnt, fname in enumerate(shuffle_ret(exp_dirs)):\n if not fname.endswith(\".tif\"):\n print(\"Skipped[{}/{}]: {} is not a .tif file\"\n .format(fname, cnt+1, len(exp_dirs)))\n continue\n\n out_exp_dir = path.join(out_dir, fname)\n if not path.isdir(out_exp_dir):\n makedirs(out_exp_dir)\n\n if path.isfile(path.join(out_exp_dir, \".lock\")):\n print(\"Skipped[{}/{}] {}: found lock file\"\n .format(cnt+1, len(exp_dirs), fname))\n continue\n\n print(\"Processing[{}/{}]: {}\".format(cnt+1, len(exp_dirs), fname))\n tmp_dir = tempfile.TemporaryDirectory(dir=\"/tmp\") \n\n #Put a lock on this analysis so that if multiple processings\n # happen in parallel they don't overlap\n Path(path.join(out_exp_dir, \".lock\")).touch()\n\n logf = open(path.join(out_exp_dir, \"log.txt\"), 'w')\n\n imgs = imread(path.join(base_dir, fname))\n img_shape = (imgs.shape[0],) + imgs.shape[2:]\n\n labs_props = [None, None, None]\n ran = [False, False, False]\n\n imsave(path.join(tmp_dir.name, \"ch1.tiff\"), imgs[:,1,:,:])\n imsave(path.join(tmp_dir.name, \"ch2.tiff\"), imgs[:,2,:,:])\n\n subp_res = subprocess.run([prog_bin] + prog_ch1_params + [path.join(tmp_dir.name, \"ch1.tiff\")], capture_output=True)\n assert(subp_res.returncode == 0)\n\n subp_res = subprocess.run([prog_bin] + prog_ch1_params + [path.join(tmp_dir.name, \"ch2.tiff\")], capture_output=True)\n assert(subp_res.returncode == 0)\n\n imgs_ch1_lab = imread(path.join(tmp_dir.name, \"ch1_Simple Segmentation.tiff\"))\n imgs_ch2_lab = imread(path.join(tmp_dir.name, \"ch2_Simple Segmentation.tiff\"))\n\n ch1_labs = label(imgs_ch1_lab == 1)\n ch2_labs = label(imgs_ch2_lab == 1)\n \n imsave(path.join(out_exp_dir, \"labs_{}.tif\".format(chan_names[syn_type][1])),\n ch1_labs.astype(\"uint16\"))\n imsave(path.join(out_exp_dir, \"labs_{}.tif\".format(chan_names[syn_type][2])),\n ch2_labs.astype(\"uint16\"))\n\n ch1_props = regionprops(ch1_labs)\n ch2_props = regionprops(ch2_labs)\n\n\n log(\" Found {} {} clusters\"\n .format(len(ch1_props), chan_names[syn_type][1]), logf)\n\n log(\" Found {} {} clusters\"\n .format(len(ch2_props), chan_names[syn_type][2]), logf)\n\n\n merged_labs = join_segmentations(ch1_labs, ch2_labs)\n\n merged_labs = merged_labs * (ch2_labs > 0) * (ch1_labs > 0)\n\n merged_props = regionprops(merged_labs)\n\n log(\" Found {} synapses\".format(len(merged_props)), logf)\n\n if generate_RGB:\n imsave(path.join(out_exp_dir, \"merged_labs_col.tiff\"),\n label2rgb(merged_labs, bg_label=0, colors=[[randint(255), randint(255), randint(255)] for i in range(len(merged_props))]).astype('uint8'))\n\n with open(path.join(out_exp_dir, \"clusts.pkl\"), \"wb\") as f:\n pickle.dump({\"overlap\": merged_props,\n chan_names[syn_type][1]: ch1_props,\n chan_names[syn_type][2]: ch2_props}, f)\n","sub_path":"quantif_synapse_ML.py","file_name":"quantif_synapse_ML.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"618714880","text":"import json, argparse\nfrom dashboardApi import import_grafana_settings, create_folder\n\nparser = argparse.ArgumentParser()\nparser.add_argument('path', help='file path saved of folder\\' setting')\nparser.add_argument('conf_filename', default=\"grafanaSettings\", help='The settings file name in the conf directory'\n ' (for example: the server name we want to backup/restore)')\nargs = parser.parse_args()\n\nfile_path = args.path\nimport_grafana_settings(args.conf_filename)\n\nwith open(file_path, 'r') as f:\n data = f.read()\n\nfolder = json.loads(data)\nresult = create_folder(json.dumps(folder))\nprint(\"create result status: {0}, msg: {1}\".format(result[0], result[1]))\n","sub_path":"src/create_folder.py","file_name":"create_folder.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"158721373","text":"#!C:\\Python\\Python\n#coding=utf-8\n\n'''\nGroup Anagrams\n\nWrite a function that takes in an array of strings and groups anagrams together.\n\nAnagrams are strings made up of exactly the same letters, where order doesn't matter.\n\nFor example, \"cinema\" and \"iceman\" are anagrams; similarly, \"foo\" and \"ofo\" are anagrams.\n\nYour function should return a list of anagram groups in no particular order. \n\nSample Input:\nwords = [\"yo\", \"act\", \"flop\", \"tac\", \"foo\", \"cat\", \"oy\", \"olfp\"]\n\nSample Output:\n[[\"yo\",\"oy\"],[\"flop\",\"olfp\"],[\"act\",\"tac\",\"cat\"],[\"foo\"]]\n'''\n\ndef groupAnagrams(words):\n\tanagrams = {}\n\tfor i in words:\n\t\tsortedString = \"\".join(sorted(i))\n\t\tif sortedString in anagrams.keys():\n\t\t\tanagrams[sortedString].append(i)\n\t\telse :\n\t\t\tanagrams[sortedString] = [i] \n\treturn list(anagrams.values())\n\nwords = [\"yo\", \"act\", \"flop\", \"tac\", \"foo\", \"cat\", \"oy\", \"olfp\"]\nprint(groupAnagrams(words))\n\n","sub_path":"Python/00_Code Interview/AlgoExpert/Difficulty/medium/String_M_033_GroupAnagrams.py","file_name":"String_M_033_GroupAnagrams.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"606185745","text":"#!/usr/bin/python3\n\"\"\" start a Flask web app\"\"\"\nfrom flask import Flask\nfrom models import storage\nfrom flask import render_template\napp = Flask(__name__)\n\n\n\n@app.route(\"/states\", strict_slashes=False)\ndef states():\n \"\"\"Display html\"\"\"\n st = storage.all(\"State\")\n return render_template(\"9-states.html\", state=st)\n\n\n@app.route(\"/states/\", strict_slashes=False)\ndef states_id(id):\n \"\"\"Display html\"\"\"\n for st in storage.all(\"State\").values():\n if st.id == id:\n return render_template(\"9-states.html\", state=st)\n return render_template(\"9-states.html\")\n\n\n@app.teardown_appcontext\ndef handle_trd(self):\n \"\"\" method to handle teardown \"\"\"\n storage.close()\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"455900847","text":"import json\n\nfrom repository.postgres_repository import execute_sql\n\n\ndef lambda_handler(event, context):\n\tsql = event['body']\n\toutput = execute_sql(sql)\n\treturn {\n\t\t'isBase64Encoded': False,\n\t\t'headers': {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Access-Control-Allow-Origin': '*'\n\t\t},\n\t\t'statusCode': 200,\n\t\t'body': json.dumps(output)\n\t}\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"395652090","text":"import pandas\nimport math\nfrom main import makeMove, stringToBoard, boardToString\nimport pickle\n\ndef createEmptyRecords():\n emptydf = pandas.DataFrame({'BoardValue': pandas.Series([],index=[]),'Player': pandas.Series([],index=[]),'Wins': pandas.Series([],index=[]),'Losses': pandas.Series([],index=[]),'Board': pandas.Series([],index=[])})\n pickle.dump(emptydf,open(\"Records.p\",\"wb\"))\n return True\n\ndef updateRecords(startingboard,history,winner):\n newRecords = computeNewRecords(startingboard,history,winner)\n try:\n oldRecords = getRecords()\n except:\n oldRecords = emptyRecords()\n saveRecords = mergeRecords(oldRecords,newRecords)\n pickle.dump(saveRecords,open(\"Records.p\",\"wb\"))\n return\n\n\ndef emptyRecords():\n return pandas.DataFrame({'BoardValue': pandas.Series([],index=[]),'Player': pandas.Series([],index=[]),'Wins': pandas.Series([],index=[]),'Losses': pandas.Series([],index=[]),'Board': pandas.Series([],index=[])})\n\n\ndef getRecords():\n try:\n records = pickle.load(open(\"Records.p\",\"rb\"))\n except:\n records = emptyRecords()\n return records\n\n# Bernoulli's lower bound for a 95% Confidence Interval (z = 1.96 gives the 95%)\ndef computeLowerBound(w,l):\n n=w+l\n z = 1.96\n root = math.sqrt(w*l*1.0/n + z**2 / 4)\n numerator = (w + ((z**2) / 2) - z*root)\n denominator = n+z**2\n return numerator*1.0 / denominator\n\n\ndef mergeRecords(recordsA,recordsB):\n fullRecords = recordsA.append(recordsB,ignore_index=True)\n fullRecords['Board'] = map(lambda x: boardToString(x),fullRecords['Board'])\n fullRecords = fullRecords.groupby(['Board','Player'],as_index=False).sum()\n fullRecords['Board'] = map(lambda x: stringToBoard(x),fullRecords['Board'])\n fullRecords['BoardValue'] = map(lambda w,l: computeLowerBound(w,l),fullRecords['Wins'],fullRecords['Losses'])\n return fullRecords\n\n\n# Creates new records using previous history.\n# History is a list of pairs of positions by order played and the person who played them\ndef computeNewRecords(startingboard,history,winner):\n newRecords = pandas.DataFrame({'BoardValue': pandas.Series([],index=[]),'Player': pandas.Series([],index=[]),'Wins': pandas.Series([],index=[]),'Losses': pandas.Series([],index=[]),'Board': pandas.Series([],index=[])})\n board = startingboard\n for i in range(0,len(history)):\n player = history[i][0]\n board = makeMove(board,player,history[i][1])\n newline = pandas.DataFrame({'BoardValue': pandas.Series([0.05],index=[i]),'Player': pandas.Series([player],index=[i]),'Wins': pandas.Series([int(player == winner)],index=[i]),'Losses': pandas.Series([int(player != winner)],index=[i]),'Board': pandas.Series([board],index=[i])})\n newRecords = newRecords.append(newline,ignore_index=True)\n newRecords['BoardValue'] = map(lambda w,l: computeLowerBound(w,l),newRecords['Wins'],newRecords['Losses'])\n return newRecords","sub_path":"learner1.py","file_name":"learner1.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"532813722","text":"from flask import Flask, render_template, request, redirect\napp = Flask(__name__)\nimport json\nimport os\n\napp.config['DEBUG'] = True\n\ndef iter_files():\n list_files = []\n l_files = os.listdir(path='posttext')\n for file in l_files:\n f = open('posttext/'+file)\n cont = f.read()\n jpost = json.loads(cont)\n list_files.append(jpost)\n f.close()\n return list_files\n\ndef add_file(title, content):\n list_files = os.listdir(path='posttext')\n end_list = list_files[(len(list_files)-1)]\n f_list = str(int(end_list)+1)\n with open('posttext/'+f_list, mode='w') as f:\n f.write(r'{\"title\":\"')\n f.write(title)\n f.write(r'\",\"content\":\"')\n f.write(content)\n f.write(r'\"}')\n\n@app.route('/')\ndef index():\n posts = iter_files()\n print(posts)\n #title = jpost['post1']['title']\n #content = jpost['post1']['content']\n return render_template('index.html', posts=posts)\n\n@app.route('/add', methods=['GET', 'POST'])\ndef add():\n if request.method == 'GET':\n return render_template('add.html')\n if request.method == 'POST':\n title = request.form['title']\n content = request.form['content']\n add_file(title, content)\n return redirect(\"/\")\napp.run()","sub_path":"papka/microblog.py","file_name":"microblog.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"291268255","text":"# -*- coding: utf-8 -*-\nfrom django.template.loader import render_to_string\nimport random\n\n\nclass Component(object):\n\n def __init__(self, request=None):\n self.id = self.id = abs(random.randint(0, 900))\n self.request = request\n self.response = None\n self.as_pdf = False\n\n def render(self, template_name):\n self.as_pdf = self.request and self.request.GET.get('pdf', False) or self.as_pdf\n return render_to_string(template_name, {'self': self})\n","sub_path":"ui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"589567933","text":"#!/usr/bin/env python3\n\nimport asyncio\nimport websockets\nimport binascii\n\nimport socket\nimport random\n\nimport sys\nimport getopt\n\nhelp_str = 'ws-tcp-proxy.py -l -p -b -d -v'\n\nLITE_IP = '127.0.0.1'\nLITE_PORT = 46732\nBIND_IP = '0.0.0.0'\nBIND_PORT = 7004\nBUFFER_SIZE = 102400\nverbose = False\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:],\"hvl:p:b:d:\",[])\nexcept getopt.GetoptError:\n print(help_str, flush=True)\n sys.exit(2)\n\nfor opt, arg in opts:\n if opt == '-h':\n print(help_str)\n sys.exit()\n elif opt == '-v':\n verbose = True\n elif opt == '-l':\n LITE_IP = arg\n elif opt == '-p':\n LITE_PORT = int(arg)\n elif opt == '-b':\n BIND_IP = arg\n elif opt == '-d':\n BIND_PORT = int(arg)\n\n\nasync def ws2tcp(ws, tcp):\n if verbose:\n print('listening client', flush=True)\n try:\n while True:\n data = await ws.recv()\n if len(data) > 0:\n print('request: ' + str(len(data)), flush=True)\n #print(binascii.hexlify(bytearray(data)))\n #if random.choice([0,1]) == 0:\n # print('Check error')\n # data = bytearray(data)\n # data[random.randint(0, len(data)-1)] = random.randint(0, 255)\n # data = bytes(data)\n tcp.write(data)\n except websockets.exceptions.ConnectionClosedError as e:\n pass\n except websockets.exceptions.ConnectionClosedOK as e:\n pass\n except Exception as e:\n print('Error ws2tcp: ' + str(e), flush=True)\n finally:\n if verbose:\n print('ws2tcp end', flush=True)\n tcp.close()\n\n\nasync def tcp2ws(tcp, ws):\n if verbose:\n print('listening server', flush=True)\n try:\n while not tcp.at_eof():\n #while True:\n data = await tcp.read(BUFFER_SIZE)\n if len(data) > 0:\n if verbose:\n print('reply: ' + str(len(data)), flush=True)\n await ws.send(data)\n finally:\n if verbose:\n print('tcp2ws end', flush=True)\n await ws.close()\n\n\nasync def handle_client(ws):\n try:\n remote_reader, remote_writer = await asyncio.wait_for(asyncio.open_connection(LITE_IP, LITE_PORT), timeout = 30)\n # print('Connected to server')\n pipe1 = ws2tcp(ws, remote_writer)\n pipe2 = tcp2ws(remote_reader, ws)\n await asyncio.gather(pipe1, pipe2)\n except asyncio.TimeoutError:\n print('Timeout connecting to server', flush=True)\n except Exception as e:\n print('Error connecting to server', flush=True)\n finally:\n pass\n\n\nasync def ws_server(websocket, path):\n if verbose:\n print('new client', flush=True)\n await handle_client(websocket)\n if verbose:\n print('client disconnected', flush=True)\n return\n\n\nif __name__ == \"__main__\":\n print('Start ws-tcp proxy server from %s:%d to %s:%d' % (LITE_IP, LITE_PORT, BIND_IP, BIND_PORT), flush=True)\n start_server = websockets.serve(ws_server, BIND_IP, BIND_PORT)\n asyncio.get_event_loop().run_until_complete(start_server)\n asyncio.get_event_loop().run_forever()\n","sub_path":"ws-tcp-proxy.py","file_name":"ws-tcp-proxy.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"450666029","text":"import pandas as pd\n#解决数据输出时列名不对齐的问题\npd.set_option('display.unicode.ambiguous_as_wide', True)\npd.set_option('display.unicode.east_asian_width', True)\ndf = pd.read_excel('mingribooks.xls')\ndf1=df[['订单付款时间','买家会员名','联系手机','买家实际支付金额']]\ndf1=df1.sort_values(by=['订单付款时间'])\ndf1 = df1.set_index('订单付款时间') # 将日期设置为索引\n#获取某个区间数据\nprint(df1['2018-05-11':'2018-06-10'])\n","sub_path":"pandas进阶/code/日期数据处理code/47/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"148078143","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QPushButton, QMessageBox\nfrom BankGUI.AccountCsv import account_exists, delete_account, user_update_history, admin_update_history, move_file\n\n\nclass UiDeleteAccountWindow(object):\n\n def main_menu(self):\n from AdminMenu import UIAdminMenu\n self.admin_menu = QtWidgets.QMainWindow()\n self.ui = UIAdminMenu()\n self.ui.setupUi(self.admin_menu)\n self.admin_menu.show()\n\n def setupUi(self, delete_account_window):\n delete_account_window.setObjectName(\"deposit_window\")\n delete_account_window.resize(800, 600)\n delete_account_window.setStyleSheet(\"background-color: rgb(0, 0, 127);\")\n self.centralwidget = QtWidgets.QWidget(delete_account_window)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.username_label = QtWidgets.QLabel(self.centralwidget)\n self.username_label.setGeometry(QtCore.QRect(30, 140, 311, 81))\n font = QtGui.QFont()\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.username_label.setFont(font)\n self.username_label.setStyleSheet(\"color: rgb(255, 255, 255);\")\n self.username_label.setObjectName(\"username_label\")\n self.logo_label = QtWidgets.QLabel(self.centralwidget)\n self.logo_label.setGeometry(QtCore.QRect(690, 10, 101, 91))\n self.logo_label.setText(\"\")\n self.logo_label.setPixmap(QtGui.QPixmap(\"../../images/Bank logo 1.png\"))\n self.logo_label.setObjectName(\"logo_label\")\n self.username_input = QtWidgets.QLineEdit(self.centralwidget)\n self.username_input.setGeometry(QtCore.QRect(370, 140, 321, 81))\n font = QtGui.QFont()\n font.setPointSize(20)\n self.username_input.setFont(font)\n self.username_input.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"selection-background-color: rgb(85, 170, 255);\")\n self.username_input.setText(\"\")\n self.username_input.setObjectName(\"username_input\")\n self.enter_button = QPushButton(self.centralwidget, clicked=lambda: self.enter_pressed_button(delete_account_window))\n self.enter_button.setGeometry(QtCore.QRect(450, 250, 161, 61))\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.enter_button.setFont(font)\n self.enter_button.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(85, 170, 255);\")\n self.enter_button.setObjectName(\"enter_button\")\n self.cancel_button = QPushButton(self.centralwidget, clicked=lambda: self.main_menu())\n self.cancel_button.clicked.connect(lambda: delete_account_window.hide())\n self.cancel_button.setGeometry(QtCore.QRect(170, 260, 161, 61))\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.cancel_button.setFont(font)\n self.cancel_button.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(170, 0, 0);\")\n self.cancel_button.setObjectName(\"cancel_button\")\n self.username_label_2 = QtWidgets.QLabel(self.centralwidget)\n self.username_label_2.setGeometry(QtCore.QRect(300, 30, 221, 81))\n font = QtGui.QFont()\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.username_label_2.setFont(font)\n self.username_label_2.setStyleSheet(\"color: rgb(255, 255, 255);\")\n self.username_label_2.setObjectName(\"username_label_2\")\n delete_account_window.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(delete_account_window)\n self.statusbar.setObjectName(\"statusbar\")\n delete_account_window.setStatusBar(self.statusbar)\n\n self.retranslateUi(delete_account_window)\n QtCore.QMetaObject.connectSlotsByName(delete_account_window)\n\n def retranslateUi(self, deposit_window):\n _translate = QtCore.QCoreApplication.translate\n deposit_window.setWindowTitle(_translate(\"deposit_window\", \"Delete Account\"))\n self.username_label.setText(_translate(\"deposit_window\", \"Input username to delete\"))\n self.enter_button.setText(_translate(\"deposit_window\", \"CONFIRM\"))\n self.cancel_button.setText(_translate(\"deposit_window\", \"CANCEL\"))\n self.username_label_2.setText(_translate(\"deposit_window\", \"DELETE ACCOUNT\"))\n\n def enter_pressed_button(self, delete_account_window):\n username = self.username_input.text()\n if not account_exists(username):\n self.error()\n else:\n delete_account(username)\n self.account_deleted_successfully()\n delete_account_window.hide()\n user_update_history(username, \"Delete Account\", \"0\")\n admin_update_history(username, \"Delete Account\")\n move_file(username)\n\n def account_deleted_successfully(self):\n message = QMessageBox()\n message.setWindowTitle(\"Success\")\n message.setText(f\"User {self.username_input.text()} is deleted.\")\n message.setIcon(QMessageBox.Information)\n message.exec_()\n self.main_menu()\n\n def error(self):\n message = QMessageBox()\n message.setWindowTitle(\"Error\")\n message.setText(\"Username not existing.\")\n message.setIcon(QMessageBox.Warning)\n message.exec_()\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n delete_account_window = QtWidgets.QMainWindow()\n ui = UiDeleteAccountWindow()\n ui.setupUi(delete_account_window)\n delete_account_window.show()\n sys.exit(app.exec_())\n","sub_path":"BankGUI/AdminMethods/DeleteAccount.py","file_name":"DeleteAccount.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"610388729","text":"#!/usr/bin/env python3\nimport json\nimport math\nimport sys\n\nimport matplotlib.cm as cm\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.interpolate import griddata\nfrom scipy.misc import imread\nfrom scipy.optimize import curve_fit\nfrom scipy.spatial.distance import cdist\n\ngraph = json.load(open('graph.dev.json'))\n\n# group multiple scans at the same position\nscans_by_position = {}\nfor scan in graph['wifidata']:\n pos = (scan['level'], scan['x'], scan['y'])\n if pos not in scans_by_position:\n scans_by_position[pos] = {}\n for station in scan['stations']:\n sid = (station['bssid'], station['ssid'])\n if sid not in scans_by_position[pos]:\n scans_by_position[pos][sid] = []\n scans_by_position[pos][sid].append(station['level'])\n\nfor pos, stations in scans_by_position.items():\n count = max(len(s) for s in stations.values())\n print(pos)\n for sid in tuple(stations.keys()):\n if len(stations[sid]) < count:\n del stations[sid]\n else:\n stations[sid] = sum(stations[sid])/count\n\n\n# group scans by station\nstations = {}\nfor pos, statlist in scans_by_position.items():\n for sid, level in statlist.items():\n if sid not in stations:\n stations[sid] = []\n stations[sid].append((pos) + (level,))\n\n# group stations\nfor sid, values in stations.items():\n print(sid)\n for val in values:\n print(val)\n print('')\n\n\n# print(scans_by_position)\n\n# if sid not in stations:\n# stations[sid] = []\n# if not stations[sid] or stations[sid][-1][-1] != station['level']:\n# stations[sid].append((pos) + (station['level'],))\n\nstations = sorted([s for s in stations.items() if len(s[1]) >= 3], key=lambda s: -len(s[1]))\n\nfor sid, values in stations:\n values = np.array(values)\n\n # if sid[1] not in ('NoMoKeTo', 'Freifunk', 'Telekom'):\n # continue\n\n grid_x, grid_y = np.mgrid[0:graph['width'], 0:graph['height']]\n\n frequency = 2400\n\n print(sid, len(values))\n print(values[:, 3].min(), values[:, 3].max())\n # grid = griddata(values[:, 1:3], values[:, 3], (grid_x, grid_y), method='cubic')\n # grid = 10000-griddata(values[:, 1:3], 10**(values[:, 3]/10), (grid_x, grid_y), method='cubic')\n # grid = 100000-griddata(values[:, 1:3], 1/(10**(values[:, 3]/10))**0.5, (grid_x, grid_y), method='cubic')\n grid = griddata(values[:, 1:3], 10**((27.55-(20*math.log10(frequency))+values[:, 3])/20), (grid_x, grid_y),\n method='linear')\n\n # print(grid.min(), grid.max())\n\n plt.imshow(imread('static/img/levels/dev/level0.jpg'))\n plt.imshow(grid.transpose(), alpha=.5, cmap=cm.jet, origin='upper')\n plt.show()\n\n # xnew = range(0, graph['width'], 2)\n # ynew = range(0, graph['height'], 2)\n # znew = f(xnew, ynew)\n # plt.plot(xnew, znew[0, :], 'b-')\n # plt.show()\n\n # continue\n\n def myfunc(x, a, b):\n return cdist(np.array([(a, b)]), x, 'euclidean')[0]\n\n frequency = 2400\n coordinates = values[:, 1:3]\n print(coordinates)\n distances = 10**((27.55 - (20 * math.log10(frequency)) + values[:, 3]*-1)/20)\n print(distances)\n\n bla = curve_fit(myfunc, coordinates, distances)\n print(bla)\n print(tuple(round(float(i), 2) for i in bla[0]))\n\n print('')\n\n # for val in values:\n # print(val)\n # print('')\n\nsys.exit(0)\n\ncoordinates = np.array([\n [-1.91373, -0.799904],\n [-0.935453, -0.493735],\n [-0.630964, -0.653075],\n [0.310857, 0.018258],\n [0.0431084, 1.24321]\n])\ndistances = np.array([\n 2.04001,\n 0.959304,\n 0.728477,\n 0.301885,\n 1.19012\n])\n\ncoordinates = np.array([[0, 0], [3, 0]])\ndistances = np.array([1, 1])\n\ncoordinates = np.array([[2, 2, 3], [1, 1, 3], [1, 2, 6]])\n\ndistances = np.array([1, 1, 3])\n\n# bla = curve_fit(myfunc, coordinates, distances)[0]\n# print(tuple(round(i, 2) for i in bla))\n","sub_path":"src/triangulatestuff.py","file_name":"triangulatestuff.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"631196072","text":"import argparse\nimport json\nimport os\nimport sys\nimport urllib.request\n\nREPO_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\")\nsys.path.append(REPO_ROOT)\nmodel_store_dir = os.path.join(REPO_ROOT, \"model_store\")\nos.makedirs(model_store_dir, exist_ok=True)\n\ndef generate_mars(mar_config):\n\n with open(mar_config) as f:\n models = json.loads(f.read())\n\n for model in models:\n serialized_file_path = None\n if model.get(\"serialized_file_remote\") and model[\"serialized_file_remote\"]:\n os.chdir(model_store_dir)\n serialized_model_file_url = \"https://download.pytorch.org/models/{}\".format(model[\"serialized_file_remote\"])\n urllib.request.urlretrieve(serialized_model_file_url, model[\"serialized_file_remote\"])\n serialized_file_path = os.path.join(model_store_dir, model[\"serialized_file_remote\"])\n elif model.get(\"serialized_file_local\") and model[\"serialized_file_local\"]:\n serialized_file_path = model[\"serialized_file_local\"]\n\n handler = None\n if model.get(\"handler\") and model[\"handler\"]:\n handler = model[\"handler\"]\n\n extra_files = None\n if model.get(\"extra_files\") and model[\"extra_files\"]:\n extra_files = model[\"extra_files\"]\n\n runtime = None\n if model.get(\"runtime\") and model[\"runtime\"]:\n runtime = model[\"runtime\"]\n\n archive_format = None\n if model.get(\"archive_format\") and model[\"archive_format\"]:\n archive_format = model[\"archive_format\"]\n\n requirements_file = None\n if model.get(\"requirements_file\") and model[\"requirements_file\"]:\n requirements_file = model[\"requirements_file\"]\n\n os.chdir(REPO_ROOT)\n export_path = model_store_dir\n if model.get(\"export_path\") and model[\"export_path\"]:\n export_path = model[\"export_path\"]\n\n cmd = model_archiver_command_builder(model[\"model_name\"], model[\"version\"], model[\"model_file\"],\n serialized_file_path, handler, extra_files,\n runtime, archive_format, requirements_file, export_path)\n print(f\"## In directory: {os.getcwd()} | Executing command: {cmd}\")\n sys_exit_code = os.system(cmd)\n if model.get(\"serialized_file_remote\") and model[\"serialized_file_remote\"]:\n os.remove(serialized_file_path)\n\n if sys_exit_code != 0:\n sys.exit(\"## {} creation failed !\\n\".format(model[\"model_name\"]))\n else :\n print(\"## {}.mar is generated.\\n\".format(model[\"model_name\"]))\n\ndef model_archiver_command_builder(model_name=None, version=None, model_file=None,\n serialized_file=None, handler=None, extra_files=None,\n runtime=None, archive_format=None, requirements_file=None,\n export_path=None, force=True):\n cmd = \"torch-model-archiver\"\n\n if model_name:\n cmd += \" --model-name {0}\".format(model_name)\n\n if version:\n cmd += \" --version {0}\".format(version)\n\n if model_file:\n cmd += \" --model-file {0}\".format(model_file)\n\n if serialized_file:\n cmd += \" --serialized-file {0}\".format(serialized_file)\n\n if handler:\n cmd += \" --handler {0}\".format(handler)\n\n if extra_files:\n cmd += \" --extra-files {0}\".format(extra_files)\n\n if runtime:\n cmd += \" --runtime {0}\".format(runtime)\n\n if archive_format:\n cmd += \" --archive-format {0}\".format(archive_format)\n\n if requirements_file:\n cmd += \" --requirements-file {0}\".format(requirements_file)\n\n if export_path:\n cmd += \" --export-path {0}\".format(export_path)\n\n if force:\n cmd += \" --force\"\n\n return cmd\n\nif __name__ == \"__main__\":\n # cmd:\n # python ts_scripts/marsgen.py\n # python ts_scripts/marsgen.py --config my_mar_config.json\n\n mar_config_file_path = os.path.join(REPO_ROOT, \"ts_scripts\", \"mar_config.json\")\n parser = argparse.ArgumentParser(description=\"Generate model mar files\")\n parser.add_argument('--config', default=mar_config_file_path, help=\"mar file configuration json file\")\n\n args = parser.parse_args()\n generate_mars(args.config)\n","sub_path":"ts_scripts/marsgen.py","file_name":"marsgen.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"549163539","text":"documents = [\n {\"type\": \"passport\", \"number\": \"2207 876234\", \"name\": \"Василий Гупкин\"},\n {\"type\": \"invoice\", \"number\": \"11-2\", \"name\": \"Геннадий Покемонов\"},\n {\"type\": \"insurance\", \"number\": \"10006\", \"name\": \"Аристарх Павлов\"},\n {\"type\": \"insurance\", \"number\": \"10006\", \"name\": \"Аристашка Павлов\"},\n {\"type\": \"insurance\", \"number\": \"10007\"}\n ]\n\ndirectories = {\n '1': ['2207 876234', '11-2', '5455 028765', '2'],\n '2': ['10006', '5400 028765', '5455 002299', '2'],\n '3': []\n }\n\ndef add_shelf(shelf_name):\n if shelf_name in directories.keys():\n print('Такая полка уже есть.')\n else:\n directories[shelf_name] = []\n print('Полка добавлена')\n\ndef get_owner_name_by_doc_number(number: str):\n res = [document.get('name') for document in documents if document.get('number') == number]\n if len(res) == 0:\n print(f'Документа с номером {number} не найден')\n elif len(res) == 1:\n print(f'Документ с номером {number} принадлежит {res[0]}')\n else:\n print(f'Документ с номером {number} не унекален. Возможные владельцы:')\n print(res)\n\ndef get_shelf_number_by_doc_number(doc_number):\n shelfs = [shelf_number for shelf_number, docs in directories.items() if doc_number in docs]\n if len(shelfs) == 0:\n print(f'Документа с номером {doc_number} нет на полках')\n elif len(shelfs) == 1:\n print(f'Документ с номером {doc_number} находиться на полек номер {shelfs[0]}')\n else:\n print('В записях ошибка!')\n print(f'Документ с номером {doc_number} находиться на одной из полок:')\n print(shelfs)\n\ndef print_list():\n print('Список всех документов:')\n for doc in documents:\n doc_type = doc.get(\"type\")\n doc_number = doc.get(\"number\")\n doc_owner = doc.get(\"name\")\n print(f'{doc_type} \"{doc_number}\" \"{doc_owner}\"')\n\ndef add_doc_to_shelf():\n doc_number = input('Введите номер документа: ')\n doc_type = input('Введите тип документа: ')\n doc_owner = input('введите владельца: ')\n shelf_number = input('Введите номер полки: ')\n doc = {\n 'type': doc_type,\n 'number': doc_number,\n 'name': doc_owner\n }\n if shelf_number not in directories:\n print(f'Полки с номром {shelf_number} нет в базе. Если вы хотите ее добавить введите е�� номер еще раз.')\n if shelf_number != input():\n print('Полка не добавлена. Данные не сохранены')\n return\n documents.append(doc)\n directories.setdefault(shelf_number, []).append(doc_number)\n print('Документ добавлен.')\n\ndef delete_by_doc_number_and_return_new_list(doc_number):\n for name in directories.keys():\n while True:\n try:\n directories[name].remove(doc_number)\n except ValueError:\n break\n return [doc for doc in documents if doc.get('number') != doc_number]\n\ndef move_to_shelf(doc_number, new_shelf):\n if new_shelf not in directories.keys():\n print(f'Полка с номером {new_shelf} не существует. Сначала добавьте новую полку командой \"as\".')\n return\n if any([(doc_number in docs) for docs in directories.values()]):\n delete_by_doc_number_and_return_new_list(doc_number)\n directories[new_shelf].append(doc_number)\n print(f'Документ с номером {doc_number} перемещен на полку {new_shelf}.')\n else:\n print('Документа нет на полках. Сначала добавьте документ командой \"a\".')\n\ndef print_all_doc_name():\n for doc in documents:\n try:\n print(f'{doc[\"name\"]} - владелец документа {doc.get(\"number\")}')\n except KeyError:\n print(f'У документа {doc.get(\"number\")} нет владельца')\n\nif __name__ == '__main__':\n print('''\np – people – команда, которая спросит номер документа и выведет имя человека, которому он принадлежит;\nl – list – команда, которая выведет список всех документов в формате passport \"2207 876234\" \"Василий Гупкин\";\ns – shelf – команда, которая спросит номер документа и выведет номер полки, на которой он находится;\na – add – команда, которая добавит новый документ в каталог и в перечень полок, спросив его номер, тип, имя владельца и номер полки, \n на котором он будет храниться;\nd – delete – команда, которая спросит номер документа и удалит его из каталога и из перечня полок;\nm – move – команда, которая спросит номер документа и целевую полку и переместит его с текущей полки на целевую;\nas – add shelf – команда, которая спросит номер новой полки и добавит ее в перечень;\npa – print all – команда, которая выведит список всех владельцов документов;\nq – quite – Выход.\n ''')\n while True:\n comand = input('Введите команду: ')\n if comand == 'q':\n break\n elif comand == 'p':\n get_owner_name_by_doc_number(input('Введите номер документа: '))\n elif comand == 'l':\n print_list()\n elif comand == 's':\n get_shelf_number_by_doc_number(input('Введите номер документа: '))\n elif comand == 'a':\n add_doc_to_shelf()\n elif comand == 'as':\n add_shelf(input('Введите номер новой полки: '))\n elif comand == 'd':\n documents = delete_by_doc_number_and_return_new_list(input('Введите номер документа: '))\n elif comand == 'm':\n move_to_shelf(input('ведите номер документа: '), input('На какую полку переместить? '))\n elif comand == 'pa':\n print_all_doc_name()\n else:\n print('Такой команды нет. Попробуйте еще.')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"13460215","text":"import random\n\nN = 100\nM = N - 2\np = 0.60\n\n\ndef makeS():\n global M, p\n A = [[-1 for i in range(M)] for j in range(M)]\n for i in range(M):\n for j in range(M):\n if i != j:\n if random.random() < p:\n if A[i][j] == -1:\n A[i][j] = int(random.random()*100)\n A[j][i] = 0\n else:\n if random.random() > 0.5:\n A[i][j] = int(random.random() * 100)\n A[j][i] = 0\n for i in range(M):\n if any([j > 0 for j in A[i]]):\n # print(i)\n pass\n else:\n\n l = [j for j in range(M) if A[i][j] == -1]\n l.remove(i)\n random.shuffle(l)\n\n if i < int(M/2):\n chose = i + 1\n else:\n chose = i - 1\n if l:\n chose = l[0]\n\n A[i][chose] = int(random.random() * 100)\n A[chose][i] = 0\n for i in range(M):\n if A[i].count(0) == 0:\n l = [j for j in range(M) if A[i][j] == -1]\n l.remove(i)\n random.shuffle(l)\n if i < int(M/2):\n chose = i + 1\n else:\n chose = i - 1\n if l:\n chose = l[0]\n\n A[i][chose] = 0\n A[chose][i] = int(random.random() * 100)\n return A\n\n\ndef checkS(SS):\n global M\n good = True\n for i in range(M):\n if any([j > 0 for j in A[i]]):\n pass\n else:\n good = False\n if SS[i].count(0) > 0:\n pass\n else:\n good = False\n if SS[i].count(-1) == 0:\n good = False\n return good\nA = makeS()\nwhile not checkS(A):\n A = makeS()\n\n\na = [i for i in range(M)]\nrandom.shuffle(a)\nx = int(M*p)\ny = int(M*p/2)\n\nz = random.randint(y, x)\nif z < 2:\n z = 2\niii = a[0:z]\niii = sorted(iii)\n\ndef makeooo():\n global M, p\n b = [i for i in range(M)]\n random.shuffle(b)\n x = int(M*p)\n y = int(M*p/2)\n\n zz = random.randint(y, x)\n if zz < 2:\n zz = 2\n\n return b[0:zz]\nooo = makeooo()\nooo = sorted(ooo)\nwhile iii == ooo:\n ooo = makeooo()\n ooo = sorted(ooo)\n\noutputstring = []\noutputstring.append(str(N)+'\\n')\ns = '1 '+str(len(iii))\nfor i in iii:\n s += ' '+str(i+2)+' '+str(int(random.random()*100))\ns += '\\n'\noutputstring.append(s)\nfor i in range(M):\n s = str(i+2)\n n = M - (A[i].count(-1) + A[i].count(0))\n if i in ooo:\n n += 1\n s += ' '+str(n)\n for j in range(M):\n if A[i][j] > 0:\n s += ' '+str(j+2)+' '+str(A[i][j])\n if i in ooo:\n s += ' '+str(N)+' '+str(int(random.random() * 100))\n s += '\\n'\n outputstring.append(s)\npass\n\n# firstline = \"{} {} \\n\".format(N,M)\n# def lineto(B):\n# sum = 0\n# s = \"\"\n# for i in range(M):\n# if B[i] == 1:\n# sum += 1\n# s += str(i+1)+' '\n# return \"{} \".format(sum)+s\nwith open('network.inp', 'w') as f:\n f.writelines(outputstring)\n # for i in range(N):\n # f.write(\"{} \".format(i+1)+lineto(A[i])+'\\n')","sub_path":"__OLD_CODE_STORAGE/max_flow_min_cut/Edmonds_Karp/produce_input.py","file_name":"produce_input.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"592849651","text":"from random import randrange\nprint('무작위로 문제를 내는 프로그램입니다.')\n\ndef get_number():\n try:\n n = int(input('몇 문제를 낼까요?\\n'))\n return n\n except:\n return get_number()\n\nn = get_number()\n\nright = 0\n\ndef retry(**kwargs):\n try:\n answer = int(input('{0}번째 문제 : {1} {2} {3} = ?\\n'.format(i, a, ca, b))) # 이타이밍\n return answer\n except ValueError:\n return retry()\n\nfor i in range(1, n+1):\n cal = randrange(0,4)\n a = randrange(2, 100)\n b = randrange(1, 100)\n\n if cal == 0:\n while a>=10 or b>=10:\n a = randrange(2, 10)\n b = randrange(1, 10)\n ca='*'\n answer = retry(i=i, a=a, b=b, ca='*')\n if answer == a*b:\n print('답을 맞췄습니다\\n')\n right = right + 1\n else:\n print('틀렸어요ㅜㅜ\\n')\n\n if cal == 1:\n ca='+'\n answer = retry(i=i, a=a, b=b, ca='+')\n if answer == a+b:\n print('답을 맞췄습니다\\n')\n right = right + 1\n else:\n print('틀렸어요ㅜㅜ\\n')\n\n if cal == 2 and a > b:\n ca='-'\n answer = retry(i=i, a=a, b=b, ca='-')\n if answer == a-b:\n print('답을 맞췄습니다\\n')\n right = right + 1\n else:\n print('틀렸어요ㅜㅜ\\n')\n\n if cal == 3:\n while a == b or int(a/b) != a/b:\n a = randrange(2, 100)\n b = randrange(2, 100)\n ca='/'\n answer = retry(i=i, a=a, b=b, ca='/')\n\n if answer == a/b:\n print('답을 맞췄습니다\\n')\n right = right + 1\n else:\n print('틀렸어요ㅜㅜ\\n')\n\n\nprint('%d개 문제 중에 %d개 맞추었습니다~\\n수고했어요!!' % (n, right))\n","sub_path":"allcalcu.py","file_name":"allcalcu.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"66215523","text":"# -*- coding: utf-8 -*-\n# Copyright 2017-2019 ControlScan, Inc.\n#\n# This file is part of Cyphon Engine.\n#\n# Cyphon Engine 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, version 3 of the License.\n#\n# Cyphon Engine 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 Cyphon Engine. If not, see .\n\"\"\"\nTests the Stream class.\n\"\"\"\n\n# standard library\ntry:\n from unittest.mock import Mock, patch\nexcept ImportError:\n from mock import Mock, patch\n\n# third party\nfrom django.db.utils import OperationalError\nfrom django.test import TestCase\nfrom testfixtures import LogCapture\n\n# local\nfrom aggregator.invoices.models import Invoice\nfrom aggregator.streams.models import Stream\nfrom tests.fixture_manager import get_fixtures\n\n\nclass StreamManagerTestCase(TestCase):\n \"\"\"\n Class for StreamManager test cases.\n \"\"\"\n fixtures = get_fixtures(['streams'])\n\n def test_close_all(self):\n \"\"\"\n Tests the close_all method.\n \"\"\"\n stream = Stream.objects.get(pk=2)\n assert stream.active\n Stream.objects.close_all()\n stream = Stream.objects.get(pk=2)\n self.assertFalse(stream.active)\n\n @patch('aggregator.streams.models.Stream.objects.update',\n side_effect=OperationalError('foobar'))\n def test_close_all_exception(self, mock_update):\n \"\"\"\n Tests the close_all method when an OperationalError is raised.\n \"\"\"\n with LogCapture() as log_capture:\n Stream.objects.close_all()\n log_capture.check(\n ('aggregator.streams.models',\n 'ERROR',\n 'An error occurred while closing Streams: foobar'),\n )\n\n\nclass StreamTestCase(TestCase):\n \"\"\"\n Class for Stream test cases.\n \"\"\"\n fixtures = get_fixtures(['streams'])\n\n def test_str(self):\n \"\"\"\n Tests the __str__ method of the Stream class.\n \"\"\"\n stream = Stream.objects.get(auth=1)\n actual = str(stream)\n expected = 'Twitter SearchAPI: twitter_1'\n self.assertEqual(actual, expected)\n\n def test_save_as_open(self):\n \"\"\"\n Tests the save_as_open method of the Stream class.\n \"\"\"\n record = Invoice.objects.get(pk=2)\n stream = Stream.objects.get(auth=1)\n self.assertIs(stream.active, False)\n stream.save_as_open(record)\n saved_stream = Stream.objects.get(auth=1)\n self.assertIs(saved_stream.active, True)\n self.assertEqual(saved_stream.record, record)\n\n def test_save_as_closed(self):\n \"\"\"\n Tests the save_as_closed method of the Stream class.\n \"\"\"\n stream = Stream.objects.get(auth=2)\n self.assertIs(stream.active, True)\n stream.save_as_closed()\n saved_stream = Stream.objects.get(auth=2)\n self.assertIs(saved_stream.active, False)\n","sub_path":"Incident-Response/Tools/cyphon/cyphon/aggregator/streams/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"63534467","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport re\nimport argparse\nfrom collections import defaultdict\nfrom functools import reduce\nimport datetime\nfrom multiBioPro import BedMan\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-anno', action='store', type=str,\n help='The annotation bed12')\nparser.add_argument('-input', action='store', type=str,\n help='The input miR-target file')\nparser.add_argument('-prefix', action='store', type=str,\n help='The prefix of output files')\nparser.add_argument('-ref', action='store', type=str,\n help='The reference files')\nparser.add_argument('-output', action='store', type=str,\n default=\"./\", help='The output directory')\n\nargs = parser.parse_args()\nif len(sys.argv[1:]) == 0:\n parser.print_help()\n parser.exit()\n\ntxGeneDict = defaultdict(dict)\ngeneDict = defaultdict(dict)\nwith open (args.anno, 'r') as f:\n for line in f:\n row = line.strip().split('\\t')\n inforList = row[3].split('|')\n txID = inforList[0]\n geneID = inforList[3]\n geneName = inforList[4]\n geneType = inforList[5]\n txGeneDict[txID] = geneID\n geneDict[geneID] = [geneName, geneType]\n\nrefDict = defaultdict(dict)\nwith open(args.ref, 'r') as f:\n __ = f.readline()\n for line in f:\n row = line.strip().split('\\t')\n GSMaccesion = row[8]\n datasetID = row[0]\n seqType = row[2]\n refDict[GSMaccesion] = datasetID\n refDict[datasetID] = seqType\n\ninteractID = 1\ninteractDict = defaultdict(dict)\nwith open (args.input, 'r') as f:\n __ = f.readline()\n for line in f:\n row = line.strip().split('\\t')\n sampleID = row[0].split('_')[2]\n datasetID = refDict[sampleID]\n readID = row[4].split('_')[0]\n uniqReadID = '-'.join([datasetID, readID])\n leftReadLocus = ':'.join([row[1], row[2], row[3], row[6]])\n rightReadLocus = ':'.join([row[7], row[8], row[9], row[12]])\n freeEnergy = row[20]\n leftPair = row[22].replace(\"RNA1 5'>\", '').replace(\">3'\", '')\n alignment = row[23].replace(\"Pair \", '').replace('.', ' ')\n rightPair = row[24].replace(\"RNA2 3'<\", '').replace(\"<5'\", '')\n smithWaterman = row[25]\n leftGeneIDList = sorted(set(map(lambda x:txGeneDict[x], re.split(r'\\||,', row[29]))))\n rightGeneIDList = sorted(set(map(lambda x:txGeneDict[x], re.split(r'\\||,', row[33]))))\n\n interactLocus = '|'.join([leftReadLocus, rightReadLocus])\n revInteractLocus = '|'.join([rightReadLocus, leftReadLocus])\n if interactLocus not in interactDict:\n if revInteractLocus in interactDict:\n interactDict[revInteractLocus]['readID'].append(uniqReadID)\n else:\n interactDict[interactLocus] = defaultdict(list)\n interactDict[interactLocus]['interactID'] = interactID\n interactDict[interactLocus]['readID'].append(uniqReadID)\n interactDict[interactLocus]['gene'] = [leftGeneIDList, rightGeneIDList]\n interactDict[interactLocus]['freeEnergy'] = freeEnergy\n interactDict[interactLocus]['leftPair'] = leftPair\n interactDict[interactLocus]['alignment'] = alignment\n interactDict[interactLocus]['rightPair'] = rightPair\n interactDict[interactLocus]['smithWaterman'] = smithWaterman\n interactID += 1\n else:\n interactDict[interactLocus]['readID'].append(uniqReadID)\n\ngeneInteractDict = defaultdict(list)\nfor interactLocus in interactDict.keys():\n locusList = [interactLocus, '']\n leftReadLocus, rightReadLocus = interactLocus.split('|')\n geneList = interactDict[interactLocus]['gene']\n leftGeneIDList = geneList[0]\n rightGeneIDList = geneList[1]\n for leftGeneID in leftGeneIDList:\n for rightGeneID in rightGeneIDList:\n if leftGeneID == rightGeneID:\n continue\n geneKey = '|'.join([leftGeneID, rightGeneID])\n revGeneKey = '|'.join([rightGeneID, leftGeneID])\n if geneKey not in geneInteractDict and revGeneKey not in geneInteractDict:\n geneInteractDict[geneKey].append(locusList)\n else:\n if geneKey in geneInteractDict:\n geneInteractDict[geneKey].append(locusList)\n else:\n revInteractLocus = '|'.join(interactLocus.split('|')[::-1])\n locusList = [revInteractLocus, interactLocus]\n geneInteractDict[revGeneKey].append(locusList)\n\nrnaRNApairFile = os.path.join(args.output, args.prefix + '_rnaRNApair.txt')\nwith open(rnaRNApairFile, 'w') as out:\n tempList = ['interactID', 'geneID', 'geneName', 'pairGeneID', 'pairGeneName',\n 'interactLocus','expNum', 'seqTypeNum', 'readsNum', 'freeEnergy',\n 'smithWaterman', 'leftPair', 'alignment', 'rightPair', 'readIDcat']\n out.write('\\t'.join(tempList) + '\\n')\n for interactLocus in sorted(interactDict.keys(), key=lambda x:interactDict[x]['interactID']):\n tempDict = interactDict[interactLocus]\n interactID = tempDict['interactID']\n readIDlist = sorted(set(tempDict['readID']))\n readIDcat = ','.join(readIDlist)\n expNum = len(set(map(lambda x:x.split('-')[0], readIDlist)))\n seqTypeNum = len(set(map(lambda x:refDict[x.split('-')[0]], readIDlist)))\n readsNum = sum(map(lambda x:int(x.split('-')[2]), readIDlist))\n geneList = tempDict['gene']\n leftGeneIDcat = ','.join(geneList[0])\n leftGeneNameCat = ','.join(list(map(lambda x: geneDict[x][0], geneList[0])))\n rightGeneIDcat = ','.join(geneList[1])\n rightGeneNameCat = ','.join(list(map(lambda x: geneDict[x][0], geneList[1])))\n freeEnergy = tempDict['freeEnergy']\n smithWaterman = tempDict['smithWaterman']\n leftPair = tempDict['leftPair']\n alignment = tempDict['alignment']\n rightPair = tempDict['rightPair']\n tempList = [str(interactID), leftGeneIDcat, leftGeneNameCat, rightGeneIDcat,\n rightGeneNameCat, interactLocus, str(expNum), str(seqTypeNum), str(readsNum), freeEnergy,\n smithWaterman, leftPair, alignment, rightPair, readIDcat]\n out.write('\\t'.join(tempList) + '\\n')\n\ntRNApattern = re.compile(r'^tRNAscan')\nrnaRNAfile = os.path.join(args.output, args.prefix + '_rnaRNA.txt')\nwith open(rnaRNAfile, 'w') as out:\n tempList = ['lineID', 'geneID', 'geneName', 'geneType', 'pairGeneID', 'pairGeneName', 'pairGeneType']\n tempList.extend(['interactionNum', 'interactIDcat', 'expNum', 'seqTypeNum', 'readsNum', 'minFreeEnergy', 'maxSmithWaterman'])\n out.write('\\t'.join(tempList) + '\\n')\n lineID = 1\n for geneKey in sorted(geneInteractDict.keys()):\n geneKeyList = geneKey.split('|')\n leftGeneID = geneKeyList[0]\n leftGeneName = geneDict[leftGeneID][0]\n leftGeneType = geneDict[leftGeneID][1]\n rightGeneID = geneKeyList[1]\n rightGeneName = geneDict[rightGeneID][0]\n rightGeneType = geneDict[rightGeneID][1]\n if tRNApattern.match(leftGeneID):\n leftGeneID = leftGeneID.split('-')[-1]\n if tRNApattern.match(rightGeneID):\n rightGeneID = rightGeneID.split('-')[-1]\n readIDtotalSet = set()\n freeEnergyList = list()\n smithWatermanList = list()\n interactIDlist = list()\n interactLocusList = geneInteractDict[geneKey]\n for locusList in interactLocusList:\n if locusList[1]:\n tempDict = interactDict[locusList[1]]\n else:\n tempDict = interactDict[locusList[0]]\n interactID = str(tempDict['interactID'])\n interactIDlist.append(interactID)\n readIDlist = tempDict['readID']\n readIDtotalSet.update(readIDlist)\n freeEnergyList.append(float(tempDict['freeEnergy']))\n smithWatermanList.append(float(tempDict['smithWaterman']))\n\n interactIDcat = ','.join(sorted(set(interactIDlist)))\n expNum = len(set(map(lambda x:x.split('-')[0], readIDtotalSet)))\n seqTypeNum = len(set(map(lambda x:refDict[x.split('-')[0]], readIDtotalSet)))\n readsNum = sum(map(lambda x:int(x.split('-')[2]), readIDtotalSet))\n minFreeEnergy = min(freeEnergyList)\n maxSmithWaterman = max(smithWatermanList)\n tempList = [str(lineID), leftGeneID, leftGeneName, leftGeneType, rightGeneID, rightGeneName, rightGeneType]\n tempList.extend([len(interactLocusList), interactIDcat, expNum, seqTypeNum, readsNum, minFreeEnergy, maxSmithWaterman])\n out.write('\\t'.join(list(map(str,tempList))) + '\\n')\n lineID += 1\n","sub_path":"rnaRNA.py","file_name":"rnaRNA.py","file_ext":"py","file_size_in_byte":8773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"584652803","text":"import sys\nsys.stdin = open('input.txt','r')\nN =int(input())\narr = [list(map(int,input().split())) for i in range(N)]\n\n\nb= [[0]*5 for i in range(5)]\n\ndi = [0, 1, 0, -1]\ndj = [1, 0, -1, 0]\n\nsum=0\n\nfor i in range(N):\n for j in range(N): # 배열 A의 모든 원소에 대해\n print(i, j, end=' ')\n print()\n for k in range(4): # k번 방향 탐색\n ni = i + di[k]\n nj = j + dj[k]\n if(ni>=0 and ni=0 and nj Inefficient but good for first implementation)\nDefine qubit registers and p-value\nDefine objective function\nDefine U(C) and U(B) operators\nBuild the quantum circuit\nMeasure the state\nUse the state to calculate the value of the objective function\nTODO above: Repeat process h times, find the largest value (Maybe implement Grover's???)\nTODO above: Repeat the whole process while varying the angles of the two operators\n#Figure out how to penalize multiple qubits set to 1 within the circuit\n'''\n\nimport cirq\nimport itertools\nimport networkx as nx\nfrom matplotlib import pyplot as plt\n\n#You must change the weights based on the number of steps that the simulator takes\n\nweight_on_first_ham = 1\nweight_on_second_ham = 2\n\n# Graph objects for creating the graphs that will be used in the optimization algorithm\n\nclass Edge:\n def __init__(self, start_node, end_node):\n self.start_node = start_node\n self.end_node = end_node\n\n\nclass Graph:\n def __init__(self, edges_set):\n self.edges_set = edges_set\n self.node_set = []\n for i in edges_set:\n if (i.start_node not in self.node_set):\n self.node_set.append(i.start_node)\n if (i.end_node not in self.node_set):\n self.node_set.append(i.end_node)\n\n#Connects nodes with an edge\n def connect_nodes(self, edge):\n if (edge not in self.edges_set and edge.start_node in self.node_set and edge.end_node in self.node_set):\n self.edges_set.append(edge)\n\n#Adds a node to the graph\n def add_nodes(self, node):\n if (node not in self.node_set):\n self.node_set.append(node)\n\n#Removes nodes from the graph. If a node is removed, all edges connected to that node are removed as well\n\n def remove_nodes(self, node):\n if (node in self.node_set):\n del self.node_set[self.node_set.index(node)]\n new = []\n for i in range (0, len(self.edges_set)):\n if (node != self.edges_set[i].start_node and node != self.edges_set[i].end_node):\n new.append(self.edges_set[i])\n self.edges_set = new\n\n#Disconnects nodes, thereby removing an edge\n def disconnect_nodes(self, edge):\n if (edge in self.edges_set):\n del self.edges_set[self.edges_set.index(edge)]\n\n\n\n#Define the problem graph\n\nset_edges = [Edge(0, 1), Edge(1, 2), Edge(0, 2), Edge(2, 3), Edge(2, 4), Edge(3, 4)]\n#set_edges = [Edge(0, 1), Edge(1, 2), Edge(0, 2), Edge(2, 3), Edge(2, 4), Edge(3, 4)]\n\n#set_edges = [Edge(0, 1), Edge(1, 2)]\n\nG = nx.Graph()\n\nfor z in set_edges:\n G.add_edge(str(z.start_node), str(z.end_node))\n\nnx.draw(G)\nplt.savefig('graph.png')\n\ngraph = Graph(set_edges)\n\nn = len(graph.node_set)\n\n\nconnection = [0, 1]\n\nmatrix_horiz = []\nfor i in connection:\n holder = []\n for g in range (0, n):\n if (g == i):\n holder.append(1)\n else:\n holder.append(-1)\n matrix_horiz.append(holder)\n\n\n#Generate and Store the qubits in an array\n\nqubits = []\nfor i in range(0, n):\n qubits.append(cirq.GridQubit(0, i))\n\nqubit_store = []\nfor i in range(0, n):\n qubits.append(cirq.GridQubit(1, i))\n\n#Creating extra/work qubits to be used during calculations\nwork_qubit = cirq.GridQubit(n+5, n+5)\n\ndef apply_h_gates(length):\n for i in range (0, length):\n yield cirq.H.on(cirq.GridQubit(0, i))\n\n\ndef apply_n_qubit_tof(number, input_target):\n yield cirq.CCX.on(qubits[input_target[0]], qubits[input_target[1]], qubit_store[0])\n for i in range (2, number):\n yield cirq.CCX.on(qubits[input_target[i]], qubit_store[i-2], qubit_store[i-1])\n\n yield cirq.CNOT.on(qubit_store[number-2], qubits[input_target[number]])\n counter = number\n for i in range (2, number):\n yield cirq.CCX.on(qubits[input_target[counter-1]], qubit_store[counter-3], qubit_store[counter-2])\n counter = counter - 1\n yield cirq.CCX.on(qubits[input_target[0]], qubits[input_target[1]], qubit_store[0])\n\ndef apply_other_c(length, gamma):\n for j in graph.node_set:\n yield cirq.CZPowGate(exponent=(-1*gamma)).on(cirq.GridQubit(0, j), work_qubit)\n\ndef apply_C_unitary(length, gamma):\n # Apply the compute --> rotate --> uncompute method to change the phase of a specific computational basis state\n for j in set_edges:\n yield cirq.CNOT.on(cirq.GridQubit(0, j.start_node), cirq.GridQubit(0, j.end_node))\n yield cirq.Rz((-1*gamma)).on(cirq.GridQubit(0, j.end_node))\n yield cirq.CNOT.on(cirq.GridQubit(0, j.start_node), cirq.GridQubit(0, j.end_node))\n yield cirq.Rz((-1*gamma)).on(work_qubit)\n\ndef apply_B_unitary(length, beta):\n for i in range(0, n):\n yield cirq.Rx((2*beta)).on(cirq.GridQubit(0, i))\n\ndef apply_everything(length, gamma, beta):\n circuit.append(apply_C_unitary(length, gamma))\n circuit.append(apply_B_unitary(length, beta))\n\ndef other_apply(length, gamma, beta):\n circuit2.append(apply_other_c(length, gamma))\n circuit2.append(apply_B_unitary(length, beta))\n\n\n\ndef objective_calc(values, extra):\n\n coefficient = 1\n total = 0\n\n for i in set_edges:\n multi = -1*values[i.start_node]*values[i.end_node]\n total = total + (multi+1)*0.5\n\n return float(coefficient)*total\n\ndef new_calc(values, extra):\n coefficient = 1\n total = 0\n for i in graph.node_set:\n multi = -1*values[i]\n total = total + (multi+1)*0.5\n\n return float(coefficient)*total\n\n\nvalues_for_rotation = [0.2, 0.4, 0.6, 0.8]\nnumber_of_steps = 4\n\nnew_rotation = list(itertools.permutations(values_for_rotation, number_of_steps))\n\nmaxcut_value = -10000\nmaxcut_state = 0\n\n#Pick 2 to be used in the set\n\nfor g in range (0, len(new_rotation)):\n for h in range(0, len(new_rotation)):\n\n gamma_matrix = new_rotation[g]\n beta_matrix = new_rotation[h]\n\n circuit = cirq.Circuit()\n\n circuit.append(apply_h_gates(n))\n\n for g in range(0, number_of_steps):\n apply_everything(n, float(gamma_matrix[g]), float(beta_matrix[g]))\n #circuit.append(apply_check_gates())\n\n circuit.append(cirq.measure(*qubits, key='x'))\n\n simulator = cirq.Simulator()\n result = simulator.run(circuit, repetitions=100)\n\n processed_results = str(result)[2:].split(\", \")\n\n sum_total = 0\n\n for j in range(0, len(processed_results[0])):\n trial_holder = []\n for k in range(0, len(processed_results)-3):\n if (int(processed_results[k][j]) == 0):\n trial_holder.append(-1)\n else:\n trial_holder.append(int(processed_results[k][j]))\n extra = int(processed_results[len(processed_results)-1][j])\n\n\n sum_total = sum_total + objective_calc(trial_holder, extra)\n\n sum_total = sum_total/100\n\n if (sum_total > maxcut_value):\n maxcut_value = sum_total\n maxcut_state = [gamma_matrix, beta_matrix]\n\n\ncircuit = cirq.Circuit()\ncircuit.append(apply_h_gates(n))\n\nfor g in range(0, number_of_steps):\n apply_everything(n, maxcut_state[0][g], maxcut_state[1][g])\n\ncircuit.append(cirq.measure(*qubits, key='x'))\n\nvalues_for_rotation = [0.1, 0.4, 0.7]\nnumber_of_steps = 3\n\nnew_rotation = list(itertools.permutations(values_for_rotation, number_of_steps))\n\nmaxcut_value = -10000\nmaxcut_state = 0\n\nfor g in range (0, len(new_rotation)):\n for h in range(0, len(new_rotation)):\n\n gamma_matrix = new_rotation[g]\n beta_matrix = new_rotation[h]\n\n circuit2 = cirq.Circuit()\n\n circuit2.append(apply_h_gates(n))\n circuit2.append(cirq.X.on(work_qubit))\n\n for g in range(0, number_of_steps):\n other_apply(n, float(gamma_matrix[g]), float(beta_matrix[g]))\n\n circuit2.append(cirq.measure(*qubits, key='x'))\n\n simulator = cirq.Simulator()\n result = simulator.run(circuit2, repetitions=100)\n\n processed_results = str(result)[2:].split(\", \")\n\n sum_total = 0\n\n for j in range(0, len(processed_results[0])):\n trial_holder = []\n for k in range(0, len(processed_results)-3):\n if (int(processed_results[k][j]) == 0):\n trial_holder.append(-1)\n else:\n trial_holder.append(int(processed_results[k][j]))\n extra = int(processed_results[len(processed_results)-1][j])\n\n\n sum_total = sum_total + new_calc(trial_holder, extra)\n\n sum_total = sum_total/100\n\n if (sum_total > maxcut_value):\n maxcut_value = sum_total\n maxcut_state = [gamma_matrix, beta_matrix]\n\ncircuit2 = cirq.Circuit()\ncircuit2.append(apply_h_gates(n))\ncircuit2.append(cirq.X.on(work_qubit))\n\nfor g in range(0, number_of_steps):\n other_apply(n, maxcut_state[0][g], maxcut_state[1][g])\n\ncircuit2.append(cirq.measure(*qubits, key='x'))\n\n#NUMBER OF SHOTS\nshots = 20\n\ndef test_circuit():\n\n simulator = cirq.Simulator()\n result = simulator.run(circuit, repetitions=5000)\n final = result.histogram(key='x')\n result2 = simulator.run(circuit2, repetitions=500)\n final2 = result2.histogram(key='x')\n\n print(final)\n print(final2)\n print(circuit)\n\n\n #Assigns a score to each of the outputted configurations\n\n entry_number = []\n entry_number2 = []\n score = []\n entry_score = []\n\n indexing = str(final).split(\", \")\n indexing2 = str(final2).split(\", \")\n\n entry_number.append(int(indexing[0][9:indexing[0].index(\":\")]))\n entry_number2.append(int(indexing2[0][9:indexing2[0].index(\":\")]))\n\n for i in range (1, len(indexing)):\n entry_number.append(int(indexing[i][0:indexing[i].index(\":\")]))\n for i in range (1, len(indexing2)):\n entry_number2.append(int(indexing2[i][0:indexing2[i].index(\":\")]))\n\n for i in entry_number:\n score.append(i)\n entry_score.append(0)\n for i in entry_number2:\n if (i not in score):\n score.append(i)\n entry_score.append(0)\n\n for i in range(0, len(entry_number)):\n entry_score[score.index(entry_number[i])] += weight_on_first_ham*(i+1)\n\n for i in range(0, len(entry_number2)):\n entry_score[score.index(entry_number2[i])] += weight_on_second_ham*(i+1)\n\n return [score, entry_score]\n\nlast_score = []\nlast_entry = []\n\n\n\nfor i in range(0, shots):\n v = test_circuit()\n for j in range (0, len(v[0])):\n if (v[0][j] not in last_score):\n last_score.append(v[0][j])\n last_entry.append(v[1][j])\n else:\n last_entry[last_score.index(v[0][j])] += v[1][j]\n\nfor b in range (0, len(last_entry)):\n last_entry[b] = last_entry[b]/shots\n\nmin_val = 10000\noptimal_choice = 0\nfor i in range(0, len(last_entry)):\n if (last_entry[i] < min_val):\n min_val = last_entry[i]\n optimal_choice = last_score[i]\noptimal_choice = float(optimal_choice)\n\nprint(optimal_choice)\n\nplt.show()\n","sub_path":"geneva.py","file_name":"geneva.py","file_ext":"py","file_size_in_byte":10921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"602427250","text":"# _*_coding:UTF-8_*_\r\n# 当前系统用户: LISICHENG \r\n# 当前系统日期:2019/7/21 \r\n# 当前系统时间:9:15 \r\n# 创建文件的IDE名称:PyCharm\r\nimport random\r\nimport math\r\nimport Tool.constant as cons\r\nimport datetime\r\n\r\nclass Task:\r\n\r\n def __init__(self, task_id, workload, output_data, child, workflow_id):\r\n self.task_id = task_id\r\n self.workload = workload\r\n self.workflow_id = workflow_id\r\n self.host_id = 10000000000000\r\n self.replication = 1 # 复制的份数\r\n self.checking_points = 2 # 断点个数\r\n if self.task_id == 0:\r\n self.serial_workload = 0\r\n self.parallel_workload = 0\r\n self.output_data = 0\r\n self.workload = 0\r\n self.is_finish = 1\r\n else:\r\n self.serial_workload = 0.3 * self.workload\r\n self.parallel_workload = 0.7 * self.workload\r\n self.output_data = output_data\r\n self.is_finish = 0\r\n self.receive_data = 0\r\n self.child = child\r\n self.parent = []\r\n self.execute_workload = 0\r\n self.sub_make_span = 0\r\n self.min_task_time = 0\r\n self.cost_resource_optimization = float('inf')\r\n self.cpu_optimization = 0\r\n self.type = ''\r\n self.cost_time_by_cpu_optimization = 0\r\n self.execute_start = 0\r\n\r\n\r\n def timeByCpuRDE(self, k):\r\n \"\"\"\r\n 被不同型号的虚拟机(核数不同)执行\r\n :param k: 当前虚拟机的核数\r\n :return: 被不同核数的虚拟机执行的时间\r\n \"\"\"\r\n cost_time = (self.output_data + self.receive_data) / cons.GBps + self.serial_workload + self.parallel_workload / k\r\n return cost_time\r\n\r\n def pVM(self, time):\r\n \"\"\"\r\n 一定时间内发生虚拟机错误的概率\r\n :param time: 时间\r\n :return:\r\n \"\"\"\r\n p_vm = math.exp(-cons.r_vm * time)\r\n return p_vm\r\n\r\n def Nrep(self, cost_time):\r\n \"\"\"\r\n 返回为了确保容错进行复制的份数\r\n :param cost_time:\r\n :param p_vm:\r\n :return:\r\n \"\"\"\r\n n_rep = math.log(cons.e, 1 - self.pVM(cost_time)) + 1\r\n return n_rep\r\n\r\n def expectedResourceCase1RDE(self, n_rep, cost_time_by_k, k):\r\n \"\"\"\r\n 计算R-DE中的case1中的资源消费\r\n :param n_rep: 复制的份数\r\n :param cost_time_by_k: 花费的时间\r\n :param k: 核数------虚拟机的核数\r\n :return: 选中K个核类型的虚拟机计算出所需要的资源期望\r\n \"\"\"\r\n n_pre = n_rep // 2\r\n n_back = n_rep - n_pre\r\n p11 = 1 - math.pow(1 - self.pVM(cost_time_by_k), n_pre)\r\n cost_resource11 = n_pre * cost_time_by_k * k + n_back * (2 * cost_time_by_k - self.sub_make_span) * k\r\n p12 = math.pow(1 - self.pVM(cost_time_by_k), n_pre)\r\n cost_resource12 = n_rep * cost_time_by_k * k\r\n excepted_resource_case1 = p11 * cost_resource11 + p12 * cost_resource12\r\n self.replication = n_pre\r\n return excepted_resource_case1\r\n\r\n def exceptedResourceCase2RDE(self, n_rep, cost_time_by_k, k):\r\n \"\"\"\r\n RDE遇到的case2,计算所需的资源期望\r\n :param n_pre: 复制的份数\r\n :param cost_time_by_k: 任务所花费的时间\r\n :param k: 核数\r\n :return: 资源期望,更上述的一样,但是情景不一样\r\n \"\"\"\r\n n_pre = n_rep // 2\r\n p21 = 1 - math.pow(1 - self.pVM(cost_time_by_k), n_pre)\r\n cost_resource21 = n_pre * cost_time_by_k * k\r\n p22 = math.pow(1 - self.pVM(cost_time_by_k), n_pre)\r\n cost_resource22 = n_rep * cost_time_by_k * k\r\n excepted_resource_case2 = p21 * cost_resource21 + p22 * cost_resource22\r\n self.replication = n_rep\r\n return excepted_resource_case2\r\n\r\n def timeByCpuCDE(self, k):\r\n \"\"\"\r\n C-DE当中的时间消耗\r\n :param k: 核数\r\n :return:\r\n \"\"\"\r\n L = 1\r\n temp = float('inf')\r\n t_ex = self.serial_workload + self.parallel_workload / k\r\n while True:\r\n t_execute_excepted = L * (1/cons.r_vm + cons.t_vm_wt) * (math.exp(cons.r_vm * (t_ex / L + cons.t_chk_rate * t_ex)) - 1)\r\n if t_execute_excepted < temp:\r\n temp = t_execute_excepted\r\n L += 1\r\n else:\r\n break\r\n cost_time = temp + (self.output_data + self.receive_data) / cons.GBps\r\n return cost_time\r\n\r\n def exceptedResourceCase1CDE(self, cost_time_by_k, k):\r\n p11 = math.exp(-cons.r_h_p * cost_time_by_k)\r\n cost_resource11 = cost_time_by_k * k + (2 * cost_time_by_k - self.sub_make_span) * k\r\n p12 = 1 - p11\r\n cost_resource12 = 2 * cost_time_by_k * k\r\n excepted_resource_case1 = p11 * cost_resource11 + p12 * cost_resource12\r\n return excepted_resource_case1\r\n\r\n def exceptedResourceCase2CDE(self, cost_time_by_k, k):\r\n p21 = math.exp(-cons.r_h_p * cost_time_by_k)\r\n cost_resource21 = cost_time_by_k * k\r\n p22 = 1 - p21\r\n cost_resource22 = 2 * cost_time_by_k * k\r\n excepted_resource_case2 = p21 * cost_resource21 + p22 * cost_resource22\r\n return excepted_resource_case2\r\n\r\n def costTimeByCpuOptimization(self):\r\n if self.type == 'R-DE':\r\n self.cost_time_by_cpu_optimization = self.timeByCpuRDE(self.cpu_optimization)\r\n else:\r\n self.cost_time_by_cpu_optimization = self.timeByCpuCDE(self.cpu_optimization)\r\n\r\n def execute_task(self):\r\n self.costTimeByCpuOptimization()\r\n self.execute_start = datetime.datetime.now()\r\n while True:\r\n time_execute_now = datetime.datetime.now()\r\n execute_time = time_execute_now - self.execute_start\r\n self.is_finish = execute_time.seconds / self.cost_time_by_cpu_optimization\r\n # print(execute_time)\r\n # self.cost_time_by_cpu_optimization\r\n if execute_time.seconds == 5:\r\n self.is_finish = 1\r\n print(str(self.workflow_id) + ':' + str(self.task_id) + ' 执行完成')\r\n break\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"structure/Task.py","file_name":"Task.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"449582001","text":"'''\nCreated on Feb 8, 2013\n\n@author: dns\n'''\n\nimport math\nimport random\n\nfrom util.mathutil import to_radians\n\nclass Directions:\n Left, Centre, Right = range(1, 4)\n\ndef class_to_name(clazz):\n return clazz.__name__\n\n'''\nChoose the next direction to head in\n'''\ndef pick_direction(logger, hHeadAngle, obstruction, maxAngle, bCtrBias):\n \n if bCtrBias and hHeadAngle > 0:\n hMax = hOffset * math.cos(hHeadAngle) \n hMin = (-2 * hOffset) + hMax\n elif bCtrBias and hHeadAngle < 0:\n hMin = -hOffset * math.cos(hHeadAngle) \n hMax = (2 * hOffset) + hMin\n else:\n hMin = -hOffset\n hMax = hOffset \n \n # do we need to avoid an obstacle?\n if not obstruction is None:\n if obstruction == Directions.Left:\n logger.log(\"there is obstruction on right \")\n hMin = 0\n elif obstruction == Directions.Right:\n logger.log(\"there is obstruction on right \")\n hMax = 0\n elif obstruction == Directions.Centre:\n logger.log(\"there is obstruction in centre \")\n else:\n logger.log(\"no obstruction\")\n \n logger.log(\"hMin = \" + str(hMin) + \", hMax = \" + str(hMax) + \", head angle = \" + str(hHeadAngle) + \", head offset = \" + str(hOffset))\n \n hDeg = random.uniform(hMin, hMax)\n return to_radians(hDeg)","sub_path":"wanderer/src/main/python/util/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"610862296","text":"from vgg16 import VGG16\nimport numpy as np\nfrom keras.preprocessing import image\nfrom imagenet_utils import preprocess_input\nimport six.moves.cPickle as pickle\nimport progressbar\n\n\ndef preprocessing():\n image_captions = open(\n \"captions/Flickr8k.token.txt\").read().split('\\n')\n caption = {}\n for i in range(len(image_captions)-1):\n id_capt = image_captions[i].split(\"\\t\")\n # to rip off the #0,#1,#2,#3,#4 from the tokens file\n id_capt[0] = id_capt[0][:len(id_capt[0])-2]\n try:\n caption[id_capt[0]].append(id_capt[1])\n except:\n caption[id_capt[0]] = [id_capt[1]]\n train_imgs_id = open(\n \"captions/Flickr_8k.trainImages.txt\").read().split('\\n')[:-1]\n\n train_imgs_captions = open(\"captions/trainimgs.txt\", 'w')\n for img_id in train_imgs_id:\n for captions in caption[img_id]:\n desc = \" \"+captions+\" \"\n train_imgs_captions.write(img_id+\"\\t\"+desc+\"\\n\")\n train_imgs_captions.flush()\n train_imgs_captions.close()\n\n test_imgs_id = open(\n \"captions/Flickr_8k.testImages.txt\").read().split('\\n')[:-1]\n\n test_imgs_captions = open(\"captions/testimgs.txt\", 'w')\n for img_id in test_imgs_id:\n for captions in caption[img_id]:\n desc = \" \"+captions+\" \"\n test_imgs_captions.write(img_id+\"\\t\"+desc+\"\\n\")\n test_imgs_captions.flush()\n test_imgs_captions.close()\n\n\ndef model_gen():\n model = VGG16(weights='imagenet', include_top=True,\n input_shape=(224, 224, 3))\n return model\n\n\ndef encodings(model, path):\n processed_img = image.load_img(path, target_size=(224, 224))\n x = image.img_to_array(processed_img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n image_final = np.asarray(x)\n prediction = model.predict(image_final)\n prediction = np.reshape(prediction, prediction.shape[1])\n\n return prediction\n\n\ndef encode_image():\n model = VGG16(weights='imagenet', include_top=True,\n input_shape=(224, 224, 3))\n image_encodings = {}\n\n train_imgs_id = open(\n \"captions/Flickr_8k.trainImages.txt\").read().split('\\n')[:-1]\n print(len(train_imgs_id))\n test_imgs_id = open(\n \"captions/Flickr_8k.testImages.txt\").read().split('\\n')[:-1]\n images = []\n images.extend(train_imgs_id)\n images.extend(test_imgs_id)\n print(len(images))\n bar = progressbar.ProgressBar(maxval=len(images),\n widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])\n bar.start()\n counter = 1\n print(\"Encoding images\")\n\n for img in images:\n path = \"images/\"+str(img)\n image_encodings[img] = encodings(model, path)\n bar.update(counter)\n counter += 1\n\n bar.finish()\n with open(\"image_encodings.p\", \"wb\") as pickle_f:\n pickle.dump(image_encodings, pickle_f)\n print(\"Encodings dumped into image_encodings.p\")\n\n\nif __name__ == \"__main__\":\n encode_image()\n","sub_path":"encode_image.py","file_name":"encode_image.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"486404901","text":"#Image Sharpening\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\na,b=2,4#No of Subplots\r\nsplot=1\r\ndef show_img(img,title=''):\r\n global splot\r\n plt.subplot(a,b,splot)\r\n splot+=1\r\n # img_show = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')\r\n plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis \r\n plt.title(title)\r\nplt.figure('Image Sharpening')\r\nimg =cv2.imread(r'D:\\sem_6\\IP\\OpenCVPract\\soduku.png',0)\r\nshow_img(img,'Original Image')\r\n\r\nlaplacian = cv2.Laplacian(img,cv2.CV_64F)\r\nsobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)\r\nsobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)\r\n# sobelxy=cv2.Sobel(img,cv2.CV_64F,1,1,ksize=5)\r\nshow_img(laplacian,'laplacian Image')\r\nshow_img(sobelx,'sobelx Image')\r\nshow_img(sobely,'sobely Image')\r\n# show_img(sobelxy,'sobelxy Image')\r\n'''\r\nThere is a slight problem with that.\r\nBlack-to-White transition is taken as Positive slope (it has a positive value)\r\nwhile White-to-Black transition is taken as a Negative slope\r\n(It has negative value). So when you convert data to np.uint8,\r\nall negative slopes are made zero. In simple words, you miss that edge.\r\n'''\r\n\r\n'''\r\n\r\n# Output dtype = cv.CV_8U\r\nsobelx8u = cv2.Sobel(img,cv2.CV_8U,1,0,ksize=5)\r\n# Output dtype = cv.CV_64F. Then take its absolute and convert to cv.CV_8U\r\nsobelx64f = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)\r\nabs_sobel64f = np.absolute(sobelx64f)\r\nsobel_8u = np.uint8(abs_sobel64f)\r\n# show_img(sobelx8u,'sobelx8u Image')\r\n# show_img(sobel_8u,'sobel_8u Image')\r\n'''\r\nlaplacian = img+laplacian\r\nsobelx = img+sobelx\r\nsobely = img+sobely\r\n# sobelxy=cv2.Sobel(img,cv2.CV_64F,1,1,ksize=5)\r\nshow_img(laplacian,'Output laplacian Image')\r\nshow_img(sobelx,'Output sobelx Image')\r\nshow_img(sobely,'Output sobely Image')\r\n\r\nplt.show()\r\n","sub_path":"a14.py","file_name":"a14.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"388855574","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nweb=\"https://scirate.com/\"\n\npage=urlopen(web)\n\nsoup=BeautifulSoup(page,\"html.parser\")\n\nall_names=soup.find_all('div',attrs={'class' : 'title'})\nall_links=soup.find_all('a',attrs={'title':'Download PDF'})\ni=0\nfor name in all_names:\n\tprint('Name = '+name.text)\n\tif(i', '')\n sel = Selector(text=results, type='html')\n\n loader = BrightcorpItemLoader(selector=sel)\n loader.add_xpath(\n 'title',\n '//div/h1[@itemprop=\"name\"]/text()'\n )\n loader.add_xpath(\n 'location',\n [\n '//div/p[@class=\"infoRow\"]/a[@class=\"location\"]/span/text()',\n '//div/p[@class=\"infoRow\"]/a[@class=\"location\"]/span/span[@itemprop=\"name\"]/text()'\n ],\n NormalizedJoin(', ')\n )\n if not loader.get_output_value('location'):\n loader.add_xpath(\n 'location',\n '//div/p[@class=\"infoRow\"]/a[@class=\"name\"]/following-sibling::span[1]/text()',\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=self.REF_REGEX\n )\n loader.add_value('url', response.url)\n loader.add_xpath(\n 'description',\n '//div/div[@class=\"mainColWrap\"]/node()',\n RemoveBadElements(['hr', 'nav', 'a', 'img'])\n )\n loader.add_xpath(\n 'company',\n '//div/p[@class=\"infoRow\"]/a[@class=\"name\"]/text()'\n )\n loader.add_xpath(\n 'logo_url',\n '//div/div[@class=\"logotypeWrapper\"]/img/@src'\n )\n loader.add_xpath(\n 'jobtype',\n '//div[@class=\"asideBoxWrap\"]/ul/p/i[@class=\"icon-briefcase\"]/../text()'\n )\n loader.add_xpath(\n 'qualifications',\n '//div[@class=\"asideBoxWrap\"]/h6[contains(text(), \"Kvalifikationer\")]/following-sibling::ul[1]'\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/happyr.py","file_name":"happyr.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"234176775","text":"# This code assumes that the combine.py has been run to creation the generations function ind data for input\n\n# libraries\n#import numpy as np #only needed for example code\n#from matplotlib import rc\n#import pandas as pd # only needed for example code\nimport sys\nimport multibar as mb\n\n#which data to graph\nTARGET = \"95\"\nGRASS = \"1\"\nIND = \"10\"\nELITE = \"2\"\nRESULT = \"swg\"\n\n#indices\nD_AVG = 0\nD_STD = 1\nD_IND = {\"10\":0,\"20\":1,\"30\":2,\"40\":3,\"50\":4,\"60\":5,\"70\":6,\"80\":7} #whatever is in the bars is listed here to put bars in desired order\n\ndef read_data(filename):\n\ttry:\n\t\tfd = open(filename, \"r\")\n\t\tdata = {}\n\t\theaders = fd.readline().strip().split(\",\") #get the headers\n\t\t#find the index of each column we care about\n\t\tF_STD = headers.index(\"stdGen\")\n\t\tF_AVG = headers.index(\"avgGen\")\n\t\tF_IND = headers.index(\"individual\")\n\t\tF_TGT = headers.index(\"target\")\n\t\tF_GRASS = headers.index(\"grass\")\n\t\tF_FUNCTION = headers.index(\"function\")\n\t\tF_ELITE = headers.index(\"elitism\")\n\t\tF_MUT = headers.index(\"mutation\")\n\t\tF_RES = headers.index(\"result\")\n\n\t\tordering = []\n\n\t\tfor line in fd:\n\t\t\tsplit = line.split(\",\")\n\t\t\tif split[F_TGT] == TARGET and split[F_GRASS].strip() == GRASS and split[F_IND] == IND and split[F_ELITE].strip() == ELITE and split[F_RES].strip() == RESULT: #and split[F_FUNCTION][:3] != \"AVG\":\n\t\t\t\tkey = split[F_FUNCTION].strip()\n\t\t\t\tind = split[F_MUT].strip()\n\t\t\t\tif not key in data:\n\t\t\t\t\tdata[key] = [[0,0] for i in range(len(D_IND))] #[[0,0],[0,0],[0,0],[0,0]]\n\t\t\t\t\tordering.append(key)\n\t\t\t\tdata[key][D_IND[ind]][D_AVG] = (float(split[F_AVG].strip()))\n\t\t\t\tdata[key][D_IND[ind]][D_STD] = (float(split[F_STD].strip()))\n\n\t\tfd.close()\n\t\treturn data, ordering\n\n\texcept IOError:\n\t\tprint(\"Error reading and processing input data file. Aborting.\")\n\t\tsys.exit(-1)\n\n\ndata, ordering = read_data(\"generationdata_by_GAparameters_result.csv\")\n#print(process_data)\n#ordered = list(process_data.keys())\n#ordered.sort()\nlegend = [\"10\",\"20\",\"30\",\"40\",\"50\",\"60\",\"70\",\"80\"]\n\nif len(data) == 0 or len(ordering) == 0:\n\tprint(\"There is no data to plot\")\nelse:\n\t#create file name for plot\n\tplotname = \"multibar_generation_function_mutation_\"+TARGET+\"_\"+GRASS+\"_\"+IND+\"_\"+ELITE+\"_\"+RESULT+\".pdf\"\n\tmb.plot_data(data,plotname,\"Fitness Function\",\"Generations\",legend,ordering)\n\n\n","sub_path":"ResultsAnalysis/multibar_generations_function_mut_swg.py","file_name":"multibar_generations_function_mut_swg.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"101825854","text":"import json\nimport time\nfrom urllib.error import HTTPError\nfrom urllib.request import Request, urlopen\n\nimport gspread\nimport pandas as pd\n\nmonitor_url = 'https://monitor.uruguaysevacuna.gub.uy/plugin/cda/api/doQuery?'\n\nuy_init_cols = [\"daily_vaccinated\", \"daily_coronavac\", \"daily_pfizer\", \"daily_astrazeneca\",\n \"daily_agenda_ini\", \"daily_agenda\",\n \"total_ar\", \"total_ca\", \"total_cl\", \"total_co\", \"total_du\", \"total_fd\", \"total_fs\",\n \"total_la\", \"total_ma\", \"total_mo\", \"total_pa\", \"total_rn\", \"total_ro\", \"total_rv\", \"total_sa\",\n \"total_sj\", \"total_so\", \"total_ta\", \"total_tt\",\n \"people_ar\", \"people_ca\", \"people_cl\", \"people_co\", \"people_du\", \"people_fd\", \"people_fs\",\n \"people_la\", \"people_ma\", \"people_mo\", \"people_pa\", \"people_rn\", \"people_ro\", \"people_rv\", \"people_sa\",\n \"people_sj\", \"people_so\", \"people_ta\", \"people_tt\",\n \"fully_ar\", \"fully_ca\", \"fully_cl\", \"fully_co\", \"fully_du\", \"fully_fd\", \"fully_fs\",\n \"fully_la\", \"fully_ma\", \"fully_mo\", \"fully_pa\", \"fully_rn\", \"fully_ro\", \"fully_rv\", \"fully_sa\",\n \"fully_sj\", \"fully_so\", \"fully_ta\", \"fully_tt\",\n ]\n\nsegment_init_cols = [\"daily_teachers\", \"daily_elepem\", \"daily_chronic\", \"daily_undefined\", \"daily_dialysis\",\n \"daily_health\", \"daily_deprived_liberty\", \"daily_essential\", \"daily_no_risk\"]\n\nage_init_cols = [\n \"daily_18_24\", \"daily_25_34\", \"daily_35_44\", \"daily_45_54\", \"daily_55_64\", \"daily_65_74\", \"daily_75_115\",\n \"daily_undefined\", \"daily_18_49\", \"daily_50_70\", \"daily_71_79\", \"daily_80_115\"]\n\nregion_letter = {\n \"A\": \"ar\", \"B\": \"ca\", \"C\": \"cl\", \"D\": \"co\", \"E\": \"du\", \"F\": \"fs\", \"G\": \"fd\", \"H\": \"la\", \"I\": \"ma\", \"J\": \"mo\",\n \"K\": \"pa\", \"L\": \"rn\", \"M\": \"rv\", \"N\": \"ro\", \"O\": \"sa\", \"P\": \"sj\", \"Q\": \"so\", \"R\": \"ta\", \"S\": \"tt\", \"X\": \"unk\"\n}\n\n\ndef find_row(date, data_dic):\n return [elem for elem in data_dic if elem[\"date\"] == date]\n\n\ndef get_row_index(sheet_dic, row):\n return sheet_dic.index(row) + 2\n\n\ndef get_col_index(headers, label):\n return headers.index(label) + 1\n\n\ndef get_data(data, columns):\n json_origin = json.loads(urlopen(Request(monitor_url, data=data)).read().decode())\n return pd.DataFrame(json_origin[\"resultset\"], columns=columns).fillna(0)\n\n\ndef daily_vaccinated():\n data = b\"path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2FVacunasCovid.cda&\" \\\n b\"dataAccessId=sql_evolucion&outputIndexId=1&pageSize=0&pageStart=0&sortBy=¶msearchBox=\"\n return get_data(data, ['date', 'daily_vaccinated', 'daily_coronavac', 'daily_pfizer'])\n\n\ndef daily_vaccinated_by_age(date):\n # Date format YYYYMMDD\n today_str = bytes(date.replace(\"-\", \"\").encode())\n data = b\"paramp_periodo_desde_sk=\" + today_str + b\"¶mp_periodo_hasta_sk=\" + \\\n today_str + b\"¶mp_rango_tipo=7&\" \\\n b\"path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2F\" \\\n b\"VacunasCovid.cda&dataAccessId=sql_vacunas_rango_edad&\" \\\n b\"outputIndexId=1&pageSize=0&pageStart=0&\" \\\n b\"sortBy=¶msearchBox=\"\n result = get_data(data, ['age', 'value'])\n result.replace({'age': {\n u\" años\": u\"\",\n \"No Definido\": \"undefined\",\n \"> 18 meses y <= 21 meses\": \"0\",\n \"4 meses\": \"0\",\n \"> 21 meses y <= 2\": \"0\"\n }}, regex=True, inplace=True)\n\n daily_ages = {\n \"18_24\": 0, \"25_34\": 0, \"35_44\": 0, \"45_54\": 0, \"55_64\": 0, \"65_74\": 0, \"75_115\": 0, \"undefined\": 0,\n \"18_49\": 0, \"50_70\": 0, \"71_79\": 0, \"80_115\": 0\n }\n\n for age_index, age_row in result.iterrows():\n age = age_row[\"age\"]\n age_key = \"undefined\"\n age_key2 = age_key\n age_int = 0 if age == \"undefined\" else int(age)\n if 18 <= age_int <= 24:\n age_key = \"18_24\"\n elif 25 <= age_int <= 34:\n age_key = \"25_34\"\n elif 35 <= age_int <= 44:\n age_key = \"35_44\"\n elif 45 <= age_int <= 54:\n age_key = \"45_54\"\n elif 55 <= age_int <= 64:\n age_key = \"55_64\"\n elif 65 <= age_int <= 74:\n age_key = \"65_74\"\n elif age_int >= 75:\n age_key = \"75_115\"\n\n daily_ages[age_key] += age_row[\"value\"]\n\n if age_key != \"undefined\":\n if 18 <= age_int <= 49:\n age_key2 = \"18_49\"\n elif 50 <= age_int <= 70:\n age_key2 = \"50_70\"\n elif 71 <= age_int <= 79:\n age_key2 = \"71_79\"\n elif age_int >= 80:\n age_key2 = \"80_115\"\n\n daily_ages[age_key2] += age_row[\"value\"]\n\n return daily_ages\n\n\ndef region_vaccinated(date):\n # Date format YYYYMMDD\n today_str = bytes(date.replace(\"-\", \"\").encode())\n data = b\"paramp_periodo_desde_sk=\" + today_str + b\"¶mp_periodo_hasta_sk=\" + today_str + \\\n b\"¶mp_ncto_desde_sk=0&\" \\\n b\"paramp_ncto_hasta_sk=0&path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2F\" \\\n b\"VacunasCovid.cda&dataAccessId=sql_vacunas_depto_vacunatorio&outputIndexId=1&pageSize=0&\" \\\n b\"pageStart=0&sortBy=¶msearchBox=\"\n return get_data(data, [\n 'code', 'p_first_dose', 'name', 'scale', 'first_dose', 'population', 'second_dose', 'p_second_dose'])\n\n\ndef region_vaccination_centers():\n data = b\"path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2FVacunasCovid.cda&\" \\\n b\"dataAccessId=sql_filtro_centro_vacuna&outputIndexId=1&pageSize=0&pageStart=0&sortBy=¶msearchBox=\"\n return get_data(data, ['code', 'name'])\n\n\ndef date_agenda(date):\n # Date format YYYYMMDD\n today_str = bytes(date.replace(\"-\", \"\").encode())\n data = b\"paramp_periodo_desde_sk=\" + today_str + b\"¶mp_periodo_hasta_sk=\" + today_str + \\\n b\"&path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2FVacunasCovid.cda&\" \\\n b\"dataAccessId=sql_indicadores_gral_agenda&outputIndexId=1&pageSize=0&pageStart=0&sortBy=¶msearchBox=\"\n return get_data(data, ['future', 'today'])\n\n\ndef date_agenda_second_dose(date):\n # Date format YYYYMMDD\n today_str = bytes(date.replace(\"-\", \"\").encode())\n data = b\"paramp_periodo_desde_sk=\" + today_str + b\"¶mp_periodo_hasta_sk=\" + today_str + \\\n b\"&path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2FVacunasCovid.cda&\" \\\n b\"dataAccessId=sql_indicadores_gral_agenda_dosis2&outputIndexId=1&pageSize=0&pageStart=0&sortBy=¶msearchBox=\"\n return get_data(data, ['future', 'today'])\n\n\ndef today_status(date):\n # Date format YYYYMMDD\n today_str = bytes(date.replace(\"-\", \"\").encode())\n data = b\"paramp_periodo_desde_sk=\" + today_str + b\"¶mp_periodo_hasta_sk=\" + today_str + \\\n b\"&path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2FVacunas\" \\\n b\"Covid.cda&dataAccessId=sql_indicadores_generales&outputIndexId=1&pageSize=0&pageStart=0&\" \\\n b\"sortBy=¶msearchBox=\"\n return get_data(data, ['total_vaccinations', 'today_vaccinations', 'first_dose', 'second_dose', 'update_time',\n 'country_doses'])\n\n\ndef segment_vaccination(date):\n # Date format YYYYMMDD\n today_str = bytes(date.replace(\"-\", \"\").encode())\n data = b\"paramp_periodo_desde_sk=\" + today_str + b\"¶mp_periodo_hasta_sk=\" + today_str + \\\n b\"&path=%2Fpublic%2FEpidemiologia%2FVacunas+Covid%2FPaneles%2FVacunas+Covid%2FVacunas\" \\\n b\"Covid.cda&dataAccessId=sql_vacunas_poblacion&outputIndexId=1&pageSize=0&pageStart=0&\" \\\n b\"sortBy=¶msearchBox=\"\n\n result = get_data(data, ['segment', 'vaccinations'])\n # Replace segment names\n result[\"segment\"].replace({\"Docentes\": \"teachers\"}, inplace=True)\n result[\"segment\"].replace({\"ELEPEM\": \"elepem\"}, inplace=True)\n result[\"segment\"].replace({\"Enfermedad crónica\": \"chronic\"}, inplace=True)\n result[\"segment\"].replace({\"No Definido\": \"undefined\"}, inplace=True)\n result[\"segment\"].replace({\"Pacientes en diálisis\": \"dialysis\"}, inplace=True)\n result[\"segment\"].replace({\"Personal de salud\": \"health\"}, inplace=True)\n result[\"segment\"].replace({\"Personas privadas de libertad\": \"deprived_liberty\"}, inplace=True)\n result[\"segment\"].replace({\"Servicios esenciales\": \"essential\"}, inplace=True)\n result[\"segment\"].replace({\"Sin factores de riesgo\": \"no_risk\"}, inplace=True)\n\n return result\n\n\ndef add_formatted_row(spreadsheet, sheet, date, init_cols):\n sheet_id = sheet.id\n last_row = len(list(filter(None, sheet.col_values(1))))\n last_col = sheet.col_count\n body = {\n 'requests': [\n {\n 'copyPaste': {\n 'source': {\n 'sheetId': sheet_id,\n 'startRowIndex': int(last_row - 1), 'endRowIndex': last_row,\n 'startColumnIndex': 0, 'endColumnIndex': last_col\n },\n 'destination': {\n 'sheetId': sheet_id,\n 'startRowIndex': last_row, 'endRowIndex': int(last_row + 1),\n 'startColumnIndex': 0, 'endColumnIndex': last_col\n },\n 'pasteType': 'PASTE_FORMULA'\n }\n }\n ]\n }\n spreadsheet.batch_update(body) # Paste Formula\n body[\"requests\"][0][\"copyPaste\"][\"pasteType\"] = \"PASTE_FORMAT\"\n spreadsheet.batch_update(body)\n\n sheet_headers = sheet.row_values(1)\n date_index = get_col_index(sheet_headers, \"date\")\n sheet.update_cell(int(last_row + 1), date_index, date)\n\n batch_update_cells = []\n for col_ini in init_cols:\n col_init_index = get_col_index(sheet_headers, col_ini)\n batch_update_cells.append(gspread.models.Cell(int(last_row + 1), col_init_index, value=0))\n if len(batch_update_cells) > 0:\n sheet.update_cells(batch_update_cells)\n\n\ndef transform_date(date_str):\n date_str = \"-\".join(date_str.split(\"-\")[::-1])\n if not date_str.startswith(\"2021-\"):\n date_str = \"2021-\" + date_str # WA when format is without year\n return date_str\n\n\ndef update():\n # region_vacc_centers = region_vaccination_centers()\n\n # for region_vacc_center_index, region_vacc_center in region_vacc_centers.iterrows():\n # name = region_vacc_center[\"name\"]\n # print(name)\n # #print(name.split(\" \")[0])\n\n # # print(region_vacc_center)\n # return False\n\n updates = False\n\n daily_vac_origin = daily_vaccinated()\n\n today = transform_date(daily_vac_origin.tail(1)[\"date\"].values[0])\n\n try:\n day_agenda = int(date_agenda(today)[\"today\"].item() or 0)\n # Increment to the total day agenda the second dose\n day_agenda += int(date_agenda_second_dose(today)[\"today\"].item() or 0)\n except HTTPError as e:\n print(\"Agenda error!\")\n day_agenda = 0\n\n today_vac_status = today_status(today)\n\n today_uodate_time = today + \" \" + today_vac_status[\"update_time\"].values[0]\n\n # TODO: The api began to misinform the total, it is calculated with people first and second dose\n # today_total_vaccinations = int(today_vac_status[\"total_vaccinations\"].item() or 0)\n today_total_people_vaccinations = int(today_vac_status[\"first_dose\"].item() or 0)\n today_total_fully_vaccinations = int(today_vac_status[\"second_dose\"].item() or 0)\n today_total_vaccinations = today_total_people_vaccinations + today_total_fully_vaccinations\n\n gc = gspread.service_account()\n sh = gc.open(\"CoronavirusUY - Vaccination monitor\")\n\n sheet = sh.worksheet(\"Uruguay\")\n sheet_dic = sheet.get_all_records()\n sheet_headers = sheet.row_values(1)\n\n sheet_segment = sh.worksheet(\"Segment\")\n sheet_segment_dic = sheet_segment.get_all_records()\n\n sheet_segment_headers = sheet_segment.row_values(1)\n last_segment_row = sheet_segment_dic[-1]\n\n sheet_age = sh.worksheet(\"Age\")\n sheet_age_dic = sheet_age.get_all_records()\n\n sheet_age_headers = sheet_age.row_values(1)\n last_age_row = sheet_age_dic[-1]\n\n daily_people_vaccinated_col_index = get_col_index(sheet_headers, \"people_vaccinated\")\n daily_people_fully_vaccinated_col_index = get_col_index(sheet_headers, \"people_fully_vaccinated\")\n\n daily_vac_total_col_index = get_col_index(sheet_headers, \"daily_vaccinated\")\n daily_coronavac_col_index = get_col_index(sheet_headers, \"daily_coronavac\")\n daily_pfizer_col_index = get_col_index(sheet_headers, \"daily_pfizer\")\n\n daily_agenda_ini_col_index = get_col_index(sheet_headers, \"daily_agenda_ini\")\n daily_agenda_col_index = get_col_index(sheet_headers, \"daily_agenda\")\n\n last_row = sheet_dic[-1]\n last_date = last_row[\"date\"]\n\n if last_date == today:\n if (today_total_vaccinations - last_row[\"total_vaccinations\"]) < -1:\n print(\"* Execution Excluded! Corrupt source data? Last valid:\" + str(\n last_row[\"total_vaccinations\"]) + \" new:\" + str(today_total_vaccinations))\n return False\n\n batch_update_cells = []\n batch_update_segment_cells = []\n batch_update_age_cells = []\n\n for daily_vac_origin_index, daily_vac_origin_row in daily_vac_origin.iterrows():\n\n # Get date\n date_row = transform_date(daily_vac_origin_row[\"date\"])\n\n sheet_row = find_row(date_row, sheet_dic)\n if len(sheet_row) == 0: # If not exist, create the row\n\n if date_row == today:\n if (today_total_vaccinations - last_row[\"total_vaccinations\"]) < -1:\n print(\"* New date, Execution Excluded! Corrupt source data? Last valid:\" + str(\n last_row[\"total_vaccinations\"]) + \" new:\" + str(today_total_vaccinations))\n return False\n\n add_formatted_row(sh, sheet, date_row, uy_init_cols)\n time.sleep(2) # Wait for refresh\n sheet_dic = sheet.get_all_records() # Get updated changes\n sheet_row = find_row(date_row, sheet_dic)\n\n last_row = sheet_dic[-1]\n last_date = last_row[\"date\"]\n\n sheet_daily_vac = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"daily_vaccinated\"] or 0)\n\n sheet_daily_vac_coronavac = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"daily_coronavac\"] or 0)\n sheet_daily_vac_pfizer = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"daily_pfizer\"] or 0)\n\n daily_vac_origin_value = daily_vac_origin_row[\"daily_vaccinated\"]\n daily_vac_coronavac_origin_value = int(daily_vac_origin_row[\"daily_coronavac\"])\n daily_vac_pfizer_origin_value = int(daily_vac_origin_row[\"daily_pfizer\"])\n\n sheet_row_index = -1 if len(sheet_row) == 0 else get_row_index(sheet_dic, sheet_row[0])\n\n sheet_agenda_ini = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"daily_agenda_ini\"] or 0)\n sheet_agenda = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"daily_agenda\"] or 0)\n\n sheet_people_vaccinated = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"people_vaccinated\"] or 0)\n sheet_fully_vaccinations = 0 if len(sheet_row) == 0 else int(sheet_row[0][\"people_fully_vaccinated\"] or 0)\n\n if today == date_row:\n if sheet_agenda_ini == 0 and day_agenda > 0:\n # Set the ini agenda value\n print(\"Update Agenda ini:\" + date_row + \" idx:\" + str(sheet_row_index) + \" old:\" + str(\n sheet_agenda_ini) + \" new:\" + str(day_agenda))\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_agenda_ini_col_index, value=day_agenda)\n )\n if sheet_agenda < day_agenda:\n print(\"Update Agenda:\" + date_row + \" idx:\" + str(sheet_row_index) + \" old:\" + str(\n sheet_agenda) + \" new:\" + str(day_agenda))\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_agenda_col_index, value=day_agenda)\n )\n\n # Update People vaccinated and Fully vaccinated\n if sheet_people_vaccinated != today_total_people_vaccinations:\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_people_vaccinated_col_index,\n value=today_total_people_vaccinations)\n )\n if sheet_fully_vaccinations != today_total_fully_vaccinations:\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_people_fully_vaccinated_col_index,\n value=today_total_fully_vaccinations)\n )\n\n if len(sheet_row) == 0: # Extra control\n print(\"Create:\" + date_row + \" old: none new:\" + str(daily_vac_origin_value))\n else:\n if sheet_daily_vac != daily_vac_origin_value:\n\n print(\"Update:\" + date_row + \" idx:\" + str(sheet_row_index) + \" old:\" + str(\n sheet_daily_vac) + \" new:\" + str(daily_vac_origin_value))\n\n if int(daily_vac_origin_value) < sheet_daily_vac:\n print(\"* Warning! decrement!\")\n\n if int(daily_vac_origin_value) != sheet_daily_vac:\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_vac_total_col_index, value=daily_vac_origin_value)\n )\n\n if int(daily_vac_coronavac_origin_value) != sheet_daily_vac_coronavac:\n # Update daily vaccinated by type\n\n print(\"Update Coronavac:\" + date_row + \" idx:\" + str(sheet_row_index) + \" old:\" + str(\n sheet_daily_vac_coronavac) + \" new:\" + str(daily_vac_coronavac_origin_value))\n\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_coronavac_col_index,\n value=daily_vac_coronavac_origin_value)\n )\n\n if int(daily_vac_pfizer_origin_value) != sheet_daily_vac_pfizer:\n print(\"Update Pfizer:\" + date_row + \" idx:\" + str(sheet_row_index) + \" old:\" + str(\n sheet_daily_vac_pfizer) + \" new:\" + str(daily_vac_pfizer_origin_value))\n\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_pfizer_col_index,\n value=daily_vac_pfizer_origin_value)\n )\n\n # Segment\n if today == date_row:\n segment = segment_vaccination(date_row)\n sheet_segment_row = find_row(date_row, sheet_segment_dic)\n if len(sheet_segment_row) == 0: # If not exist, create the row\n add_formatted_row(sh, sheet_segment, date_row, segment_init_cols)\n time.sleep(2) # Wait for refresh\n sheet_segment_dic = sheet_segment.get_all_records() # Get updated changes\n sheet_segment_row = find_row(date_row, sheet_segment_dic)\n\n sheet_segment_row_index = -1 if len(sheet_segment_row) == 0 else get_row_index(sheet_segment_dic,\n sheet_segment_row[0])\n\n for daily_segment_origin_index, daily_segment_origin_row in segment.iterrows():\n segment_label = \"daily_\" + daily_segment_origin_row[\"segment\"]\n segment_daily = int(daily_segment_origin_row[\"vaccinations\"])\n\n daily_segment_col_index = get_col_index(sheet_segment_headers, segment_label)\n\n batch_update_segment_cells.append(\n gspread.models.Cell(sheet_segment_row_index, daily_segment_col_index,\n value=segment_daily)\n )\n\n # Age\n if today == date_row:\n daily_by_age = daily_vaccinated_by_age(date_row)\n sheet_age_row = find_row(date_row, sheet_age_dic)\n if len(sheet_age_row) == 0: # If not exist, create the row\n add_formatted_row(sh, sheet_age, date_row, age_init_cols)\n time.sleep(2) # Wait for refresh\n sheet_age_dic = sheet_age.get_all_records() # Get updated changes\n sheet_age_row = find_row(date_row, sheet_age_dic)\n\n sheet_age_row_index = -1 if len(sheet_age_row) == 0 else get_row_index(sheet_age_dic,\n sheet_age_row[0])\n\n for daily_age_key, daily_age_value in daily_by_age.items():\n age_label = \"daily_\" + daily_age_key\n age_daily = daily_age_value\n\n daily_age_col_index = get_col_index(sheet_age_headers, age_label)\n batch_update_age_cells.append(\n gspread.models.Cell(sheet_age_row_index, daily_age_col_index,\n value=age_daily)\n )\n\n if today == date_row:\n\n # Get region data for that date\n # TODO: The api lost the filter by date\n daily_vac_region_origin = region_vaccinated(date_row)\n\n for daily_vac_region_origin_index, daily_vac_region_origin_row in daily_vac_region_origin.iterrows():\n # Generate the label with the sheet format\n region_id = daily_vac_region_origin_row[\"code\"].split(\"-\")[1].lower()\n region_total_label = \"total_\" + region_id\n region_people_label = \"people_\" + region_id\n region_fully_label = \"fully_\" + region_id\n sheet_total_vac_region = 0 if len(sheet_row) == 0 else int(sheet_row[0][region_total_label] or 0)\n\n population = int(daily_vac_region_origin_row[\"population\"].replace(\".\", \"\"))\n daily_vac_region_origin_p_first_value = float(\n daily_vac_region_origin_row[\"p_first_dose\"].replace(\"%\", \"\").replace(\",\", \".\")) / 100\n\n daily_vac_region_origin_p_second_value = float(\n daily_vac_region_origin_row[\"p_second_dose\"].replace(\"%\", \"\").replace(\",\", \".\")) / 100\n\n daily_vac_region_origin_people_value = int(population * daily_vac_region_origin_p_first_value)\n daily_vac_region_origin_fully_value = int(population * daily_vac_region_origin_p_second_value)\n daily_vac_region_origin_total_value = daily_vac_region_origin_people_value\n daily_vac_region_origin_total_value += daily_vac_region_origin_fully_value\n\n if len(sheet_row) == 0:\n print(\"Create Region:\" + date_row + \" \" + region_total_label + \" old: none new:\" + str(\n daily_vac_region_origin_total_value))\n elif sheet_total_vac_region != daily_vac_region_origin_total_value:\n daily_vac_total_col_index = get_col_index(sheet_headers, region_total_label)\n daily_vac_people_col_index = get_col_index(sheet_headers, region_people_label)\n daily_vac_fully_col_index = get_col_index(sheet_headers, region_fully_label)\n\n print(\"Update Region:\" + date_row + \" \" + region_total_label + \" idx:\" + str(\n sheet_row_index) + \" old:\" + str(sheet_total_vac_region) + \" new:\" + str(\n daily_vac_region_origin_total_value))\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_vac_total_col_index,\n value=daily_vac_region_origin_total_value)\n )\n\n # Update people and fully\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_vac_people_col_index,\n value=daily_vac_region_origin_people_value)\n )\n batch_update_cells.append(\n gspread.models.Cell(sheet_row_index, daily_vac_fully_col_index,\n value=daily_vac_region_origin_fully_value)\n )\n if daily_vac_region_origin_total_value < sheet_total_vac_region:\n print(\"* Warning! decrement! \")\n\n to_update_segment = len(batch_update_segment_cells)\n if to_update_segment > 0:\n update_data = sheet_segment.update_cells(batch_update_segment_cells)\n # TODO: Implement a generic method to update batch of a sheet with retries\n\n to_update_age = len(batch_update_age_cells)\n if to_update_age > 0:\n update_data = sheet_age.update_cells(batch_update_age_cells)\n # TODO: Implement a generic method to update batch of a sheet with retries\n\n to_update = len(batch_update_cells)\n if to_update > 0:\n updates = True\n update_data = sheet.update_cells(batch_update_cells)\n updated = update_data[\"updatedCells\"]\n print(\"To update cells:\" + str(to_update) + \" Updated:\" + str(updated))\n\n if to_update != updated:\n # Find difference and force to update\n address = []\n rows = []\n cols = []\n values = []\n for cell in batch_update_cells:\n rows.append(cell.row)\n cols.append(cell.col)\n address.append(cell.address)\n values.append(cell.value)\n\n ret_values = sheet.batch_get(address)\n force_cells = []\n for index, val in enumerate(ret_values):\n if int(val[0][0]) != values[index]:\n print(\"Not updated:\" + address[index] + \" Val:\" + str(values[index]) + \" S:\" + str(int(val[0][0])))\n force_cells.append(\n gspread.models.Cell(rows[index], cols[index], value=values[index])\n )\n to_update = len(force_cells)\n if to_update > 0:\n update_data = sheet.update_cells(force_cells)\n updated = update_data[\"updatedCells\"]\n print(\"Force to update cells:\" + str(to_update) + \" Updated:\" + str(updated))\n\n # Refresh and check results\n time.sleep(2) # Wait for refresh\n sheet_dic = sheet.get_all_records() # Get updated changes\n last_row = sheet_dic[-1]\n last_date = last_row[\"date\"]\n\n if last_date == today:\n print(\"Source Total:\" + str(last_row[\"total_vaccinations\"]) + \" Final Total:\" + str(today_total_vaccinations))\n\n # Update date time data\n sheet_data = sh.worksheet(\"Data\")\n sheet_data.update_cell(6, 10, today_uodate_time)\n\n return updates\n\n\nif __name__ == \"__main__\":\n limit_retry = 10\n num_retry = 1\n while num_retry <= limit_retry:\n print(\"Update:\" + str(num_retry))\n if not update():\n print(\"Update finished\")\n break\n print(\"Updated data, retrying to ensure no pending data...\")\n num_retry += 1\n\n if num_retry > limit_retry:\n print(\"Retry limit reached\")\n","sub_path":"scripts/incremental.py","file_name":"incremental.py","file_ext":"py","file_size_in_byte":27536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"625095298","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 6 14:28:34 2016\n\n@author: james\n\"\"\"\n\nimport RNADictionary as RNA\n\ninfo = RNA.giveDict()\n\nfile = open('rosalind_mrna.txt')\nline = file.readline()\n\ntotal=1\ncount=0\n\nfor j in line:\n print(j)\n if(j == ' '):\n j = 'STOP'\n for keys in info:\n if( info[keys] == j ):\n count+=1\n if(count != 0 ):\n total*=count\n count=0\n \nprint(total%1000000)","sub_path":"inferringmRNAFromProtein.py","file_name":"inferringmRNAFromProtein.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"353422092","text":"#!/usr/bin/python3\n\n\"\"\"Module matrix_divided\nDocumentation as specified by how can divided a matrix.\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n\n \"\"\"Example function matrix_divided.\n Args:\n matrix: First parameter.\n div: Second parameter.\n Return:\n return new matrix.\n \"\"\"\n\n sizeRow = \"Each row of the matrix must have the same size\"\n matrix_new = []\n for list in matrix:\n list_new = []\n for item_list in list:\n if type(item_list) is not int and type(item_list) is not float:\n raise TypeError('matrix must be a matrix (list of lists) \\\n of integers/floats')\n if len(list) != len(matrix[0]):\n raise TypeError(sizeRow)\n if type(div) != int and type(div) != float:\n raise TypeError('div must be a number')\n if div == 0:\n raise ZeroDivisionError('division by zero')\n result = item_list / div\n list_new.append(round(result, 2))\n matrix_new.append(list_new)\n return matrix_new\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"612736520","text":"def solve(lines):\n instr = [int(i) for i in lines]\n\n steps = 0\n ptr = 0\n\n while True:\n steps += 1\n\n offs = instr[ptr]\n if instr[ptr] >= 3:\n instr[ptr] -= 1\n else:\n instr[ptr] += 1\n ptr += offs\n\n if ptr >= len(instr) or ptr < 0:\n break\n\n print(steps)\n\n\nwith open(\"input.txt\", \"r\") as file:\n solve(file.read().splitlines())\n","sub_path":"5/second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"534046153","text":"\nclass Solution(object):\n def calculateMinimumHP(self, dungeon):\n \"\"\"\n :type dungeon: List[List[int]]\n :rtype: int\n \"\"\"\n hp = [ [ float(\"inf\") for col in range(len(dungeon[0])+1) ] for row in range(len(dungeon)+1)]\n\n # initialize\n hp[-1][-2] = 1\n\n for row in range(len(hp)-2, -1, -1):\n for col in range(len(hp[0])-2, -1, -1):\n hp[row][col] = max(1, min(hp[row][col+1], hp[row+1][col]) - dungeon[row][col])\n\n return hp[0][0]\n","sub_path":"174sol.py","file_name":"174sol.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"371970690","text":"from sklearn import svm\nimport time\nimport shelve\n\ncorrect_for_REST = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ncorrect_for_SOAP = [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]\ncorrect_for_XMLRPC = [31, 32, 33, 34, 35, 36, 37, 38, 39, 40]\n\nsample = raw_input('Enter the sample file: ')\nexpdata = raw_input('Enter the experience data: ')\n\ndigt_sample = shelve.open(sample)\ndigt_expdata = shelve.open(expdata)\n\nsample_data = digt_sample['res']['sample']\nsample_label = digt_sample['res']['label']\n\nSOAP = 0\nREST = 0\nXMLRPC = 0\nERROR = 0\n\nSOAPlines = []\nRESTlines = []\nXMLRPClines = []\n\nstart = time.clock()\n\nclf = svm.SVC()\nclf.fit(sample_data, sample_label)\n\nfor i in digt_expdata['res']:\n if clf.predict(digt_expdata['res'][i])[0] == 'SOAPAPI':\n SOAP += 1\n SOAPlines.append(i)\n if clf.predict(digt_expdata['res'][i])[0] == 'XMLRPC':\n XMLRPC += 1\n XMLRPClines.append(i)\n if clf.predict(digt_expdata['res'][i])[0] == 'RESTAPI':\n REST += 1\n RESTlines.append(i)\n\nend = time.clock()\n\nalltrueinfo = {\n 'SOAP': len(correct_for_SOAP),\n 'REST': len(correct_for_REST),\n 'XMLRPC': len(correct_for_XMLRPC)}\npretureinfo = {'SOAP': 0, 'REST': 0, 'XMLRPC': 0}\nalltesttureinfo = {'SOAP': 0, 'REST': 0, 'XMLRPC': 0}\n\npretureinfo['SOAP'] += len(SOAPlines)\npretureinfo['REST'] += len(RESTlines)\npretureinfo['XMLRPC'] += len(XMLRPClines)\n\ntmp1 = []\nfor i in SOAPlines:\n if i in correct_for_SOAP:\n alltesttureinfo['SOAP'] += 1\n if i not in correct_for_SOAP:\n tmp1.append(i)\nERROR += len(tmp1)\n\ntmp1 = []\nfor i in RESTlines:\n if i in correct_for_REST:\n alltesttureinfo['REST'] += 1\n if i not in correct_for_REST:\n tmp1.append(i)\nERROR += len(tmp1)\n\ntmp1 = []\nfor i in XMLRPClines:\n if i in correct_for_XMLRPC:\n alltesttureinfo['XMLRPC'] += 1\n if i not in correct_for_XMLRPC:\n tmp1.append(i)\nERROR += len(tmp1)\n\nprint(\"SOAP flows: \", SOAP, \"Lines: \", SOAPlines,\n \"Recall: \", (float(alltesttureinfo['SOAP']) / float(alltrueinfo['SOAP'])),\n \"Precision: \", (float(alltesttureinfo['SOAP']) / float(pretureinfo['SOAP'])))\nprint(\"REST flows: \", REST, \"Lines: \", RESTlines,\n \"Recall: \", (float(alltesttureinfo['REST']) / float(alltrueinfo['REST'])),\n \"Precision: \", (float(alltesttureinfo['REST']) / float(pretureinfo['REST'])))\nprint(\"XMLRPC flows: \",\n XMLRPC,\n \"Lines: \",\n XMLRPClines,\n \"Recall: \",\n (float(alltesttureinfo['REST']) / float(alltrueinfo['REST'])),\n \"Precision: \",\n (float(alltesttureinfo['XMLRPC']) / float(pretureinfo['XMLRPC'])))\nprint(\"Cannot identify: \", ERROR)\nprint(\"Cost: %f seconds\") % (end - start)\n","sub_path":"TEST1/tool/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"382638365","text":"#py3.7\r\nimport os\r\n\r\ndef makeListsOfFiles(DirPath): #from 010fileDirs.py\r\n fileFullPathList = []\r\n for root, dirs, files in os.walk(DirPath):\r\n for file in files:\r\n fileFullPathList.append(root + \"\\\\\" + file)\r\n return fileFullPathList\r\n \r\ndef filterText(text):\r\n def filterOnlyPrintable(str):\r\n return filter(lambda x: x in '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\\'()*+,-./:;<=>?@[\\]^_`{|}~ \\t\\n\\r\\x0b\\x0c', str) #import string #string.printable\r\n def filterOnlySeenableAndSpace(str):\r\n return filter(lambda x: x not in '\\t\\n\\r\\x0b\\x0c', str) #characters taken from end of string.printable\r\n \r\n filtered1 = filterOnlyPrintable(text)\r\n filtered2 = filterOnlySeenableAndSpace(filtered1)\r\n return filtered2\r\n \r\ndef fileReadFiltered(filePath):\r\n txt = open(filePath)\r\n return filterText(txt.read())\r\n \r\n \r\ndef combineNPletDicts(dict1, dict2):\r\n ret = dict1.copy()\r\n for i in dict2:\r\n if i in ret:\r\n ret[i]+=dict2[i]\r\n else:\r\n ret[i]=dict2[i]\r\n return ret\r\n \r\ndef nPlets(text, n): #from 012nPletsFromString.py\r\n ret = {}\r\n if n<1: return ret\r\n \r\n for i in range(len(text)-n+1):\r\n cut = text[i:i+n]\r\n if cut in ret:\r\n ret[cut] += 1\r\n else:\r\n ret[cut] = 1\r\n #print(cut)\r\n return ret\r\n \r\n#########################################################################\r\nimport unittest\r\n\r\nclass TestStringMethods(unittest.TestCase):\r\n def test_combineDicts(self):\r\n duDict1 = {'a ': 1, ' s': 2, 'sa': 3, 'am': 2, 'mp': 1}\r\n duDict2 = {'sa': 1, ' b': 3, 'am': 5, 'nd': 3, ' a': 1 ,'ot': 2}\r\n duDict3 = combineNPletDicts(duDict1, duDict2)\r\n self.assertEqual(duDict3, {'a ': 1, ' s': 2, 'sa': 4, 'am': 7, 'mp': 1, ' b': 3, 'nd': 3, ' a': 1, 'ot': 2})\r\n self.assertEqual(duDict1['am'], 2)\r\n self.assertEqual(duDict2['am'], 5)\r\n\r\n \r\n def test_isupper(self):\r\n self.assertTrue('FOO'.isupper())\r\n self.assertFalse('Foo'.isupper())\r\n\r\n def test_split(self):\r\n s = 'hello world'\r\n self.assertEqual(s.split(), ['hello', 'world'])\r\n # check that s.split fails when the separator is not a string\r\n with self.assertRaises(TypeError):\r\n s.split(2)\r\n\r\nif __name__ == \"__main__\":\r\n from sys import argv\r\n if len(argv)>1 and argv[1] == 'runTests':\r\n unittest.main(argv=['FakeArgvToRemoveErrorsIfCalledWithParams'])\r\n else:\r\n print('Runned just like a program without \"runTests\" parameter, argv: ', argv)\r\n","sub_path":"_01moduleNPLETS.py","file_name":"_01moduleNPLETS.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"72455724","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport cv2 as cv2\nimport numpy as np\n\nfrom model.model_segmentation_HySegnetV2 import model_segmentation_HySegnetV2\nfrom util.segmentation_dataloader_v1 import segmentation_dataloader_v1\n\ntrain_loader = segmentation_dataloader_v1('C://Github//OpenDL//python//dataset//portrait_segmentation_train_input256x256//', 'C://Github//OpenDL//python//dataset//portrait_segmentation_train_label256x256//')\nvalidation_loader = segmentation_dataloader_v1('C://Github//OpenDL//python//dataset//portrait_segmentation_validation_input256x256//', 'C://Github//OpenDL//python//dataset//portrait_segmentation_validation_label256x256//')\n\ntrain_epoch = 10000\nbatch_size = 6\nsample_size = train_loader.size()\ntotal_batch = int(sample_size / batch_size)\ntarget_accuracy = 0.90\nlearning_rate = 0.003\n\nsess = tf.Session()\nmodel = model_segmentation_HySegnetV2(sess=sess, name=\"model_segmentation_HySegnetV2\")\n\nglobal_variable_initializer = tf.compat.v1.global_variables_initializer()\nprint('global variable initializer name : ', global_variable_initializer.name)\nsess.run(global_variable_initializer)\n\n## save model file\nsaver = tf.compat.v1.train.Saver()\nsaver.save(sess, 'C:/Github/OpenDL/python/pretrained-model/model_segmentation_HySegnetV1/model_segmentation_HySegnetV2')\ntf.train.write_graph(sess.graph_def, \"\", 'C:/Github/OpenDL/python/pretrained-model/model_segmentation_HySegnetV1/model_segmentation_HySegnetV2.pbtxt', as_text=True)\n\n\ncost_graph = []\naccuracy_graph = []\nprint('Learning start.')\n\nfor step in range(train_epoch):\n\n train_loader.clear()\n avg_cost = 0\n avg_accuracy = 0\n accuracy = 0\n for batch in range(total_batch):\n #train_loader.clear()\n input_images, input_labels = train_loader.load([1024, 1024, 1], [1024, 1024, 1], 1, 255, batch_size)\n\n if input_images is None:\n train_loader.clear()\n break\n\n cost, _ = model.train(input_images, input_labels, keep_prop=True, learning_rate=learning_rate)\n avg_cost += cost / total_batch\n\n validation_loader.clear()\n for validation_step in range(100):\n validation_images, validation_labels = validation_loader.load([1024, 1024, 1], [1024, 1024, 1], 1, 255, 1)\n accuracy = model.get_accuracy(validation_images, validation_labels, keep_prop=False)\n avg_accuracy += (accuracy / 100)\n print('Validation Step: ', '%04d' % (validation_step + 1), ' step accuracy = ', '{:.9f}'.format(accuracy),)\n\n output_images = model.reconstruct(validation_images, keep_prop=False)\n output_reshape = output_images[0] * 255\n input_image = validation_images[0]\n input_label = validation_labels[0] * 255\n\n\n cv2.imshow('reconstruced image', output_reshape)\n cv2.imshow('input image', input_image)\n cv2.imshow('input label', input_label)\n cv2.waitKey(10)\n validation_loader.clear()\n\n accuracy_graph.append(accuracy)\n cost_graph.append(avg_cost)\n\n print('Epoch : ', '%04d' % (step + 1), 'cost =', '{:.9f}'.format(avg_cost), 'accuracy =', '{:.9f}'.format(avg_accuracy))\n if avg_accuracy > target_accuracy:\n break;\n\ntf.train.write_graph(sess.graph.as_graph_def(),\"./pretrained-models/model_segmentation_HySegnetV1/\", \"model_segmentation_HySegnetV1.pb\")\nsaver = tf.train.Saver(tf.global_variables())\nsaver.save(sess, './pretrained-models/model_segmentation_HySegnetV1/model_segmentation_HySegnetV1.ckpt')\n\nplt.plot(cost_graph)\nplt.plot(accuracy_graph)\nplt.ylabel('cost, accuracy')\nplt.legend(['cost', 'accuracy'], loc='upper left')\nplt.savefig('./pretrained-models/model_segmentation_HySegnetV1/model_segmentation_HySegnetV1.png')\nplt.show()\n\nprint('Learning finished.')","sub_path":"python/work/tensorflow-HySegnetV1-train.py","file_name":"tensorflow-HySegnetV1-train.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"354009473","text":"import pygame\nimport time\nimport socket\nimport threading\nfrom PIL import Image\nimport pyscreenshot as ImageGrab\nimport zlib\nfrom pymouse import PyMouse\n\nIMAGE_SIZE = 1024, 768\n\nclass Client(object):\n\tdef __init__(self):\n\t\tself.running = True\n\t\tself.server_host = 'localhost'\n\t\tself.my_socket = None\n\t\tpygame.init()\n\t\tsize=(IMAGE_SIZE)\n\t\tself.screen = pygame.display.set_mode(size) \n\t\tself.clock = pygame.time.Clock() # clock for timing\n\t\tpygame.display.set_caption('myRDC', 'myRDC')\n\t\tself.mouse = PyMouse()\n\n\tdef run(self):\n\t\tself.my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.my_socket.connect((self.server_host, 6666))\n\t\tmax_size = 3 * IMAGE_SIZE[0] * IMAGE_SIZE[1]\n\t\ttry:\n\t\t\tdata = self.my_socket.recv(max_size)\n\t\t\twhile self.running:\n\t\t\t\tif(len(data) == max_size):\n\t\t\t\t\t#decimg = zlib.decompress(data)\n\t\t\t\t\timg = pygame.image.fromstring(data, IMAGE_SIZE, \"RGB\")\n\t\t\t\t\tself.screen.blit(img,(0,0))\n\t\t\t\t\tpygame.display.flip() # update the display\n\t\t\t\t\tclient.clock.tick(30) # only tick 30 frames per second\n\t\t\t\t\tdata = self.my_socket.recv(max_size)\n\t\t\t\telse:\n\t\t\t\t\tdata += self.my_socket.recv(max_size)\n\t\t\t\tself.my_socket.send((str(self.mouse.position()[0]) + \",\" + str(self.mouse.position()[1])).encode())\n\t\t\t\tfor event in pygame.event.get():\n\t\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\t\tself.running = False\n\t\t\tself.kill()\n\t\t\tpygame.quit()\n\t\texcept SystemExit:\n\t\t\tself.kill()\n\t\tpygame.quit()\n\n\t\t#threading.Thread(target=self.receive).start()\n\n\tdef kill(self):\n\t\tself.running = False\n\t\tself.my_socket.close()\n\n\nif __name__ == '__main__':\n\tclient = Client()\n\tclient.run()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"280617930","text":"from pyramid.security import (\n Allow,\n Authenticated,\n ALL_PERMISSIONS,\n Everyone,\n Deny\n)\n\nfrom .init_db import Base, BaseExport, dbConfig, get_redis_con\nfrom .base_model import *\nfrom .base_view import *\nfrom .base_resource import *\nfrom .configuration_model import *\n\n\nclass SecurityRoot(Resource):\n __acl__ = [\n (Allow, Authenticated, 'fixForOld'),\n (Allow, Authenticated, 'read'),\n (Allow, Authenticated, 'all'),\n (Allow, 'group:admin', 'admin'),\n (Allow, 'group:admin', 'superUser'),\n (Allow, 'group:admin', 'all'),\n (Allow, 'group:superUser', 'superUser'),\n (Allow, 'group:superUser', 'all')\n ]\n\n def __init__(self, request):\n Resource.__init__(self, ref='', parent=None)\n self.request = request\n\n def __getitem__(self, item):\n if item == 'ecoReleve-Core':\n return RootCore(item, self)\n else:\n raise KeyError\n\n\nclass RootCore(Resource):\n\n children = []\n\n def retrieve(self):\n return {'next items': self}","sub_path":"Back/ecoreleve_server/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"98180383","text":"import unittest\nimport threading\nfrom rtfMRI.MsgTypes import MsgType, MsgEvent, MsgResult # type: ignore\nfrom rtfMRI.Messaging import RtMessagingServer, Message # type: ignore\nfrom rtfMRI.Messaging import RtMessagingClient\n\n\nclass Test_Messaging(unittest.TestCase):\n def setUp(self):\n self.server = RtMessagingServer(5501)\n\n def serveRequests():\n while True:\n req = self.server.getRequest()\n if req.type == MsgType.Shutdown:\n break\n reply = Message()\n reply.id = req.id\n reply.type = MsgType.Reply\n reply.event_type = req.event_type\n reply.result = MsgResult.Success\n self.server.sendReply(reply)\n self.server.close()\n self.server_thread = threading.Thread(\n name='server', target=serveRequests)\n self.server_thread.setDaemon(True)\n self.server_thread.start()\n\n def tearDown(self):\n self.server.close()\n\n def test_sendMessages(self):\n print(\"test_sendMessages\")\n client = RtMessagingClient('localhost', 5501)\n msg = Message()\n msg.id = 1\n msg.type = MsgType.Command\n msg.event_type = MsgEvent.TRData\n msg.fields.a = 10\n msg.data = b\"1, 2, 3, 4, 5\"\n client.sendRequest(msg)\n reply = client.getReply()\n self.assertTrue(reply.type == MsgType.Reply)\n self.assertTrue(reply.event_type == msg.event_type)\n self.assertTrue(reply.result == MsgResult.Success)\n client.close()\n # Reconnect to client\n client = RtMessagingClient('localhost', 5501)\n client.sendRequest(msg)\n reply = client.getReply()\n self.assertTrue(reply.type == MsgType.Reply)\n self.assertTrue(reply.event_type == msg.event_type)\n self.assertTrue(reply.result == MsgResult.Success)\n msg.type = MsgType.Shutdown\n client.sendRequest(msg)\n self.server_thread.join()\n client.close()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/rtfMRI/test_Messaging.py","file_name":"test_Messaging.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"545892605","text":"import numpy as np\nimport struct\nimport random\nfrom tkinter import filedialog\nimport pyttsx3\nimport csv\nimport string\n\n\ndef float_to_byte(sig):\n # float32 -> int16(PCM_16) -> byte\n return float2pcm(sig, dtype='int16').tobytes()\n\n\ndef float2pcm(sig, dtype='int16'):\n \"\"\"Convert floating point signal with a range from -1 to 1 to PCM.\n Any signal values outside the interval [-1.0, 1.0) are clipped.\n No dithering is used.\n Note that there are different possibilities for scaling floating\n point numbers to PCM numbers, this function implements just one of\n them. For an overview of alternatives see\n http://blog.bjornroche.com/2009/12/int-float-int-its-jungle-out-there.html\n Parameters\n ----------\n sig : array_like\n Input array, must have floating point type.\n dtype : data type, optional\n Desired (integer) data type.\n Returns\n -------\n numpy.ndarray\n Integer data, scaled and clipped to the range of the given\n *dtype*.\n See Also\n --------\n pcm2float, dtype\n \"\"\"\n sig = np.asarray(sig)\n if sig.dtype.kind != 'f':\n raise TypeError(\"'sig' must be a float array\")\n dtype = np.dtype(dtype)\n if dtype.kind not in 'iu':\n raise TypeError(\"'dtype' must be an integer type\")\n\n i = np.iinfo(dtype)\n abs_max = 2 ** (i.bits - 1)\n offset = i.min + abs_max\n return (sig * abs_max + offset).clip(i.min, i.max).astype(dtype)\n\n\ndef floatArraytoPCM(toConvert):\n samples = [sample * 32767\n for sample in toConvert]\n return struct.pack(\"<%dh\" % len(samples), *samples)\n\n\ndef getAudioPath():\n fileName = filedialog.askopenfilename(filetypes=((\"Audio Files\", \".wav .ogg\"), (\"All files\", \"*.*\")))\n return fileName\n\n\ndef randomColors(numSpeakers):\n distinctColors = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231',\n '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe',\n '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000',\n '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080',\n '#000000']\n random.shuffle(distinctColors)\n return distinctColors[0:numSpeakers]\n\n\n# enables audio notifications\ndef verbalSuggestions(cues, isMale=False, rate=146):\n if isMale:\n isMale = 0\n else:\n isMale = 1\n engine = pyttsx3.init()\n voices = engine.getProperty('voices')\n engine.setProperty('rate', rate)\n engine.setProperty('voice', voices[isMale].id)\n for cue in cues:\n # que cue\n engine.say(cue)\n engine.runAndWait()\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"517310229","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018 CERN.\n# Copyright (C) 2018 RERO.\n#\n# Invenio-Circulation is free software; you can redistribute it and/or modify\n# it under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Tests for loan states.\"\"\"\n\nfrom datetime import timedelta\n\nimport mock\nimport pytest\nfrom flask import current_app\nfrom helpers import SwappedConfig, SwappedNestedConfig\n\nfrom invenio_circulation.api import Loan, is_item_available\nfrom invenio_circulation.errors import ItemNotAvailable, \\\n NoValidTransitionAvailable, TransitionConstraintsViolation\nfrom invenio_circulation.proxies import current_circulation\nfrom invenio_circulation.search import LoansSearch\nfrom invenio_circulation.utils import parse_date\n\n\n@mock.patch(\n 'invenio_circulation.transitions.transitions'\n '.get_pending_loans_by_doc_pid'\n)\ndef test_loan_checkout_checkin(mock_pending_loans_for_document, loan_created,\n db, params, mock_is_item_available):\n \"\"\"Test loan checkout and checkin actions.\"\"\"\n mock_pending_loans_for_document.return_value = []\n assert loan_created['state'] == 'CREATED'\n\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='checkout')\n )\n db.session.commit()\n assert loan['state'] == 'ITEM_ON_LOAN'\n\n # set same transaction location to avoid \"in transit\"\n same_location = params['transaction_location_pid']\n with SwappedConfig('CIRCULATION_ITEM_LOCATION_RETRIEVER',\n lambda x: same_location):\n loan = current_circulation.circulation.trigger(loan, **dict(params))\n db.session.commit()\n assert loan['state'] == 'ITEM_RETURNED'\n\n\ndef test_loan_request(loan_created, db, params):\n \"\"\"Test loan request action.\"\"\"\n assert loan_created['state'] == 'CREATED'\n\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n trigger='request',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert loan['state'] == 'PENDING'\n\n\ndef test_loan_extend(loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test loan extend action.\"\"\"\n\n def get_max_count_1(loan):\n return 1\n\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='checkout')\n )\n db.session.commit()\n end_date = parse_date(loan['end_date'])\n\n loan = current_circulation.circulation.trigger(\n loan, **dict(params, trigger='extend')\n )\n db.session.commit()\n new_end_date = parse_date(loan['end_date'])\n assert new_end_date == end_date + timedelta(days=30)\n assert loan['extension_count'] == 1\n loan = current_circulation.circulation.trigger(\n loan, **dict(params, trigger='extend')\n )\n db.session.commit()\n\n # test to manny extensions\n current_app.config['CIRCULATION_POLICIES']['extension'][\n 'max_count'] = get_max_count_1\n with pytest.raises(TransitionConstraintsViolation):\n loan = current_circulation.circulation.trigger(\n loan, **dict(params, trigger='extend')\n )\n\n\ndef test_loan_extend_from_enddate(loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test loan extend action from transaction date.\"\"\"\n\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='checkout')\n )\n db.session.commit()\n extension_date = parse_date(loan.get('transaction_date'))\n current_app.config['CIRCULATION_POLICIES']['extension'][\n 'from_end_date'] = False\n\n loan = current_circulation.circulation.trigger(\n loan, **dict(params, trigger='extend')\n )\n db.session.commit()\n new_end_date = parse_date(loan['end_date'])\n assert new_end_date == extension_date + timedelta(days=30)\n assert loan['extension_count'] == 1\n\n\ndef test_cancel_action(loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test should pass when calling `cancel` from `ITEM_ON_LOAN`.\"\"\"\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='checkout')\n )\n db.session.commit()\n\n current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='cancel')\n )\n assert loan['state'] == 'CANCELLED'\n\n\ndef test_cancel_fail(loan_created, params):\n \"\"\"Test should fail when calling `cancel` from `CREATED`.\"\"\"\n with pytest.raises(NoValidTransitionAvailable):\n current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='cancel')\n )\n\n\ndef test_validate_item_in_transit_for_pickup(loan_created, db, params):\n \"\"\".\"\"\"\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n trigger='request',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert loan['state'] == 'PENDING'\n\n with SwappedConfig('CIRCULATION_ITEM_LOCATION_RETRIEVER',\n lambda x: 'external_location_pid'):\n loan = current_circulation.circulation.trigger(loan,\n **dict(params))\n assert loan['state'] == 'ITEM_IN_TRANSIT_FOR_PICKUP'\n\n\ndef test_validate_item_at_desk(loan_created, db, params):\n \"\"\".\"\"\"\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n trigger='request',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert loan['state'] == 'PENDING'\n\n with SwappedConfig('CIRCULATION_ITEM_LOCATION_RETRIEVER',\n lambda x: 'pickup_location_pid'):\n loan = current_circulation.circulation.trigger(loan_created,\n **dict(params))\n assert loan['state'] == 'ITEM_AT_DESK'\n\n\ndef test_checkout_start_is_transaction_date(loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test checkout start date to transaction date when not set.\"\"\"\n number_of_days = 10\n\n with SwappedNestedConfig(\n ['CIRCULATION_POLICIES', 'checkout', 'duration_default'],\n lambda x: number_of_days):\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='checkout')\n )\n db.session.commit()\n\n assert loan['state'] == 'ITEM_ON_LOAN'\n assert loan['start_date'] == loan['transaction_date']\n start_date = parse_date(loan['start_date'])\n end_date = start_date + timedelta(number_of_days)\n assert loan['end_date'] == end_date.isoformat()\n\n\ndef test_checkout_with_input_start_end_dates(loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test checkout start and end dates are set as input.\"\"\"\n start_date = '2018-02-01T09:30:00+02:00'\n end_date = '2018-02-10T09:30:00+02:00'\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n start_date=start_date,\n end_date=end_date,\n trigger='checkout')\n )\n db.session.commit()\n assert loan['state'] == 'ITEM_ON_LOAN'\n assert loan['start_date'] == start_date\n assert loan['end_date'] == end_date\n\n\ndef test_checkout_fails_when_wrong_dates(loan_created, params,\n mock_is_item_available):\n \"\"\"Test checkout fails when wrong input dates.\"\"\"\n with pytest.raises(ValueError):\n current_circulation.circulation.trigger(\n loan_created, **dict(params,\n start_date='2018-xx',\n end_date='2018-xx',\n trigger='checkout')\n )\n\n\ndef test_checkout_fails_when_duration_invalid(loan_created, params,\n mock_is_item_available):\n \"\"\"Test checkout fails when wrong max duration.\"\"\"\n with pytest.raises(TransitionConstraintsViolation):\n with SwappedNestedConfig(\n ['CIRCULATION_POLICIES', 'checkout', 'duration_validate'],\n lambda x: False):\n current_circulation.circulation.trigger(\n loan_created, **dict(params,\n start_date='2018-02-01T09:30:00+02:00',\n end_date='2018-04-10T09:30:00+02:00',\n trigger='checkout')\n )\n\n\n@mock.patch(\n 'invenio_circulation.transitions.transitions'\n '.get_pending_loans_by_doc_pid'\n)\ndef test_checkin_end_date_is_transaction_date(mock_pending_loans_for_document,\n loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test date the checkin date is the transaction date.\"\"\"\n mock_pending_loans_for_document.return_value = []\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n start_date='2018-02-01T09:30:00+02:00',\n end_date='2018-02-10T09:30:00+02:00',\n trigger='checkout')\n )\n db.session.commit()\n assert loan['state'] == 'ITEM_ON_LOAN'\n\n same_location = params['transaction_location_pid']\n with SwappedConfig('CIRCULATION_ITEM_LOCATION_RETRIEVER',\n lambda x: same_location):\n params['transaction_date'] = '2018-03-11T19:15:00+02:00'\n loan = current_circulation.circulation.trigger(loan, **dict(params))\n assert loan['state'] == 'ITEM_RETURNED'\n assert loan['end_date'] == params['transaction_date']\n\n\ndef test_search_loans_by_pid(indexed_loans):\n \"\"\"Test retrieve loan list given belonging to an item.\"\"\"\n loans = list(LoansSearch.search_loans_by_pid(item_pid='item_pending_1'))\n assert loans\n assert len(loans) == 1\n loan = Loan.get_record_by_pid(loans[0]['loanid'])\n assert loan.get('item_pid') == 'item_pending_1'\n\n loans = list(\n LoansSearch.search_loans_by_pid(\n item_pid='item_multiple_pending_on_loan_7',\n exclude_states=['ITEM_ON_LOAN'],\n )\n )\n assert len(loans) == 2\n\n\ndef test_item_availibility(indexed_loans):\n \"\"\"Test item_availibility with various conditions.\"\"\"\n assert not is_item_available(item_pid='item_pending_1')\n assert not is_item_available(item_pid='item_on_loan_2')\n assert is_item_available(item_pid='item_returned_3')\n assert not is_item_available(item_pid='item_in_transit_4')\n assert not is_item_available(item_pid='item_at_desk_5')\n assert not is_item_available(item_pid='item_pending_on_loan_6')\n assert is_item_available(item_pid='item_returned_6')\n assert is_item_available(item_pid='no_loan')\n\n\ndef test_checkout_on_unavailable_item(loan_created, db, params,\n mock_is_item_available):\n \"\"\"Test checkout fails on unvailable item.\"\"\"\n mock_is_item_available.return_value = False\n\n with pytest.raises(ItemNotAvailable):\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params, trigger='checkout')\n )\n\n loan_created['state'] = 'ITEM_AT_DESK'\n\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params)\n )\n\n\n@mock.patch('invenio_circulation.api.is_item_available')\ndef test_request_on_document_with_available_items(mock_available_item,\n loan_created, db, params):\n \"\"\"Test loan request action.\"\"\"\n mock_available_item.return_value = True\n with SwappedConfig('CIRCULATION_ITEMS_RETRIEVER_FROM_DOCUMENT',\n lambda x: ['item_pid']):\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n trigger='request',\n item_pid=None,\n document_pid='document_pid',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert loan['state'] == 'PENDING'\n assert loan['item_pid'] == 'item_pid'\n assert loan['document_pid'] == 'document_pid'\n\n\n@mock.patch('invenio_circulation.api.is_item_available')\ndef test_request_on_document_with_unavailable_items(mock_available_item,\n loan_created, db, params):\n \"\"\"Test loan request action.\"\"\"\n mock_available_item.return_value = False\n with SwappedConfig('CIRCULATION_ITEMS_RETRIEVER_FROM_DOCUMENT',\n lambda x: ['item_pid']):\n # remove item_pid\n params.pop('item_pid')\n loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n trigger='request',\n document_pid='document_pid',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert loan['state'] == 'PENDING'\n assert 'item_pid' not in loan\n assert loan['document_pid'] == 'document_pid'\n\n\n@mock.patch(\n 'invenio_circulation.transitions.transitions'\n '.get_pending_loans_by_doc_pid'\n)\n@mock.patch('invenio_circulation.api.is_item_available')\ndef test_document_requests_on_item_returned(mock_available_item,\n mock_pending_loans_for_document,\n mock_is_item_available,\n loan_created, db, params):\n \"\"\"Test loan request action.\"\"\"\n\n # return item is not available\n mock_available_item.return_value = False\n\n with SwappedConfig('CIRCULATION_DOCUMENT_RETRIEVER_FROM_ITEM',\n lambda x: 'document_pid'):\n same_location = params['transaction_location_pid']\n with SwappedConfig('CIRCULATION_ITEM_LOCATION_RETRIEVER',\n lambda x: same_location):\n # start a loan on item with pid 'item_pid'\n new_loan = current_circulation.circulation.trigger(\n loan_created, **dict(params,\n trigger='checkout',\n item_pid='item_pid',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert new_loan['state'] == 'ITEM_ON_LOAN'\n\n # create a new loan request on document_pid without items available\n new_loan_created = Loan.create({})\n # remove item_pid\n params.pop('item_pid')\n pending_loan = current_circulation.circulation.trigger(\n new_loan_created,\n **dict(params, trigger='request',\n document_pid='document_pid',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert pending_loan['state'] == 'PENDING'\n # no item available found. Request is created with no item attached\n assert 'item_pid' not in pending_loan\n assert pending_loan['document_pid'] == 'document_pid'\n\n # resolve pending document requests to `document_pid`\n mock_pending_loans_for_document.return_value = [pending_loan]\n\n returned_loan = current_circulation.circulation.trigger(\n new_loan, **dict(params,\n item_pid='item_pid',\n pickup_location_pid='pickup_location_pid')\n )\n db.session.commit()\n assert returned_loan['state'] == 'ITEM_RETURNED'\n\n # item `item_pid` has been attached to pending loan request on\n # `document_pid` automatically\n assert pending_loan['state'] == 'PENDING'\n assert pending_loan['item_pid'] == 'item_pid'\n assert pending_loan['document_pid'] == 'document_pid'\n","sub_path":"tests/test_loan_transitions.py","file_name":"test_loan_transitions.py","file_ext":"py","file_size_in_byte":16290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"212623522","text":"from bpy.types import Node\nfrom arm.logicnode.arm_nodes import *\nimport arm.nodes_logic\n\nclass TestNode(Node, ArmLogicTreeNode):\n '''Test node'''\n bl_idname = 'LNTestNode'\n bl_label = 'Test'\n bl_icon = 'QUESTION'\n\n def init(self, context):\n self.inputs.new('ArmNodeSocketAction', 'In')\n self.outputs.new('ArmNodeSocketAction', 'Out')\n \nclass RotateVectorAroundAxisNode(Node, ArmLogicTreeNode):\n '''Rotate object around axis node'''\n bl_idname = 'LNRotateVectorAroundAxisNode'\n bl_label = 'Rotate Vector Around Axis'\n bl_icon = 'QUESTION'\n\n def init(self, context):\n self.inputs.new('NodeSocketVector', 'Vector')\n self.inputs.new('NodeSocketVector', 'Axis')\n self.inputs[-1].default_value = [0, 0, 1]\n self.inputs.new('NodeSocketFloat', 'Angle')\n self.outputs.new('NodeSocketVector', 'Euler Angles')\n self.outputs.new('NodeSocketVector', 'Vector')\n self.outputs.new('NodeSocketVector', 'Quaternion XYZ')\n\nclass RotateVector(Node, ArmLogicTreeNode):\n '''Rotate object around axis node'''\n bl_idname = 'LNRotateVector'\n bl_label = 'Rotate Vector'\n bl_icon = 'QUESTION'\n\n def init(self, context):\n self.inputs.new('NodeSocketVector', 'Vector')\n self.inputs.new('NodeSocketVector', 'Quaternion XYZ')\n self.inputs.new('NodeSocketFloat', 'Quaternion W')\n self.outputs.new('NodeSocketVector', 'Vector')\n \nclass VectorAngles2D(Node, ArmLogicTreeNode):\n '''Rotate object around axis node'''\n bl_idname = 'LNVectorAngles2D'\n bl_label = 'Vector Angles 2D XY'\n bl_icon = 'QUESTION'\n\n def init(self, context):\n self.inputs.new('NodeSocketVector', 'Vector 1')\n self.inputs.new('NodeSocketVector', 'Vector 2')\n self.outputs.new('NodeSocketFloat', 'Angle Rad')\n self.outputs.new('NodeSocketFloat', 'Angle Deg')\n\n\nclass ReflectVector(Node, ArmLogicTreeNode):\n '''Rotate object around axis node'''\n bl_idname = 'LNReflectVector'\n bl_label = 'Reflect Vector at Axis'\n bl_icon = 'QUESTION'\n\n def init(self, context):\n self.inputs.new('NodeSocketVector', 'Vector')\n self.inputs.new('NodeSocketVector', 'Axis')\n self.inputs[-1].default_value = [0, 0, 1]\n self.outputs.new('NodeSocketVector', 'Euler Angles')\n self.outputs.new('NodeSocketVector', 'Vector')\n self.outputs.new('NodeSocketVector', 'Quaternion XYZ')\n\nclass EulerToDirectionalVector(Node, ArmLogicTreeNode):\n '''Rotate object around axis node'''\n bl_idname = 'LNEulerToDirectionalVector'\n bl_label = 'Euler Angles to directional Vector'\n bl_icon = 'QUESTION'\n\n def init(self, context):\n self.inputs.new('NodeSocketVector', 'Euler Angles')\n self.outputs.new('NodeSocketVector', 'Vector')\n\nclass ArrayGetIndexNode(Node, ArmLogicTreeNode):\n '''Rotate object around axis node'''\n bl_idname = 'LNArrayGetIndexNode'\n bl_label = 'Array Get Index'\n bl_icon = 'QUESTION'\n\n def init(self, context): \n self.inputs.new('ArmNodeSocketArray', 'Array')\n self.inputs.new('NodeSocketShader', 'Value')\n self.outputs.new('NodeSocketInt', 'Index')\n\nclass CalculateBeamPositions(Node,ArmLogicTreeNode):\n \"\"\n bl_idname = \"LNCalculateBeamPositions\"\n bl_label = \"Calculate Beam Positions\"\n bl_icon = \"QUESTION\"\n\n def init(self,context):\n self.inputs.new('ArmNodeSocketAction', 'In')\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Positions\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Directions\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Sources\")\n self.inputs.new(\"ArmNodeSocketObject\", \"Source Object\")\n self.inputs.new(\"NodeSocketString\", \"Trait Property Name\")\n self.inputs.new(\"NodeSocketString\", \"Direction Function Name\")\n self.inputs.new('NodeSocketInt', 'Interactive Filter Mask')\n self.inputs.new('NodeSocketInt', 'Max Numner of Beam Segments')\n\n self.outputs.new('ArmNodeSocketAction', 'Out')\n self.outputs.new(\"ArmNodeSocketArray\",\"Array Beam Positions\")\n self.outputs.new(\"ArmNodeSocketArray\",\"Array Beam Directions\")\n self.outputs.new(\"ArmNodeSocketArray\",\"Array Beam Sources\")\n self.outputs.new(\"NodeSocketBool\", \"Beam Blocked\")\n\nclass SpawnBeams(Node,ArmLogicTreeNode):\n \"\"\n bl_idname = \"LNSpawnBeams\"\n bl_label = \"Spawn Beams\"\n bl_icon = \"QUESTION\"\n\n def init(self,context):\n self.inputs.new('ArmNodeSocketAction', 'In')\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Positions\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Directions\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Sources\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Objects\")\n self.inputs.new(\"NodeSocketString\", \"Beam Object Name\")\n self.inputs.new(\"NodeSocketString\", \"Array Name Beam SubObject\")\n self.inputs.new(\"NodeSocketString\", \"Component Trait Property Name\")\n self.inputs.new(\"NodeSocketString\", \"GetProperties Function Name\")\n self.inputs.new(\"NodeSocketBool\", \"Beam Blocked\")\n self.inputs.new(\"NodeSocketFloat\", \"Beam Diameter\")\n\n self.outputs.new('ArmNodeSocketAction', 'Out')\n self.outputs.new(\"ArmNodeSocketArray\",\"Array Beam Objects\")\n\nclass DespawnBeams(Node,ArmLogicTreeNode):\n \"\"\n bl_idname = \"LNDespawnBeams\"\n bl_label = \"Despawn Beams\"\n bl_icon = \"QUESTION\"\n\n def init(self,context):\n self.inputs.new('ArmNodeSocketAction', 'In')\n self.inputs.new(\"ArmNodeSocketArray\",\"Beam Objects Array\")\n self.inputs.new(\"NodeSocketString\", \"Array Name Beam SubObject\")\n\n self.outputs.new('ArmNodeSocketAction', 'Out') \n\nclass SpawnDespawnPol(Node,ArmLogicTreeNode):\n \"\"\n bl_idname = \"LNSpawnDespawnPol\"\n bl_label = \"Spawn and Despawn Polarization Arrows\"\n bl_icon = \"QUESTION\"\n\n def init(self,context):\n self.inputs.new('ArmNodeSocketAction', 'In')\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Positions\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Directions\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array Beam Objects\")\n self.inputs.new(\"ArmNodeSocketArray\",\"Array All Arrows\")\n self.inputs.new(\"NodeSocketString\", \"Arrow Object Name\")\n self.inputs.new(\"NodeSocketString\", \"Array Name Beam SubObject\")\n self.inputs.new(\"NodeSocketFloat\", \"Arrow Diameter\")\n self.inputs.new(\"NodeSocketFloat\", \"Arrow Length\")\n self.inputs.new(\"NodeSocketFloat\", \"Arrow Distance\")\n self.inputs.new(\"NodeSocketInt\", \"Max Arrow Number\")\n self.inputs.new(\"NodeSocketBool\", \"Polarization On\")\n\n self.outputs.new('ArmNodeSocketAction', 'Out') \n\n\n\ndef register():\n add_node(RotateVectorAroundAxisNode, category='Action') \n add_node(ReflectVector, category='Action') \n add_node(TestNode, category='Action')\n add_node(EulerToDirectionalVector, category='Action')\n add_node(RotateVector, category='Action') \n add_node(VectorAngles2D, category='Action')\n add_node(ArrayGetIndexNode, category='Array')\n\n add_node(CalculateBeamPositions, category=\"Action\") \n add_node(SpawnBeams, category=\"Action\") \n add_node(SpawnDespawnPol, category=\"Action\") \n add_node(DespawnBeams, category=\"Action\")\n\n arm.nodes_logic.register_nodes()\n ","sub_path":"MainScene_v1/Libraries/mynodes/blender.py","file_name":"blender.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"163654971","text":"import cv2\nfrom calHistogram import compute_histogram\nfrom tracking import tracking_by_my_meanshift\nfrom mean_shift_by_CV import get_img_hist, find_new_roi_window\nimport build_bin as bi\n\n\ndef main(video_path):\n cap = cv2.VideoCapture(video_path)\n count = 0\n Total_Frame_Number = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n roi_flag = 0\n\n while count < Total_Frame_Number:\n count += 1\n ret, img = cap.read()\n k = cv2.waitKey(20)\n if k == ord('q'):\n break\n if k == 32: # pause when press SPACE\n cv2.waitKey(0)\n if k == ord('a'):\n # set up the ROI for tracking when press A\n roi_window = cv2.selectROI('ROI', img, fromCenter=False)\n x, y, w, h = roi_window\n print('roi: ', roi_window)\n roi = img[y:y + h, x:x + w]\n roi_hist = get_img_hist(roi)\n\n roi_flag = 1\n\n cv2.imshow(\"roi_img\", roi)\n cv2.waitKey(0)\n cv2.destroyWindow('roi_img')\n cv2.destroyWindow('ROI')\n\n if roi_flag:\n roi_window = find_new_roi_window(roi_hist, roi_window, img)\n # roi_window = tracking_by_my_meanshift(roi, roi_window, img)\n\n # 将roi区域画出来\n x, y, w, h = roi_window\n img = cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)\n\n # 当前帧数\n cv2.putText(img, str(count), (40, 40), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 1, cv2.LINE_AA)\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n cv2.imshow('Video', img)\n\n cv2.destroyAllWindows()\n cap.release()\n\n\nif __name__ == \"__main__\":\n main('data/video2.mp4')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"555969380","text":"\"\"\"\n Description:\n This module helps to implement primitive load balancing\n by returning a list of running schedds and the total\n number of running jobs per schedd\n\n\n Project:\n JobSub\n\n Author:\n Dennis Box\n\n\"\"\"\nimport cherrypy\nimport logger\nimport logging\nimport sys\nfrom condor_commands import ui_condor_status_totalrunningjobs\nimport socket\nimport os\n\nfrom format import format_response\n\n\n@cherrypy.popargs('acctgroup')\nclass ScheddLoadResource(object):\n\n def doGET(self, acctgroup, kwargs):\n \"\"\"\n perform http GET\n \"\"\"\n\n if os.environ.get('JOBSUB_TURN_OFF_SCHEDD_BALANCE'):\n hostname = socket.gethostname()\n return {'out': [\"%s 0\" % hostname]}\n else:\n jobs = ui_condor_status_totalrunningjobs(acctgroup=acctgroup,\n check_downtime=True)\n return {'out': jobs.split('\\n')}\n\n @cherrypy.expose\n @format_response\n def index(self, acctgroup=None, **kwargs):\n \"\"\"\n index.html for jobsub/scheddload\n \"\"\"\n\n logger.log('acctgroup=%s, kwargs=%s' % (acctgroup, kwargs))\n try:\n if cherrypy.request.method == 'GET':\n ret_code = self.doGET(acctgroup, kwargs)\n else:\n err = 'Unimplemented method: %s' % cherrypy.request.method\n logger.log(err)\n logger.log(err, severity=logging.ERROR, logfile='error')\n ret_code = {'err': err}\n except:\n err = 'Exception on ScheddLoadResource.index: %s' % sys.exc_info()[\n 1]\n cherrypy.response.status = 500\n logger.log(err, traceback=True)\n logger.log(err,\n traceback=True,\n severity=logging.ERROR,\n logfile='error')\n ret_code = {'err': err}\n\n return ret_code\n","sub_path":"server/webapp/scheddload.py","file_name":"scheddload.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"539252038","text":"'''\nhttps://leetcode.com/problems/keyboard-row/description/\n\nGiven a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.\n\nAmerican keyboard\n----------------\nQWERTYUIOP\nASDFGHJKL\nZXCVBNM\n----------------\n\nExample 1:\nInput: [\"Hello\", \"Alaska\", \"Dad\", \"Peace\"]\nOutput: [\"Alaska\", \"Dad\"]\nNote:\nYou may use one character in the keyboard more than once.\nYou may assume the input string will only contain letters of alphabet.\n'''\n\nclass Solution(object):\n def findWords(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n rlt = []\n rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']\n \n for word in words:\n for row in rows:\n if all(map(lambda x: x in row, word.lower())):\n rlt.append(word)\n \n return rlt\n \n'''\nStefanPochmann's solution:\n\ndef findWords(self, words):\n return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)\n'''\n","sub_path":"500. Keyboard Row.py","file_name":"500. Keyboard Row.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"119374415","text":"#!/usr/bin/python3\n\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nimport time\nfrom subprocess import call\nimport os\nfrom math import *\n\nfolder = \"/home/pi/Display\"\n\nbg_img = folder + \"/bg.png\"\nsteckdosean_image = folder + \"/steckdosean.png\"\nsteckdoseaus_image = folder + \"/steckdoseaus.png\"\nmusikan_image = folder + \"/musikan.png\"\nmusikaus_image = folder + \"/musikaus.png\"\nledan_image = folder + \"/ledan.png\"\nledaus_image = folder + \"/ledaus.png\"\nquit_image = folder + \"/quit.png\"\n\nwindow = 1\n\nmaster = Tk()\nmaster.minsize(width=1360, height=768)\nmaster.maxsize(width=1360, height=768)\n\nimage = Image.open(bg_img)\nimage = image.resize((1360, 768))\nimg = ImageTk.PhotoImage(image)\n\nbackground = Frame(height=768, width=1360, bd=0, relief=RAISED)\nbackground.place(x=0, y=0)\nbg_image = Label(background,image=img).place(x=0, y=0)\n\nmenu_frame = Frame(bg_image, height=900, width=560, bd=0, relief=SUNKEN, bg=\"White\")\nmenu_frame.place(x=400, y=0)\nmenu_frame.lift()\n\ndef steckdosean():\n print(\"Schalte Steckdose an...\")\n call([\"sudo\",\"/home/pi/Display/Rcswitch-pi/send\",\"01011\",\"3\",\"1\"])\n print(\"Steckdose wurde angeschaltet!\")\n\ndef steckdoseaus():\n print(\"Schalte Steckdose aus...\")\n call([\"sudo\",\"/home/pi/Display/Rcswitch-pi/send\",\"01011\",\"3\",\"0\"])\n print(\"Steckdose wurde ausgeschaltet!\")\n\ndef musikan():\n print(\"Schalte Musik an...\")\n call([\"sudo\",\"Python\",\"/home/pi/Display/Python/client.py\",\"musikan\"])\n print(\"Musik wurde angeschaltet!\")\n \ndef musikaus():\n print(\"Schalte Musik aus...\")\n call([\"sudo\",\"Python\",\"/home/pi/Display/Python/client.py\",\"musikaus\"])\n print(\"Musik wurde ausgeschaltet!\")\n\ndef ledan():\n print(\"Schalte LEDs an...\")\n call([\"sudo\",\"/home/pi/Display/RPi_utils/codesend\",\"13\"])\n\ndef ledaus():\n print(\"Schalte LEDs aus...\")\n call([\"sudo\",\"/home/pi/Display/RPi_utils/codesend\",\"10\"])\n\ndef ledaus2():\n call([\"sudo\",\"/home/pi/Display/RPi_utils/codesend\",\"14\"])\n\ndef exit():\n print(\"Exiting Application...\")\n master.destroy()\n\ntime1 = ''\nclock = Label(menu_frame,height=2,width=13,font=('times', '70', 'bold'))\nclock.place(x=0,y=0)\nclock.lift()\n\ndef tick():\n global time1\n time2 = time.strftime(\"%H:%M:%S\")\n if time2 != time1:\n time1 = time2\n clock.config(text=time2)\n clock.after(200,tick)\n\nping = ''\nping_label = Label(master,height=2,width=13,justify=LEFT,font=('times', '50', 'bold'))\nping_label.place(x=845,y=0)\nping_label.lower(belowThis=clock)\n\ndef tick2():\n global ping\n ping = os.popen('sudo ping -c1 google.de | grep rtt | cut -d\"/\" -f5').read()\n ping = ping.split(\".\")[0]\n ping = ping + \" ms\"\n ping_label.config(text=ping)\n ping_label.after(1000,tick2)\n\n\n#Wecker\n#tage = ['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag','Alle']\n#weckerVar = StringVar(master)\n#weckerVar.set(tage[1])\n#combo = Combobox(master,values = tage)\n#combo.place(x=845,y=100)\n\n#weckerAn = Button(master,height=100,width=100,command=weckerOn)\n#weckerAn.place()\n\n#weckerAus = Button(master,height=100,width=100,command=weckerOff)\n#weckerAus.place()\n\nb1_image = Image.open(steckdosean_image)\nb1_img = ImageTk.PhotoImage(b1_image)\n\nb2_image = Image.open(steckdoseaus_image)\nb2_img = ImageTk.PhotoImage(b2_image)\n\nb3_image = Image.open(musikan_image)\nb3_img = ImageTk.PhotoImage(b3_image)\n\nb4_image = Image.open(musikaus_image)\nb4_img = ImageTk.PhotoImage(b4_image)\n\nb5_image = Image.open(ledan_image)\nb5_img = ImageTk.PhotoImage(b5_image)\n\nb6_image = Image.open(ledaus_image)\nb6_img = ImageTk.PhotoImage(b6_image)\n\ncloseb_image = Image.open(quit_image)\ncloseb_img = ImageTk.PhotoImage(closeb_image)\n\n\nb1 = Button(master, image=b1_img, height=100, width=559, command=steckdosean)\nb1.place(x=400, y=200)\n\nb2 = Button(master, image=b2_img, height=100, width=559, command=steckdoseaus)\nb2.place(x=400, y=305)\n\nb3 = Button(master, image=b3_img, height=100, width=559, command=musikan)\nb3.place(x=400, y=410)\n\nb4 = Button(master, image=b4_img, height=100, width=559, command=ledaus2)\nb4.place(x=400, y=515)\n\nb5 = Button(master, image=b5_img, height=200, width=200, command=ledan)\nb5.place(x=0, y=0)\n\nb6 = Button(master, image=b6_img, height=200, width=200, command=ledaus)\nb6.place(x=0, y=210)\n\ncloseb = Button(master, image=closeb_img, height=200, width=200, command=exit)\ncloseb.place(x=0, y=420)\n\nmaster.overrideredirect(1)\ntick2()\ntick()\nmainloop()\n","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"161744307","text":"# pylint: disable=missing-docstring, protected-access\n# type: ignore\n\nimport unittest\nimport sys\nimport os\n\n\nclass ModuleUserTestCase(unittest.TestCase):\n def setUp(self):\n # Unload any previously loaded `exonum_main` modules from other tests:\n loaded_modules = list(sys.modules.keys())\n for module in loaded_modules:\n if module.startswith(\"exonum_modules\"):\n del sys.modules[module]\n\n\nclass PrecompiledModuleUserTestCase(ModuleUserTestCase):\n @classmethod\n def setUpClass(cls):\n # Add a folder with pre-compiled Protobuf messages to the path (so it can be imported):\n sys.path.append(os.path.abspath(\"tests/proto_dir\"))\n\n @classmethod\n def tearDownClass(cls):\n # Remove the Protobuf directory from the path:\n sys.path.remove(os.path.abspath(\"tests/proto_dir\"))\n","sub_path":"tests/module_user.py","file_name":"module_user.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"593788630","text":"\ninfolist=[]\nwith open('data/player.txt','r') as f:\n for i,l in enumerate(f.readlines()):\n temp = l.split('\\t')\n temp[-1] = temp[-1].strip()\n temp[-1] = 'http://'+temp[-1]\n infolist+=[temp]\n# infolist = sorted(infolist,key=lambda i:int(i[2]))\nfor i in xrange(len(infolist)):\n infolist[i] = [i+1]+infolist[i]\n\ncolumn = ['name','official_id','current_ranking','country','peak_ranking','prizemoney','date_of_birth','years','img']\npart = '({})'.format(','.join(column))\nimport sqlite3\nconn = sqlite3.connect(\"db.sqlite3\")\nc = conn.cursor()\n\nfor info in infolist:\n c.execute(\"insert into tenniscrap_player\"+\" values(\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\')\"%tuple(info))\n conn.commit()\nconn.close()\n","sub_path":"sqlite3_write_player.py","file_name":"sqlite3_write_player.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"413576127","text":"import pandas as pd\nimport numpy as np\nimport os\n#from sklearn import preprocessing\n#from sklearn import linear_model\nfrom sklearn.ensemble import RandomForestRegressor\n#from sklearn.tree import DecisionTreeRegressor\n#from sklearn.linear_model import Ridge\nfrom treeinterpreter import treeinterpreter as ti\n#import sklearn as sk\n#import scipy\n#os.chdir('D://pwd/playrix')\nos.chdir('C://pwd/playrix')\n\nproduct_info = pd.read_csv('product_info_advanced.txt', sep = '\\t', header = 0,\\\n dtype = {'cost': np.float64, 'gain_barn/m': np.float64, 'gain_barn': np.float64,\\\n 'grow_time_m_total': np.float64}, decimal = ',')\nproduct_info.set_index('name_en', inplace = True)\n\n#modification of type column\nproduct_info['type'].replace('seed', 0, inplace = True)\nproduct_info['type'].replace('goods', 1, inplace = True)\n\n# Calculate correlations\nx_names = product_info.columns[0:13].tolist()\ncorm = product_info[x_names].corr()[product_info[x_names].corr() >= 0.9]\ncorm[corm == 1] = np.nan\ncorm.dropna(axis = 0, how = 'all', inplace = True)\ncorm.dropna(axis = 1, how = 'all', inplace = True)\n#print(corm)\ncorm.to_csv('correlations.txt', sep = '\\t', decimal = ',')\n\n# Delete correlated features\ndel product_info['exp']\ndel product_info['avg_price_cash_before_in']\ndel product_info['gain_barn']\ndel product_info['price_cash_total']\ndel product_info['avg_price_barn_before_in']\n\n# Set low and top lvl of analysis\nlow_lvl = 29\ntop_lvl = 33\ny_feat = 'refused' + str(low_lvl) + '-' + str(top_lvl)\n# Split product_info dataframe for x_df and y_df\ndf_names = product_info.columns[0:8].tolist()\ndf_names.append(y_feat)\nxy_df = product_info[df_names][product_info['lvl_in'] <= top_lvl]\n\n# Recalculate number of refused goods depending on lvl_in\nxy_df['lvl_count'] = xy_df['lvl_in']\nxy_df['lvl_count'][xy_df['lvl_count'] <= low_lvl] = top_lvl - low_lvl + 1\nxy_df['lvl_count'][xy_df['lvl_count'] > low_lvl] = top_lvl - xy_df['lvl_count'] + 1\nxy_df['lvl_count']\nxy_df[y_feat] = xy_df[y_feat]/xy_df['lvl_count']\ndel xy_df['lvl_count']\n\n#xy_df.drop('shirt', inplace = True)\n\n# Split xy_df for x_df and y_df\ny_df = xy_df[y_feat]\nx_df = xy_df.ix[:, 'type':'gain_barn/m']\n\n# Define names of features\nfeat_names = x_df.columns\n\n# Set x and y nympy arrays for models\ny = y_df.values\nx = x_df.values\n################################################################################\n# RandomForestRegressor\nrf = RandomForestRegressor(n_estimators = 1000)\nrf = rf.fit(x, y)\n\n# R^2\n#print('R^2: ', rf.score(x, y))\n# R^2 adjusted\n#print('R^2 adjusted: ', 1 - (1 - rf.score(x, y))*(y.size - 1)/\\\n# (y.size - x.shape[1] - 1 - 1))\n \n#print(\"Residual sum of squares: %.2f\"\n# % np.mean((rf.predict(x) - y) ** 2))\n\nxy_df['predicted'] = rf.predict(x)\nxy_df['delta'] = xy_df[y_feat] - xy_df['predicted']\n#xy_df = xy_df.sort(columns = y_feat, ascending = False)\n\n#xy_df.to_csv(y_feat + '_predict.txt', sep = '\\t', decimal = ',')\n################################################################################\n# TreeInterpreter\n# Calculate feature importances\nfeat_imp_df = pd.DataFrame(data = rf.feature_importances_, index = feat_names,\\\n columns = ['feature_importances'])\nprediction, bias, contributions = ti.predict(rf, x)\ncontr_df = pd.DataFrame(contributions, index = xy_df.index, columns = feat_names)\nbias_df = pd.DataFrame(bias, index = xy_df.index, columns = ['bias'])\nfeat_stat_df = bias_df.join(contr_df)\nfeat_stat_df = pd.concat([feat_stat_df, feat_imp_df.transpose()])\nfeat_stat_df = feat_stat_df.T.sort(columns = 'feature_importances',\\\n na_position = 'first', ascending = False).T\n#feat_stat_df.to_csv(y_feat + '_feature_statistics.txt', sep = '\\t',\\\n# decimal = ',')\n\nresult = pd.concat([xy_df, feat_stat_df], axis = 1)\nresult = result.sort(columns = y_feat, ascending = False, na_position = 'last')\nresult.columns = [['DataSet', 'DataSet', 'DataSet', 'DataSet', 'DataSet', \\\n 'DataSet', 'DataSet', 'DataSet', 'DataSet', 'DataSet', 'DataSet',\\\n 'Feature_Statistics', 'Feature_Statistics', 'Feature_Statistics',\\\n 'Feature_Statistics', 'Feature_Statistics', 'Feature_Statistics',\\\n 'Feature_Statistics', 'Feature_Statistics', 'Feature_Statisticst'],\\\n result.columns]\nresult.to_csv(y_feat + '_result.txt', sep = '\\t', decimal = ',')\n \n\n#for i in range(len(x)):\n# print \"Instance\", i\n# print \"Bias (trainset mean)\", bias[i]\n# print \"Feature contributions:\"\n# for c, feature in sorted(zip(contributions[i], \n# feat_names), \n# key=lambda t: -abs(t[0])):\n# print feature, round(c, 2)\n# print \"-\"*20 \n\n\n'''\n################################################################################\n# GLM\nglm = linear_model.LinearRegression()\nglm.fit(x, y)\n\n#product_info['predicted'] = glm.predict(x)\n#product_info['delta'] = product_info['refused20-23'] - product_info['predicted']\n\n# The coefficients of GLM\nprint \"The coefficients of GLM:\"\nprint sorted(zip(map(lambda x: round(x, 2), glm.coef_),\\\n feat_names), reverse=True)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((glm.predict(x) - y) ** 2))\n# R^2\nglm.score(x, y)\n# R^2 adjusted\nprint('R^2 adjusted: ', 1 - (1 - glm.score(x, y))*(y.size - 1)/\\\n (y.size - x.shape[1] - 1 - 1))\n\nproduct_info.to_csv('product_info_20_23_out.txt', sep = '\\t', decimal = ',')\n\n################################################################################\n# RidgeRegression\n\nrr = Ridge(alpha=2.0)\nrr.fit(x, y) \n\n# The coefficients of RR\nprint \"The coefficients of RR:\"\nprint sorted(zip(map(lambda x: round(x, 2), rr.coef_),\\\n feat_names), reverse=True)\n# R^2\nrr.score(x, y)\n# R^2 adjusted\nprint('R^2 adjusted: ', 1 - (1 - rr.score(x, y))*(y.size - 1)/\\\n (y.size - x.shape[1] - 1 - 1))\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((rr.predict(x) - y) ** 2))\n\n################################################################################\n# LassoRegression\n\nlr = linear_model.Lasso(alpha=3.00)\nlr.fit(x, y) \n\n# The coefficients of LR\nprint \"The coefficients of LR:\"\nprint sorted(zip(map(lambda x: round(x, 2), lr.coef_),\\\n feat_names), reverse=True)\nlr.intercept_\n# R^2\nlr.score(x, y)\n# R^2 adjusted\nprint('R^2 adjusted: ', 1 - (1 - lr.score(x, y))*(y.size - 1)/\\\n (y.size - x.shape[1] - 1 - 1))\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((lr.predict(x) - y) ** 2))\n'''","sub_path":"refused_analysis.py","file_name":"refused_analysis.py","file_ext":"py","file_size_in_byte":6408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"653407083","text":"from untwisted.network import core, xmap, READ\nfrom untwisted.mode import Mode\nfrom head import send_cmd\n\nclass Stdout(file, Mode):\n def __init__(self):\n file.__init__(self, '/dev/stdout', 'r')\n Mode.__init__(self)\n core.gear.register(self)\n\n def destroy(self):\n core.gear.unregister(self)\n self.base.clear()\n\ndef install(con):\n stdout = Stdout()\n xmap(stdout, READ, prompt, con)\n\ndef prompt(stdout, con):\n #It means you want to input some data\n #It will wait until you input your actual data\n stdout.readline()\n\n #Draw the prompt\n print('->')\n data = stdout.readline()\n # I have to strip the '\\n' cause send_cmd appends '\\r\\n' to it.\n # Otherwise some commands might get messed.\n data = data.rstrip('\\n')\n print('<-')\n\n send_cmd(con, data)\n\n\n\n\n\n","sub_path":"ficsbot-code/plugins/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"447733351","text":"'''\r\nCreated on Apr 10, 2017\r\nEnter the sudoku entries in the grid found in the initialize() function. Undefined behaviour in the case of invalid input\r\n@author: David\r\n'''\r\nimport numpy as np\r\nimport time\r\n\r\ndef initialize():\r\n '''declare and initialize the Sudoku puzzle input, with blanks in the grid represented as 0's'''\r\n puzzle = np.zeros((9,9),dtype = int)\r\n puzzle[0,:] = [0,0,5,3,0,0,0,0,0]\r\n puzzle[1,:] = [8,0,0,0,0,0,0,2,0]\r\n puzzle[2,:] = [0,7,0,0,1,0,5,0,0]\r\n puzzle[3,:] = [4,0,0,0,0,5,3,0,0]\r\n puzzle[4,:] = [0,1,0,0,7,0,0,0,6]\r\n puzzle[5,:] = [0,0,3,2,0,0,0,8,0]\r\n puzzle[6,:] = [0,6,0,5,0,0,0,0,9]\r\n puzzle[7,:] = [0,0,4,0,0,0,0,3,0]\r\n puzzle[8,:] = [0,0,0,0,0,9,7,0,0]\r\n '''declare and initialize 3D boolean matrix of possible values for each grid slot'''\r\n puzzPoss = np.ones((9,9,9),dtype = bool)\r\n zers = np.equal(puzzle,np.zeros((9,9),dtype = int))\r\n for numIdx in range(9):\r\n puzzPoss[:,:,numIdx] = np.logical_or(zers,np.equal(puzzle, (numIdx+1)*np.ones((9,9),dtype = int)))\r\n return puzzPoss\r\n\r\ndef checkRowColSq(puzzPoss):\r\n '''update puzzPoss based on row, col and square constraints'''\r\n updates = True\r\n while(updates):\r\n initSum = puzzPoss.sum() # tracks whether puzzPoss changes or not\r\n '''if there is a slot in a row/col/square with a certain number, then none of the other slots in\r\n that same row/col/square can have the same number, so we update puzzPoss based on this observation'''\r\n for outRowIdx in range(9):\r\n for outColIdx in range(9):\r\n if puzzPoss[outRowIdx,outColIdx,:].sum() == 1:\r\n numIdx = np.where(puzzPoss[outRowIdx,outColIdx,:] == True)[0][0]\r\n # update row\r\n puzzPoss[outRowIdx,:,numIdx] = np.zeros(9,dtype = bool)\r\n puzzPoss[outRowIdx,outColIdx,numIdx] = True\r\n # update col\r\n puzzPoss[:,outColIdx,numIdx] = np.zeros(9,dtype = bool)\r\n puzzPoss[outRowIdx,outColIdx,numIdx] = True\r\n # determine which square [outRowIdx,outColIdx] is in\r\n sqRow = (outRowIdx > 2) + (outRowIdx > 5)\r\n sqCol = (outColIdx > 2) + (outColIdx > 5)\r\n # update square\r\n puzzPoss[3*sqRow:3*sqRow+3,3*sqCol:3*sqCol+3,numIdx] = np.zeros((3,3),dtype = bool)\r\n puzzPoss[outRowIdx,outColIdx,numIdx] = True\r\n \r\n '''if a row/col/square has only one slot which could possibly contain a certain number, then\r\n that slot must contain that number, so we update puzzPoss based on this observation'''\r\n for numIdx in range(9):\r\n # update rows\r\n for rowIdx in range(9):\r\n if puzzPoss[rowIdx,:,numIdx].sum() == 1:\r\n colIdx = np.where(puzzPoss[rowIdx,:,numIdx] == True)[0][0]\r\n puzzPoss[rowIdx,colIdx,:] = np.zeros(9,dtype = bool)\r\n puzzPoss[rowIdx,colIdx,numIdx] = True\r\n # update cols\r\n for colIdx in range(9):\r\n if puzzPoss[:,colIdx,numIdx].sum() == 1:\r\n rowIdx = np.where(puzzPoss[:,colIdx,numIdx] == True)[0][0]\r\n puzzPoss[rowIdx,colIdx,:] = np.zeros(9,dtype = bool)\r\n puzzPoss[rowIdx,colIdx,numIdx] = True\r\n # update squares\r\n for sqRow in range(3):\r\n for sqCol in range(3):\r\n if puzzPoss[3*sqRow:3*sqRow+3,3*sqCol:3*sqCol+3, numIdx].sum() == 1:\r\n [rowIdx,colIdx] = np.where(puzzPoss[3*sqRow:3*sqRow+3, 3*sqCol:3*sqCol+3,numIdx] == True)\r\n puzzPoss[3*sqRow:3*sqRow+3,3*sqCol:3*sqCol+3,numIdx] = np.zeros((3,3),dtype = bool)\r\n puzzPoss[3*sqRow+rowIdx,3*sqCol+colIdx,numIdx] = True\r\n updates = puzzPoss.sum() != initSum\r\n return puzzPoss\r\n\r\ndef solveSudoku():\r\n '''solve the sudoku puzzle specified in initializeSudoku()'''\r\n puzzPoss = checkRowColSq(initialize())\r\n puzzle = guess(puzzPoss)\r\n print(puzzle)\r\n return\r\n\r\ndef guess(puzzPoss):\r\n '''iteratively make and retract guesses as needed to solve the puzzle\r\n post: returns all 0's if puzzle is unsolvable'''\r\n # initialize variables\r\n possSums = np.sum(puzzPoss,axis=2) # number of possibilities for each slot\r\n appliedGuesses = list() # stack of guesses that have already been applied\r\n rowIdx = 0\r\n colIdx = 0\r\n for numIdx in range(2,10): # prioritize guessing highly constrained slots\r\n if numIdx in possSums:\r\n [rowIdx,colIdx] = np.argwhere(possSums == numIdx)[0] # slot to guess\r\n break\r\n guessNum = np.where(puzzPoss[rowIdx,colIdx,:] == True)[0][0] # num to guess\r\n preChanges = np.zeros((9,9,9),dtype = bool)\r\n solved = (possSums == np.ones((9,9),dtype = int)).all()\r\n guessChanges = np.zeros((9,9,9),dtype = bool) # changes resulting from guess\r\n \r\n while not solved:\r\n np.copyto(preChanges,puzzPoss)\r\n # try out the guess\r\n puzzPoss[rowIdx,colIdx,:] = np.zeros(9,dtype = bool)\r\n puzzPoss[rowIdx,colIdx,guessNum] = True\r\n checkRowColSq(puzzPoss)\r\n \r\n possSums = np.sum(puzzPoss,axis=2) \r\n \r\n # check if the guess is valid or not\r\n if not 0 in possSums:\r\n solved = (possSums == np.ones((9,9),dtype = int)).all()\r\n # prep all variables for the next guess to be made\r\n appliedGuesses.append([rowIdx,colIdx,guessNum, np.not_equal(preChanges,puzzPoss)])\r\n for numIdx in range(2,10):\r\n if numIdx in possSums:\r\n [rowIdx,colIdx] = np.argwhere(possSums == numIdx)[0]\r\n break\r\n guessNum = np.where(puzzPoss[rowIdx,colIdx,:] == True)[0][0]\r\n else:\r\n found = False # have not yet found the next guess to make\r\n np.copyto(puzzPoss,preChanges) # undo changes made by wrong guess\r\n possSums = np.sum(puzzPoss,axis=2)\r\n while not found:\r\n prevGuessNum = guessNum\r\n # determine if we can use the next guessNum in the same slot\r\n guessNum += 1\r\n while guessNum < 9:\r\n if puzzPoss[rowIdx,colIdx,guessNum] == True:\r\n break\r\n guessNum += 1\r\n # if we can use guessNum in the same slot, we do so\r\n if guessNum < 9:\r\n if not appliedGuesses:\r\n puzzPoss[rowIdx,colIdx,prevGuessNum] = False\r\n puzzPoss = checkRowColSq(puzzPoss)\r\n possSums = np.sum(puzzPoss,axis=2)\r\n solved = (possSums == np.ones((9,9),dtype = int)).all()\r\n found = True\r\n #if we cannot, we undo the previous guess and keep looking\r\n else:\r\n if not appliedGuesses:\r\n return np.zeros((9,9,9),dtype = bool) # unsolvable\r\n [rowIdx,colIdx,guessNum,guessChanges] = appliedGuesses.pop()\r\n puzzPoss = np.logical_or(guessChanges,puzzPoss)\r\n possSums = np.sum(puzzPoss,axis=2)\r\n '''generate solved sudoku from puzzPoss'''\r\n puzzle = np.zeros((9,9),dtype = int)\r\n for numIdx in range(9):\r\n puzzle = np.add(puzzle,(numIdx+1)*puzzPoss[:,:,numIdx])\r\n return puzzle\r\n\r\nt0 = time.time()\r\nsolveSudoku()\r\nprint(time.time()-t0)\r\n","sub_path":"SudokuSolver.py","file_name":"SudokuSolver.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"648919315","text":"import operator as op\nimport pytest\n\nfrom itertools import permutations\n\nfrom sweetpea import factor, derived_level, else_level, within_trial, at_most_k_in_a_row, transition\nfrom sweetpea import fully_cross_block, synthesize_trials_non_uniform\n\n\ncongruency = factor(\"congruency\", [\"congruent\", \"incongruent\", \"neutral\"])\ncongruency_transition = factor(\"congruency_transition\", [\n derived_level(\"con-con\", transition(lambda c: c[0] == \"congruent\" and c[1] == \"congruent\", [congruency])),\n derived_level(\"con-inc\", transition(lambda c: c[0] == \"congruent\" and c[1] == \"incongruent\", [congruency])),\n derived_level(\"con-ntr\", transition(lambda c: c[0] == \"congruent\" and c[1] == \"neutral\", [congruency])),\n derived_level(\"inc-con\", transition(lambda c: c[0] == \"incongruent\" and c[1] == \"congruent\", [congruency])),\n derived_level(\"inc-inc\", transition(lambda c: c[0] == \"incongruent\" and c[1] == \"incongruent\", [congruency])),\n derived_level(\"inc-ntr\", transition(lambda c: c[0] == \"incongruent\" and c[1] == \"neutral\", [congruency])),\n derived_level(\"ntr-con\", transition(lambda c: c[0] == \"neutral\" and c[1] == \"congruent\", [congruency])),\n derived_level(\"ntr-inc\", transition(lambda c: c[0] == \"neutral\" and c[1] == \"incongruent\", [congruency])),\n else_level(\"ntr-ntr\")\n])\n\n@pytest.mark.parametrize('design', permutations([congruency, congruency_transition]))\ndef test_correct_solution_count_with_congruence_factor_but_unconstrained(design):\n crossing = [congruency]\n constraints = []\n\n block = fully_cross_block(design, crossing, constraints)\n experiments = synthesize_trials_non_uniform(block, 100)\n\n assert len(experiments) == 6\n","sub_path":"acceptance/test_transition_with_three_levels.py","file_name":"test_transition_with_three_levels.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"103857180","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import Select\nimport pandas as pd\nimport csv\nimport time\n\n\n# creates a new saved_stops.csv file\ndef create_saved_stops():\n routes = list()\n stops = list()\n saved_stops = pd.DataFrame({\n \"Route\": routes,\n \"Stop\": stops\n })\n saved_stops.to_csv(\"stop_files/saved_stops.csv\", encoding='utf-8', index=False)\n\n\n# returns data frame read in from saved_stops.csv\n# dependent on create_saved_stops\ndef load_saved_stops():\n # use while loop instead to reduce number of lines?\n try:\n saved_stops = pd.read_csv('stop_files/saved_stops.csv')\n return saved_stops\n except FileNotFoundError: # create a new saved_stops file if none exists\n create_saved_stops()\n saved_stops = pd.read_csv('stop_files/saved_stops.csv')\n return saved_stops\n\n\n# add an entry to saved_stops.csv\ndef add_to_saved_stops(route, stop):\n # format a new row, write to the csv file\n new_stop = [route, stop]\n with open(r'stop_files/saved_stops.csv', 'a') as f:\n writer = csv.writer(f)\n writer.writerow(new_stop)\n print(\"Stop saved. Saved stops: \")\n print(load_saved_stops().to_string(index=False))\n\n\n# write a data frame back to saved_stops.csv\ndef write_to_saved_stops(df):\n df.to_csv(\"stop_files/saved_stops.csv\", encoding='utf-8', index=False)\n\n\n# remove a stop from the csv file\ndef remove_saved_stop(saved_stops):\n print(saved_stops.to_string(index=True))\n remove_choice = input(\"Choose a stop to remove (by index): \")\n remove_choice = remove_choice.replace(' ', '') # eliminate whitespace\n if remove_choice == 'q':\n print(\"Remove operation halted.\")\n return\n # load data frame\n ss = load_saved_stops()\n # remove by index\n ss.drop(ss.index[int(remove_choice)], inplace=True)\n if ss.empty:\n print(\"Saved stops list is now empty.\")\n else:\n print(\"New saved stops list: \")\n print(ss.to_string(index=False))\n write_to_saved_stops(ss)\n\n\n# retrieve predictions for all saved stops\ndef saved_stop_predictions(saved_stops):\n start_time = time.clock()\n print(\"Saved stop predictions: \\n\")\n option = webdriver.ChromeOptions()\n option.add_argument(\"--incognito\")\n browser = webdriver.Chrome(executable_path='C:\\\\Users\\\\whloo\\\\PycharmProjects\\\\chromedriver.exe',\n chrome_options=option)\n # create lists from both columns of the data frame\n line_list = saved_stops['Route']\n stop_list = saved_stops['Stop']\n # iterate through each at the same rate\n for i in range(0, len(line_list)):\n # open predictions web page for the corresponding line and stop\n route_url = \"https://unitrans.ucdavis.edu/routes/\" + line_list[i] + \"/prediction\"\n browser.get(route_url)\n try: # Wait until the final element is loaded.\n WebDriverWait(browser, 20).until(EC.visibility_of_element_located(\n (By.XPATH, \"//select[@id='stop-select']\")))\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n browser.quit()\n # retrieve prediction, and print it\n select_stop = Select(browser.find_element_by_id('stop-select'))\n select_stop.select_by_visible_text(stop_list[i])\n try:\n WebDriverWait(browser, 5).until(EC.visibility_of_all_elements_located(\n (By.XPATH, \"//span[@class='time']\")))\n arrival_times = browser.find_elements_by_xpath(\"//span[@class='time']\")\n print(line_list[i], \" Line: '\", stop_list[i], \"' stop: \")\n print(\"The next bus(es) will arrive in:\", arrival_times[0].text, \"min\\n\")\n except TimeoutException:\n prediction_check = browser.find_element_by_xpath(\"//div[@class='prediction']\")\n prediction_tags = prediction_check.find_elements_by_css_selector('p')\n if prediction_tags[1].get_attribute('style') == \"display: none;\":\n print(\"Line stopped running.\\n\")\n\n browser.close()\n print(\"Retrieved prediction in --- %s seconds ---\" % round(time.clock() - start_time, 2))","sub_path":"unitrans/saved_stop_functions.py","file_name":"saved_stop_functions.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"20121619","text":"# -*- coding:utf-8 -*-\n__author__ = \"Pei Xu, #5186611, xuxx0884@umn.edu\"\n__copyright__ = \"Copyright 2015-, Pei Xu\"\n__license__ = \"MIT\"\n__version__ = \"1.0.1\"\n__date__ = \"17:39:50, Nov. 21th, 2015\"\n\"\"\"This is the main program of the HappyPosion homework with the interface of terminal-line.\nRun main.py for the GUI version with full functions\"\"\"\n\nimport HP.Game as Game\nimport tkinter as tk\nfrom HP.AppGUI import *\n\nif __name__ == '__main__':\n\n print('\\n\\033[92m===== Welcome =====\\033[0m')\n print('Hi, this is a HappyPoison game developed by Pei Xu')\n print('\\nHope you love this game.\\n')\n print('Version: ' + __version__)\n print('License: ' + __license__)\n print('Copyright: ' + __copyright__)\n print('\\033[92m===================\\033[0m\\n')\n\n while True:\n print('Please Choose UI Mode')\n print('1. TUI')\n print('2. GUI (Tk)')\n choose = input('')\n if int(choose) == 1:\n mode = 1\n break\n elif int(choose) == 2:\n mode = 2\n break\n\n if mode == 1:\n while True:\n print('Please choose a game mode: 1 or 2')\n print('1: Computer v.s. Computer')\n print('2: Human v.s. Computer')\n choose = input('')\n if int(choose) == 1:\n player = 'C'\n break\n elif int(choose) == 2:\n player = 'H'\n break\n print('Game Starts')\n Game.run(player)\n else:\n AppGUI(master=tk.Tk()).mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"570952125","text":"from .utils_ml import TequilaMLException\nfrom shutil import which\nfrom tequila.objective import Objective\nSUPPORTED_PLATFORMS = ['pytorch', 'tensorflow']\nCONVERTERS = {}\n\n#HAS_TORCH = which('torch') is not None or which('pytorch') is not None\nHAS_TORCH = True\ntry:\n import torch\nexcept:\n HAS_TORCH = False\n\nif HAS_TORCH:\n from .interface_torch import TorchLayer\n CONVERTERS['pytorch'] = TorchLayer\n\n\nHAS_TF = True\ntry:\n import tensorflow\nexcept:\n HAS_TF = False\n\nif HAS_TF:\n from .interface_tf import TFLayer\n CONVERTERS['tensorflow'] = TFLayer\n\n\ndef to_platform(objective: Objective, platform: str,\n compile_args: dict = None, input_vars: list = None):\n plat = platform.lower()\n if plat == 'torch':\n # common alias.\n plat = 'pytorch'\n\n if plat == 'tf':\n # common alias\n plat = 'tensorflow'\n\n try:\n f = CONVERTERS[plat]\n return f(objective, compile_args, input_vars)\n except KeyError:\n raise TequilaMLException('Desired ML platform {} either not supported, or not installed.'.format(plat))\n","sub_path":"src/tequila/ml/ml_api.py","file_name":"ml_api.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"106856866","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Li Yuanming\nEmail: yli056@e.ntu.edu.sg\nDate: 6/20/2020\n\"\"\"\nfrom typing import List\n\nfrom fastapi import APIRouter\n\nfrom modelci.persistence.service import ModelService\nfrom modelci.types.bo import Framework, Engine, Task\nfrom modelci.types.vo.model_vo import ModelDetailOut, ModelListOut, Framework as Framework_, Engine as Engine_, \\\n Task as Task_\n\nrouter = APIRouter()\n\n\n@router.get('/', response_model=List[ModelListOut])\ndef get_all_model(name: str = None, framework: Framework_ = None, engine: Engine_ = None, task: Task_ = None,\n version: int = None):\n if framework is not None:\n framework = Framework[framework.value.upper()]\n if engine is not None:\n engine = Engine[engine.value.upper()]\n if task is not None:\n engine = Task[task.value.upper()]\n\n models = ModelService.get_models(name=name, framework=framework, engine=engine, task=task, version=version)\n return list(map(ModelListOut.from_bo, models))\n\n\n@router.get('/{id}', response_model=ModelDetailOut)\ndef get_model(*, id: str): # noqa\n model = ModelService.get_model_by_id(id)\n return ModelDetailOut.from_bo(model)\n","sub_path":"modelci/app/v1/endpoints/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"134120578","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import VarianceThreshold\n\nparibas_data = pd.read_csv(r\"C:\\Users\\TAYFUN BUĞRA BAŞ\\Desktop\\odevler vs\\Müh Proje\\hepsisonuclu.csv\", nrows=20000)\nparibas_data.shape\n\nnum_colums = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\nnumerical_columns = list(paribas_data.select_dtypes(include=num_colums).columns)\nparibas_data = paribas_data[numerical_columns]\nparibas_data.shape\n\ntrain_features, test_features, train_labels, test_labels = train_test_split(\n paribas_data.drop(labels=['0', '1'], axis=1),\n paribas_data['0'],\n test_size=0.33,\n random_state=41)\n\ncorrelated_features = set()\ncorrelation_matrix = paribas_data.corr()\nfor i in range(len(correlation_matrix .columns)):\n for j in range(i):\n if abs(correlation_matrix.iloc[i, j]) > 0.8:\n colname = correlation_matrix.columns[i]\n correlated_features.add(colname)\n\n\ntrain_features.drop(labels=correlated_features, axis=1, inplace=True)\ntest_features.drop(labels=correlated_features, axis=1, inplace=True)\n\ntrain_features.shape, test_features.shape\n\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score\n\nfrom mlxtend.feature_selection import SequentialFeatureSelector\n\nfeature_selector = SequentialFeatureSelector(RandomForestClassifier(n_jobs=-1),\n k_features=15,\n forward=True,\n verbose=2,\n scoring='roc_auc',\n cv=4)\n\nfeatures = feature_selector.fit(np.array(train_features.fillna(0)), train_labels)\n\nfiltered_features= train_features.columns[list(features.k_feature_idx_)]\nfiltered_features\n\nclf = RandomForestClassifier(n_estimators=100, random_state=41, max_depth=3)\nclf.fit(train_features[filtered_features].fillna(0), train_labels)\n\ntrain_pred = clf.predict_proba(train_features[filtered_features].fillna(0))\nprint('Accuracy on training set: {}'.format(roc_auc_score(train_labels, train_pred[:,1])))\n\ntest_pred = clf.predict_proba(test_features[filtered_features].fillna(0))\nprint('Accuracy on test set: {}'.format(roc_auc_score(test_labels, test_pred [:,1])))","sub_path":"Müh Proje/untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"630849137","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 19 10:07:28 2018\n\n@author: alex\n\"\"\"\nfrom up_convolution import convolution,trans_convolve\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport pickle\nfrom sklearn.preprocessing import StandardScaler\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n############################################ NETWORK BUILDING ############################################\ndef get_bilinear_filter(filter_shape, upscale_factor):\n '''\n Description : Generates a filter than performs simple bilinear interpolation for a given upsacle_factor\n \n Arguments:\n filter_shape -- [width, height, num_in_channels, num_out_channels] -> num_in_channels = num_out_channels\n upscale_factor -- The number of times you want to scale the image.\n \n Returns :\n weigths -- The populated bilinear filter\n '''\n \n kernel_size = filter_shape[1]\n \n # Centre location of the filter for which value is calculated\n if kernel_size % 2 == 1:\n centre_location = upscale_factor - 1\n else:\n centre_location = upscale_factor - 0.5\n \n bilinear = np.zeros([filter_shape[0], filter_shape[1]])\n for x in range(filter_shape[0]):\n for y in range(filter_shape[1]):\n ##Interpolation Calculation\n value = (1 - abs((x - centre_location)/ upscale_factor)) * (1 - abs((y - centre_location)/ upscale_factor))\n bilinear[x, y] = value\n weights = np.zeros(filter_shape)\n \n for k in range(filter_shape[3]):\n for i in range(filter_shape[2]):\n weights[:, :, i, k] = bilinear\n \n return weights \n\ndef constant_initializer(x):\n\n arr = np.ones(shape = (x,1))\n arr *= 0.01\n arr = np.reshape(arr, newshape = (x))\n\n return arr\n\ndef variable_summaries_weights_biases(var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n tf.summary.histogram('histogram',var)\n\ndef variable_summaries_scalars(var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n tf.summary.scalar('value',var)\n\ndef create_placeholders(n_H0,n_W0,n_C0):\n \"\"\"\n Creates the placeholders for the input size and for the number of output classes.\n \n Arguments:\n n_W0 -- scalar, width of an input matrix\n n_C0 -- scalar, number of channels of the input\n n_y -- scalar, number of classes\n \n Returns:\n X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype \"float\"\n Y -- placeholder for the input labels, of shape [None, n_y] and dtype \"float\"\n \"\"\"\n \n with tf.name_scope(\"Inputs\") :\n # Keep the number of examples as a variable (None) and the height of the matrix as variables (None)\n X = tf.placeholder(dtype = tf.float32, shape = (None,n_H0,n_W0,n_C0), name = \"X\") \n Y = tf.placeholder(dtype = tf.float32, shape = (None,n_H0,n_W0,1), name = \"Y\")\n \n \n return X,Y\n\n\ndef initialize_parameters():\n '''\n Description:\n Initialize weight parameters for the weight matrix.\n\n Returns: \n weight_parameters - A dictionary containing all the weights of the neural network\n '''\n \n l_11 = constant_initializer(32)\n left_1_1_conv = tf.get_variable(name = \"Road_tar_left_1_1_conv\",shape = (3,3,9,32),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_1_1_conv_bias = tf.get_variable(name = \"Road_tar_left_1_1_conv_bias\",shape = (32),dtype = tf.float32,initializer = tf.constant_initializer(l_11),trainable = True)\n \n l_12 = constant_initializer(32)\n left_1_2_conv = tf.get_variable(name = \"Road_tar_left_1_2_conv\",shape = (3,3,32,32),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_1_2_conv_bias = tf.get_variable(name = \"Road_tar_left_1_2_conv_bias\",shape = (32),dtype = tf.float32,initializer = tf.constant_initializer(l_12),trainable = True)\n\n l_21 = constant_initializer(64)\n left_2_1_conv = tf.get_variable(name = \"Road_tar_left_2_1_conv\",shape = (3,3,32,64),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_2_1_conv_bias = tf.get_variable(name = \"Road_tar_left_2_1_conv_bias\",shape = (64),dtype = tf.float32,initializer = tf.constant_initializer(l_21),trainable = True)\n \n l_22 = constant_initializer(64)\n left_2_2_conv = tf.get_variable(name = \"Road_tar_left_2_2_conv\",shape = (3,3,64,64),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_2_2_conv_bias = tf.get_variable(name = \"Road_tar_left_2_2_conv_bias\",shape = (64),dtype = tf.float32,initializer = tf.constant_initializer(l_22),trainable = True) \n \n l_31 = constant_initializer(128)\n left_3_1_conv = tf.get_variable(name = \"Road_tar_left_3_1_conv\",shape = (3,3,64,128),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_3_1_conv_bias = tf.get_variable(name = \"Road_tar_left_3_1_conv_bias\",shape = (128),dtype = tf.float32,initializer = tf.constant_initializer(l_31),trainable = True)\n\n l_32 = constant_initializer(128)\n left_3_2_conv = tf.get_variable(name = \"Road_tar_left_3_2_conv\",shape = (3,3,128,128),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_3_2_conv_bias = tf.get_variable(name = \"Road_tar_left_3_2_conv_bias\",shape = (128),dtype = tf.float32,initializer = tf.constant_initializer(l_32),trainable = True)\n \n l_41 = constant_initializer(256) \n left_4_1_conv = tf.get_variable(name = \"Road_tar_left_4_1_conv\",shape = (3,3,128,256),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_4_1_conv_bias = tf.get_variable(name = \"Road_tar_left_4_1_conv_bias\",shape = (256),dtype = tf.float32,initializer = tf.constant_initializer(l_41),trainable = True) \n \n l_42 = constant_initializer(256) \n left_4_2_conv = tf.get_variable(name = \"Road_tar_left_4_2_conv\",shape = (3,3,256,256),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n left_4_2_conv_bias = tf.get_variable(name = \"Road_tar_left_4_2_conv_bias\",shape = (256),dtype = tf.float32,initializer = tf.constant_initializer(l_42),trainable = True) \n \n c_51 = constant_initializer(512) \n centre_5_1_conv = tf.get_variable(name = \"Road_tar_centre_5_1_conv\",shape = (3,3,256,512),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n centre_5_1_conv_bias = tf.get_variable(name = \"Road_tar_centre_5_1_conv_bias\",shape = (512),dtype = tf.float32,initializer = tf.constant_initializer(c_51),trainable = True) \n \n c_52 = constant_initializer(512)\n centre_5_2_conv = tf.get_variable(name = \"Road_tar_centre_5_2_conv\",shape = (3,3,512,512),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n centre_5_2_conv_bias = tf.get_variable(name = \"Road_tar_centre_5_2_conv_bias\",shape = (512),dtype = tf.float32,initializer = tf.constant_initializer(c_52),trainable = True)\n\n weights_1 = np.transpose(get_bilinear_filter([2,2,512,128],2),(1,0,3,2))\n centre_5_3_deconv = tf.get_variable(name = \"Road_tar_centre_5_3_deconv\",shape = (2,2,128,512),dtype = tf.float32,initializer = tf.constant_initializer(value=weights_1,dtype=tf.float32),trainable = False) \n\n r_41 = constant_initializer(256)\n right_4_1_conv = tf.get_variable(name = \"Road_tar_right_4_1_conv\",shape = (3,3,128 + 256,256),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_4_1_conv_bias = tf.get_variable(name = \"Road_tar_right_4_1_conv_bias\",shape = (256),dtype = tf.float32,initializer = tf.constant_initializer(r_41),trainable = True)\n \n r_42 = constant_initializer(256) \n right_4_2_conv = tf.get_variable(name = \"Road_tar_right_4_2_conv\",shape = (3,3,256,256),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_4_2_conv_bias = tf.get_variable(name = \"Road_tar_right_4_2_conv_bias\",shape = (256),dtype = tf.float32,initializer = tf.constant_initializer(r_42),trainable = True)\n\n weights_2 = np.transpose(get_bilinear_filter([2,2,256,256],2),(1,0,3,2)) \n right_4_3_deconv = tf.get_variable(name = \"Road_tar_right_4_3_deconv\",shape = (2,2,256,256),dtype = tf.float32,initializer = tf.constant_initializer(value=weights_2,dtype=tf.float32),trainable = False) \n \n r_31 = constant_initializer(128) \n right_3_1_conv = tf.get_variable(name = \"Road_tar_right_3_1_conv\",shape = (3,3,128 + 256,128),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_3_1_conv_bias = tf.get_variable(name = \"Road_tar_right_3_1_conv_bias\",shape = (128),dtype = tf.float32,initializer = tf.constant_initializer(r_31),trainable = True)\n \n r_32 = constant_initializer(128) \n right_3_2_conv = tf.get_variable(name = \"Road_tar_right_3_2_conv\",shape = (3,3,128,128),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_3_2_conv_bias = tf.get_variable(name = \"Road_tar_right_3_2_conv_bias\",shape = (128),dtype = tf.float32,initializer = tf.constant_initializer(r_32),trainable = True)\n\n weights_3 = np.transpose(get_bilinear_filter([2,2,128,128],2),(1,0,3,2)) \n right_3_3_deconv = tf.get_variable(name = \"Road_tar_right_3_3_deconv\", shape = (2,2,128,128),dtype = tf.float32,initializer = tf.constant_initializer(value=weights_3,dtype=tf.float32),trainable = False)\n\n r_21 = constant_initializer(64)\n right_2_1_conv = tf.get_variable(name = \"Road_tar_right_2_1_conv\",shape = (3,3,128 + 64,64),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_2_1_conv_bias = tf.get_variable(name = \"Road_tar_right_2_1_conv_bias\",shape = (64),dtype = tf.float32,initializer = tf.constant_initializer(r_21),trainable = True)\n \n r_22 = constant_initializer(64) \n right_2_2_conv = tf.get_variable(name = \"Road_tar_right_2_2_conv\",shape = (3,3,64,64),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_2_2_conv_bias = tf.get_variable(name = \"Road_tar_right_2_2_conv_bias\",shape = (64),dtype = tf.float32,initializer =tf.constant_initializer(r_22),trainable = True)\n\n weights_4 = np.transpose(get_bilinear_filter([2,2,64,64],2),(1,0,3,2)) \n right_2_3_deconv = tf.get_variable(name = \"Road_tar_right_2_3_deconv\",shape = (2,2,64,64),dtype = tf.float32,initializer = tf.constant_initializer(value=weights_4,dtype=tf.float32),trainable = False)\n\n r_11 = constant_initializer(32)\n right_1_1_conv = tf.get_variable(name = \"Road_tar_right_1_1_conv\",shape = (9,9,64+32,32),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_1_1_conv_bias = tf.get_variable(name = \"Road_tar_right_1_1_conv_bias\",shape = (32),dtype = tf.float32,initializer = tf.constant_initializer(r_11),trainable = True)\n \n r_12 = constant_initializer(1) \n right_1_2_conv = tf.get_variable(name = \"Road_tar_right_1_2_conv\",shape = (9,9,32,1),dtype = tf.float32,initializer = tf.keras.initializers.he_uniform(),trainable = True)\n right_1_2_conv_bias = tf.get_variable(name = \"Road_tar_right_1_2_conv_bias\",shape = (1),dtype = tf.float32,initializer = tf.constant_initializer(r_12),trainable = True)\n \n weight_parameters = {}\n\n weight_parameters[\"left_1_1_conv\"] = left_1_1_conv\n weight_parameters[\"left_1_1_conv_bias\"] = left_1_1_conv_bias\n \n weight_parameters[\"left_1_2_conv\"] = left_1_2_conv\n weight_parameters[\"left_1_2_conv_bias\"] = left_1_2_conv_bias\n\n weight_parameters[\"left_2_1_conv\"] = left_2_1_conv\n weight_parameters[\"left_2_1_conv_bias\"] = left_2_1_conv_bias \n \n weight_parameters[\"left_2_2_conv\"] = left_2_2_conv\n weight_parameters[\"left_2_2_conv_bias\"] = left_2_2_conv_bias \n\n weight_parameters[\"left_3_1_conv\"] = left_3_1_conv\n weight_parameters[\"left_3_1_conv_bias\"] = left_3_1_conv_bias \n \n weight_parameters[\"left_3_2_conv\"] = left_3_2_conv\n weight_parameters[\"left_3_2_conv_bias\"] = left_3_2_conv_bias \n\n weight_parameters[\"left_4_1_conv\"] = left_4_1_conv\n weight_parameters[\"left_4_1_conv_bias\"] = left_4_1_conv_bias \n \n weight_parameters[\"left_4_2_conv\"] = left_4_2_conv\n weight_parameters[\"left_4_2_conv_bias\"] = left_4_2_conv_bias \n \n weight_parameters[\"centre_5_1_conv\"] = centre_5_1_conv\n weight_parameters[\"centre_5_1_conv_bias\"] = centre_5_1_conv_bias \n \n weight_parameters[\"centre_5_2_conv\"] = centre_5_2_conv\n weight_parameters[\"centre_5_2_conv_bias\"] = centre_5_2_conv_bias \n\n weight_parameters[\"centre_5_3_deconv\"] = centre_5_3_deconv\n\n weight_parameters[\"right_4_1_conv\"] = right_4_1_conv\n weight_parameters[\"right_4_1_conv_bias\"] = right_4_1_conv_bias \n \n weight_parameters[\"right_4_2_conv\"] = right_4_2_conv\n weight_parameters[\"right_4_2_conv_bias\"] = right_4_2_conv_bias\n\n weight_parameters[\"right_4_3_deconv\"] = right_4_3_deconv\n\n weight_parameters[\"right_3_1_conv\"] = right_3_1_conv\n weight_parameters[\"right_3_1_conv_bias\"] = right_3_1_conv_bias \n \n weight_parameters[\"right_3_2_conv\"] = right_3_2_conv\n weight_parameters[\"right_3_2_conv_bias\"] = right_3_2_conv_bias\n \n weight_parameters[\"right_3_3_deconv\"] = right_3_3_deconv\n \n weight_parameters[\"right_2_1_conv\"] = right_2_1_conv\n weight_parameters[\"right_2_1_conv_bias\"] = right_2_1_conv_bias\n \n weight_parameters[\"right_2_2_conv\"] = right_2_2_conv\n weight_parameters[\"right_2_2_conv_bias\"] = right_2_2_conv_bias \n \n weight_parameters[\"right_2_3_deconv\"] = right_2_3_deconv\n \n weight_parameters[\"right_1_1_conv\"] = right_1_1_conv\n weight_parameters[\"right_1_1_conv_bias\"] = right_1_1_conv_bias\n\n weight_parameters[\"right_1_2_conv\"] = right_1_2_conv\n weight_parameters[\"right_1_2_conv_bias\"] = right_1_2_conv_bias\n \n return weight_parameters\n\n\ndef forward_prop(X,weight_parameters,bool_train = True) : \n \n '''\n Description :\n Performs the forward propagation in the network.\n \n Arguments :\n X -- np.array\n The input matrix\n weight_parameters -- dict.\n The initialized weights for the matrix\n bool_train -- Bool.\n An argument passed to the batch normalization parameter, to allow the updation of batch mean and variance\n\n Returns :\n conv18 -- The final feature vector\n '''\n \n left_1_1_conv = weight_parameters[\"left_1_1_conv\"] \n left_1_2_conv = weight_parameters[\"left_1_2_conv\"]\n \n left_2_1_conv = weight_parameters[\"left_2_1_conv\"]\n left_2_2_conv = weight_parameters[\"left_2_2_conv\"]\n \n left_3_1_conv = weight_parameters[\"left_3_1_conv\"]\n left_3_2_conv = weight_parameters[\"left_3_2_conv\"]\n \n left_4_1_conv = weight_parameters[\"left_4_1_conv\"]\n left_4_2_conv = weight_parameters[\"left_4_2_conv\"]\n \n centre_5_1_conv = weight_parameters[\"centre_5_1_conv\"]\n centre_5_2_conv = weight_parameters[\"centre_5_2_conv\"]\n\n left_1_1_conv_bias = weight_parameters[\"left_1_1_conv_bias\"] \n left_1_2_conv_bias = weight_parameters[\"left_1_2_conv_bias\"]\n \n left_2_1_conv_bias = weight_parameters[\"left_2_1_conv_bias\"]\n left_2_2_conv_bias = weight_parameters[\"left_2_2_conv_bias\"]\n \n left_3_1_conv_bias = weight_parameters[\"left_3_1_conv_bias\"]\n left_3_2_conv_bias = weight_parameters[\"left_3_2_conv_bias\"]\n \n left_4_1_conv_bias = weight_parameters[\"left_4_1_conv_bias\"]\n left_4_2_conv_bias = weight_parameters[\"left_4_2_conv_bias\"]\n \n centre_5_1_conv_bias = weight_parameters[\"centre_5_1_conv_bias\"]\n centre_5_2_conv_bias = weight_parameters[\"centre_5_2_conv_bias\"]\n\n centre_5_3_deconv = weight_parameters[\"centre_5_3_deconv\"]\n\n right_4_1_conv = weight_parameters[\"right_4_1_conv\"] \n right_4_1_conv_bias = weight_parameters[\"right_4_1_conv_bias\"] \n \n right_4_2_conv = weight_parameters[\"right_4_2_conv\"] \n right_4_2_conv_bias = weight_parameters[\"right_4_2_conv_bias\"] \n\n right_4_3_deconv = weight_parameters[\"right_4_3_deconv\"]\n\n right_3_1_conv = weight_parameters[\"right_3_1_conv\"]\n right_3_1_conv_bias = weight_parameters[\"right_3_1_conv_bias\"] \n \n right_3_2_conv = weight_parameters[\"right_3_2_conv\"] \n right_3_2_conv_bias = weight_parameters[\"right_3_2_conv_bias\"]\n \n right_3_3_deconv = weight_parameters[\"right_3_3_deconv\"]\n \n right_2_1_conv = weight_parameters[\"right_2_1_conv\"]\n right_2_1_conv_bias = weight_parameters[\"right_2_1_conv_bias\"]\n \n right_2_2_conv = weight_parameters[\"right_2_2_conv\"] \n right_2_2_conv_bias = weight_parameters[\"right_2_2_conv_bias\"] \n \n right_2_3_deconv = weight_parameters[\"right_2_3_deconv\"]\n \n right_1_1_conv = weight_parameters[\"right_1_1_conv\"] \n right_1_1_conv_bias = weight_parameters[\"right_1_1_conv_bias\"] \n\n right_1_2_conv = weight_parameters[\"right_1_2_conv\"] \n right_1_2_conv_bias = weight_parameters[\"right_1_2_conv_bias\"] \n\n\n ### Left Branch 1st Layer ###\n \n \n ## INTERESTING -- TENSORFLOW DOES A BAD JOB WHEN WE WANT TO PAD AN EVEN INPUT WITH AN ODD KERNEL ## \n with tf.name_scope(\"Left_Branch_1st_Layer\") :\n \n with tf.name_scope(\"Conv_1\") :\n conv1 = tf.nn.conv2d(tf.pad(X,paddings = [[0,0],[112,112],[112,112],[0,0]],mode = 'SYMMETRIC'),left_1_1_conv,strides = (1,3,3,1),padding = \"VALID\",name = \"convolve\")\n conv1 = tf.nn.bias_add(conv1,left_1_1_conv_bias,name = \"bias_add\")\n conv1 = tf.layers.batch_normalization(conv1,training = bool_train,name = \"norm\")\n conv1 = tf.nn.leaky_relu (conv1,name = \"activation\")\n variable_summaries_weights_biases(left_1_1_conv)\n variable_summaries_weights_biases(left_1_1_conv_bias)\n \n with tf.name_scope(\"Conv_2\") : \n conv2 = tf.nn.conv2d(tf.pad(conv1,paddings = [[0,0],[112,112],[112,112],[0,0]],mode = 'SYMMETRIC'), left_1_2_conv, (1,3,3,1), padding = \"VALID\",name = \"convolve\")\n conv2 = tf.nn.bias_add(conv2,left_1_2_conv_bias,name = \"bias_add\")\n conv2 = tf.layers.batch_normalization(conv2,training = bool_train,name = \"norm_2\")\n conv2 = tf.nn.leaky_relu(conv2,name = \"activation\")\n variable_summaries_weights_biases(left_1_2_conv)\n variable_summaries_weights_biases(left_1_2_conv_bias)\n \n with tf.name_scope(\"Pool\") :\n max_pool_1 = tf.nn.max_pool(tf.pad(conv2,paddings = [[0,0],[8,8],[8,8],[0,0]],mode = 'SYMMETRIC'),ksize = (1,2,2,1), strides = (1,2,2,1),padding = \"VALID\",name = \"max_pool\")\n \n \n ### Left Branch 2nd layer ###\n \n with tf.name_scope(\"Left_Branch_2nd_Layer\") : \n\n with tf.name_scope(\"Conv_1\") :\n conv3 = tf.nn.conv2d(tf.pad(max_pool_1,paddings = [[0,0],[64,64],[64,64],[0,0]],mode = 'SYMMETRIC'),left_2_1_conv, (1,3,3,1), padding = \"VALID\",name = \"convolve\")\n conv3 = tf.nn.bias_add(conv3,left_2_1_conv_bias,name = \"bias_add\")\n conv3 = tf.layers.batch_normalization(conv3,training = bool_train,name = \"norm_3\")\n conv3 = tf.nn.leaky_relu(conv3,name = \"activation\")\n variable_summaries_weights_biases(left_2_1_conv)\n variable_summaries_weights_biases(left_2_1_conv_bias)\n\n with tf.name_scope(\"Conv_2\") :\n conv4 = tf.nn.conv2d(tf.pad(conv3,paddings = [[0,0],[64,64],[64,64],[0,0]],mode = 'SYMMETRIC'),left_2_2_conv, (1,3,3,1), padding = 'VALID',name = \"convolve\")\n conv4 = tf.nn.bias_add(conv4,left_2_2_conv_bias,name = \"bias_add\")\n conv4 = tf.layers.batch_normalization(conv4,training = bool_train,name = \"norm_4\")\n conv4 = tf.nn.leaky_relu(conv4,name = \"activation\")\n variable_summaries_weights_biases(left_2_2_conv)\n variable_summaries_weights_biases(left_2_2_conv_bias)\n\n with tf.name_scope(\"Pool\") :\n max_pool_2 = tf.nn.max_pool(conv4,ksize = (1,2,2,1),strides = (1,2,2,1),padding = \"VALID\",name = \"max_pool\")\n\n \n ### Left Branch 3rd layer ###\n \n with tf.name_scope(\"Left_Branch_3rd_Layer\") :\n \n with tf.name_scope(\"Conv_1\") :\n conv5 = tf.nn.conv2d(tf.pad(max_pool_2,paddings = [[0,0],[32,32],[32,32],[0,0]],mode = 'SYMMETRIC'),left_3_1_conv, (1,3,3,1), padding = 'VALID',name = \"convolve\")\n conv5 = tf.nn.bias_add(conv5,left_3_1_conv_bias,name = \"bias_add\")\n conv5 = tf.layers.batch_normalization(conv5,training = bool_train,name = \"norm_5\")\n conv5 = tf.nn.leaky_relu(conv5,name = \"activation\")\n variable_summaries_weights_biases(left_3_1_conv)\n variable_summaries_weights_biases(left_3_1_conv_bias)\n\n with tf.name_scope(\"Conv_2\") :\n conv6 = tf.nn.conv2d(tf.pad(conv5,paddings = [[0,0],[32,32],[32,32],[0,0]],mode = 'SYMMETRIC'),left_3_2_conv, (1,3,3,1), padding = 'VALID',name = \"convolve\")\n conv6 = tf.nn.bias_add(conv6,left_3_2_conv_bias,name = \"bias_add\")\n conv6 = tf.layers.batch_normalization(conv6,training = bool_train,name = \"norm_6\")\n conv6 = tf.nn.leaky_relu(conv6,name = \"activation\")\n variable_summaries_weights_biases(left_3_2_conv)\n variable_summaries_weights_biases(left_3_2_conv_bias)\n\n with tf.name_scope(\"Pool\") :\n max_pool_3 = tf.nn.max_pool(conv6,ksize = (1,2,2,1),strides = (1,2,2,1),padding = \"VALID\",name = \"max_pool\")\n \n ### Left Branch 4th layer ###\n \n with tf.name_scope(\"Left_Branch_4th_Layer\"):\n \n with tf.name_scope(\"Conv_1\") :\n conv7 = tf.nn.conv2d(tf.pad(max_pool_3,paddings = [[0,0],[16,16],[16,16],[0,0]],mode = 'SYMMETRIC'),left_4_1_conv,(1,3,3,1),padding = \"VALID\",name = \"convolve\")\n conv7 = tf.nn.bias_add(conv7,left_4_1_conv_bias,name = \"bias_add\")\n conv7 = tf.layers.batch_normalization(conv7,training = bool_train,name = \"norm_7\")\n conv7 = tf.nn.leaky_relu(conv7,name = \"activation\")\n variable_summaries_weights_biases(left_4_1_conv)\n variable_summaries_weights_biases(left_4_1_conv_bias)\n \n with tf.name_scope(\"Conv_2\") :\n conv8 = tf.nn.conv2d(tf.pad(conv7,paddings = [[0,0],[16,16],[16,16],[0,0]],mode = 'SYMMETRIC'),left_4_2_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv8 = tf.nn.bias_add(conv8,left_4_2_conv_bias,name = \"bias_add\")\n conv8 = tf.layers.batch_normalization(conv8,training = bool_train,name = \"norm_8\")\n conv8 = tf.nn.leaky_relu(conv8,name = \"activation\")\n variable_summaries_weights_biases(left_4_2_conv)\n variable_summaries_weights_biases(left_4_2_conv_bias)\n\n with tf.name_scope(\"Pool\") :\n max_pool_4 = tf.nn.max_pool(conv8,ksize = (1,2,2,1),strides = (1,2,2,1),padding = \"VALID\",name = \"max_pool\")\n \n \n ### Centre Branch ###\n \n with tf.name_scope(\"Centre_Branch\"):\n \n with tf.name_scope(\"Conv_1\") :\n \n conv9 = tf.nn.conv2d(tf.pad(max_pool_4,paddings = [[0,0],[8,8],[8,8],[0,0]],mode = 'SYMMETRIC'),centre_5_1_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv9 = tf.nn.bias_add(conv9,centre_5_1_conv_bias,name = \"bias_add\")\n conv9 = tf.layers.batch_normalization(conv9,training = bool_train,name = \"norm_9\")\n conv9 = tf.nn.leaky_relu(conv9,name = \"activation\")\n variable_summaries_weights_biases(centre_5_1_conv) \n variable_summaries_weights_biases(centre_5_1_conv_bias)\n \n with tf.name_scope(\"Conv_2\") :\n \n conv10 = tf.nn.conv2d(tf.pad(conv9,paddings = [[0,0],[8,8],[8,8],[0,0]],mode = 'SYMMETRIC'),centre_5_2_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv10 = tf.nn.bias_add(conv10,centre_5_2_conv_bias,name = \"bias_add\")\n conv10 = tf.layers.batch_normalization(conv10,training = bool_train,name = \"norm_10\")\n conv10 = tf.nn.leaky_relu(conv10,name = \"activation\")\n variable_summaries_weights_biases(centre_5_2_conv)\n variable_summaries_weights_biases(centre_5_2_conv_bias)\n\n conv10_obj = convolution(conv9.shape[1],conv9.shape[2],conv9.shape[3],centre_5_2_conv.shape[0],centre_5_2_conv.shape[1],centre_5_2_conv.shape[3],3,3,conv9.shape[1],conv9.shape[2])\n de_conv10_obj = trans_convolve(None,True,conv10_obj.output_h,conv10_obj.output_w,conv10_obj.output_d,kernel_h = 2,kernel_w = 2,kernel_d =128,stride_h = 2,stride_w = 2,padding = 'VALID') \n \n with tf.name_scope(\"Deconvolve\") : \n de_conv10 = tf.nn.conv2d_transpose(conv10,centre_5_3_deconv, output_shape = (tf.shape(X)[0],de_conv10_obj.output_h,de_conv10_obj.output_w,de_conv10_obj.output_d), strides = (1,2,2,1),padding = 'VALID',name = \"deconv\")\n variable_summaries_weights_biases(centre_5_3_deconv) \n\n ### Right Branch 4th layer ###\n \n with tf.name_scope(\"Merging\") :\n \n merge1 = tf.concat([de_conv10,conv8],axis = 3,name = \"merge\") \n \n \n with tf.name_scope(\"Right_Branch_4th_Layer\"):\n \n with tf.name_scope(\"Conv_1\") :\n \n conv11 = tf.nn.conv2d(tf.pad(merge1,paddings = [[0,0],[16,16],[16,16],[0,0]],mode = 'SYMMETRIC'),right_4_1_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv11 = tf.nn.bias_add(conv11,right_4_1_conv_bias,name = \"bias_add\")\n conv11 = tf.layers.batch_normalization(conv11,training = bool_train,name = \"norm_11\")\n conv11 = tf.nn.leaky_relu(conv11,name = \"activation\")\n variable_summaries_weights_biases(right_4_1_conv)\n\n with tf.name_scope(\"Conv_2\") :\n \n conv12 = tf.nn.conv2d(tf.pad(conv11,paddings = [[0,0],[16,16],[16,16],[0,0]],mode = 'SYMMETRIC'),right_4_2_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv12 = tf.nn.bias_add(conv12,right_4_2_conv_bias,name = \"bias_add\")\n conv12 = tf.layers.batch_normalization(conv12,training = bool_train,name = \"norm_12\")\n conv12 = tf.nn.leaky_relu(conv12,name = \"activation\")\n variable_summaries_weights_biases(right_4_2_conv)\n variable_summaries_weights_biases(right_4_2_conv_bias)\n\n conv12_obj = convolution(conv11.shape[1],conv11.shape[2],conv11.shape[3],right_4_2_conv.shape[0],right_4_2_conv.shape[1],right_4_2_conv.shape[3],3,3,conv11.shape[1],conv11.shape[2]) \n de_conv12_obj = trans_convolve(None,True,conv12_obj.output_h,conv12_obj.output_w,conv12_obj.output_d,kernel_h = 2,kernel_w = 2,kernel_d = 256,stride_h = 2,stride_w = 2,padding = 'VALID') \n \n with tf.name_scope(\"Deconvolve\") : \n de_conv12 = tf.nn.conv2d_transpose(conv12,right_4_3_deconv,output_shape = (tf.shape(X)[0],de_conv12_obj.output_h,de_conv12_obj.output_w,de_conv12_obj.output_d), strides = (1,2,2,1),padding = 'VALID',name = \"deconv\")\n variable_summaries_weights_biases(right_4_3_deconv)\n \n ### Right Branch 3rd layer ###\n \n with tf.name_scope(\"Merging\") :\n \n merge2 = tf.concat([de_conv12,conv6],axis = 3,name = \"merge\")\n \n with tf.name_scope(\"Right_Branch_3rd_Layer\"):\n \n with tf.name_scope(\"Conv_1\") :\n \n conv13 = tf.nn.conv2d(tf.pad(merge2,paddings = [[0,0],[32,32],[32,32],[0,0]],mode = 'SYMMETRIC'),right_3_1_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv13 = tf.nn.bias_add(conv13,right_3_1_conv_bias,name = \"bias_add\")\n conv13 = tf.layers.batch_normalization(conv13,training = bool_train,name = \"norm_13\")\n conv13 = tf.nn.leaky_relu(conv13,name = \"activation\")\n variable_summaries_weights_biases(right_3_1_conv) \n variable_summaries_weights_biases(right_3_1_conv_bias)\n \n with tf.name_scope(\"Conv_2\") :\n \n conv14 = tf.nn.conv2d(tf.pad(conv13,paddings = [[0,0],[32,32],[32,32],[0,0]],mode = 'SYMMETRIC'),right_3_2_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv14 = tf.nn.bias_add(conv14,right_3_2_conv_bias,name = \"bias_add\")\n conv14 = tf.layers.batch_normalization(conv14,training = bool_train,name = \"norm_14\")\n conv14 = tf.nn.leaky_relu(conv14,name = \"activation\") \n variable_summaries_weights_biases(right_3_2_conv)\n variable_summaries_weights_biases(right_3_2_conv_bias)\n conv14_obj = convolution(conv13.shape[1],conv13.shape[2],conv13.shape[3],right_3_2_conv.shape[0],right_3_2_conv.shape[1],right_3_2_conv.shape[3],3,3,conv13.shape[1],conv13.shape[2]) \n de_conv14_obj = trans_convolve(None,True,conv14_obj.output_h,conv14_obj.output_w,conv14_obj.output_d,kernel_h = 2,kernel_w = 2,kernel_d = 128,stride_h = 2,stride_w = 2,padding = 'VALID')\n \n with tf.name_scope(\"Deconvolve\") : \n de_conv14 = tf.nn.conv2d_transpose(conv14,right_3_3_deconv,output_shape = (tf.shape(X)[0],de_conv14_obj.output_h,de_conv14_obj.output_w,de_conv14_obj.output_d), strides = (1,2,2,1),padding = 'VALID',name = \"deconv\")\n variable_summaries_weights_biases(right_3_3_deconv) \n \n ### Right Branch 2nd layer ###\n \n with tf.name_scope(\"Merging\") :\n \n merge3 = tf.concat([de_conv14,conv4],axis = 3,name = \"merge\")\n \n with tf.name_scope(\"Right_Branch_2nd_Layer\"):\n \n with tf.name_scope(\"Conv_1\") : \n conv15 = tf.nn.conv2d(tf.pad(merge3,paddings = [[0,0],[64,64],[64,64],[0,0]],mode = 'SYMMETRIC'),right_2_1_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv15 = tf.nn.bias_add(conv15,right_2_1_conv_bias,name = \"bias_add\")\n conv15 = tf.layers.batch_normalization(conv15,training = bool_train,name = \"norm_15\")\n conv15 = tf.nn.leaky_relu(conv15,name = \"activation\")\n variable_summaries_weights_biases(right_2_1_conv)\n variable_summaries_weights_biases(right_2_1_conv_bias)\n \n with tf.name_scope(\"Conv_2\") :\n conv16 = tf.nn.conv2d(tf.pad(conv15,paddings = [[0,0],[64,64],[64,64],[0,0]],mode = 'SYMMETRIC'),right_2_2_conv,(1,3,3,1),padding = 'VALID',name = \"convolve\")\n conv16 = tf.nn.bias_add(conv16,right_2_2_conv_bias,name = \"bias_add\")\n conv16 = tf.layers.batch_normalization(conv16,training = bool_train,name = \"norm_16\")\n conv16 = tf.nn.leaky_relu(conv16,name = \"activation\")\n variable_summaries_weights_biases(right_2_2_conv)\n variable_summaries_weights_biases(right_2_2_conv_bias)\n\n conv16_obj = convolution(conv15.shape[1],conv15.shape[2],conv15.shape[3],right_2_2_conv.shape[0],right_2_2_conv.shape[1],right_2_2_conv.shape[3],3,3,conv15.shape[1],conv15.shape[2]) \n de_conv16_obj = trans_convolve(None,True,conv16_obj.output_h,conv16_obj.output_w,conv16_obj.output_d,kernel_h = 2,kernel_w = 2,kernel_d = 64,stride_h = 2,stride_w = 2,padding = 'VALID') \n \n with tf.name_scope(\"Deconvolve\") :\n de_conv16 = tf.nn.conv2d_transpose(conv16,right_2_3_deconv,output_shape = (tf.shape(X)[0],de_conv16_obj.output_h,de_conv16_obj.output_w,de_conv16_obj.output_d), strides = (1,2,2,1),padding = 'VALID',name = \"deconv\") \n variable_summaries_weights_biases(right_2_3_deconv)\n \n ### Right Branch 1st layer ###\n\n with tf.name_scope(\"Merging\") :\n conv2 = tf.pad(conv2,paddings=[[0,0],[8,8],[8,8],[0,0]],mode = 'SYMMETRIC')\n merge4 = tf.concat([de_conv16,conv2], axis = 3,name = \"merge\")\n\n\n with tf.name_scope(\"Right_Branch_1st_Layer\"):\n\n with tf.name_scope(\"Conv1\") : \n conv17 = tf.nn.conv2d(merge4,right_1_1_conv,(1,1,1,1),padding = 'VALID',name = \"convolve\")\n conv17 = tf.nn.bias_add(conv17,right_1_1_conv_bias,name = \"bias_add\") \n conv17 = tf.layers.batch_normalization(conv17,training = bool_train,name = \"norm_17\")\n conv17 = tf.nn.leaky_relu(conv17,name = \"activation\")\n variable_summaries_weights_biases(right_1_1_conv)\n variable_summaries_weights_biases(right_1_1_conv_bias)\n assert(conv17.shape[1:] == [120,120,32])\n \n with tf.name_scope(\"Conv2\"):\n conv18 = tf.nn.conv2d(conv17,right_1_2_conv,(1,1,1,1),padding='VALID',name=\"convolve\")\n conv18 = tf.nn.bias_add(conv18,right_1_2_conv_bias,name = \"bias_add\")\n conv18 = tf.layers.batch_normalization(conv18,training = bool_train,name = \"norm_18\")\n conv18 = tf.sigmoid(conv18,name=\"activation\")\n variable_summaries_weights_biases(right_1_2_conv)\n variable_summaries_weights_biases(right_1_2_conv_bias) \n assert(conv18.shape[1:] == [112,112,1]) \n \n return conv18\n\ndef compute_jaccard_cost(Y,Z3,batch_size) :\n ''' Computes the Jaccard Index and the Jaccard Cost.\n\n Description :\n The normal Jaccard index is non-differentiable. This function is an approximation to this index\n that makes this index differentiable.\n\n Arguments :\n Y -- np.array.\n Ground truth values of the mini-batch.\n Z3 -- np.array.\n The ouput vector from the forward propagation.\n batch_size -- Int.\n The number of images in a mini-batch.\n\n Returns :\n Jaccard -- np.array.\n Contains the jaccard values for each input image\n Jaccard_loss -- np.array.\n Contains the jaccard loss for each input image.\n '''\n \n with tf.name_scope(\"Costs\") :\n \n with tf.name_scope(\"Jaccard_Loss\") :\n\n # Intersection\n nr = tf.multiply(Y,Z3)\n\n # Union\n dr = Y + Z3 -nr\n\n # Jaccard = Intersection/Union\n Jaccard = tf.divide( tf.reshape(tf.reduce_sum(nr,axis = [1,2,3]),shape = (batch_size,1)) , tf.reshape(tf.reduce_sum(dr,axis = [1,2,3] ),shape = (batch_size,1)) )\n \n Jaccard_loss = -tf.log(Jaccard)\n \n variable_summaries_weights_biases(Jaccard)\n \n return Jaccard,Jaccard_loss\n \n\n############################################ NETWORK BUILDING ############################################\n\n############################################# MODEL BUILDING #############################################\n\ndef model(img_rows,img_cols,num_channels,learning = 0.003,num_epochs = 50,batch_size = 16):\n\n # Tensorflow Graph\n X,Y = create_placeholders(img_rows,img_cols,num_channels)\n \n parameters = initialize_parameters()\n \n Z3 = forward_prop(X,parameters,bool_train = True)\n \n Jaccard,Jaccard_loss = compute_jaccard_cost(Y,Z3,batch_size)\n\n global_step = tf.Variable(0, trainable=False)\n starter_learning_rate = learning\n\n learning_rate = tf.train.exponential_decay(starter_learning_rate,global_step,10000,decay_rate = 1)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n with tf.name_scope(\"Optimizer\") :\n optimizer = tf.train.AdamOptimizer(learning_rate).minimize(Jaccard_loss,global_step=global_step,name = \"Adam\")\n # Tensorflow Graph\n \n init = tf.global_variables_initializer()\n \n # Creating the saving object \n saver = tf.train.Saver(max_to_keep = 10000,var_list = tf.global_variables())\n \n merged = tf.summary.merge_all()\n with tf.Session() as sess:\n\n train_writer = tf.summary.FileWriter(\"Summaries/Road_tar\",sess.graph)\n sess.run(init)\n \n jaccard_list = []\n epoch_list = []\n \n for epoch in range(num_epochs) :\n \n print(\"Epoch Number : \" + str(epoch))\n \n jaccards = 0\n \n counting = 0\n for i in range(1500) :\n \n \n with open(\"./Data_training/Road/train\" + \"_\" + str(i) + \"_\" + \".pkl\",\"rb\") as f :\n X_input = pickle.load(f)\n \n with open(\"./Data_training/Road/test\" + \"_\" + str(i) + \"_\" + \".pkl\",\"rb\") as f :\n Y_input = pickle.load(f)\n\n if X_input is None or Y_input is None :\n print(\"Something is wrong\")\n return None\n\n X_input = X_input/2047\n \n if ((epoch%1 == 0) and (counting == 1499)):\n _,batch_jaccard,summary = sess.run([optimizer,Jaccard,merged], feed_dict = {X:X_input[:,:,:,0:9],Y:Y_input}) \n else:\n _,batch_jaccard,learning_rate_val = sess.run([optimizer,Jaccard,learning_rate], feed_dict = {X:X_input[:,:,:,0:9],Y:Y_input})\n \n X_input = None\n Y_input = None\n \n jaccards += np.sum(batch_jaccard)/batch_size\n \n counting += 1\n \n print(jaccards/1500)\n print(learning_rate_val)\n \n jaccard_list.append(jaccards/1500)\n epoch_list.append(epoch)\n \n if epoch == 0:\n highest_jaccard = jaccards \n \n if epoch%1 == 0:\n \n train_writer.add_summary(summary,global_step = epoch)\n \n if highest_jaccard <= jaccards :\n \n highest_jaccard = jaccards\n \n path = os.path.join(os.getcwd(),'Parameters/Road_tar/track-model.ckpt')\n saver.save(sess,path,global_step=epoch) \n \n train_writer.close()\n \n \n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.set_ylabel(\"Jaccard\")\n ax1.set_xlabel(\"Epochs\")\n ax1.plot(epoch_list,jaccard_list)\n plt.show()\n plt.close()\n \n \n############################################# MODEL BUILDING #############################################\n\nif __name__ == '__main__':\n\n img_rows=112\n img_cols=112\n num_channels=9\n \n model(img_rows,img_cols,num_channels)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"train_road_tar.py","file_name":"train_road_tar.py","file_ext":"py","file_size_in_byte":38752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"314199502","text":"import copy\nimport os\nfrom os.path import join\nimport sys\nimport math\nimport itertools\n\nsys.path.append('./python/')\nimport config\nconfig.SCALE = config.PRES_SCALE\nconfig.BASE_WIDTH = config.PRES_WIDTH\nconfig.BASE_HEIGHT = config.PRES_HEIGHT\nconfig.TITLE_FONTSIZE = config.PRES_TITLE_FONTSIZE\nconfig.SUBTITLE_FONTSIZE = config.PRES_SUBTITLE_FONTSIZE\nconfig.LABEL_FONTSIZE = config.PRES_LABEL_FONTSIZE\nconfig.TICK_FONTSIZE = config.PRES_TICK_FONTSIZE\nimport inversion as inv\nimport format_plots as fp\n\nimport xarray as xr\nimport numpy as np\n\nimport pandas as pd\nfrom scipy.sparse import diags, identity\nfrom scipy import linalg, stats\n\nfrom matplotlib import cm, colorbar, colors, rcParams\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom matplotlib.collections import PolyCollection\nimport matplotlib.pyplot as plt\nimport matplotlib.table as tbl\nimport matplotlib.image as mpimg\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.ndimage import zoom\nimport cartopy.crs as ccrs\nimport cartopy\nfrom cartopy.mpl.patch import geos_to_path\n\n#########################\n### PLOTTING DEFAULTS ###\n#########################\n\n# rcParams default\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = 'AppleGothic'\nrcParams['font.size'] = config.LABEL_FONTSIZE*config.SCALE\nrcParams['text.usetex'] = True\n# rcParams['mathtext.fontset'] = 'stixsans'\nrcParams['text.latex.preamble'] = r'\\usepackage{cmbright}'\nrcParams['axes.titlepad'] = 10\n\n# Colormaps\nc = plt.cm.get_cmap('inferno', lut=10)\nplasma_trans = fp.cmap_trans('plasma')\nplasma_trans_r = fp.cmap_trans('plasma_r')\nrdbu_trans = fp.cmap_trans_center('RdBu_r', nalpha=70)\n\n# Small (i.e. non-default) figure settings\nsmall_fig_kwargs = {'max_width' : 4.5,\n 'max_height' : 4.25}\nsmall_map_kwargs = {'draw_labels' : False}\n\n######################\n### FILE LOCATIONS ###\n######################\nmain = '/Users/hannahnesser/Documents/Harvard/Research/Reduced_Rank_Jacobian'\nplots = join(main, 'presentation_plots')\ncode = join(main, 'python')\ninputs = join(main, 'input')\n\n#################\n### LOAD DATA ###\n#################\n\n# Clusters\nclusters = xr.open_dataarray(join(inputs, 'clusters_1x125.nc'))\nclusters_plot = xr.open_dataarray(join(inputs, 'clusters_1x125_plot.nc'))\n\n# Estimated, true, and reduced-dimension Jacobian\nk_est = xr.open_dataarray(join(inputs, 'k_est.nc'))\nk_est_sparse = xr.open_dataarray(join(inputs, 'k_est_sparse.nc'))\nk_true = xr.open_dataarray(join(inputs, 'k_true.nc'))\nk_rd = pd.read_csv(join(inputs, 'k_rd.csv'), header=None).to_numpy()\n\n# Native-resolution prior and prior error\nxa = xr.open_dataarray(join(inputs, 'xa.nc'))\nxa_abs = xr.open_dataarray(join(inputs, 'xa_abs.nc'))\nsa_vec = xr.open_dataarray(join(inputs, 'sa_vec.nc'))\n\n# Reduced-dimension quantitites\nstate_vector_rd = pd.read_csv(join(inputs, 'state_vector_rd.csv'),\n header=None).to_numpy().reshape(-1,)\nxa_rd = pd.read_csv(join(inputs, 'xa_rd.csv'),\n header=None).to_numpy().reshape(-1,)\nxa_abs_rd = pd.read_csv(join(inputs, 'xa_abs_rd.csv'),\n header=None).to_numpy().reshape(-1,)\nsa_vec_rd = pd.read_csv(join(inputs, 'sa_vec_rd.csv'),\n header=None).to_numpy().reshape(-1,)\nxhat_long_rd = pd.read_csv(join(inputs, 'xhat_long_rd.csv'),\n header=None).to_numpy().reshape(-1,)\ndofs_long_rd = pd.read_csv(join(inputs, 'dofs_long_rd.csv'),\n header=None).to_numpy().reshape(-1,)\n\n# Vectorized observations and error\ny = xr.open_dataarray(join(inputs, 'y.nc'))\ny_base = xr.open_dataarray(join(inputs, 'y_base.nc'))\nso_vec = xr.open_dataarray(join(inputs, 'so_vec.nc'))\n\n# Gridded observations\nobs = pd.read_csv(join(inputs, 'sat_obs.gosat.00.m'),\n delim_whitespace=True,\n header=0)\nobs['GOSAT'] *= 1e9\nobs['model'] *= 1e9\nobs = obs[obs['GLINT'] == False]\nobs = obs[['NNN', 'LON', 'LAT', 'GOSAT', 'model']]\nobs = obs.rename(columns={'LON' : 'lon',\n 'LAT' : 'lat',\n 'NNN' : 'Nobs'})\n\n#####################\n### SET CONSTANTS ###\n#####################\n\nRF = 20\n\n#####################\n### TRUE JACOBIAN ###\n#####################\n\n# Create a true Reduced Rank Jacobian object\ntrue = inv.ReducedRankJacobian(k_true.values, xa.values, sa_vec.values,\n y.values, y_base.values, so_vec.values)\ntrue.model_runs = true.nstate\ntrue.xa_abs = xa_abs*1e3\ntrue.rf = RF\n\n# Complete an eigendecomposition of the prior pre-\n# conditioned Hessian, filling in the eigenvalue\n# and eigenvector attributes of true.\ntrue.edecomp()\n\n# Solve the inversion, too.\ntrue.solve_inversion()\n\n########################\n### INITIAL JACOBIAN ###\n########################\n\nest0 = inv.ReducedRankJacobian(k_est.values, xa.values, sa_vec.values,\n y.values, y_base.values, so_vec.values)\nest0.xa_abs = xa_abs*1e3\nest0.rf = RF\nest0.edecomp()\nest0.solve_inversion()\n\n##################################\n### REDUCED DIMENSION JACOBIAN ###\n##################################\nest_rd = inv.ReducedRankJacobian(k_rd, xa_rd, sa_vec_rd,\n y.values, y_base.values, so_vec.values)\nest_rd.rf = RF*est_rd.nstate/true.nstate\nest_rd.xa_abs = xa_abs_rd\nest_rd.xhat_long = xhat_long_rd\nest_rd.dofs_long = dofs_long_rd\nest_rd.state_vector = state_vector_rd\nest_rd.model_runs = 534\nest_rd.solve_inversion()\n\nprint(est_rd.dofs.sum())\n\n#############################\n### REDUCED RANK JACOBIAN ###\n#############################\n\n# First set of updates\nest1 = est0.update_jacobian(true.k, snr=2.5)\n\n# Second set\nest2 = est1.update_jacobian(true.k, rank=est0.get_rank(pct_of_info=0.985))\nest2.model_runs += 1\n\n# second set\nest1a = est0.update_jacobian(true.k,\n snr=1)\nest2a = est1a.update_jacobian(true.k, rank=est2.model_runs-est1a.model_runs)\n\n# third set\nest1b = est0.update_jacobian(true.k,\n snr=4)\nest2b = est1b.update_jacobian(true.k, rank=est2.model_runs-est1b.model_runs)\n\n# Filter\nmask = np.diag(est2.a) > 0.01\nest2_f, true_f = est2.filter(true, mask)\n\n# Print diagnostics\nprint('-----------------------')\nprint('MODEL RUNS: ', est2.model_runs)\nprint('CONSTRAINED CELLS: ', len(est2_f.xhat))\nprint('DOFS: ', np.trace(est2_f.a))\nprint('-----------------------\\n')\n\n###############################################\n### REDUCED-RANK JACOBIAN SENSITIVITY TESTS ###\n###############################################\n\n# Open summary files\nr2_summ = np.load(join(inputs, 'r2_summary.npy'))\nnc_summ = np.load(join(inputs, 'nc_summary.npy'))\nnm_summ = np.load(join(inputs, 'nm_summary.npy'))\ndofs_summ = np.load(join(inputs, 'dofs_summary.npy'))\n\n#####################################\n### FIGURE 00: GOSAT OBSERVATIONS ###\n#####################################\nfig01, ax = fp.make_axes(maps=True, lats=obs['lat'], lons=obs['lon'])\n\ncol = ax.scatter(obs['lon'], obs['lat'], c=obs['GOSAT'],\n cmap='inferno', vmin=1700, vmax=1800,\n s=20)\n\nax = fp.add_title(ax, r'GOSAT XCH$_4$ (July 2009)')\nax = fp.format_map(ax, obs['lat'], obs['lon'])\nax.set_xlim(clusters_plot.lon.min(), clusters_plot.lon.max())\nax.set_ylim(clusters_plot.lat.min(), clusters_plot.lat.max())\n\ncax = fp.add_cax(fig01, ax)\ncbar = plt.colorbar(col, cax=cax)\ncbar = fp.format_cbar(cbar, 'XCH4 (ppb)')\n\n# Save plot\nfig01.savefig(join(plots, 'fig00_gosat_obs.png'),\n bbox_inches='tight', dpi=300)\nprint('Saved fig00_gosat_obs.png')\n\n###################################\n### FIGURE 00: JACOBIAN COLUMNS ###\n###################################\nn = 750\nfig01, ax = fp.make_axes(maps=True, lats=obs['lat'], lons=obs['lon'])\n\ncol = ax.scatter(obs['lon'], obs['lat'], c=est0.k[:, n],\n cmap=fp.cmap_trans('Reds'), vmin=0, vmax=0.1,\n s=20)\n\nax = fp.add_title(ax, r'Initial estimate Jacobian matrix K$_{:, %d}$' % n)\nax = fp.format_map(ax, obs['lat'], obs['lon'])\nax.set_xlim(clusters_plot.lon.min(), clusters_plot.lon.max())\nax.set_ylim(clusters_plot.lat.min(), clusters_plot.lat.max())\n\ncax = fp.add_cax(fig01, ax)\ncbar = plt.colorbar(col, cax=cax)\ncbar = fp.format_cbar(cbar, 'dy/dx$_{%d}$ (ppb)' % n)\n\n# Save plot\nfig01.savefig(join(plots, f'fig00_est0_k_{n}.png'),\n bbox_inches='tight', dpi=300)\nprint(f'Saved fig00_est0_k_{n}.png')\n\nfig01, ax = fp.make_axes(maps=True, lats=obs['lat'], lons=obs['lon'])\n\ncol = ax.scatter(obs['lon'], obs['lat'], c=true.k[:, n],\n cmap=fp.cmap_trans('Reds'), vmin=0, vmax=0.1,\n s=20)\n\nax = fp.add_title(ax, r'Native-resolution Jacobian matrix K$_{:, %d}$' % n)\nax = fp.format_map(ax, obs['lat'], obs['lon'])\nax.set_xlim(clusters_plot.lon.min(), clusters_plot.lon.max())\nax.set_ylim(clusters_plot.lat.min(), clusters_plot.lat.max())\n\ncax = fp.add_cax(fig01, ax)\ncbar = plt.colorbar(col, cax=cax)\ncbar = fp.format_cbar(cbar, 'dy/dx$_{%d}$ (ppb)' % n)\n\n# Save plot\nfig01.savefig(join(plots, f'fig00_true_k_{n}.png'),\n bbox_inches='tight', dpi=300)\nprint(f'Saved fig00_true_k_{n}.png')\n\n\n###############################################\n### FIGURE 1: RANK AND DIMENSION FLOW CHART ###\n###############################################\n\n# General settings\ndef flow_chart_settings(ax):\n ax.add_feature(cartopy.feature.OCEAN, facecolor='white', zorder=2)\n ax.coastlines(color='grey', zorder=5, linewidth=0.5)\n ax.outline_patch.set_visible(False)\n return ax\n\ntitle_kwargs = {'y' : 1,\n 'pad' : (1.5*config.TITLE_PAD +\n 1*config.SUBTITLE_FONTSIZE*config.SCALE)}\n\n## Original dimension\nfig1a, ax = est0.plot_multiscale_grid(clusters_plot, colors='0.5', zorder=3,\n linewidths=0.5,\n fig_kwargs=small_fig_kwargs,\n map_kwargs=small_map_kwargs)\nax = flow_chart_settings(ax)\nax = fp.add_title(ax, 'Native resolution', **title_kwargs)\nax = fp.add_subtitle(ax, r'dimension $n$, rank $> k$')\nfp.save_fig(fig1a, loc=plots, name='fig1a_dimn_rankn')\n\n## Reduced rank\ntrue.evec_sum = true.evecs[:, :3].sum(axis=1)\nfig1b, ax, c = true.plot_state('evec_sum', clusters_plot,\n title='', cbar=False, cmap='RdBu_r',\n vmin=-0.1, vmax=0.1, default_value=0,\n fig_kwargs=small_fig_kwargs,\n map_kwargs=small_map_kwargs)\nax = flow_chart_settings(ax)\nax = fp.add_subtitle(ax, 'Reduced rank',\n fontsize=config.TITLE_FONTSIZE*config.SCALE,\n y=0, va='top', xytext=(0, -config.TITLE_PAD))\nax = fp.add_subtitle(ax, r'dimension $n$, rank $k$',\n y=0, va='top',\n xytext=(0,\n -(1.5*config.TITLE_PAD +\n config.TITLE_FONTSIZE*config.SCALE)))\nfp.save_fig(fig1b, loc=plots, name='fig1b_dimn_rankk')\n\n## Reduced rank and dimension (not aggregate)\n# Base images\nfor i in range(3):\n fig1c, ax, c = true.plot_state(('evecs', i), clusters_plot,\n title='', cbar=False, cmap='RdBu_r',\n vmin=-0.1, vmax=0.1,default_value=0,\n fig_kwargs=small_fig_kwargs,\n map_kwargs=small_map_kwargs)\n ax = flow_chart_settings(ax)\n fp.save_fig(fig1c, loc=plots, name='fig1c_evec' + str(i))\n\n# Reduced dimension (aggregate)\nfig1d, ax = est_rd.plot_multiscale_grid(clusters_plot,\n colors='0.5', zorder=3,\n linewidths=0.5,\n fig_kwargs=small_fig_kwargs,\n map_kwargs=small_map_kwargs)\nax = flow_chart_settings(ax)\nax = fp.add_title(ax, 'Reduced dimension', **title_kwargs)\nax = fp.add_subtitle(ax, r'dimension $k$, rank $k$')\nfp.save_fig(fig1d, loc=plots, name='fig1d_dimk_rankk_ms')\n\n# # Compile plots\n# fig1, ax1 = fp.get_figax(rows=2, cols=2, maps=True,\n# lats=clusterS_plot.lat, lons=clusters_plot.lon)\n\n# Some labels\nfig1e, ax = fp.get_figax()\nax.annotate(r'$\\mathbf{\\Gamma} (k \\times n)$',\n xy=(0.5, 0.75), xycoords='axes fraction',\n fontsize=config.SUBTITLE_FONTSIZE*config.SCALE)\nax.annotate(r'$\\mathbf{\\Gamma}^* (n \\times k)$',\n xy=(0.5, 0.5), xycoords='axes fraction',\n fontsize=config.SUBTITLE_FONTSIZE*config.SCALE)\nax.annotate(r'$\\mathbf{\\Pi} (n \\times n)$',\n xy=(0.5, 0.25), xycoords='axes fraction',\n fontsize=config.SUBTITLE_FONTSIZE*config.SCALE)\nax.annotate('Pattern 1',\n xy=(0.25, 0.75), xycoords='axes fraction',\n fontsize=config.SUBTITLE_FONTSIZE*config.SCALE)\nax.annotate('Pattern 2',\n xy=(0.25, 0.5), xycoords='axes fraction',\n fontsize=config.SUBTITLE_FONTSIZE*config.SCALE)\nax.annotate('Pattern 3',\n xy=(0.25, 0.25), xycoords='axes fraction',\n fontsize=config.SUBTITLE_FONTSIZE*config.SCALE)\nfp.save_fig(fig1e, loc=plots, name='fig1e_labels')\n\n########################################################################\n### FIGURE 2: AVERAGING KERNEL SENSITIVITY TO PRIOR AND OBSERVATIONS ###\n########################################################################\n\n# True averaging kernel\ntitle = 'Native-resolution averaging\\nkernel sensitivities'\navker_cbar_kwargs = {'title' : r'$\\partial\\hat{x}_i/\\partial x_i$',\n 'horizontal' : True}\navker_kwargs = {'cmap' : plasma_trans, 'vmin' : 0, 'vmax' : 1,\n 'cbar_kwargs' : avker_cbar_kwargs}\n # 'fig_kwargs' : small_fig_kwargs,\n # 'map_kwargs' : small_map_kwargs}\nfig2a, ax, c = true.plot_state('dofs', clusters_plot, title=title,\n **avker_kwargs)\nax.text(0.025, 0.05, 'DOFS = %d' % np.trace(true.a),\n fontsize=config.LABEL_FONTSIZE*config.SCALE,\n transform=ax.transAxes)\nfp.save_fig(fig2a, plots, 'fig2a_true_averaging_kernel')\n\n# Initial estimate averaging kernel\ntitle = 'Initial estimate averaging\\nkernel sensitivities'\navker_cbar_kwargs = {'title' : r'$\\partial\\hat{x}_i/\\partial x_i$',\n 'horizontal' : True}\navker_kwargs['cbar_kwargs'] = avker_cbar_kwargs\nfig2b, ax, c = est0.plot_state('dofs', clusters_plot, title=title,\n **avker_kwargs)\nax.text(0.025, 0.05, 'DOFS = %d' % np.trace(est0.a),\n fontsize=config.LABEL_FONTSIZE*config.SCALE,\n transform=ax.transAxes)\nfp.save_fig(fig2b, plots, 'fig2b_est0_averaging_kernel')\n\n# Prior error\ntrue.sd_vec = true.sa_vec**0.5\ntrue.sd_vec_abs = true.sd_vec*true.xa_abs\ncbar_kwargs = {'title' : 'Tg/month'}\nfig2c, ax, c = true.plot_state('sd_vec_abs', clusters_plot,\n title='Prior error standard deviation',\n cmap=fp.cmap_trans('viridis'),\n vmin=0, vmax=15,\n fig_kwargs=small_fig_kwargs,\n cbar_kwargs=cbar_kwargs,\n map_kwargs=small_map_kwargs)\nfp.save_fig(fig2c, plots, 'fig2c_prior_error')\n\n# Observational density\nlat_res = np.diff(clusters_plot.lat)[0]\nlat_edges = np.append(clusters_plot.lat - lat_res/2,\n clusters_plot.lat[-1] + lat_res/2)\n# lat_edges = lat_edges[::2]\nobs['lat_edges'] = pd.cut(obs['lat'], lat_edges, precision=4)\n\nlon_res = np.diff(clusters_plot.lon)[0]\nlon_edges = np.append(clusters_plot.lon - lon_res/2,\n clusters_plot.lon[-1] + lon_res/2)\n# lon_edges = lon_edges[::2]\nobs['lon_edges'] = pd.cut(obs['lon'], lon_edges, precision=4)\n\nobs_density = obs.groupby(['lat_edges', 'lon_edges']).count()\nobs_density = obs_density['Nobs'].reset_index()\nobs_density['lat'] = obs_density['lat_edges'].apply(lambda x: x.mid)\nobs_density['lon'] = obs_density['lon_edges'].apply(lambda x: x.mid)\nobs_density = obs_density.set_index(['lat', 'lon'])['Nobs']\nobs_density = obs_density.to_xarray()\n\ntitle = 'GOSAT observation density\\n(July 2009)'\nviridis_trans_long = fp.cmap_trans('viridis', nalpha=90, ncolors=300)\ncbar_kwargs = {'ticks' : np.arange(0, 25, 5),\n 'title' : 'Count'}\nfig2d, ax, c = true.plot_state_format(obs_density, title=title,\n vmin=0, vmax=10, default_value=0,\n cmap=viridis_trans_long,\n fig_kwargs=small_fig_kwargs,\n cbar_kwargs=cbar_kwargs,\n map_kwargs=small_map_kwargs)\nfp.save_fig(fig2d, plots, 'fig2d_gosat_obs_density')\n\n##############################################\n### FIGURE 3 : CONSOLIDATED POSTERIOR PLOT ###\n##############################################\n\nfig3a, ax3a = fp.get_figax(rows=1, cols=3, maps=True,\n lats=clusters_plot.lat, lons=clusters_plot.lon)\nfig3b, ax3b = fp.get_figax(rows=1, cols=3, maps=True,\n lats=clusters_plot.lat, lons=clusters_plot.lon)\n\ndef add_dofs_subtitle(inversion_object, ax,\n state_vector_element_string='cell'):\n subtitle = ('%d DOFS (%.2f/%s)\\n%d model simulations'\n % (round(np.trace(inversion_object.a)),\n (np.trace(inversion_object.a)/inversion_object.nstate),\n state_vector_element_string,\n inversion_object.model_runs + 1))\n ax = fp.add_subtitle(ax, subtitle)\n return ax\n\ntitle_kwargs = {'y' : 1,\n 'pad' : (1.5*config.TITLE_PAD +\n 2*config.SUBTITLE_FONTSIZE*config.SCALE)}\nstate_cbar_kwargs = {'ticks' : np.arange(-1, 4, 1)}\ndofs_cbar_kwargs = {'ticks' : np.arange(0, 1.1, 0.2)}\nstate_kwargs = {'default_value' : 1, 'cmap' : 'RdBu_r',\n 'vmin' : -1, 'vmax' : 3,\n 'cbar' : False, 'cbar_kwargs' : state_cbar_kwargs,\n 'title_kwargs' : title_kwargs, 'map_kwargs' : small_map_kwargs}\ndofs_kwargs = {'cmap' : plasma_trans, 'vmin' : 0, 'vmax' : 1,\n 'cbar' : False, 'cbar_kwargs' : dofs_cbar_kwargs,\n 'title_kwargs' : title_kwargs, 'map_kwargs' : small_map_kwargs}\ntitles = ['Native resolution', 'Reduced dimension', 'Reduced rank']\nsve_string = ['cell', 'cluster', 'cell']\nquantities = ['', '_long', '']\n\nfor i, inv in enumerate([true, est_rd, est2]):\n state_kwargs['title'] = titles[i]\n state_kwargs['fig_kwargs'] = {'figax' : [fig3a, ax3a[i]]}\n dofs_kwargs['title'] = '' #'titles[i]'\n dofs_kwargs['fig_kwargs'] = {'figax' : [fig3b, ax3b[i]]}\n\n # Posterior emissions\n fig3a, ax3a[i], ca = inv.plot_state('xhat' + quantities[i],\n clusters_plot, **state_kwargs)\n ax3a[i] = add_dofs_subtitle(inv, ax3a[i], sve_string[i])\n\n # Averaging kernel sensitivities\n fig3b, ax3b[i], cb = inv.plot_state('dofs' + quantities[i],\n clusters_plot, **dofs_kwargs)\n # ax3b[i] = add_dofs_subtitle(inv, ax3b[i], sve_string[i])\n\n# Polishing posterior emissions\n# Colorbar\ncax = fp.add_cax(fig3a, ax3a)\ncbar = fig3a.colorbar(ca, cax=cax, **state_cbar_kwargs)\ncbar = fp.format_cbar(cbar, cbar_title='Scaling factors')\n\n# Label\nax3a[0].text(-0.3, 0.5, 'Posterior\\nscaling\\nfactors',\n fontsize=config.TITLE_FONTSIZE*config.SCALE,\n rotation=90, ha='center', va='center',\n transform=ax3a[0].transAxes)\n# Save\nfp.save_fig(fig3a, plots, 'fig3a_posterior_mean_summary')\n\n# Polishing averaging kernel sensitivities\n# Colorbar\ncax = fp.add_cax(fig3b, ax3b)\ncbar = fig3b.colorbar(cb, cax=cax, **dofs_cbar_kwargs)\ncbar = fp.format_cbar(cbar, cbar_title=r'$\\partial\\hat{x}_i/\\partial x_i$')\n\n# Label\nax3b[0].text(-0.3, 0.5, 'Averaging\\nkernel\\nsensitivities',\n fontsize=config.TITLE_FONTSIZE*config.SCALE,\n rotation=90, ha='center', va='center',\n transform=ax3b[0].transAxes)\n\n# Save\nfp.save_fig(fig3b, plots, 'fig3b_averaging_kernel_summary')\n\n#################################################\n### FIGURE 4: REDUCED RANK SENSITIVITY TESTS ###\n#################################################\n\nmin_mr = 0\nmax_mr = 1000\nincrement = 25\nn = int((max_mr - min_mr)/increment) + 1\n\ndef mr2n(model_runs,\n min_mr=min_mr, max_mr=max_mr, max_n=n):\n '''This function converts a number of model runs\n to an index along an axis from 0 to n'''\n x0 = min_mr\n y0 = 0\n slope = (max_n - 1)/(max_mr - min_mr)\n func = lambda mr : slope*(mr - x0) + y0\n return func(model_runs)\n\n# R2 plot\n# fig4, ax = fp.get_figax()\nfigsize = fp.get_figsize(aspect=0.665, rows=1, cols=1)\nfig4, ax = plt.subplots(2, 1,\n figsize=figsize,\n gridspec_kw={'height_ratios': [1, 4]})\nplt.subplots_adjust(hspace=0.4)\ncax = fp.add_cax(fig4, ax[1])\n# ax = fp.add_title(ax, r'Posterior Emissions r$^2$'))\nax[0] = fp.add_title(ax[0], 'Reduced Rank DOFS', pad=config.TITLE_PAD*2)\n# ax = fp.add_title(ax, 'Number of Constrained Grid Cells')\n\n# Plot DOFS contours (shaded)\n# cf = ax.contourf(r2_summ, levels=np.linspace(0, 1, 25), vmin=0, vmax=1)\ncf = ax[1].contourf(dofs_summ,\n levels=np.linspace(0, true.dofs.sum(), 25),\n vmin=0, vmax=200, cmap='plasma')\n# cf = ax.contourf(nc_summ, levels=np.arange(0, 2000, 100),\n# vmin=0, vmax=2000)\n\n# Get the ridge values\ndofs_summ_short = dofs_summ[1:, 1:]\ndofs_summ_flat = dofs_summ_short.flatten().reshape((-1, 1))\nnm_summ_short = nm_summ[1:, 1:].flatten().reshape((-1, 1))\nsumm_short = np.concatenate([nm_summ_short, dofs_summ_flat], axis=1)\nsumm_short = pd.DataFrame(data=summ_short, columns=['model_runs', 'DOFS'])\nsumm_short = summ_short.groupby('model_runs').max().reset_index(drop=True)\n\nx, y = np.where(np.isin(dofs_summ_short, summ_short['DOFS']))\n\ndofs_summ_short = dofs_summ[1:, 1:]\nnm_summ_short = nm_summ[1:, 1:]\nx = []\ny = []\nz = []\nnp.set_printoptions(precision=0)\nfor i in np.unique(nm_summ_short):\n mask_nm = np.where(nm_summ_short == i)\n mask_dofs_max = np.argmax(dofs_summ_short[mask_nm])\n dofs_max = dofs_summ_short[mask_nm][mask_dofs_max]\n yi, xi = np.where((dofs_summ_short == dofs_max) & (nm_summ_short == i))\n x.append(xi[0] + 1)\n y.append(yi[0] + 1)\n z.append(dofs_max)\n\n# ax[1].plot(x, y, c='0.25')\nx = np.unique(nm_summ_short)\nz = np.array(z)\nax[0].plot(x[x <= 1000], z[x <= 1000], c='0.25', ls='--')\nax[0].scatter(est2.model_runs, est2.dofs.sum(),\n zorder=10, c='0.25', s=75, marker='*')\nax[0].set_xticks(np.arange(200, 1010, 200))\nax[0].set_xlim(0, 1000)\nax[0].set_ylim(50, 216)\nax[0].set_facecolor('0.98')\nax[0] = fp.add_labels(ax[0],\n xlabel='Total Model Runs',\n ylabel='Optimal\\nDOFS',\n labelpad=config.LABEL_PAD/2)\n\n# Plot number of model run contours (lines)\nlevels = [250, 750, 1250]\n# locs = [(n/8, n/8),\n# (n/2, n/2),\n# (5*n/8, 5*n/8)]\nlocs = [(mr2n(l)/2, mr2n(l)/2) for l in levels]\n\n# nm_summ[0, :] -= 1\n# nm_summ[1:, 0] -= 1\ncl = ax[1].contour(nm_summ, levels=levels, colors='white',\n linestyles='dotted')\nax[1].clabel(cl, cl.levels, inline=True, manual=locs, fmt='%d',\n fontsize=config.TICK_FONTSIZE*config.SCALE)\ncl = ax[1].contour(nm_summ, levels=[est2.model_runs], colors='0.25',\n linestyles='dashed')\nax[1].clabel(cl, cl.levels, inline=True,\n manual=[(mr2n(est2.model_runs)/2, mr2n(est2.model_runs)/2)],\n fmt='%d',\n fontsize=config.TICK_FONTSIZE*config.SCALE)\n\nax[1].scatter(mr2n(est1.model_runs),\n mr2n(est2.model_runs-est1.model_runs),\n zorder=10,\n c='0.25',\n s=75, marker='*')\nax[1].scatter(mr2n(est1a.model_runs),\n mr2n(est2a.model_runs-est1a.model_runs),\n zorder=10, c='0.25', s=75, marker='.')\nax[1].scatter(mr2n(est1b.model_runs),\n mr2n(est2b.model_runs-est1b.model_runs),\n zorder=10, c='0.25', s=75, marker='.')\n\n# cbar = fig4.colorbar(cf, cax=cax, ticks=np.linspace(0, 1, 6))\ncbar = fig4.colorbar(cf, cax=cax,\n ticks=np.arange(0, true.dofs.sum(), 50))\n# cbar = fig4.colorbar(cf, cax=cax, ticks=np.arange(0, 2000, 500))\n\n# cbar = fp.format_cbar(cbar, r'r$^2$')\ncbar = fp.format_cbar(cbar, 'DOFS')\n# cbar = fp.format_cbar(cbar, 'Number of Constrained Cells')\n\n# Axis and tick labels\nax[1] = fp.add_labels(ax[1],\n 'First Update Model Runs',\n 'Second Update Model Runs',\n labelpad=config.LABEL_PAD/2)\n\n# ....This is still hard coded\nax[1].set_xticks(np.arange(4, n, (n-4)/9))\nax[1].set_xticklabels(np.arange(100, 1100, 100),\n fontsize=config.TICK_FONTSIZE*config.SCALE)\nax[1].set_xlim(0, (n-1)*750/975)\n\nax[1].set_yticks(np.arange(4, n, (n-4)/9))\nax[1].set_yticklabels(np.arange(100, 1100, 100),\n fontsize=config.TICK_FONTSIZE*config.SCALE)\nax[1].set_ylim(0, (n-1)*750/975)\nax[1].set_aspect('equal')\n\nfp.save_fig(fig4, plots, 'fig4_dofs_comparison')\n\n############################################################\n### FIGURE 5: EST2_F POSTERIOR COMPARSION SCATTER PLOTS ###\n############################################################\nfig5, _, _ = est2_f.full_analysis(true_f, clusters_plot)\n\nax = fig5.axes\nax[0].set_xticks([0, 5])\nax[0].set_yticks([0, 5])\n\nax[1].set_xticks([-10, 0, 10])\nax[1].set_yticks([-10, 0, 10])\n\nax[2].set_xticks([0.2, 0.4])\nax[2].set_yticks([0.2, 0.4])\n\nax[3].set_xticks([0, 0.5, 1])\nax[3].set_yticks([0, 0.5, 1])\n\nfp.save_fig(fig5, plots, 'fig5_posterior_scattter_comparison')\n\n","sub_path":"python/presentation_plots.py","file_name":"presentation_plots.py","file_ext":"py","file_size_in_byte":25824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"282111637","text":"##Script that automatically does PL measurements by adjusting the laser frequency\n##This measurement applies long excitation pulses up to 100 us\n##Chnl sends the excitation pulse, and sync the delay generator to drive the optical switch as a shutter\n\nimport numpy as np\nimport pyqtgraph as pg\nimport time\nimport csv\nimport os\n\nfrom PyQt5.Qsci import QsciScintilla, QsciLexerPython\nimport matplotlib.pyplot as plt\n\nfrom spyre import Spyrelet, Task, Element\nfrom spyre.widgets.task import TaskWidget\nfrom spyre.plotting import LinePlotWidget\nfrom spyre.widgets.rangespace import Rangespace\nfrom spyre.widgets.param_widget import ParamWidget\nfrom spyre.widgets.repository_widget import RepositoryWidget\n\nfrom lantz import Q_\nimport time\n\n\nfrom lantz.drivers.bristol import Bristol_771\nfrom toptica.lasersdk.client import NetworkConnection, Client\n\nclass PLThinFilm(Spyrelet):\n\trequires = {\n\t\t'wm': Bristol_771\n\t}\n\tqutag = None\n\tlaser = NetworkConnection('1.1.1.2')\n\n\tdef configureQutag(self):\n\t\tqutagparams = self.qutag_params.widget.get()\n\t\tstart = qutagparams['Start Channel']\n\t\tstop = qutagparams['Stop Channel']\n\t\t##True = rising edge, False = falling edge. Final value is threshold voltage\n\t\tself.qutag.setSignalConditioning(start,self.qutag.SIGNALCOND_MISC,True,1)\n\t\tself.qutag.setSignalConditioning(stop,self.qutag.SIGNALCOND_MISC,True,0.1)\n\t\tself.qutag.enableChannels((start,stop))\n\n\tdef homelaser(self,start):\n\t\tcurrent=self.wm.measure_wavelength()\n\t\twith Client(self.laser) as client:\n\t\t\twhile currentstart+0.001:\n\t\t\t\tsetting=client.get('laser1:ctl:wavelength-set', float)\n\t\t\t\toffset=current-start\n\t\t\t\tclient.set('laser1:ctl:wavelength-set', setting-offset)\n\t\t\t\ttime.sleep(3)\n\t\t\t\tcurrent=self.wm.measure_wavelength()\n\t\t\t\tprint(current, start)\n\n\tdef createHistogram(self,stoparray, timebase, bincount, period, index, wls):\n\t\thist = [0]*bincount\n\t\tfor stoptime in stoparray:\n\t\t\tbinNumber = int(stoptime*timebase*bincount/(period))\n\t\t\tif binNumber >= bincount:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\thist[binNumber]+=1\n\t\tout_name = \"D:\\\\Data\\\\12.22.2019_PL_34\\\\0field\"\n\t\tnp.savez(os.path.join(out_name,str(index)),hist,wls)\n\t\t#np.savez(os.path.join(out_name,str(index+40)),hist,wls)\n\t\tprint('Data stored under File Name: ' + self.exp_parameters.widget.get()['File Name'] + str(index))\n\n\n\t@Task()\n\tdef startpulse(self, timestep=100e-9):\n\n\t\t##Qutag Part\n\t\tself.configureQutag()\n\t\texpparams = self.exp_parameters.widget.get()\n\t\twlparams = self.wl_parameters.widget.get()\n\t\tself.homelaser(wlparams['start'])\n\t\tprint('Laser Homed!')\n\t\tqutagparams = self.qutag_params.widget.get()\n\t\tlost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer\n\t\tstoptimestamp = 0\n\t\tsynctimestamp = 0\n\t\tbincount = qutagparams['Bin Count']\n\t\ttimebase = self.qutag.getTimebase()\n\t\tstart = qutagparams['Start Channel']\n\t\tstop = qutagparams['Stop Channel']\n\t\tfor i in range(expparams['# of points']):\n\t\t\t##Wavemeter measurements\n\t\t\tstoparray = []\n\t\t\tstartTime = time.time()\n\t\t\twls=[]\n\t\t\tlost = self.qutag.getLastTimestamps(True)\n\t\t\twhile time.time()-startTime < expparams['Measurement Time'].magnitude:\n\t\t\t\tlost = self.qutag.getLastTimestamps(True)\n\t\t\t\ttime.sleep(5*0.1)\n\t\t\t\ttimestamps = self.qutag.getLastTimestamps(True)\n\n\t\t\t\ttstamp = timestamps[0] # array of timestamps\n\t\t\t\ttchannel = timestamps[1] # array of channels\n\t\t\t\tvalues = timestamps[2] # number of recorded timestamps\n\t\t\t\tfor k in range(values):\n\t\t\t\t\t# output all stop events together with the latest start event\n\t\t\t\t\tif tchannel[k] == start:\n\t\t\t\t\t\tsynctimestamp = tstamp[k]\n\t\t\t\t\telse:\n\t\t\t\t\t\tstoptimestamp = tstamp[k]\n\t\t\t\t\t\tstoparray.append(stoptimestamp)\n\t\t\t\twls.append(str(self.wm.measure_wavelength()))\n\t\t\tself.createHistogram(stoparray, timebase, bincount, 0.1,i, wls)\n\t\t\tprint(i)\n\t\t\twith Client(self.laser) as client:\n\t\t\t\tsetting=client.get('laser1:ctl:wavelength-set', float)\n\t\t\t\tclient.set('laser1:ctl:wavelength-set', setting-0.006)\n\t\t\t\ttime.sleep(1)\n\n\t@Task()\n\tdef qutagInit(self):\n\t\tprint('qutag successfully initialized')\n\n\t@Element(name='Wavelength parameters')\n\tdef wl_parameters(self):\n\t\tparams = [\n\t# ('arbname', {'type': str, 'default': 'arbitrary_name'}),,\n\t\t('start', {'type': float, 'default': 1535.71}),\n\t\t('stop', {'type': float, 'default': 1535.50})\n\t\t]\n\t\tw = ParamWidget(params)\n\t\treturn w\n\n\t@Element(name='Experiment Parameters')\n\tdef exp_parameters(self):\n\t\tparams = [\n\t# ('arbname', {'type': str, 'default': 'arbitrary_name'}),,\n\t\t('# of points', {'type': int, 'default': 50}),\n\t\t('Measurement Time', {'type': int, 'default': 100, 'units':'s'}),\n\t\t('File Name', {'type': str})\n\t\t]\n\t\tw = ParamWidget(params)\n\t\treturn w\n\n\t@Element(name='QuTAG Parameters')\n\tdef qutag_params(self):\n\t\tparams = [\n\t# ('arbname', {'type': str, 'default': 'arbitrary_name'}),,\n\t\t('Start Channel', {'type': int, 'default': 0}),\n\t\t('Stop Channel', {'type': int, 'default': 1}),\n\t\t('Bin Count', {'type': int, 'default': 1000})\n\t\t]\n\t\tw = ParamWidget(params)\n\t\treturn w\n\n\t@startpulse.initializer\n\tdef initialize(self):\n\t\tself.wm.start_data()\n\n\t@startpulse.finalizer\n\tdef finalize(self):\n\t\tself.wm.stop_data()\n\t\tprint('Lifetime measurements complete.')\n\t\treturn\n\n\t@qutagInit.initializer\n\tdef initialize(self):\n\t\tfrom lantz.drivers.qutools import QuTAG\n\t\tself.qutag = QuTAG()\n\t\tdevType = self.qutag.getDeviceType()\n\t\tif (devType == self.qutag.DEVTYPE_QUTAG):\n\t\t\tprint(\"found quTAG!\")\n\t\telse:\n\t\t\tprint(\"no suitable device found - demo mode activated\")\n\t\tprint(\"Device timebase:\" + str(self.qutag.getTimebase()))\n\t\treturn\n\n\t@qutagInit.finalizer\n\tdef finalize(self):\n\t\treturn\n\n\n","sub_path":"spyre/spyre/spyrelets/T2heterodyne_wavelength_spyrelet.py","file_name":"T2heterodyne_wavelength_spyrelet.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"510048411","text":"\nclass Solution(object):\n def plusOne(self, digits):\n\n carry = 1\n for i in reversed(range(len(digits))):\n digits[i] += int(carry)\n carry = digits[i] / 10\n digits[i] %= 10\n\n if int(carry):\n digits = [1] + digits\n\n return digits\n\nplusedOne = Solution().plusOne([9, 9, 9, 9])\n\nprint(plusedOne)\n","sub_path":"plus-one/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"485495737","text":"import random\nimport math\nimport vehicle_tools as tools\nimport stimulus\n\n# vy = 0\n\nclass vehicle(object):\n def __init__(self, xpos, ypos, z, stim, alpha):\n self.xpos = xpos\n self.ypos = ypos\n self.z = z # vehicle size scale\n self.stim = stim\n self.alpha = alpha # takes care of vehicle orienation\n\n def display(self):\n # sets up vehicle color intensity as per net velocity\n if(math.isnan(v)):\n c = color(0)\n else:\n c = color(int(255*(1-math.exp(-v))))\n stroke(c)\n # print(\"angle = \",self.alpha)\n self.displayBody()\n self.displayW1()\n self.displayW2()\n self.displaySensors()\n\n\n def displayBody(self):\n r = math.sqrt(20) * self.z\n angle = math.atan(1.0/2)\n theta = [2 * math.pi - angle, angle , math.pi - angle, math.pi + angle]\n # adding alpha to each theta\n theta = list(map(lambda t : t + self.alpha, theta))\n\n x1 = self.xpos+ r*math.cos(theta[0])\n y1 = self.ypos+ r*math.sin(theta[0])\n x2 = self.xpos+ r*math.cos(theta[1])\n y2 = self.ypos+ r*math.sin(theta[1])\n x3 = self.xpos+ r*math.cos(theta[2])\n y3 = self.ypos+ r*math.sin(theta[2])\n x4 = self.xpos+ r*math.cos(theta[3])\n y4 = self.ypos+ r*math.sin(theta[3])\n\n line(x1, y1, x2, y2)\n line(x2, y2, x3, y3)\n line(x3, y3, x4, y4)\n line(x4, y4, x1, y1)\n\n\n\n\n def displayW1(self):\n r = [math.sqrt(13) * self.z, math.sqrt(18) * self.z, math.sqrt(34) * self.z, math.sqrt(29) * self.z]\n angle = [math.atan(2.0/3), math.atan(1.0), math.atan(3.0/5), math.atan(2.0/5)]\n theta = [math.pi - angle[0], math.pi - angle[1] , math.pi - angle[2], math.pi - angle[3]]\n # adding alpha to each theta\n theta = list(map(lambda t : t + self.alpha, theta))\n\n x5 = self.xpos+ r[0]*math.cos(theta[0])\n y5 = self.ypos+ r[0]*math.sin(theta[0])\n x6 = self.xpos+ r[1]*math.cos(theta[1])\n y6 = self.ypos+ r[1]*math.sin(theta[1])\n x7 = self.xpos+ r[2]*math.cos(theta[2])\n y7 = self.ypos+ r[2]*math.sin(theta[2])\n x8 = self.xpos+ r[3]*math.cos(theta[3])\n y8 = self.ypos+ r[3]*math.sin(theta[3])\n\n line(x5, y5, x6, y6)\n line(x6, y6, x7, y7)\n line(x7, y7, x8, y8)\n line(x8, y8, x5, y5)\n\n\n\n\n def displayW2(self):\n r = [math.sqrt(13) * self.z, math.sqrt(18) * self.z, math.sqrt(34) * self.z, math.sqrt(29) * self.z]\n angle = [math.atan(2.0/3), math.atan(1.0), math.atan(3.0/5), math.atan(2.0/5)]\n theta = [math.pi + angle[0], math.pi + angle[1] , math.pi + angle[2], math.pi + angle[3]]\n # adding alpha to each theta\n theta = list(map(lambda t : t + self.alpha, theta))\n\n x9 = self.xpos+ r[0]*math.cos(theta[0])\n y9 = self.ypos+ r[0]*math.sin(theta[0])\n x10 = self.xpos+ r[1]*math.cos(theta[1])\n y10 = self.ypos+ r[1]*math.sin(theta[1])\n x11 = self.xpos+ r[2]*math.cos(theta[2])\n y11 = self.ypos+ r[2]*math.sin(theta[2])\n x12 = self.xpos+ r[3]*math.cos(theta[3])\n y12 = self.ypos+ r[3]*math.sin(theta[3])\n\n line(x9, y9, x10, y10)\n line(x10, y10, x11, y11)\n line(x11, y11, x12, y12)\n line(x12, y12, x9, y9)\n\n\n def displaySensors(self):\n r = [math.sqrt(40) * self.z, math.sqrt(40) * self.z, math.sqrt(16+4.0/9) * self.z, math.sqrt(16+4.0/9) * self.z]\n angle = [math.atan(1.0/3), math.atan(1.0/3), math.atan(1.0/6), math.atan(1.0/6)]\n theta = [2 * math.pi - angle[0], angle[1] , angle[2], 2 * math.pi - angle[3]]\n # adding alpha to each theta\n theta = list(map(lambda t : t + self.alpha, theta))\n\n x13 = self.xpos+ r[0]*math.cos(theta[0])\n y13 = self.ypos+ r[0]*math.sin(theta[0])\n x14 = self.xpos+ r[1]*math.cos(theta[1])\n y14 = self.ypos+ r[1]*math.sin(theta[1])\n x15 = self.xpos+ r[2]*math.cos(theta[2])\n y15 = self.ypos+ r[2]*math.sin(theta[2])\n x16 = self.xpos+ r[3]*math.cos(theta[3])\n y16 = self.ypos+ r[3]*math.sin(theta[3])\n\n # line(x13, y13, x14, y14)\n line(x14, y14, x15, y15)\n # line(x15, y15, x16, y16)\n line(x16, y16, x13, y13)\n\n def sensorLocation(self):\n r = [math.sqrt(40) * self.z, math.sqrt(40) * self.z, math.sqrt(16+4.0/9) * self.z, math.sqrt(16+4.0/9) * self.z]\n angle = [math.atan(1.0/3), math.atan(1.0/3), math.atan(1.0/6), math.atan(1.0/6)]\n theta = [2 * math.pi - angle[0], angle[1] , angle[2], 2 * math.pi - angle[3]]\n # adding alpha to each theta\n theta = list(map(lambda t : t + self.alpha, theta))\n x13 = self.xpos+ r[0]*math.cos(theta[0])\n y13 = self.ypos+ r[0]*math.sin(theta[0])\n x14 = self.xpos+ r[1]*math.cos(theta[1])\n y14 = self.ypos+ r[1]*math.sin(theta[1])\n return x13, y13, x14, y14\n\n def location(self):\n return self.xpos,self.ypos\n\n\n\n def move(self):\n global v\n v, v1, v2, a1, a2 = 0, 0, 0, 0, 0\n # acquiring instantaneous co-ordinates of sensors\n s1x,s1y,s2x,s2y = self.sensorLocation()\n m = len(self.stim)\n # processing each of m stimuli at a time\n for i in range(m): \n type = self.stim[i].type\n # decide on wiring weights based on vehicle type\n if(type == \"1a\" or type == \"1b\"):\n w1,w2,w3,w4 = 1,1,1,1\n elif(type == \"2a\" or type == \"3a\"):\n w1,w2,w3,w4 = 1,1,0,0 # parallel wiring\n elif(type == \"2b\" or type == \"3b\"):\n w1,w2,w3,w4 = 0,0,1,1 # crossed wiring\n else:\n w1,w2,w3,w4 = 0,0,0,0\n\n x,y = self.stim[i].location() # acquiring location of ith stimulus\n a1 += tools.activation(x,y,s1x,s1y,type) # activation in 1st sensor due to ith stimulus\n a2 += tools.activation(x,y,s2x,s2y,type) # activation in 2nd sensor due to ith stimulus\n\n v1 = w1*a1 + w4*a2 # velocity activation in 1st wheel\n v2 = w3*a1 + w2*a2 # velocity activation in 2nd wheel\n \n v = (v1 + v2) / 2 # net velocity of vehicle\n\n vx = v * math.cos(self.alpha)\n vy = v * math.sin(self.alpha)\n\n self.alpha += (v1 - v2) * .05\n\n # updating the new position as vehicle moves\n self.xpos = self.xpos + vx\n self.ypos = self.ypos + vy\n\n # to make vehciles reappear from other side of environment as they escape\n if self.xpos > .9*width:\n self.alpha += math.pi\n elif self.xpos <= 0:\n self.alpha += math.pi\n if self.ypos >= height:\n self.alpha += math.pi\n elif self.ypos <= 0:\n self.alpha += math.pi\n\n","sub_path":"build/vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"89575184","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}\nbase_url = 'http://www.qiushibaike.com/8hr/page/'\n\nfor num in range(1,5):\n\tprint('第{}页'.format(num))\n\n\tr = requests.get(base_url + str(num),headers = headers)\n\tcontent = r.text\n\tsoup = BeautifulSoup(content,'lxml')\n\n\tlinks = soup.find_all(class_ = 'contentHerf')\n\n\tfor link in links:\n\t\tjoke = link.span.get_text()\n\t\tprint(joke)\n\t\tprint('----')\n\n","sub_path":"py/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"554877842","text":"from __future__ import absolute_import\n\nfrom __future__ import division\n\nfrom __future__ import print_function\n\nimport pycocotools.coco as coco\n\nfrom pycocotools.cocoeval import COCOeval\n\nimport numpy as np\n\nimport json\n\nimport os\n\nimport torch.utils.data as data\n\n\n\nclass SHAPES(data.Dataset):\n num_classes = 5\n default_resolution = [128, 128]\n mean = np.array([0.40789654, 0.44719302, 0.47026115],\n dtype=np.float32).reshape(1, 1, 3)\n std = np.array([0.28863828, 0.27408164, 0.27809835],\n dtype=np.float32).reshape(1, 1, 3)\n\n \n def __init__(self, opt, split):\n super(SHAPES, self).__init__()\n# _folder_name = {'train': opt.shape_param + '_' + opt.shape_param_value,\n# 'test': opt.shape_param + '_' + opt.shape_param_value,\n# 'val': opt.shape_param + '_' + opt.shape_param_value,\n# }\n\n \n self.class_names = ['__background__', \"square\", \"circle\", \"triangle\", \"hexagon\", \"eclipse\"]\n self.default_resolution = [128, 128]\n\n # ONLY CHANGE \n self.data_dir =os.path.join(opt.data_dir, 'shape_multicombined/')\n self.img_dir = os.path.join(self.data_dir, 'multicombined_800_train2019')\n self.annot_path = os.path.join(self.data_dir, 'annotations', 'instances_shape_multicombined_800_train2019.json')\n\n self.max_objs = self.num_classes\n self.class_name = self.class_names[:self.num_classes+1]\n self._valid_ids = np.arange(1, self.num_classes+1, dtype=np.int32)\n\n\n self.cat_ids = {v: i for i, v in enumerate(self._valid_ids)}\n\n self._data_rng = np.random.RandomState(123)\n\n self._eig_val = np.array([0.2141788, 0.01817699, 0.00341571],\n\n dtype=np.float32)\n\n self._eig_vec = np.array([\n\n [-0.58752847, -0.69563484, 0.41340352],\n\n [-0.5832747, 0.00994535, -0.81221408],\n\n [-0.56089297, 0.71832671, 0.41158938]\n\n ], dtype=np.float32)\n\n\n self.split = split\n\n self.opt = opt\n\n print('==> initializing shapes {} data.'.format(split))\n\n self.coco = coco.COCO(self.annot_path)\n\n self.images = self.coco.getImgIds()\n\n self.num_samples = len(self.images)\n\n print('Loaded {} {} samples'.format(split, self.num_samples))\n\n def _to_float(self, x):\n\n return float(\"{:.2f}\".format(x))\n\n def convert_eval_format(self, all_bboxes):\n\n # import pdb; pdb.set_trace()\n\n detections = []\n\n for image_id in all_bboxes:\n\n for cls_ind in all_bboxes[image_id]:\n\n category_id = self._valid_ids[cls_ind - 1]\n\n for bbox in all_bboxes[image_id][cls_ind]:\n\n bbox[2] -= bbox[0]\n\n bbox[3] -= bbox[1]\n\n score = bbox[4]\n\n bbox_out = list(map(self._to_float, bbox[0:4]))\n\n detection = {\n\n \"image_id\": int(image_id),\n\n \"category_id\": int(category_id),\n\n \"bbox\": bbox_out,\n\n \"score\": float(\"{:.2f}\".format(score))\n\n }\n\n if len(bbox) > 5:\n extreme_points = list(map(self._to_float, bbox[5:13]))\n\n detection[\"extreme_points\"] = extreme_points\n\n detections.append(detection)\n\n return detections\n\n def __len__(self):\n\n return self.num_samples\n\n def save_results(self, results, save_dir):\n\n json.dump(self.convert_eval_format(results),\n\n open('{}/results.json'.format(save_dir), 'w'))\n\n def run_eval(self, results, save_dir):\n\n # result_json = os.path.join(save_dir, \"results.json\")\n\n # detections = self.convert_eval_format(results)\n\n # json.dump(detections, open(result_json, \"w\"))\n\n # import ipdb; ipdb.set_trace()\n\n self.save_results(results, save_dir)\n\n coco_dets = self.coco.loadRes('{}/results.json'.format(save_dir))\n\n coco_eval = COCOeval(self.coco, coco_dets, \"bbox\")\n\n coco_eval.evaluate()\n\n coco_eval.accumulate()\n\n coco_eval.summarize()\n\n\n\n\n\n\n","sub_path":"lib/datasets/dataset/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"46444151","text":"natural_number = -1\r\n\r\nwhile natural_number < 0:\r\n user_number = int(input('Введите любое натуральное число, например: 1, 5, 987\\n>>>'))\r\n\r\n if user_number < 0:\r\n print('Упс! Ввденное значение не является натуральным числом.\\nНатуральные числа имеют вид: 0, 1, 2, 3 и т.д. до бесконечноти.')\r\n\r\n natural_number = user_number\r\n\r\ni = 1\r\nfactorial = i\r\n\r\nwhile i <= user_number:\r\n factorial = factorial * i\r\n i = i + 1\r\n\r\nprint('Факториал числа {} = {}'.format(user_number, factorial))","sub_path":"hw_2_3_v2.py","file_name":"hw_2_3_v2.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"579653414","text":"from django.test import TestCase\nfrom question_tine.tests.factories import TineProfileFactory\n\n\nclass TestDisplayNameFinders(TestCase):\n \"\"\"Test the three display_name finders.\"\"\"\n def test_username_finder(self):\n \"\"\"username__name_finder returns the underlying user's username.\"\"\"\n profile = TineProfileFactory(display_name_preference='username')\n self.assertEqual(\n profile.display_name,\n profile.user.username\n )\n\n def test_full_name_finder(self):\n \"\"\"full_name__name_finder returns the underlying user's full name.\"\"\"\n profile = TineProfileFactory(display_name_preference='full_name')\n self.assertEqual(\n profile.display_name,\n profile.user.get_full_name()\n )\n\n def test_anonymous_finder(self):\n \"\"\"anonymous__name_finder returns 'Anonymous.'\"\"\"\n profile = TineProfileFactory(display_name_preference='anonymous')\n self.assertEqual(\n profile.display_name,\n 'Anonymous'\n )\n\n def test_invalid_finder_function(self):\n \"\"\"A ValueError is raised for an invalid finder function.\"\"\"\n profile = TineProfileFactory(display_name_preference='doesnotexist')\n with self.assertRaisesRegexp(\n ValueError,\n \"TineProfile display_name_preference doesnotexist does not\"\n \" match a TINE_PROFILE_DISPLAY_NAME_FINDERS function.\"\n ):\n profile.display_name\n","sub_path":"question_tine/tests/test_tine_profile.py","file_name":"test_tine_profile.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"451351395","text":"# import the necessary packages\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.optimizers import SGD\nfrom keras.optimizers import Adam\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.utils import shuffle\nfrom sklearn.decomposition import PCA\n# import random\n\nimport numpy as np\nimport pandas as pd\nfrom numpy import genfromtxt\n\ndef load_data():\n # train_data1 = genfromtxt('2005_data-lite.csv', delimiter=',', skip_header=1, dtype=str)\n # train_data2 = genfromtxt('2006_data-lite.csv', delimiter=',', skip_header=1, dtype=str)\n # train_data3 = genfromtxt('2007_data-lite.csv', delimiter=',', skip_header=1, dtype=str)\n # train_data = np.concatenate((train_data1, train_data2, train_data3), axis=0)\n # test_data = genfromtxt('2008_data-lite.csv', delimiter=',', skip_header=1, dtype=str)\n train_data = genfromtxt('data_processed.csv', delimiter=',', skip_header=1, dtype=str)\n\n train_data = pd.DataFrame(data=train_data, columns=train_data[0, :], dtype=str)\n # test_data = pd.DataFrame(data=test_data, columns=test_data[0, :], dtype=str)\n #\n # # cleanup the data by removing rows with missing values\n train_data.replace('', np.nan, inplace=True)\n train_data.dropna(axis=0, how='any', inplace=True)\n test_data.replace('', np.nan, inplace=True)\n test_data.dropna(axis=0, how='any', inplace=True)\n\n # shuffle the data\n train_data = shuffle(train_data[1:].values)\n test_data = shuffle(test_data[1:].values)\n\n\n # train_data = shuffle(train_data)\n # test_data = shuffle(test_data)\n #\n # dict = {}\n # trainY = train_data[:,0]\n # trainX = preprocessing(train_data[:,1:], dict)\n # testY = test_data[:,0]\n # testX = preprocessing(test_data[:,1:], dict)\n\n # testY = test_data.iloc[:,0]\n # testX = test_data.iloc[:,1:]\n # trainY = train_data.iloc[:,0]\n # trainX = train_data.iloc[:,1:]\n\n (trainX, testX, trainY, testY) = train_test_split(trainX,trainY, test_size=0.25, random_state=42)\n\n # Uncomment to use PCA first, and change the shape number in line 64\n # pca = PCA(n_components=11)\n # trainX = pca.fit_transform(trainX)\n # testX = pca.fit_transform(testX)\n return [trainX, testX, trainY, testY]\n\n# This changes the alpha numeric field into a unique number\ndef preprocessing(data, dict = {}):\n count = 1\n for i in range(data.shape[0]):\n for j in range(data.shape[1]):\n d = data[i][j]\n # print(\"blah blah \" + str(d))\n if not d.isnumeric():\n # print(\"hello mama\")\n if not dict.get(d):\n # print(\"changing \" + str(data[i][j]) + \" into \" + str(count) )\n dict[d] = count\n count += 1\n\n data[i][j] = dict[d]\n else:\n data[i][j] = float(d)\n\n return data\n\n(trainX, testX, trainY, testY) = load_data()\n# encode the labels as 1-hot vectors\nlb = LabelBinarizer()\ntrainY = lb.fit_transform(trainY)\ntestY = lb.transform(testY)\n\n# # define the 27-220-12 architecture using Keras\nmodel = Sequential()\nmodel.add(Dense(100, input_shape=(trainX.shape[1],), activation=\"sigmoid\"))\nmodel.add(Dense(11, activation=\"softmax\"))\n\n# train the model using SGDprint(\"[INFO] training network...\")\n# opt = SGD(lr=0.15, momentum=0.9)\nopt = Adam(lr=0.01, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=opt,metrics=[\"accuracy\"])\nH = model.fit(trainX, trainY, validation_data=(testX, testY),epochs=10, batch_size=500)\n\n# evaluate the networkprint(\"[INFO] evaluating network...\")\npredictions = model.predict(testX, batch_size=5000)\nprint(classification_report(testY.argmax(axis=1),predictions.argmax(axis=1)))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"352465122","text":"import pandas as pd\nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom scipy.special import factorial\n#funkcje pomocnicze\ndef take_n_split(string,delimiter,pos):\n s=string.split(delimiter)\n return int(s[pos])\ndef select_minute(data,minute):\n return data.loc[data['Minutes'] == minute]\n\ndata=pd.read_csv('weblog.csv')\ndata=data.head(50)\n\ndata['Minutes']=data['Time'].apply(lambda x: take_n_split(x,':',2))\ndata['Seconds']=data['Time'].apply(lambda x: take_n_split(x,':',3))\ndata=select_minute(data,38)\nnr_events=len(data['Seconds'])\n\nlogs_per_second=[]\nfor i in range (60):\n n_logs=len(data.loc[data['Seconds']==i])\n logs_per_second.append([i,n_logs])\n\nax=plt.figure()\nplt.scatter(np.array(logs_per_second)[:,0],np.array(logs_per_second)[:,1])\nplt.plot(np.array(logs_per_second)[:,0],np.array(logs_per_second)[:,1])\nplt.show()\nlps=np.array(logs_per_second)\nprob_lps=[i/len(lps) for i in lps[:,1]]\n\nfig=plt.figure()\nplt.scatter(lps[:,0],prob_lps)\n\nplt.show()\n\n# dystrybuanta\ndistribution=[]\ndist2=[0]\ndistribution.append(logs_per_second[0])\nfor i in range(1,len(logs_per_second)):\n\n distribution.append([i,distribution[i-1][1]+logs_per_second[i][1]/nr_events])\n dist2.append(distribution[i-1][1])\nax2=plt.figure()\ndist=np.array(distribution)\n#plt.plot(dist[:,0],dist[:,1])\nplt.scatter(dist[:,0],dist[:,1])\nd=np.array(dist2)\n\nplt.plot(dist[:,0],d,'bo',mfc='none')\n\nplt.show()\n\ndef poisson(k, lamb):\n return (lamb**k/factorial(k)) * np.exp(-lamb)\n\n# fit with curve_fit\n\n\nparameters, cov_matrix = curve_fit(poisson, lps[:,0],prob_lps)\n\nfigure2=plt.figure()\nx=np.linspace(0,60,1000)\n\nplt.plot(x, poisson(x, parameters), 'r-', lw=2)\nplt.scatter(lps[:,0], poisson(lps[:,0], parameters))\nplt.show()\n\n","sub_path":"models/web_parser.py","file_name":"web_parser.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"194013933","text":"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom collections import OrderedDict\n\nimport numpy as np\nimport oneflow as flow\nimport oneflow.typing as oft\nfrom test_util import GenArgList, type_name_to_flow_type, type_name_to_np_type\n\n\ndef test_sync_dynamic_resize(_):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"x_shape\"] = [\n (100,),\n (100, 1),\n (1000, 10),\n (10, 10, 200),\n ]\n arg_dict[\"data_type\"] = [\"float32\", \"double\", \"int32\", \"int64\"]\n arg_dict[\"size_type\"] = [\"int32\", \"int64\"]\n\n for device_type, x_shape, data_type, size_type in GenArgList(arg_dict):\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n\n @flow.global_function(function_config=func_config)\n def TestJob(\n x: oft.Numpy.Placeholder(x_shape, dtype=type_name_to_flow_type[data_type]),\n size: oft.Numpy.Placeholder((1,), dtype=type_name_to_flow_type[size_type]),\n ):\n with flow.scope.placement(device_type, \"0:0\"):\n return flow.sync_dynamic_resize(x, size)\n\n size = np.random.randint(0, x_shape[0])\n x = np.random.rand(*x_shape).astype(type_name_to_np_type[data_type])\n y = (\n TestJob(x, np.array([size]).astype(type_name_to_np_type[size_type]))\n .get()\n .numpy_list()[0]\n )\n assert np.array_equal(y, x[:size])\n","sub_path":"oneflow/python/test/ops/test_sync_dynamic_resize.py","file_name":"test_sync_dynamic_resize.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"106272085","text":"#!/usr/bin/env python\r\nfrom djeasytests.testsetup import TestSetup, default_settings\r\n\r\ndefault_settings.update(dict(\r\n ROOT_URLCONF='thing.urls',\r\n DATABASES = {\r\n 'default': {\r\n 'ENGINE': 'django.db.backends.sqlite3',\r\n 'NAME': ':memory:',\r\n }\r\n },\r\n INSTALLED_APPS = [\r\n 'django.contrib.auth',\r\n 'django.contrib.contenttypes',\r\n 'django.contrib.sessions',\r\n 'django.contrib.admin',\r\n 'django.contrib.sites',\r\n 'django.contrib.staticfiles',\r\n 'thing',\r\n ]\r\n))\r\n\r\ntestsetup = TestSetup(appname='thing',\r\n default_settings=default_settings)\r\n\r\nif __name__ == '__main__':\r\n testsetup.run('tests')","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"97007941","text":"# -*- coding:utf-8 -*-\n# @Time :2019/6/21 0:32\n# @Author: Athany\n# @File : 6.21-Spider-批量代理爬.py\n\n\"\"\"\n构建代理集群/队列\n每次访问服务器,随机抽取一个代理\n抽取可以使用random.choice\n\n\"\"\"\n\n# 分析步骤:\n# 1、构建代理群\n# 2、每次访问,随机选取代理并执行\n\nfrom urllib import request, error\nimport random\n\n\n# 1.设置代理地址\n# 列表里存放的是字典类型的元素\nproxy_list = [\n {\"http\": \"219.157.146.198:8118\"},\n {\"http\": \"111.13.134.22:80\"},\n {\"http\": \"39.137.77.66:8080\"},\n {\"http\": \"111.13.134.23:80\"},\n\n]\n\n# 2.创建ProxyHandler\nproxy_Handler_list = []\nfor proxy in proxy_list:\n proxy_Handler = request.ProxyHandler(proxy)\n proxy_Handler_list.append(proxy_Handler)\n\n# 3.创建opener\nopener_list = []\nfor proxy_Handler in proxy_Handler_list:\n opener = request.build_opener(proxy_Handler)\n opener_list.append(opener)\n\n\n\n\nurl = \"http://www.baidu.com\"\n\ntry:\n # 4.安装opener\n opener = random.choice(opener_list)\n request.install_opener(opener)\n\n rsp = request.urlopen(url)\n html = rsp.read().decode(\"utf-8\")\n print(html)\n\nexcept error.URLError as e:\n print(e)\n\nexcept Exception as e:\n print(e)\n","sub_path":"习题课/6.21-Spider-批量代理爬.py","file_name":"6.21-Spider-批量代理爬.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"127370933","text":"from django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom django.shortcuts import render_to_response, get_object_or_404, get_list_or_404\nfrom django.template import RequestContext, Template, loader\n\nclass SetRemoteAddrFromForwardedFor(object) :\n def process_request(self, request) :\n try :\n real_ip = request.META['HTTP_X_FORWARDED_FOR']\n except KeyError :\n return None\n else :\n real_ip = real_ip.split(\",\")[0].strip()\n request.META['REMOTE_ADDR'] = real_ip","sub_path":"apps/middleware/ip_proxy.py","file_name":"ip_proxy.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"395454032","text":"'''\nFusions Control board \na combination of the logic board and the kerr microcontroller \nsee Photon Machines Logic Board Command Set for additional information\n'''\n#=============enthought library imports=======================\nfrom enthought.traits.api import Instance, DelegatesTo, Str, Button\nfrom enthought.traits.ui.api import Item, VGroup, RangeEditor\n#=============standard library imports ========================\n\nimport os\n#=============local library imports ==========================\nfrom fusions_motor_configurer import FusionsMotorConfigurer\nfrom src.hardware.core.core_device import CoreDevice\n\nfrom src.hardware.kerr.kerr_snap_motor import KerrSnapMotor\nfrom src.hardware.kerr.kerr_microcontroller import KerrMicrocontroller\nfrom src.hardware.kerr.kerr_motor import KerrMotor\n\nclass FusionsLogicBoard(CoreDevice):\n '''\n '''\n\n motor_microcontroller = Instance(KerrMicrocontroller)\n\n beam_motor = Instance(KerrMotor)\n beam = DelegatesTo('beam_motor', prefix = 'data_position')\n beammin = DelegatesTo('beam_motor', prefix = 'min')\n beammax = DelegatesTo('beam_motor', prefix = 'max')\n beam_enabled = DelegatesTo('beam_motor', prefix = 'enabled')\n update_beam = DelegatesTo('beam_motor', prefix = 'update_position')\n\n zoom_motor = Instance(KerrMotor)\n zoom = DelegatesTo('zoom_motor', prefix = 'data_position')\n zoommin = DelegatesTo('zoom_motor', prefix = 'min')\n zoommax = DelegatesTo('zoom_motor', prefix = 'max')\n zoom_enabled = DelegatesTo('zoom_motor', prefix = 'enabled')\n update_zoom = DelegatesTo('zoom_motor', prefix = 'update_position')\n\n\n initialize_beam = True\n initialize_zoom = True\n configure = Button\n\n\n prefix = Str\n\n def initialize(self, *args, **kw):\n '''\n '''\n progress = kw['progress'] if kw.has_key('progress') else None\n\n #disable laser \n if progress is not None:\n progress.change_message('Disabling Laser')\n self._disable_laser_()\n\n #turn off pointer\n if progress is not None:\n progress.change_message('Turning off pointer laserr')\n self.set_pointer_onoff(False)\n\n #initialize Kerr devices\n self.motor_microcontroller.initialize(*args, **kw)\n\n if self.initialize_zoom:\n zm = self.zoom_motor\n zm.initialize(*args, **kw)\n self.set_zoom(zm.nominal_position)\n\n if self.initialize_beam:\n bm = self.beam_motor\n bm.initialize(*args, **kw)\n self.set_beam_diameter(bm.nominal_position)\n\n return True\n\n def _build_command(self, cmd):\n '''\n \n '''\n if self.prefix is not None:\n return ''.join((self.prefix, cmd))\n else:\n self.warning('Prefix not set')\n\n def load_additional_args(self, config):\n '''\n \n '''\n\n self.prefix = self.config_get(config, 'General', 'prefix')\n if self.prefix is None:\n return False\n\n z = self.config_get(config, 'Motors', 'zoom')\n b = self.config_get(config, 'Motors', 'beam', optional = True)\n\n if z is not None:\n self.zoom_motor.load(os.path.join(self.configuration_dir_path, z))\n\n if b is not None:\n self.beam_motor.load(os.path.join(self.configuration_dir_path, b))\n\n return True\n\n def read_power_meter(self):\n '''\n '''\n cmd = self._build_command('ADC1')\n r = self._parse_response(self.ask(cmd))\n\n# if cmd is not None:\n# r = self._parse_response(self.ask(cmd))\n# else:\n# return self.current_value\n\n if r is not None:\n try:\n r = float(r)\n except:\n self.warning('*Bad response from ADC ==> %s' % r)\n\n return r\n\n def _scan_(self, *args):\n '''\n\n '''\n\n r = self.read_power_meter()\n\n if r is not None:\n self.stream_manager.record(r, self.name)\n\n\n def _configure_fired(self):\n '''\n '''\n self.configure_motors()\n\n def configure_motors(self):\n '''\n '''\n fc = FusionsMotorConfigurer(motors = [self.zoom_motor, self.beam_motor])\n fc.edit_traits()\n\n#==============================================================================\n#laser methods\n#==============================================================================\n\n def check_interlocks(self):\n '''\n '''\n lock_bits = []\n\n if not self.simulation:\n cmd = self._build_command('INTLK')\n if cmd is not None:\n resp = None\n i = 0\n ntries = 3\n while resp is None and i < ntries:\n resp = self._parse_response(self.ask(cmd, verbose = True, delay = 100))\n try:\n resp = int(resp)\n except:\n resp = None\n i += 1\n\n if resp is None:\n return ['Failed Response']\n\n if resp != 0:\n LOCK_MAP = ['External', 'E-stop', 'Coolant Flow']\n rbits = []\n for i in range(16):\n if (resp >> i) & 1 == 1:\n rbits.append(i)\n\n lock_bits = [LOCK_MAP[cb] for cb in rbits]\n\n\n return lock_bits\n\n def _enable_laser_(self):\n '''\n '''\n interlocks = self.check_interlocks()\n if not interlocks:\n cmd = self._build_command('ENBL 1')\n if cmd is not None:\n resp = self._parse_response(self.ask(cmd, delay = 100))\n\n if resp == 'OK' or self.simulation:\n return True\n\n else:\n self._disable_laser_()\n self.warning('Cannot fire. Interlocks enabled')\n for i in interlocks:\n self.warning(i)\n\n def _disable_laser_(self):\n '''\n '''\n cmd = self._build_command('ENBL 0')\n if cmd is not None:\n resp = self._parse_response(self.ask(cmd, delay = 100))\n\n if resp == 'OK' or self.simulation:\n return True\n\n\n def _set_laser_power_(self, *args, **kw):\n '''\n \n '''\n pass\n\n def set_pointer_onoff(self, onoff):\n '''\n \n '''\n if onoff:\n cmd = 'DRV1 1'\n else:\n cmd = 'DRV1 0'\n\n cmd = self._build_command(cmd)\n self.ask(cmd)\n\n def _parse_response(self, resp):\n '''\n remove the CR at EOL\n '''\n if resp is not None:\n return resp.rstrip()\n\n def _motor_microcontroller_default(self):\n '''\n '''\n return KerrMicrocontroller(name = 'microcontroller',\n parent = self)\n\n def _zoom_motor_default(self):\n '''\n '''\n return KerrMotor(name = 'zoom', parent = self)\n\n def _beam_motor_default(self):\n '''\n '''\n return KerrSnapMotor(name = 'beam', parent = self)\n#==============================================================================\n#motor methods\n#==============================================================================\n def _block_(self, motor):\n '''\n\n '''\n self.info('waiting for move to complete')\n if not self.simulation:\n motor.block()\n self.info('move complete')\n\n def _enable_motor_(self, motor, pos):\n '''\n '''\n if motor.data_position != pos:\n motor.enabled = False\n\n def set_zoom(self, zoom, block = False, relative = False):\n '''\n\n '''\n motor = self.zoom_motor\n\n if relative:\n zoom = motor.data_position + zoom\n if not 0 <= zoom <= 100:\n return\n\n self._enable_motor_(motor, zoom)\n\n self.info('setting zoom to %0.1f' % zoom)\n\n motor.data_position = zoom\n\n if block:\n self._block_(motor)\n\n def set_beam_diameter(self, pos, block = True):\n '''\n\n '''\n motor = self.beam_motor\n\n self._enable_motor_(motor, pos)\n\n self.info('setting beam position {:0.3f}'.format(pos))\n\n motor.data_position = pos\n\n if block == True:\n self._block_(motor)\n\n def get_control_group(self):\n be = RangeEditor(low_name = 'beammin',\n high_name = 'beammax'\n )\n ube = RangeEditor(low_name = 'beammin',\n high_name = 'beammax',\n enabled = False\n )\n zo = RangeEditor(low_name = 'zoommin',\n high_name = 'zoommax'\n )\n uzo = RangeEditor(low_name = 'zoommin',\n high_name = 'zoommax',\n enabled = False\n )\n return VGroup(\n Item('zoom', editor = zo),\n Item('update_zoom', editor = uzo, show_label = False),\n Item('beam', editor = be),\n Item('update_beam', editor = ube, show_label = False),\n )\n\n#================== EOF ================================================\n\n\n","sub_path":"src/hardware/fusions/fusions_logic_board.py","file_name":"fusions_logic_board.py","file_ext":"py","file_size_in_byte":9346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"68779963","text":"# Sean Groathouse\n# CMPT 307\n# Database Project - Conservatory\n\n# This file contains the majority of the url definitions for the projects. The regular expressions\n# can become hard to read, so I've provided some sample urls for each. These simply map any url\n# matching a given regular expression to the corresponding view (a controller in MVC) which in \n# turn provides the relevant information to one of the templates.\n\n# Two different types of views are called upon here, both custom views entirely created by me, and\n# some of Django's built in views, such as the Detail View. \n\nfrom django.conf.urls import patterns, url\nfrom musician import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'), # matches the empty url '/' (given the way urls are forwarded here, both '/' and '/m/' will work)\n url(r'^(?P\\d+)/$', views.MusicianDetailView.as_view(), name='musician_detail'), # matches /m/2\n url(r'^piece/(?P\\d+)/$', views.PieceDetailView.as_view(), name='piece_detail'), # matches /m/piece/3\n url(r'^composer/(?P\\d+)/$', views.ComposerDetailView.as_view(), name='composer_detail'), # matches /m/composer/5\n url(r'^group/(?P\\d+)/$', views.GroupDetailView.as_view(), name='group_detail'),\t\t\t\t # matches /m/group/7\n url(r'^concert/(?P\\d+)/$', views.ConcertDetailView.as_view(), name='concert_detail'),\t\t # matches /m/concert/11\n url(r'^practice/(?P\\d+)/$', views.PracticeDetailView.as_view(), name='practice_detail'), # matches /m/practice/13\n\n url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'musician/login.html'}), # matches /m/login\n url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'),\t\t\t\t\t\t\t\t # matches /m/logout\n\n url(r'^modify/$', views.modify, name='modify'), \t\t\t\t\t\t\t\t\t\t\t\t # matches /m/modify\n url(r'^profile/$', views.profile, name='profile'), # matches /m/profile\n\n url(r'^new/concert/$', views.new_concert, name='new_concert'), # matches /m/new/concert\n url(r'^add/concert/$', views.add_concert, name='add_concert'), # matches /m/add/concert\n url(r'^new/group/$', views.new_group, name='new_group'), # matches /m/new/group\n url(r'^add/group/$', views.add_group, name='add_group'), # matches /m/add/group\n url(r'^new/practice/$', views.new_practice, name='new_practice'), # matches /m/new/practice\n url(r'^add/practice/$', views.add_practice, name='add_practice'), # matches /m/add/practice\n url(r'^new/instrument/$', views.new_instrument, name='new_instrument'), # matches /m/new/instrument\n url(r'^add/instrument/$', views.add_instrument, name='add_instrument'), # matches /m/add/instrument\n url(r'^new/piece/$', views.new_piece, name='new_piece'), # matches /m/new/piece\n url(r'^add/piece/$', views.add_piece, name='add_piece'), # matches /m/add/piece\n url(r'^new/rehearsal/$', views.new_rehearsal, name='new_rehearsal'), # matches /m/new/rehearsal\n url(r'^add/rehearsal/$', views.add_rehearsal, name='add_rehearsal'), # matches /m/add/rehearsal\n \n url(r'^del/instrument/(?P\\d+)/$', views.del_instrument), # matches /m/del/instrument/17\n url(r'^del/repertoire/(?P\\d+)/$', views.del_repertoire), # matches /m/del/repertoire/19\n url(r'^del/group/(?P\\d+)/$', views.del_group), # matches /m/del/group/23\n url(r'^del/concert/(?P\\d+)/$', views.del_concert), # mathces /m/del/concert/29\n url(r'^del/practice/(?P\\d+)/$', views.del_practice), # matches /m/del/practice/31\n\n)","sub_path":"conservatory/musician/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"145319324","text":"from flask import Flask\n\n# 서버 리소스\nresource = []\n\n# 사용자 정보 조회\n@app.route('/user/', methods=['GET'])\ndef get_user(user_id):\n\n for user in resource:\n if user['user_id'] is user_id:\n return jsonify(user)\n \n return jsonify(None)\n\n# 사용자 추가\n@app.route('/user', methods=['POST'])\ndef add_user(user_id):\n user = request.get_json()\n resource.append(user)\n return jsonify(resource)\n\n@app.route('/json//')\n@app.route('/JSON//')\ndef send_message(dest_id,message):\n json = {\n \"bot_id\": dest_id,\n \"message\": send_message\n }\n return json\n\nif __name__ == '__main__':\n app.run()","sub_path":"1_slack/ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"45191016","text":"import pandas as pd\nimport datetime\nfrom bson import json_util\n\ndef _instance_to_str(index):\n if isinstance(index, datetime.datetime):\n return index.isoformat()\n \n return index\n\ndef series_to_list_with_index(series):\n out_list = []\n\n if not(isinstance(series, pd.Series)): return out_list\n\n s_dict = series.to_dict()\n\n for key in s_dict:\n new_dict = {}\n index_key = type(key).__name__.lower()\n new_dict[index_key] = _instance_to_str(key)\n new_dict['value'] = s_dict[key]\n out_list.append(new_dict)\n \n return out_list\n\ndef dataframe_to_list_with_index(df):\n out_list = []\n\n if not(isinstance(df, pd.DataFrame)): return out_list\n\n for index, row in df.iterrows():\n rdict = row.to_dict()\n index_key = type(index).__name__.lower()\n rdict[index_key] = _instance_to_str(index)\n out_list.append(rdict)\n \n return out_list\n\ndef to_camel_case(string):\n out = string\n\n if not(isinstance(out, str)): return out\n\n # Make lower case\n out = out.lower()\n\n # Capitlize first letter of each pieces except the first one\n pieces = out.split(' ')\n out = pieces[0] + ''.join(x.title() for x in pieces[1:])\n\n return out\n\ndef lookup_fn(df, key_row, key_col):\n try:\n return df.iloc[key_row][key_col]\n except IndexError:\n return 0\n\ndef parse_json(data):\n return json_util.dumps(data, default=json_util.default)\n\n\n","sub_path":"yfinancerestapi/common/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"646337387","text":"import asyncio\nimport inspect\nimport itertools\nimport random\nimport sys\nimport time\nimport traceback\nimport typing\nimport logging\nimport inspect\nimport bisect\nimport warnings\nfrom collections import deque\n\nfrom ..errors._rpcbase import RpcError\nfrom .._events.raw import Raw\nfrom .._events.base import StopPropagation, EventBuilder, EventHandler\nfrom .._events.filters import make_filter, NotResolved\nfrom .._misc import utils\nfrom .. import _tl\n\nif typing.TYPE_CHECKING:\n from .telegramclient import TelegramClient\n\n\nCallback = typing.Callable[[typing.Any], typing.Any]\n\n\nasync def set_receive_updates(self: 'TelegramClient', receive_updates):\n self._no_updates = not receive_updates\n if receive_updates:\n await self(_tl.fn.updates.GetState())\n\nasync def run_until_disconnected(self: 'TelegramClient'):\n # Make a high-level request to notify that we want updates\n await self(_tl.fn.updates.GetState())\n await self._sender.wait_disconnected()\n\ndef on(self: 'TelegramClient', *events, priority=0, **filters):\n def decorator(f):\n for event in events:\n self.add_event_handler(f, event, priority=priority, **filters)\n return f\n\n return decorator\n\ndef add_event_handler(\n self: 'TelegramClient',\n callback=None,\n event=None,\n priority=0,\n **filters\n):\n if callback is None:\n return functools.partial(add_event_handler, self, event=event, priority=priority, **filters)\n\n if event is None:\n for param in inspect.signature(callback).parameters.values():\n event = None if param.annotation is inspect.Signature.empty else param.annotation\n break # only check the first parameter\n\n if event is None:\n event = Raw\n\n if not inspect.iscoroutinefunction(callback):\n raise TypeError(f'callback was not an async def function: {callback!r}')\n\n if not isinstance(event, type):\n raise TypeError(f'event type was not a type (an instance of something was probably used): {event!r}')\n\n if not isinstance(priority, int):\n raise TypeError(f'priority was not an integer: {priority!r}')\n\n if not issubclass(event, EventBuilder):\n try:\n if event.SUBCLASS_OF_ID != 0x9f89304e:\n raise TypeError(f'invalid raw update type for the event handler: {event!r}')\n\n if 'types' in filters:\n warnings.warn('\"types\" filter is ignored when the event type already is a raw update')\n\n filters['types'] = event\n event = Raw\n except AttributeError:\n raise TypeError(f'unrecognized event handler type: {param.annotation!r}')\n\n handler = EventHandler(event, callback, priority, make_filter(**filters))\n\n if self._dispatching_update_handlers:\n # Now that there's a copy, we're no longer dispatching from the old update_handlers,\n # so we can modify it. This is why we can turn the flag off.\n self._update_handlers = self._update_handlers[:]\n self._dispatching_update_handlers = False\n\n bisect.insort(self._update_handlers, handler)\n return handler\n\ndef remove_event_handler(\n self: 'TelegramClient',\n callback,\n event,\n priority,\n):\n if callback is None and event is None and priority is None:\n raise ValueError('must specify at least one of callback, event or priority')\n\n if not self._update_handlers:\n return [] # won't be removing anything (some code paths rely on non-empty lists)\n\n if self._dispatching_update_handlers:\n # May be an unnecessary copy if nothing was removed, but that's not a big deal.\n self._update_handlers = self._update_handlers[:]\n self._dispatching_update_handlers = False\n\n if isinstance(callback, EventHandler):\n if event is not None or priority is not None:\n warnings.warn('event and priority are ignored when removing EventHandler instances')\n\n index = bisect.bisect_left(self._update_handlers, callback)\n try:\n if self._update_handlers[index] == callback:\n return [self._update_handlers.pop(index)]\n except IndexError:\n pass\n return []\n\n if priority is not None:\n # can binary-search (using a dummy EventHandler)\n index = bisect.bisect_right(self._update_handlers, EventHandler(None, None, priority, None))\n try:\n while self._update_handlers[index].priority == priority:\n index += 1\n except IndexError:\n pass\n\n removed = []\n while index > 0 and self._update_handlers[index - 1].priority == priority:\n index -= 1\n if callback is not None and self._update_handlers[index].callback != callback:\n continue\n if event is not None and self._update_handlers[index].event != event:\n continue\n removed.append(self._update_handlers.pop(index))\n\n return removed\n\n # slow-path, remove all matching\n removed = []\n for index, handler in reversed(enumerate(self._update_handlers)):\n if callback is not None and handler.callback != callback:\n continue\n if event is not None and handler.event != event:\n continue\n removed.append(self._update_handlers.pop(index))\n\n return removed\n\ndef list_event_handlers(self: 'TelegramClient')\\\n -> 'typing.Sequence[typing.Tuple[Callback, EventBuilder]]':\n return self._update_handlers[:]\n\nasync def catch_up(self: 'TelegramClient'):\n # The update loop is probably blocked on either timeout or an update to arrive.\n # Unblock the loop by pushing a dummy update which will always trigger a gap.\n # This, in return, causes the update loop to catch up.\n await self._updates_queue.put(_tl.UpdatesTooLong())\n\nasync def _update_loop(self: 'TelegramClient'):\n try:\n updates_to_dispatch = deque()\n while self.is_connected():\n if updates_to_dispatch:\n await _dispatch(self, updates_to_dispatch.popleft())\n continue\n\n get_diff = self._message_box.get_difference()\n if get_diff:\n self._log[__name__].info('Getting difference for account updates')\n diff = await self(get_diff)\n updates, users, chats = self._message_box.apply_difference(diff, self._entity_cache)\n self._entity_cache.extend(users, chats)\n updates_to_dispatch.extend(updates)\n continue\n\n get_diff = self._message_box.get_channel_difference(self._entity_cache)\n if get_diff:\n self._log[__name__].info('Getting difference for channel updates')\n diff = await self(get_diff)\n updates, users, chats = self._message_box.apply_channel_difference(get_diff, diff, self._entity_cache)\n self._entity_cache.extend(users, chats)\n updates_to_dispatch.extend(updates)\n continue\n\n deadline = self._message_box.check_deadlines()\n try:\n updates = await asyncio.wait_for(\n self._updates_queue.get(),\n deadline - asyncio.get_running_loop().time()\n )\n except asyncio.TimeoutError:\n self._log[__name__].info('Timeout waiting for updates expired')\n continue\n\n processed = []\n users, chats = self._message_box.process_updates(updates, self._entity_cache, processed)\n self._entity_cache.extend(users, chats)\n updates_to_dispatch.extend(processed)\n except Exception:\n self._log[__name__].exception('Fatal error handling updates (this is a bug in Telethon, please report it)')\n\n\nasync def _dispatch(self, update):\n self._dispatching_update_handlers = True\n\n event_cache = {}\n for handler in self._update_handlers:\n event = event_cache.get(handler._event)\n if not event:\n event_cache[handler._event] = event = handler._event._build(\n update, [], self._session_state.user_id, {}, self)\n\n while True:\n # filters can be modified at any time, and there can be any amount of them which are not yet resolved\n try:\n if handler._filter(event):\n try:\n await handler._callback(event)\n except StopPropagation:\n self._dispatching_update_handlers = False\n return\n except Exception:\n name = getattr(handler._callback, '__name__', repr(handler._callback))\n self._log[__name__].exception('Unhandled exception on %s (this is likely a bug in your code)', name)\n except NotResolved as nr:\n try:\n await nr.unresolved.resolve()\n continue\n except Exception as e:\n # we cannot really do much about this; it might be a temporary network issue\n warnings.warn(f'failed to resolve filter, handler will be skipped: {e}: {nr.unresolved!r}')\n except Exception as e:\n # invalid filter (e.g. types when types were not used as input)\n warnings.warn(f'invalid filter applied, handler will be skipped: {e}: {e.filter!r}')\n\n # we only want to continue on unresolved filter (to check if there are more unresolved)\n break\n\n self._dispatching_update_handlers = False\n","sub_path":"telethon/_client/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":9583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"187819511","text":"import sys\r\nimport os\r\nimport numpy as np\r\n#Load sample images from disk\r\nfrom skimage import color\r\nfrom skimage import io\r\nimport pickle as pkl\r\nsys.path.append('lib/python')\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.colors import ListedColormap\r\nfrom sklearn.metrics import confusion_matrix\r\nimport itertools\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\ndef get_subFiles(p,r):\r\n imagenes = os.listdir(p)\r\n indices_mezclados = np.random.permutation(len(imagenes))\r\n for i in indices_mezclados[:10]:\r\n rta = os.path.join(p,imagenes[i])\r\n test_local.append(rta)\r\n test_cat_mapping[rta] = r\r\n for i in indices_mezclados[10:]:\r\n rta = os.path.join(p,imagenes[i])\r\n train_local.append(rta)\r\n train_cat_mapping[rta]=r\r\n \r\ndef get_subFolderFolder(rt,sb):\r\n for r in (rt):\r\n categories.append(r)\r\n rutaruta = os.path.join(sb,r)\r\n get_subFiles(rutaruta,r)\r\n \r\ndef get_subFolders(ruta):\r\n for ru in ruta:\r\n sub_ruta = os.path.join(data_path,ru)\r\n sub = os.listdir(sub_ruta)\r\n #print(sub)\r\n get_subFolderFolder(sub,sub_ruta)\r\ndef create_texton_dict():\r\n tmp = {}\r\n for cat in categories:\r\n tmp[cat]=[]\r\n return tmp\r\n\r\ndef configure(list_,flag_):\r\n temp = []\r\n temp_dict = {}\r\n for im in list_:\r\n \r\n arra = io.imread(im)\r\n re_shape = arra[:30,30:60]\r\n temp_dict[im] = re_shape\r\n if flag_ ==0:\r\n ct = train_cat_mapping[im]\r\n txtn_train_dict[ct].append(re_shape)\r\n else:\r\n ct = test_cat_mapping[im]\r\n txtn_test_dict[ct].append(re_shape)\r\n temp.append(re_shape)\r\n return temp,temp_dict\r\n\r\ndef asignar_texton_train(dc):\r\n coter = 0\r\n tm_dict = {}\r\n for k,v in dc.items():\r\n tmp_rr = []\r\n for ele in v:\r\n tmap =assignTextons(fbRun(fb,ele),textons.transpose())\r\n tmp_rr.append(tmap)\r\n tm_dict[k]=tmp_rr\r\n return tm_dict\r\ndef histc(X, bins):\r\n map_to_bins = np.digitize(X,bins)\r\n r = np.zeros(bins.shape)\r\n for i in map_to_bins:\r\n r[i-1] += 1\r\n return np.array(r)\r\n\r\ndef create_data_ml(dicti):\r\n data_ = []\r\n labels_ = []\r\n for k, v in dicti.items():\r\n label_ = k\r\n arra = v\r\n for ar in arra:\r\n h = histc(ar.flatten(), np.arange(25))/len(ar)\r\n data_.append(h)\r\n labels_.append(k)\r\n return data_, labels_\r\n\r\ndef plot_confusion_matrix(cm, classes,\r\n normalize=False,\r\n title='Confusion matrix',\r\n cmap=plt.cm.Blues):\r\n \"\"\"\r\n This function prints and plots the confusion matrix.\r\n Normalization can be applied by setting `normalize=True`.\r\n \"\"\"\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n print(\"Normalized confusion matrix\")\r\n else:\r\n print('Confusion matrix, without normalization')\r\n\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n plt.imsave('confusionmatrix.jpg',cm)\r\n plt.title(title)\r\n plt.colorbar()\r\n tick_marks = np.arange(len(classes))\r\n #plt.xticks(tick_marks, classes, rotation=90)\r\n #plt.yticks(tick_marks, classes)\r\n\r\n fmt = '.1f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n plt.text(j, i, format(cm[i, j], fmt),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n\r\n plt.tight_layout()\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label')\r\n diag = np.diag(cm)\r\n acc = np.average(diag)\r\n return acc\r\n\r\ndata_path = '../data/'\r\ndata_dir = os.listdir(data_path)\r\ntest_local = []\r\ntrain_local =[]\r\ncategories = []\r\ntrain_cat_mapping = {}\r\ntest_cat_mapping = {}\r\nnp.random.seed(42)\r\n\r\nget_subFolders(data_dir)\r\n\r\ntest_dict = {}\r\ntxtn_train_dict = create_texton_dict()\r\ntxtn_test_dict = create_texton_dict()\r\n\r\nlist_images_entrenamiento , train_dict = configure(train_local,0)\r\nimages_test, test_dict = configure(test_local,1)\r\n\r\nfrom fbCreate import fbCreate\r\nfb = fbCreate()\r\nhstac = np.hstack(list_images_entrenamiento)\r\n\r\nfrom fbRun import fbRun\r\nfilterResponses = fbRun(fb,np.hstack(list_images_entrenamiento))\r\n\r\nfrom computeTextons import computeTextons\r\nfrom assignTextons import assignTextons\r\nmap, textons = computeTextons(filterResponses, 25)\r\n\r\ntxtn_train_dict = asignar_texton_train(txtn_train_dict)\r\ntxtn_test_dict = asignar_texton_train(txtn_test_dict)\r\n\r\nentrenar_x, entrenar_y = create_data_ml(txtn_train_dict)\r\n\r\n\r\nprobar_x, probar_y = create_data_ml(txtn_test_dict)\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nclf = KNeighborsClassifier()\r\nclf.fit(entrenar_x,entrenar_y)\r\n\r\n #Predict the train data\r\nresult1 = clf.predict(entrenar_x)\r\nmtrx = confusion_matrix(entrenar_y,result1)\r\naverage = plot_confusion_matrix(mtrx, classes=list(txtn_train_dict.keys()),normalize=True, title='Train Confusion matrix, with normalization')\r\nplt.show()\r\nprint('Training nn average classification error ',average)\r\n\r\nclf2 = KNeighborsClassifier()\r\nclf2.fit(probar_x,probar_y)\r\nresult2 = clf.predict(probar_x)\r\nmtrx_2 = confusion_matrix(probar_y,result2)\r\naverage_2 = plot_confusion_matrix(mtrx_2, classes=list(txtn_test_dict.keys()),normalize=True, title='Test Confusion matrix, with normalization')\r\nprint('Testing nn average classification error ',average_2)\r\nplt.show()\r\n\r\nrndomforrest = RandomForestClassifier(n_estimators=10)\r\nrndomforrest.fit(entrenar_x,entrenar_y)\r\n#Predict the train data\r\npredi_train = rndomforrest.predict(entrenar_x)\r\nrnd_mtrx = confusion_matrix(entrenar_y,predi_train)\r\naverage_3 = plot_confusion_matrix(rnd_mtrx, classes=list(txtn_train_dict.keys()),normalize=True, title='Train Confusion matrix, with normalization')\r\n\r\nprint('Training random forest average classification error ',average_3)\r\n\r\n\r\nrndomforrest2 = RandomForestClassifier(n_estimators=10)\r\nrndomforrest2.fit(entrenar_x,entrenar_y)\r\n#Predict the train data\r\npredi_train2 = rndomforrest2.predict(probar_x)\r\nrnd_mtrx = confusion_matrix(probar_y,predi_train2)\r\naverage_4 = plot_confusion_matrix(rnd_mtrx, classes=list(txtn_test_dict.keys()),normalize=True, title='Train Confusion matrix, with normalization')\r\n\r\nprint('Testing rndm forest average classification error ',average_4)","sub_path":"05-Textons/code/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"496894083","text":"from django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom session_csrf import anonymous_csrf\nfrom ..models import Config\nfrom ..forms import SettingsForm\n\n@anonymous_csrf\ndef list(request):\n if request.method == 'POST':\n form = SettingsForm(request.POST)\n if form.is_valid():\n for field in form:\n config = Config.objects.get(key=field.__dict__['html_name'])\n config.value = form.cleaned_data[field.__dict__['html_name']]\n config.save()\n else:\n initial = {}\n data = {}\n for i in Config.objects.all():\n initial[i.key] = i.value\n\n for i in SettingsForm.checkbox_fields:\n initial[i] = (initial[i] == '1')\n \n form = SettingsForm(initial)\n \n return render_to_response(\n 'setting/index.html',\n {'form': form },\n context_instance = RequestContext(request)\n )\n","sub_path":"BanHammer/blacklist/views/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"35164963","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Initial step:\n# import fundamental pkgs\nimport numpy as np\nimport pandas as pd\npd.options.display.max_columns = None\npd.options.display.max_rows = None\nimport datetime as dt\n\n# import visualization pkgs\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom IPython.display import HTML\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# import machine learning pkgs\nfrom sklearn import metrics\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier\nfrom sklearn.metrics import f1_score, recall_score, precision_score, roc_auc_score\nfrom sklearn.metrics import classification_report, precision_recall_curve, roc_curve, auc\n\n\n# ### First stage\n\n# In[2]:\n\n\n# Next step:\n# load data and name the dataFrame as df\ndf = pd.read_csv('data.csv',low_memory=False)\n\n\n# In[3]:\n\n\n# Have a look at data structure\ndf.head()\n\n\n# In[4]:\n\n\n# Check the number of rows and cols\ndf.shape\n\n\n# In[5]:\n\n\n# Check the column info in list form\nlist(df.columns)\n\n\n# In[6]:\n\n\n# Check the target variable\ndf['loan_status'].value_counts()\n\n\n# ##### From the values under loan_status col we can see there are some people who did not meet the credit policy, these data should be removed.\n\n# In[7]:\n\n\n# Remove the improper data set\ndf = df.loc[df['loan_status'].isin(['Fully Paid', 'Charged Off'])]\n\n\n# In[8]:\n\n\n# Check the new one\ndf['loan_status'].value_counts()\n\n\n# In[9]:\n\n\n# After rearranged the target variable,\n# check the missing values, and return the missing rate.\n# Define a function:\ndef missingVals(df):\n '''\n This function return a table of number of missing values, \n and it's percentage.\n '''\n # Total missing values\n missingVals = df.isnull().sum()\n \n # Proportion of missing values\n propMissingVals = missingVals / len(df) * 100\n \n # Create a table\n tableMissingVals = pd.concat([df.isnull().sum(), propMissingVals], axis=1)\n \n # Rename the cols\n renTableMissVals = tableMissingVals.rename(\n columns = {0: \"Missing Value Total\", 1: \"Percentage (%) of Missing Value\"})\n \n # Sort the table by percentage of missing values\n # in descending order (ie. highest ot lowest).\n renTableMissVals = renTableMissVals[\n renTableMissVals.iloc[:,1] != 0].sort_values(\n \"Percentage (%) of Missing Value\",\n ascending = False).round(2)\n \n # Print conclustion messages for readers.\n print (\"Your selected dataframe has \" + str(df.shape[1]) + \" columns.\\n\" \n \"There are \" + str(renTableMissVals.shape[0]) +\n \" columns that have missing values.\")\n \n # Return the data frame in table with missing values not removed.\n return renTableMissVals\n\n\n# In[10]:\n\n\nmissing = missingVals(df)\nprint(missing)\n\n\n# In[11]:\n\n\n# Drop the columns with high percentage (80%)\nmissingCols = list(missing.index[\n missing[\"Percentage (%) of Missing Value\"] > 80])\n\ndfSub = df.drop(columns = missingCols)\n\n\n# In[12]:\n\n\n# Check\nmissingVals(dfSub)\n\n\n# In[13]:\n\n\n# After check missings, check duplicated values and drop.\ndfSub[dfSub.duplicated()]\ndfSub.drop_duplicates(inplace= True)\n\n\n# In[14]:\n\n\n# Check once, how many rows and cols remaining.\ndfSub.shape\n\n\n# ### Stage Two: Exploratory Data Analysis\n\n# In[15]:\n\n\n# Check the data is balanced or imbalanced\n# Create a new col named charged_off, where fully paid is 0 and charged off is 1.\ndfSub[\"charged_off\"] = dfSub[\"loan_status\"].apply(lambda x: 1 if x == \"Charged Off\" else 0)\n\n\n# In[16]:\n\n\n# charge off rate (in %)\nchargeOffRate = dfSub[\"charged_off\"].sum() / dfSub.shape[0] * 100\nchargeOffRate.round(2)\n\n\n# The charge off rate is relatively high (14%), we consider the data set as imbalanced.\n\n# In[17]:\n\n\n# Drop the cols that potentially cause data leakage.\nleakCols = [\"total_pymnt_inv\",\"total_rec_prncp\",\"funded_amnt\",\"funded_amnt_inv\",\"total_pymnt\",\n \"total_rec_int\",\"total_rec_late_fee\",\"recoveries\",\"collection_recovery_fee\",\n \"last_pymnt_amnt\",\"chargeoff_within_12_mths\",\"debt_settlement_flag\"]\n\n\n# In[18]:\n\n\ndfSub.drop(columns = leakCols, inplace=True)\n\n\n# In[19]:\n\n\ndfSub.shape\n\n\n# In[20]:\n\n\n54 - 43 == len(leakCols) - 1\n\n\n# #### Numerical features\n\n# In[21]:\n\n\n# Get the statistical parameters again.\ndfSub.describe()\n\n\n# In[22]:\n\n\ndfSub[\"delinq_amnt\"].value_counts()\n\n\n# In[23]:\n\n\n# Drop zero values cols since they are unnecessary,\n# These cols are those with zero means and SDs.\ndfSub.drop(columns=[\n 'collections_12_mths_ex_med','tax_liens','out_prncp','out_prncp_inv','delinq_amnt','acc_now_delinq']\n , inplace=True)\n\n\n# In[24]:\n\n\ndfSub.shape\n\n\n# #### Categorical features\n\n# In[25]:\n\n\nprint(dfSub.info())\n\n\n# In[26]:\n\n\n# To manipulate categorical columns,\n# we need to create a subset data frame which\n# only contains categorical variables.\ndfCat = dfSub.select_dtypes(include=['object'])\ndfCat.shape\n\n\n# In[27]:\n\n\n# Drop the target variable (y)\ncatCols = dfCat.drop(columns=['loan_status']).columns.tolist()\ncatCols\n\n\n# In[28]:\n\n\n# Strip leading and trailing space of each categorical column\nfor i in catCols:\n dfSub[i] = dfSub[i].str.strip()\n\n\n# In[29]:\n\n\npd.set_option(\"display.max_columns\", None)\n# Display the categorical columns\ndfSub[catCols].head(8)\n\n\n# In[30]:\n\n\n# Here catCols is a 'list'\ntype(catCols)\n\n\n# In[31]:\n\n\n# Return frequency for every element (for loop).\nfor each in catCols:\n print(dfSub[each].value_counts().to_frame())\n\n\n# In[32]:\n\n\ndfSub[\"emp_title\"].value_counts()\n\n\n# In[33]:\n\n\ndfSub[\"title\"].value_counts()\n\n\n# In[34]:\n\n\n# check homogeny\ndfSub[\"initial_list_status\"].value_counts()\n\n\n# In[35]:\n\n\n# check homogeny\ndfSub[\"hardship_flag\"].value_counts()\n\n\n# In[36]:\n\n\n# check homogeny\ndfSub[\"pymnt_plan\"].value_counts()\n\n\n# In[37]:\n\n\n# Check homogeny\ndfSub[\"application_type\"].value_counts()\n\n\n# We should drop \"desc\" predictor since it is an irrelavent predictor for the model. Also, \"initial_list_status\", \"hardship_flag\", \"pymnt_plan\", \"application_type\" are indentical (ie. all values are the same), which means they should not be considered as predictors.\n\n# Some predictors are hard to verify, such as \"emp_length\" and \"purpose\". There is no way or very hard to verify what they filled in, in order to keep the accuracy of the regression model, we should safely drop these columns.\n\n# The predictor \"sub_grade\" is the detailed classification of \"grade\", here we only keep to simplify the workload.\t\n\n# In[38]:\n\n\ndfSub[\"title\"].value_counts()\n\n\n# This predictor has too many different values (classifications) and some values only showed once. Instead of ignoring the partical infomation (for example, value less than 10 is not considered), it is better to drop the entire column. \"emp_title\" variable has the same problem.\n\n# In[39]:\n\n\ndfSub[\"zip_code\"]\n\n\n# This predictor is useless beacuse it has imcomplete infomation, it only contains the first 3 digits of every zip code. It should be droped.\n\n# In[40]:\n\n\n# Creating a list including the columns that should be droped.\ndropCols = ['desc','issue_d','last_pymnt_d','last_credit_pull_d',\n 'earliest_cr_line','pymnt_plan','hardship_flag',\n 'emp_title', 'emp_length', 'zip_code','title', 'purpose',\n 'sub_grade','initial_list_status','application_type']\n\n\n# In[41]:\n\n\n# drop the cols\ndfSub = dfSub.drop(columns = dropCols, axis = 1)\n\n\n# In[42]:\n\n\n# have a look of the new one\ndfSub.head()\n\n\n# In[43]:\n\n\n# remaining categorical predictors:\nrCatCols = []\nfor element in catCols:\n if element not in dropCols:\n rCatCols.append(element)\n else:\n continue\n\n\n# In[44]:\n\n\nprint(rCatCols)\n\n\n# In[45]:\n\n\ntype(rCatCols)\n\n\n# ### We are aiming to convert all categorical predictors into numerical ones.\n\n# In[46]:\n\n\nobjColsList = dfSub.select_dtypes(include=['object']).columns.tolist()\n\n\n# In[47]:\n\n\n# convert percentage (%) into decimals\nfor eachColumn in objColsList:\n if \"%\" in dfSub[eachColumn][1]:\n dfSub[eachColumn] = dfSub[eachColumn].str.replace('%', '').astype(float)/100\n\n\n# In[48]:\n\n\ndfSub[rCatCols].head()\n\n\n# In[49]:\n\n\ndfSub[\"verification_status\"].value_counts()\n\n\n# In[50]:\n\n\n# Convert verification status into 1 (verified) and 0 (not verified):\ndfSub.loc[dfSub[\"verification_status\"] == \"Not Verified\", \"verification_status\"] = 0\ndfSub.loc[dfSub[\"verification_status\"] == \"Verified\", \"verification_status\"] = 1\ndfSub.loc[dfSub[\"verification_status\"] == \"Source Verified\", \"verification_status\"] = 1\n\n\n# In[51]:\n\n\n# double check it\ndfSub[\"verification_status\"].value_counts()\n\n\n# In[52]:\n\n\n# what remaining:\ncateRemainList = list(dfSub.select_dtypes(include=['object']).drop(columns = [\"loan_status\"]).columns)\ncateRemainList\n\n\n# In[53]:\n\n\n# Check if there is any missing value remaining\ncheckMis = missingVals(dfSub)\ncheckMis\n\n\n# In[54]:\n\n\n# get rid of missings by replacing them to 0:\ndfSub[\"mths_since_last_delinq\"].fillna(value=0, inplace=True)\ndfSub[\"pub_rec_bankruptcies\"].fillna(value=0, inplace=True)\ndfSub[\"revol_util\"].fillna(value=0, inplace=True)\n\n\n# In[55]:\n\n\n# check again\ncheckMis = missingVals(dfSub)\ncheckMis\n\n\n# In[56]:\n\n\n# define a function to deal with the categorical variables\ndef cateToNum(df):\n '''\n Convert categorical columns into numerical columns \n by dividing them into subgroups.\n '''\n # original column list\n oriColLst = df.columns.tolist()\n # categorical column in list\n cateCol = [c for c in df.columns if df[c].dtype == 'object']\n # get dummy variable and assign new columns to dataframe\n df = pd.get_dummies(df, dummy_na = True, columns = cateCol)\n \n # also return a new list of column of dummy columns (not required)\n newCol = []\n for each in df.columns:\n if each not in oriColLst:\n newCol.append(each)\n return df\n\n\n# In[57]:\n\n\ndfSub = cateToNum(dfSub)\n\n\n# In[58]:\n\n\ndfSub.head()\n\n\n# In[59]:\n\n\ndfSub.shape\n\n\n# In[76]:\n\n\n# make a copy\ndfFinal = dfSub.copy()\n\n\n# In[61]:\n\n\n# to csv\ndfSub.to_csv(\"cleaned_data.csv\")\n\n\n# ### Stage three: modelling\n\n# In[77]:\n\n\n# correlation checking\ncorr = dfFinal.corr()[\"charged_off\"].sort_values(ascending = False)\ncorr\n\n\n# In[78]:\n\n\ny = dfFinal['charged_off']\nx = dfFinal.drop(columns = 'charged_off')\n\n\n# In[79]:\n\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)\nprint(x_train.shape)\nprint(y_train.shape)\nprint(x_test.shape)\nprint(y_test.shape)\n\n\n# In[80]:\n\n\n# fit logistic model\nlogist= LogisticRegression()\n\n\n# In[81]:\n\n\nlogist.fit(x_train, y_train)\n\n\n# In[82]:\n\n\nlog_reg_pred = logist.predict_proba(x_test)\n# actural probability:\ny_pred_proba=log_reg_pred[:,1]\ny_pred = logist.predict(x_test)\n\n\n# In[83]:\n\n\n# Show the ROC_CURVE\nimport numpy as np\n[fpr, tpr, thr] = metrics.roc_curve(y_test, y_pred_proba)\nidx = np.min(np.where(tpr > 0.95)) # index of the first threshold for which the sensibility > 0.95\nplt.figure()\nplt.plot(fpr, tpr, color='coral', label='ROC curve (area = %0.3f)' % metrics.auc(fpr, tpr))\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot([0, fpr[idx]], [tpr[idx], tpr[idx]], 'k--', color='blue')\nplt.plot([fpr[idx], fpr[idx]], [0, tpr[idx]], 'k--', color='blue')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate (1 - specificity)', fontsize=14)\nplt.ylabel('True Positive Rate (recall)', fontsize=14)\nplt.title('Receiver operating characteristic (ROC) curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[84]:\n\n\n# Random Forest\nrf_model = RandomForestClassifier()\n\n\n# In[85]:\n\n\nrf_model = RandomForestClassifier(\n n_estimators=200,\n max_depth=5)\nrf_model.fit(X=x_train, y=y_train)\n\n# For illustration purposes, we are instructing the model to build 200 trees, \n# where each tree can only grow up to the depth of 5\n\n\n# In[86]:\n\n\n# get the feature importances\nrf_model.feature_importances_\n\n\n# In[87]:\n\n\nfeature_importance_df = pd.DataFrame(list(zip(rf_model.feature_importances_, list(x_train.columns))))\nfeature_importance_df.columns = ['feature.importance', 'feature']\nfeature_importance_df.sort_values(by='feature.importance', ascending=False).head(20)\n\n\n# In[88]:\n\n\nrf_model_pred = rf_model.predict_proba(x_test)\ny_pred_proba=rf_model_pred[:,1]\ny_pred = rf_model.predict(x_test)\n\n\n# In[93]:\n\n\nimport numpy as np\n[fpr, tpr, thr] = metrics.roc_curve(y_test, y_pred_proba)\nidx = np.min(np.where(tpr > 0.95)) # index of the first threshold for which the sensibility > 0.95\nplt.figure()\nplt.plot(fpr, tpr, color='coral', label='ROC curve (area = %0.3f)' % metrics.auc(fpr, tpr))\nplt.plot([0, 1], [0, 1], 'k--')\nplt.plot([0, fpr[idx]], [tpr[idx], tpr[idx]], 'k--', color='blue')\nplt.plot([fpr[idx], fpr[idx]], [0, tpr[idx]], 'k--', color='blue')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate (1 - specificity)', fontsize=14)\nplt.ylabel('True Positive Rate (recall)', fontsize=14)\nplt.title('Receiver operating characteristic (ROC) curve')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\n# Idk why ROC area is 1, still trying to fix the problem...\n# And I'm currently still learning random forest model,\n# this will be fixed and finished later. (To be Con'd)\n\n# End of project.\n\n","sub_path":"data-analysis-pandas-loanPayment-prediction.py","file_name":"data-analysis-pandas-loanPayment-prediction.py","file_ext":"py","file_size_in_byte":13364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"82285504","text":"__author__ = 'beigank'\n\n\nclass ProcessDescriptionWhenTextFile(object):\n \"\"\"\n This class takes a preprocessed Description file\n where each line represents a single record with\n two fields, namely Address and Description\n Note: PowerGrep was used to pre-process the PDF\n \"\"\"\n\n def __init__(self, FileName, PLCName):\n self.__PLCName = PLCName\n self.__PLCAddressFieldName = \"PLC_Address\"\n self.__AddressFieldName = \"Address\"\n self.__DescriptionFieldName = \"Description\"\n self.AllAddressAndDescriptions = self.__Read310_1PreFormattedTextFile(FileName)\n\n def GetDescriptionDatabase(self):\n import pandas\n\n DescriptionDatabase = pandas.DataFrame(self.AllAddressAndDescriptions)\n DescriptionDatabase[\"PLC\"] = self.__PLCName\n DescriptionDatabase[self.__PLCAddressFieldName] = DescriptionDatabase.Address.apply(\n lambda addr: self.__PLCName + addr)\n return DescriptionDatabase\n\n def __Read310_1PreFormattedTextFile(self, FileName):\n Address = []\n Description = []\n with open(FileName, mode=\"r\") as DescriptionTextFile:\n for SingleAddress in DescriptionTextFile.readlines():\n if self.__isAddressDelimitedWithComma(SingleAddress):\n Address.append(self.__GetDelimitedAddress(SingleAddress))\n Description.append(self.__GetDescriptionWithAddressDelimited(SingleAddress))\n else:\n Address.append(self.__GetAddress(SingleAddress))\n Description.append(self.__GetDescription(SingleAddress))\n return {self.__AddressFieldName: Address, self.__DescriptionFieldName: Description}\n\n def __isAddressDelimitedWithComma(self, SingleLineInPreProcessedTxtFile):\n AddressDelimiter = \",\"\n isDelimited = 3\n DividedUpLine = SingleLineInPreProcessedTxtFile.split(AddressDelimiter)\n return len(DividedUpLine[0]) == isDelimited\n\n def __GetDelimitedAddress(self, SingleAddress):\n RawAddress = SingleAddress.replace(\",\", \" \", 1)\n RawAddress = RawAddress.split()[:2]\n Address = \",\".join(RawAddress)\n return Address\n\n def __GetDescriptionWithAddressDelimited(self, Singleline):\n RawDescription = Singleline.split()[1:]\n RawDescription = \" \".join(RawDescription)\n Description = RawDescription.strip()\n return Description\n\n def __GetAddress(self, SingleAddress):\n RawAddress = SingleAddress.replace(\",\", \" \", 1)\n return RawAddress.split(\" \")[0]\n\n def __GetDescription(self, SingleAddress):\n RawDescription = SingleAddress.replace(\",\", \" \", 1)\n return \" \".join(RawDescription.split()[1:])\n\n","sub_path":"Description/Preprocess.py","file_name":"Preprocess.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"461238608","text":"\"\"\"\nHandle all game menu like intro, outro and pause menu.\n\"\"\"\nimport pygame as pg\nfrom blit_text import blit_text\n\ndef intro(screen, font_title, font_text, font_color):\n \"\"\"\n Intro screen.\n\n Parameters:\n -----------\n screen: Surface of the window (surface)\n font: Font used for the text (font)\n font_color: Color for the text (tuple)\n \"\"\"\n\n screen_half_width = screen.get_width() / 2\n screen_half_heigth = screen.get_height() / 2\n\n text_to_print_intro = \"SPACE INVADER\"\n text_to_print_intro_2 = \"Press SPACE to play or\\n press ESCAPE to exit.\"\n\n blit_text(screen, text_to_print_intro,\n (screen_half_width - 125, screen_half_heigth - 110), font_title, font_color)\n\n blit_text(screen, text_to_print_intro_2,\n (screen_half_width - 75, screen_half_heigth - 25), font_text, font_color)\n\n pg.display.update()\n\n wait_input = True\n while wait_input:\n\n # Quit the game if the quit boutton is pressed or ESCAPE.\n keys = pg.key.get_pressed()\n for event in pg.event.get():\n\n if keys[pg.K_ESCAPE] or (event.type == pg.QUIT):\n wait_input = False\n pg.quit()\n quit()\n\n # Continue to play when SPACE is pressed.\n if keys[pg.K_SPACE]:\n wait_input = False\n\ndef outro(result, screen, font_title_result, font, font_color):\n \"\"\"\n Outro screen.\n\n Parameters:\n -----------\n result: Result of the game (str)\n screen: Surface of the window (surface)\n font: Font used for the text (font)\n font_color: Color used for the text (tuple or list)\n \"\"\"\n # Make the screen black to clear the screen.\n screen.fill((0, 0, 0))\n\n screen_half_width = screen.get_width() / 2\n screen_half_heigth = screen.get_height() / 2\n\n text_to_print_end_game = \"Press SPACE to try again \\nor press ESCAPE to exit.\"\n\n blit_text(screen, result,\n (screen_half_width - 70, screen_half_heigth - 110), font_title_result, font_color)\n blit_text(screen, text_to_print_end_game,\n (screen_half_width - 85, screen_half_heigth - 25), font, font_color)\n\n pg.display.update()\n pg.time.delay(1000)\n\n wait_input = True\n while wait_input:\n\n # Quit the game if the quit boutton is pressed or ESCAPE.\n keys = pg.key.get_pressed()\n\n for event in pg.event.get():\n\n if keys[pg.K_ESCAPE] or (event.type == pg.QUIT):\n wait_input = False\n pg.quit()\n quit()\n\n # Quit if ESCAPE is pressed.\n if keys[pg.K_ESCAPE]:\n wait_input = False\n pg.quit()\n quit()\n\n # Continue if SPACE is pressed.\n if keys[pg.K_SPACE]:\n wait_input = False\n\n\ndef pause(screen, font_title, font, font_color):\n \"\"\"\n Pause the game.\n\n Parameters:\n -----------\n screen: Surface of the window (surface)\n background: Surface of the screen (surface)\n font_title: Font used to print text title on surface (font)\n font: Font used to print text on surface (font)\n font_color: Color of the font (tuple)\n \"\"\"\n paused = True\n screen.fill((0, 0, 0))\n\n screen_half_heigth = screen.get_height() / 2\n screen_half_width = screen.get_width() / 2\n\n text_title = \"Pause\"\n text = \"Press SPACE to resume\"\n\n blit_text(screen, text_title,\n (screen_half_width - 35, screen_half_heigth - 100), font_title, font_color)\n blit_text(screen, text,\n (screen_half_width - 70, screen_half_heigth - 15), font, font_color)\n\n pg.display.flip()\n screen.blit(screen, (0, 0))\n\n while paused:\n\n keys = pg.key.get_pressed()\n for event in pg.event.get():\n\n if event.type == pg.QUIT:\n paused = False\n pg.quit()\n quit()\n\n if keys[pg.K_SPACE]:\n paused = False\n\n\ndef hud(screen, clock, font, life, score):\n \"\"\"\n Display information for the player in game.\n\n Parameters:\n -----------\n screen: Surface of the window(Surface)\n clock: An object to help track time (Clock)\n font: Dictionnary with differente font and color (dict)\n life: Life of the player (int)\n score: Score of the player (int)\n \"\"\"\n version = \"0.2.0\"\n ui_text = \"Life: {} Score: {} FPS: {} Ver: {}\"\n ui_text_to_print = ui_text.format(life, score, int(clock.get_fps()), version)\n blit_text(screen, ui_text_to_print, (0, 0), font[\"basic\"], font[\"color_white\"])\n","sub_path":"game_ui.py","file_name":"game_ui.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"280231986","text":"import pytest\n\nfrom flask_ import url_for\nfrom app import make_app\nfrom configs import TestConfig\nfrom db import Database, DatabaseMixin, Article\nfrom commands import init_db\n\nimport random\nfrom collections import namedtuple\n\n\n@pytest.fixture(scope='function')\ndef client():\n app = make_app(TestConfig)\n\n db = Database(app)\n db.crete_tables()\n app.config['TESTING'] = True\n client = app.test_client()\n client.db = db\n client.app = app\n yield client\n\n db.delete_db()\n\n\ndef test_cli(client):\n run = client.app.test_cli_runner()\n result = run.invoke(init_db)\n assert result.exit_code == 0\n\n\ndef test_index(client):\n r = client.get('/')\n assert r.status_code == 200\n r = client.post('/')\n assert r.status_code == 200\n\ndef test_detail(client):\n r = client.post('/')\n assert r.status_code == 200\n with client.db.init_db():\n id = client.db.c.execute('SELECT id FROM articles DESC LIMIT 1').fetchone()[0]\n with client.app.test_request_context():\n url = url_for('detail', id=id )\n r = client.get(url)\n assert r.status_code == 200\n\n\ndef test_db(client):\n mixin = DatabaseMixin()\n mixin.db = client.db\n mixin.Table = Article\n\n def check_article(first, second):\n assert first.title == second.title\n assert first.subtitle == second.subtitle\n assert first.article == second.article\n assert first.date == second.date\n assert first.image == second.image\n assert first.id == second.id\n\n with mixin.db.init_db():\n with client.app.test_request_context():\n articles = {}\n\n # create\n like_article = namedtuple('article', ['title', 'subtitle', 'article', 'date', 'image', 'id'])\n\n for i in range(1, 11):\n a = mixin.create(f'title{i}', f'subtitle{i}', f'article{i}', f'date{i}', f'image{i}')\n a_ = like_article(f'title{i}', f'subtitle{i}', f'article{i}', f'date{i}', f'image{i}', i)\n check_article(a, a_)\n articles[i] = a\n\n # get_many\n articles_ = mixin.get_many()\n for a_ in articles_:\n a = articles[a_.id]\n check_article(a, a_)\n\n # get_id\n a = articles[random.randrange(1, 11)]\n a_ = mixin.get_id(a.id)\n check_article(a, a_)\n\n # delete_many\n articles_ = mixin.get_many()\n assert len(articles_) == 10\n mixin.delete_many()\n articles_ = mixin.get_many()\n assert len(articles_) == 0\n\n # Article\n obj = Article('title', 'subtitle', 'article' * 100, 'date', 'image', 1)\n assert len(obj.get_text(300)) + len(obj.title) == 300\n\n\n\n","sub_path":"flask_/example2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"599418451","text":"def list_from_csv(path, delimiter=\",\", sort=False, timestamp_idx=2, header=True):\n \"\"\"\n Import a csv event log file as a python list of tuples. We assume that\n the first column is the case identifier.\n \"\"\"\n log = []\n header_skip = 0\n if header:\n header_skip = 1\n\n with open(path, \"r\") as f:\n for line in f:\n if header_skip > 0:\n header_skip -= 1\n continue\n line = line.strip()\n if len(line) == 0:\n continue\n parts = line.split(delimiter)\n event = tuple(parts)\n log.append(event)\n\n if sort and timestamp_idx is not None:\n log.sort(key=lambda event: (event[0], event[timestamp_idx]))\n\n return log\n\n","sub_path":"promstudy/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"467779068","text":"from animation.Animation import AnimationObject\nfrom loading.AudioStreamer import play_place_sound, play_slide_sound\nfrom pygame.math import Vector2 as Vector\nfrom pygame import Surface, Rect\nfrom math import sin, cos\n\nt_fade = 0.4\nt_scroll = 0.25\nt_travel = 0.5\n\n\nclass ScrollArea:\n def __init__(self, table: Surface,\n card_positions: [(int, int)],\n start: int, end: int,\n card_size: (int, int),\n carryover: bool):\n self.initialized = False\n self.carryover = carryover\n region_w = card_size[0] * (end - start)\n region_h = card_size[1]\n # create surface for scrolling\n if self.carryover:\n self.scroll_surface = Surface((region_w + card_size[0], region_h))\n # draw carry over from next row\n carryover_region = Rect(card_positions[end], card_size)\n self.table_carryover = table.subsurface(carryover_region)\n else:\n # expand surface to cover up visual artifacts from scrolling\n trail_brush = int(1 / t_scroll)\n self.scroll_surface = Surface((region_w + trail_brush, region_h))\n # pop cards from table onto area surface\n table_region = Rect(card_positions[start], (region_w, region_h))\n self.table_subsurface = table.subsurface(table_region)\n\n def get_offset(self) -> (int, int):\n return self.table_subsurface.get_offset()\n\n def pop(self):\n self.scroll_surface.blit(self.table_subsurface, (0, 0))\n if self.carryover:\n self.scroll_surface.blit(source=self.table_carryover,\n dest=(self.table_subsurface.get_size()[0], 0))\n self.initialized = True\n\n def scroll(self, delta: int):\n self.scroll_surface.scroll(delta)\n\n def push(self):\n self.table_subsurface.blit(self.scroll_surface, (0, 0))\n self.initialized = False\n\n\ndef fade_out(region: Surface) -> AnimationObject:\n step = AnimationObject()\n fade_surface = Surface(region.get_size())\n fade_surface.blit(region, (0, 0))\n region.fill((0, 0, 0))\n\n def animation_fade_out(ani_srfc, dtime):\n if step.first_call:\n play_slide_sound()\n progress = min(1, step.animation_time/t_fade)\n fade_surface.set_alpha(255*(1-progress))\n ani_srfc.blit(fade_surface, region.get_offset())\n if progress == 1:\n step.done = True\n step.draw_update = animation_fade_out\n return step\n\n\ndef scroll(areas: [ScrollArea], card_w: int) -> AnimationObject:\n step = AnimationObject()\n\n def ani_scroll(ani_srfc, dtime):\n if step.animation_time < t_scroll:\n position = int(step.animation_time / t_scroll * card_w)\n else:\n position = card_w\n step.done = True\n for area in areas:\n if not area.initialized:\n # initialize by fetching scroll pixels from table subsurface\n area.pop()\n # scroll to the left\n prev_position = int((step.animation_time-dtime) / t_scroll * card_w)\n area.scroll(-position+prev_position)\n ani_srfc.blit(area.scroll_surface, area.get_offset())\n # blit back to table using corresponding subsurface\n if step.done:\n area.push()\n step.draw_update = ani_scroll\n return step\n\n\ndef travel(pile_position: (int, int), card_region: Surface, card_back: Surface, card_front: Surface) -> AnimationObject:\n translate = Vector() + card_region.get_offset() - pile_position\n step = AnimationObject()\n\n def animation_draw_card(ani_srfc: Surface, dtime: float):\n if step.first_call:\n play_place_sound()\n progress = min(1, step.animation_time/t_travel)\n ani_srfc.blit(source=card_back,\n dest=pile_position + translate * progress)\n if progress == 1:\n card_region.blit(card_front, (0, 0))\n step.done = True\n step.draw_update = animation_draw_card\n return step\n\n\ndef shaky_card_pile(card: Surface, pile_position, condition_shake, condition_draw):\n pile_x, pile_y = pile_position\n pile = AnimationObject()\n\n def ani_shaky_pile(ani_srfc, dtime):\n if condition_draw():\n if condition_shake():\n timing = pile.animation_time * 5\n shake_x = + 2 * cos(timing)\n shake_y = - 2 * abs(sin(timing))\n ani_srfc.blit(card, (pile_x + shake_x, pile_y + shake_y))\n else:\n ani_srfc.blit(card, (pile_x, pile_y))\n pile.draw_update = ani_shaky_pile\n return pile\n","sub_path":"src/animation/TableAnimations.py","file_name":"TableAnimations.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"559221455","text":"from numpy import array, cov, corrcoef\nimport math\nimport json\n\ndef cov_r(list1, list2):\n if len(list1) != len(list2):\n return False\n data = array([list1, list2])\n cov_matrix = cov(data, bias=1)\n sqrt_delta_x = math.sqrt(cov_matrix[0][0]) \n sqrt_delta_y = math.sqrt(cov_matrix[1][1])\n r = float(cov_matrix[0][1]) / sqrt_delta_x / sqrt_delta_y\n return cov_matrix, r\n\n\nwith open('./data/opensorce_20180104.json') as sourcefile:\n lines = sourcefile.readlines()\nall_languages = {}\nfor line in lines:\n line = json.loads(line)\n if line['main_language'] not in all_languages.keys():\n all_languages[line['main_language']] = []\n all_languages[line['main_language']].append([line[\"project_star\"],line['project_fork']])\nfor key in all_languages:\n list_star = []\n list_fork = []\n for project in all_languages[key]:\n list_star.append(project[0])\n list_fork.append(project[1])\n if len(list_star) < 3:\n continue\n cov_matrix, r = cov_r(list_star, list_fork)\n print(key,'_r:',r,len(list_star))","sub_path":"readcominfo.py","file_name":"readcominfo.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"383857282","text":"from GoogleNews import GoogleNews\nfrom newspaper import Article\nimport newsArticle\nimport pandas as pd\n\n\ndef initialize(query):\n news = GoogleNews()\n news.search(query)\n return news.result()\n\ndef parseData(query):\n \"\"\"Reads in website data, creates a data fram of all scraped articles, and then creates a list of\n newsArticle objects\"\"\"\n\n result = initialize(query)\n df = pd.DataFrame(result)\n return createDict(df)\n\ndef createDict(df):\n newsList = []\n for ind in df.index:\n article = Article(df['link'][ind])\n try:\n article.download()\n article.parse()\n article.nlp()\n\n except:\n pass\n\n if article.text:\n dict = {}\n dict[\"title\"] = article.title\n dict[\"url\"] = article.url\n dict[\"image\"] = df['images']\n # = newsArticle.NewsArticle()\n # news_page.setDate(df['date'][ind])\n # news_page.setMedia(df['media'][ind])\n # news_page.setTitle(article.title)\n # news_page.setArticle(article.text)\n # news_page.setSummary(article.summary)\n # news_page.setImageList(article.imgs)\n # news_page.setUrl(article.url)\n #\n # newsList.append(news_page)\n\n return newsList","sub_path":"googleSearch/newsGetter.py","file_name":"newsGetter.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"426872333","text":"\nimport logging, logging.handlers, logging.config\nfrom socket import error as socket_error\nfrom datetime import datetime\n\nDEFAULT_ROOT_LOG_LEVEL = 'ERROR'\nLOG_LEVEL_NAMES = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL']\n\n\ndef parse_log_level(arg):\n \"\"\"\n Parse a `module=level` log level argument into a module name and a log\n level (as identifiable by the logging module).\n\n Also accepts simply `level` to set the log level of the root logger, in\n which case it returns None as the module name.\n \"\"\"\n if '=' in arg:\n mod, level = arg.split('=', 1)\n else:\n mod = None\n level = arg\n if level.upper() not in LOG_LEVEL_NAMES:\n raise ValueError(\"Invalid log level: \" + level)\n return mod, level.upper()\n\ndef valid_log_level(arg):\n \"\"\"\n Parses the log level to ensure that it's valid, but just returns\n the original string.\n \"\"\"\n # The following call is only for its error-raising side effects.\n parse_log_level(arg)\n return arg\n\n\ndef add_argparse_group(parser):\n \"\"\"Add a configuration group for plumb_util to an argparser\"\"\"\n log_level_help = (\n 'Set the logging level. A bare level (e.g., \"warn\") sets the level of '\n 'the root logger (defaults to \"error\"); arguments of the form '\n '\"module=level\" set the logging level for a particular module (and its '\n 'descendents, unless configured otherwise)')\n group = parser.add_argument_group('find_service', 'SRV lookup configuration')\n group.add_argument('-D', '--domain', type = str, dest = 'zone', default = None,\n help = 'DNS domain to consult for service autodiscovery.')\n group.add_argument('-L', '--loglevel', dest='log_level', action='append',\n default=[], type=valid_log_level,\n help=log_level_help)\n\n\ndef serialize_log_args(log_level_args):\n \"\"\"\n Return a version of the logging arguments suitable to pass on to\n another process also using this module.\n \"\"\"\n args = []\n for arg in log_level_args:\n args.extend(['-L', arg])\n return args\n\n\n# logging.Formatter insists on time tuples (which don't contain sub-second\n# resolution), and strftime format strings don't allow you to specify precision\n# on the microseconds. So we need to subclass. Annoying.\nclass MillisecondLogFormatter(logging.Formatter):\n def formatTime(self, record, dateFmt):\n assert dateFmt.endswith('%f')\n return datetime.fromtimestamp(record.created).strftime(dateFmt)[:-3]\n\n\ndef init_logging(procname, config_dict):\n root_logger = logging.root\n str_fmt = '%(asctime)s ' + procname + ': ' + logging.BASIC_FORMAT\n date_fmt = '%b %d %H:%M:%S.%f'\n log_fmt = MillisecondLogFormatter(str_fmt, date_fmt)\n\n stderr_handler = logging.StreamHandler()\n stderr_handler.setFormatter(log_fmt)\n root_logger.addHandler(stderr_handler)\n\n try:\n syslog_handler = logging.handlers.SysLogHandler(\n address='/dev/log',\n facility=logging.handlers.SysLogHandler.LOG_LOCAL0)\n except socket_error:\n root_logger.warn('unable to initialize syslog logger')\n else:\n syslog_handler.setFormatter(log_fmt)\n root_logger.addHandler(syslog_handler)\n\n # Use the config_dict to only update the log levels.\n logging.config.dictConfig(dict(\n config_dict, incremental=True, version=1))\n\n return root_logger\n\ndef logger_from_args(args, procname):\n levels = {None: DEFAULT_ROOT_LOG_LEVEL}\n levels.update(map(parse_log_level, args.log_level))\n\n config_dict = {'root': {'level': levels.pop(None)}}\n config_dict['loggers'] = {module: {'level': level}\n for module, level in levels.iteritems()}\n\n return init_logging(procname, config_dict)\n\n","sub_path":"plumb_util/args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"342208058","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n\ndef plot_wind_rose(dirs,yval,color='blue',alpha=0.25,title=False,titlesize=20,titlefont='serif',\\\n tics=False,ticangle=-45.,ticlabels=False,ticlabelsize=18,ticlabelfont='serif',\\\n dirsize=20,dirfont='serif'):\n\n \"\"\"create wind rose plot.\n must save figure outside of this function\n must call plt.show() if you want the figure to remain shown\n\n\n INPUTS\n ______________________________________________________________________________\n dirs: wind directions in degrees as an numpy array\n yval: wind value (frequency or wind speed) as a numpy array\n\n color: color of the wind rose, default pyplot colors (string) or custom RBG values (float)\n alpha: transparancy of the wind rose as a float as a float\n title: plot title as a string. This must be active for the other title options to work\n titlesize: title font size as a float\n titlefont: title font family\n tics: locations of custom tics as a tuple. This must be active for the other tic options to work\n ticangle: angle of the tic labels\n ticlabels: custom tic labels as a tuple. This must be active for the other ticlabel options to work\n ticlabelsize: font size of the tic labels\n ticlabelfont: font family of the tic labels\n dirsize: font size of the directions\n dirfont: font size of the directions\n \"\"\"\n\n nDirections = len(dirs)\n dirs += 270.\n for i in range(nDirections):\n dirs[i] = np.radians(dirs[i])*-1.\n width = (2*np.pi) / nDirections\n dirs = dirs-width/2.\n max_height = np.max(yval)\n ax = plt.subplot(111, polar=True)\n bars = ax.bar(dirs, yval, width=width, bottom=0., color=color,alpha=alpha)\n ax.set_xticklabels(['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE'],fontsize=dirsize,family=dirfont)\n\n if tics:\n ax.set_rgrids(tics, angle=ticangle)\n else:\n max_tic = float(format(max(yval), '.1g'))\n ax.set_rgrids([max_tic/3.,2.*max_tic/3.,max_tic], angle=ticangle)\n\n if ticlabels:\n ax.set_yticklabels(ticlabels,fontsize=ticlabelsize,family=ticlabelfont)\n if title:\n plt.title(title, y=1.09,fontsize=titlesize,family=titlefont)\n plt.tight_layout()\n plt.draw()\n plt.pause(0.001)\n\n\n\n\ndef plot_turbine_locations(turbineX,turbineY,rotorDiameter,color='blue',alpha=0.25,title=False,titlesize=20,titlefont='serif',\\\n starting=False,startingX=False,startingY=False,starting_color='red',staring_alpha=0.25,lines=False,linecolor='black',linestyle='solid',\\\n circle_boundary=False,farm_radius=False,farm_center=(0.,0.),\\\n custom_boundary=False,boundaryX=False,boundaryY=False,\n boundary_color='black',boundary_line='dashed',boundary_width=1,farm_bounds=False):\n\n \"\"\"plot wind farm layouts.\n must save figure outside of this function\n must call plt.show() if you want the figure to remain shown when the program ends\n\n INPUTS\n ______________________________________________________________________________\n turbineX: numpy array of x locations\n turbineY: numpy array of y locations\n rotorDiameter: numpy array of turbine rotor diameters\n\n color: color of turbines, default pyplot colors (string) or custom RBG values (float)\n alpha: transparancy of the turbines as a float as a float\n title: plot title as a string. This must be active for the other title options to work\n titlesize: title font size as a float\n titlefont: title font family\n starting: True if you want to compare the starting locations to final locations\n startingX: numpy array of starting x locations\n startingY: numpy array of starting y locations\n starting_color: color of starting turbines, default pyplot colors (string) or custom RBG values (float)\n staring_alpha: transparancy of the starting turbines as a float as a float\n lines: True if you want lines connecting each starting turbine to its final location\n linecolor: color or lines connecting turibnes\n linestyle: style of lines connecting turbines\n circle_boundary: True if you want to display a circular wind farm boundary\n farm_radius: circular wind farm boundary radius (float)\n farm_center: circular wind farm boundary center (x,y)\n custom_boundary: True if you want to define a custom wind farm boundary\n boundaryX: numpy array of x values for a custom wind farm boundary\n boundaryY: numpy array of y values for a custom wind farm boundary\n boundary_color: color of the wind farm boundary\n boundary_line: line style of the wind farm boundary\n boundary_width: line width of the wind farm boundary\n farm_bounds: custom axis bounds on the plot (xmin,xmax,ymin,ymax)\n \"\"\"\n\n\n nTurbines = len(turbineX)\n for i in range(nTurbines):\n if starting:\n opt_turbine = plt.Circle((startingX[i],startingY[i]),rotorDiameter[i]/2.,fc=starting_color,alpha=staring_alpha,lw=0.)\n plt.gca().add_patch(opt_turbine)\n if lines:\n plt.plot(np.array([startingX[i],turbineX[i]]),np.array([startingY[i],turbineY[i]]),color=linecolor,linestyle=linestyle)\n\n turbine = plt.Circle((turbineX[i],turbineY[i]),rotorDiameter[i]/2.,fc=color,alpha=alpha,lw=0.)\n plt.gca().add_patch(turbine)\n\n if circle_boundary:\n farm_boundary = plt.Circle(farm_center,farm_radius,linestyle=boundary_line,fc='none',edgecolor=boundary_color,linewidth=boundary_width)\n plt.gca().add_patch(farm_boundary)\n elif custom_boundary:\n plt.plot(boundaryX,boundaryY,color=boundary_color,linestyle=boundary_line,linewidth=boundary_width)\n\n\n \"\"\"limits on the axes\"\"\"\n plt.axis('equal')\n if farm_bounds:\n plt.axis(farm_bounds)\n elif circle_boundary:\n plt.xlim(farm_center[0]-farm_radius-2.*rotorDiameter[0],farm_center[0]+farm_radius+2.*rotorDiameter[0])\n plt.ylim(farm_center[1]-farm_radius-2.*rotorDiameter[0],farm_center[1]+farm_radius+2.*rotorDiameter[0])\n else:\n plt.xlim(min(turbineX)-2.*rotorDiameter[0],max(turbineX)+2.*rotorDiameter[0])\n plt.ylim(min(turbineY)-2.*rotorDiameter[0],max(turbineY)+2.*rotorDiameter[0])\n\n if title:\n plt.title(title,fontsize=titlesize,family=titlefont)\n\n plt.axis('off')\n plt.tight_layout()\n plt.draw()\n plt.pause(0.001)\n\n\nif __name__==\"__main__\":\n\n \"\"\"test wind rose\"\"\"\n # wf = np.array([1.17812570e-02, 1.09958570e-02, 9.60626600e-03, 1.21236860e-02,\n # 1.04722450e-02, 1.00695140e-02, 9.68687400e-03, 1.00090550e-02,\n # 1.03715390e-02, 1.12172280e-02, 1.52249700e-02, 1.56279300e-02,\n # 1.57488780e-02, 1.70577560e-02, 1.93535770e-02, 1.41980570e-02,\n # 1.20632100e-02, 1.20229000e-02, 1.32111160e-02, 1.74605400e-02,\n # 1.72994400e-02, 1.43993790e-02, 7.87436000e-03, 0.00000000e+00,\n # 2.01390000e-05, 0.00000000e+00, 3.42360000e-04, 3.56458900e-03,\n # 7.18957000e-03, 8.80068000e-03, 1.13583200e-02, 1.41576700e-02,\n # 1.66951900e-02, 1.63125500e-02, 1.31709000e-02, 1.09153300e-02,\n # 9.48553000e-03, 1.01097900e-02, 1.18819700e-02, 1.26069900e-02,\n # 1.58895900e-02, 1.77021600e-02, 2.04208100e-02, 2.27972500e-02,\n # 2.95438600e-02, 3.02891700e-02, 2.69861000e-02, 2.21527500e-02,\n # 2.12465500e-02, 1.82861400e-02, 1.66147400e-02, 1.90111800e-02,\n # 1.90514500e-02, 1.63932050e-02, 1.76215200e-02, 1.65341460e-02,\n # 1.44597600e-02, 1.40370300e-02, 1.65745000e-02, 1.56278200e-02,\n # 1.53459200e-02, 1.75210100e-02, 1.59702700e-02, 1.51041500e-02,\n # 1.45201100e-02, 1.34527800e-02, 1.47819600e-02, 1.33923300e-02,\n # 1.10562900e-02, 1.04521380e-02, 1.16201970e-02, 1.10562700e-02])\n # nDirections = len(wf)\n # dirs = np.linspace(0,360-360/nDirections, nDirections)\n # color = 'red'\n # alpha = 0.25\n # title = 'Amalia Wind Rose'\n # titlesize = 20\n # titlefont = 'serif'\n # tics = [0.01,0.02,0.03]\n # ticlabels = ['1%','2%','3%']\n # ticangle= -45.\n # plot_wind_rose(dirs,wf)\n # # plot_wind_rose(dirs,wf,color=color,alpha=alpha,title=title,titlesize=titlesize,titlefont=titlefont,\\\n # # tics=tics,ticangle=ticangle,ticlabels=ticlabels,ticsize=18,ticfont='serif',dirsize=20,dirfont='serif')\n #\n # plt.show()\n\n\n \"\"\"test layout plot\"\"\"\n turbineX = np.array([0.,0.,0.,500.,500.,500.,1000.,1000.,1000.])\n turbineY = np.array([0.,500.,1000.,0.,500.,1200.,0.,500.,1000.])\n startingX = np.array([0.,0.,0.,500.,500.,500.,1000.,1000.,1000.])+np.random.rand(len(turbineX))*100.\n startingY = np.array([0.,500.,1000.,0.,500.,1200.,0.,500.,1000.])+np.random.rand(len(turbineX))*100.\n rotorDiameter = np.ones(len(turbineX))*100.\n plot_turbine_locations(turbineX,turbineY,rotorDiameter,starting=True,startingX=startingX,startingY=startingY,color='blue',lines=True,circle_boundary=True,farm_radius=1000.*np.sqrt(2))\n plt.show()\n plot_turbine_locations(turbineX,turbineY,rotorDiameter)\n plt.show()\n","sub_path":"image_gen/wind_farm_visualization.py","file_name":"wind_farm_visualization.py","file_ext":"py","file_size_in_byte":9471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"165423784","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 27 21:43:34 2018\n\n@author: TZQ88888\n\"\"\"\nimport xarray as xr\nfrom glob import glob\nimport pandas as pd\nimport numpy as np\nglobal fr_list,type_list\ntype_list=['IGBP','UMD','LAI','BGC','PFT']\nfr_list=['Fr_Paved','Fr_Bldgs','Fr_EveTr','Fr_DecTr','Fr_Grass','Fr_Bsoil','Fr_Water']\n \npath='Processed/*vrt*tif'\ndef counts(path,lat=40,lon=116,r=0.05):\n fl_cvt = glob(path)\n \n fl_cvt[0].split('LC_')[-1].split('_')[0]\n \n # using xarray to subset GeoTiffs\n ds_cvt = xr.Dataset(\n {fn.split('LC_')[-1].split('_')[0]:\n xr.open_rasterio(fn).squeeze(drop=True)\n for fn in fl_cvt}).rename(\n {'Type1': 'IGBP', 'Type2': 'UMD',\n 'Type3': 'LAI', 'Type4': 'BGC', 'Type5': 'PFT'})\n da_cvt = ds_cvt.to_array(dim='type')\n type_list=['IGBP','UMD','LAI','BGC','PFT']\n\n\n lat_min=lat-r\n lat_max=lat+r\n lon_min=lon-r\n lon_max=lon+r\n counts=[pd.DataFrame(\n {var:values for var,values in zip(np.unique(da_cvt.loc[i, lat_max:lat_min, lon_min:lon_max].values,return_counts=True)[0],np.unique(da_cvt.loc[i, lat_max:lat_min, lon_min:lon_max].values,return_counts=True)[1])},index=[i])for i in type_list]\n counts=pd.concat(counts)\n return counts.T\n\ndef rule(x,ra_type,fr_rule):\n# print (x)\n \n for fr in fr_list:\n try:\n rule_list=fr_rule[fr].at[ra_type].split(',')\n except: \n rule_list=str(fr_rule[fr].at[ra_type])\n \n# print (rule_list) \n if str(x) in rule_list:\n\n return fr\n\ndef fr_get(count):\n fr=[] \n \n for i in type_list:\n fr_rule=pd.read_csv('rule.txt',sep='\\s+')\n df=count[i].reset_index()\n df['fr']=df['index'].apply(rule,ra_type=i,fr_rule=fr_rule)\n df1=df.drop(['index'],axis = 1).groupby('fr').sum()\n df2=(df1/df1.sum()).round(2)\n \n fr.append(df2)\n fr=pd.concat(fr,axis=1) \n return fr.T\n\ndef w_siteSelect(fr,cover_type='IGBP'):\n SUEWS_SiteSelect_path=r'archive/SUEWS_SiteSelect.txt' \n \n siteSelect=pd.read_csv(SUEWS_SiteSelect_path,sep='\\s+',skiprows=1)\n for i in fr_list:\n siteSelect[i].loc[0]=0\n for var in fr.columns:\n siteSelect[var].loc[0]=fr[var].loc[cover_type]\n siteSelect=siteSelect.T.reset_index().T \n siteSelect.to_csv('SUEWS_SiteSelect.txt',index=None,sep=' ')\n\ncount=counts(path,lat=29.58,lon=106.47,r=0.05)\nfr=fr_get(count).fillna(0)\nw_siteSelect(fr,cover_type='IGBP') ","sub_path":"Chongqing-LoHCool/landcover_image/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"379843674","text":"import copy\nimport numpy as np\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef nelder_mead(\n fun, \n x0: np.ndarray,\n initial_step=0.1,\n no_improve_thr=10e-6, \n no_improve_break=10,\n maxiter=0,\n alpha=1., gamma=2., rho=-0.5, sigma=0.5,\n verbose=False\n ):\n '''\n parameters:\n fun (function): function to optimize, must return a scalar score\n and operate over a numpy array of the same dimensions as x0\n x0 (numpy array): initial position\n initial_step (float/np array): determines the stepsize to construct\n the initial simplex. If a float is specified it uses the same\n value for all parameters, if an array is specified it uses\n the specified step for each parameter.\n\n no_improve_thr, no_improve_break (float, int): \n break after no_improve_break iterations \n with an improvement lower than no_improve_thr\n maxiter (int): always break after this number of iterations.\n Set it to 0 to loop indefinitely.\n alpha (float): reflection coefficient\n gamma (float): expansion coefficient\n rho (float): contraction coefficient\n sigma (float): shrink coefficient\n For details on these parameters see Wikipedia page\n\n return: tuple (best parameter array, best score)\n\n\n Pure Python/Numpy implementation of the Nelder-Mead algorithm.\n Implementation from https://github.com/fchollet/nelder-mead, edited by\n Adriaan Rol for use in PycQED.\n Reference: https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method\n '''\n # init\n x0 = np.array(x0) # ensures algorithm also accepts lists\n dim = len(x0)\n prev_best = fun(x0)\n no_improve = 0\n res = [[x0, prev_best]]\n if type(initial_step) is float:\n initial_step_matrix = np.eye(dim)*initial_step\n elif (type(initial_step) is list) or (type(initial_step) is np.ndarray):\n if len(initial_step) != dim:\n raise ValueError('initial_step array must be same lenght as x0')\n initial_step_matrix = np.diag(initial_step)\n else:\n raise TypeError('initial_step ({})must be list or np.array'.format(\n type(initial_step)))\n\n for i in range(dim):\n x = copy.copy(x0)\n x = x + initial_step_matrix[i]\n score = fun(x)\n res.append([x, score])\n\n # simplex iter\n iters = 0\n while 1:\n # order\n res.sort(key=lambda x: x[1])\n best = res[0][1]\n\n # break after maxiter\n if maxiter and iters >= maxiter:\n # Conclude failure break the loop\n if verbose:\n print('max iterations exceeded, optimization failed')\n break\n iters += 1\n\n if best < prev_best - no_improve_thr:\n no_improve = 0\n prev_best = best\n else:\n no_improve += 1\n\n if no_improve >= no_improve_break:\n # Conclude success, break the loop\n if verbose:\n print('No improvement registered for {} rounds,'.format(\n no_improve_break) + 'concluding succesful convergence')\n break\n\n # centroid\n x0 = [0.] * dim\n for tup in res[:-1]:\n for i, c in enumerate(tup[0]):\n x0[i] += c / (len(res)-1)\n\n # reflection\n xr = x0 + alpha*(x0 - res[-1][0])\n rscore = fun(xr)\n if res[0][1] <= rscore < res[-2][1]:\n del res[-1]\n res.append([xr, rscore])\n continue\n\n # expansion\n if rscore < res[0][1]:\n xe = x0 + gamma*(x0 - res[-1][0])\n escore = fun(xe)\n if escore < rscore:\n del res[-1]\n res.append([xe, escore])\n continue\n else:\n del res[-1]\n res.append([xr, rscore])\n continue\n\n # contraction\n xc = x0 + rho*(x0 - res[-1][0])\n cscore = fun(xc)\n if cscore < res[-1][1]:\n del res[-1]\n res.append([xc, cscore])\n continue\n\n # reduction\n x1 = res[0][0]\n nres = []\n for tup in res:\n redx = x1 + sigma*(tup[0] - x1)\n score = fun(redx)\n nres.append([redx, score])\n res = nres\n\n # once the loop is broken evaluate the final value one more time as\n # verification\n fun(res[0][0])\n return res[0]\n\n\ndef SPSA(fun, x0,\n initial_step=0.1,\n no_improve_thr=10e-6, no_improv_break=10,\n maxiter=0,\n gamma=0.101, alpha=0.602, a=0.2, c=0.3, A=300,\n p=0.5, ctrl_min=0., ctrl_max=np.pi,\n verbose=False):\n '''\n parameters:\n fun (function): function to optimize, must return a scalar score\n and operate over a numpy array of the same dimensions as x0\n x0 (numpy array): initial position\n\n\n no_improv_thr, no_improv_break (float, int): break after\n no_improv_break iterations with an improvement lower than\n no_improv_thr\n maxiter (int): always break after this number of iterations.\n Set it to 0 to loop indefinitely.\n alpha, gamma, a, c, A, (float): parameters for the SPSA gains\n (see refs for definitions)\n p (float): probability to get 1 in Bernoulli +/- 1 distribution\n (see refs for context)\n ctrl_min, ctrl_max (float/array): boundaries for the parameters.\n can be either a global boundary for all dimensions, or a\n numpy array containing the boundary for each dimension.\n return: tuple (best parameter array, best score)\n\n alpha, gamma, a, c, A and p, are parameters for the algorithm.\n Their function is described in the references below,\n and even optimal values have been discussed in the literature.\n\n\n Pure Python/Numpy implementation of the SPSA algorithm designed by Spall.\n Implementation from http://www.jhuapl.edu/SPSA/PDF-SPSA/Spall_An_Overview.PDF,\n edited by Ramiro Sagastizabal for use in PycQED.\n Reference: http://www.jhuapl.edu/SPSA/Pages/References-Intro.htm\n '''\n # init\n x0 = np.array(x0) # ensures algorithm also accepts lists\n dim = len(x0)\n prev_best = fun(x0)\n no_improv = 0\n res = [[x0, prev_best]]\n\n x = copy.copy(x0)\n\n # SPSA iter\n iters = 0\n while 1:\n # order\n res.sort(key=lambda x: x[1])\n best = res[0][1]\n\n # break after maxiter\n if maxiter and iters >= maxiter:\n # Conclude failure break the loop\n if verbose:\n print('max iterations exceeded, optimization failed')\n break\n iters += 1\n\n if best < prev_best - no_improve_thr:\n no_improv = 0\n prev_best = best\n else:\n no_improv += 1\n\n if no_improv >= no_improv_break:\n # Conclude success, break the loop\n if verbose:\n print('No improvement registered for {} rounds,'.format(\n no_improv_break) + 'concluding succesful convergence')\n break\n # step 1\n a_k = a/(iters+A)**alpha\n c_k = c/iters**gamma\n # step 2\n delta = np.where(np.random.rand(dim) > p, 1, -1)\n # step 3\n x_plus = x+c_k*delta\n x_minus = x-c_k*delta\n y_plus = fun(x_plus)\n y_minus = fun(x_minus)\n # res.append([x_plus, y_plus])\n # res.append([x_minus, y_minus])\n # step 4\n gradient = (y_plus-y_minus)/(2.*c_k*delta)\n # step 5\n x = x-a_k*gradient\n x = np.where(x < ctrl_min, ctrl_min, x)\n x = np.where(x > ctrl_max, ctrl_max, x)\n score = fun(x)\n log.warning(\"SPSA: Evaluated gradient at x_minus={};x_plus={}\".format(x_minus,\n x_plus))\n log.warning(\"SPSA: y_minus={};y_plus={}\".format(y_plus,\n y_minus))\n log.warning(\"SPSA: Gradient={}\".format(gradient))\n log.warning(\"SPSA: Jump={};new_x={}\".format(a_k*gradient, x))\n res.append([x, score])\n\n # once the loop is broken evaluate the final value one more time as\n # verification\n fun(res[0][0])\n return res[0]\n\n# ######################################################################\n# Some utilities\n# ######################################################################\n\n\ndef multi_targets_phase_offset(target, spacing, phase_name: str = None):\n \"\"\"\n Intended to be used in cost functions that targets several phases\n at the same time equaly spaced\n\n Args:\n target(float): unit = deg, target phase for which the output\n will be zero\n\n spacing(float): unit = deg, spacing > 0, spacing to other phases\n for which the output will be zero\n\n phase_name(str): if specified a string version of the function\n will be returned, inteded for the construction of a custom\n cost lambda function including other terms, e.g. some\n other target phase using this funtion.\n NB: numpy needs to be defined as \"np\" in the file the string\n function will be executed\n \"\"\"\n target = np.asarray(target)\n if phase_name is not None:\n string = 'np.min([({phase_name} - {target}) % {spacing}, (360 - ({phase_name} - {target})) % {spacing}])'\n return string.format(\n phase_name=phase_name,\n target=str(target),\n spacing=str(spacing))\n else:\n return lambda phase: np.min([(phase - target) % spacing, (360 - (phase - target)) % spacing], axis=0)\n","sub_path":"pycqed/measurement/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":9763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"593910853","text":"# https://stackoverflow.com/questions/7207309/how-to-run-functions-in-parallel\r\nfrom __future__ import print_function\r\nimport os\r\nimport time\r\nfrom multiprocessing import Process\r\nfrom typing import List, Tuple, Union\r\nfrom subprocess import Popen, PIPE, STDOUT\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nclass Preprocess(object):\r\n \r\n def __init__(self, input_size, fill_value : int =128):\r\n \"\"\"\r\n Initialize parametyers for preprocessing.\r\n Parameters\r\n ----------\r\n input_size : int or tuple\r\n input dimensions of the input image\r\n may be tuple of (H, W) or an int\r\n fill_value : int\r\n Fill-in values for padding areas\r\n \"\"\"\r\n self.input_size = input_size\r\n self.fill_value = fill_value\r\n\r\n if isinstance(self.input_size, List) or isinstance(self.input_size, Tuple):\r\n assert self.input_size[0] == self.input_size[1] , \"Input weight and width are not the same.\"\r\n self.input_size = int(self.input_size[0])\r\n \r\n @staticmethod\r\n def _aspectaware_resize_padding(image, width, height, interpolation=None, means=None):\r\n \"\"\"\r\n Pads input image without losing the aspect ratio of the original image\r\n Parameters\r\n ----------\r\n image : numpy array\r\n In BGR format\r\n uint8 numpy array of shape (img_h, img_w, 3)\r\n width : int\r\n width of newly padded image\r\n height : int\r\n height of newly padded image\r\n interpolation : str\r\n method, to be applied on the image for resizing\r\n \r\n Returns\r\n ------- \r\n canvas : numpy array\r\n float 32 numpy array of shape (height, width, 3)\r\n new_w : int\r\n width, of the image after resizing without losing aspect ratio\r\n new_h : int\r\n height, of the image after resizing without losing aspect ratio\r\n old_w : int\r\n width, of the image before padding\r\n old_h : int\r\n height, of the image before padding\r\n padding_w : int\r\n width, of the image after padding\r\n padding_h : int\r\n height, of the image after padding\r\n \"\"\"\r\n\r\n old_h, old_w, _ = image.shape\r\n if old_w > old_h:\r\n new_w = width\r\n new_h = int(width / old_w * old_h)\r\n else:\r\n new_w = int(height / old_h * old_w)\r\n new_h = height\r\n \r\n # resize the image by maintaining aspect ratio\r\n if new_w != old_w or new_h != old_h:\r\n if interpolation is None:\r\n image = cv2.resize(image, (new_w, new_h))\r\n else:\r\n image = cv2.resize(image, (new_w, new_h), interpolation=interpolation)\r\n\r\n padding_h = height - new_h\r\n padding_w = width - new_w\r\n\r\n # parameter for inserting resized image to the middle of canvas\r\n h_start = max(0, height - new_h) // 2\r\n w_start = max(0, width - new_w) // 2\r\n\r\n # pad the resized-contrast ratio maintained image to get desired dimensions\r\n image = cv2.copyMakeBorder(image, h_start, h_start, w_start, w_start, cv2.BORDER_CONSTANT, value=[means, means, means])\r\n\r\n return image, new_w, new_h, old_w, old_h, padding_w, padding_h,\r\n\r\n def __call__(self, img):\r\n \"\"\"\r\n Preprocess an image for YOLOv5 TensorRT model inferencing.\r\n Parameters\r\n ----------\r\n img : numpy array\r\n In BGR format\r\n uint8 numpy array of shape (img_h, img_w, 3)\r\n \r\n Returns\r\n -------\r\n img : numpy array\r\n preprocessed image\r\n float32 numpy array of shape (3, H, W)\r\n metas : list\r\n list containing additional informations about the image\r\n \"\"\"\r\n # resize the image and pad the image by maintaining contrast ratio\r\n img_meta = self._aspectaware_resize_padding(image=img, width=self.input_size, \r\n height=self.input_size, interpolation=cv2.INTER_LINEAR, means=self.fill_value)\r\n\r\n img = np.transpose(img_meta[0], (2, 0, 1)).astype(np.float32)\r\n img = np.expand_dims(img, axis=0)\r\n img /= 255.0\r\n\r\n return img\r\n\r\ndef extract_frames_ffmpeg(video_path, folder_path):\r\n print(\"Extracting frames from {}\".format(video_path))\r\n\r\n abs_video_path = os.path.abspath(video_path)\r\n folder_path = \"data/{:s}\".format(folder_path)\r\n\r\n command = \"ffmpeg -hide_banner -loglevel error -i {:s} {:s}/out-%04d.jpg\".format(abs_video_path, folder_path)\r\n\r\n # Execute Command\r\n process = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)\r\n for line in iter(process.stdout.readline, b''):\r\n print(line.rstrip().decode('utf-8'))\r\n process.stdout.close()\r\n process.wait()\r\n\r\n print(\"Extracting frames from {:s} done!\".format(abs_video_path))\r\n\r\ndef extract_preprocessed_frames_opencv(video_path, folder_name):\r\n print(\"Extracting frames from {}\".format(video_path))\r\n\r\n abs_video_path = os.path.abspath(video_path)\r\n folder_path = \"data/{:s}\".format(folder_name)\r\n preprocess_fn = Preprocess(input_size = 640)\r\n\r\n count = 0\r\n vidcap = cv2.VideoCapture(abs_video_path)\r\n\r\n while True:\r\n success, image = vidcap.read()\r\n\r\n if not success:\r\n break\r\n else:\r\n npy_path = \"%s/out-%04d.npy\" % (folder_path, count)\r\n npy = preprocess_fn(image)\r\n np.save(npy_path, npy)\r\n success,image = vidcap.read()\r\n count += 1\r\n\r\n print(\"Extracting and Preprocessing frames from {:s} done!\".format(abs_video_path))\r\n\r\nif __name__ == \"__main__\":\r\n\r\n all_videos = [\"C:\\\\Users\\\\Htut Lynn Aung\\Desktop\\work\\AsyncCV\\\\videos\\\\1.mp4\",\r\n \"C:\\\\Users\\\\Htut Lynn Aung\\Desktop\\work\\AsyncCV\\\\videos\\\\2.mp4\",\r\n \"C:\\\\Users\\\\Htut Lynn Aung\\Desktop\\work\\AsyncCV\\\\videos\\\\3.mp4\",\r\n \"C:\\\\Users\\\\Htut Lynn Aung\\Desktop\\work\\AsyncCV\\\\videos\\\\4.mp4\"]\r\n\r\n start_time = time.time()\r\n\r\n for i in range(4):\r\n video = all_videos[i]\r\n frames_folder = str(i + 1)\r\n extract_preprocessed_frames_opencv(video_path=video,\r\n folder_name=frames_folder)\r\n \r\n end_time = time.time()\r\n\r\n print(\"Total elapsed time : {}\".format(end_time - start_time))","sub_path":"sequential_np.py","file_name":"sequential_np.py","file_ext":"py","file_size_in_byte":6786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"450486552","text":"#!/usr/bin/python3\n\"\"\"\nmodule to create a new view for State objects that\nhandles all default RESTFul API actions\n\n\"\"\"\n\nfrom api.v1.views import app_views\nfrom flask import Flask\nfrom flask import jsonify\nfrom models.city import City\nfrom models.state import State\nfrom models.place import Place\nfrom models.user import User\nfrom models.review import Review\nfrom models import storage\nfrom flask import request\nfrom flask import abort\n\n\n@app_views.route('/places//reviews', strict_slashes=False)\ndef retrive_reviews(place_id):\n \"\"\"Retrieves the list of all State objects\"\"\"\n try:\n review_list = []\n place_obj = storage.get(Place, place_id)\n for review_obj in place_obj.reviews:\n review_list.append(review_obj.to_dict())\n return (jsonify(review_list))\n except:\n abort(404)\n\n\n@app_views.route('/reviews/', strict_slashes=False)\ndef retrive_reviews_by_id(review_id):\n \"\"\"Retrieves a State object\"\"\"\n try:\n obj = storage.get(Review, review_id)\n return (jsonify(obj.to_dict()))\n except:\n abort(404)\n\n\n@app_views.route(\n '/reviews/',\n strict_slashes=False,\n methods=['DELETE']\n)\ndef delete_reviews_by_id(review_id):\n \"\"\"Deletes a State object\"\"\"\n try:\n obj = storage.get(Review, review_id)\n State.delete(obj)\n storage.save()\n return ({}), 200\n except:\n abort(404)\n\n\n@app_views.route(\n 'places//reviews',\n strict_slashes=False,\n methods=['POST'])\ndef create_reviews(place_id):\n \"\"\"Creates a State\"\"\"\n json_data = request.get_json()\n if not (json_data):\n abort(400, 'Not a JSON')\n elif ('name' not in json_data.keys()):\n abort(400, 'Missing name')\n else:\n try:\n state_obj = storage.get(Place, place_id)\n storage.get(User, user_id)\n new_place = Review()\n if ('user_id' in state_obj.keys()):\n setattr(new_place, 'user_id', json_data['user_id'])\n else:\n abort(400, 'Missing user_id')\n if ('text' in state_obj.keys()):\n setattr(new_place, 'text', json_data['text'])\n else:\n abort(400, 'Missing text')\n storage.new(new_place)\n storage.save()\n return (jsonify(new_place.to_dict()), 201)\n except:\n abort(404)\n\n\n@app_views.route(\n '/reviews/',\n strict_slashes=False,\n methods=['PUT']\n )\ndef update_reviews(review_id):\n \"\"\"Updates a State object\"\"\"\n try:\n json_data = request.get_json()\n if not (json_data):\n abort(400, 'Not a JSON')\n else:\n obj = storage.get(Review, review_id)\n if ('text' in state_obj.keys()):\n setattr(obj, 'text', json_data['text'])\n storage.save()\n return (jsonify(obj.to_dict()), 200)\n except:\n abort(404)\n","sub_path":"api/v1/views/places_reviews.py","file_name":"places_reviews.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"557729268","text":"#!/usr/bin/python3\n\"\"\"\ncommit.py - what the commit\nauthor: mutantmonkey \n\"\"\"\n\nimport web\nfrom tools import GrumbleError\n\n\ndef commit(phenny, input):\n \"\"\".commit - Get a What the Commit commit message.\"\"\"\n\n msg = web.get(\"http://whatthecommit.com/index.txt\")\n phenny.reply(msg)\ncommit.commands = ['commit']\n\nif __name__ == '__main__':\n print(__doc__.strip())\n","sub_path":"modules/commit.py","file_name":"commit.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"517016867","text":"\n\nclass Tarefas:\n\n\n def __init__(self,lista,redolista):\n self.lista\n self.redolista\n\n def display(lista):\n print()\n print(\"Tasks: \")\n print(lista)\n\n def undo(self, redolista, lista):\n if not self.lista:\n print('Nothing list')\n return\n lastlista = lista.pop()\n self.redolista.append(lastlista)\n\n def redo(self,lista, redolista):\n if not self.lista:\n print('Nothing list')\n return\n lastlista = redolista.pop()\n self.lista.append(lastlista)\n\n def add(self,option, lista):\n self.lista.append(option)\n\n\n\n\nif __name__ == '__main__':\n lista = []\n redolista = []\n while True:\n option = input('Enter your list\\n|1-Undo , 2-redo , 3-print list| \\n')\n if option == 'print':\n lista.display(lista)\n continue\n elif option == 'undo':\n lista.undo(lista, redolista)\n continue\n elif option == 'redo':\n lista.redo(lista, redolista)\n continue\n\n lista.add(option, lista)\n","sub_path":"Curso python/Cursopy/poo/testeclasse.py","file_name":"testeclasse.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"497163968","text":"#fare per hour on day of week\nfrom __future__ import print_function\nimport sys\nimport csv\nfrom operator import add\nfrom datetime import datetime\nfrom pyspark import SparkContext\n\nif __name__ == \"__main__\":\n sc = SparkContext(appName=\"PythonWordCount\")\n data1=\"/Users/DMRC/Downloads/taxi.csv\"\n lines = sc.textFile(data1)\n lines=lines.mapPartitions(lambda x: csv.reader(x))\n fare_dayofweek = lines.map(lambda x: (x[12],x[1])).filter(lambda x: x[1]!=\"tpep_pickup_datetime\").map(lambda x: ((datetime.strptime(x[1],\"%Y-%m-%d %H:%M:%S\").strftime('%A'),datetime.strptime(x[1],\"%Y-%m-%d %H:%M:%S\").hour), float(x[0]))).reduceByKey(add)\n trips_dayofweek = lines.map(lambda x: (x[12],x[1])).filter(lambda x: x[1]!=\"tpep_pickup_datetime\").map(lambda x: ((datetime.strptime(x[1],\"%Y-%m-%d %H:%M:%S\").strftime('%A'),datetime.strptime(x[1],\"%Y-%m-%d %H:%M:%S\").hour), 1)).reduceByKey(add)\n trip_output = trips_dayofweek.collect()\n fare_output = fare_dayofweek.collect()\n for day1,count in trip_output:\n #print(\"%s, %i\" % (day1,count))\n for day2,sum in fare_output:\n if day1 == day2:\n print(\"%s , %.2f\" % (day1,sum/count))\n sc.stop()","sub_path":"Spark_Jobs/Fare_per_hour_on_day_of_week.py","file_name":"Fare_per_hour_on_day_of_week.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"454866330","text":"class Solution(object):\n\n def findLengthOfLCIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n\n dp_array = [1]*2 # space optimization\n max_len = 1\n\n for i, num in enumerate(nums[1:]):\n i += 1\n if num > nums[i-1]:\n dp_array[i % 2] = dp_array[(i-1) % 2] + 1\n max_len = max(max_len, dp_array[i % 2])\n else:\n dp_array[i % 2] = 1\n\n return max_len\n\n","sub_path":"dp/674-longest-continuous-increasing-subsequence.py","file_name":"674-longest-continuous-increasing-subsequence.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"227560953","text":"import hashlib\nfrom server_config import NODES\n\nclass NodeRing(object):\n \n def __init__(self, nodes=None, replicas=3):\n self.replicas = replicas\n self.allring = dict()\n self.sorted_keys = []\n if nodes:\n for node in nodes:\n self.add_node(node)\n \n def add_node(self, node):\n for i in range(0, self.replicas):\n key = self.keygenerator('%s:%s' % (node, i))\n self.allring[key] = node\n self.sorted_keys.append(key)\n self.sorted_keys.sort()\n \n def get_node(self, key):\n val = self.find_node_position(key)[0]\n return val\n \n def find_node_position(self, key):\n key = self.keygenerator(key)\n nodes = self.sorted_keys\n for i in range(0, len(nodes)):\n node = nodes[i]\n if key <= node:\n return self.allring[node], i\n return self.allring[nodes[0]], 0\n \n def get_nodes(self, string_key):\n print(\"get node\")\n node, position = self.find_node_position(string_key)\n for key in self.sorted_keys[position:]:\n yield self.allring[key] #return the value but msintsin the state\n while True:\n for key in self.sorted_keys:\n yield self.allring[key]\n \n def keygenerator(self, key):\n h = hashlib.md5()\n h.update(key.encode('utf-8'))\n return int(h.hexdigest(), 16)\n\ndef test():\n ring = NodeRing(nodes=NODES)\n node = ring.get_nodes('9ad5794ec94345c4873c4e591788743a')\n print(node)\n print(ring.get_nodes('ed9440c442632621b608521b3f2650b8'))\n\n#test()","sub_path":"assignment4/ch_node_ring.py","file_name":"ch_node_ring.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"61642064","text":"import tkinter as tk\r\nfrom tkinter import messagebox\r\n\r\nroot= tk.Tk() # create window\r\nroot.title(\"Laxz's\")\r\nroot.minsize(200, 100)\r\n#root.wm_iconbitmap('MyIcon.ico')\r\n\r\ncanvas1 = tk.Canvas(root, width = 180, height = 100)\r\ncanvas1.pack()\r\n\r\ndef ExitApplication():\r\n MsgBox = tk.messagebox.askquestion ('--Shutdown--','Are you sure you want to shutdown ?',icon = 'question')\r\n if MsgBox == 'yes':\r\n import os\r\n os.system('shutdown -s -f -t 60')\r\n root.destroy()\r\n else:\r\n tk.messagebox.showinfo('Return','Cancelled',icon='info')\r\n root.destroy()\r\n \r\nbutton1 = tk.Button (root, text='Shutdown',command=ExitApplication , highlightbackground='#0000aa')\r\ncanvas1.create_window(90, 50, window=button1)\r\n\r\nroot.mainloop()\r\n","sub_path":"shutdown-gui.py","file_name":"shutdown-gui.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"177558015","text":"#!/usr/bin/env python\n\nimport os, sys, _mysql\n\n\nclass LogLoader:\n logFileName = '/usr/local/www/var/log/archive.tilos.hu-access.log'\n archivePath = '/usr/local/www/vhosts/archive.tilos.hu/htdocs'\n fileSizeDict = dict()\n requestDict = dict()\n resultList = list()\n\n def escapeChars(self, text):\n return text.replace('\\'', '\\\\\\'')\n\n def processFileName(self, requestName):\n archiveNameList = requestName.split('-')\n if len(archiveNameList) == 3:\n return '%s%s'%(archiveNameList[1], archiveNameList[2][:4])\n return False\n\n def processLine(self, line):\n lineList = line.split(' ')\n # Response code\n if int(lineList[8]) in [304, 206, 200]:\n # Does the file exist?\n fileName = self.processFileName(lineList[6])\n if not self.fileSizeDict.has_key(fileName):\n try:\n fileSize = os.path.getsize(os.path.join(self.archivePath, lineList[6][1:]))\n self.fileSizeDict[fileName] = fileSize\n except OSError:\n pass\n if self.fileSizeDict.has_key(fileName):\n # File exists\n self.resultList.append([fileName, lineList[8], lineList[-1]])\n\n def processStats(self):\n dataForDatabaseDict = dict()\n for fileName, responseCode, servedBytes in self.resultList:\n responseCodeDict = dataForDatabaseDict.get(fileName, dict())\n responseCodeStatDict = responseCodeDict.get(responseCode, dict())\n newServedBytes = responseCodeStatDict.get('servedBytes', 0) + int(servedBytes)\n newHitCount = responseCodeStatDict.get('hitCount', 0) + 1\n responseCodeStatDict.update({'servedBytes' : newServedBytes, 'hitCount' : newHitCount})\n responseCodeDict.update({responseCode : responseCodeStatDict})\n dataForDatabaseDict.update({fileName : responseCodeDict})\n self.requestDict = dataForDatabaseDict\n\n def doDatabase(self):\n dbConn = _mysql.connect(host = '127.0.0.3', user = 'archiveStat', passwd = 'thei8Ahh', db = 'archiveStat')\n\n # Do filesizes first\n for fileName in self.fileSizeDict:\n fileSize = str(self.fileSizeDict[fileName])\n dbConn.query(\"REPLACE INTO fileSizes SET fileName = '%s', fileSize = '%s'\"%(self.escapeChars(fileName), self.escapeChars(fileSize)))\n\n # Do requests\n for fileName in self.requestDict:\n for responseCode in self.requestDict[fileName]:\n servedBytes = self.requestDict[fileName][responseCode]['servedBytes']\n hitCount = self.requestDict[fileName][responseCode]['hitCount']\n # Select if this record exists\n dbConn.query(\"SELECT fileName FROM requestData WHERE fileName = '%s' AND responseCode = '%s'\"%(self.escapeChars(fileName), self.escapeChars(responseCode)))\n result = dbConn.store_result()\n if result.num_rows() == 0:\n query = (\"INSERT INTO requestData SET fileName = '%s', responseCode = '%s', hitCount = '%s', servedBytes = '%s'\"%(\n self.escapeChars(fileName),\n self.escapeChars(responseCode),\n hitCount,\n servedBytes\n ))\n # print query\n dbConn.query(query)\n else:\n query = (\"UPDATE requestData SET hitCount = hitCount + %s, servedBytes = servedBytes + %s WHERE fileName = '%s' AND responseCode = '%s'\"%(\n hitCount,\n servedBytes,\n self.escapeChars(fileName),\n self.escapeChars(responseCode)\n ))\n # print query\n dbConn.query(query)\n dbConn.close()\n\n def run(self):\n os.chdir(os.path.dirname(sys.argv[0]))\n with open('archiveStat.dat') as posFileDescriptor:\n filePos = int(posFileDescriptor.read())\n fileDescriptor = open(self.logFileName)\n if os.path.getsize(self.logFileName) >= filePos:\n # Only do incremental analyzing if file is bigger then the latest filePos, else analyzing will start from the beginning.\n # This is useful for switched logs.\n fileDescriptor.seek(filePos)\n for line in fileDescriptor:\n if line.find('\"GET /online/') > -1 and line.find('filename') == -1:\n if line.find('0.mp3 HTTP/1.\" ') > -1:\n # Line matches\n self.processLine(line.strip())\n filePos = fileDescriptor.tell()\n with open('archiveStat.dat', 'w') as posFileDescriptor:\n posFileDescriptor.write(str(filePos))\n fileDescriptor.close()\n self.processStats()\n self.doDatabase()\n\nlogLoader = LogLoader()\n\nlogLoader.run()\n","sub_path":"archiveStat.py","file_name":"archiveStat.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"36296464","text":"import math\nimport time\nimport traceback\nimport numpy\nimport socket\nimport cv2\nimport os\n\nTCP_IP = \"0.0.0.0\"\nTCP_PORT = 5800\n\nconn = None\n\n# Method to grab the size of the image array and verify that it is being decoded correctly\ndef recvall(sock, count):\n buf = b''\n while count:\n newbuf = sock.recv(count)\n if not newbuf: return None\n buf += newbuf\n count -= len(newbuf)\n return buf\n\ndef attemptConnection():\n\n global conn\n\n # Create a new socket with standard SOCK STREAM settings\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # Set socket to be able to reconnect immediately and ignore timeouts\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # Bind socket to IP and port supplied from constructor\n s.bind((TCP_IP, TCP_PORT))\n\n # Listen for exactly 1 host\n s.listen(1)\n\n # Accept first connection and set connection to be class-wide\n print(\"Listening for video streaming on port\", TCP_PORT)\n conn, addr = s.accept()\n print(\"Accepted connection\")\n\ndef loop():\n print(\"Receiving stream ...\")\n\n global conn\n winName = \"Streaming video at %s port\" % str(TCP_PORT)\n winSize = (550, 400)\n\n while True:\n try:\n # Grab length data sent by client to correctly format image\n length = recvall(conn, 16)\n\n # Grab image data based on the length data previously recieved\n if length is not None:\n stringData = recvall(conn, int(length))\n # print(stringData)\n else:\n print(\"No streaming data!!\")\n print(\"--- Strat over ---\")\n cv2.destroyAllWindows() # Not work!\n break\n\n # Decode JPG base64 string into a NumPy matrix of RGB data\n data = numpy.frombuffer(stringData, dtype='uint8')\n\n # Convert NumPy color matrix into OpenCV Matrix\n decimg = cv2.imdecode(data, 1)\n\n # update the image on window\n decimg = cv2.resize(decimg, winSize)\n cv2.imshow(winName, decimg)\n\n # Use the OpenCV famous break statement to allow imshow to function properly.\n k = cv2.waitKey(5) & 0xFF\n if k == '+':\n break\n\n # If something breaks, say what happened\n except Exception as e:\n print(\"Broke in show loop\")\n print(traceback.format_exc())\n break\n # Close and destroy OpenCV stuff on crash.\n\nwhile True:\n try:\n # Attempt to connect to socket\n attemptConnection()\n # Strat the playback loop\n loop()\n except ConnectionRefusedError:\n pass\n # Start the connection again if lost data\n\n","sub_path":"home/pi/jpeg-stream/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"358316594","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2017-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n\"\"\"Provide stub objects that can act as stand-in \"dummy\" datasets for simple use\ncases, like getting all classes in a dataset. This exists so that demos can be\nrun without requiring users to download/install datasets first.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom detectron.utils.collections import AttrDict\n\n\ndef get_coco_dataset():\n \"\"\"A dummy COCO dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = [\n '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',\n 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',\n 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack',\n 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',\n 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',\n 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass',\n 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich',\n 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake',\n 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv',\n 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',\n 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',\n 'scissors', 'teddy bear', 'hair drier', 'toothbrush'\n ]\n ds.classes = {i: name for i, name in enumerate(classes)}\n return ds\n\n\ndef get_coco_chinese_dataset():\n \"\"\"A dummy COCO dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = [\n '__background__', u'人',u'自行车',u'车',u'摩托车',u'飞机',u'大巴',u'火车',u'卡车',\n u'船',u'交通灯',u'消防栓',u'停止标识',u'停车计时器',u'长凳',u'鸟',u'猫',u'狗',u'马',\n u'羊',u'牛',u'大象',u'熊',u'斑马',u'长颈鹿',u'背包',u'伞',u'手提包',u'领带',u'手提箱',\n u'飞盘',u'雪橇',u'滑雪板',u'体育用球',u'风筝',u'棒球棒',u'棒球手套',u'滑板',u'冲浪板',\n u'网球拍',u'瓶子',u'红酒杯',u'杯子',u'叉子',u'小刀',u'勺子',u'碗',u'香蕉',u'苹果',\n u'三明治',u'橘子',u'西兰花',u'萝卜',u'热狗',u'披萨',u'甜甜圈',u'蛋糕',u'椅子',u'沙发',\n u'盆栽',u'床',u'餐桌',u'厕所',u'显示器',u'笔记本',u'鼠标',u'遥控',u'键盘',u'手机',\n u'微波炉',u'烤箱',u'吐司机',u'水槽',u'冰箱',u'书',u'闹钟',u'花瓶',u'剪刀',u'泰迪熊',\n u'吹风机',u'牙刷'\n ]\n ds.classes = {i: name for i, name in enumerate(classes)}\n return ds\n\n\ndef get_cityscapes_dataset():\n \"\"\"A dummy COCO dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = [\n 'person',\n 'rider',\n 'car',\n 'truck',\n 'bus',\n 'train',\n 'motorcycle',\n 'bicycle',\n ]\n ds.classes = {i: name for i, name in enumerate(classes)}\n return ds\n\n\ndef get_trash_dataset():\n \"\"\"A dummy Trash dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = [\n '__background__', u'sld', u'pz', u'zzsgx', u'slsgx', u'pmsgx', u'stt',\n u'ylg', u'pmkch', u'bzl', u'ylx', u'ml', u'cj', u'mqg', u'bzd', u'kqst'\n ]\n ds.classes = {i: name for i, name in enumerate(classes)}\n return ds\n\n\ndef get_general_dataset():\n \"\"\"A dummy Trash dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = ['__background__', u'sld', u'slc', u'ys', u'slsgx', u'pmsgx', u'ljd', u'cjx', u'ggp',\n u'zz', u'yz', u'stt', u'tys', u'ls', u'mqg', u'bzd', u'pz', u'hua',\n u'lp', u'bzl', u'c', u'cj', u'ml', u'kqst', u'pmkch', u'thl', u'zzsgx',\n u'pjx', u'zb', u'bd', u'yc', u'ylx', u'gz', u'ylg', u'qq', u'cqm']\n ds.classes = {i: name for i, name in enumerate(classes)}\n return ds\n\ndef get_new_general_dataset():\n \"\"\"A dummy Trash dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = ['__background__', u'塑料袋', u'饮料瓶', u'矿泉水桶', u'箱子', u'矿泉水桶', u'桌子', u'yc', u'椅子', u'煤炉', u'慛据',\n u'雨伞', u'脸盆', u'编织篮', u'编织袋', u'惨论车', u'忧伤']\n # classes = ['__background__', u'塑料袋', u'pz', u'煤炉', u'箱子', u'煤气罐', u'桌子', u'yc', u'游商', u'ml', u'cj',\n # u'tys', u'lp', u'煤炉', u'编织袋', u'游商', u'游商']\n ds.classes = {i: name for i, name in enumerate(classes)}\n return ds\n\n\n","sub_path":"detectron/datasets/dummy_datasets.py","file_name":"dummy_datasets.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"188082508","text":"#!/usr/bin/python\nimport sys, os\nfrom optparse import *\nsys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\nfrom broomstick_simulation_plot import plotAllBroomstickSimulations\n\nif __name__ == \"__main__\":\n\n # Parse the command line arguments\n parser = OptionParser()\n parser.add_option(\"--wh_data_file\", type=\"string\", dest=\"wh_data_file\",\n help=\"the wh data file to load\")\n parser.add_option(\"--ia_data_file\", type=\"string\", dest=\"ia_data_file\",\n help=\"the ia data file to load\")\n parser.add_option(\"--hybrid_data_file\", type=\"string\", dest=\"hybrid_data_file\",\n help=\"the hybrid data file to load\")\n parser.add_option(\"--consistent_data_file\", type=\"string\", dest=\"consistent_data_file\",\n help=\"the consistent data file to load\")\n options,args = parser.parse_args()\n\n ylims = [0.0, 60.0]\n xlims = [0.065, 0.1]\n legend_pos = (0.86,0.76)\n # xlims = [0.095, 0.1]\n # legend_pos = (0.75,0.76)\n\n # Plot the spectrum\n plotAllBroomstickSimulations( options.wh_data_file,\n \"FRENSIE-WH\",\n options.hybrid_data_file,\n \"FRENSIE-Hybrid Dopp\",\n options.ia_data_file,\n \"FRENSIE-IA\",\n options.consistent_data_file,\n \"FRENSIE-Consistent Dopp\",\n ylims,\n xlims,\n legend_pos )\n","sub_path":"photon/broomstick/H2O/all_comp/0.1/broomstick-comp-plot.py","file_name":"broomstick-comp-plot.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"40621103","text":"from dataset.grunge_library import *\nfrom music.db_fragments.riff import *\nfrom music.db_fragments.solo import *\n\n\ndef analyse_tonality():\n griff_table = get_guitar_riff_table()\n briff_table = get_bass_riff_table()\n gsolo_table = get_guitar_solo_table()\n\n for griff in griff_table.find():\n try:\n guitar_riff = GuitarRiff(griff['Path'])\n\n measures_num = guitar_riff.measures_num\n measures_tonality = guitar_riff.tonality_by_measures()\n\n griff_table.update_one(\n {'_id': griff['_id']},\n {'$set': {\n 'MeasuresNum': measures_num,\n 'MeasuresTonality': measures_tonality\n }}\n )\n\n except:\n print(griff['Path'])\n\n for briff in briff_table.find():\n try:\n bass_riff = BassRiff(briff['Path'])\n\n measures_num = bass_riff.measures_num\n measures_tonality = bass_riff.tonality_by_measures()\n\n briff_table.update_one(\n {'_id': briff['_id']},\n {'$set': {\n 'MeasuresNum': measures_num,\n 'MeasuresTonality': measures_tonality\n }}\n )\n\n except:\n print(briff['Path'])\n\n for gsolo in gsolo_table.find():\n try:\n guitar_solo = GuitarSolo(gsolo['Path'])\n\n measures_num = guitar_solo.measures_num\n measures_tonality = guitar_solo.tonality_by_measures()\n\n gsolo_table.update_one(\n {'_id': gsolo['_id']},\n {'$set': {\n 'MeasuresNum': measures_num,\n 'MeasuresTonality': measures_tonality\n }}\n )\n\n except:\n print(gsolo['Path'])\n\n\ndef test_tonal():\n path = 'E:/database/test.mid'\n guitar_riff = GuitarRiff(path)\n print(guitar_riff.get_note_lengths_divided_by_measure())\n\n\nif __name__ == '__main__':\n analyse_tonality()","sub_path":"music/analysis/tonality.py","file_name":"tonality.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"421686170","text":"import machine\nimport utime\nimport _thread\nimport random\n\ninternal_led = machine.Pin(25, machine.Pin.OUT)\ngreen_led = machine.Pin(13, machine.Pin.OUT)\nblue_led = machine.Pin(15, machine.Pin.OUT)\nBlue_Button = machine.Pin(22, machine.Pin.IN, machine.Pin.PULL_UP)\n\n\nbaton = _thread.allocate_lock()\n\ndef Button_Handler(pin):\n baton.acquire()\n print(\"Green\")\n green_led.toggle()\n utime.sleep(2.2)\n baton.release()\n\n\ndef Button_Watcher():\n while True:\n blue_led.toggle()\n print(\"Blue\")\n utime.sleep(0.5)\n\nBlue_Button.irq(trigger=machine.Pin.IRQ_RISING, handler=Button_Handler)\n\n_thread.start_new_thread(Button_Watcher, ())\n\nwhile True:\n internal_led.toggle()\n print(\"Internal\")\n utime.sleep(0.5)","sub_path":"threadinterupttest.py","file_name":"threadinterupttest.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"447650691","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom __future__ import absolute_import, division, print_function, unicode_literals\r\n\r\n\"\"\" Depth of field blurring also demos MergeShape radial copying\r\nTo blur something against its background both object are drawn to an offscreen\r\ntexture. They are then drawn to the screen with a depth blur effect.\r\n\r\nThe Font class is also demonstrated. This generates a texture from\r\na true-type font file on the RPi system or added from an external resource\r\n(standard fonts are available on raspbian in /usr/share/fonts/truetype)\r\n\r\nThis demo also shows the use of an additional orthographic camera for\r\nrendering the string in 2D. If you change the Display size you will see\r\nthat the text stays the same size, also the text will be rendered on top\r\nof the 3d view. x and y locations for the text represent pixel offsets\r\nfrom the centre of the screen\r\n\"\"\"\r\nimport math, random, time\r\n\r\nimport demo\r\nimport sys\r\nif sys.version_info[0] == 3:\r\n unichr = chr\r\n\r\nimport pi3d\r\n\r\nLOGGER = pi3d.Log(__name__, level='INFO', format='%(message)s')\r\n# or you can log to file, or use default format\r\n#LOGGER = pi3d.Log(__name__, level='DEBUG', file='dump.txt')\r\n#LOGGER = pi3d.Log(__name__, level='ERROR')\r\n''' to display all the pi3d module logging activity you must leave the\r\nname argument blank (it will default to None) this will set the logger\r\nto the root logger i.e.\r\n'''\r\n#LOGGER = pi3d.Log(level='DEBUG')\r\n# these can be changed subsequently using LOGGER.set_logs()\r\nMESSAGE = \"\"\"\\\r\nblurring\r\nwith\r\ndistance!\r\n---------\r\njustified\r\nmultiline\r\nunicode æ ö ¼\r\nStrings \"\"\" + unichr(255) + ' ' + unichr(256) + ' ' + unichr(257)\r\n\r\n# character 255 should appear, character 256 should not.\r\n\r\n# Setup display and initialise pi3d\r\nDISPLAY = pi3d.Display.create(x=10, y=10, w=900, h=600, frames_per_second=25)\r\nDISPLAY.set_background(0.4, 0.6, 0.8, 1.0) # r,g,b,alpha\r\n\r\npersp_cam = pi3d.Camera.instance() # default instance camera perspecive view\r\northo_cam = pi3d.Camera(is_3d=False) # 2d orthographic view camera\r\n\r\n#setup textures, light position and initial model position\r\npi3d.Light((0, 5, 0))\r\n#create shaders\r\nshader = pi3d.Shader(\"uv_reflect\")\r\nflatsh = pi3d.Shader(\"uv_flat\")\r\ndefocus = pi3d.Defocus()\r\n\r\n#Create textures\r\nshapeimg = pi3d.Texture(\"textures/straw1.jpg\")\r\nshapebump = pi3d.Texture(\"textures/floor_nm.jpg\")\r\nshapeshine = pi3d.Texture(\"textures/pong3.png\")\r\n\r\n#Create shape\r\nmyshape = pi3d.MergeShape(camera=persp_cam) #specify perspective view\r\nasphere = pi3d.Sphere(sides=16, slices=16)\r\nmyshape.radialCopy(asphere, step=72)\r\nmyshape.position(0.0, 0.0, 5.0)\r\nmyshape.set_draw_details(shader, [shapeimg, shapebump, shapeshine], 8.0, 0.1)\r\n\r\nmysprite = pi3d.Sprite(w=10.0, h=10.0, camera=persp_cam)\r\nmysprite.position(0.0, 0.0, 15.0)\r\nmysprite.set_draw_details(flatsh, [shapebump])\r\n\r\ntick=0\r\nnext_time = time.time()+2.0\r\n\r\n#load ttf font and set the font colour to 'raspberry'\r\narialFont = pi3d.Font(\"fonts/NotoSerif-Regular.ttf\", (221,0,170,255),\r\n add_codepoints=[256])\r\narialFont.blend = True #much better anitaliased look but must String.draw() after everything else \r\nmystring = pi3d.String(font=arialFont, string=MESSAGE,\r\n camera=ortho_cam, z=1.0, is_3d=False, justify=\"r\") # orthographic view\r\nmystring.set_shader(flatsh)\r\n\r\n# Fetch key presses.\r\nmykeys = pi3d.Keyboard()\r\n\r\n# Display scene and rotate shape\r\nwhile DISPLAY.loop_running():\r\n\r\n defocus.start_blur()\r\n # 1. drawing objects now renders to an offscreen texture ####################\r\n mysprite.draw()\r\n myshape.draw()\r\n defocus.end_blur()\r\n # 2. drawing now back to screen. The texture can now be used by defocus.blur()\r\n\r\n # 3. redraw these two objects applying a distance blur effect ###############\r\n defocus.blur(myshape, 4, 9, 5) # 4 is focal distance, >= 9 distance will get\r\n defocus.blur(mysprite, 4, 9, 5) # 5 x blurring, nearer than focus also blurs\r\n\r\n myshape.rotateIncY(1.247)\r\n myshape.rotateIncX(0.1613)\r\n\r\n mystring.draw()\r\n mystring.rotateIncZ(0.05)\r\n\r\n if time.time() > next_time:\r\n LOGGER.info(\"FPS: %4.1f\", (tick / 2.0))\r\n tick=0\r\n next_time = time.time() + 2.0\r\n tick+=1\r\n\r\n k = mykeys.read()\r\n if k==112:\r\n pi3d.screenshot(\"blur1.jpg\")\r\n elif k==27:\r\n mykeys.close()\r\n defocus.delete_buffers()\r\n DISPLAY.destroy()\r\n break\r\n\r\n","sub_path":"pi3ddemos/Blur.py","file_name":"Blur.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"640400186","text":"import pandas as pd\n\nbase = pd.read_csv('house_prices.csv')\n\nx= base.iloc[:, 5:6].values\ny= base.iloc[:, 2].values\n\n#Divide a base de dados em treinamento e teste\nfrom sklearn.model_selection import train_test_split\nx_treinamento, x_teste, y_treinamento, y_teste = train_test_split(x,y,\n test_size= 0.3,\n random_state=0 )\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\n#Faz o treinamento com regressao linear\nregressor.fit(x_treinamento, y_treinamento)\n#Mostra o score de treinamento\nscore= regressor.score(x_treinamento, y_treinamento)\n\nimport matplotlib.pyplot as plt\n#Mostra o grafico do treinamento\nplt.scatter(x_treinamento, y_treinamento)\n#Mostra a linha no grafico\nplt.plot(x_treinamento, regressor.predict(x_treinamento), color='red')\n\n#Mostra as previsoes de acordo com o treinamento\nprevisoes= regressor.predict(x_teste)\n\n#Mostra a diferença dos resultados obtidos para o real\nresultado = abs(y_teste-previsoes)\n#Mostra a media do erro de previsao\nresultado.mean()\n\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nmae = mean_absolute_error(y_teste, previsoes)\nmse = mean_squared_error(y_teste, previsoes)\n\n\nimport matplotlib.pyplot as plt\n#Mostra o grafico do teste\nplt.scatter(x_teste, y_teste)\n#Mostra a linha no grafico\nplt.plot(x_teste, regressor.predict(x_teste), color='red')\n\n#Mostra o score do teste\nregressor.score(x_teste, y_teste)\n","sub_path":"Regression/Linear Regression/regressao_linear_simples_casas.py","file_name":"regressao_linear_simples_casas.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"163397186","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport docker\nimport argparse\n\n\nclass DataSpoutContainers:\n def __init__(self):\n self.client = docker.from_env()\n self.dockerfile_path = './'\n self.image_tag = 'dataspout'\n self.image = None\n\n def build_image(self):\n print('Start building image....')\n self.image = self.client.images.build(path=self.dockerfile_path, tag=self.image_tag)\n\n def run_container(self, name, hostname, command):\n container = self.client.containers.run(image='dataspout',\n detach=True,\n name=name,\n hostname=hostname,\n tty=True,\n stdin_open=True,\n command=command)\n return container\n\n def main(self):\n parser = argparse.ArgumentParser()\n parser.add_argument('-z', '--zk_address', type=str, help='The address of ZooKeeper server.')\n args = parser.parse_args()\n zk_address = args.zk_address\n for i in range(1):\n container_name = 'DataSpout' + str(i+1)\n print('Start running container DataSpout %s' % str(i+1))\n command = 'python /home/SpoutingData.py -s ' + str(i+1) + ' -z ' + zk_address\n self.run_container(container_name, container_name, command)\n\n\nif __name__ == '__main__':\n spout = DataSpoutContainers()\n spout.build_image()\n spout.main()\n\n\n\n\n\n\n\n\n","sub_path":"FinalProject/SourceCode/DataSourcePart/DataSpoutContainers.py","file_name":"DataSpoutContainers.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"162943738","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server import util\n\n\nclass OrderMessage(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, username: str=None, order: str=None): # noqa: E501\n \"\"\"OrderMessage - a model defined in Swagger\n\n :param username: The username of this OrderMessage. # noqa: E501\n :type username: str\n :param order: The order of this OrderMessage. # noqa: E501\n :type order: str\n \"\"\"\n self.swagger_types = {\n 'username': str,\n 'order': str\n }\n\n self.attribute_map = {\n 'username': 'username',\n 'order': 'order'\n }\n\n self._username = username\n self._order = order\n\n @classmethod\n def from_dict(cls, dikt) -> 'OrderMessage':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The OrderMessage of this OrderMessage. # noqa: E501\n :rtype: OrderMessage\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def username(self) -> str:\n \"\"\"Gets the username of this OrderMessage.\n\n\n :return: The username of this OrderMessage.\n :rtype: str\n \"\"\"\n return self._username\n\n @username.setter\n def username(self, username: str):\n \"\"\"Sets the username of this OrderMessage.\n\n\n :param username: The username of this OrderMessage.\n :type username: str\n \"\"\"\n if username is None:\n raise ValueError(\"Invalid value for `username`, must not be `None`\") # noqa: E501\n\n self._username = username\n\n @property\n def order(self) -> str:\n \"\"\"Gets the order of this OrderMessage.\n\n\n :return: The order of this OrderMessage.\n :rtype: str\n \"\"\"\n return self._order\n\n @order.setter\n def order(self, order: str):\n \"\"\"Sets the order of this OrderMessage.\n\n\n :param order: The order of this OrderMessage.\n :type order: str\n \"\"\"\n if order is None:\n raise ValueError(\"Invalid value for `order`, must not be `None`\") # noqa: E501\n\n self._order = order\n","sub_path":"api-server/swagger_server/models/order_message.py","file_name":"order_message.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"41012724","text":"from scrapy_redis.spiders import RedisCrawlSpider as RCS, RedisSpider as RSD\nfrom scrapy.spiders import CrawlSpider as CS, Spider as SD\n\n\nimport scrapy\nimport json\nfrom functools import partial\n\nfrom .spider_utils import request_to_dict_cus\nfrom .utils import UtilsPKG\nfrom .shortcut import ShortCut\nfrom .preset_items import ErrorItem\nfrom .preset_pipelines import MongodbPipeline\n\nfrom scrapy.core.downloader.middleware import DownloaderMiddlewareManager,\\\n defer, Request, Response, mustbe_deferred\n\nimport six\nfrom .log import init_logger\n\n\ndef download(self, download_func, request, spider):\n\n def save_error(reason):\n request_dict = request_to_dict_cus(request, spider)\n\n item_ = ErrorItem(reason=reason,\n request=request_dict,\n traceback=spider.ShortCut.format_exc())\n\n MongodbPipeline.add_ts(item_)\n spider.ShortCut.thread_mongodb_insert(spider.crawler.settings.get(\n 'MONGODB_DATABASE', ''), 'RequestError', dict(item_))\n\n @defer.inlineCallbacks\n def process_request(request):\n for method in self.methods['process_request']:\n\n response = yield method(request=request, spider=spider)\n\n assert response is None or isinstance(response, (Response, Request)), \\\n 'Middleware %s.process_request must return None, Response or Request, got %s' % \\\n (six.get_method_self(method).__class__.__name__, response.__class__.__name__)\n if response:\n defer.returnValue(response)\n defer.returnValue((yield download_func(request=request, spider=spider)))\n\n @defer.inlineCallbacks\n def process_response(response):\n assert response is not None, 'Received None in process_response'\n if isinstance(response, Request):\n defer.returnValue(response)\n\n for method in self.methods['process_response']:\n try:\n response = yield method(request=request, response=response,\n spider=spider)\n except Exception as e:\n save_error('process_response_error')\n raise\n\n assert isinstance(response, (Response, Request)), \\\n 'Middleware %s.process_response must return Response or Request, got %s' % \\\n (six.get_method_self(method).__class__.__name__, type(response))\n if isinstance(response, Request):\n defer.returnValue(response)\n defer.returnValue(response)\n\n @defer.inlineCallbacks\n def process_exception(_failure):\n exception = _failure.value\n for method in self.methods['process_exception']:\n\n try:\n response = yield method(request=request, exception=exception,\n spider=spider)\n except Exception as e:\n _ = e\n \"\"\"错误搜集函数\"\"\"\n save_error('process_exception_error')\n\n raise\n\n assert response is None or isinstance(response, (Response, Request)), \\\n 'Middleware %s.process_exception must return None, Response or Request, got %s' % \\\n (six.get_method_self(method).__class__.__name__, type(response))\n if response:\n defer.returnValue(response)\n\n defer.returnValue(_failure)\n\n deferred = mustbe_deferred(process_request, request)\n deferred.addErrback(process_exception)\n deferred.addCallback(process_response)\n return deferred\n\nDownloaderMiddlewareManager.download = download\n\n\n# @zs_logging.log_to_fluentd()\nclass BaseSpider(object):\n\n UtilsPKG = UtilsPKG\n ShortCut = ShortCut\n\n def __init__(self, *args, **kwargs):\n # self.logger = init_logger(__name__)\n\n self._mode = kwargs.get('mode', 'normal')\n # 对不同模式下的爬虫进行识别调整设置\n\n self._kpl_time = None\n if self._mode == 'KPL':\n self._kpl_time = int(kwargs.get('kpl_time', '600'))\n\n def to_json(self_, text=None):\n if not text:\n return json.loads(self_.text)\n else:\n return json.loads(text)\n\n def retry_(response, retry_times=10, priority=10):\n meta = response.meta\n times_ = meta.get('retry_times_cus', 0)\n\n if retry_times == -1:\n times_ += 1\n resquest_ = response.request\n resquest_.dont_filter = True\n resquest_.meta['retry_times_cus'] = times_\n resquest_.priority = priority\n\n self.logger.info('retry times: {}, {}'.format(times_, response.url))\n return resquest_\n\n if times_ <= retry_times:\n\n times_ += 1\n resquest_ = response.request\n resquest_.dont_filter = True\n resquest_.meta['retry_times_cus'] = times_\n resquest_.priority = priority\n\n self.logger.info('retry times: {}, {}'.format(times_, response.url))\n return resquest_\n else:\n self.logger.info('retry times: {} too many {}'.format(times_, response.url))\n\n req = request_to_dict_cus(response.request, self)\n\n item = ErrorItem(\n reason='cus_retry too many',\n request=req,\n )\n\n return item\n\n scrapy.http.Response.json = to_json\n scrapy.http.Response.retry = retry_\n\n if hasattr(self, 'parse'):\n scrapy.Request = partial(scrapy.Request, errback=self._error_back, callback=self.parse)\n else:\n scrapy.Request = partial(scrapy.Request, errback=self._error_back)\n\n assert not self.__dict__.get('custom_settings'), \"请设置custom_settings\"\n # 自动集成储存源数据系统\n\n # 开启线程池\n if self.custom_settings.get('EnThreadPool', False):\n self.executor = self.ShortCut.futures.ThreadPoolExecutor(max_workers=self.custom_settings['max_workers'])\n self.executor.shutdown()\n\n def _error_back(self, failure):\n self.logger.error('_error_back, error_url:{}, reason:{}'.format(failure.request.url, failure.value))\n self.logger.error('{}. _error_back'.format(failure))\n self.logger.error('end')\n\n\n req = request_to_dict_cus(failure.request, self)\n\n item = ErrorItem(\n reason=str(failure.value),\n request=req,\n failure=self.failure_to_dict(failure),\n )\n yield item\n\n @staticmethod\n def failure_to_dict(failure):\n d = failure.__dict__.copy()\n del_list_k = ['value', 'type', 'request', 'tb']\n for k in del_list_k:\n try:\n del d[k]\n except:\n pass\n return d\n\n\nclass CrawlSpider(BaseSpider, CS):\n\n def __init__(self, *args, **kwargs):\n BaseSpider.__init__(self, *args, **kwargs)\n CS.__init__(self, *args, **kwargs)\n\n\nclass CrawlSpiderRedis(BaseSpider, RCS):\n\n def __init__(self, *args, **kwargs):\n BaseSpider.__init__(self, *args, **kwargs)\n RCS.__init__(self, *args, **kwargs)\n\n\nclass Spider(BaseSpider, SD):\n\n def __init__(self, *args, **kwargs):\n BaseSpider.__init__(self, *args, **kwargs)\n SD.__init__(self, *args, **kwargs)\n\n\nclass SpiderRedis(BaseSpider, RSD):\n\n def __init__(self, *args, **kwargs):\n BaseSpider.__init__(self, *args, **kwargs)\n RSD.__init__(self, *args, **kwargs)\n","sub_path":"scrapy_poi/utils/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":7585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"407470627","text":"\"\"\"Simple addition of numbers in a list when there are two consecutive nubmers\"\"\"\n\ndef add_numbers_from_file(file, number):\n \"\"\"Iterate through file and add the numbers together when there are two consecutive numbers\"\"\"\n\n last_num = number\n total = 0\n with file:\n while True:\n curr_num = file.read(1)\n\n if curr_num:\n if curr_num == last_num:\n total += int(curr_num)\n last_num = curr_num\n else:\n return total, last_num\n\ndef main():\n \"\"\"Run add_numbers_from_file\"\"\"\n file = open(\"../puzzle_input.txt\")\n\n first_num = file.read(1)\n\n total, last_num = add_numbers_from_file(file, first_num)\n\n if first_num == last_num:\n total += int(first_num)\n\n print(total)\n\nif __name__ == '__main__':\n main()\n ","sub_path":"day1/python/solve_puzzle_1.py","file_name":"solve_puzzle_1.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"343827893","text":"from Crypto.Cipher import AES\nimport base64\n\ndef xor(b1, b2):\n b = bytearray(len(b1))\n for i in range(len(b1)):\n b[i] = b1[i] ^ b2[i]\n return b\n\ndef pkcs7_pad(msg, blk):\n pad_len = blk - (len(msg)%blk)\n return msg + bytes([pad_len])*pad_len\n\ndef pkcs7_unpad(msg):\n\tpadding = msg[-1]\n\tlength = len(msg)\n\n\tfor i in range(length-1, length-padding-1, -1):\n\t\tif msg[i] != msg[-1]:\n\t\t\treturn msg\n\tunpadded_msg = bytearray()\n\tunpadded_msg[:] = msg[:-padding]\n\treturn unpadded_msg\n\ndef ebc_enc(buffer, key):\n obj = AES.new(key, AES.MODE_ECB)\n return bytearray(obj.encrypt(bytes(buffer)))\n\ndef ecb_dec(buffer, key):\n obj = AES.new(key, AES.MODE_ECB)\n return bytearray(obj.decrypt(bytes(buffer)))\n\ndef cbc_enc(msg, iv, key):\n\tAES_blk_size = AES.block_size\n\tplaintext = pkcs7_pad(msg, AES_blk_size)\n\tciphertext = bytearray(len(plaintext))\n\tprevious_blk = iv\n\tplaintext_len = len(plaintext)\n\tfor i in range(0, plaintext_len, AES_blk_size):\n\t\tciphertext[i:i+AES_blk_size] = ebc_enc(xor(plaintext[i:i+AES_blk_size], previous_blk), key)\n\t\tprevious_blk = ciphertext[i:i+AES_blk_size]\n\treturn ciphertext\n\ndef cbc_dec(ciphertext, iv, key):\n AES_blk_size = AES.block_size\n ciphertext_len = len(ciphertext)\n plaintext = bytearray(ciphertext_len)\n previous_blk = iv\n for i in range(0, ciphertext_len, AES_blk_size):\n plaintext[i:i+AES_blk_size] = xor(ecb_dec(ciphertext[i:i+AES_blk_size], key), previous_blk)\n previous_blk = ciphertext[i:i+AES_blk_size]\n return pkcs7_unpad(plaintext)\n\ndef main():\n #plaintext = bytearray(\"Hello my name is Michael\", 'utf-8')\n iv = bytearray(b'\\x00' * AES.block_size)\n key = \"YELLOW SUBMARINE\"\n #enc = cbc_enc(plaintext, iv, key)\n #print(\"After Encryption->\", enc)\n ciphertext = bytearray(\"\".join(list(open(\"file.txt\", \"r\"))), 'utf-8')\n ciphertext = base64.b64decode(ciphertext)\n dec = cbc_dec(ciphertext, iv, key)\n print(\"After Decryption->\", dec)\n \nmain()\n","sub_path":"Set2/Challange10.py","file_name":"Challange10.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"382961782","text":"from discord.ext import commands \r\nimport discord\r\n\r\nimport random, os, json\r\nfrom setup import var\r\nfrom functions import customerror\r\nfrom functions import functions\r\nfrom datetime import datetime, timedelta\r\n\r\nfrom discord import app_commands\r\n\r\nclass Moderation3(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n \r\n @app_commands.command(name=\"role\", description=\"Add or remove roles from users\")\r\n @app_commands.guild_only()\r\n @app_commands.describe(setting=\"Add or remove role\", user=\"The user to add or remove the role to. Can be 'all'\", role=\"The role to add or remove\")\r\n @app_commands.choices(setting=[app_commands.Choice(name=\"Add\", value=\"add\"), app_commands.Choice(name=\"Remove\", value=\"remove\")])\r\n async def role(\r\n self, \r\n ctx : discord.Interaction, \r\n setting : str, \r\n user : str, \r\n role : discord.Role\r\n ):\r\n\r\n if setting == \"add\":\r\n if user not in [\"all\", \"everyone\", \"allmembers\"]:\r\n users = user.replace(\"<\", \"\").replace(\">\", \"\").replace(\"@\", \"\").replace(\"!\", \"\")\r\n for member in ctx.guild.members:\r\n if str(member.id) == users:\r\n userobject = member\r\n\r\n if not ctx.user.guild_permissions.manage_roles or not ctx.user.top_role.position > role.position and not ctx.guild.owner == ctx.user:\r\n return await ctx.response.send_message(\"> You do not have permission to do this!\")\r\n try:\r\n theuser = userobject\r\n except Exception as error:\r\n theuser = None\r\n return await ctx.response.send_message(\"> Could not find such user.\")\r\n if theuser != None:\r\n try:\r\n await userobject.add_roles(role)\r\n return await ctx.response.send_message(f\"> Successfully added role **{role}** to **{userobject.name}**\")\r\n except Exception as error:\r\n return await ctx.response.send_message(f\"> I do not have permission to add role {role}.\")\r\n elif user in [\"all\", \"everyone\", \"allmembers\"]:\r\n counter = 0\r\n errors = 0\r\n successful = 0\r\n firsttime = round(int(len(ctx.guild.members)) / 5)\r\n calculation = round(firsttime * 3.5)\r\n\r\n if not ctx.user.guild_permissions.manage_roles or not ctx.user.top_role.position > role.position and not ctx.guild.owner == ctx.user:\r\n return await ctx.response.send_message(\"> You do not have permission to do this!\")\r\n try:\r\n await ctx.response.send_message(f\"> Started adding role **{role.name}** to all {len(ctx.guild.members)} members! This is estimated to take {calculation} seconds.\")\r\n goahead = 1\r\n except Exception as e:\r\n await ctx.response.send_message(f\"> Could not find role **{role}**!\") \r\n goahead = 0\r\n\r\n if goahead == 1:\r\n for member in ctx.guild.members:\r\n try:\r\n await member.add_roles(role)\r\n successful = successful + 1\r\n except Exception as error:\r\n errors = errors + 1\r\n counter = counter + 1\r\n if counter == int(round(int(len(ctx.guild.members)) / 2)):\r\n await ctx.channel.send(\"> **50 percent done**\")\r\n embed = discord.Embed(title=\"Roles added to **{}** users!\".format(str(counter)), colour=var.embed) \r\n embed.add_field(name=\"Information\", value=f\"Added role **{role}** to **{successful}** users\")\r\n if errors == 0:\r\n errors = \"No errors 🎉\"\r\n else:\r\n errors = f\"Could not add role **{role}** to **{errors}** users `Missing permissions`\"\r\n embed.add_field(name=\"Errors\", value=errors)\r\n await ctx.channel.send(embed=embed)\r\n elif setting == \"remove\":\r\n if user in [\"all\", \"everyone\", \"allmembers\"]:\r\n counter = 0\r\n errors = 0\r\n successful = 0\r\n firsttime = round(int(len(ctx.guild.members)) / 5)\r\n calculation = round(firsttime * 3.5)\r\n\r\n if not ctx.user.guild_permissions.manage_roles or not ctx.user.top_role.position > role.position and not ctx.guild.owner == ctx.user:\r\n return await ctx.response.send_message(\"> You do not have permission to do this!\")\r\n try:\r\n await ctx.response.send_message(f\"> Started removing role **{role.name}** from all {len(ctx.guild.members)} members! This is estimated to take {calculation} seconds.\")\r\n goahead = 1\r\n except Exception as e:\r\n await ctx.response.send_message(f\"> I am missing permission to remove role {role}.\") \r\n goahead = 0\r\n if goahead == 1:\r\n for member in ctx.guild.members:\r\n try:\r\n await member.remove_roles(role)\r\n successful = successful + 1\r\n except Exception as error:\r\n errors = errors + 1\r\n counter = counter + 1\r\n if counter == int(round(int(len(ctx.guild.members)) / 2)):\r\n await ctx.channel.send(\"> **50 percent done**\")\r\n embed = discord.Embed(title=f\"Roles removed from **{counter}** users!\", colour=var.embed) \r\n embed.add_field(name=\"Information\", value=f\"Removed role **{role}** from **{successful}** users\")\r\n if errors == 0:\r\n errors = \"No errors 🎉\"\r\n else:\r\n errors = f\"Could not remove role **{role}** from **{errors}** users `Missing permissions`\"\r\n embed.add_field(name=\"Errors\", value=errors)\r\n await ctx.channel.send(embed=embed)\r\n else:\r\n users = user.replace(\"<\", \"\").replace(\">\", \"\").replace(\"@\", \"\").replace(\"!\", \"\")\r\n for member in ctx.guild.members:\r\n if str(member.id) == users:\r\n userobject = member\r\n\r\n if not ctx.user.guild_permissions.manage_roles or not ctx.user.top_role.position > role.position and not ctx.guild.owner == ctx.user:\r\n return await ctx.response.send_message(\"> You do not have permission to do this!\")\r\n\r\n try:\r\n theuser = userobject\r\n except Exception as error:\r\n theuser = None\r\n await ctx.response.send_message(\"> Could not find such user.\")\r\n if theuser != None:\r\n try:\r\n await userobject.remove_roles(role)\r\n await ctx.response.send_message(f\"> Successfully removed role **{role}** from **{userobject.name}**\")\r\n except Exception as error:\r\n await ctx.response.send_message(f\"> I am missing permission to remove role {role}\")\r\n \r\n @app_commands.command(name=\"nick\", description=\"Change the nickname of a user\")\r\n @app_commands.guild_only()\r\n @app_commands.describe(user=\"The user to change the nickname of. Can also be 'all'\", nickname=\"The nickname to change to. Can be 'reset'\")\r\n async def nick(\r\n self, \r\n ctx : discord.Interaction, \r\n user : str, \r\n nickname : str\r\n ):\r\n\r\n if user != \"all\":\r\n for member in ctx.guild.members:\r\n if str(member.id) in user or member.display_name == user or member.name == user:\r\n if ctx.user.guild_permissions.change_nickname and member == ctx.user:\r\n doit=1\r\n elif ctx.user.guild_permissions.manage_nicknames:\r\n doit=1\r\n else:\r\n doit=0\r\n await ctx.response.send_message(\"> An error has occurred: Missing `manage_nicknames` permission\")\r\n if doit == 1:\r\n try:\r\n if nickname == \"reset\":\r\n await member.edit(nick=member.name)\r\n await ctx.response.send_message(f\"> Successfully reset **{member}**s nickname!\")\r\n else:\r\n await member.edit(nick=nickname)\r\n await ctx.response.send_message(f\"> Successfully set **{member}**s nickname to **{nickname}**\")\r\n except Exception as e:\r\n await ctx.response.send_message(\"> Could not change nickname `Bot Missing permissions`\")\r\n else:\r\n if ctx.user.guild_permissions.manage_nicknames:\r\n counter = 0\r\n errors = 0\r\n successful = 0\r\n firsttime = round(int(len(ctx.guild.members)) / 5)\r\n calculation = round(firsttime * 3.5)\r\n\r\n if nickname != \"reset\":\r\n await ctx.response.send_message(f\"> Started changing {len(ctx.guild.members)} nicknames to {nickname}. This is estimated to take {calculation} seconds.\")\r\n else:\r\n await ctx.response.send_message(f\"> Started resetting {len(ctx.guild.members)} nicknames. This is estimated to take {str(calculation)} seconds.\")\r\n\r\n data = {}\r\n \r\n with open(\"databases/nicks.json\") as f:\r\n prefixes = json.load(f)\r\n\r\n for member in ctx.guild.members:\r\n try:\r\n try:\r\n if str(member.id) in prefixes[str(ctx.guild.id)]:\r\n pass \r\n else:\r\n data[str(member.id)] = member.display_name\r\n except Exception as e:\r\n data[str(member.id)] = member.display_name\r\n if nickname == \"reset\":\r\n try:\r\n prev = prefixes[str(ctx.guild.id)][str(member.id)]\r\n except Exception as e:\r\n prev = member.name\r\n await member.edit(nick=prev)\r\n else:\r\n await member.edit(nick=nickname)\r\n successful = successful + 1\r\n\r\n\r\n except Exception as error:\r\n errors = errors + 1\r\n counter = counter + 1\r\n if counter == int(round(int(len(ctx.guild.members)) / 2)):\r\n await ctx.channel.send(\"> **50 percent done**\")\r\n if nickname == \"reset\":\r\n data = \"none\"\r\n\r\n try:\r\n if str(ctx.guild.id) in prefixes:\r\n if prefixes[str(ctx.guild.id)] != \"none\":\r\n if nickname == \"reset\":\r\n prefixes[str(ctx.guild.id)] = data\r\n doit=1\r\n else:\r\n doit = 0\r\n else:\r\n prefixes[str(ctx.guild.id)] = data\r\n doit =1\r\n else:\r\n prefixes[str(ctx.guild.id)] = data\r\n doit = 1\r\n except Exception as e:\r\n prefixes[str(ctx.guild.id)] = data\r\n doit = 1\r\n if doit == 1:\r\n with open(\"databases/nicks.json\", \"w\") as f:\r\n json.dump(prefixes, f)\r\n embed = discord.Embed(title=f\"Nickname set for **{counter}** users!\", \r\n description=f\"Set nickname to {nickname} for {successful} users\" if nickname != \"reset\" else f\"Reset {successful} user's nicknames\", colour=var.embed) \r\n if errors == 0:\r\n errors = \"No errors 🎉\"\r\n else:\r\n errors = f\"Could not set nickname **{nickname}** for **{errors}** users `Missing permissions`\"\r\n await ctx.channel.send(embed=embed)\r\n\r\nasync def setup(bot):\r\n await bot.add_cog(Moderation3(bot), guilds=var.guilds)","sub_path":"cogs/Moderation3.py","file_name":"Moderation3.py","file_ext":"py","file_size_in_byte":12840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"621846623","text":"import logging\n\nfrom utils.functions_ import is_empty\nfrom utils.database import db_functions as db\n\nfrom discord import Colour, Embed\nfrom discord.ext.commands import Bot, Cog\nfrom discord.ext import commands\n\nlog = logging.getLogger('bot.' + __name__)\n\n\nclass JobsCog(Cog, name='Jobs'):\n \"\"\"Commands related to jobs.\"\"\"\n\n def __init__(self, bot: Bot):\n self.bot = bot\n self.config = self.bot.config\n\n @commands.group(name=\"job\", invoke_without_command=True)\n async def job(self, ctx):\n \"\"\"A tutorial on Jobs.\"\"\"\n embed = Embed(title=\"Jobs\", colour=Colour.blurple(), description=\n \"\"\"You can earn money by joining a job. \n To join a job use `!job join {job}` \n You can have 1 job at a time.\n Each job has its own unique action, check the list below: \n **Miner:** `!mine`\n \"\"\")\n return await ctx.send(embed=embed)\n\n @job.command(name=\"join\")\n async def job_join(self, ctx, job_to_join: str):\n \"\"\"Join a new job.\"\"\"\n db_connection = await db.dbconnection()\n cursor = await db_connection.cursor()\n user_id = ctx.author.id\n sql = \"SELECT * FROM jobs WHERE character_id = '%s'\"\n val = user_id\n await cursor.execute(sql, (val,))\n results = await cursor.fetchall()\n result = []\n available_jobs =[]\n columns = [desc[0] for desc in cursor.description]\n for row in results:\n row = dict(zip(columns, row))\n if row['current_job'] == 'false':\n result.append(row)\n available_jobs.append(row['job'])\n if is_empty(result):\n await cursor.close()\n db_connection.close()\n return await ctx.send(\"You may only have 1 job at a time.\")\n else:\n if job_to_join in available_jobs:\n sql = \"UPDATE jobs SET current_job = 'true' WHERE character_id = '%s' AND job = %s\"\n val = (user_id, job_to_join.lower())\n await cursor.execute(sql, val)\n await db_connection.commit()\n await cursor.close()\n db_connection.close()\n return await ctx.send(f\"Changed your job to: {job_to_join.lower()}.\")\n else:\n await cursor.close()\n db_connection.close()\n return await ctx.send(f\"That job doesnt exist. Pick one of the following: {[job for job in available_jobs]}\")\n\n @job.command(name=\"leave\")\n async def job_leave(self, ctx):\n \"\"\"Leave your job.\"\"\"\n db_connection = await db.dbconnection()\n cursor = await db_connection.cursor()\n user_id = ctx.author.id\n sql = \"SELECT * FROM jobs WHERE character_id = '%s' AND current_job = %s\"\n val = (user_id, 'true')\n await cursor.execute(sql, val)\n results = await cursor.fetchall()\n if is_empty(results):\n await cursor.close()\n db_connection.close()\n return await ctx.send(\"You dont have a job. Use `!job join {job_name}` to join one.\")\n else:\n sql = \"SELECT job FROM jobs WHERE current_job = %s\"\n val = \"true\"\n await cursor.execute(sql, (val,))\n results = await cursor.fetchall()\n sql = \"UPDATE jobs SET current_job = %s WHERE character_id = '%s' AND job = %s\"\n val = ('false', user_id, results[0][0])\n await cursor.execute(sql, val)\n await db_connection.commit()\n await cursor.close()\n db_connection.close()\n return await ctx.send(\"Left your job.\")\n\n\ndef setup(bot):\n bot.add_cog(JobsCog(bot))\n log.debug('Loaded')\n","sub_path":"cogs/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"408123601","text":"from gevent import monkey\nfrom gevent.pool import Pool\nimport gevent\nimport urllib\nfrom urllib import request\nmonkey.patch_all()\n'''协程(coroutine),又称微线程,纤程,是一种用户级的轻量级线程。\n协程拥有自己的寄存器上下文和栈。\n协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈。\n因此协程能保留上一次调用时的状态,每次过程重入时,就相当于进入上一次调用的状态。'''\n# 在并发编程中,协程与线程类似,每个协程表示一个执行单元,有自己的本地数据,与其他协程共享全局数据和其他资源。\n'''\n协程需要用户自己来编写调度逻辑,对于 CPU 来说,协程其实是单线程,所以 CPU 不用去考虑怎么调度、切换上下文,这就省去了 CPU 的切换开销,所以协程在一定程度上又好于多线程。\n实现协程\nPython 通过 yield 提供了对协程的基本支持,但是不完全,而使用第三方 gevent 库是更好的选择,gevent 提供了比较完善的协程支持。\ngevent 是一个基于协程的 Python 网络函数库,使用 greenlet 在 libev 事件循环顶部提供了一个有高级别并发性的 API。\n主要特性有以下几点:\n基于 libev 的快速事件循环,Linux 上是 epoll 机制。\n基于 greenlet 的轻量级执行单元。\nAPI 复用了 Python 标准库里的内容。\n支持 SSL 的协作式 sockets。\n可通过线程池或 c-ares 实现 DNS 查询。\n通过 monkey patching 功能使得第三方模块变成协作式。\ngevent 对协程的支持,本质上是 greenlet 在实现切换工作。\ngreenlet 工作流程如下:\n假如进行访问网络的 IO 操作时,出现阻塞,greenlet 就显式切换到另一段没有被阻塞的代码段执行,直到原先的阻塞状况消失以后,再自动切换回原来的代码段继续处理。\n因此,greenlet 是一种合理安排的串行方式。\n由于 IO 操作非常耗时,经常使程序处于等待状态,有了 gevent 为我们自动切换协程,就保证总有 greenlet 在运行,而不是等待 IO,\n这就是协程一般比多线程效率高的原因。\n由于切换是在 IO 操作时自动完成,所以 gevent 需要修改 Python 自带的一些标准库,将一些常见的阻塞,如 socket、select 等地方实现协程跳转,\n这一过程在启动时通过 monkey patch 完成。下面通过一个的例子来演示 gevent 的使用流程,代码如下:\n'''\n\n\ndef run_task(url):\n print('Visit --> %s' % url)\n try:\n response = urllib.request.urlopen(url)\n data = response.read().decode('utf-8')\n print('%d bytes received from %s.' % (len(data), url))\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n urls = ['https://github.com/', 'https://www.python.org/', 'http://www.cnblogs.com/']\n greenlets = [gevent.spawn(run_task, url) for url in urls]\n gevent.joinall(greenlets)\n\n# 以上程序主要用了 gevent 中的 spawn 方法和 joinall 方法。\n# spawn 方法可以看做是用来形成协程,joinall 方法就是添加这些协程任务,并且启动运行。\n# 从运行结果来看,3个网络操作是并发执行的,而且结束顺序不同,但其实只有一个线程。\n\n'''gevent 中还提供了对池的支持。\n当拥有动态数量的 greenlet 需要进行并发管理(限制并发数)时,\n就可以使用池,\n这在处理大量的网络和 IO 操作时是非常需要的。\n接下来使用 gevent 中 pool 对象,对上面的例子进行改写,程序如下:'''\n\nprint('gevent 中还提供了对池的支持')\n\n\ndef run_task(url):\n print('Visit --> %s' % url)\n try:\n response = urllib.request.urlopen(url)\n data = response.read().decode('utf-8')\n print('%d bytes received from %s.' % (len(data), url))\n except Exception as e:\n print(e)\n return 'url:%s --->finish' % url\n\n\nif __name__ == '__main__':\n pool = Pool(2)\n urls = ['https://github.com/', 'https://www.python.org/', 'http://www.cnblogs.com/']\n results = pool.map(run_task, urls)\n print(results)\n# Pool 对象确实对协程的并发数量进行了管理,先访问了前两个网址,当其中一个任务完成时,才会执行第三个。\n","sub_path":"2018.12.14_d/爬虫/多进程和多线程/协程.py","file_name":"协程.py","file_ext":"py","file_size_in_byte":4355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"44714051","text":"import pygame\nimport numpy as np\n\nfrom pygame.draw import *\nfrom random import randint\npygame.init()\n\nFPS = 20\n\n\nprint(\"Ваше имя:\")#узнаём имя игрока\nusername=input()\n\nglobal length, height, N0\n\nlength = 1200 #длина экрана\nheight = 900 #высота экрана\nN0 = 30 #число шариков на экране\n\nscreen = pygame.display.set_mode((length, height))\n\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nGREEN = (0, 255, 0)\nMAGENTA = (255, 0, 255)\nCYAN = (0, 255, 255)\nBLACK = (0, 0, 0)\nCOLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN]\n\n\ndef cifra(x0,y0,a,color,n):\n '''\n функция рисует цифры от 0 до 9\n x0,y0 - координаты левого нижнего угла\n а - размер цифры\n color - цвет\n n - сама цифра\n '''\n if n == 0:\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0+a, y0-2*a], [x0, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0, y0], 5)\n if n == 1:\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n if n == 2:\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0+a, y0-a], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0, y0], [x0, y0-a], 5)\n if n == 3:\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n if n == 4:\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0, y0-a], 5)\n if n == 5:\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0, y0-a], 5)\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-a], 5)\n if n == 6:\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0, y0], 5)\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0+a, y0-2*a], 5) \n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-a], 5)\n if n == 7:\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0+a, y0-2*a], [x0, y0-2*a], 5)\n if n == 8:\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0, y0], 5)\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0+a, y0-2*a], 5)\n if n == 9:\n pygame.draw.line(screen, color, [x0, y0], [x0+a, y0], 5)\n pygame.draw.line(screen, color, [x0, y0-a], [x0+a, y0-a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0+a, y0], [x0+a, y0-2*a], 5)\n pygame.draw.line(screen, color, [x0, y0-2*a], [x0, y0-a], 5)\n \n# score - счёт \nglobal score\nscore = 0\n\ndef schet(x0,y0,b,color1,color2,N):\n '''\n функция выводит счёт на экран\n xo,y0 - координаты левого верхнего угла квадратика\n b - сторона квадратика\n color1 - цвет квадратика\n color2 - цвет цифор\n N - счёт\n \n '''\n rect(screen, color1, (x0, y0, b, b))\n cifra(x0+b/5,y0+3/4*b,b/4,color2, int(N/10))\n cifra(x0+11*b/20,y0+3/4*b,b/4,color2, N-10*int(N/10))\n \n\nball_list = []\n'''\nсоздаём массив со словарями-шарами\nx,y - координаты\ndx,dy - элементарные перемещения\nr - радиус\ncolor - цвет\ntime - время жизни\n \n'''\nfor i in range(0,N0,1):\n ball_list.append({'ball_x':randint(0,length),'ball_y':randint(0,height),\n 'ball_dx':randint(5,20)*(-1)**randint(1,2),\n 'ball_dy':randint(5,20)*(-1)**randint(1,2),\n 'ball_r':randint(10,40),'ball_color':COLORS[randint(0,5)],\n 'ball_time':randint(50,100)} )\n\nstar_list = []\n'''\nсоздаём массив со словарями-звёздами\nx,y - координаты\ndx,dy - элементарные перемещения\nr - радиус\ncolor - цвет\ntime - время жизни\nalpha - угол поворота\n \n'''\nfor i in range(0,int(N0/10),1):\n star_list.append({'star_x':randint(0,length),'star_y':randint(0,height),\n 'star_dx':randint(5,20)*(-1)**randint(1,2),\n 'star_dy':randint(5,20)*(-1)**randint(1,2),\n 'star_r':randint(10,40),'star_color':COLORS[randint(0,5)],\n 'star_time':randint(50,100),'star_alpha':randint(0,180)} )\n\n\n \ndef new_ball(x,y,r,color):\n '''\n рисует новый шарик\n x,y - координаты шарика\n r - радиус шариков\n color - цвет шарика\n '''\n\n circle(screen, color, (x, y), r)\n\n \ndef new_star(x,y,R,color,alpha):\n '''\n рисует новую звезду\n x,y - координаты звезды\n R - радиус окружности, описывающую звезду\n alpha - угол поворота звезды\n color - цвет звезды\n '''\n polygon(screen, color, [(x+R*np.sin(alpha/180*np.pi),y-R*np.cos(alpha/180*np.pi)),\n (x+R*np.sin((36-alpha)/180*np.pi), y+R*np.cos((36-alpha)/180*np.pi)),\n (x-R/(4*np.cos(18/180*np.pi)*np.cos(18/180*np.pi)-1)*np.sin(alpha/180*np.pi)\n ,y+R/(4*np.cos(18/180*np.pi)*np.cos(18/180*np.pi)-1)*np.cos(alpha/180*np.pi)),\n (x-R*np.sin((36+alpha)/180*np.pi), y+R*np.cos((36+alpha)/180*np.pi)),\n (x+R*np.sin(alpha/180*np.pi),y-R*np.cos(alpha/180*np.pi))])\n polygon(screen, color, [(x-R*np.sin((72-alpha)/180*np.pi),y - R*np.cos((72-alpha)/180*np.pi)),\n (x+R*np.sin((72+alpha)/180*np.pi),y - R*np.cos((72+alpha)/180*np.pi)),\n (x-R*np.sin((36+alpha)/180*np.pi), y+R*np.cos((36+alpha)/180*np.pi)),\n (x-R/(4*np.cos(18/180*np.pi)*np.cos(18/180*np.pi)-1)*np.sin((72+alpha)/180*np.pi), \n y+R/(4*np.cos(18/180*np.pi)*np.cos(18/180*np.pi)-1)*np.cos((72+alpha)/180*np.pi)),\n (x-R*np.sin((72-alpha)/180*np.pi),y - R*np.cos((72-alpha)/180*np.pi))]) \n\ndef move_ball(i):\n '''\n i - номер нужного объкта\n функция создаёт движение шарика для i-ого элемента массива\n '''\n ball_list[i]['ball_x'] += ball_list[i]['ball_dx']\n \n if ball_list[i]['ball_x'] >= length:\n ball_list[i]['ball_dx'] = -ball_list[i]['ball_dx']\n else:\n ball_list[i]['ball_dx'] = ball_list[i]['ball_dx']\n if ball_list[i]['ball_x'] <= 0:\n ball_list[i]['ball_dx'] = -ball_list[i]['ball_dx']\n else:\n ball_list[i]['ball_dx'] = ball_list[i]['ball_dx']\n \n ball_list[i]['ball_y'] += ball_list[i]['ball_dy']\n \n if ball_list[i]['ball_y'] >= height:\n ball_list[i]['ball_dy'] = -ball_list[i]['ball_dy']\n else:\n ball_list[i]['ball_dy'] = ball_list[i]['ball_dy']\n if ball_list[i]['ball_y'] <= 0:\n ball_list[i]['ball_dy'] = -ball_list[i]['ball_dy']\n else:\n ball_list[i]['ball_dy'] = ball_list[i]['ball_dy']\n \ndef move_star(i):\n '''\n i - номер нужного объекта\n функция создаёт движение шарика для i-ого элемента массива\n '''\n star_list[i]['star_x'] += star_list[i]['star_dx']\n \n if star_list[i]['star_x'] >= length:\n star_list[i]['star_dx'] = -star_list[i]['star_dx']\n else:\n star_list[i]['star_dx'] = star_list[i]['star_dx']\n if star_list[i]['star_x'] <= 0:\n star_list[i]['star_dx'] = -star_list[i]['star_dx']\n else:\n star_list[i]['star_dx'] = star_list[i]['star_dx']\n \n star_list[i]['star_y'] += star_list[i]['star_dy']\n \n if star_list[i]['star_y'] >= height:\n star_list[i]['star_dy'] = -star_list[i]['star_dy']\n else:\n star_list[i]['star_dy'] = star_list[i]['star_dy']\n if star_list[i]['star_y'] <= 0:\n star_list[i]['star_dy'] = -star_list[i]['star_dy']\n else:\n star_list[i]['star_dy'] = star_list[i]['star_dy']\n\npygame.display.update()\nclock = pygame.time.Clock()\nfinished = False\n\n \n \nwhile not finished:\n clock.tick(FPS)\n for i in range(len(ball_list)):\n new_ball(ball_list[i]['ball_x'], ball_list[i]['ball_y'],\n ball_list[i]['ball_r'], ball_list[i]['ball_color'])\n ball_list[i]['ball_time'] -= 1\n move_ball(i)\n if ball_list[i]['ball_time'] == 0:\n ball_list[i]['ball_time'] = randint(50,100)\n ball_list[i]['ball_x'] = (randint(0,length))\n ball_list[i]['ball_y'] = (randint(0,height))\n ball_list[i]['ball_color'] = (COLORS[randint(0,5)])\n for i in range(0,int(N0/10),1):\n new_star(star_list[i]['star_x'], star_list[i]['star_y'],\n star_list[i]['star_r'], star_list[i]['star_color'],\n star_list[i]['star_alpha'])\n star_list[i]['star_time'] -= 1\n move_star(i)\n star_list[i]['star_alpha'] += 10\n if star_list[i]['star_time'] == 0:\n star_list[i]['star_time'] = randint(50,100)\n star_list[i]['star_x'] = (randint(0,length))\n star_list[i]['star_y'] = (randint(0,height))\n star_list[i]['star_color'] = (COLORS[randint(0,5)])\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n finished = True\n elif event.type == pygame.MOUSEBUTTONDOWN:\n for i in range(0,N0,1):\n if (ball_list[i]['ball_x']-event.pos[0])*(ball_list[i]['ball_x']-event.pos[0])\\\n +(ball_list[i]['ball_y']-event.pos[1])*(ball_list[i]['ball_y']-event.pos[1])\\\n < ball_list[i]['ball_r']*ball_list[i]['ball_r']:\n \n #\"исчезновение\" шарика\n ball_list[i]['ball_time'] = randint(50,100)\n ball_list[i]['ball_x'] = (randint(0,length))\n ball_list[i]['ball_y'] = (randint(0,height))\n ball_list[i]['ball_color'] = (COLORS[randint(0,5)])\n score +=1\n else:\n score +=0\n for i in range(0,int(N0/10),1):\n if (star_list[i]['star_x']-event.pos[0])*(star_list[i]['star_x']-event.pos[0])\\\n +(star_list[i]['star_y']-event.pos[1])*(star_list[i]['star_y']-event.pos[1])\\\n < star_list[i]['star_r']*star_list[i]['star_r']:\n #\"исчезновение\" звезды\n star_list[i]['star_time'] = randint(50,100)\n star_list[i]['star_x'] = (randint(0,length))\n star_list[i]['star_y'] = (randint(0,height))\n star_list[i]['star_color'] = (COLORS[randint(0,5)])\n \n score +=5\n else:\n score +=0\n \n schet(100,100,70,RED,YELLOW,score) \n pygame.display.update()\n screen.fill(BLACK)\n\n \n \npygame.quit()\n\n#создаём рейтинг\ntable=[]\nfile = open('Results.txt','r')\nfor i in file.readlines():\n table.append(i.split(':'))\nfile.close()\ntable.append([0,username,str(score),'\\n'])\ntables=sorted(table, key=lambda t: -int(t[2]))\n\nfile1 = open('Results.txt','w')\nfile1.flush()\nfor i in range(len(tables)):\n file1.write(str(i+1)+':'+tables[i][1]+':'+tables[i][2]+':\\n')\nfile1.close()\n\nprint(username,':',score)\n","sub_path":"Lab7.py","file_name":"Lab7.py","file_ext":"py","file_size_in_byte":12689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"591273839","text":"#time python3 MitocallerResult2seq_2.py refDG.fasta fils.txt\nfrom sys import argv\nfrom itertools import islice\nimport re\nfrom collections import OrderedDict\nfrom Bio import SeqIO\nfrom Bio.Seq import MutableSeq\nfrom Bio.SeqRecord import SeqRecord\n\n\nseq_record =SeqIO.read(argv[1],\"fasta\")\n\ndef cpr(genetype,frq):\n genetypes,frqs=re.split(':|/',genetype)[1:],re.split(':|/',frq)[1:]\n d=dict(zip(genetypes,frqs))\n d_sort=OrderedDict(sorted(d.items(),key = lambda t:t[1],reverse=True))\n genefrq=list(d_sort.items())[0]\n g,f=genefrq[0],genefrq[1]\n return g,f\n\nl0=list(range(1,19525))\ndef op(f):\n dpos,lhave={},[]\n with open(f,\"r\") as mitocall:\n for line in islice(mitocall,1,None):\n #strline=line.strip()#get substitution line\n line=line.strip().split(\"\\t\")\n pos,ref,genetype,frq=int(line[1]),line[2],line[30],line[31]\n lhave.append(pos)\n depth0,depth1=line[3],line[11]\n depth=re.split(':',depth1)[1]\n\n alt,altfrq=cpr(genetype,frq)\n refbase=re.split(':|/',ref)[1]\n if alt!=\"N\" and refbase != alt and int(depth)>=10 and float(altfrq)==1:\n dpos[pos]=[refbase,alt,altfrq,line]\n dpos_sort=OrderedDict(sorted(dpos.items(),key=lambda t:t[0],reverse=False))\n lnot=list(set(l0)-set(lhave))\n lnot.sort()\n return dpos_sort,lnot\n\ndef ref2seq(d,l):\n mutseq1=MutableSeq(str(seq_record.seq))\n for k in d.keys():\n if mutseq1[k-1]==d[k][0]:\n #print(\"###REFSEQ GENE MATCH XLS REF###\")\n mutseq1[k-1]=d[k][1]\n #for i in l:#change not get pos to ?\n #mutseq1[i-1]=\"?\"\n return mutseq1\n\nwith open(argv[2],\"r\") as allfils:\n for i in allfils.readlines():\n i=i.strip()\n name=i.split(\".\")[0]\n otfil=open(name+\".ref2seqfromMitocall_1\",\"w\")\n subfil=open(name+\".sub_1\",\"w\")\n daltpos,lnot=op(i)\n for k in daltpos.keys():\n subfil.write(\"\\t\".join(daltpos[k][3])+\"\\n\")\n #print(len(daltpos.keys()),daltpos)\n nalt,nnot=len(daltpos.keys()),len(lnot)\n changeseq=ref2seq(daltpos,lnot)\n rec=SeqRecord(changeseq,id=name,description=str(nalt)+\" subs \"+str(nnot)+\" posnot\")\n SeqIO.write(rec,otfil,\"fasta\")\n otfil.close()\n subfil.close()\n","sub_path":"MitocallerResult2seq.py","file_name":"MitocallerResult2seq.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"514878213","text":"import json\r\nimport pandas as pd\r\n\r\nwith open(\"./sparql_rawdata/sparql_almaMater.json\",\"r\",encoding='utf-8') as f:\r\n new_dict = json.loads(f.read())\r\n\r\n dic = new_dict['results']['bindings']\r\n celebrity = []\r\n almaMater = []\r\n for item in dic:\r\n name_temp = item['name']['value']\r\n name = name_temp.strip().strip('(').strip(')')\r\n x = item['x']['value']\r\n y = item['y']['value']\r\n temp = item['place']['value']\r\n school = temp.split('/')[-1].split(',')[0].replace(\"_\",\" \")\r\n if len(name)>0:\r\n if len(celebrity)>0:\r\n if name == celebrity[-1] and school == almaMater[-1]:\r\n pass\r\n else:\r\n celebrity.append(name)\r\n almaMater.append(school)\r\n else:\r\n celebrity.append(name)\r\n almaMater.append(school)\r\n dataframe = pd.DataFrame({'celebrity': celebrity, 'almaMater': almaMater})\r\n dataframe.to_csv(\"almaMater.csv\", index=False, sep=',')\r\n","sub_path":"data_crawler/dbpedia_sparql/almaMater.py","file_name":"almaMater.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"80537401","text":"#!/usr/bin/env python\n\"\"\"Collection of functions for the manipulation of time series.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport mando\nfrom mando.rst_text_formatter import RSTHelpFormatter\n\nfrom .. import tsutils\n\n\n@mando.command(\"pca\", formatter_class=RSTHelpFormatter, doctype=\"numpy\")\n@tsutils.doc(tsutils.docstrings)\ndef pca_cli(\n input_ts=\"-\",\n columns=None,\n start_date=None,\n end_date=None,\n clean=False,\n skiprows=None,\n index_type=\"datetime\",\n names=None,\n n_components=None,\n source_units=None,\n target_units=None,\n round_index=None,\n tablefmt=\"csv\",\n):\n \"\"\"Return the principal components analysis of the time series.\n\n Does not return a time-series.\n\n Parameters\n ----------\n n_components : int\n [optional, default is None]\n\n The columns in the input_ts will be grouped into `n_components`\n groups.\n {input_ts}\n {columns}\n {start_date}\n {end_date}\n {clean}\n {skiprows}\n {index_type}\n {names}\n {source_units}\n {target_units}\n {round_index}\n {tablefmt}\n\n \"\"\"\n tsutils.printiso(\n pca(\n input_ts=input_ts,\n columns=columns,\n start_date=start_date,\n end_date=end_date,\n clean=clean,\n skiprows=skiprows,\n index_type=index_type,\n names=names,\n n_components=n_components,\n source_units=source_units,\n target_units=target_units,\n round_index=round_index,\n ),\n tablefmt=tablefmt,\n )\n\n\n@tsutils.validator(n_components=[int, [\"range\", [1, None]], 1])\ndef pca(\n input_ts=\"-\",\n columns=None,\n start_date=None,\n end_date=None,\n clean=False,\n skiprows=None,\n index_type=\"datetime\",\n names=None,\n n_components=None,\n source_units=None,\n target_units=None,\n round_index=None,\n):\n \"\"\"Return the principal components analysis of the time series.\"\"\"\n from sklearn.decomposition import PCA\n\n tsd = tsutils.common_kwds(\n tsutils.read_iso_ts(\n input_ts, skiprows=skiprows, names=names, index_type=index_type\n ),\n start_date=start_date,\n end_date=end_date,\n round_index=round_index,\n pick=columns,\n source_units=source_units,\n target_units=target_units,\n clean=clean,\n )\n\n pca = PCA(n_components)\n pca.fit(tsd.dropna(how=\"any\"))\n return pca.components_\n\n\npca.__doc__ = pca_cli.__doc__\n","sub_path":"tstoolbox/functions/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"635114900","text":"# -*- coding: utf-8 -*-\nimport torch\nfrom torch import nn\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\nfrom dataset import CarDataset\nfrom network import resnet101\nfrom util import Trainer\n\nif __name__ == '__main__':\n # Hyper-params\n data_root = './record/images/'\n train_csv = './record/train.txt'\n val_csv = './record/val.txt'\n model_path = './models/'\n batch_size = 40 # batch_size per GPU, if use GPU mode; resnet34: batch_size=120\n num_workers = 2\n\n init_lr = 0.01\n lr_decay = 0.8\n momentum = 0.9\n weight_decay = 0.000\n nesterov = True\n\n # Set Training parameters\n params = Trainer.TrainParams()\n params.max_epoch = 500\n params.criterion = nn.CrossEntropyLoss()\n params.gpus = [0] # set 'params.gpus=[]' to use CPU mode\n params.save_dir = model_path\n params.ckpt = None\n params.save_freq_epoch = 50\n\n # 图片转换 原图:(135, 202, 3)\n transform = transforms.Compose([\n transforms.Resize(224), # 缩放图片,保持长宽比不变,最短边的长为224像素,\n transforms.CenterCrop(224), # 从中间切出 224*224的图片\n transforms.ToTensor(), # 将图片转换为Tensor,归一化至[0,1]\n transforms.Normalize(mean=[.5, .5, .5], std=[.5, .5, .5]) # 标准化至[-1,1]\n ])\n\n # load data\n print(\"Loading dataset...\")\n train_data = CarDataset(train_csv, data_root, transform=transform)\n val_data = CarDataset(val_csv, data_root, transform=transform)\n\n batch_size = batch_size if len(params.gpus) == 0 else batch_size * len(params.gpus)\n\n train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=num_workers)\n print('train dataset len: {}'.format(len(train_dataloader.dataset)))\n\n val_dataloader = DataLoader(val_data, batch_size=batch_size, shuffle=False, num_workers=num_workers)\n print('val dataset len: {}'.format(len(val_dataloader.dataset)))\n\n # models\n # model = resnet34(pretrained=False, modelpath=model_path, num_classes=1000) # batch_size=120, 1GPU Memory < 7000M\n # model.fc = nn.Linear(512, 6)\n model = resnet101(pretrained=False, modelpath=model_path, num_classes=1000) # batch_size=60, 1GPU Memory > 9000M\n model.fc = nn.Linear(512 * 4, 2951)\n\n # optimizer\n trainable_vars = [param for param in model.parameters() if param.requires_grad]\n print(\"Training with sgd\")\n params.optimizer = torch.optim.SGD(trainable_vars, lr=init_lr,\n momentum=momentum,\n weight_decay=weight_decay,\n nesterov=nesterov)\n\n # Train\n params.lr_scheduler = ReduceLROnPlateau(params.optimizer, 'min', factor=lr_decay, patience=10, cooldown=10,\n verbose=True)\n trainer = Trainer(model, params, train_dataloader, val_dataloader)\n trainer.train()\n","sub_path":"classifier_train.py","file_name":"classifier_train.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"191743551","text":"#!/usr/bin/python\nimport smbus\nimport math\nimport requests\nimport json\nimport time\n\n#POST URL\nurl=\"http://192.168.43.115:5000/api/\"\n\n#PI_URL = \"192.168.43.215\"\n \n# Register\npower_mgmt_1 = 0x6b\npower_mgmt_2 = 0x6c\n \ndef read_byte(reg):\n return bus.read_byte_data(address, reg)\n \ndef read_word(reg):\n h = bus.read_byte_data(address, reg)\n l = bus.read_byte_data(address, reg+1)\n value = (h << 8) + l\n return value\n \ndef read_word_2c(reg):\n val = read_word(reg)\n if (val >= 0x8000):\n return -((65535 - val) + 1)\n else:\n return val\n \ndef dist(a,b):\n return math.sqrt((a*a)+(b*b))\n \ndef get_y_rotation(x,y,z):\n radians = math.atan2(x, dist(y,z))\n return -math.degrees(radians)\n \ndef get_x_rotation(x,y,z):\n radians = math.atan2(y, dist(x,z))\n return math.degrees(radians)\nwhile(True): \n bus = smbus.SMBus(1) # bus = smbus.SMBus(0) fuer Revision 1\n address = 0x68 # via i2cdetect\n \n # Aktivieren, um das Modul ansprechen zu koennen\n bus.write_byte_data(address, power_mgmt_1, 0)\n \n #print \"Gyroskop\"\n #print \"--------\"\n \n gyroskop_xout = read_word_2c(0x43)\n gyroskop_yout = read_word_2c(0x45)\n gyroskop_zout = read_word_2c(0x47)\n \n #print \"gyroskop_xout: \", (\"%5d\" % gyroskop_xout), \" skaliert: \", (gyroskop_xout / 131)\n #print \"gyroskop_yout: \", (\"%5d\" % gyroskop_yout), \" skaliert: \", (gyroskop_yout / 131)\n #print \"gyroskop_zout: \", (\"%5d\" % gyroskop_zout), \" skaliert: \", (gyroskop_zout / 131)\n \n #print\n #print \"Beschleunigungssensor\"\n #print \"---------------------\"\n \n beschleunigung_xout = read_word_2c(0x3b)\n beschleunigung_yout = read_word_2c(0x3d)\n beschleunigung_zout = read_word_2c(0x3f)\n \n beschleunigung_xout_skaliert = beschleunigung_xout / 16384.0\n beschleunigung_yout_skaliert = beschleunigung_yout / 16384.0\n beschleunigung_zout_skaliert = beschleunigung_zout / 16384.0\n \"\"\" \n print \"beschleunigung_xout: \", (\"%6d\" % beschleunigung_xout), \" skaliert: \", beschleunigung_xout_skaliert\n print \"beschleunigung_yout: \", (\"%6d\" % beschleunigung_yout), \" skaliert: \", beschleunigung_yout_skaliert\n print \"beschleunigung_zout: \", (\"%6d\" % beschleunigung_zout), \" skaliert: \", beschleunigung_zout_skaliert\n \n print \"X Rotation: \" , get_x_rotation(beschleunigung_xout_skaliert, beschleunigung_yout_skaliert, beschleunigung_zout_skaliert)\n print \"Y Rotation: \" , get_y_rotation(beschleunigung_xout_skaliert, beschleunigung_yout_skaliert, beschleunigung_zout_skaliert)\n \"\"\"\n\n x_post = get_x_rotation(beschleunigung_xout_skaliert, beschleunigung_yout_skaliert, beschleunigung_zout_skaliert)\n y_post = get_y_rotation(beschleunigung_xout_skaliert, beschleunigung_yout_skaliert, beschleunigung_zout_skaliert)\n\n request_str = {\"base\":{\"x\":x_post,\"y\":y_post}}\n\n requests.post(url, json=json.dumps(request_str))\n time.sleep(1)","sub_path":"rpi/gyro.py","file_name":"gyro.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"377467858","text":"#!/usr/bin/env python3\n\nimport requests\nimport pprint\nimport json\nimport time\nimport argparse\n\n\nMAXRECORDS = 10\nRETRIES = 3\n\nBASEURL = \"http://localhost:8080/todo/api/tasks\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--url\", help=\"The URL to manipulate ReST API\",\n type=str)\nparser.add_argument(\"--records\", help=\"The number of records to insert into the ReST API\",\n type=int)\nargs = parser.parse_args()\n\nif args.url:\n BASEURL = args.url\n#else:\n# print(\"You most enter a URL\")\n\nif args.records:\n MAXRECORDS = args.records\n\n\ndef get_http_status_code(r):\n return(r.status_code)\n \ndef send_http_command(command, payload, url, expected_code):\n\n attempts = 1\n while (attempts <= RETRIES):\n if command == 'POST':\n r = requests.post(url, json=payload)\n status = get_http_status_code(r)\n if status == 201:\n attempts = RETRIES + 1\n print(\"Post was successful\")\n else:\n attempt += 1 \n print(\"Post was unsuccessful - will wait and retry\")\n sleep(1)\n elif command == 'PUT':\n r = requests.put(url, json=payload)\n status = get_http_status_code(r)\n if status == 200:\n attempts = RETRIES + 1\n print(\"Put was successful\")\n else:\n attempt += 1 \n print(\"Put was unsuccessful - will wait and retry\")\n sleep(1)\n elif command == 'DELETE':\n r = requests.delete(url, json=payload) \n status = get_http_status_code(r)\n if status == 200:\n attempts = RETRIES + 1\n print(\"Delete was successful\")\n else:\n attempt += 1 \n print(\"Delete was unsuccessful - will wait and retry\")\n sleep(1)\n elif command == 'GET':\n r = requests.get(url) \n status = get_http_status_code(r)\n if status == 200:\n attempts = RETRIES + 1\n print(\"Get was successful\")\n else:\n attempt += 1 \n print(\"Get was unsuccessful - will wait and retry\")\n sleep(1)\n else:\n print(\"Tragedy has occurred. Exiting\")\n exit(99)\n return(r)\n\nwhile True:\n print(\" << Dumping records >> \")\n print(\"===================================================================================\")\n r = send_http_command(\"GET\", \"\", BASEURL, 200)\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(r.json())\n print(\"===================================================================================\\n\")\n time.sleep(3)\n\n print(\" << Inserting records >> \")\n print(\"===================================================================================\")\n for i in range(2,MAXRECORDS+1):\n title_str = \"One: task#\"+str(i)\n desc_str = \"Actions to take for task #\"+str(i)\n payload = {'title':title_str, 'description':desc_str}\n print(\"Inserting ->\", payload)\n r = send_http_command(\"POST\", payload, BASEURL, 201)\n print(\"-----------------------------------------------------------------------------------\")\n time.sleep(1)\n\n print(\"\\n\")\n print(\" << Dumping records >> \")\n print(\"===================================================================================\\n\")\n r = requests.get(BASEURL)\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(r.json())\n print(\"===================================================================================\\n\")\n time.sleep(3)\n\n\n print(\" << Updating records >> \")\n print(\"===================================================================================\")\n for i in range(1,MAXRECORDS+1):\n NEWURL = BASEURL + \"/\" + str(i) \n payload = {'done':True}\n print(\"setting %s on %s\" % (payload, NEWURL))\n r = send_http_command(\"PUT\", payload, NEWURL, 200)\n print(\"-----------------------------------------------------------------------------------\")\n time.sleep(1)\n\n print(\"\\n\")\n print(\" << Dumping records >> \")\n print(\"===================================================================================\\n\")\n r = requests.get(BASEURL)\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(r.json())\n print(\"===================================================================================\\n\")\n time.sleep(3)\n\n\n\n print(\" << Purging records >> \")\n print(\"===================================================================================\")\n for i in range(2,MAXRECORDS+1):\n NEWURL = BASEURL + \"/\" + str(i)\n payload = {'id':i}\n print(\"Deleting record %s on %s\" % (payload, NEWURL))\n r = send_http_command(\"DELETE\", payload, NEWURL, 200)\n print(\"-----------------------------------------------------------------------------------\")\n time.sleep(1)\n\n\n print(\"\\n\")\n print(\" << Dumping records >> \")\n print(\"===================================================================================\\n\")\n r = requests.get(BASEURL)\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(r.json())\n print(\"===================================================================================\\n\")\n time.sleep(3)\n\n print(\"\\n\")\n print(\" << Updating base record >> \")\n print(\"===================================================================================\\n\")\n NEWURL = BASEURL + \"/\" + str(1) \n payload = {'done':False}\n print(\"Updating record %s with %s\" % (NEWURL, payload))\n r = requests.put(NEWURL, json=payload)\n\n print(\"\\n\")\n print(\" << Dumping records >> \")\n print(\"===================================================================================\\n\")\n r = requests.get(BASEURL)\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(r.json())\n print(\"===================================================================================\\n\")\n","sub_path":"RestClient/rest_client.py","file_name":"rest_client.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"245192616","text":"#!/usr/bin/python\n\n# imports\nimport sys\nimport math\nimport operator\nimport numpy as np\nimport os\nfrom scipy.sparse import *\n\n# constants\nLR_RANK_TEST_FILE = \"bin/lr_rank_test.txt\" \nFEAT_SIZE = 44\n\n\ndef get_no_rows(fileName):\n\treturn sum(1 for line in open(fileName))\n\ndef normalize(v):\n\tnorm = 0\n\tfor i in v:\n\t\tnorm = norm + i*i\n\tnorm = math.sqrt(norm)\n\tfor i in range(len(v)):\n\t\tv[i] = v[i] / norm\n\treturn v\n\ndef read_data(data):\n\tX = {}\n\ty = {}\n\ti = 0\n\tfor sample in open(data):\n\t\ti = i + 1 \n\t\tX[i] = []\n\t\tarr_sample = sample.split(\" \")\n\t\tlabel_sample = int(arr_sample[0])\n\t\tarr_sample[-1] = (arr_sample[-1])[:-1]\n\t\tqid = int(arr_sample[1].split(\":\")[1])\n\t\tfor j in range(1, FEAT_SIZE+1):\n\t\t\tentry = arr_sample[j+1]\n\t\t\t(fid, val) = entry.split(\":\")\n\t\t\tX[i].append(float(val))\n\t\tdocid = int(arr_sample[-1])\n\t\ty[i] = label_sample\n\t\tX[i] = normalize(X[i])\n\treturn X, y\n\n\n\n\ndef main(argv):\n\ttest_data_file = argv[1]\n\tif os.path.isfile(LR_RANK_TEST_FILE) == False:\n\t\tX, y = read_data(test_data_file)\n\t\t# Create new file\n\t\tlr_rank_test_file = open(LR_RANK_TEST_FILE, 'w+')\n\n\t\tfor j in X:\t\n\t\t\tlr_rank_test_file.write(\"%d\" % y[j])\n\t\t\tv = X[j]\n\t\t\tfor i in range(len(v)):\n\t\t\t\tlr_rank_test_file.write(\" %d:%f\" % (i+1, v[i])) \n\t\t\tlr_rank_test_file.write(\"\\n\")\n\n\n\t\t# # Close new file\n\t\tlr_rank_test_file.close()\n\n\nif __name__ == \"__main__\":\n\tmain(sys.argv)","sub_path":"LOGISTIC/Implementation/normalize_test.py","file_name":"normalize_test.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"114509480","text":"#/usr/bin/env python\n\nimport sys\n\n# Queue for BFS\nclass Queue:\n def __init__(self):\n self.storage = []\n \n # enqueue method\n def enqueue(self, value):\n self.storage.append(value)\n\n # dequeue method\n def dequeue(self):\n return self.storage.pop(0) if self.size() > 0 else None\n\n\n # size method\n def size(self):\n return len(self.storage)\n\n # for indexing\n def __getitem__(self, index):\n return self.storage[index]\n\n def __setitem__(self, index):\n return self.storage[index]\n\n# Edge class\nclass Edge:\n def __init__(self, destination, weight=1):\n self.destination = destination\n self.weight = weight\n\n\n# Vertex class\nclass Vertex:\n def __init__(self, value='vertex', color='white', parent=None):\n self.value = value\n self.edges = []\n # Color of this vertex\n # Used to mark vertices for the traversal algorithm (BFS or DFS)\n self.color = color\n # Parent reference to keep track of the previous node in the\n # graph when traversing through the graph\n self.parent = parent\n\n\n# Graph class\nclass Graph:\n def __init__(self):\n self.vertices = []\n\n def find_vertex(self, value):\n \"\"\"\n Looks through all the vertices in the graph instance and returns\n the first vertex it finds that matches the `value` parameter.\n\n Used in the `main` function to look up the vertices passed in\n from the command line.\n\n @param {*} value: The value of the Vertex to find\n\n @return None if no such Vertex exists in the Graph.\n @return {Vertex} the found Vertex\n \"\"\"\n # looping over all vertices and if the value matches return the vert otherwise return none\n for vert in self.vertices:\n if vert.value == value:\n return vert\n return None\n\n def bfs(self, start):\n \"\"\"\n Breadth-First search from an input starting Vertex\n Should maintain parent references back from neighbors to their parent.\n\n @param {Vertex} start: The starting vertex\n \"\"\"\n # bfs needs a rework\n # rework idea using my new Queue() class updates\n\n # create an empty queue\n queue = Queue()\n\n # # loop over the vertices setting them to while like in bokeh grids\n ## and clear the parents\n for vert in self.vertices:\n vert.color = \"white\"\n vert.parent = None\n \n ## set the starting vert color to gray\n ## and add it to the queue\n start.color = \"gray\"\n queue.enqueue(start)\n\n ## while the queue has some items grab the first item off it and set it to the current one\n while queue.size() > 0:\n current = queue[0] # this made me have to make some new methods in my queue class\n\n ## loop over thr edges and if the edge destination is white then \n ## set the edge destination to gray and set the edge destination pareent to the current\n ## and add the edge.destination to the queue\n for edge in current.edges:\n if edge.destination.color == \"white\":\n edge.destination.color = \"gray\"\n edge.destination.parent = current\n queue.enqueue(edge.destination)\n\n ## set the current color to black and and deque the front off\n current.color = \"black\"\n queue.dequeue()\n\n\n\n\n def output_route(self, start):\n \"\"\"\n Print out the route from the start vertex back along its parent\n references (these were set in the `bfs` method)\n\n @param {Vertex} start: The starting Vertex to follow and print\n \"\"\"\n # going back to basics to get a simplified version with a list comprehension\n route_list = []\n vert = start\n\n while vert:\n route_list.append(vert)\n vert = vert.parent\n\n print(\" --> \".join([F\"{v.value}\" for v in route_list]))\n return \" --> \".join([F\"{v.value}\" for v in route_list]) # this breaks bfs\n\n def route(self, start, end):\n # BFS to build the parent reference tree\n self.bfs(end)\n # print the route from the start Vertex\n self.output_route(start)\n\n\n# Helper function to add bidirectional edges\ndef add_edge(start, end):\n start.edges.append(Edge(end))\n end.edges.append(Edge(start))\n\n\ngraph = Graph()\nvertA = Vertex('HostA')\nvertB = Vertex('HostB')\nvertC = Vertex('HostC')\nvertD = Vertex('HostD')\nvertE = Vertex('HostE')\nvertF = Vertex('HostF')\nvertG = Vertex('HostG')\nvertH = Vertex('HostH')\n\nadd_edge(vertA, vertB)\nadd_edge(vertB, vertD)\nadd_edge(vertA, vertC)\nadd_edge(vertC, vertD)\nadd_edge(vertC, vertF)\nadd_edge(vertG, vertF)\nadd_edge(vertE, vertF)\nadd_edge(vertH, vertF)\nadd_edge(vertH, vertE)\n\ngraph.vertices.append(vertA)\ngraph.vertices.append(vertB)\ngraph.vertices.append(vertC)\ngraph.vertices.append(vertD)\ngraph.vertices.append(vertE)\ngraph.vertices.append(vertF)\ngraph.vertices.append(vertG)\ngraph.vertices.append(vertH)\n\n# Look up the hosts passed in from the command line by\n# name to see if we can find them.\nhostAVert = graph.find_vertex(sys.argv[1])\nif hostAVert is None:\n print('routing.py: could not find host: ', sys.argv[1])\n sys.exit()\n\nhostBVert = graph.find_vertex(sys.argv[2])\n\nif hostBVert is None:\n print('routing.py: could not find host: ', sys.argv[2])\n sys.exit()\n\n# Show the route from one Vertex to the other\ngraph.route(hostAVert, hostBVert)\n","sub_path":"GIT-USERS/TOM2/Sprint-Challenge--Graphs/graph_shortest_path/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"503054298","text":"from sys import stdin\nfrom collections import deque\nfrom collections.abc import MutableMapping\n\n\n\nclass MapBase(MutableMapping):\n \"\"\"Abstract base class that includes a nonpublic _Item class.\"\"\"\n\n class _Item:\n \"\"\"Ligthweight component to store key-value pairs as map items.\"\"\"\n __slots__ = \"_key\", \"_value\"\n\n def __init__(self, k, v):\n self._key = k\n self._value = v\n\n def __eq__(self, other):\n return self._key == other._key\n\n def __ne__(self, other):\n return not (self == other)\n\n def __lt__(self, other):\n return self._key < other._key\n\n\n\nclass Tree:\n \"\"\"Abstract base class representing a tree structure.\"\"\"\n\n #--------------------------nested Position class--------------------------\n class Position:\n \"\"\"An abstraction representing the location of a single element.\"\"\"\n def element(self):\n \"\"\"Return the element stored at this Position.\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def __eq__(self, other):\n \"\"\"Return True if other Position represents the same location.\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def __ne__(self, other):\n \"\"\"Return True if other does not represent the same location.\"\"\"\n return not (self == other)\n\n #----------abstract methods that concrete subclass must support-----------\n def root(self):\n \"\"\"Return Position representing tree's root (or None if empty).\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def parent(self, p):\n \"\"\"Return postion representing p's parent (or None if p is root).\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def num_children(self, p):\n \"\"\"Return the number children that Position p has.\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def children(self, p):\n \"\"\"Generate an iteration over Posistions representing p's children.\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def __len__(self):\n \"\"\"Return total number of elements in the tree.\"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n #----------------concrete methods implemented in this class---------------\n def __iter__(self):\n \"\"\"Generate an iteration of the tree's elements.\"\"\"\n for p in self.positions():\n yield p.element()\n\n def positions(self):\n \"\"\"Generate an iteration of the tree's positions.\"\"\"\n return self.preoder()\n \n def is_root(self, p):\n \"\"\"Return True if Position p is the root of the tree.\"\"\"\n return self.root() == p\n\n def is_leaf(self, p):\n \"\"\"Return True if Position p does not have any children.\"\"\"\n return self.num_children(p) == 0\n\n def is_empty(self):\n \"\"\"Return True if tree is empty.\"\"\"\n return len(self) == 0\n\n def depth(self, p):\n \"\"\"Return the number of levels separating Postion p from the root.\"\"\"\n if self.is_root(p):\n return 0\n else:\n return 1 + self.depth(self.parent(p))\n\n def _height(self, p):\n \"\"\"Return the height of the subtree rooted at Position p.\"\"\"\n if self.is_leaf(p):\n return 0\n else:\n return 1 + max(self._height(child) for child in self.children(p))\n\n def height(self, p = None):\n \"\"\"\n Return the height of the subtree rooted at Position p.\n If p is None return the height of the entire tree.\n \"\"\"\n if p is None:\n p = self.root()\n return self._height(p)\n\n def _subtree_preoder(self, p):\n \"\"\"Generate a preoder iteration of positions of subtree rooted at p.\"\"\"\n yield p\n for child in self.children(p):\n for other in self._subtree_preoder(child):\n yield other\n\n def preoder(self, p = None):\n \"\"\"Generate a preoder iteration of positions in the tree.\"\"\"\n if not self.is_empty():\n for p in self._subtree_preoder(self.root()):\n yield p\n\n def _subtree_postoder(self, p):\n \"\"\"Generate a postoder iteration of positions of subtree rooted at p.\"\"\"\n for child in self.children(p):\n for other in self._subtree_postoder(child):\n yield other\n yield p\n\n def postoder(self):\n \"\"\"Generate a postoder iteration of positions in the tree.\"\"\"\n if not self.is_empty():\n for p in self._subtree_postoder(self.root()):\n yield p\n\n def breadthfirst(self):\n \"\"\"Generate a breadth-first iteration of positions in the tree.\"\"\"\n if not self.is_empty():\n boundary = deque()\n boundary.append(self.root())\n while len(boundary) > 0:\n p = boundary.popleft()\n yield p\n for child in self.children(p):\n boundary.append(child)\n\n\n\nclass BinaryTree(Tree):\n \"\"\"Abstract base class representing a binary tree structure.\"\"\"\n #-----------------------additional abstract methods-----------------------\n def left(self, p):\n \"\"\"\n Return a Position representing p's left child.\n Return None if p does not have left child.\n \"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n def right(self, p):\n \"\"\"\n Return a Position representing p's right child.\n Return None if p does not have right child.\n \"\"\"\n raise NotImplementedError(\"must be implemented by subclass\")\n\n #----------------concrete methods implemented in this class---------------\n def sibling(self, p):\n \"\"\"\n Return a Position representig p's sibling\n (or None if there's no sibling).\n \"\"\"\n parent = self.parent(p)\n if parent is None: # p is root\n return None\n else:\n if p == self.left(parent):\n return self.right(parent)\n else:\n return self.left(parent)\n\n def children(self, p):\n \"\"\"Generate an iteration over p's children.\"\"\"\n if self.left(p) is not None:\n yield self.left(p)\n if self.right(p) is not None:\n yield self.right(p)\n\n def positions(self):\n \"\"\"Generate an iteration of the tree's positions.\"\"\"\n return self.inorder()\n\n def _subtree_inorder(self, p):\n \"Generate an inorder iteration of positions of subtree rooted at p.\"\"\"\n if self.left(p) is not None:\n for other in self._subtree_inorder(self.left(p)):\n yield other\n yield p\n if self.right(p) is not None:\n for other in self._subtree_inorder(self.right(p)):\n yield other\n\n def inorder(self):\n \"\"\"Generate an inoder iteration of positions in the tree.\"\"\"\n if not self.is_empty():\n for p in self._subtree_inorder(self.root()):\n yield p\n\n\n\nclass LinkedBinaryTree(BinaryTree):\n \"\"\"Linked representation for a binary tree structure.\"\"\"\n \n class _Node:\n \"\"\"Lightweight nonpublic class for storing a node.\"\"\"\n __slots__ = \"_element\", \"_parent\", \"_left\", \"_right\"\n def __init__(self, element, parent = None, left = None, right = None):\n self._element = element\n self._parent = parent\n self._left = left\n self._right = right\n\n class Position(BinaryTree.Position):\n \"\"\"An abstraction representing the position of a single element.\"\"\"\n def __init__(self, container, node):\n \"\"\"Constructor should not be invoked by user.\"\"\"\n self._container = container\n self._node = node\n\n def element(self):\n \"\"\"Return the element stored at this Position.\"\"\"\n return self._node._element\n\n def __eq__(self, other):\n \"\"\"Return True if other is a Position representing the same location.\"\"\"\n return (type(self) is type(other)) and (self._node is other._node)\n\n def _validate(self, p):\n \"\"\"Return associated node if Position p is valid.\"\"\"\n if not isinstance(p, self.Position):\n raise TypeError(\"p must be prober Poision type.\")\n if p._container is not self:\n raise ValueError(\"p does not belong to this container\")\n if p._node._parent is p._node:\n raise ValueError(\"p is no longer valid\")\n return p._node\n\n def _make_position(self, node):\n \"\"\"Return Position instance of given node (or None if no node).\"\"\"\n return self.Position(self, node) if node is not None else None\n\n #-------------------------binary tree constructor-------------------------\n def __init__(self):\n \"\"\"Create an initially empty binary tree.\"\"\"\n self._size = 0\n self._root = None\n\n #----------------------------public accessors-----------------------------\n def __len__(self):\n \"\"\"Return the total number of elements in the tree.\"\"\"\n return self._size\n\n def root(self):\n \"\"\"Return the root Position of the tree (or None if tree is empty).\"\"\"\n return self._make_position(self._root)\n\n def parent(self, p):\n \"\"\"Return the Position of p's parent (or None if p is a root).\"\"\"\n node = self._validate(p)\n return self._make_position(node._parent)\n\n def left(self, p):\n \"\"\"Return the Position of p's left child (or None if no right child).\"\"\"\n node = self._validate(p)\n return self._make_position(node._left)\n\n def right(self, p):\n \"\"\"Return the Position of p's right child (or None if no right child).\"\"\"\n node = self._validate(p)\n return self._make_position(node._right)\n\n def num_children(self, p):\n \"\"\"Returm the number of of children of Position p.\"\"\"\n count = 0\n node = self._validate(p)\n if node._left is not None:\n count += 1\n if node._right is not None:\n count += 1\n return count\n\n #------------------------------update methods-----------------------------\n def _add_root(self, e):\n \"\"\"\n Place element e at the root of an empty tree and return new Position.\n Raise ValueError if tree is not empty.\n \"\"\"\n if self._root is not None:\n raise ValueError(\"Root exists\")\n self._size = 1\n self._root = self._Node(e)\n return self._make_position(self._root)\n\n def _add_left(self, p, e):\n \"\"\"\n Create a new left child for Position p, storing element e.\n Return the Position of new node.\n Raise ValueError if Position p is invalid or p already has a left child.\n \"\"\"\n node = self._validate(p)\n if node._left is not None:\n raise ValueError(\"Left child exists\")\n self._size += 1\n node._left = self._Node(e, node)\n return self._make_position(node._left)\n \n\n def _add_right(self, p, e):\n \"\"\"\n Create a new right child for Position p, storing element e.\n Return the Position of new node.\n Raise ValueError if Position p is invalid or p already has a right child.\n \"\"\"\n node = self._validate(p)\n if node._right is not None:\n raise ValueError(\"Right child exists\")\n self._size += 1\n node._right = self._Node(e, node)\n return self._make_position(node._right)\n\n def _replace(self, p, e):\n \"\"\"Replace the element at position p with e and return old element.\"\"\"\n node = self._validate(p)\n old = node._element\n node._element = e\n return old\n\n def _delete(self, p):\n \"\"\"\n Delete the node at Position p and replace it with its child if any.\n Return the element that had been stored at Position p.\n Raise ValueError if Position p is invalid or p has two children.\n \"\"\"\n node = self._validate(p)\n if self.num_children(p) == 2:\n raise ValueError(\"p has two children\")\n child = node._left if node._left else node._right\n if child is not None:\n child._parent = node._parent # child's grandparent becomes parent\n if node is self._root:\n self._root = child # child becomes root\n else:\n parent = node._parent\n if node is parent._left:\n parent._left = child\n else:\n parent._right = child\n self._size -= 1\n node._parent = node # convention for deprecated node\n return node._element\n\n def _attach(self, p, t1, t2):\n \"\"\"Attach trees t1 and t2 as left and right subtrees of external p.\"\"\"\n node = self._validate(p)\n if not self.is_leaf(p):\n raise ValueError(\"position must be leaf\")\n if not type(self) is type(t1) is type(t2):\n raise TypeError(\"Tree types must match\")\n self._size += len(t1) + len(t2)\n if not t1.is_empty():\n t1._root._parent = node\n node._left = t1._root\n t1._root = None\n t1._size = 0\n if not t2.is_empty():\n t2._root._parent = node\n node._right = t2._root\n t2._root = None\n t2._size = 0\n\n\n\nclass TreeMap(LinkedBinaryTree, MapBase):\n \"\"\"Sorted map implementation using a binary search tree.\"\"\"\n\n class Position(LinkedBinaryTree.Position):\n def key(self):\n \"\"\"Return key of map's key-value pair.\"\"\"\n return self.element()._key\n\n def value(self):\n \"\"\"Return value of map's key-value pair.\"\"\"\n return self.element()._value\n\n #---------------------------nonpublic utilities---------------------------\n def _subtree_search(self, p, k):\n \"\"\"Return Position of p's subtree having key k, or last node searched.\"\"\"\n if k == p.key():\n return p\n elif k < p.key():\n if self.left(p) is not None:\n return self._subtree_search(self.left(p), k)\n else:\n if self.right(p) is not None:\n return self._subtree_search(self.right(p), k)\n return p # unsuccessful search\n\n def _subtree_first_position(self, p):\n \"\"\"Return Position of first item in subtree rooted at p.\"\"\"\n walk = p\n while self.left(walk) is not None:\n walk = self.left(walk)\n return walk\n\n def _subtree_last_position(self, p):\n \"\"\"Return Position of last item in subtree rooted at p.\"\"\"\n walk = p\n while self.right(walk) is not None:\n walk = self.right(walk)\n return walk\n\n def _rebalance_insert(self, p):\n pass\n\n def _rebalance_delete(self, p):\n pass\n\n def _rebalance_access(self, p):\n pass\n\n #---------nonpublic utilities for balanced search tree subclasses---------\n def _relink(self, parent, child, make_left_child):\n \"\"\"Relink parent node with child node (child is allowed to be None).\"\"\"\n if make_left_child:\n parent._left = child # make it a left child\n else:\n parent._right = child # make it a right child\n if child is not None:\n child._parent = parent # make child point to parent\n\n def _rotate(self, p):\n \"\"\"Rotate Position p above its parent.\"\"\"\n x = p._node\n y = x._parent\n z = y._parent\n if z is None:\n self._root = x\n x._parent = None\n else:\n self._relink(z, x, y == z._left) # x becomes a direct child of z\n # now rotate x and y, including transfer of middle subtree\n if x == y._left:\n self._relink(y, x._right, True) # x._right becomes left child of y\n self._relink(x, y, False) # y becomes right child of x\n else:\n self._relink(y, x._left, False) # x._left becomes right child of y\n self._relink(x, y, True) # y becomes left child of x\n\n def _restructure(self, x):\n \"\"\"Perform trinode restructure of Position x with parent/grandparent.\"\"\"\n y = self.parent(x)\n z = self.parent(y)\n if (x == self.right(y)) == (y == self.right(z)): # matching alignments\n self._rotate(y) # single rotation of y\n return y # y is new subtree root\n else: # opposite alignments\n self._rotate(x)\n self._rotate(x)\n return x # x is new subtree root\n\n #---------------------------navigational methods--------------------------\n def first(self):\n \"\"\"Return the first Position in the tree (or None if empty).\"\"\"\n return self._subtree_first_position(self.root()) if len(self) > 0 else None\n\n def last(self):\n \"\"\"Return the last Position in the tree (or None if empty).\"\"\"\n return self._subtree_last_position(self.root()) if len(self) > 0 else None\n\n def before(self, p):\n \"\"\"Return the Position just before p in the natural order.\"\"\"\n self._validate(p)\n if self.left(p):\n return self._subtree_last_position(self.left(p))\n else:\n walk = p\n ancestor = self.parent(walk)\n while ancestor is not None and self.left(ancestor) == walk:\n walk = ancestor\n ancestor = self.parent(walk)\n return ancestor\n\n def after(self, p):\n \"\"\"Return the Position just after p in the natural order.\"\"\"\n self._validate(p)\n if self.right(p):\n return self._subtree_first_position(self.right(p))\n else:\n walk = p\n ancestor = self.parent(walk)\n while ancestor is not None and self.right(ancestor) == walk:\n walk = ancestor\n ancestor = self.parent(walk)\n return ancestor\n\n def find_position(self, k):\n \"\"\"Return position with key k, or else neighbor (or None if empty).\"\"\"\n if self.is_empty():\n return None\n else:\n p = self._subtree_search(self.root(), k)\n self._rebalance_access(p)\n return p\n\n def find_min(self):\n \"\"\"Return (key, value) pair with minimum key (or None if empty).\"\"\"\n if self.is_empty():\n return None\n else:\n p = self.first()\n return (p.key, p.value())\n\n def find_max(self):\n \"\"\"Return (key, value) pair with maximum key (or None if empty).\"\"\"\n if self.is_empty():\n return None\n else:\n p = self.last()\n return (p.key(), p.value())\n\n def find_ge(self, k):\n \"\"\"\n Return (key, value) pair with least key greater than or equal to k.\n Return None if there does not exist such a key.\n \"\"\"\n if self.is_empty():\n return None\n else:\n p = self.find_position(k)\n if p.key() < k:\n p = self.after(p)\n return (p.key(), p.value()) if p is not None else None\n\n def find_le(self, k):\n \"\"\"\n Return (key, value) pair with least key lesser than or equal to k.\n Return None if there does not exist such a key.\n \"\"\"\n if self.is_empty():\n return None\n else:\n p = self.find_position(k)\n if p.key() > k:\n p = self.before(p)\n return (p.key(), p.value()) if p is not None else None\n \n #--------map operations for accessing, inserting and deleting items-------\n def __getitem__(self, k):\n \"\"\"Return value associated with key k (raise KeyError if not found).\"\"\"\n if self.is_empty():\n raise KeyError(\"Key Error: \" + repr(k))\n else:\n p = self._subtree_search(self.root(), k)\n self._rebalance_access(p)\n if k != p.key():\n raise KeyError(\"Key Error: \" + repr(k))\n return p.value()\n\n def __setitem__(self, k, v):\n \"\"\"Assign value v to key k, overwriting existing value if present.\"\"\"\n if self.is_empty():\n leaf = self._add_root(self._Item(k, v))\n else:\n p = self._subtree_search(self.root(), k)\n if k == p.key():\n p.element()._value = v # replace existing item's value\n return\n else:\n item = self._Item(k, v)\n if p.key() < k:\n leaf = self._add_right(p, item)\n else:\n leaf = self._add_left(p, item)\n self._rebalance_insert(leaf)\n\n def delete(self, p):\n \"\"\"Remove the item at the given Position.\"\"\"\n self._validate(p)\n if self.left(p) and self.right(p):\n replacement = self._subtree_last_position(self.left(p))\n self._replace(p, replacement.element())\n p = replacement\n # now p has at most one child\n parent = self.parent(p)\n self._delete(p)\n self._rebalance_delete(parent)\n\n def __delitem__(self, k):\n \"\"\"Remove item associated with key k (raise KeyError if not found).\"\"\"\n if not self.is_empty():\n p = self._subtree_search(self.root(), k)\n if k == p.key():\n self.delete(p)\n return\n raise KeyError(\"Key Error: \" + repr(k))\n\n def __iter__(self):\n \"\"\"Generate an iteration of all keys in the map in order.\"\"\"\n p = self.first()\n while p is not None:\n yield p.key\n p = self.after(p)\n\n\n\nclass AVLTreeMap(TreeMap):\n \"\"\"Sorted map implementation using an AVL tree.\"\"\"\n class _Node(TreeMap._Node):\n \"\"\"Node class for AVL maintains height value for balancing.\"\"\"\n __slots__ = \"_height\"\n\n def __init__(self, element, parent = None, left = None, right = None):\n super().__init__(element, parent, left, right)\n self._height = 0\n\n def left_height(self):\n return self._left._height if self._left is not None else 0\n\n def right_height(self):\n return self._right._height if self._right is not None else 0\n\n def _recompute_height(self, p):\n p._node._height = 1 + max(p._node.left_height(), p._node.right_height())\n\n def _isbalanced(self, p):\n return abs(p._node.left_height() - p._node.right_height()) <= 1\n\n def _tall_child(self, p, favorleft = False):\n if p._node.left_height() + (1 if favorleft else 0) > p._node.right_height():\n return self.left(p)\n else:\n return self.right(p)\n\n def _tall_grandchild(self, p):\n child = self._tall_child(p)\n # if child is on left, favor left grandchild; else favor right\n alignment = (child == self.left(p))\n return self._tall_child(child, alignment)\n\n def _rebalance(self, p):\n while p is not None:\n old_height = p._node._height\n if not self._isbalanced(p):\n p = self._restructure(self._tall_grandchild(p))\n self._recompute_height(self.left(p))\n self._recompute_height(self.right(p))\n self._recompute_height(p) # adjust for recent changes\n if p._node._height == old_height: # has height changed?\n p = None # no further changes needed\n else:\n p = self.parent(p) # repeat with parent\n\n def _rebalance_insert(self, p):\n self._rebalance(p)\n\n def _rebalance_delete(self, p):\n self._rebalance(p)\n\n\n\n\n\ndef main():\n avl_tree = AVLTreeMap()\n reader = (line for line in stdin)\n num_commands = int(next(reader))\n for num in seq:\n if num >= 0:\n avl_tree[num] = None\n else:\n del avl_tree[-num]\n print(avl_tree.height() + 1)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"alg_06_03.py","file_name":"alg_06_03.py","file_ext":"py","file_size_in_byte":24164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"126103906","text":"\nfrom __future__ import absolute_import\n\nfrom myhdl import enum, Signal, intbv, always_seq\n\nfrom rhea.system.memmap import MemoryMapped\nfrom rhea.system.memmap import Barebone\n\n\ndef controller_basic(generic, memmap):\n \"\"\"\n\n Ports:\n :param generic: barebone interface\n :param memmap: any memory-map interface\n :return:\n\n Parameters:\n\n This module contains a basic\n\n \"\"\"\n\n assert isinstance(generic, Barebone)\n assert isinstance(memmap, MemoryMapped)\n\n states = enum('idle', 'wait', 'write', 'writeack', 'read',\n 'readdone', 'done', 'end')\n state = Signal(states.idle)\n\n timeout_max = 33\n tocnt = Signal(intbv(0, min=0, max=timeout_max))\n\n # map the generic bus to the bus in use\n conv_inst = memmap.map_from_generic(generic)\n\n @always_seq(memmap.clock.posedge, reset=memmap.reset)\n def beh_sm():\n\n # ~~~[Idle]~~~\n if state == states.idle:\n if not generic.done:\n state.next = states.wait\n elif generic.write:\n state.next = states.write\n elif generic.read:\n state.next = states.read\n\n # ~~~[Wait]~~~\n elif state == states.wait:\n if generic.done:\n tocnt.next = 0\n if generic.write:\n state.next = states.done\n elif generic.read:\n state.next = states.readdone\n\n # ~~~[Write]~~~\n elif state == states.write:\n state.next = states.done\n tocnt.next = 0\n\n # ~~~[Read]~~~\n elif state == states.read:\n state.next = states.readdone\n\n # ~~~~[ReadDone]~~~\n elif state == states.readdone:\n if generic.done:\n state.next = states.done\n\n # ~~~[Done]~~~\n elif state == states.done:\n # wait for transaction signals to be release\n if not (generic.write or generic.read):\n state.next = states.idle\n\n # ~~~[]~~~\n else:\n assert False, \"Invalid state %s\" % (state,)\n\n return conv_inst, beh_sm\n","sub_path":"rhea/cores/memmap/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"200002785","text":"import threading\n\nimport numpy as np\nfrom Environment.player import Player\nfrom Environment.deck import Deck\nfrom Environment.card import Card\nfrom Environment.state import State #, AbstractState\n\n\nclass UnoEnvironment:\n def __init__(self, print_state=False):\n self.number_of_players = 2\n self.print_state = print_state\n self.deck = Deck()\n self.state_tracker = State()\n self.players = None\n self.played_cards = None\n self.top = None\n self.played_card = None\n self.current_player_index = None\n self.current_player = None\n self.previous_player_index = None\n self.turn = None\n self.done = None\n\n self.reward_info = [[None, None, None, None], [None, None, None, None]]\n # if self.print_state:\n # self.pretty_print_state()\n\n def reset(self, player_1: Player, player_2: Player):\n player_1.reset()\n player_2.reset()\n self.players = [player_1, player_2]\n self.deck.reset()\n self.players[0].draw_cards(self.deck.draw_cards(7))\n self.players[1].draw_cards(self.deck.draw_cards(7))\n self.played_card = None\n self.played_cards = self.reveal_top_card()\n self.top = self.played_cards[-1]\n self.current_player_index = 0\n self.current_player = self.players[0]\n self.previous_player_index = None\n self.turn = 0\n self.state_tracker = State()\n self.done = False\n if self.print_state:\n self.pretty_print_state()\n # TODO: use built in state function\n return self.get_state(0)\n #current_players_hand = self.current_player.cards\n # n_cards_other_players_hand = len(self.next_player().cards)\n #return self.state_tracker.encode_state(current_players_hand, n_cards_other_players_hand, self.played_cards,\n #self.top)\n\n def reveal_top_card(self):\n revealed_cards = self.deck.draw_cards(1)\n while revealed_cards[-1].kind != Card.Kind.NUMBER:\n revealed_cards += self.deck.draw_cards(1)\n\n return revealed_cards\n\n def check_win_or_continue(self, skip):\n #print(\"Should Skip\", skip)\n self.turn += 1\n if len(self.players[0].cards) == 0:\n self.done = True\n if self.print_state:\n self.pretty_print_state()\n print(self.players[0].name + \" wins!\")\n elif len(self.players[1].cards) == 0:\n self.done = True\n if self.print_state:\n self.pretty_print_state()\n print(self.players[1].name + \" wins!\")\n else:\n self.next_turn(skip)\n \"\"\"if skip:\n self.previous_player_index = self.current_player_index\n if self.print_state:\n self.pretty_print_state()\n else:\n self.next_turn()\"\"\"\n\n def set_hand_info_before(self):\n if self.current_player_index == 0:\n # Moj hand ob začetku actiona - p1b\n self.reward_info[0][0] = self.players[0].get_hand_size()\n # Opponentov hand ob začetku actiona - p1ob\n self.reward_info[0][1] = self.players[1].get_hand_size()\n else:\n # Moj hand ob začetku actiona - p2b\n self.reward_info[1][0] = self.players[1].get_hand_size()\n # Opponentov hand ob začetku actiona - p2ob\n self.reward_info[1][1] = self.players[0].get_hand_size()\n\n def set_hand_info_after(self):\n # Po koncu opponentovega actiona sm js na vrsti spet al pa on, če se je zgodil skip\n # Loh sm tud js na vrsti takoj za sabo če skippam\n if self.current_player_index == 0:\n # Moj hand ob koncu opponentovega actiona - p2a\n self.reward_info[0][2] = self.players[0].get_hand_size()\n # Opponentov hand ob koncu opponentovega actiona - p2oa\n self.reward_info[0][3] = self.players[1].get_hand_size()\n else:\n # Moj hand ob koncu opponentovega actiona - p1a\n self.reward_info[1][2] = self.players[1].get_hand_size()\n # Opponentov hand ob koncu opponentovega actiona - p1oa\n self.reward_info[1][3] = self.players[0].get_hand_size()\n\n def step(self, action):\n\n self.set_hand_info_before() # Current player je ta k izvaja step\n self.take_action(action)\n self.set_hand_info_after() # Current player je nasledni, k je na vrsti\n\n #current_players_hand = self.players[self.current_player_index].cards\n #opponents_hand_len = len(self.players[self.next_player_index()].cards)\n #self.top = self.played_cards[-1]\n\n #print(\"Reward info:\", self.reward_info)\n return self.get_state(self.previous_player_index), self.done\n\n #return self.state_tracker.encode_state(current_players_hand, opponents_hand_len, self.played_cards,\n #self.top), self.done\n\n def step_with_opp_step(self, action):\n #if len(self.deck.cards) + len(self.players[0].cards) + len(self.players[1].cards) \\\n # + len(self.played_cards) != 108:\n # print(\"Fuck\", len(self.deck.cards) + len(self.players[0].cards) + len(self.players[1].cards)\n # + len(self.played_cards))\n self.set_hand_info_before() # Current player je ta k izvaja step\n self.take_action(action)\n self.set_hand_info_after() # Current player je nasledni, k je na vrsti\n # Opponent is part of the environment, so it has to make it's actions before returning the new state and rewards\n self.opponent_action()\n\n reward = self.calculate_built_in_reward(0)\n\n #agents_hand = self.players[0].cards\n #opponents_hand_len = len(self.players[1].cards)\n #self.top = self.played_cards[-1]\n #if len(self.deck.cards) + len(self.players[0].cards) + len(self.players[1].cards) \\\n # + len(self.played_cards) != 108:\n # print(\"Fuck\", len(self.deck.cards) + len(self.players[0].cards) + len(self.players[1].cards)\n # + len(self.played_cards))\n #state = self.state_tracker.encode_state(agents_hand, opponents_hand_len, self.played_cards, self.top)\n return self.get_state(0), reward, self.done\n\n def opponent_action(self):\n while self.current_player_index == 1 and not self.done:\n self.set_hand_info_before() # Current player je ta k izvaja step\n action = self.players[1].get_action(self.get_legal_actions(), self.get_state(1))\n self.take_action(action)\n self.set_hand_info_after() # Current player je nasledni, k je na vrsti\n\n def take_action(self, action):\n skip = False\n if action != 54:\n # Get appropriate card from players hand depending on provided action\n index = [card.action_number for card in self.current_player.cards].index(action)\n self.played_card = self.current_player.cards[index]\n else:\n self.played_card = None\n\n if not self.played_card:\n self.draw_cards(self.current_player, 1)\n drawn_card_action_number = self.current_player.cards[len(self.current_player.cards)-1].action_number\n if drawn_card_action_number in self.get_legal_actions():\n # If drawn card is legal to play, then do so\n if self.print_state:\n print(\"Automatically playing drawn card!\")\n self.take_action(drawn_card_action_number)\n return\n else:\n skip = self.play_card(index)\n \"\"\"if self.played_card.trait == Card.ActionTraits.SKIP or self.played_card.trait == Card.ActionTraits.REVERSE:\n skip = True\n elif self.played_card.trait == Card.ActionTraits.DRAW_2:\n self.draw_cards(self.next_player(), 2)\n skip = True\n elif self.played_card.trait == Card.WildTraits.WILD:\n self.played_card.color = Card.Color(np.random.randint(3))\n elif self.played_card.trait == Card.WildTraits.DRAW_4:\n self.draw_cards(self.next_player(), 4)\n self.played_card.color = Card.Color(np.random.randint(3))\n skip = True\n\n self.played_cards.append(self.current_player.play_card(index))\"\"\"\n self.check_win_or_continue(skip)\n\n def play_card(self, index):\n skip = False\n if self.played_card.trait == Card.ActionTraits.SKIP or self.played_card.trait == Card.ActionTraits.REVERSE:\n skip = True\n elif self.played_card.trait == Card.ActionTraits.DRAW_2:\n self.draw_cards(self.next_player(), 2)\n skip = True\n elif self.played_card.trait == Card.WildTraits.WILD:\n self.played_card.color = Card.Color(np.random.randint(3))\n elif self.played_card.trait == Card.WildTraits.DRAW_4:\n self.draw_cards(self.next_player(), 4)\n self.played_card.color = Card.Color(np.random.randint(3))\n skip = True\n\n self.played_cards.append(self.current_player.play_card(index))\n return skip\n\n '''def calculate_reward(self, hand_size_before, opponents_hand_size_before,\n hand_size_after, opponents_hand_size_after, player_index):\n if self.done:\n if self.players[player_index].get_hand_size() == 0:\n reward = 1\n else:\n reward = -1\n else:\n if self.current_player_index == self.previous_player_index:\n # Skipping is always positive\n return 1\n elif hand_size_before > hand_size_after < opponents_hand_size_after:\n # Decreasing hand size is positive, unless you're behind\n return 1\n return -1\n if self.current_player_index == self.previous_player_index \\\n or hand_size_after < hand_size_before \\\n or opponents_hand_size_after > opponents_hand_size_before:\n # Means there was a skip\n return 1\n else:\n return -1\n return reward'''\n\n def calculate_built_in_reward(self, player_index):\n if self.done:\n if self.players[player_index].get_hand_size() == 0:\n reward = 1\n else:\n reward = -1\n else:\n hand_size_before = self.reward_info[player_index][0]\n hand_size_after = self.reward_info[player_index][2]\n opponents_hand_size_after = self.reward_info[player_index][3]\n #if self.current_player_index == self.previous_player_index or \\\n if hand_size_before > hand_size_after < opponents_hand_size_after:\n # Skipping is always positive\n # Decreasing hand size is positive, unless you're behind\n return 1\n #elif hand_size_before > hand_size_after < opponents_hand_size_after:\n # Decreasing hand size is positive, unless you're behind\n #return 1\n return -1\n return reward\n\n '''def clip_value(self, value):\n if value > 0:\n value = 0\n elif value <= 0:\n value = -1\n return value'''\n\n def get_state(self, player_index):\n current_hand = self.players[player_index].cards\n opponents_hand_len = len(self.players[(player_index + 1) % self.number_of_players].cards)\n self.top = self.played_cards[-1]\n return self.state_tracker.encode_state(current_hand, opponents_hand_len, self.played_cards,\n self.top)\n\n \"\"\"def get_abstract_state(self):\n self.top = self.played_cards[-1]\n return AbstractState.encode_state(self.top, self.players[0].cards, self.get_legal_actions())\"\"\"\n\n def get_legal_actions(self):\n self.top = self.played_cards[-1]\n legal_actions = []\n draw_4_actions = []\n matches_top_color = False\n if self.top.kind == Card.Kind.WILD:\n for card in self.current_player.cards:\n if card.kind == Card.Kind.WILD:\n if card.trait == Card.WildTraits.DRAW_4:\n draw_4_actions = card.action_number\n else:\n legal_actions.append(card.action_number)\n if card.color == self.top.color:\n matches_top_color = True\n legal_actions.append(card.action_number)\n\n else:\n for card in self.current_player.cards:\n if card.kind == Card.Kind.WILD:\n if card.trait == Card.WildTraits.DRAW_4:\n draw_4_actions = card.action_number\n else:\n legal_actions.append(card.action_number)\n if card.color == self.top.color:\n matches_top_color = True\n legal_actions.append(card.action_number)\n elif card.trait == self.top.trait:\n legal_actions.append(card.action_number)\n\n # Only if there are no other card with same color as the top actions except draw, draw_4 is legal\n if not matches_top_color and draw_4_actions:\n legal_actions.append(draw_4_actions)\n legal_actions.append(54)\n return legal_actions\n\n def get_playable_cards_for_current_player(self):\n legal_actions = self.get_legal_actions()\n playable_cards = []\n for card in self.current_player.cards:\n if card.action_number in legal_actions and card not in playable_cards:\n playable_cards.append(card)\n return playable_cards\n\n def next_player(self):\n return self.players[self.next_player_index()]\n\n def next_player_index(self):\n return (self.current_player_index + 1) % self.number_of_players\n\n def draw_cards(self, player, number_of_cards_to_draw):\n # Handle empty deck\n cards_to_draw = []\n for draw in range(number_of_cards_to_draw):\n if self.deck.get_number_of_cards_in_deck() == 0:\n self.shuffle_played_cards_into_deck()\n cards_to_draw += self.deck.draw_cards(1)\n player.draw_cards(cards_to_draw)\n\n def shuffle_played_cards_into_deck(self):\n if len(self.played_cards) == 1:\n # Trying to draw from empty deck and only one card left on the played pile\n return\n temp = [self.played_cards.pop(-1)]\n for card in self.played_cards:\n # reset randomly assigned color\n if card.trait == Card.WildTraits.WILD or card.trait == Card.WildTraits.DRAW_4:\n card.color = Card.Color.BLACK\n\n self.deck.set_cards(self.played_cards)\n self.played_cards = temp\n self.deck.shuffle_deck()\n\n def get_hand(self):\n return self.current_player.cards\n\n def get_other_hand_size(self):\n return len(self.players[self.next_player_index()].cards)\n\n def next_turn(self, skip):\n if skip:\n self.previous_player_index = self.current_player_index\n else:\n self.current_player = self.next_player() # cycles 0 and 1\n self.previous_player_index = self.current_player_index\n self.current_player_index = self.next_player_index()\n\n if self.print_state:\n self.pretty_print_state()\n\n def pretty_print_state(self):\n print(\"-------------------------------------------------------------------------------------------------------\")\n print(\"Turn \" + str(self.turn))\n Card.pretty_print_cards(self.played_cards[len(self.played_cards) - 1:], False)\n\n for i, player in enumerate(self.players):\n\n if i == self.current_player_index:\n print(\"ACTIVE-\", end='')\n print(player.name + \"'s hand:\")\n player.print_hand()\n print(\"-------------------------------------------------------------------------------------------------------\")\n","sub_path":"Environment/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":16118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"260635324","text":"from sklearn.metrics import roc_curve, roc_auc_score\nimport csv\nimport matplotlib.pyplot as plt\nfrom os.path import splitext\n\n\ndef plot_ROC(n_actives, n_decoys, title, fname, results,\n legend, show, glidefile):\n colors = ['b', 'g', 'b', 'g', 'r', 'c', 'm', 'y', 'k']\n\n results_file = results[0::3]\n results_type = results[1::3]\n results_name = results[2::3]\n\n ys = []\n scores = []\n data_types = []\n glide_y, glide_score, _ = GetYScoreFromResult(glidefile, 'dock', [], [])\n\n for i in range(len(results_file)):\n y, score, t = GetYScoreFromResult(results_file[i], results_type[i],\n glide_y, glide_score)\n ys.append(y)\n scores.append(score)\n data_types.append(t)\n\n plt.figure(figsize=(8, 8), dpi=150)\n SetupROCCurvePlot(plt, title)\n\n aucs = []\n ef10s = []\n ef1s = []\n for i in range(len(results_file)):\n auc, ef10, ef1 = AddROCCurve(plt, ys[i], scores[i], colors[i],\n results_name[i], n_actives, n_decoys, data_types[i])\n aucs.append(auc)\n ef10s.append(ef10)\n ef1s.append(ef1)\n\n SaveROCCurvePlot(plt, fname, show, legend, True)\n SaveAUCEF(fname, results, aucs, ef10s, ef1s)\n\n\ndef SaveAUCEF(fname, results, aucs, ef10s, ef1s):\n\n results_file = results[0::3]\n results_type = results[1::3]\n results_name = results[2::3]\n\n glide_auc = proposed_auc = 0\n with open(splitext(fname)[0] + \"_result.txt\", \"w\") as f_result:\n f_result.write(str(title) + \"\\n\")\n for i in range(len(results_file)):\n f_result.write(results_name[i] + \"_AUC, \" + str(aucs[i]) + \"\\n\")\n f_result.write(results_name[i] + \"_EF10, \" + str(ef10s[i]) + \"\\n\")\n f_result.write(results_name[i] + \"_EF1, \" + str(ef1s[i]) + \"\\n\")\n\n if \"Glide\" in results_name[i]:\n glide_auc = aucs[i]\n\n elif \"proposed\" in results_name[i]:\n proposed_auc = aucs[i]\n\n if proposed_auc == 0 or glide_auc == 0:\n pass\n elif proposed_auc - glide_auc > 0.001:\n f_result.write(\"proposed, win\\n\")\n elif proposed_auc - glide_auc < -0.001:\n f_result.write(\"proposed, lose\\n\")\n else:\n f_result.write(\"proposed, draw\\n\")\n\n\ndef GetYScoreFromResult(filename, datatype, glide_y, glide_score):\n y = []\n score = []\n\n try:\n data = csv.reader(open(filename, 'rb'), delimiter=',', quotechar='#')\n except IOError:\n print(\"postprocess was cancelled. auc is the same as glide SP.\")\n return glide_y, glide_score, \"dock\"\n\n if 'dock' in datatype:\n # print(filename)\n for line in data:\n if \"ZINC\" in line[0] or \"TEMP\" in line[0]:\n y.append(0)\n else:\n y.append(1)\n\n score.append(float(line[1]))\n\n else:\n # datatype=='stat':\n for line in data:\n y.append(int(line[3]))\n score.append(float(line[2]))\n\n return y, score, datatype\n\n\ndef GetRates(y, scores, n_actives, n_decoys):\n\n tpr = [0.0] # true positive rate\n fpr = [0.0] # false positive rate\n\n foundactives = 0.0\n founddecoys = 0.0\n for idx, score in enumerate(scores):\n if y[idx] == 1:\n foundactives += 1.0\n else:\n founddecoys += 1.0\n\n tpr.append(foundactives / float(n_actives))\n fpr.append(founddecoys / float(n_decoys))\n\n tpr.append(1.0)\n fpr.append(1.0) # add [1.0, 1.0]\n\n return tpr, fpr\n\n\ndef SetupROCCurvePlot(plt, title):\n\n plt.xlabel(\"False Positive rate\", fontsize=14)\n plt.ylabel(\"True Positive rate\", fontsize=14)\n plt.title(\"ROC Curve (\" + title + \")\", fontsize=14)\n\n\ndef AddROCCurve(plt, actives, scores, color, label, n_actives, n_decoys, type):\n tpr, fpr = GetRates(actives, scores, n_actives, n_decoys)\n # print(actives,label)\n if \"dock\" in type:\n scores = [-x for x in scores] # reverse order\n # print(tpr)\n\n auc_tmp = roc_auc_score(actives, scores)\n # +((1-fpr[-1])*tpr[-1]) #adjust final position\n auc_tmp = (auc_tmp * tpr[-1])\n auc = round(auc_tmp, 3)\n\n ef_10 = tpr[len(tpr) // 10] * 10\n ef_1 = tpr[len(tpr) // 100] * 100\n label = label + \", auc=\" + str(auc)\n\n if \"Glide\" in label:\n plt.plot(fpr, tpr, linestyle='dashed', color=color,\n linewidth=2, label=label)\n else:\n plt.plot(fpr, tpr, color=color, linewidth=2, label=label)\n return auc, ef_10, ef_1\n\n\ndef SaveROCCurvePlot(plt, fname, show, legend, randomline=True):\n\n if randomline:\n x = [0.0, 1.0]\n plt.plot(x, x, linestyle='dashed', color='red',\n linewidth=2, label='random')\n\n plt.xlim(0.0, 1.0)\n plt.ylim(0.0, 1.0)\n if legend:\n plt.legend(fontsize=10, loc='best')\n\n plt.tight_layout()\n plt.savefig(fname)\n if show:\n plt.show()\n\n\nif __name__ == '__main__':\n import sys\n x = sys.argv\n if len(x) <= 5 and len(x) % 3 != 2:\n print(\"usage: n_actives, n_decoys, graph_title, graph_filename,\"\n \"legend, show, glidefile, results(file, type, name)...\")\n\n n_actives = int(x[1])\n n_decoys = int(x[2])\n title = x[3]\n fname = x[4]\n legend = x[5]\n if legend in [\"False\", \"false\", \"0\", \"No\", \"no\"]:\n legend = False\n else:\n legend = True\n\n show = x[6]\n if show in [\"False\", \"false\", \"0\", \"No\", \"no\"]:\n show = False\n else:\n show = True\n\n glidefile = x[7]\n results = x[8:]\n\n plot_ROC(n_actives, n_decoys, title, fname,\n results, legend, show, glidefile)\n","sub_path":"score_statistics_rivals.py","file_name":"score_statistics_rivals.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"573018337","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'MFC'\n__time__ = '2019-07-16 17:46'\n\nimport os\nimport requests\nimport json\nfrom tkinter import *\n\n\nclass Get_url_short():\n def __init__(self):\n self.source = 2540340328 # 2540340328, 2849184197, 202088835, 211160679\n self.url = 'https://api.t.sina.com.cn/short_url/shorten.json?'\n\n def get_short(self):\n try:\n url_long = self.tk_url_long.get()\n url = self.url + 'source=' + str(self.source) + '&url_long=' + str(url_long)\n html = requests.get(url)\n html = html.text\n html = json.loads(html)\n self.url_short = html[0]['url_short']\n Label(text='Short URL:').grid(row=1, column=0)\n Label(text=self.url_short).grid(row=1, column=1)\n Button(self.short, text=\"Copy\", width=10, command=self.short_copy).grid(row=1, column=2, sticky=W, padx=10,\n pady=5)\n except:\n Label(text='请输入带http或https的长链接').grid(row=2, column=1)\n\n def short_copy(self):\n try:\n self.short.clipboard_clear() # 清除剪贴板内容\n self.short.clipboard_append(self.url_short) # 向剪贴板追加内容\n Label(text='URL copy succeeded', font=', 10').grid(row=2, column=1)\n except:\n Label(text='URL copy failed', font=', 10').grid(row=2, column=1)\n\n def short_begin(self):\n self.short = Tk()\n self.short.title('Short URL')\n Label(text='Long URL:').grid(row=0, column=0)\n self.tk_url_long = Entry(self.short)\n self.tk_url_long.grid(row=0, column=1)\n Button(self.short, text=\"转化\", width=10, command=self.get_short).grid(row=0, column=2, sticky=W, padx=10, pady=5)\n mainloop()\n\n\n# from other, no use in the script now\n\ndef sina_url(api, source, url_long):\n url = api + 'source=' + str(source) + '&url_long=' + str(url_long)\n http = requests.get(url)\n jsonstr = json.loads(http.text)\n url_short = jsonstr[0]['url_short']\n copy(url_short)\n\n\ndef copy(url_short):\n os.system('echo ' + url_short + '| clip')\n\nif __name__ == '__main__':\n short = Get_url_short()\n short.short_begin()","sub_path":"otherdemo/short_url.py","file_name":"short_url.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"96315257","text":"# Load pickled data\nimport pickle\nimport csv\n\n# TODO: Fill this in based on where you saved the training and testing data\ntext_labels = []\nwith open('signnames.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n n = 0;\n for row in reader:\n if n > 0: #skip first row\n text_labels += [row[1]]\n n += 1\n\ntraining_file = 'traffic-signs-data/train.p'\nvalidation_file='traffic-signs-data/valid.p'\ntesting_file = 'traffic-signs-data/test.p'\n\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n test = pickle.load(f)\n \nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']\n\n\n### Replace each question mark with the appropriate value. \n### Use python, pandas or numpy methods rather than hard coding the results\n\nimport numpy as np\n\n# TODO: Number of training examples\nn_train = len(X_train)\n\n# TODO: Number of validation examples\nn_valid = len(X_valid)\n\n# TODO: Number of testing examples.\nn_test = len(X_test)\n\n# TODO: What's the shape of an traffic sign image?\nimage_shape = np.shape(X_train[0])\n\n# TODO: How many unique classes/labels there are in the dataset.\nn_classes = len(np.unique(y_train))\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Number of validation examples =\", n_valid)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)\n\n### Data exploration visualization code goes here.\n### Feel free to use as many code cells as needed.\nimport matplotlib.pyplot as plt\n#%matplotlib inline\nif 0:\n # Visualizations will be shown in the notebook.\n\n labels_valid, sizes_valid = np.unique(y_valid, return_counts=True)\n labels_train, sizes_train = np.unique(y_train, return_counts=True)\n labels_test, sizes_test = np.unique(y_test, return_counts=True)\n ind = labels_valid\n p1 = plt.barh(ind, sizes_train, .35, color='blue')\n p2 = plt.barh(ind, sizes_valid, .35, left = sizes_train, color='red')\n p3 = plt.barh(ind, sizes_test, .35, left = sizes_valid + sizes_train, color='green')\n plt.yticks(ind, text_labels)\n plt.legend((p1[0], p2[0], p3[0]), ('Train', 'Validate', 'Test'))\n plt.title('Distribution of Traffic Signs')\n plt.show()\n\n import math\n plt.figure(figsize=(15, 30))\n n_unique, unique_index = np.unique(y_train, return_index=True)\n for i in range(0,len(n_unique)):\n plt.subplot(math.ceil(len(n_unique)/4), 4, i+1)\n plt.imshow(X_train[unique_index[i]])\n plt.title(text_labels[y_train[unique_index[i]]])\n plt.axis('off')\n plt.suptitle('Traffic Sign Lables')\n plt.show()\n\n### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include \n### converting to grayscale, etc.\n### Feel free to use as many code cells as needed.\n\n\n# Add synthesized data\nfrom skimage.transform import warp, SimilarityTransform\nfrom skimage import img_as_ubyte\nfrom skimage.exposure import adjust_gamma\nimport math\nimport numpy as np\nfrom numpy import random\nimport warnings\n\ndef jitter(img):\n ''' Jitter the image as described in the paper referenced here:\n http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf'''\n \n # knobs\n max_rot = 15 * math.pi/180.0\n max_scale = 0.1\n max_delta = 2\n max_gamma = 0.7\n\n # randomize\n rot = random.uniform(-1,1) * max_rot\n scl = random.uniform(-1,1) * max_scale + 1.0\n xd = random.randint(-max_delta, max_delta)\n yd = random.randint(-max_delta, max_delta)\n gamma = random.uniform(-1,1) * max_gamma + 1.0\n\n # scale, roation, and translation\n tform = SimilarityTransform(rotation=rot, scale=scl, translation=(xd, yd))\n offx, offy = np.array(img.shape[:2]) / 2\n recenter = SimilarityTransform(translation=(offx, offy))\n recenter_inv = SimilarityTransform(translation=(-offx, -offy))\n img = warp(img, (recenter_inv + (tform + recenter)).inverse, mode='edge')\n \n # gamma\n img = adjust_gamma(img, gamma)\n \n # convert back to RGB [0-255] and ignore the silly precision warning\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return img_as_ubyte(img)\n\ndef jitter_data(data):\n result = np.empty_like(data)\n for i in range(data.shape[0]):\n result[i] = jitter(data[i])\n return result\n\nprint(\"Adding synthetic data.\")\nimport os.path\nif (os.path.isfile('traffic-signs-data/synthetic.p') == False):\n print(\"Generating Synthetic Data.\", end='', flush=True)\n for i in range(0,5,1):\n if (i == 0):\n X_synth = jitter_data(X_train)\n y_synth = y_train\n else: \n X_synth = np.concatenate((X_synth, jitter_data(X_train)))\n y_synth = np.concatenate((y_synth, y_train))\n print(\".\", end='', flush=True)\n n_synth = len(X_synth)\n print(\"done. \", n_train + n_synth, \" samples.\");\n pickle.dump((X_synth, y_synth), open('traffic-signs-data/synthetic.p', \"wb\"))\nelse:\n print(\"Loading Synthetic data.\")\n (X_synth, y_synth) = pickle.load(open('traffic-signs-data/synthetic.p', \"rb\"))\nprint(np.shape(X_synth[0]))\n\n# Display an example\ni = random.randint(0,len(X_train))\nplt.subplot(1,2,1)\nplt.title(\"Original\")\nplt.imshow(X_train[i])\nplt.subplot(1,2,2)\nplt.title(\"Synthesized\")\nplt.imshow(X_synth[i])\nplt.show()\n\nX_train = np.concatenate((X_train, X_synth))\ny_train = np.concatenate((y_train, y_synth))\nn_train = len(X_train)\nprint(\"Total training samples = \", n_train);\n\n# Shuffle training set\nprint(\"Shuffle training set.\")\nfrom sklearn.utils import shuffle\nX_train, y_train = shuffle(X_train, y_train)\n\n# Quick Normalize\ndef normalize(data):\n return data/255 - 0.5\n\nimport cv2\ndef preprocess_data(data):\n i, x, y, d = np.shape(data)\n result = []\n cnt = 0\n for n in data:\n img = cv2.cvtColor(n, cv2.COLOR_RGB2GRAY)\n img = cv2.equalizeHist(img)\n result.append(img)\n result = np.reshape(np.array(result), (i,x,y,1))\n return normalize(result)\n\nif 0:\n print(\"Normalizing the input\")\n X_train = normalize(X_train) \n X_test = normalize(X_test) \n X_valid = normalize(X_valid)\n n_depth = 3\nif 1:\n print(\"Preprocessing images.\")\n X_train = preprocess_data(X_train) \n X_test = preprocess_data(X_test) \n X_valid = preprocess_data(X_valid)\n n_depth = 1\n\n#import sys\n#sys.exit(0)\n\n### Define your architecture here.\n### Feel free to use as many code cells as needed.\nimport tensorflow as tf\n\n#X_train = tf.image.convert_image_dtype(X_train, tf.float32)\n#X_train = tf.image.rgb_to_hsv(X_train)\n\nfrom tensorflow.contrib.layers import flatten\n\nconv_1 = None\nconv_2 = None\nconv_3 = None\n\ndef LeNet(x, depth, keep_prob=1.0):\n global conv_1, conv_2, conv_3\n # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer\n mu = 0\n sigma = 0.1\n \n # TODO: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.\n c1_w = tf.Variable(tf.truncated_normal(shape=(5,5,depth,32), mean = mu, stddev = sigma))\n c1_b = tf.Variable(tf.zeros(32))\n conv_1 = tf.nn.conv2d(x, c1_w, strides=[1,1,1,1], padding='VALID')\n conv_1 = tf.nn.bias_add(conv_1, c1_b)\n \n # TODO: Activation.\n conv_1 = tf.nn.relu(conv_1)\n\n # TODO: Pooling. Input = 28x28x6. Output = 14x14x6.\n pool_1 = tf.nn.max_pool(conv_1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')\n\n # TODO: Layer 2: Convolutional. Output = 10x10x16.\n c2_w = tf.Variable(tf.truncated_normal(shape=(5,5,32,64), mean = mu, stddev = sigma))\n c2_b = tf.Variable(tf.zeros(64))\n conv_2 = tf.nn.conv2d(pool_1, c2_w, strides=[1,1,1,1], padding='VALID')\n conv_2 = tf.nn.bias_add(conv_2, c2_b)\n \n # TODO: Activation.\n conv_2 = tf.nn.relu(conv_2)\n \n # Layer 3: Convolutional. Output = 10x10x16.\n c3_w = tf.Variable(tf.truncated_normal(shape=(5,5,64,128), mean = mu, stddev = sigma))\n c3_b = tf.Variable(tf.zeros(128))\n conv_3 = tf.nn.conv2d(conv_2, c3_w, strides=[1,1,1,1], padding='VALID')\n conv_3 = tf.nn.bias_add(conv_3, c3_b)\n # Activation.\n conv_3 = tf.nn.relu(conv_3)\n\n # TODO: Pooling. Input = 10x10x16. Output = 5x5x16.\n pool_2 = tf.nn.max_pool(conv_3, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')\n \n # TODO: Flatten. Input = 5x5x16. Output = 400.\n pool_2 = tf.contrib.layers.flatten(pool_2)\n\n \n # TODO: Layer 4: Fully Connected. Input = 400. Output = 120.\n fc1_w = tf.Variable(tf.truncated_normal(shape=(1152,120), mean = mu, stddev = sigma))\n fc1_b = tf.Variable(tf.zeros(120))\n #fc_1 = tf.add(tf.matmul(pool_2, fc1_w), fc1_b)\n fc_1 = tf.matmul(pool_2, fc1_w) + fc1_b\n \n # TODO: Activation.\n fc_1 = tf.nn.relu(fc_1)\n\n # Dropout\n fc_1 = tf.nn.dropout(fc_1, keep_prob)\n\n # TODO: Layer 5: Fully Connected. Input = 120. Output = 84.\n fc2_w = tf.Variable(tf.truncated_normal(shape=(120,84), mean = mu, stddev = sigma))\n fc2_b = tf.Variable(tf.zeros(84))\n fc_2 = tf.add(tf.matmul(fc_1, fc2_w), fc2_b)\n \n # TODO: Activation.\n fc_2 = tf.nn.relu(fc_2)\n\n # Dropout\n fc_2 = tf.nn.dropout(fc_2, keep_prob)\n\n # TODO: Layer 6: Fully Connected. Input = 84. Output = 43.\n fc3_w = tf.Variable(tf.truncated_normal(shape=(84,n_classes), mean = mu, stddev = sigma))\n fc3_b = tf.Variable(tf.zeros(n_classes))\n logits = tf.add(tf.matmul(fc_2, fc3_w), fc3_b)\n \n return logits\n\n### Train your model here.\n### Calculate and report the accuracy on the training and validation set.\n### Once a final model architecture is selected, \n### the accuracy on the test set should be calculated and reported as well.\n### Feel free to use as many code cells as needed.\n\nx = tf.placeholder(tf.float32, (None, 32, 32, n_depth))\ny = tf.placeholder(tf.int32, (None))\nkeep_prob = tf.placeholder(tf.float32)\nlearning_rate = tf.placeholder(tf.float32)\none_hot_y = tf.one_hot(y, n_classes)\nk_pred = tf.placeholder(tf.int32)\n\n#Training Pipeline\nEPOCHS = 20\nBATCH_SIZE = 128\nrate = 0.001\ndecay = 1.0\ndrop = 0.5\n\nlogits = LeNet(x, n_depth)\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = rate)\n#optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate)\n\n#Model Evaluation\ntraining_operation = optimizer.minimize(loss_operation)\npredict_operation = tf.argmax(logits, 1)\nsoftmax_operation = tf.nn.softmax(logits)\ntopk_operation = tf.nn.top_k(softmax_operation, k_pred)\ncorrect_prediction = tf.equal(predict_operation, tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nsaver = tf.train.Saver()\n\ndef evaluate(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0\n total_loss = 0\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n loss, accuracy = sess.run([loss_operation, accuracy_operation], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})\n total_accuracy += (accuracy * len(batch_x))\n total_loss += (loss * len(batch_x))\n return total_loss / num_examples, total_accuracy / num_examples\n\ntrain_loss = []\ntrain_acc = []\nvalid_loss = []\nvalid_acc = []\n\n#Train Model\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n num_examples = len(X_train)\n \n print(\"Training...\")\n print()\n for i in range(EPOCHS):\n X_train, y_train = shuffle(X_train, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train[offset:end], y_train[offset:end]\n sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, learning_rate: rate, keep_prob: drop})\n\n training_loss, training_accuracy = evaluate(X_train, y_train)\n train_loss.append(training_loss)\n train_acc.append(training_accuracy*100.0)\n validation_loss, validation_accuracy = evaluate(X_valid, y_valid)\n valid_loss.append(validation_loss)\n valid_acc.append(validation_accuracy*100.0)\n print(\"EPOCH {} ...\".format(i+1)) \n #print(\"Training Accuracy = {:.3f}\".format(training_accuracy))\n #print(\"Training Loss = {:.3f}\".format(training_loss)) \n print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n #print(\"Validation Loss = {:.3f}\".format(validation_loss))\n #print(\"Learning Rate = {:.6f}\".format(rate))\n #print()\n rate = rate * decay\n\n saver.save(sess, './lenet')\n print(\"Model saved\")\n\n#Evaluate Model\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_loss, test_accuracy = evaluate(X_test, y_test)\n print(\"Test Accuracy = {:.3f}\".format(test_accuracy))\n\n#Plot Training Stats\nif 1:\n fig, ax1 = plt.subplots()\n plt.title(\"Training Results [Test Accuracy = {:.3f}]\".format(test_accuracy))\n ax1.plot(range(1,EPOCHS+1), train_loss, 'b', label='Training Loss')\n ax1.plot(range(1,EPOCHS+1), valid_loss, 'g', label='Validation Loss')\n ax1.set_ylabel('Loss')\n ax1.set_xlabel('Epoch')\n ax2 = ax1.twinx()\n ax2.plot(range(1,EPOCHS+1), valid_acc, 'r', label='Validation Accuracy')\n ax2.set_ylabel('Accuracy (%)')\n fig.tight_layout()\n ax2.set_ylim([0,100])\n lines, labels = ax1.get_legend_handles_labels()\n lines2, labels2 = ax2.get_legend_handles_labels()\n ax2.legend(lines + lines2, labels + labels2, bbox_to_anchor=(0., -.2, 1., -.2), mode=\"expand\", borderaxespad=0., ncol=3, loc=3)\n plt.show()\n\n\n### Load the images and plot them here.\n### Feel free to use as many code cells as needed.\n\nX_wild = []\ny_wild = []\nfor i in range(1,6,1):\n img = cv2.imread('traffic-signs-data/wild_{}.png'.format(i), cv2.IMREAD_COLOR)\n RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n X_wild.append(RGB_img)\nwith open('traffic-signs-data/wild.csv', 'r') as csvfile:\n for row in csv.reader(csvfile, delimiter=','):\n y_wild.append(int(row[0]))\n\nn_wild = len(y_wild)\nif 0:\n plt.figure(figsize=(5, 4))\n for i in range(0,n_wild):\n plt.subplot(1, n_wild, i+1)\n plt.imshow(X_wild[i])\n plt.title(text_labels[y_wild[i]])\n plt.axis('off')\n plt.suptitle('Wild Traffic Signs')\n plt.show()\n\n\n### Run the predictions here and use the model to output the prediction for each image.\n### Make sure to pre-process the images with the same pre-processing pipeline used earlier.\n### Feel free to use as many code cells as needed.\n\nX_wild = preprocess_data(X_wild)\n\n#Evaluate Model\ndef evaluate_topk(X_data, k):\n sess = tf.get_default_session()\n X_data = np.expand_dims(X_data, axis=0)\n topk = sess.run(topk_operation, feed_dict={x: X_data, keep_prob: 1.0, k_pred: k})\n return topk\n\ndef evaluate_prediction(X, y):\n sess = tf.get_default_session()\n X = np.expand_dims(X, axis=0)\n p = sess.run(predict_operation, feed_dict={x: X, keep_prob: 1.0})\n c = (p == y)\n return p,c\n\nif 1:\n with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n for i in range(0,5,1):\n p,c = evaluate_prediction(X_wild[i], y_wild[i])\n print(p,c)\n\n\n### Calculate the accuracy for these 5 new images. \n### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n test_loss, test_accuracy = evaluate(X_wild, y_wild)\n print(\"Wild Test Accuracy = {:.3f}\".format(test_accuracy))\n\n\n### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. \n### Feel free to use as many code cells as needed.\nif 0:\n with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n for i in range(0,5,1):\n top5 = evaluate_topk(X_wild[i], 5)\n plt.bar(top5.indices[0], top5.values[0])\n plt.xlabel(\"Class\")\n plt.ylabel('Softmax probability')\n plt.show()\n\n\n### Visualize your network's feature maps here.\n### Feel free to use as many code cells as needed.\n\n# image_input: the test image being fed into the network to produce the feature maps\n# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer\n# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output\n# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry\n\ndef outputFeatureMap(image_input, tf_activation, title, activation_min=-1, activation_max=-1 ,plt_num=1):\n # Here make sure to preprocess your image_input in a way your network expects\n # with size, normalization, ect if needed\n # image_input =\n # Note: x should be the same name as your network's tensorflow data placeholder variable\n # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function\n activation = tf_activation.eval(session=sess,feed_dict={x : image_input})\n featuremaps = activation.shape[3]\n cols = (featuremaps+1) / 4 + 1\n rows = (featuremaps+1) / cols + 1\n plt.figure(plt_num, figsize=(15,rows))\n for featuremap in range(featuremaps):\n plt.subplot(rows, cols, featuremap+1) # sets the number of feature maps to show on each row and column\n #plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number\n if activation_min != -1 & activation_max != -1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin =activation_min, vmax=activation_max, cmap=\"gray\")\n elif activation_max != -1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmax=activation_max, cmap=\"gray\")\n elif activation_min !=-1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin=activation_min, cmap=\"gray\")\n else:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", cmap=\"gray\")\n plt.suptitle(title)\n plt.show()\n\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n img = np.expand_dims(X_wild[0], axis=0)\n outputFeatureMap(img, conv_1, \"Layer 1\")\n outputFeatureMap(img, conv_2, \"Layer 2\")\n outputFeatureMap(img, conv_3, \"Layer 3\")\n","sub_path":"Traffic_Sign_Classifier.py","file_name":"Traffic_Sign_Classifier.py","file_ext":"py","file_size_in_byte":18865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"585297255","text":"from __future__ import division\nfrom __future__ import print_function\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport sys\nfrom datetime import datetime\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nclass VariationalEncoder(object):\n def timeit(method):\n def timed(*args, **kw):\n ts = time.time()\n result = method(*args, **kw)\n te = time.time()\n print ('[{}'.format(method.__name__), 'takes {0:.2f} sec]'.format(te-ts))\n return result\n return timed\n \n def get_log_name(self):\n date = datetime.now()\n return \"vae-{}-{}-{}-{}-{}\".format(self.name, date.month, date.day, date.hour, date.minute)\n \n def __init__(self, config, sess):\n print('Reading config file...') \n # model parameters\n self.sess = sess\n self.batch_size = config.batch_size\n self.hidden_dim = config.hidden_dim\n self.input_dim = config.input_dim\n self.label_dim = config.label_dim\n self.latent_dim = config.latent_dim\n self.num_batch = config.num_batch\n self.lr_init = config.lr_init\n self.optimizer_name = config.optimizer_name\n self.max_grad_norm = config.max_grad_norm\n self.minval = config.minval\n self.maxval = config.maxval\n self.dataset = config.dataset\n self.name = config.name\n \n # Training configuration \n self.checkpoint_dir = config.checkpoint_dir \n\n # Tensorflow: modules\n self.writer = None\n self.summarizer = None\n self.optimizer = None\n self.saver = None\n\n # Tensorflow: placeholders \n self.X = tf.placeholder(tf.float32, shape=[None, self.input_dim])\n self.Z = tf.placeholder(tf.float32, shape=[None, self.latent_dim])\n \n # MNIST\n self.mnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n \n # Model\n self.KL = None\n self.P = None\n self.posterior = None\n\n if not os.path.isdir(self.checkpoint_dir):\n raise Exception(\"[!] Directory {} not found\".format(self.checkpoint_dir))\n \n @timeit\n def build_var(self):\n self.global_step = tf.Variable(0, trainable=False, name=\"global_step\")\n self.learning_rate = tf.placeholder(tf.float32, shape=[])\n initializer = tf.random_uniform_initializer(self.minval, self.maxval) \n print('1.Encoding') \n with tf.variable_scope(\"encode\"):\n self.W_x = tf.get_variable(\"W_x\", shape=[self.input_dim, self.hidden_dim],\n initializer=initializer)\n self.b_x = tf.get_variable(\"b_x\", shape=[self.hidden_dim],\n initializer=initializer)\n self.W_mu = tf.get_variable(\"W_mu\", shape=[self.hidden_dim, self.latent_dim],\n initializer=initializer)\n self.b_mu = tf.get_variable(\"b_mu\", shape=[self.latent_dim],\n initializer=initializer)\n self.W_sig = tf.get_variable(\"W_sig\", shape=[self.hidden_dim, self.latent_dim],\n initializer=initializer)\n self.b_sig = tf.get_variable(\"b_sig\", shape=[self.latent_dim],\n initializer=initializer)\n print('2.Decoding') \n with tf.variable_scope(\"decode\"):\n self.W_z = tf.get_variable(\"W_z\", shape=[self.latent_dim, self.hidden_dim],\n initializer=initializer)\n self.b_z = tf.get_variable(\"b_z\", shape=[self.hidden_dim],\n initializer=initializer)\n with tf.variable_scope(\"Normal\"):\n self.W_mu = tf.get_variable(\"W_mu\", shape=[self.hidden_dim, self.input_dim],\n initializer=initializer)\n self.b_mu = tf.get_variable(\"b_mu\", shape=[self.input_dim],\n initializer=initializer)\n self.W_sig = tf.get_variable(\"W_sig\", shape=[self.hidden_dim, self.input_dim],\n initializer=initializer)\n self.b_sig = tf.get_variable(\"b_sig\", shape=[self.input_dim],\n initializer=initializer)\n with tf.variable_scope(\"Bernoulli\"):\n self.W_p = tf.get_variable(\"W_p\", shape=[self.hidden_dim, self.input_dim],\n initializer=initializer)\n self.b_p = tf.get_variable(\"b_p\", shape=[self.input_dim],\n initializer=initializer)\n \n @timeit \n def build_graph(self):\n print('1.Encoding') \n with tf.variable_scope(\"encode\", reuse = True):\n W = tf.get_variable(\"W_x\")\n b = tf.get_variable(\"b_x\")\n W_mu = tf.get_variable(\"W_mu\") \n b_mu = tf.get_variable(\"b_mu\") \n W_sig = tf.get_variable(\"W_sig\") \n b_sig = tf.get_variable(\"b_sig\") \n \n h = tf.tanh(tf.matmul(self.X, W) + b)\n mu = tf.matmul(h, W_mu) + b_mu\n mu2 = tf.square(mu) \n log_sigma2 = tf.matmul(h, W_sig) + b_sig \n sigma2 = tf.exp(log_sigma2) \n sigma = tf.exp(0.5*log_sigma2) \n\n epsilon = tf.random_normal([self.batch_size, self.latent_dim], \n mean=0.0, stddev=1.0, dtype=tf.float32)\n self.z = mu + tf.mul(epsilon, sigma)\n with tf.variable_scope(\"Loss\"):\n self.KL = tf.reduce_sum(1 + log_sigma2 - mu2 - sigma2, 1)\n\n print('2.Decoding') \n with tf.variable_scope(\"decode\", reuse = True):\n W = tf.get_variable(\"W_z\")\n b = tf.get_variable(\"b_z\")\n h = tf.tanh(tf.matmul(self.z, W) + b) \n \n with tf.variable_scope(\"Bernoulli\", reuse = True):\n W_p = tf.get_variable(\"W_p\") \n b_p = tf.get_variable(\"b_p\") \n with tf.variable_scope(\"sample\"):\n self.Y = tf.sigmoid(tf.matmul(tf.tanh(tf.matmul(self.Z, W) + b), W_p) + b_p)\n Y = tf.sigmoid(tf.matmul(h, W_p) + b_p) \n self.posterior = tf.contrib.distributions.Bernoulli(p = Y)\n #self.log_pz = tf.reduce_sum(self.X*tf.log(self.Y) + (1 - self.X)*tf.log(1 - self.Y), 1) \n #TODO: Gaussian \n with tf.variable_scope(\"Normal\", reuse = True):\n W_mu = tf.get_variable(\"W_mu\") \n b_mu = tf.get_variable(\"b_mu\") \n W_sig = tf.get_variable(\"W_sig\") \n b_sig = tf.get_variable(\"b_sig\") \n mu = tf.matmul(h, W_mu) + b_mu\n sigma = tf.exp(0.5 * (tf.matmul(h, W_sig) + b_sig))\n #print(mu.get_shape(), self.X.get_shape()) \n #with tf.variable_scope(\"sample\"):\n # self.Y = tf.matmul(tf.tanh(tf.matmul(self.Z, W) + b), W_mu) + b_mu\n #self.posterior = tf.contrib.distributions.MultivariateNormalDiag(mu, sigma)\n \n with tf.variable_scope(\"Loss\"):\n self.log_pz = tf.reduce_sum(self.posterior.log_prob(self.X), 1)\n #self.log_pz = self.posterior.log_pdf(self.X)\n #print(self.KL.get_shape()) \n self.loss = tf.reduce_sum(-self.log_pz - self.KL)/self.batch_size \n\n @timeit \n def build_optimizer(self):\n self.optimizer = tf.contrib.layers.optimize_loss(\n loss = self.loss, \n global_step = self.global_step,\n learning_rate = self.learning_rate, \n optimizer = self.optimizer_name, \n clip_gradients = self.max_grad_norm)\n\n @timeit\n def build_other_helpers(self):\n self.saver = tf.train.Saver(tf.trainable_variables())\n #tf.scalar_summary(\"loss\", self.loss)\n tf.scalar_summary(\"learning rate\", self.learning_rate)\n #tf.scalar_summary(\"best training loss\", self.best_loss)\n self.summarizer = tf.merge_all_summaries()\n self.writer = tf.train.SummaryWriter(\"./logs/{}\".format(self.get_log_name()),\\\n self.sess.graph)\n\n @timeit\n def initialization(self):\n self.sess.run(tf.initialize_all_variables())\n \n def train(self):\n self.build_model()\n merged_sum = tf.merge_all_summaries()\n for i in range(self.num_batch):\n X, _ = self.mnist.train.next_batch(self.batch_size)\n feed_dict = {self.learning_rate: self.lr_init,\n self.X: X}\n outputs = self.sess.run([self.optimizer, self.loss, self.summarizer], feed_dict) \n\n print(\"Iteration {} | LR {} | Loss {}\".format(i, self.lr_init, outputs[0]))\n self.writer.add_summary(outputs[-1], i)\n if i % 1000 == 1:\n self.save()\n sys.stdout.flush()\n \n def build_model(self):\n print('-------------Variable building') \n self.build_var() \n print('-------------Graph building') \n self.build_graph()\n print('There are {} parameters in the graph.'.format(self.countParameters())) \n print('-------------Optimizer building') \n self.build_optimizer() \n print('-------------Saver, writer and summarizer building') \n self.build_other_helpers() \n print('-------------Variable initialization') \n self.initialization()\n \n def sample(self, Z):\n return self.sess.run([self.Y], feed_dict={self.Z: Z})[0]\n \n @timeit\n def save(self): \n self.saver.save(self.sess, \n os.path.join(self.checkpoint_dir, self.get_log_name()))\n \n @timeit\n def load(self):\n self.build_var()\n self.build_graph()\n self.build_other_helpers()\n print(\"[*] Reading checkpoints...\")\n ckpt = tf.train.get_checkpoint_state(self.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n else:\n raise Exception(\"[!] No checkpoint found\")\n\n def countParameters(self): \n total_parameters = 0\n for variable in tf.trainable_variables():\n shape = variable.get_shape()\n variable_parametes = 1\n for dim in shape:\n variable_parametes *= dim.value\n total_parameters += variable_parametes\n return total_parameters \n","sub_path":"vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":10829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"50815743","text":"from mitmproxy import http\nimport json\nfrom datetime import datetime\nfrom uuid import uuid1\nimport numpy as np\nfrom api import userCard\n\ndef send(flow):\n body = json.loads(flow.request.text)\n nowstr = str(datetime.now()).split('.')[0].replace('-', '/')\n\n with open('data/user/user.json', encoding='utf-8') as f:\n userId = json.load(f)['id']\n with open('data/user/userCardList.json', encoding='utf-8') as f:\n userCardList = json.load(f)\n with open('data/user/userCharaList.json', encoding='utf-8') as f:\n userCharaList = json.load(f)\n with open('data/user/userQuestBattleResult.json', encoding='utf-8') as f:\n battle = json.load(f)\n if not battle['id'] == body['userQuestBattleResultId']:\n flow.response = http.HTTPResponse.make(400, '{\"errorTxt\": \"You didn\\'t really start this quest, or something...\",\"resultCode\": \"error\",\"title\": \"Error\"}', {})\n return\n\n # add exp to user and level up, maybe\n userExp = battle['questBattle']['exp']\n with open('data/user/gameUser.json', encoding='utf-8') as f:\n gameUser = json.load(f)\n gameUser['exp'] += userExp\n newStatus = []\n if gameUser['exp'] >= gameUser['totalExpForNextLevel']:\n gameUser['level'] += 1\n gameUser['totalExpForCurrentLevel'] = gameUser['totalExpForNextLevel']\n gameUser['totalExpForNextLevel'] += 10 # TODO: how does this actually work lol\n with open('data/user/userStatusList.json', encoding='utf-8') as f:\n userStatusList = json.load(f)\n \n maxAPIdx = 0\n currAPIdx = 0\n for i, status in enumerate(userStatusList):\n if status['statusId'] == 'MAX_ACP':\n maxAPIdx = i\n if status['statusId'] == 'ACP':\n currAPIdx = i\n userStatusList[maxAPIdx]['point'] += 10\n userStatusList[currAPIdx]['point'] += userStatusList[maxAPIdx]['point']\n newStatus.append(userStatusList[maxAPIdx])\n newStatus.append(userStatusList[currAPIdx])\n\n with open('data/user/userStatusList.json', 'w+', encoding='utf-8') as f:\n json.dump(userStatusList, f, ensure_ascii=False)\n\n with open('data/user/gameUser.json', 'w+', encoding='utf-8') as f:\n json.dump(gameUser, f, ensure_ascii=False)\n\n # TODO: add to stories\n resultUserQuestAdventureList = []\n\n # change userQuestBattleResult status\n battle['questBattleStatus'] = 'SUCCESSFUL'\n\n # add to userQuestBattleList\n with open('data/user/userQuestBattleList.json', encoding='utf-8') as f:\n userQuestBattleList = json.load(f)\n\n resultUserQuestBattle = {}\n # TODO: get real mission clear values\n for userQuestBattle in userQuestBattleList:\n if userQuestBattle['questBattleId'] == battle['questBattleId']:\n resultUserQuestBattle = userQuestBattle\n if resultUserQuestBattle == {}:\n resultUserQuestBattle = {\n \"userId\": userId,\n \"questBattleId\": battle['questBattleId'],\n \"questBattle\": battle,\n \"cleared\": True,\n \"missionStatus1\": \"NON_CLEAR\",\n \"missionStatus2\": \"NON_CLEAR\",\n \"missionStatus3\": \"NON_CLEAR\",\n \"rewardDone\": False,\n \"clearCount\": 0,\n \"maxDamage\": 0,\n \"createdAt\": nowstr\n }\n userQuestBattleList.append(resultUserQuestBattle)\n resultUserQuestBattleList = [resultUserQuestBattle]\n with open('data/user/userQuestBattleList.json', 'w+', encoding='utf-8') as f:\n json.dump(userQuestBattleList, f, ensure_ascii=False)\n\n # add exp to cards\n charaNos = []\n leaderCardId = 0\n leaderCharaId = 0\n cardIds = []\n resultUserCardList = []\n for i in range(9):\n numberedId = 'userCardId'+str(i+1)\n if numberedId in battle:\n cardIds.append(battle[numberedId])\n if battle[numberedId] == battle['episodeUserCardId']:\n leaderCardId = battle[numberedId]\n\n for i, currUserCard in enumerate(userCardList):\n if currUserCard['id'] in cardIds:\n charaNos.append(currUserCard['card']['charaNo'])\n if currUserCard['id'] == leaderCardId:\n leaderCharaId = currUserCard['card']['charaNo']\n\n exp = battle['questBattle']['cardExp']\n newLevel, extraExp = userCard.getFinalLevel(currUserCard, exp)\n maxLevel = userCard.maxLevels[currUserCard['card']['rank']]\n if newLevel >= maxLevel:\n userCardList[i]['level'] = maxLevel\n userCardList[i]['experience'] = 0\n else:\n userCardList[i]['level'] = newLevel\n userCardList[i]['experience'] = extraExp\n\n resultUserCardList.append(userCardList[i])\n\n with open('data/user/userCardList.json', 'w+', encoding='utf-8') as f:\n json.dump(userCardList, f, ensure_ascii=False)\n\n # add episode points to charas\n for i in range(9):\n numberedId = 'userCardId'+str(i+1)\n if numberedId in body:\n cardIds.append(body[numberedId])\n\n resultUserCharaList = []\n for i, userChara in enumerate(userCharaList):\n if userChara['charaId'] in charaNos:\n eps = battle['questBattle']['baseBondsPt']\n if userChara['charaId'] == leaderCharaId:\n eps *= 1.5\n userCharaList[i]['bondsTotalPt'] = min(userCharaList[i]['bondsTotalPt']+eps, 64000)\n resultUserCharaList.append(userCharaList[i])\n\n with open('data/user/userCharaList.json', 'w+', encoding='utf-8') as f:\n json.dump(userCharaList, f, ensure_ascii=False)\n\n # TODO: calculate drops and add to items\n resultUserItemList = []\n\n # make response\n response = {\n \"resultCode\": \"success\",\n 'gameUser': gameUser,\n 'userQuestAdventureList': resultUserQuestAdventureList,\n 'userCardList': resultUserCardList,\n 'userCharaList': resultUserCharaList,\n 'userItemList': resultUserItemList,\n 'userQuestBattleResultList': [battle],\n 'userQuestBattleList': resultUserQuestBattleList\n }\n if newStatus != []:\n response['userStatusList'] = newStatus\n flow.response = http.HTTPResponse.make(200, json.dumps(response, ensure_ascii=False), {})\n\ndef extractArts(userCard, userPieceList):\n arts = []\n if userCard is not None:\n arts += [userCard['card']['cardMagia'][key] for key in userCard['card']['cardMagia'].keys() if key.startswith('art')\n and not key.startswith('artId')]\n\n arts += [userCard['card']['cardSkill'][key] for key in userCard['card']['cardSkill'].keys() if key.startswith('art')\n and not key.startswith('artId')]\n for piece in userPieceList:\n skills = [piece['piece'][key] for key in piece['piece'].keys() if key.startswith('pieceSkill')]\n for skill in skills:\n arts += [skill[key] for key in skill.keys() if key.startswith('art')\n and not key.startswith('artId')]\n return arts\n\ndef cardMagiaToMagia(userCard):\n cardMagia = userCard['card']['cardMagia']\n return {\n \"magiaId\": cardMagia['id'],\n \"name\": cardMagia['name'],\n \"icon\": cardMagia['groupId'],\n \"level\": userCard['magiaLevel'],\n \"description\": cardMagia['shortDescription'],\n \"artList\": [cardMagia[key] for key in cardMagia if key.startswith('artId')]\n }\n\ndef cardSkillToConnect(userCard):\n cardSkill = userCard['card']['cardSkill']\n return {\n \"connectId\": cardSkill['id'],\n \"name\": cardSkill['name'],\n \"icon\": cardSkill['groupId'],\n \"description\": cardSkill['shortDescription'],\n \"artList\": [cardSkill[key] for key in cardSkill if key.startswith('artId')]\n }\n\ndef piecesToMemoriae(memoriaIds):\n memoria = []\n with open('data/user/userPieceList.json', encoding='utf-8') as f:\n userPieceList = json.load(f)\n for userPiece in userPieceList:\n if userPiece['id'] in memoriaIds:\n memoria.append({\n \"memoriaId\": str(userPiece['piece']['pieceId'])+'00', # TODO: replace 00 with something else?\n \"name\": userPiece['piece']['name'],\n \"icon\": userPiece['piece']['pieceSkill']['groupId'],\n \"level\": userPiece['level'],\n \"cost\": 0,\n \"description\": userPiece['piece']['description'],\n \"voice\": 0,\n \"artList\": extractArts(None, [userPiece['piece']]),\n \"type\": userPiece['piece']['pieceType'],\n \"displayType\": \"MEMORIA\"\n })\n return memoria\n\ndef cardToPlayer(userCard, userChara, battleInfo):\n charaMessages = [message for message in userChara['chara']['charaMessageList']if 40<=message['messageId']<50]\n charaMessage = np.random.choice(charaMessages)\n return {\n \"diskId\": 0,\n \"helper\": battleInfo['helper'],\n \"friend\": battleInfo['friend'],\n \"endMessageId\": charaMessage['messageId'],\n \"endMessage\": charaMessage['message'],\n \"memoriaMax\": 1,\n \"cardId\": userCard['cardId'],\n \"charId\": userChara['charaId'],\n \"miniCharId\": userCard['card']['miniCharaNo'],\n \"miniMagiaId\": userCard['card']['magiaCharaNo'],\n \"pos\": battleInfo['pos'],\n \"name\": userChara['chara']['name'],\n \"level\": userCard['level'],\n \"align\": userCard['card']['attributeId'],\n \"rank\": int(userCard['card']['rank'][-1]),\n \"hpStart\": userCard['hp'],\n \"hp\": userCard['hp'],\n \"mpStart\": 0,\n \"maxMp\": 1000, # TODO: allow doppels\n \"attack\": userCard['attack'],\n \"defence\": userCard['defense'],\n \"speed\": 0,\n \"discType1\": userCard['card']['commandType1'],\n \"discType2\": userCard['card']['commandType2'],\n \"discType3\": userCard['card']['commandType3'],\n \"discType4\": userCard['card']['commandType4'],\n \"discType5\": userCard['card']['commandType5'],\n \"connectId\": userCard['card']['cardSkill']['id'],\n \"magiaId\": str(userCard['card']['cardMagia']['id'])+str(userCard['magiaLevel']),\n \"blast\": 0,\n \"charge\": 0,\n \"mpup\": 0,\n \"rateGainMpAtk\": userCard['card']['rateGainMpAtk'],\n \"rateGainMpDef\": userCard['card']['rateGainMpDef'],\n \"leader\": battleInfo['leader'],\n \"ai\": 3 if userChara['charaId']==1001 else 1, # TODO: figure out how this actually works\n \"memoriaList\": battleInfo['memoriaList']\n }\n\ndef get(flow):\n body = json.loads(flow.request.text)\n\n isMirrors = False # TODO: make this actually represent if it's a mirrors battle\n\n with open('data/user/userQuestBattleResult.json', encoding='utf-8') as f:\n battle = json.load(f)\n if not battle['id'] == body['userQuestBattleResultId']:\n flow.response = http.HTTPResponse.make(400, '{\"errorTxt\": \"You didn\\'t really start this quest, or something...\",\"resultCode\": \"error\",\"title\": \"Error\"}', {})\n return\n\n with open('data/user/userDeckList.json', encoding='utf-8') as f:\n userDeckList = json.load(f)\n with open('data/user/userCardList.json', encoding='utf-8') as f:\n userCardList = json.load(f)\n with open('data/user/userCharaList.json', encoding='utf-8') as f:\n userCharaList = json.load(f)\n with open('data/user/userPieceList.json', encoding='utf-8') as f:\n userPieceList = json.load(f)\n\n # grab team info\n deck = {}\n for userDeck in userDeckList:\n if userDeck['deckType'] == battle['deckType']:\n deck = userDeck\n\n playerList = []\n artList = []\n magiaList = []\n connectList = []\n doppelList = []\n memoria = []\n for key in battle.keys():\n if key.startswith('userCardId'):\n currCardIdx = 0\n for i in range(4):\n if 'questPositionId'+str(i+1) in deck:\n if deck['questPositionId'+str(i+1)]==int(key[-1]):\n currCardIdx = i+1\n \n userCardId = deck['userCardId'+str(currCardIdx)]\n userCard = {}\n for card in userCardList:\n if card['id'] == userCardId and card['enabled']:\n userCard = card\n if userCard == {}:\n flow.response = http.HTTPResponse.make(400, '{\"errorTxt\": \"Tried to start quest with a meguca you don\\'t have...\",\"resultCode\": \"error\",\"title\": \"Error\"}', {})\n return\n magiaList.append(cardMagiaToMagia(userCard))\n connectList.append(cardSkillToConnect(userCard))\n\n userCharaId = userCard['card']['charaNo']\n userChara = {}\n for chara in userCharaList:\n if chara['charaId'] == userCharaId:\n userChara = chara\n if userChara == {}:\n flow.response = http.HTTPResponse.make(400, '{\"errorTxt\": \"Tried to start quest with a meguca you don\\'t have...\",\"resultCode\": \"error\",\"title\": \"Error\"}', {})\n return\n\n pieceIds = [deck[key] for key in deck.keys() if key.startswith('userPieceId0'+str(currCardIdx))]\n pieces = [userPiece for userPiece in userPieceList if userPiece['id'] in pieceIds]\n artList += extractArts(userCard, pieces)\n currMemoria = piecesToMemoriae(pieces)\n memoria += currMemoria\n\n battleInfo = {\n 'helper': False,\n 'friend': False,\n 'pos': int(key[-1]),\n 'leader': deck['questEpisodeUserCardId'] == userCharaId,\n 'memoriaList': currMemoria\n }\n playerList.append(cardToPlayer(userCard, userChara, battleInfo))\n\n # do the same, but now for the helper\n # TODO: use actual support\n with open('data/npc.json', encoding='utf-8') as f:\n helper = json.load(f)\n helperCard = helper['userCardList'][0]\n helperChara = helper['userCharaList'][0]\n helperPieces = helper['userPieceList']\n\n magiaList.append(cardMagiaToMagia(helperCard))\n connectList.append(cardSkillToConnect(helperCard))\n artList += extractArts(helperCard, helperPieces)\n helperMemoria = piecesToMemoriae(helperPieces)\n memoria += helperMemoria\n\n battleInfo = {\n 'helper': True,\n 'friend': True, # TODO: actually change this\n 'pos': deck['questPositionHelper'],\n 'leader': False,\n 'memoriaList': helperMemoria\n }\n playerList.append(cardToPlayer(helperCard, helperChara, battleInfo))\n\n # add support points\n with open('data/user/userItemList.json', encoding='utf-8') as f:\n userItems = json.load(f)\n supportPoints = {}\n for i, item in enumerate(userItems):\n if item['itemId'] == 'YELL':\n userItems[i]['quantity'] += 60 # TODO: change this based on the helper\n supportPoints = userItems[i]\n with open('data/user/userItemList.json', 'w+', encoding='utf-8') as f:\n json.dump(userItems, f)\n\n # spend AP\n with open('data/user/userStatusList.json', encoding='utf-8') as f:\n userStatuses = json.load(f)\n apStatus = {}\n for i, status in enumerate(userStatuses):\n if status['statusId'] == 'ACP':\n userStatuses[i]['point'] -= 1 # TODO: figure out how to find this...\n apStatus = userStatuses[i]\n with open('data/user/userStatusList.json', 'w+', encoding='utf-8') as f:\n json.dump(userStatuses, f)\n\n # change quest status\n battle['questBattleStatus'] = 'LOTTERY'\n with open('data/user/userQuestBattleResult.json', 'w+', encoding='utf-8') as f:\n json.dump(battle, f)\n\n # TODO: use follower\n userFollowList = []\n\n # compile web data\n with open('data/user/gameUser.json', encoding='utf-8') as f:\n gameUser = json.load(f)\n webData = {\n \"gameUser\": gameUser,\n \"userStatusList\": [apStatus],\n \"userQuestBattleResultList\": [battle],\n \"resultCode\": \"success\",\n \"userFollowList\": [userFollowList],\n \"userItemList\": [supportPoints]\n }\n\n with open('data/hardCodedWave.json', encoding='utf-8') as f:\n wave = json.load(f)\n\n response = {\n 'scenario': battle['questBattle'],\n 'waveList': [wave],\n 'battleType': 'QUEST', # TODO: change for tutorials, mirrors\n 'playerList': playerList,\n 'doppelList': doppelList,\n 'artList': artList,\n 'memoriaList': memoria,\n 'connectList': connectList,\n 'magiaList': magiaList,\n 'continuable': True,\n 'isHalfSkill': isMirrors,\n 'webData': webData\n }\n flow.response = http.HTTPResponse.make(200, json.dumps(response, ensure_ascii=False), {})\n\ndef start(flow): \n body = json.loads(flow.request.text)\n nowstr = str(datetime.now()).split('.')[0].replace('-', '/')\n\n with open('data/user/gameUser.json', encoding='utf-8') as f:\n userInfo = json.load(f)\n\n with open('data/user/userQuestBattleList.json', encoding='utf-8') as f:\n userQuestBattleList = json.load(f)\n\n userQuestInfo = {}\n for userQuestBattle in userQuestBattleList:\n if userQuestBattle['questBattleId'] == body['questBattleId']:\n userQuestInfo = userQuestBattle\n\n if userQuestInfo == {}:\n with open('data/questBattleList.json', encoding='utf-8') as f:\n allBattles = json.load(f)\n for battle in allBattles: \n if battle['questBattleId'] == body['questBattleId']:\n userQuestInfo = {\n \"userId\": userInfo['userId'],\n \"questBattleId\": battle['questBattleId'],\n \"questBattle\": battle,\n \"cleared\": True,\n \"missionStatus1\": \"NON_CLEAR\",\n \"missionStatus2\": \"NON_CLEAR\",\n \"missionStatus3\": \"NON_CLEAR\",\n \"rewardDone\": False,\n \"clearCount\": 0,\n \"maxDamage\": 0,\n \"createdAt\": nowstr\n }\n userQuestBattleList.append(userQuestInfo)\n with open('data/user/userQuestBattleList.json', 'w+', encoding='utf-8') as f:\n json.dump(userQuestBattleList, f, ensure_ascii=False)\n\n with open('data/user/userDeckList.json', encoding='utf-8') as f:\n userDeckList = json.load(f)\n chosenTeam = None\n for userDeck in userDeckList:\n if userDeck['deckType'] == body['deckType']:\n chosenTeam = userDeck\n if chosenTeam is None:\n flow.response = http.HTTPResponse.make(500, '{\"errorTxt\": \"The team doesn\\'t exist...\",\"resultCode\": \"error\",\"title\": \"Error\"}', {})\n return\n\n with open('data/user/userFormationSheetList.json', encoding='utf-8') as f:\n formations = json.load(f)\n chosenFormation = None\n for formation in formations:\n if formation['formationSheetId'] == chosenTeam['formationSheetId']:\n chosenFormation = formation\n if chosenFormation is None:\n flow.response = http.HTTPResponse.make(500, '{\"errorTxt\": \"You don\\'t have that formation.\",\"resultCode\": \"error\",\"title\": \"Error\"}', {})\n return\n\n userQuestBattleResult = {\n \"battleType\": \"QUEST\",\n \"bondsPt1\": 0,\n \"bondsPt2\": 0,\n \"bondsPt3\": 0,\n \"bondsPt4\": 0,\n \"bondsPt5\": 0,\n \"bondsPt6\": 0,\n \"bondsPt7\": 0,\n \"bondsPt8\": 0,\n \"bondsPt9\": 0,\n \"clearedMission1\": userQuestInfo['missionStatus1']=='CLEARED',\n \"clearedMission2\": userQuestInfo['missionStatus2']=='CLEARED',\n \"clearedMission3\": userQuestInfo['missionStatus3']=='CLEARED',\n \"connectNum\": 0,\n \"continuedNum\": 0,\n \"createdAt\": nowstr,\n \"deadNum\": 0,\n \"deckType\": body['deckType'],\n \"diskAcceleNum\": 0,\n \"diskBlastNum\": 0,\n \"diskChargeNum\": 0,\n \"doppelNum\": 0,\n \"enemyNum\": 0,\n \"episodeUserCardId\": chosenTeam['questEpisodeUserCardId'],\n \"exp\": 0,\n \"follow\": True,\n \"follower\": True,\n \"formationSheetId\": chosenTeam['formationSheetId'],\n \"formationSheet\": chosenFormation,\n \"helpAttributeId\": body['helpAttributeId'],\n \"helpBondsPt\": 0,\n \"helpPosition\": chosenTeam['questPositionHelper'],\n \"id\": str(uuid1()),\n \"level\": userInfo['level'],\n \"magiaNum\": 0,\n \"nativeClearTime\": 0,\n \"questBattle\": userQuestInfo['questBattle'],\n \"questBattleId\": body['questBattleId'],\n \"questBattleStatus\": \"CREATED\",\n \"riche\": 0,\n \"serverClearTime\": 0,\n \"skillNum\": 0,\n \"turns\": 0,\n \"userId\": userInfo['userId']\n }\n\n if 'helpUserCardId' in body:\n userQuestBattleResult[\"helpUserCardId\"] = body['helperUserCardId'],\n userQuestBattleResult[\"helpUserId\"] = body['helperUserId'],\n\n for i in range(4):\n numberedId = 'userCardId'+str(i+1)\n if numberedId in body:\n userQuestBattleResult['userCardId'+str(body['questPositionId'+str(i+1)])] = body[numberedId]\n\n resultdict = {\n \"resultCode\": \"success\",\n \"userQuestBattleResultList\": [userQuestBattleResult]\n }\n\n with open('data/user/userQuestBattleResult.json', 'w+', encoding='utf-8') as f:\n json.dump(userQuestBattleResult, f, ensure_ascii=False)\n\n flow.response = http.HTTPResponse.make(200, json.dumps(resultdict, ensure_ascii=False), {})\n\ndef handleQuest(flow):\n endpoint = flow.request.path.replace('/magica/api/quest', '')\n if endpoint.startswith('/start'):\n start(flow)\n elif endpoint.startswith('/native/get'):\n get(flow)\n elif endpoint.startswith('/native/result/send'):\n send(flow)\n else:\n flow.response = http.HTTPResponse.make(501, \"Not implemented\", {})","sub_path":"api/quest.py","file_name":"quest.py","file_ext":"py","file_size_in_byte":21924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"595981400","text":"\"\"\"\nPython_project.py input_fastq_file expected_seq_partA\n\"\"\"\n\nfrom sys import argv\nimport subprocess\nfrom Bio import SeqIO\nfrom Bio.Blast import NCBIWWW\nfrom Bio.Blast.Applications import NcbiblastnCommandline\nimport csv\n\ninput_fastq_file = argv[1]\nmin_length = 300\nlen_first_part = 82\nexpected_seq_partA = argv[2]\nmin_ident = 97\n\n#Convert fastq file into fasta file\ndef fastq_to_fasta(input_file):\n fasta_file = input_file.replace(\".fastq\", \".fasta\")\n count = SeqIO.convert(input_file,\"fastq\",fasta_file,\"fasta\")\n print(\"\\n %i records converted to fasta format\" % count)\n return fasta_file\n\n#Filter out short sequences\ndef filter_short(input_file, min_length):\n count = 0\n total = 0\n filtered_seq = input_file.replace(\".fasta\", \"_filtered%s.fasta\" % min_length)\n output_handle = open(filtered_seq, \"w\")\n for record in SeqIO.parse(input_file, \"fasta\"):\n total += 1\n if len(record) >= min_length:\n count += 1\n SeqIO.write(record, output_handle, \"fasta\")\n output_handle.close()\n print(\"\\n %i sequences longer than %i out of %i \" % (count, min_length, total))\n return filtered_seq\n\n#Cut the sequences at the expected length of the first part by creating 2 files with one part of the sequence in each\ndef split_seq(input_file, len_first_part):\n split_A = input_file.replace(\".fasta\", \"_splitA.fasta\")\n split_16S = input_file.replace(\".fasta\", \"_split16S.fasta\")\n output_handle = open(split_A, \"w\")\n for record in SeqIO.parse(input_file, \"fasta\"):\n record.seq = record.seq[:len_first_part]\n SeqIO.write(record, output_handle, \"fasta\")\n output_handle.close()\n output_handle = open(split_16S, \"w\")\n for record in SeqIO.parse(input_file, \"fasta\"):\n record.seq = record.seq[len_first_part:]\n SeqIO.write(record, output_handle, \"fasta\")\n output_handle.close()\n return split_A, split_16S\n\n##Verify that the first part of the sequences matches the expected gene and eliminate the ones that dont\n\n#create a database with the expected sequence(s)\ndef database_expect(expected_seq):\n expected_seq_db = expected_seq.replace(\".fasta\", \"_db\")\n subprocess.call(\"makeblastdb -in %s -out %s -dbtype nucl\" % (expected_seq, expected_seq_db),shell=True)\n return expected_seq_db\n\n#blast the part A of the sequences to the expected sequence\ndef blast_partA(input_partA, database):\n Blast_rslt_A = \"Blast_rslt_\" + expected_seq_db.replace(\"_db\",\"\")\n NcbiblastnCommandline(query= input_partA, db = database, out= Blast_rslt_A, outfmt = 6)()\n return Blast_rslt_A\n\n#use the blast results to keep only the right sequences\ndef verify_seq(blast_rslt, in_16S, min_ident):\n verified_16S = in_16S.replace(\"_filtered300_split16S.fasta\", \"_verified_16S\")\n fieldnames = [\"qseqid\", \"sseqid\", \"pident\",\"length\",\"mismatch\",\"gapopen\",\"qstart\",\"qend\",\"sstart\",\"send\",\"evalue\",\"bitscore\"]\n total = 0\n matching = 0\n #create a list of dictionaries using csv reader\n with open(blast_rslt, \"r\") as table:\n table_reader = csv.DictReader(table, delimiter='\\t', fieldnames=fieldnames)\n table_contents = []\n for i in table_reader:\n table_contents.append(i)\n #verify that the identity of partA is high enough if it is the case write the corresponding 16S seq in a new file\n output_handle = open(verified_16S, \"w\")\n for i in table_contents:\n total += 1\n if float(i[\"pident\"]) >= min_ident:\n matching += 1\n for record in SeqIO.parse(in_16S, \"fasta\"):\n if i[\"qseqid\"] == record.id:\n SeqIO.write(record, output_handle, \"fasta\")\n output_handle.close()\n print(\"\\n %i sequences out of %i matching the expected sequence with more than %s percent identity\\n\" %(matching, total, min_ident))\n\nfasta_file = fastq_to_fasta(input_fastq_file)\nfiltered_seq = filter_short(fasta_file, min_length)\nsplit_A, split_16S = split_seq(filtered_seq, len_first_part)\nexpected_seq_db = database_expect(expected_seq_partA)\nBlast_rslt_A = blast_partA(split_A, expected_seq_db)\nverify_seq(Blast_rslt_A, split_16S, min_ident)\n","sub_path":"Python_project.py","file_name":"Python_project.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"572408288","text":"import sqlite3\nimport sys\n\nimport chnlp.pdtb.pd\n\nif __name__ == '__main__':\n p = pd.PDTB()\n t = pd.TaggedPDTB(sys.argv[1])\n if len(sys.argv) > 2:\n causes = p.get_causal(sys.argv[2], sys.argv[3])\n else:\n causes = p.get_causal()\n #print(len(causes))\n intra_tags,adjacent_tags = t.read_relations()\n \n i=0\n j=0\n tagged_causes = []\n tags = intra_tags\n #print(len(tags))\n while True:\n #print(i,j)\n #print('{}:{}'.format(causes[i].text, tags[j].text))\n \n #for each causal relation, iterate over the text until we find a match\n if causes[i].text in tags[j].text and causes[i].text in tags[j].text.split('\\t')[0] and causes[i].text2 in tags[j].text:\n #might get false hit, make sure that if its two sentences, it occurs in the first sentence\n print('Match {}:{}'.format(causes[i].text, tags[j].text))\n tag = pd.Tag(**tags[j].__dict__)\n tag.set_alt_tag(causes[i].tag)\n tag.relation = causes[i].relation\n i += 1\n j+=1\n #j=0\n tagged_causes.append(tag)\n else:\n j += 1\n \n if j >= len(tags) or i >= len(causes):\n #print(\"ALSO TRUE\")\n if tags==intra_tags:\n #print(\"TRUE!!!\")\n tags = adjacent_tags\n i=0\n j=0\n else:\n break\n\n for t in tagged_causes:\n print(t)\n","sub_path":"misc/find_false_negatives.py","file_name":"find_false_negatives.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"291740734","text":"#\n# MANAGEMENT COMMANDS LOGIC\n#\nimport os\nimport sys\n\nimport djpcms\nfrom djpcms.utils.importer import import_module\n\nfrom .base import Command, CommandError, CommandOption\n\n__all__ = ['Command', 'CommandError', 'CommandOption', 'execute',\n 'fetch_command']\n\ndef find_commands(management_dir):\n \"\"\"\n Given a path to a management directory, returns a list of all the command\n names that are available.\n\n Returns an empty list if no commands are defined.\n \"\"\"\n command_dir = os.path.join(management_dir, 'commands')\n try:\n return (f[:-3] for f in os.listdir(command_dir)\n if not f.startswith('_') and f.endswith('.py'))\n except OSError:\n return ()\n\ndef load_command_class(app_name, name):\n \"\"\"\n Given a command name and an application name, returns the Command\n class instance. All errors raised by the import process\n (ImportError, AttributeError) are allowed to propagate.\n \"\"\"\n module = import_module('%s.management.commands.%s' % (app_name, name))\n return module.Command(name)\n\ndef execute(website, argv=None, stdout=None, stderr=None):\n '''Execute a command against a sites instance'''\n utility = ManagementUtility(website, argv)\n return utility.execute(stdout=stdout, stderr=stderr)\n\ndef fetch_command(website, command, argv=None, stdout=None, stderr=None):\n utility = ManagementUtility(website, argv)\n return utility.command_to_run(command, utility.argv,\n stdout=stdout, stderr=stderr)\n\n\nclass ManagementUtility(object):\n \"\"\"\n Encapsulates the logic of the django-admin.py and manage.py utilities.\n\n A ManagementUtility has a number of commands, which can be manipulated\n by editing the self.commands dictionary.\n \"\"\"\n def __init__(self, website, argv=None):\n if argv is None:\n argv = sys.argv[:]\n self.prog_name = os.path.basename(argv[0])\n self.argv = argv[1:]\n self.website = website\n\n def get_parser(self, with_commands=True, nargs='?', **params):\n '''Get the argument parser'''\n import argparse\n if with_commands:\n params['usage'] = self.get_usage()\n p = argparse.ArgumentParser(**params)\n p.add_argument('command', nargs=nargs, help='command to run')\n p.add_argument('-c','--config',\n default=self.website.settings_file,\n help='The path to the config file.')\n p.add_argument('-v','--version',\n action='version',\n version=self.website.version or djpcms.__version__,\n help='Print the version.')\n return p\n\n def get_usage(self):\n \"\"\"\n Returns the script's main help text, as a string.\n \"\"\"\n site = self.website()\n commands = site.get_commands()\n usage = \"\\nType '{0} --help' for help on a specific\\\n command.\\n\\nAvailable commands:\\n\".format(self.prog_name)\n cmds = '\\n'.join((' %s' % cmd for cmd in sorted(commands)))\n text = '{0}\\n{1}'.format(usage,cmds)\n if site.settings.DESCRIPTION:\n text = '{0}\\n{1}'.format(site.settings.DESCRIPTION, text)\n if site.settings.EPILOG:\n text = '{0}\\n{1}'.format(text, site.settings.EPILOG)\n return '\\n'+text\n\n def fetch_command(self, subcommand):\n \"\"\"Tries to fetch the given *subcommand*, printing a message with the\nappropriate command called from the command line (usually\n \"django-admin.py\" or \"manage.py\") if it can't be found.\n \"\"\"\n site = self.website()\n try:\n app_name = site.get_commands()[subcommand]\n except KeyError:\n raise ValueError(\"Unknown command: %r\\nType '%s --help'\\\n for usage.\\n\" % (subcommand, self.prog_name))\n if isinstance(app_name, Command):\n # If the command is already loaded, use it directly.\n klass = app_name\n else:\n klass = load_command_class(app_name, subcommand)\n return klass\n\n def command_to_run(self, command, argv, stdout=None, stderr=None):\n cmd = self.fetch_command(command)\n return cmd.clone(self.website, argv, stdout=stdout, stderr=stderr)\n\n def execute(self, stdout=None, stderr=None, **kwargs):\n \"\"\"Given the command-line arguments, this figures out which\nsubcommand is being run, creates a parser appropriate to that command,\nand runs it.\"\"\"\n argv = self.argv\n parser = self.get_parser(with_commands=False, add_help=False)\n args, _ = parser.parse_known_args(argv)\n self.website.settings_file = args.config\n parser = self.get_parser(add_help=False)\n args, argv = parser.parse_known_args(argv)\n if args.command:\n # Command is available. delegate the argv parsing to it\n command = self.command_to_run(args.command, argv,\n stdout=stdout, stderr=stderr)\n return command(**kwargs)\n else:\n # this should fail unless we pass -h\n parser = self.get_parser(nargs=1)\n parser.parse_args()\n\n\n","sub_path":"djpcms/cms/management/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"507591069","text":"#!/usr/bin/env python\n\n# The name of the file\n__name__ = \"IPRO Suite Restraint Functions\"\n# Documentation\n__doc__ = \"\"\"\nWritten in 2013 by Robert Pantazes of the Costas Maranas Lab in the Chemical\nEngineering Department of the Pennsylvania State University.\n\nThis file contains functions for the creation and collection of restraints used\nto maintain structures during IPRO Suite energy minimizations.\"\"\"\n\n# Include standard installation PYTHON modules\nimport os\nimport sys\n# Include IPRO Suite modules, too\nfrom STANDARDS import *\nimport CHARMM\nimport MOLECULES\nimport EXPERIMENT\n\nclass RestraintError(IPRO_Error):\n \"\"\"An error for problems in the RESTRAINTS module\"\"\"\n def __init__(self, error = ''):\n \"\"\"The initialization function of the Restraint Error class.\"\"\"\n IPRO_Error.__init__(self, error)\n\ndef CHARMM_PDB_label_maker(atom, format = 1):\n \"\"\"Create a label describing a PDB formatted Atom in CHARMM.\"\"\"\n # Store the label here\n label = ''\n # If desired, include the Molecule's name in the specification. Technically\n # this isn't necessary (since each Residue has a unique number), but it is\n # clearer\n if format == 1:\n label += \"atom ml\"\n if atom.moleculeName != ' ':\n label += atom.moleculeName.lower()\n label += \" \"\n # Always include the Atom's Residue's number and the atom's name \n label += str(atom.residueNumber) + \" \" + atom.name.lower()\n return label\n\ndef CHARMM_PDB_fix_atoms(molecules):\n \"\"\"Fix Atoms in place in CHARMM when the PDB file format is used\"\"\"\n # Store the text to fix the Atoms in place here\n fix = ''\n # Loop through the molecules\n for molecule in molecules:\n # Loop through the Residues\n for residue in molecule:\n # Skip Residues where nothing is fixed in place\n if residue.freedom != \"FIXED\" and len(residue.fixedAtoms) == 0:\n continue\n # Since something should be fixed in place, make sure the text is\n # prepared\n if fix == '':\n fix = \"defi fixed sele none end\\n\"\n # If the entire Residue should be fixed in place\n if residue.freedom == \"FIXED\":\n fix += \"defi fixed sele fixed .or. resi \" + str(residue.number)\n fix += \" end\\n\"\n # Or if there are Atoms that should be fixed in place\n elif len(residue.fixedAtoms) > 0:\n # Loop through the Atom names in the list\n for an in residue.fixedAtoms:\n # This should be impossible, but if the Atom isn't in the\n # Residue, skip it\n if an not in residue:\n continue\n # Include the Atom in the fixing\n fix += \"defi fixed sele fixed .or. \"\n fix += CHARMM_PDB_label_maker(residue[an]) + \" end\\n\"\n # If anything is fixed in place, finish the definition of the fixed list in\n # CHARMM\n if fix != '':\n fix += \"cons fix sele fixed end\\n\\n\"\n return fix\n\ndef fix_atoms(molecules):\n \"\"\"Create text to fix Atoms in place during energy minimizations\"\"\"\n # Do this differently based on the file format and force field\n if molecules[0].forceField == \"CHARMM\" and molecules[0].fileFormat == \"PDB\":\n return CHARMM_PDB_fix_atoms(molecules)\n # If the file format and force field combination aren't supported, raise an\n # error\n else:\n text = \"The fix atoms function does not support the \" + \\\n molecules[0].fileFormat + \" file format and \" + molecules[0].forceField\\\n + \" force field combination.\"\n raise RestraintError(text)\n\ndef CHARMM_PDB_position(group, experiment):\n \"\"\"Make restraints to keep PDB formatted Atoms near a position in CHARMM\"\"\"\n # It has already been confirmed by the position restraints function that the\n # experiment is an Experiment with position restraints and that the group is\n # a Design Group.\n # In CHARMM, these position restraints are referred to as harmonic\n # restraints\n # Store the generated restraints here\n harmonic = ''\n # Keep track of how many harmonic restraints have been made\n count = '0'\n # Loop through the harmonic restraints in the experiment\n for info in experiment[\"Restraints\"][\"Position\"]:\n # Get the specifications of the restraint - the group(s), molecule(s),\n # residue(s) and atom(s) it applies to, as well as the force constant\n gn = info[0]\n mn = info[1]\n rn = info[2]\n an = info[3]\n f = format(info[4], '.3f')\n # The default is to maintain the position close to the original\n # structure. However, it IS possible to maintain the position close to\n # an Atom in another Design Group\n if len(info) == 6:\n D = info[5]\n else:\n D = 0\n # If the restraint is for a particular group that is not this one, skip\n # it\n if gn not in ['all', group.number]:\n continue\n # Also skip it if it applies to a specific Molecule that is not in this\n # Design Group\n elif mn != 'all' and mn not in group:\n continue\n # Since some Residues and Atoms may or may not be fixed in place, try to\n # make the restraint. Store the positions here\n COORS = ''\n # And the atom specifications here\n ATOMS = ''\n # Get the relevant Molecules\n if mn == 'all':\n molecules = group\n else:\n molecules = [group[mn]]\n # Loop through those relevant Molecules\n for molecule in molecules:\n # Get the relevant Residues\n if rn == 'all':\n residues = molecule\n else:\n residues = [molecule[rn]]\n # Loop through those Residues\n for residue in residues:\n # If the Residue is fixed in place, skip it\n if residue.freedom == \"FIXED\":\n continue\n # Get the relevant Atoms\n atoms = []\n if an == 'all':\n # If the Residue is an amino acid, only use the N, CA, and C\n if residue.kind in aminoAcids[residue.fileFormat]:\n for atomName in ['N', 'CA', 'C']:\n atoms.append(residue[atomName])\n # Otherwise, use all non-hydrogen atoms\n else:\n for atom in residue:\n if not MOLECULES.is_hydrogen(atom):\n atoms.append(atom)\n else:\n atoms.append(residue[an])\n # Loop through those Atoms\n for atom in atoms:\n # If the Atom is fixed in place, skip it\n if atom in residue.fixedAtoms:\n continue\n # Otherwise the Atom should be in the restraint. If this is\n # the first Atom, start the restraint\n if ATOMS == '':\n count = str(int(count) + 1)\n ATOMS = \"\\ndefi rain\" + count + \" sele none end\\n\"\n # Include the atom in the restraint\n ATOMS += \"defi rain\" + count + \" sele rain\" + count + \\\n \" .or. \" + CHARMM_PDB_label_maker(atom) + \" end\\n\"\n # Get the Atom that this Atom is being kept close to\n atom2 =experiment[D][molecule.name][residue.name][atom.name]\n # Include the Atom's coordinates in COORS\n COORS += \"coor set comp xdir \" + format(atom2[0], '.3f') + \\\n \" ydir \" + format(atom2[1], '.3f') + \" zdir \" + \\\n format(atom2[2], '.3f') + \" sele \" + \\\n CHARMM_PDB_label_maker(atom) + \" end\\n\"\n # If a restraint was generated, include it\n if ATOMS != '':\n # Create the comparison set of Atom structures in CHARMM\n if harmonic == '':\n harmonic += \"coor copy comp\\n\\n\"\n # Constrain this set of Atoms\n harmonic += COORS + \"\\n\" + ATOMS + \"\\ncons harm force \" + f + \\\n \"mass sele rain\" + count + \" end comp\\n\"\n # Return the harmonic restraints\n return harmonic\n\ndef position_restraints(molecules, experiment):\n \"\"\"Create restraints that keep Atoms near specified positions.\"\"\"\n # Make sure the input is an Experiment class object with the proper values\n # and a Design Group. Otherwise, don't do anything\n if not isinstance(experiment, (EXPERIMENT.Experiment,dict)) or \"Restraints\"\\\n not in experiment or \"Position\" not in experiment[\"Restraints\"] or not \\\n isinstance(molecules, MOLECULES.DesignGroup):\n return ''\n # Create the restraints differently based on file format and force field\n if experiment[\"Force Field\"] == \"CHARMM\" and experiment[\"File Format\"] == \\\n \"PDB\":\n return CHARMM_PDB_position(molecules, experiment)\n # Otherwise raise an error\n else:\n text = \"The position_restraints function does not support the \"\n text += str(experiment[\"File Format\"]) + \" file format and \"\n text += str(experiment[\"Force Field\"]) + \" force field combination\"\n raise RestraintError(text)\n\ndef CHARMM_PDB_distance(group, experiment):\n \"\"\"Create restraints that maintain the distance between two Atoms\"\"\"\n # The distance restraints function has already made sure there are\n # restraints and that the group is a Design Group\n # In CHARMM, distance restraints are imposed using Nuclear-Overhouser\n # Effects (NOE restraints)\n # Store the restraints here\n noe = ''\n # Go through the NOE restraints in the experiment\n for info in experiment[\"Restraints\"][\"Distance\"]:\n # Make sure this particular NOE restraint should be applied\n if info[0] not in [group.number, 'all']:\n continue\n # For each Atom, make sure the Molecule is actually present in this\n # Design Group AND that both Atoms aren't fixed in place\n count = 0\n for i in range(1, 3):\n # if the Molecule isn't in the group, we can stop checking\n if info[i][0] not in group:\n count = 5000\n break\n # Get the Residue\n residue = group[info[i][0]][info[i][1]]\n # If the Residue can't move or the Atom is always fixed in place,\n # increment the counter\n if residue.freedom == \"FIXED\" or info[i][2] in residue.fixedAtoms:\n count += 1\n # If the counter is greater than 1, the restraint shouldn't be made\n if count > 1:\n continue\n # Get the two atoms\n atom1 = group[info[1][0]][info[1][1]][info[1][2]]\n atom2 = group[info[2][0]][info[2][1]][info[2][2]]\n # Create the NOE restraint\n if noe == '':\n noe = \"noe\\n\"\n noe += \"\\nassign sele \" + CHARMM_PDB_label_maker(atom1) + \" end sele \"+\\\n CHARMM_PDB_label_maker(atom2) + \" end -\\nkmin \" + format(info[3], \\\n '.3f') + \" rmin \" + format(info[4], '.3f') + \" kmax \" + \\\n format(info[5], '.3f') + \" rmax \" + format(info[6], '.3f')+\" fmax \"\\\n + format(info[7], '.3f') + \"\\n\"\n # If NOE restraints were declared, end their declaration\n if noe != '':\n noe += \"\\nend\\n\\n\"\n return noe\n\ndef distance_restraints(molecules, experiment):\n \"\"\"Create restraints that keep two Atoms a certain distance apart\"\"\"\n # Make sure the inputs are acceptable. Otherwise, return a blank string\n if not isinstance(experiment, (EXPERIMENT.Experiment,dict)) or \"Restraints\"\\\n not in experiment or \"Distance\" not in experiment[\"Restraints\"] or not \\\n isinstance(molecules, MOLECULES.DesignGroup):\n return ''\n # Create them based on file format and force field\n if experiment[\"Force Field\"] == \"CHARMM\" and experiment[\"File Format\"] == \\\n \"PDB\":\n return CHARMM_PDB_distance(molecules, experiment)\n else:\n text = \"The distance_restraints function does not support the \"\n text += str(experiment[\"File Format\"]) + \" file format and \"\n text += str(experiment[\"Force Field\"]) + \" force field combination\"\n raise RestraintError(text)\n\ndef CHARMM_PDB_dihedral(group, experiment):\n \"\"\"Create dihedral restraints for PDB formatted Atoms in CHARMM\"\"\"\n # Store the restraints here\n dihedral = ''\n # Loop through the Dihedral restraints\n for info in experiment[\"Restraints\"][\"Dihedral\"]:\n # Make sure the restraint applies to this Design Group\n if info[0] not in ['all', group.number]:\n continue\n # Determine if the Restraint should actually be made\n count = 0\n for i in range(1, 5):\n # If a Molecule is missing, don't try to make the restraint\n if info[i][0] not in group:\n count = 5000\n break\n # Get the specified Residue\n residue = group[info[i][0]][info[i][1]]\n if residue.freedom == \"FIXED\" or info[i][2] in residue.fixedAtoms:\n count += 1\n # If the restraint should not be made, skip it\n if count > 3:\n continue\n # Create the restraint\n dihedral += \"cons dihe\"\n for i in range(1, 5):\n atom = group[info[i][0]][info[i][1]][info[i][2]]\n dihedral += \" \" + CHARMM_PDB_label_maker(atom, 2)\n dihedral += \" force \" + format(info[5], '.3f') + \" min \"\n dihedral += format(info[6], '.3f') + \"\\n\"\n # Add an extra end line character if the restraints were actually created\n if dihedral != '':\n dihedral += \"\\n\"\n return dihedral\n\ndef dihedral_restraints(molecules, experiment):\n \"\"\"Restrain dihedral angles between Atoms.\"\"\"\n # Make sure the inputs are acceptable\n if not isinstance(experiment, (EXPERIMENT.Experiment,dict)) or \"Restraints\"\\\n not in experiment or \"Dihedral\" not in experiment[\"Restraints\"] or not \\\n isinstance(molecules, MOLECULES.DesignGroup):\n return ''\n # Do this differently based on the file format and force field\n if experiment[\"Force Field\"] == \"CHARMM\" and experiment[\"File Format\"] == \\\n \"PDB\":\n return CHARMM_PDB_dihedral(molecules, experiment)\n else:\n text = \"The dihedral_restraints function does not support the \"\n text += str(experiment[\"File Format\"]) + \" file format and \"\n text += str(experiment[\"Force Field\"]) + \" force field combination.\"\n raise RestraintError(text)\n","sub_path":"modules/RESTRAINTS.py","file_name":"RESTRAINTS.py","file_ext":"py","file_size_in_byte":14732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"508133322","text":"import numpy as np\nfrom scipy import fftpack\nfrom matplotlib import pyplot as plt\n\ndef image(n,tab):\n l=len(tab)\n k=0\n t_liste=[]\n t=1/n\n \n for i in range(l):\n t_liste.append(k)\n k+=t\n\n fe = 100\n T = t_liste[l-1]\n N = T*fe\n signal=tab\n # return shape(tab)\n signal = réduction_leaderprice(signal)\n signal = signal - mean(signal) # soustraction de la valeur moyenne du signal\n # la fréquence nulle ne nous intéresse pas \n signal_FFT = abs(fft(signal))\n # signal fréquentiel : on divise par la taille du vecteur pour normaliser la fft\n #fourier = fftpack.fft(tab)/l\n axe_f = np.fft.fftfreq(l,t)\n plt.figure()\n plt.subplot(121)\n plt.plot(t_liste,tab)\n plt.xlabel('axe temporel, en seconde')\n plt.subplot(122)\n plt.plot(axe_f,signal_FFT)\n plt.xlabel('axe frequentiels en Hertz')\n plt.show()\n\n","sub_path":"Tipe/tipe2.py","file_name":"tipe2.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"303504087","text":"from random import randint\nimport os, time\n\nbars = [\n\t\"▁\",\n\t\"▂\",\n\t\"▃\",\n\t\"▄\",\n\t\"▅\",\n\t\"▆\",\n\t\"▇\",\n\t\"█\"\n]\n\nclear = lambda : os.system('')\nprints = lambda t : print(t)\n\ndef get_starting():\n\treturn randint(0, len(bars) - 1)\n\ndef get_ending(n):\n\tstarting_size = n\n\tending_size = randint(0, len(bars) - 1)\n\tif ending_size == starting_size:\n\t\treturn get_ending(n)\n\t\tprint(\"retrying!\")\n\telse:\n\t\treturn ending_size\n\ndef print_bar(bars, start, end, waittime):\n\t# get bar starting size\n\tbar_opts = len(bars)\n\t#prints(bars[start])\n\ttime.sleep(waittime)\n\t#print(\"end\",end,\"start\", start)\n\tfor i in range(abs(end - start)):\n\t\tclear()\n\t\tif start < end:\n\t\t\tprints(bars[start + i])\n\t\telse:\n\t\t\tprints(bars[start - i])\n\t\ttime.sleep(waittime)\n\tprint_bar(bars, end, get_ending(end), waittime)\n\nprint(get_ending(3))\nstarting = get_starting()\nending = get_ending(starting)\nprint_bar(bars, starting, ending, .05)","sub_path":"config/polybar/randomwaveform.py","file_name":"randomwaveform.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"68101803","text":"import sys\n\nmax_x = 0\nmax_y = 0\n\ntable = []\nup_s = []\nright_s = []\ndown_s = []\nleft_s = []\n\ndef reset_values():\n global max_x\n global max_y\n global table\n global up_s\n global right_s\n global down_s\n global left_s\n\n max_x = 0\n max_y = 0\n\n table = []\n up_s = []\n right_s = []\n down_s = []\n left_s = []\n\ndef count_i(y, x):\n if x>=2 and y>=2:\n return min(x//2,y) + min(y//2,x) - 2\n else:\n return 0\n\ndef valid_coord(y, x):\n if y < 0 or x < 0 or y > max_y or x > max_x:\n return False\n return True\n\ndef fill_down(y, x):\n global down_s\n\n count = 1\n while valid_coord(y,x):\n if down_s[y][x] >= 1:\n down_s[y][x] = count\n count += 1\n else:\n count = 1\n y -= 1\n return\n\ndef fill_right(y, x):\n global right_s\n \n count = 1\n while valid_coord(y,x):\n if right_s[y][x] >= 1:\n right_s[y][x] = count\n count += 1\n else:\n count = 1\n x -= 1\n \n return\n\ndef fill_up(y, x):\n global up_s\n\n count = 1\n while valid_coord(y,x):\n if up_s[y][x] == 1:\n up_s[y][x] = count\n count += 1\n else:\n count = 1\n y += 1\n return\n\ndef fill_left(y, x):\n global left_s\n \n count = 1\n while valid_coord(y,x):\n if left_s[y][x] == 1:\n left_s[y][x] = count\n count += 1\n else:\n count = 1\n x += 1\n return\n\ncount = int(sys.stdin.readline())\n\ncase_num = 1\nfor _ in range(0,count):\n reset_values()\n max_y, max_x = sys.stdin.readline().rstrip().split(\" \")\n \n max_y = int(max_y) - 1\n max_x = int(max_x) - 1\n\n # print(max_y, max_x)\n\n for _ in range(max_y+1):\n line = list(map(int, sys.stdin.readline().rstrip().split(\" \")))\n table.append(line)\n\n up_s.append(line.copy())\n right_s.append(line.copy())\n down_s.append(line.copy())\n left_s.append(line.copy())\n\n def fill_tables():\n for y, row in enumerate(table):\n for x, column in enumerate(row):\n fill_up(y,x)\n fill_down(y,x)\n if 1 in row:\n fill_right(y,x) \n fill_left(y,x)\n\n fill_tables()\n\n # [print(line) for line in up_s]\n # print(\"\")\n # [print(line) for line in right_s]\n # print(\"\")\n # [print(line) for line in down_s]\n # print(\"\")\n # [print(line) for line in left_s]\n # print(\"\")\n\n retval = 0\n for y in range(0, len(table)):\n for x in range(0, len(table[0])):\n retval += count_i(up_s[y][x], right_s[y][x])\n retval += count_i(up_s[y][x], left_s[y][x])\n retval += count_i(down_s[y][x], right_s[y][x])\n retval += count_i(down_s[y][x], left_s[y][x])\n\n print(\"Case #{}: {}\".format(case_num, retval))\n case_num += 1","sub_path":"google_kickstart/2021/round_a/l_shaped_plots.py","file_name":"l_shaped_plots.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"345096327","text":"import math\nimport random \n#mul and pow are for q-matrix\ndef mul( A, B,mod):\n C = [[0 for i in xrange(len(B[0]))]for i in xrange(len(A))]\n for i in xrange(0,len(A)):\n for j in xrange(0,len(B[0])):\n for k in xrange(0,len(B)):\n C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod\n return C\ndef pow(A, p,mod):\n if p == 1:\n return A\n if (p % 2)==1: \n return mul(A, pow(A, p-1,mod),mod)\n X = pow(A, p/2,mod)\n return mul(X, X,mod)\ndef phi(n): \n totients = []\n for i in xrange(0,n+1):\n totients.append(i)\n for i in xrange(2,n+1):\n if totients[i] == i: \n for j in xrange(i,n+1,i):\n totients[j] = totients[j] / i * (i - 1)\n \n return totients;\ndef miller_rabin(m, k):\n s=1\n t = (m-1)/2\n while t%2 == 0:\n t /= 2\n s += 1\n\n for r in range(0,k):\n rand_num = random.randint(1,m-1)\n y = pow(rand_num, t, m)\n prime = False\n\n if (y == 1):\n prime = True\n\n\n for i in range(0,s):\n if (y == m-1):\n prime = True\n break\n else:\n y = (y*y)%m\n\n if not prime:\n return False\n\n return True\ndef sieve(n):\n isPrime = [False]*2+[True]*(n-1)\n i=2\n while i*i<=n:\n j=i\n while i * j <=n:\n isPrime[i*j]=False\n j+=1\n i+=1\n return isPrime\ndef getPrimeList(n):\n isPrime = sieve(n)\n listPrimes = []\n for i in range(2, n+1):\n if isPrime[i]:listPrimes.append(i)\n\n return listPrimes\n\ndef powMod(a,b,c):\n if(b==1): return a%c\n x = powMod(a,b>>1,c) \n x = (x*x)%c\n if(b&1==1)==1: # if odd number\n x = (x*a)%c\n return x\ndef isPrime(n):\n if n <= 1:\n return False\n if n == 2: \n return True\n if n % 2 == 0:\n return False\n if n < 9 :\n return True\n if n % 3 == 0:\n return False\n counter = 5\n while (counter * counter) <= n:\n if n % counter == 0:\n return False\n if n % (counter + 2) == 0: \n return False \n counter += 6 \n return True\ndef gcd(x, y):\n while y != 0 :\n z = x % y\n x = y\n y = z\n \n return x\ndef egcd(a,b):\n x,y,u,v = 0,1,1,0\n while a!=0:\n q,r = b//a,b%a\n m,n = x-u*q,y-v*q\n b,a,x,y,u,v=a,r,u,v,m,n\n gcd = b\n return gcd,x,y\ndef modinv(a,m):\n gcd,x,y = egcd(a,m)\n if gcd !=1:\n return None\n else:\n return x%m \n ","sub_path":"Library.py","file_name":"Library.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"406295862","text":"from paul_resources import PriceTable, daily_returns, tprint, rprint, lprint\nfrom beta_class_6 import Beta, ScrubParams, StockLineBetaAdjusted\nimport numpy as np\nimport pandas as pd\nimport math\nfrom operator import mul\nfrom functools import reduce\nimport matplotlib.pyplot as plt\nfrom decorators import my_time_decorator\nfrom paul_resources import HealthcareSymbols, BestBetas, info\n\ndef get_total_return(df: 'df of prices'):\n #return prices_df_stock.head(1).iloc[0] / prices_df_stock.tail(1).iloc[0] - 1\n print(df.columns.tolist(), df.head(1), df.tail(1), sep=\"\\n\"*2)\n return df.head(1).iloc[0, 0] / df.tail(1).iloc[0, 0] - 1\n\ndef calc_HV(df: 'df of daily returns'):\n return df.dropna(axis=0, how='any').iloc[:, 0].std(ddof=0)*math.sqrt(252)\n\ndef get_sample_size(df: 'df of daily_returns'):\n return df.shape[0]\n \n@my_time_decorator\ndef alpha_df(df: 'df of prices', lookback):\n prices_df = df.head(lookback)\n #returns_df = daily_returns(prices_df).dropna(axis=0, how='any')\n returns_df = daily_returns(prices_df)\n #print(prices_df.isnull().values.ravel().sum())\n\n stocks = df.columns.values.tolist()\n total_returns = []\n HVs = []\n alpha_ratios = []\n adj_alpha_ratios = []\n sample_sizes = []\n indices = []\n betas = []\n times = []\n correlations = []\n \n #for stock in stocks:\n # result = prices_df[prices_df[stock].isnull()].index.tolist()\n # print(stock, \": \", result, sep='')\n \n for stock in stocks:\n prices_df_stock = prices_df[stock].dropna(axis=0, how='any').to_frame()\n daily_returns_df_stock = daily_returns(prices_df_stock).dropna(axis=0, how='any')\n\n # Calculate Adjusted Returns\n index = 'IBB'\n if stock == 'SPY':\n index = 'IWM'\n beta_object = Beta(stock, index, 500, ScrubParams(.075, .0125, .8))\n beta = beta_object.beta_value\n #beta_value = 0\n beta = BestBetas.loc[stock]['Beta']\n index = BestBetas.loc[stock]['Index']\n if stock == 'SPY':\n beta = 0\n adj_stock_line = StockLineBetaAdjusted(stock, lookback, beta, index)\n \n prices_df_stock = adj_stock_line.prices_df\n daily_returns_df_stock = adj_stock_line.adjusted_returns\n\n num_observations = len(daily_returns_df_stock.values.tolist())\n\n #total_return = prices_df_stock.head(1).iloc[0] / prices_df_stock.tail(1).iloc[0] - 1\n #print('HEREEE', total_move)\n #total_return = get_total_return(prices_df_stock)\n total_return = adj_stock_line.total_return\n total_returns.append(total_return)\n \n HV = calc_HV(daily_returns_df_stock)\n HVs.append(HV)\n\n sample_size = get_sample_size(daily_returns_df_stock)\n sample_sizes.append(sample_size)\n\n alpha_ratio = total_return / HV\n alpha_ratios.append(alpha_ratio)\n\n # Should the Time Adjustment be sqrt(time)?\n adj_alpha_ratio = alpha_ratio * math.sqrt(252/num_observations)\n adj_alpha_ratio = alpha_ratio * (252/num_observations)\n std_dev_over_time_period = HV*math.sqrt(num_observations / 252)\n adj_alpha_ratio = total_return / std_dev_over_time_period\n adj_alpha_ratios.append(adj_alpha_ratio)\n\n indices.append(index)\n betas.append(beta)\n\n correlation = beta_object.corr\n correlations.append(correlation)\n \n time = num_observations/252\n times.append(time)\n\n\n alpha_df_info = {'Stock': stocks,\n 'Total_Return': total_returns,\n 'HV': HVs,\n 'Alpha_Ratio': alpha_ratios,\n 'Adj_Alpha_Ratio': adj_alpha_ratios,\n 'Sample_Size': sample_sizes,\n 'Index': indices,\n 'Beta': betas,\n 'Correlation': correlations,\n 'Time': times\n }\n\n alpha_df = pd.DataFrame(alpha_df_info).set_index('Stock').loc[:, ['Total_Return',\n 'HV',\n 'Alpha_Ratio',\n 'Adj_Alpha_Ratio',\n 'Sample_Size',\n 'Index',\n 'Beta',\n 'Correlation',\n 'Time']].round(3)\n return alpha_df\n\nstocks = PriceTable.columns.values.tolist()\n#stocks = [i for i in stocks if i in {'SPY','IWM', 'QQQ', 'FB', 'NKTR', 'AAPL', 'NVDA'}]\nstocks = [i for i in stocks if i in HealthcareSymbols][0:1000]\n\nprices_df = PriceTable.loc[:, stocks].head(252)\nalpha_df = alpha_df(prices_df, 252)\nalpha_df = alpha_df[alpha_df.HV < .4]\n\nindustries = info.loc[:, 'Industry']\n\nalpha_df = alpha_df.join(industries, how='left')\nprint(alpha_df.sort_values(['Industry', 'Adj_Alpha_Ratio'], ascending=[True, False]).to_string())\n\ndef graph():\n values = alpha_df['Adj_Alpha_Ratio'].tolist()\n bins = np.arange(-5., 5.5, .5)\n \n plt.hist(values, bins, histtype = 'bar', rwidth=.8)\n \n plt.xlabel('Adj_Alpha_Ratio')\n plt.ylabel('Frequency')\n plt.title('S&P 500 Alpha Distribution')\n plt.legend()\n plt.show()\n\ngraph()\n\ndef get_probability_density(distribution, target, greater_than = True):\n i = 0\n if greater_than is True:\n for number in distribution:\n if number > target:\n i += 1\n else:\n for number in distribution:\n if number < target:\n i += 1\n return i / len(distribution)\n\n\n\nadj_alpha_ratios = alpha_df.loc[:, ['Adj_Alpha_Ratio']].values.tolist()\n\nfor i in np.arange(-3, 4, 1):\n if i >= 0:\n greater_than = True\n print_sym = \">\"\n else:\n greater_than = False\n print_sym = \"<\"\n \n density = get_probability_density(adj_alpha_ratios, i, greater_than)\n print(\"{}{:.1f} SD: {:.1f}%\".format(print_sym, i, density*100))\n","sub_path":"Old_Versions/alpha_oldR/alpha4.py","file_name":"alpha4.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"165111108","text":"# Learn Python Coding in 2020\n# By Jerry Garretson\n##########################\n\n#Clear the terminal screen\nimport os\nos.system('clear')\n\n##########################\n# DATA TYPES\n# Strings\n# Numbers\n# Lists\n# Tuples\n# Dictionaries\n# Boolean\n##########################\n\n\nfirst_name = 'Jerry'\nage = 38\nnames_list = [\"Jerry\", \"Brens\", \"George\"]\nnames_tupul = (\"Jerry\", \"Brens\", \"George\")\nfav_pizza = {\n\t\"John\": \"Pepperoni\",\n\t\"Bob\": \"Cheese\",\n\t\"Mary\": \"Mushroom\"\n\t}\nname = True\n\nprint(first_name)\nprint(age)\nprint(names_list)\nprint(names_tupul)\nprint(fav_pizza[\"Bob\"])\nprint(name)","sub_path":"version_control.py","file_name":"version_control.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"403947078","text":"import mock_db\nimport uuid\nfrom worker import worker_main\nfrom threading import Thread\n\ndef lock_is_free():\n \"\"\"\n CHANGE ME, POSSIBLY MY ARGS\n\n Return whether the lock is free\n \"\"\"\n\n return True\n\n\ndef attempt_run_worker(worker_hash, give_up_after, db, retry_interval):\n \"\"\"\n CHANGE MY IMPLEMENTATION, BUT NOT FUNCTION SIGNATURE\n\n Run the worker from worker.py by calling worker_main\n\n Args:\n worker_hash: a random string we will use as an id for the running worker\n give_up_after: if the worker has not run after this many seconds, give up\n db: an instance of MockDB\n retry_interval: continually poll the locking system after this many seconds\n until the lock is free, unless we have been trying for more\n than give_up_after seconds\n \"\"\"\n if lock_is_free():\n worker_main(worker_hash, db)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n DO NOT MODIFY\n\n Main function that runs the worker five times, each on a new thread\n We have provided hard-coded values for how often the worker should retry\n grabbing lock and when it should give up. Use these as you see fit, but\n you should not need to change them\n \"\"\"\n\n db = mock_db.DB()\n threads = []\n for _ in range(25):\n t = Thread(target=attempt_run_worker, args=(uuid.uuid1(), 2000, db, 0.1))\n threads.append(t)\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n","sub_path":"starter_code.py","file_name":"starter_code.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"498077505","text":"\"\"\"The application's model objects\"\"\"\nimport sqlalchemy as sa\nfrom sqlalchemy import orm\nfrom sqlalchemy.orm import clear_mappers\nfrom sqlalchemy.orm import relation, backref\n\nfrom librarycrm.model import meta\n\n\n#from librarycrm.model.meta import Session, Base\n\n\ndef init_model(engine):\n meta.Session.configure(bind=engine)\n meta.engine = engine\n\nmembers_table = sa.Table('members', meta.metadata,\n sa.Column('memberID', sa.types.Integer, primary_key=True),\n sa.Column('name', sa.types.String(20)),\n sa.Column('address', sa.types.String(50)),\n sa.Column('suburb', sa.types.String(50)),\n sa.Column('city', sa.types.String(50)))\n\nbooks_table = sa.Table('books', meta.metadata,\n sa.Column('bookID', sa.types.Integer, primary_key=True),\n sa.Column('title', sa.types.String(100)),\n sa.Column('author', sa.types.String(100)),\n sa.Column('status', sa.types.Boolean))\n\nissues_table = sa.Table('issues', meta.metadata,\n sa.Column('issueID', sa.types.Integer, primary_key=True),\n sa.Column('memberID', sa.types.Integer, sa.ForeignKey('members.memberID')),\n sa.Column('bookID', sa.types.Integer, sa.ForeignKey('books.bookID')),\n sa.Column('issueDate', sa.types.Date),\n sa.Column('dueDate', sa.types.Date),\n sa.Column('returned', sa.types.Boolean))\n\nclass Members(object):\n def __init__(self, name, address, suburb, city):\n self.name = name\n self.address = address\n self.suburb = suburb\n self.city = city\n\nclass Books(object):\n def __init__(self, title, author, status):\n self.title = title\n self.author = author\n self.status = status\n\nclass Issues(object):\n def __init__(self, memberID, bookID, issueDate, dueDate, returned):\n self.memberID = memberID\n self.bookID = bookID\n self.issueDate = issueDate\n self.dueDate = dueDate\n self.returned = returned\n\norm.mapper(Members, members_table)\norm.mapper(Books, books_table)\norm.mapper(Issues, issues_table, properties = {\n 'books': relation(Books, order_by='Books.bookID', backref='issues'),\n 'members': relation(Members),\n})\n","sub_path":"librarycrm/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"303330688","text":"def time_this(original_function):\n def new_function(*args, **kwargs):\n import datetime\n before = datetime.datetime.now()\n x = original_function(*args, **kwargs)\n after = datetime.datetime.now()\n print(\"Elapsed Time = {0}\".format(after - before))\n return x\n\n return new_function\n\n\n@time_this\ndef func_a(stuff):\n import time\n time.sleep(3)\n print(\"ai\")\n\n\nfunc_a(1)","sub_path":"codementor/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"626049301","text":"import random\n\ndoors = [0, 1, 2]\ngifts = ['goat', 'goat', 'car']\n\n\ndef game_initialize():\n random.shuffle(doors)\n random.shuffle(gifts)\n dic = dict(zip(doors, gifts))\n # print(dic)\n return dic\n\n\n# game_initialize()\n\ndef game_body(dictionary):\n print('===================================')\n '''\n 选手选择第一扇门\n '''\n first_key = input('Choose a door to open:')\n first_value = dictionary[int(first_key)]\n # print(first_value)\n\n '''\n 主持人打开有goat的一扇门\n '''\n del [dictionary[int(first_key)]]\n # print(dictionary)\n goat_key = list(dictionary.keys())[list(dictionary.values()).index('goat')]\n print('\"goat\" behind the door ' + str(goat_key))\n\n '''\n 选手选择是否更换为第三扇门\n '''\n del [dictionary[int(goat_key)]]\n # print(dictionary)\n second_key = dictionary.keys()\n # print(list(second_key)[0])\n choice = input('Switch to ' + str(list(second_key)[0]) + '?(y/n)')\n if (choice == 'y'):\n second_value = dictionary[list(second_key)[0]]\n if (second_value == 'car'):\n print('You Win!')\n else:\n print('You Lose!')\n if (choice == 'n'):\n if (first_value == 'car'):\n print('You Win!')\n else:\n print('You Lose!')\n\n return\n\n\ngame_body(game_initialize())\nwhile (input('Do you want to try once more?(y/n)') == 'y'):\n game_body(game_initialize())\n\n","sub_path":"experiment4/mendebell.py","file_name":"mendebell.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"505023504","text":"\"\"\"This file makes the vote dataframes as well as\nthe unique lawmakers dictionary \"\"\"\nimport re\nimport pickle\nfrom sys import argv\nfrom collections import defaultdict\nimport subprocess as sp\nimport resource_paths as rp\nimport pandas as pd\n\nNAME, CHAMBER=argv\n\ndef separate_by_congress(votefp):\n congresses = [str(num) for num in xrange(109,116)]\n links_list = defaultdict(list)\n\n for congress in congresses:\n congfind = re.compile(congress)\n for path in votefp:\n if congfind.search(path) is not None:\n links_list[congress].append(path)\n\n return links_list\n\n\ndef year_to_cong(year):\n ytc = {2005:109, 2006:109, 2008:110, 2009:111, 2010:111, 2011:112,\n 2012:112, 2014:113, 2015:114, 2016:114, 2017:115}\n\n return ytc[year]\n\n\n\ndef create_congress_dflst(linkslist, house_initial):\n dfs = []\n for lst in linkslist:\n cur_cong_votes =[]\n years=[]\n for link in linkslist[lst]:\n with open(link, \"rb\") as f:\n df = pickle.load(f)\n df = reload_without_dupes(df,link)\n df, year= append_year(df, link, house_initial)\n cur_cong_votes.append(df)\n years.append(year)\n\n if len(cur_cong_votes) > 1:\n cur_cong_votes[1] = cur_cong_votes[1].iloc[:,4:]\n\n final_df = pd.concat(cur_cong_votes, axis=1)\n final_df[\"congress\"]=year_to_cong(years[0])\n\n dfs.append(final_df)\n\n return dfs\n\ndef append_year(df, link, house_initial):\n find_year = re.compile(r\"[0-9]{4}\")\n year = find_year.search(link).group(0)\n new_name = year + house_initial + \"-\"\n df = df.add_prefix(new_name)\n\n return df, int(year)\n\n\ndef reload_without_dupes(df, fp):\n \"\"\"Pandas bundles duplicates in a dataframe...\n This behavior (and the existance of duplicates)\n was unexpected so to avoid scraping the data again.\n This is the workaround\"\"\"\n fp = fp[:-4] + \".csv\"\n df.to_csv(fp, encoding='utf-8', sep=',')\n df = pd.read_csv(fp, encoding='utf-8', index_col=0, mangle_dupe_cols=True, sep=',')\n\n sp.call([\"rm\", fp])\n\n return df\n\n\ndef unique_lawmakers(votes):\n \"\"\"Makes a set with all of the lawmakers' IDs\"\"\"\n unique_l = defaultdict(set)\n\n for df in votes:\n for lawmaker in df.index.values.tolist():\n congress = int(df[\"congress\"].iloc[0])\n unique_l[lawmaker].add(congress)\n\n\n return unique_l\n\n\nif __name__ == '__main__':\n votefp = rp.get_all_dfs(CHAMBER+\"vote\")\n\n linkslist = separate_by_congress(votefp)\n\n dfs = create_congress_dflst(linkslist, CHAMBER)\n\n unique = unique_lawmakers(dfs)\n\n with open(\"./\"+CHAMBER+\"votes_p_congress.pkl\", \"wb\") as f:\n pickle.dump(dfs, f)\n\n with open(\"./\"+CHAMBER+\"_lawmakers.pkl\", \"wb\") as f:\n pickle.dump(unique, f)\n\n","sub_path":"src/datasets-building/make_vote_df.py","file_name":"make_vote_df.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"389449385","text":"import os\nimport os.path\nimport glob\nimport fnmatch # pattern matching\nimport numpy as np\nfrom numpy import linalg as LA\nfrom random import choice\nfrom PIL import Image\nimport torch\nimport torch.utils.data as data\nimport cv2\nfrom dataloaders import transforms\nfrom dataloaders.pose_estimator import get_pose_pnp\n\ninput_options = ['d', 'rgb', 'rgbd', 'g', 'gd']\n\ndef load_calib():\n \"\"\"\n Temporarily hardcoding the calibration matrix using calib file from 2011_09_26\n \"\"\"\n calib = open(\"dataloaders/calib_cam_to_cam.txt\", \"r\")\n lines = calib.readlines()\n P_rect_line = lines[25]\n\n Proj_str = P_rect_line.split(\":\")[1].split(\" \")[1:]\n Proj = np.reshape(np.array([float(p) for p in Proj_str]),(3,4)).astype(np.float32)\n K = Proj[:3,:3] # camera matrix\n\n # note: we will take the center crop of the images during augmentation\n # that changes the optical centers, but not focal lengths\n K[0,2] = K[0,2] - 13 # from width = 1242 to 1216, with a 13-pixel cut on both sides\n K[1,2] = K[1,2] - 11.5 # from width = 375 to 352, with a 11.5-pixel cut on both sides\n return K\n\nroot_d = os.path.join('..', 'data', 'kitti_depth')\nroot_rgb = os.path.join('..', 'data', 'kitti_rgb')\ndef get_paths_and_transform(split, args):\n assert (args.use_d or args.use_rgb or args.use_g), 'no proper input selected'\n\n if split == \"train\":\n transform = train_transform\n glob_gt = \"train/*_sync/proj_depth/groundtruth/image_0[2,3]/*.png\"\n pattern_d = (\"groundtruth\",\"velodyne_raw\")\n def get_rgb_paths(p):\n ps = p.split('/')\n pnew = '/'.join([root_rgb]+ps[-6:-4]+ps[-2:-1]+['data']+ps[-1:])\n return pnew\n elif split == \"val\":\n if args.val == \"full\":\n transform = val_transform\n glob_gt = \"val/*_sync/proj_depth/groundtruth/image_0[2,3]/*.png\"\n pattern_d = (\"groundtruth\",\"velodyne_raw\")\n def get_rgb_paths(p):\n ps = p.split('/')\n pnew = '/'.join([root_rgb]+ps[-6:-4]+ps[-2:-1]+['data']+ps[-1:])\n return pnew\n elif args.val == \"select\":\n transform = no_transform\n glob_gt = \"val_selection_cropped/groundtruth_depth/*.png\"\n pattern_d = (\"groundtruth_depth\",\"velodyne_raw\")\n def get_rgb_paths(p):\n return p.replace(\"groundtruth_depth\",\"image\")\n elif split == \"test_completion\":\n transform = no_transform\n glob_gt = None #\"test_depth_completion_anonymous/\"\n base = \"/test_depth_completion_anonymous/\"\n glob_d = root_d+base+\"/velodyne_raw/*.png\"\n glob_rgb = root_d+base+\"/image/*.png\"\n elif split == \"test_prediction\":\n transform = no_transform\n glob_gt = None #\"test_depth_completion_anonymous/\"\n base = \"/test_depth_prediction_anonymous/\"\n glob_d = root_d+base+\"/velodyne_raw/*.png\"\n glob_rgb = root_d+base+\"/image/*.png\"\n else:\n raise ValueError(\"Unrecognized split \"+str(split))\n\n if glob_gt is not None:\n glob_gt = os.path.join(root_d,glob_gt)\n paths_gt = sorted(glob.glob(glob_gt))\n paths_d = [p.replace(pattern_d[0],pattern_d[1]) for p in paths_gt]\n paths_rgb = [get_rgb_paths(p) for p in paths_gt]\n else: # test and only has d or rgb\n paths_rgb = sorted(glob.glob(glob_rgb))\n paths_gt = [None]*len(paths_rgb)\n if split == \"test_prediction\":\n paths_d = [None]*len(paths_rgb) # test_prediction has no sparse depth\n else:\n paths_d = sorted(glob.glob(glob_d))\n\n if len(paths_d) == 0 and len(paths_rgb) == 0 and len(paths_gt) == 0:\n raise(RuntimeError(\"Found 0 images in data folders\"))\n if len(paths_d) == 0 and args.use_d:\n raise(RuntimeError(\"Requested sparse depth but none was found\"))\n if len(paths_rgb) == 0 and args.use_rgb:\n raise(RuntimeError(\"Requested rgb images but none was found\"))\n if len(paths_rgb) == 0 and args.use_g:\n raise(RuntimeError(\"Requested gray images but no rgb was found\"))\n if len(paths_rgb) != len(paths_d) or len(paths_rgb) != len(paths_gt):\n raise(RuntimeError(\"Produced different sizes for datasets\"))\n\n paths = {\"rgb\":paths_rgb, \"d\":paths_d, \"gt\":paths_gt}\n return paths, transform\n\ndef rgb_read(filename):\n assert os.path.exists(filename), \"file not found: {}\".format(filename)\n img_file = Image.open(filename)\n # rgb_png = np.array(img_file, dtype=float) / 255.0 # scale pixels to the range [0,1]\n rgb_png = np.array(img_file, dtype='uint8') # in the range [0,255]\n img_file.close()\n return rgb_png\n\ndef depth_read(filename):\n # loads depth map D from png file\n # and returns it as a numpy array,\n # for details see readme.txt\n assert os.path.exists(filename), \"file not found: {}\".format(filename)\n img_file = Image.open(filename)\n depth_png = np.array(img_file, dtype=int)\n img_file.close()\n # make sure we have a proper 16bit depth map here.. not 8bit!\n assert np.max(depth_png) > 255, \\\n \"np.max(depth_png)={}, path={}\".format(np.max(depth_png),filename)\n\n depth = depth_png.astype(np.float) / 256.\n # depth[depth_png == 0] = -1.\n depth = np.expand_dims(depth,-1)\n return depth\n\noheight, owidth = 352, 1216\n\ndef drop_depth_measurements(depth, prob_keep):\n mask = np.random.binomial(1, prob_keep, depth.shape)\n depth *= mask\n return depth\n\ndef train_transform(rgb, sparse, target, rgb_near, args):\n # s = np.random.uniform(1.0, 1.5) # random scaling\n # angle = np.random.uniform(-5.0, 5.0) # random rotation degrees\n do_flip = np.random.uniform(0.0, 1.0) < 0.5 # random horizontal flip\n\n transform_geometric = transforms.Compose([\n # transforms.Rotate(angle),\n # transforms.Resize(s),\n transforms.BottomCrop((oheight, owidth)),\n transforms.HorizontalFlip(do_flip)\n ])\n if sparse is not None:\n sparse = transform_geometric(sparse)\n target = transform_geometric(target)\n if rgb is not None:\n brightness = np.random.uniform(max(0, 1 - args.jitter), 1 + args.jitter)\n contrast = np.random.uniform(max(0, 1 - args.jitter), 1 + args.jitter)\n saturation = np.random.uniform(max(0, 1 - args.jitter), 1 + args.jitter)\n transform_rgb = transforms.Compose([\n transforms.ColorJitter(brightness, contrast, saturation, 0),\n transform_geometric\n ])\n rgb = transform_rgb(rgb)\n if rgb_near is not None:\n rgb_near = transform_rgb(rgb_near)\n # sparse = drop_depth_measurements(sparse, 0.9)\n\n return rgb, sparse, target, rgb_near\n\ndef val_transform(rgb, sparse, target, rgb_near, args):\n transform = transforms.Compose([\n transforms.BottomCrop((oheight, owidth)),\n ])\n if rgb is not None:\n rgb = transform(rgb)\n if sparse is not None:\n sparse = transform(sparse)\n if target is not None:\n target = transform(target)\n if rgb_near is not None:\n rgb_near = transform(rgb_near)\n return rgb, sparse, target, rgb_near\n\ndef no_transform(rgb, sparse, target, rgb_near, args):\n return rgb, sparse, target, rgb_near\n\nto_tensor = transforms.ToTensor()\nto_float_tensor = lambda x: to_tensor(x).float()\n\ndef handle_gray(rgb, args):\n if rgb is None:\n return None, None\n if not args.use_g:\n return rgb, None\n else:\n img = np.array(Image.fromarray(rgb).convert('L'))\n img = np.expand_dims(img,-1)\n if not args.use_rgb:\n rgb_ret = None\n else:\n rgb_ret = rgb\n return rgb_ret, img\n\ndef get_rgb_near(path, args):\n assert path is not None, \"path is None\"\n\n def extract_frame_id(filename):\n head, tail = os.path.split(filename)\n number_string = tail[0:tail.find('.')]\n number = int(number_string)\n return head, number\n\n def get_nearby_filename(filename, new_id):\n head, _ = os.path.split(filename)\n new_filename = os.path.join(head, '%010d.png' % new_id)\n return new_filename\n\n head, number = extract_frame_id(path)\n count = 0\n max_frame_diff = 3\n candidates = [i-max_frame_diff for i in range(max_frame_diff*2+1) if i-max_frame_diff!=0]\n while True:\n random_offset = choice(candidates)\n path_near = get_nearby_filename(path, number+random_offset)\n if os.path.exists(path_near):\n break\n assert count < 20, \"cannot find a nearby frame in 20 trials for {}\".format(path_rgb_tgt)\n\n return rgb_read(path_near)\n\nclass KittiDepth(data.Dataset):\n \"\"\"A data loader for the Kitti dataset\n \"\"\"\n def __init__(self, split, args):\n self.args = args\n self.split = split\n paths, transform = get_paths_and_transform(split, args)\n self.paths = paths\n self.transform = transform\n self.K = load_calib()\n self.threshold_translation = 0.1\n\n def __getraw__(self, index):\n rgb = rgb_read(self.paths['rgb'][index]) if \\\n (self.paths['rgb'][index] is not None and (self.args.use_rgb or self.args.use_g)) else None\n sparse = depth_read(self.paths['d'][index]) if \\\n (self.paths['d'][index] is not None and self.args.use_d) else None\n target = depth_read(self.paths['gt'][index]) if \\\n self.paths['gt'][index] is not None else None\n rgb_near = get_rgb_near(self.paths['rgb'][index], self.args) if \\\n self.split == 'train' and self.args.use_pose else None\n return rgb, sparse, target, rgb_near\n\n def __getitem__(self, index):\n rgb, sparse, target, rgb_near = self.__getraw__(index)\n rgb, sparse, target, rgb_near = self.transform(rgb,sparse, target, rgb_near, self.args)\n r_mat, t_vec = None, None\n if self.split == 'train' and self.args.use_pose:\n success, r_vec, t_vec = get_pose_pnp(rgb, rgb_near, sparse, self.K)\n # discard if translation is too small\n success = success and LA.norm(t_vec) > self.threshold_translation\n if success:\n r_mat, _ = cv2.Rodrigues(r_vec)\n else:\n # return the same image and no motion when PnP fails\n rgb_near = rgb\n t_vec = np.zeros((3,1))\n r_mat = np.eye(3)\n\n rgb, gray = handle_gray(rgb, self.args)\n candidates = {\"rgb\":rgb, \"d\":sparse, \"gt\":target, \\\n \"g\":gray, \"r_mat\":r_mat, \"t_vec\":t_vec, \"rgb_near\":rgb_near}\n items = {key:to_float_tensor(val) for key, val in candidates.items() if val is not None}\n\n return items\n\n def __len__(self):\n return len(self.paths['gt'])\n\n\ndef get_dataset_path(base_dir, setname='train'):\n \"\"\"\n get dataset path according to setname\n :param base_dir: basic data dir\n :param setname: train, val, seval, test\n :return: lidar_dir, depth_dir, rgb_dir\n \"\"\"\n\n import os\n if setname == 'train':\n lidar_dir = os.path.join(base_dir, 'data_depth_velodyne', 'train')\n depth_dir = os.path.join(base_dir, 'data_depth_annotated', 'train')\n rgb_dir = os.path.join(base_dir, 'raw')\n elif setname == 'val':\n lidar_dir = os.path.join(base_dir, 'data_depth_velodyne', 'val')\n depth_dir = os.path.join(base_dir, 'data_depth_annotated', 'val')\n rgb_dir = os.path.join(base_dir, 'raw')\n elif setname == 'selval':\n lidar_dir = os.path.join(base_dir, 'val_selection_cropped', 'velodyne_raw')\n depth_dir = os.path.join(base_dir, 'val_selection_cropped', 'groundtruth_depth')\n rgb_dir = os.path.join(base_dir, 'val_selection_cropped', 'image')\n elif setname == 'test':\n lidar_dir = os.path.join(base_dir, 'test_depth_completion_anonymous', 'velodyne_raw')\n depth_dir = os.path.join(base_dir, 'test_depth_completion_anonymous', 'velodyne_raw')\n rgb_dir = os.path.join(base_dir, 'test_depth_completion_anonymous', 'image')\n else:\n raise ValueError(\"Unrecognized setname \"+str(setname))\n\n return lidar_dir, depth_dir, rgb_dir\n\n\ndef get_transform(mode):\n if mode == 'train':\n transform = train_transform\n elif mode == 'eval':\n transform = val_transform\n else:\n raise ValueError(\"Unrecognized mode \"+str(mode))\n\n return transform\n\n\nclass KittiDataset(data.Dataset):\n \"\"\"\n origin format as original\n \"\"\"\n def __init__(self, base_dir, mode, setname, args):\n \"\"\"\n :param base_dir:\n :param setname:\n :param transform:\n :param return_idx:\n :param crop:\n \"\"\"\n self.dataset_name = 'kitti'\n\n self.mode = mode\n self.setname = setname\n self.args = args\n\n self.base_dir = base_dir\n lidar_dir, depth_dir, rgb_dir = self.get_paths(base_dir)\n self.lidar_dir = lidar_dir\n self.depth_dir = depth_dir\n self.rgb_dir = rgb_dir\n\n self.transform = get_transform(mode)\n\n self.crop_h = 352\n self.crop_w = 1216\n\n # sparsity\n self.use_sparsity = False\n self.sparsity_ratio = 0.2\n\n self.crop = True\n\n self.lidars = list(sorted(glob.iglob(self.lidar_dir + \"/**/*.png\", recursive=True)))\n\n def __len__(self):\n return len(self.lidars)\n\n def __getitem__(self, index):\n \"\"\"\n :param index:\n :return:\n \"\"\"\n return self.getitem(index)\n\n def get_file_name(self, item):\n lidar_path = self.lidars[item]\n file_names = lidar_path.split('/')\n return file_names[-1]\n\n def get_paths(self, base_dir):\n return get_dataset_path(base_dir, setname=self.setname)\n\n def split_selval_filename(self, filename):\n mid = 'velodyne_raw_'\n name_split = filename.split(mid)\n pre, pos = name_split[0], name_split[1]\n return pre, mid, pos\n\n def get_depth_path(self, lidar_path):\n depth_path = None\n if self.setname == 'train' or self.setname == 'val':\n file_names = lidar_path.split('/')\n depth_path = os.path.join(self.depth_dir, *file_names[-5:-3], 'groundtruth', *file_names[-2:])\n elif self.setname == 'test':\n file_names = lidar_path.split('/')\n depth_path = os.path.join(self.depth_dir, file_names[-1])\n elif self.setname == 'selval':\n file_names = lidar_path.split('/')\n file_name = file_names[-1]\n pre, mid, pos = self.split_selval_filename(file_name)\n depth_file_name = pre + \"groundtruth_depth_\" + pos\n depth_path = os.path.join(self.depth_dir, depth_file_name)\n return depth_path\n\n def get_rgb_path(self, lidar_path):\n rgb_path = None\n if self.setname == 'train' or self.setname == 'val':\n file_names = lidar_path.split('/')\n rgb_path = os.path.join(self.rgb_dir, file_names[-5].split('_drive')[0], file_names[-5],\n file_names[-2], 'data', file_names[-1])\n elif self.setname == 'test':\n file_names = lidar_path.split('/')\n rgb_path = os.path.join(self.rgb_dir, file_names[-1])\n elif self.setname == 'selval':\n file_names = lidar_path.split('/')\n file_name = file_names[-1]\n pre, mid, pos = self.split_selval_filename(file_name)\n rgb_file_name = pre + \"image_\" + pos\n rgb_path = os.path.join(self.rgb_dir, rgb_file_name)\n return rgb_path\n\n def get_raw_data(self, lidar_path):\n depth_path = self.get_depth_path(lidar_path)\n rgb_path = self.get_rgb_path(lidar_path)\n assert(rgb_path != '')\n\n depth = self.read_depth(depth_path)\n lidar = self.read_depth(lidar_path)\n rgb = self.read_rgb(rgb_path)\n\n if self.use_sparsity:\n rand_value = np.random.rand(*lidar.shape)\n rand_mask = rand_value <= self.sparsity_ratio\n lidar = lidar * rand_mask\n\n return rgb, lidar, depth\n\n def crop_data(self, data):\n w = data.shape[1]\n lp = (w - self.crop_w) // 2\n return data[-self.crop_h:, lp:lp + self.crop_w, :]\n\n def deal_data(self, rgb, lidar, depth):\n depth = np.expand_dims(depth, axis=2)\n lidar = np.expand_dims(lidar, axis=2)\n\n if self.transform:\n rgb, lidar, depth, rgb_ = self.transform(rgb, lidar, depth, rgb, self.args)\n\n gray = np.array(Image.fromarray(rgb).convert('L'))\n gray = np.expand_dims(gray, -1)\n\n if self.crop:\n rgb = self.crop_data(rgb)\n lidar = self.crop_data(lidar)\n depth = self.crop_data(depth)\n gray = self.crop_data(gray)\n\n return rgb.astype(np.float32), lidar.astype(np.float32), depth.astype(np.float32), gray.astype(np.float32)\n\n def get_ori_item(self, index):\n lidar_path = self.lidars[index]\n rgb, lidar, depth = self.get_raw_data(lidar_path)\n\n out = (rgb, lidar, depth)\n\n return out\n\n def get_ori_shape(self, index):\n lidar_path = self.lidars[index]\n return self._get_ori_shape(lidar_path)\n\n def _get_ori_shape(self, lidar_path):\n import magic\n import re\n\n info = magic.from_file(lidar_path)\n size_info = re.search('(\\d+) x (\\d+)', info).groups()\n width = int(size_info[0])\n height = int(size_info[1])\n return height, width\n\n def getitem(self, index):\n lidar_path = self.lidars[index]\n rgb, lidar, depth = self.get_raw_data(lidar_path)\n\n # verify shape size\n ori_shape = lidar.shape\n assert ori_shape == depth.shape == rgb.shape[0:2] == self.get_ori_shape(index)\n\n rgb, lidar, depth, gray = self.deal_data(rgb, lidar, depth)\n\n index_3d = np.zeros((1, 1, 1))\n index_3d[0, 0, 0] = index\n\n candidates = {\"rgb\":rgb, \"d\":lidar, \"gt\":depth, \"g\":gray, \"index\":index_3d, \"r_mat\":None, \"t_vec\":None, \"rgb_near\":None}\n items = {key:to_float_tensor(val) for key, val in candidates.items() if val is not None}\n\n return items\n\n def read_rgb(self, path):\n img = np.array(Image.open(path).convert('RGB'), dtype=np.uint8)\n return img\n\n def read_depth(self, path):\n depth_png = np.array(Image.open(path), dtype=np.uint16)\n # make sure we have a proper 16bit depth map here.. not 8bit!\n assert (np.max(depth_png) > 255)\n depth_image = (depth_png / 256.).astype(np.float32)\n # depth_image = self.mask_depth_image(depth_image, self.depth_start, self.depth_end)\n return depth_image\n\n\nclass VKittiDataset(data.Dataset):\n \"\"\"\n origin format as original\n \"\"\"\n def __init__(self, base_dir, mode, args, setname='train', subset='clone'):\n \"\"\"\n :param base_dir:\n :param setname:\n :param transform:\n :param return_seg:\n :param return_idx:\n :param use_stereo:\n :param crop:\n :param compose_depth:\n :param split_depth: True or False, if True, split depth into multiple channels according to depth\n :param split_mode: single_offset or multiple_offset, output single channel offset or multiple channel offset\n \"\"\"\n self.mode = mode\n self.setname = setname\n self.subset = subset\n self.args = args\n\n self.base_dir = base_dir\n lidar_dir, depth_dir, rgb_dir = self.get_paths(base_dir)\n self.lidar_dir = lidar_dir\n self.depth_dir = depth_dir\n self.rgb_dir = rgb_dir\n\n self.transform = get_transform(mode)\n\n self.crop_h = 352\n self.crop_w = 1216\n\n # sparsity\n self.use_sparsity = False\n self.sparsity_ratio = 0.2\n\n self.crop = True\n\n self.lidars = list(sorted(glob.iglob(self.lidar_dir + \"/**/\" + subset + \"/*.png\", recursive=True)))\n\n def __len__(self):\n return len(self.lidars)\n\n def __getitem__(self, index):\n \"\"\"\n :param index:\n :return:\n \"\"\"\n return self.getitem(index)\n\n def get_file_name(self, item):\n lidar_path = self.lidars[item]\n file_names = lidar_path.split('/')\n return file_names[-1]\n\n def get_paths(self, base_dir):\n \"\"\"\n get dataset path according to setname\n :param base_dir: basic data dir\n :param setname: train, val, seval, test\n :param use_compose_depth: use left-right composed depth as ground-truth or not\n :return: lidar_dir, depth_dir, rgb_dir\n \"\"\"\n if self.setname == 'train':\n lidar_dir = os.path.join(base_dir, 'train', 'sparse_lidar')\n depth_dir = os.path.join(base_dir, 'train', 'ka_depth')\n rgb_dir = os.path.join(base_dir, 'train', 'rgb')\n elif self.setname == 'test':\n lidar_dir = os.path.join(base_dir, 'test', 'sparse_lidar')\n depth_dir = os.path.join(base_dir, 'test', 'ka_depth')\n rgb_dir = os.path.join(base_dir, 'test', 'rgb')\n else:\n raise Exception(\"setname {} does not exist!\".format(self.setname))\n\n return lidar_dir, depth_dir, rgb_dir\n\n def get_rgb_path(self, lidar_path):\n file_names = lidar_path.split('/')\n rgb_path = os.path.join(self.rgb_dir, *file_names[-3:])\n return rgb_path\n\n def get_depth_path(self, lidar_path):\n file_names = lidar_path.split('/')\n depth_path = os.path.join(self.depth_dir, *file_names[-3:])\n return depth_path\n\n def get_raw_data(self, lidar_path):\n depth_path = self.get_depth_path(lidar_path)\n rgb_path = self.get_rgb_path(lidar_path)\n assert(rgb_path != '')\n\n depth = self.read_depth(depth_path)\n lidar = self.read_depth(lidar_path)\n rgb = self.read_rgb(rgb_path)\n\n if self.use_sparsity:\n rand_value = np.random.rand(*lidar.shape)\n rand_mask = rand_value <= self.sparsity_ratio\n lidar = lidar * rand_mask\n\n return rgb, lidar, depth\n\n def set_top_zero(self, data):\n # only keep values in 256 pixels from bottom\n data[0:-256, :, :] = 0\n\n return data\n\n def deal_data(self, rgb, lidar, depth):\n depth = np.expand_dims(depth, axis=2)\n lidar = np.expand_dims(lidar, axis=2)\n\n if self.transform:\n rgb, lidar, depth, rgb_ = self.transform(rgb, lidar, depth, rgb, self.args)\n\n gray = np.array(Image.fromarray(rgb).convert('L'))\n gray = np.expand_dims(gray, -1)\n\n if self.crop:\n lidar = self.set_top_zero(lidar)\n depth = self.set_top_zero(depth)\n\n return rgb.astype(np.float32), lidar.astype(np.float32), depth.astype(np.float32), gray.astype(np.float32)\n\n def get_ori_item(self, index):\n lidar_path = self.lidars[index]\n rgb, lidar, depth = self.get_raw_data(lidar_path)\n\n out = (rgb, lidar, depth)\n\n return out\n\n def get_ori_shape(self, index):\n lidar_path = self.lidars[index]\n return self._get_ori_shape(lidar_path)\n\n def _get_ori_shape(self, lidar_path):\n import magic\n import re\n\n info = magic.from_file(lidar_path)\n size_info = re.search('(\\d+) x (\\d+)', info).groups()\n width = int(size_info[0])\n height = int(size_info[1])\n return height, width\n\n def getitem(self, index):\n lidar_path = self.lidars[index]\n rgb, lidar, depth = self.get_raw_data(lidar_path)\n\n # verify shape size\n ori_shape = lidar.shape\n assert ori_shape == depth.shape == rgb.shape[0:2] == self.get_ori_shape(index)\n\n rgb, lidar, depth, gray = self.deal_data(rgb, lidar, depth)\n\n index_3d = np.zeros((1, 1, 1))\n index_3d[0, 0, 0] = index\n\n candidates = {\"rgb\":rgb, \"d\":lidar, \"gt\":depth, \"g\":gray, \"index\":index_3d, \"r_mat\":None, \"t_vec\":None, \"rgb_near\":None}\n items = {key:to_float_tensor(val) for key, val in candidates.items() if val is not None}\n\n return items\n\n def read_rgb(self, path):\n img = np.array(Image.open(path).convert('RGB'), dtype=np.uint8)\n return img\n\n def read_depth(self, path):\n depth_png = np.array(Image.open(path), dtype=np.uint16)\n # make sure we have a proper 16bit depth map here.. not 8bit!\n assert (np.max(depth_png) > 100)\n depth_image = (depth_png / 100.).astype(np.float32)\n # depth_image = self.mask_depth_image(depth_image, self.depth_start, self.depth_end)\n return depth_image\n\n\nclass OurDataset(data.Dataset):\n \"\"\"\n origin format as original\n \"\"\"\n def __init__(self, base_dir, mode, setname, args):\n \"\"\"\n :param base_dir:\n :param setname:\n \"\"\"\n self.base_dir = base_dir\n self.mode = mode\n self.setname = setname\n self.args = args\n\n lidar_dir, depth_dir, rgb_dir = self.get_paths(base_dir)\n self.lidar_dir = lidar_dir\n self.depth_dir = depth_dir\n self.rgb_dir = rgb_dir\n\n self.transform = get_transform(mode)\n\n self.crop_h = 352\n self.crop_w = 1216\n\n self.crop = True\n\n self.lidars = list(sorted(glob.iglob(self.lidar_dir + \"/**/*.png\", recursive=True)))\n\n def get_file_name(self, item):\n lidar_path = self.lidars[item]\n file_names = lidar_path.split('/')\n return file_names[-1]\n\n def __len__(self):\n return len(self.lidars)\n\n def __getitem__(self, index):\n \"\"\"\n :param index:\n :return:\n \"\"\"\n return self.getitem(index)\n\n def get_paths(self, base_dir):\n lidar_dir = os.path.join(base_dir, 'lidar')\n depth_dir = os.path.join(base_dir, 'depth')\n rgb_dir = os.path.join(base_dir, 'image')\n\n return lidar_dir, depth_dir, rgb_dir\n\n def get_depth_path(self, lidar_path):\n file_names = lidar_path.split('/')\n depth_path = os.path.join(self.depth_dir, file_names[-1])\n return depth_path\n\n def get_rgb_path(self, lidar_path):\n file_names = lidar_path.split('/')\n rgb_path = os.path.join(self.rgb_dir, file_names[-1])\n # rgb_path = os.path.join(self.rgb_dir, file_names[-1][:-4] + \".jpg\")\n return rgb_path\n\n def get_raw_data(self, lidar_path):\n depth_path = self.get_depth_path(lidar_path)\n rgb_path = self.get_rgb_path(lidar_path)\n assert(rgb_path != '')\n\n depth = self.read_depth(depth_path)\n lidar = self.read_depth(lidar_path)\n rgb = self.read_rgb(rgb_path)\n\n return rgb, lidar, depth\n\n def crop_data(self, data):\n w = data.shape[1]\n lp = (w - self.crop_w) // 2\n return data[-self.crop_h:, lp:lp + self.crop_w, :]\n\n def deal_data(self, rgb, lidar, depth):\n depth = np.expand_dims(depth, axis=2)\n lidar = np.expand_dims(lidar, axis=2)\n\n gray = np.array(Image.fromarray(rgb).convert('L'))\n gray = np.expand_dims(gray, -1)\n\n if self.transform:\n rgb, lidar, depth = self.transform(rgb, lidar, depth)\n\n # crop to size(input_h, input_w) at the bottom and right of the image\n if self.crop:\n rgb = self.crop_data(rgb)\n lidar = self.crop_data(lidar)\n depth = self.crop_data(depth)\n gray = self.crop_data(gray)\n\n return rgb.astype(np.float32), lidar.astype(np.float32), depth.astype(np.float32), gray.astype(np.float32)\n\n def get_ori_shape(self, index):\n lidar_path = self.lidars[index]\n return self._get_ori_shape(lidar_path)\n\n def _get_ori_shape(self, lidar_path):\n import magic\n import re\n\n info = magic.from_file(lidar_path)\n size_info = re.search('(\\d+) x (\\d+)', info).groups()\n width = int(size_info[0])\n height = int(size_info[1])\n return height, width\n\n def getitem(self, index):\n lidar_path = self.lidars[index]\n rgb, lidar, depth = self.get_raw_data(lidar_path)\n\n # verify shape size\n ori_shape = lidar.shape\n assert ori_shape == depth.shape == rgb.shape[0:2] == self.get_ori_shape(index)\n\n rgb, lidar, depth, gray = self.deal_data(rgb, lidar, depth)\n\n index_3d = np.zeros((1, 1, 1))\n index_3d[0, 0, 0] = index\n\n candidates = {\"rgb\":rgb, \"d\":lidar, \"gt\":depth, \"g\":gray, \"index\": index_3d, \"r_mat\":None, \"t_vec\":None, \"rgb_near\":None}\n items = {key:to_float_tensor(val) for key, val in candidates.items() if val is not None}\n\n return items\n\n def read_rgb(self, path):\n img = np.array(Image.open(path).convert('RGB'), dtype=np.uint8)\n return img\n\n def read_depth(self, path):\n depth_png = np.array(Image.open(path), dtype=np.uint16)\n # make sure we have a proper 16bit depth map here.. not 8bit!\n assert (np.max(depth_png) > 255)\n depth_image = (depth_png / 256.).astype(np.float32)\n # depth_image = self.mask_depth_image(depth_image, self.depth_start, self.depth_end)\n return depth_image\n\n\nclass NuScenesDataset(OurDataset):\n def __init__(self, base_dir, mode, setname, args):\n super().__init__(base_dir=base_dir, mode=mode, setname=setname, args=args)\n\n def get_paths(self, base_dir):\n lidar_dir = os.path.join(base_dir, 'lidar')\n depth_dir = os.path.join(base_dir, 'lidar_agg')\n rgb_dir = os.path.join(base_dir, 'image')\n\n return lidar_dir, depth_dir, rgb_dir\n\n","sub_path":"dataloaders/kitti_loader.py","file_name":"kitti_loader.py","file_ext":"py","file_size_in_byte":29345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"340755964","text":"import string\nfrom utilities import XLUtils\nfrom utilities.readProperties import ReadConfig\n\nclass Test_WorkingFile:\n\n\n def test_FileWrite(self,setup):\n self.driver=setup\n file = ReadConfig.getFilePath()\n print(\"File path is: \"+str(file))\n Summary=\"Manas\"\n i=2\n XLUtils.writeData(file,'PullReqs',i,4,Summary)\n self.driver.close()\n\n def test_TextCompare(self):\n Dvalue= \"['Value2', 'Value3']\"\n Value=\"['Value2', 'Value3']\"\n\n if str(Value) in str(Dvalue):\n print(\"passed\")\n else:\n print(\"Failed\")\n\n def test_ConvertString1to2(self):\n OldString=\"1613377508168-uiGrid-000M-header-text\"\n NewString1= str.replace(OldString,'-uiGrid','-0-uiGrid')\n print(\"New String 1 is: \")\n print(NewString1)\n NewString2 = str.replace(NewString1, '-header-text', '-cell')\n print(\"New String 1 is: \")\n print(NewString2)\n\n\n","sub_path":"TestCases/WorkingFile2.py","file_name":"WorkingFile2.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"540196368","text":"import sys\nfrom boardInterfaces import graphicInterface, terminalInterface, stadisticInterface\nfrom agents import agent_MCTS,agent_Heuristic, agent_MiniMax,agent_QLearning\nimport player\nimport json\n\ndef agents_choose(agent_choose,size):\n \"\"\"\n Load the agent\n \"\"\"\n agent_choose = int(agent_choose)\n data = config()\n if agent_choose ==1:\n agent = agent_MCTS.MCTS(exploration_weight = data[\"agents\"][\"MCST\"][\"exploration_weight\"])\n print(\"MCTS loaded\")\n elif agent_choose ==2:\n agent = agent_MiniMax.MiniMax(data[\"agents\"][\"MiniMax\"][\"depth\"])\n print(\"MiniMax loaded\")\n elif agent_choose == 3:\n agent = agent_Heuristic.Heuristic()\n print(\"Heuristic loaded\")\n elif agent_choose == 4:\n agent = agent_QLearning.QLearning(size = size)\n print(\"Q learning loaded\")\n else:\n agent = None\n return agent\n\ndef config():\n \"\"\"\n Load the config.json file\n \"\"\"\n try:\n with open('config.json') as f:\n data = json.load(f)\n except:\n assert False, \"Error reading config.json.\"\n return data\n\ndef train(agent):\n \"\"\"\n Train the agent\n \"\"\"\n data = config()\n learning_rate = data[\"agents\"][\"Training\"][\"learning_rate\"]\n total_games = data[\"agents\"][\"Training\"][\"total_games\"]\n loadPre = data[\"agents\"][\"Training\"][\"preload\"]\n print(\"Training agent\")\n agent.train_model(total_games, learning_rate = learning_rate, loadPre = loadPre)\n return agent\n\ndef main():\n try:\n size = int(sys.argv[1])\n data = config()\n width = data[\"Graphic interace screen\"][\"witdh\"]\n height = data[\"Graphic interace screen\"][\"height\"]\n train_steps = data[\"agents\"][\"train_steps\"]\n except:\n raise RuntimeError(\"Error: must be 'python main size train_steps height width' with ints \")\n print(\"Welcome, choose game type:\")\n print(\"1) Player vs Player\")\n print(\"2) Player vs IA\")\n print(\"3) IA vs Player\")\n print(\"4) IA vs IA\")\n print(\"5) IA vs IA stadistics\")\n while(True): #Initial menu\n try:\n game_mode = input(\"Select number: \")\n assert game_mode in [\"1\",\"2\",\"3\",\"4\",\"5\"], \"Must be one of the options\"\n break\n except:\n print(\"You must choose one of the options\")\n\n boardType = \"0\"\n if int(game_mode) < 5:\n print(\"Choose board:\")\n print(\"1) Graphic board\")\n print(\"2) Terminal board\")\n while(True): #Initial menu\n try:\n boardType = input(\"Select number: \")\n assert boardType in [\"1\",\"2\"], \"Must be one of the options\"\n break\n except:\n print(\"You must choose one of the options\")\n\n agent_choose = 0\n if int(game_mode) > 1:\n print(\"Choose IA:\")\n print(\"1) MCTS (Monte Carlo Tree Search)\")\n print(\"2) MiniMax\")\n print(\"3) Heuristic\")\n print(\"4) Q learning\")\n while(True): #Initial menu\n try:\n agent_choose = input(\"Select number: \")\n assert agent_choose in [\"1\",\"2\",\"3\",\"4\"], \"Must be one of the options\"\n break\n except:\n print(\"You must choose one of the options\")\n\n if int(game_mode) >= 4:\n print(\"Choose second IA:\")\n print(\"1) MCTS (Monte Carlo Tree Search)\")\n print(\"2) MiniMax (with Alpha Beta pruning)\")\n print(\"3) Heuristic\")\n print(\"4) Q learning\")\n while(True): #Initial menu\n try:\n agent_choose2 = input(\"Select number: \")\n assert agent_choose2 in [\"1\",\"2\",\"3\",\"4\"], \"Must be one of the options\"\n break\n except:\n print(\"You must choose one of the options\")\n\n ##LOAD AGENT\n agent = agents_choose(agent_choose,size)\n agent = train(agent)\n agent2 = agents_choose(agent_choose2,size) if int(game_mode) >= 4 else None\n agent2 = train(agent2) if int(game_mode) >= 4 else None\n #CHOOSE GAME MODE\n game_mode = int(game_mode)\n turnPlayer = player.players()\n if game_mode == 1:\n turnPlayer.insertPlayer_1(player.typePlayer.GRAPHIC_PLAYER, \"Player 1\")\n turnPlayer.insertPlayer_2(player.typePlayer.GRAPHIC_PLAYER, \"Player 2\")\n elif game_mode == 2:\n turnPlayer.insertPlayer_1(player.typePlayer.GRAPHIC_PLAYER, \"Player 1\")\n turnPlayer.insertPlayer_2(player.typePlayer.IA_PLAYER, agent.agent_name)\n elif game_mode == 3:\n turnPlayer.insertPlayer_1(player.typePlayer.IA_PLAYER, agent.agent_name)\n turnPlayer.insertPlayer_2(player.typePlayer.GRAPHIC_PLAYER, \"Player 2\")\n elif game_mode >= 4:\n turnPlayer.insertPlayer_1(player.typePlayer.IA_PLAYER, agent.agent_name)\n turnPlayer.insertPlayer_2(player.typePlayer.IA_PLAYER_2, agent2.agent_name)\n\n boardType = int(boardType)\n if game_mode == 5:\n visualize = data[\"Stadistics interface\"][\"visualize\"]\n save_games = data[\"Stadistics interface\"][\"save_games\"]\n stadisticInterface.gameStadistic(size,train_steps,turnPlayer,agent,agent2,save_games = save_games,visualize =visualize)\n elif boardType == 1:\n graphicInterface.gameInterface(height,width,size,train_steps,turnPlayer,agent,agent2)\n else:\n terminalInterface.gameTerminal(size,train_steps,turnPlayer,agent,agent2)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"181917601","text":"import random\nimport numpy as np\nfrom math import pi\nfrom operator import attrgetter\nimport seaborn as sns\nimport multiprocessing as mp\nfrom collision_checker import CollisionChecker\nfrom geometry import World\nfrom geometry import ObjectGenerator\nfrom geometry import RobotArm\nfrom viewer import RealtimePlot\nfrom prm import PRM\nfrom cell_decomposition import CellDecomposition\nimport time\nsns.set()\n# np.random.seed(1)\n\n\nclass Individual(np.ndarray):\n \"\"\"Container of a individual.\"\"\"\n fitness = None\n\n def __new__(cls, a):\n return np.asarray(a).view(cls)\n\n\nclass GeneticAlgorithm():\n\n def __init__(self, world=None, NGEN=1000, n_ind=100, n_elite=10,\n fitness_thresh=0.1, margin_on=False, verbose=True):\n self.trajectory = [world.start]\n self.history = []\n self.pop = []\n self.best_ind = []\n self.gtot = 0\n\n self.n_ind = n_ind # The number of individuals in a population.\n self.n_elite = n_elite\n self.NGEN = NGEN # The number of generation loop.\n self.fitness_thresh = fitness_thresh\n self.verbose = verbose\n\n # --- Generate Collision Checker\n self.world = world\n if margin_on:\n self.world_margin = world.mcopy(rate=1.05)\n else:\n self.world_margin = world\n self.cc = CollisionChecker(world)\n self.ccm = CollisionChecker(self.world_margin)\n\n def create_pop_prm(self, m, n):\n prm_list = [PRM(self.world_margin, 30, 3) for i in range(m)]\n path_list = []\n for prm in prm_list:\n prm.single_query()\n if prm.path_list != []:\n prm.multi_query(n)\n path_list += prm.path_list\n return [Individual(path) for path in path_list]\n\n def create_pop_cd(self):\n cd = CellDecomposition(self.world_margin)\n path_list = cd.main(self.n_ind, shortcut=True)\n self.pop = [Individual(path) for path in path_list]\n return self.pop\n\n def set_fitness(self, eval_func):\n \"\"\"Set fitnesses of each individual in a population.\"\"\"\n for i, fit in enumerate(map(eval_func, self.pop)):\n self.pop[i].fitness = fit\n\n def evalOneMax(self, gene):\n \"\"\"Objective function.\"\"\"\n delta = [0.1]\n score_list = []\n for d in delta:\n pts = self.smoothing(gene, d)\n score = 0.0\n for i in range(len(pts) - 1):\n dist = np.linalg.norm(pts[i + 1] - pts[i])\n score = score + dist\n # if not cc.path_validation(pts[i], pts[i+1]):\n # score = score + 10\n if not self.ccm.path_validation(pts):\n score = score + 10\n score_list.append(score)\n return min(score_list)\n\n def eval_for_cx(self, gene):\n \"\"\"Objective function.\"\"\"\n pts = gene.copy()\n score = 0.0\n for i in range(len(pts) - 1):\n dist = np.linalg.norm(pts[i + 1] - pts[i])\n score = score + dist\n return score\n\n def selTournament(self, tournsize):\n \"\"\"Selection function.\"\"\"\n chosen = []\n for i in range(self.n_ind - self.n_elite):\n aspirants = [random.choice(self.pop) for j in range(tournsize)]\n chosen.append(min(aspirants, key=attrgetter(\"fitness\")))\n return chosen\n\n def selElite(self):\n pop_sort = sorted(self.pop, key=attrgetter(\"fitness\"))\n elites = pop_sort[:self.n_elite]\n return elites\n\n def calc_intersection_point(self, A, B, C, D):\n denominator = (B[0] - A[0]) * (C[1] - D[1]) - \\\n (B[1] - A[1]) * (C[0] - D[0])\n # If two lines are parallel,\n if abs(denominator) < 1e-6:\n return None, None, None\n AC = A - C\n r = ((D[1] - C[1]) * AC[0] - (D[0] - C[0]) * AC[1]) / denominator\n s = ((B[1] - A[1]) * AC[0] - (B[0] - A[0]) * AC[1]) / denominator\n # If the intersection is out of the edges\n if r < -1e-6 or r > 1.00001 or s < -1e-6 or s > 1.00001:\n return None, r, s\n # Endpoint and startpoint make the intersection.\n if ((np.linalg.norm(r - 1.0) < 1e-6 and np.linalg.norm(s) < 1e-6) or\n (np.linalg.norm(s - 1.0) < 1e-6 and np.linalg.norm(r) < 1e-6)):\n return None, r, s\n point_intersection = A + r * (B - A)\n return point_intersection, r, s\n\n def subcalc(self, queue, seed, offspring, elites, n):\n np.random.seed(seed)\n crossover = []\n for i in range(10):\n randint1 = np.random.randint(len(offspring))\n randint2 = np.random.randint(len(elites))\n child = self.cx(offspring[randint1], elites[randint2])\n crossover.append(child)\n queue.put(crossover)\n\n def cx(self, ind1, ind2):\n \"\"\"Crossover function for path planning.\"\"\"\n # --- If the ind1 and the ind2 is the same path, return ind1 and exit.\n if len(ind1) == len(ind2) and all((ind1 == ind2).flatten()):\n return ind1\n\n # --- Initialize\n best = []\n id1 = [0]\n id2 = [0]\n tmp1 = ind1.copy()\n tmp2 = ind2.copy()\n j = 0\n\n # --- Search for the intersection\n for i1 in range(len(ind1) - 1):\n for i2 in range(len(ind2) - 1):\n # Calculate an intersection between line AB and line CD.\n pt, r, s = self.calc_intersection_point(\n ind1[i1], ind1[i1 + 1], ind2[i2], ind2[i2 + 1])\n # If intersection is found,\n if pt is not None:\n if np.linalg.norm(r - 1.0) > 1e-6 and \\\n np.linalg.norm(r) > 1e-6:\n # Add the intersection to the point lists.\n tmp1 = np.insert(tmp1, i1 + j + 1, pt, axis=0)\n tmp2 = np.insert(tmp2, i2 + j + 1, pt, axis=0)\n # Revise the intersection lists.\n id1.append(i1 + j + 1)\n id2.append(i2 + j + 1)\n # j: Num. of the intersection points.\n j = j + 1\n # Add the last point of the path to the intersection lists.\n id1 = id1 + [len(ind1) + j + 1]\n id2 = id2 + [len(ind2) + j + 1]\n\n # --- Select the best path based on the path length.\n for i in range(len(id1) - 1):\n if (self.eval_for_cx(tmp1[id1[i]:id1[i + 1] + 1])\n < self.eval_for_cx(tmp2[id2[i]: id2[i + 1] + 1])):\n best = best + list(tmp1[id1[i]: id1[i + 1]])\n else:\n best = best + list(tmp2[id2[i]: id2[i + 1]])\n\n return Individual(best)\n\n def node_reduction(self, path):\n path = np.array(path)\n new_path = [path[0]]\n for i in range(1, len(path) - 1):\n u = path[i + 1] - path[i]\n umag = np.linalg.norm(u)\n if umag > 0.1:\n new_path.append(path[i])\n elif not self.ccm.line_validation(new_path[-1], path[i + 1]):\n new_path.append(path[i])\n new_path.append(path[-1])\n\n path = new_path.copy()\n new_path = [path[0]]\n for i in range(1, len(path) - 1):\n u = path[i + 1] - path[i]\n v = path[i - 1] - path[i]\n umag = np.linalg.norm(u)\n vmag = np.linalg.norm(v)\n if umag != 0 and vmag != 0:\n cos = np.dot(u, v) / (umag * vmag)\n if abs(cos) < 0.99:\n new_path.append(path[i])\n elif not self.ccm.line_validation(new_path[-1], path[i + 1]):\n new_path.append(path[i])\n new_path.append(path[-1])\n new_path = np.array(new_path)\n return new_path\n\n def mut_normal(self, ind, indpb, maxiter):\n \"\"\"Mutation function.\"\"\"\n mut = ind.copy()\n for i in range(1, len(ind) - 1):\n if random.random() < indpb:\n var = 0.5\n for j in range(maxiter):\n mut[i] = ind[i] + np.random.normal(0.0, var, 2)\n var = var * 0.5\n if self.ccm.path_validation(\n [mut[i - 1], mut[i], mut[i + 1]]):\n break\n else:\n mut[i] = ind[i]\n return Individual(mut)\n\n def smoothing(self, pts, delta=0.1):\n # resampled_path = post_process.resampling(pts, delta)\n # bezier_path = post_process.bezier(resampled_path, 50)\n # return bezier_path\n return pts\n\n def main(self, duration):\n '''\n Main Routine for Genetic Algorithm\n '''\n ini_time = time.time()\n\n # --- Evaluate the initial population\n self.set_fitness(self.evalOneMax)\n self.best_ind = min(self.pop, key=attrgetter(\"fitness\"))\n\n self.history.append([self.gtot, self.best_ind.fitness])\n self.trajectory.append([self.world.start[0], self.world.start[1]])\n\n np.vstack((self.trajectory, self.world.start))\n\n if self.verbose:\n rp.plot(self.pop, self.best_ind, self.trajectory, self.history)\n\n # --- Generation loop starts.\n print('\\n[Genetic Algorithm]')\n print(\"Generation loop start.\")\n print(\"Generation: 0. Best fitness: {}\\n\"\n .format(str(self.best_ind.fitness)))\n for g in range(self.NGEN):\n\n '''\n STEP1 : Selection.\n '''\n t0 = time.time()\n # Elite selection\n elites = self.selElite()\n # Tournament Selection\n offspring = self.selTournament(tournsize=3)\n\n '''\n STEP2 : Mutation.\n '''\n t1 = time.time()\n mutant = []\n for ind in offspring:\n if np.random.rand() < 0.7:\n tmp = self.mut_normal(ind, indpb=0.7, maxiter=3)\n mutant.append(tmp)\n else:\n mutant.append(ind)\n offspring = mutant.copy()\n # mutant = self.create_pop_cd(10)\n mutant = self.create_pop_prm(2, 5)\n\n '''\n Step3 : Crossover.\n '''\n t2 = time.time()\n proc = 8\n n_cross = 10\n queue = mp.Queue()\n ps = [\n mp.Process(target=self.subcalc, args=(\n queue, i, offspring, elites, n_cross))\n for i in np.random.randint(100, size=proc)\n ]\n\n for p in ps:\n p.start()\n\n crossover = []\n for i in range(proc):\n crossover += queue.get()\n '''\n STEP4: Update next generation.\n '''\n t3 = time.time()\n n_offspring = self.n_ind - \\\n (len(elites) + len(crossover) + len(mutant))\n self.pop = (list(elites) + list(crossover) +\n list(offspring[0:n_offspring])) + list(mutant)\n\n # --- Delete the redundant points on the path.\n self.pop = [Individual(self.node_reduction(path))\n for path in self.pop]\n\n self.set_fitness(self.evalOneMax)\n\n '''\n Output\n '''\n t4 = time.time()\n\n # --- Print best fitness in the population.\n self.best_ind = min(self.pop, key=attrgetter(\"fitness\"))\n print(\"Generation: {: > 2}\".format(g))\n print(\"Best fitness: {: .3f}\".format(self.best_ind.fitness))\n print(\"Time: {0:.3f}, {1:.3f}, {2:.3f}, {3:.3f}, Total: {4:.3f} \\n\"\n .format(t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0))\n\n # Fitness transition\n self.history.append([self.gtot, self.best_ind.fitness])\n\n '''\n # STEP5: Termination\n '''\n # --- Visualization\n if self.verbose:\n rp.plot(self.pop, self.best_ind, self.trajectory, self.history)\n\n if time.time() - ini_time > duration:\n # --- Visualization\n if self.verbose:\n rp.plot(self.pop, self.best_ind,\n self.trajectory, self.history)\n\n break\n\n if self.best_ind.fitness <= self.fitness_thresh:\n print('The best fitness reaches the threshold value.')\n break\n\n if g >= 5:\n diff = np.abs(self.history[-5][1] - self.history[-1][1])\n if diff < 1e-2:\n print('The best fitness does not change for 10 steps.')\n break\n\n self.gtot += 1\n\n\nif __name__ == '__main__':\n # World\n world = World()\n world.generate_frame([-10, 10], [-10, 10])\n world.type = 'cartesian'\n\n # Objects in the cartesian space\n og = ObjectGenerator(world)\n og.generate_object([[3.5, 6.5], [3.5, 3.5], [6.5, 3.5], [6.5, 6.5]])\n\n # Robot\n robot2R = RobotArm(base=[0, 0], lengths=[3.0, 5.0])\n robot2R.start = np.array([pi / 2, -pi / 7])\n robot2R.goal = np.array([pi / 5, - pi / 7])\n\n # C-space\n cspace = World()\n cspace.robot = robot2R\n cspace.generate_frame([-pi, pi], [-pi, pi])\n cspace.start = cspace.robot.start\n cspace.goal = cspace.robot.goal\n cspace.generate_cspace_objects([100, 100], world.objects)\n cspace.generate_cspace_objects([100, 100], [world.frame])\n cspace.type = 'cspace'\n\n # world.start = np.array([-3.0, -3.0])\n # world.goal = np.array([3.0, 3.0])\n # og = ObjectGenerator(world)\n # og.generate_object_sample1()\n ga = GeneticAlgorithm(world=cspace, NGEN=100, n_ind=100, n_elite=10,\n fitness_thresh=0.0, margin_on=False, verbose=True)\n rp = RealtimePlot(cspace, 100, dt=0.01)\n # --- Initial Population\n # initial_pop = create_pop_cd(100)\n ga.pop = ga.create_pop_prm(1, 1)\n ga.main(100.0)\n rp.fig.clf()\n","sub_path":"ga_planner_2R.py","file_name":"ga_planner_2R.py","file_ext":"py","file_size_in_byte":13992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"561140369","text":"#!/usr/bin/env python\n# vim: set sw=4 et:\n\nimport logging\nimport time\nimport threading\nimport kombu\nfrom umbra.browser import BrowserPool\n\nclass AmqpBrowserController:\n \"\"\"\n Consumes amqp messages representing requests to browse urls, from the\n specified amqp queue (default: \"urls\") on the specified amqp exchange\n (default: \"umbra\"). Incoming amqp message is a json object with 3\n attributes:\n\n {\n \"clientId\": \"umbra.client.123\",\n \"url\": \"http://example.com/my_fancy_page\",\n \"metadata\": {\"arbitrary\":\"fields\", \"etc\":4}\n }\n\n \"url\" is the url to browse.\n\n \"clientId\" uniquely identifies the client of umbra. Umbra uses the clientId\n as the amqp routing key, to direct information via amqp back to the client.\n It sends this information on the same specified amqp exchange (default:\n \"umbra\").\n\n Each url requested in the browser is published to amqp this way. The\n outgoing amqp message is a json object:\n\n {\n \"url\": \"http://example.com/images/embedded_thing.jpg\",\n \"method\": \"GET\",\n \"headers\": {\"User-Agent\": \"...\", \"Accept\": \"...\", ...},\n \"parentUrl\": \"http://example.com/my_fancy_page\",\n \"parentUrlMetadata\": {\"arbitrary\":\"fields\", \"etc\":4, ...}\n }\n\n POST requests have an additional field, postData.\n \"\"\"\n\n logger = logging.getLogger(__module__ + \".\" + __qualname__)\n\n def __init__(self, amqp_url='amqp://guest:guest@localhost:5672/%2f',\n chrome_exe='chromium-browser', browser_wait=60,\n max_active_browsers=1, queue_name='urls', routing_key='url',\n exchange_name='umbra'):\n self.amqp_url = amqp_url\n self.queue_name = queue_name\n self.routing_key = routing_key\n self.exchange_name = exchange_name\n\n self._browser_pool = BrowserPool(size=max_active_browsers,\n chrome_exe=chrome_exe, chrome_wait=browser_wait)\n\n def start(self):\n self._exchange = kombu.Exchange(name=self.exchange_name, type='direct',\n durable=True)\n\n self._producer = None\n self._producer_lock = threading.Lock()\n with self._producer_lock:\n self._producer_conn = kombu.Connection(self.amqp_url)\n self._producer = self._producer_conn.Producer(serializer='json')\n\n self._amqp_thread = threading.Thread(target=self._consume_amqp, name='AmqpConsumerThread')\n self._amqp_stop = threading.Event()\n self._amqp_thread.start()\n\n def shutdown(self):\n self.logger.info(\"shutting down amqp consumer {}\".format(self.amqp_url))\n self._amqp_stop.set()\n self._amqp_thread.join()\n # with self._producer_lock:\n # self._producer_conn.close()\n # self._producer_conn = None\n\n def shutdown_now(self):\n self._browser_pool.shutdown_now()\n\n def _consume_amqp(self):\n # XXX https://webarchive.jira.com/browse/ARI-3811\n # After running for some amount of time (3 weeks in the latest case),\n # consumer looks normal but doesn't consume any messages. Not clear if\n # it's hanging in drain_events() or not. As a temporary measure for\n # mitigation (if it works) or debugging (if it doesn't work), close and\n # reopen the connection every 15 minutes\n RECONNECT_AFTER_SECONDS = 15 * 60\n\n url_queue = kombu.Queue(self.queue_name, routing_key=self.routing_key,\n exchange=self._exchange)\n\n while not self._amqp_stop.is_set():\n try:\n self.logger.info(\"connecting to amqp exchange={} at {}\".format(self._exchange.name, self.amqp_url))\n with kombu.Connection(self.amqp_url) as conn:\n conn_opened = time.time()\n with conn.Consumer(url_queue) as consumer:\n consumer.qos(prefetch_count=1)\n while (not self._amqp_stop.is_set() and time.time() - conn_opened < RECONNECT_AFTER_SECONDS):\n import socket\n try:\n browser = self._browser_pool.acquire() # raises KeyError if none available\n consumer.callbacks = [self._make_callback(browser)]\n conn.drain_events(timeout=0.5)\n consumer.callbacks = None\n except KeyError:\n # no browsers available\n time.sleep(0.5)\n except socket.timeout:\n # no urls in the queue\n self._browser_pool.release(browser)\n\n except BaseException as e:\n self.logger.error(\"amqp exception {}\".format(e))\n time.sleep(0.5)\n self.logger.error(\"attempting to reopen amqp connection\")\n\n def _make_callback(self, browser):\n def callback(body, message):\n self._browse_page(browser, body['clientId'], body['url'], body['metadata'])\n message.ack()\n return callback\n\n def _browse_page(self, browser, client_id, url, parent_url_metadata):\n def on_request(chrome_msg):\n payload = chrome_msg['params']['request']\n payload['parentUrl'] = url\n payload['parentUrlMetadata'] = parent_url_metadata\n self.logger.debug('sending to amqp exchange={} routing_key={} payload={}'.format(self.exchange_name, client_id, payload))\n with self._producer_lock:\n publish = self._producer_conn.ensure(self._producer, self._producer.publish)\n publish(payload, exchange=self._exchange, routing_key=client_id)\n\n def browse_page_async():\n self.logger.info('browser={} client_id={} url={}'.format(browser, client_id, url))\n try:\n browser.browse_page(url, on_request=on_request)\n finally:\n self._browser_pool.release(browser)\n\n import random\n threadName = \"BrowsingThread{}-{}\".format(browser.chrome_port,\n ''.join((random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') for _ in range(6))))\n threading.Thread(target=browse_page_async, name=threadName).start()\n\n","sub_path":"umbra/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":6308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"305703463","text":"from tkinter import *\r\nimport time\r\n\r\nfile = open('chat.txt', 'w')\r\nfile.write(f'I, JOIN THE CHAT.')\r\nfile.close()\r\nchat = Tk()\r\nchat.title('chat app')\r\nchat.geometry('800x800+700+300')\r\nchat.configure(bg='yellow')\r\n# chat.overrideredirect(1)\r\nchat.wm_attributes('-transparentcolor', 'yellow')\r\nchat.attributes('-alpha', 0.50)\r\n\r\n\r\ndef send_d(e=''):\r\n file = open('chat.txt', 'w')\r\n file.write(f'{E.get()}')\r\n file.close()\r\n global lx, ly, ly1, lx1\r\n ly += 30\r\n ly1 += 30\r\n L = Label(text=E.get(), fg='red')\r\n L.place(x=lx1, y=ly1)\r\n E.delete(0, END)\r\n if ly > 750:\r\n o = Label(bg='yellow', width=200, height=800)\r\n o.place(x=0, y=30)\r\n ly = 0\r\n ly1 = 0\r\n\r\n\r\nE = Entry(bg='white', border=0, width=200)\r\nE.place(x=0, y=0)\r\nE.bind('', send_d)\r\n\r\ni = 0\r\ntext = ''\r\nlx = 200\r\nly = 30\r\nlx1 = 0\r\nly1 = 30\r\n\r\nwhile True:\r\n chat.update()\r\n i += 1\r\n chat.update_idletasks()\r\n time.sleep(0.01)\r\n print(i)\r\n file = open('chat_y.txt', 'r')\r\n fr = file.read()\r\n file.close()\r\n if fr in text:\r\n if ly > 750:\r\n o = Label(bg='yellow', width=200, height=800)\r\n o.place(x=0, y=30)\r\n ly = 0\r\n ly1 = 0\r\n else:\r\n ly += 30\r\n ly1 += 30\r\n L = Label(text=fr)\r\n L.place(x=lx, y=ly)\r\n text = fr\r\n if ly > 750:\r\n o = Label(bg='yellow', width=200, height=800)\r\n o.place(x=0, y=30)\r\n ly = 0\r\n ly1 = 0\r\n\r\nchat.mainloop()\r\n","sub_path":"chp1.py","file_name":"chp1.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"173507994","text":"import machine\nimport network\nfrom neopixel import NeoPixel\nimport time\n\n# Parameters\nNETWORK_PREFIX = \"find_my_py_\"\nMEASURE_AVG = 3\nMEASURE_THRESHOLD = -50\nNEOPIXEL_PIN = 5\nSLEEP_TIME_MS = 500\n\n\n# Initialize NeoPixel\nnp = NeoPixel(machine.Pin(NEOPIXEL_PIN), 1)\n\n# Setup Passive WiFi Network\nu_id = machine.unique_id()\nessid = NETWORK_PREFIX + str(int.from_bytes(u_id, 16))\n\nap = network.WLAN(network.AP_IF)\nap.active(True)\nap.config(essid=essid, channel=11)\n\nprint('Opened Network \"{}\"\" on channel {}'.format(\n ap.config('essid'), ap.config('channel')))\n\n# Setup WiFi for Search\nsta_if = network.WLAN(network.STA_IF)\nsta_if.active(True)\n\nprint(\"sta_if.active: \" + str(sta_if.active()))\nprint(\"ap.active: \" + str(ap.active()))\n\n\ndef find_nodes(active_node=None):\n '''Return strongest or updated node'''\n\n # Find all find-my-py nodes\n networks = sta_if.scan()\n fmp_nodes = list(\n filter(lambda x: x[0].startswith(NETWORK_PREFIX), networks))\n\n # Sort by signal state\n if len(fmp_nodes) == 0:\n active_node = None\n else:\n fmp_nodes.sort(key=lambda n: n[3], reverse=True)\n\n if active_node:\n active_node = \\\n [node for node in fmp_nodes if node[0] == active_node[0]][0]\n else:\n active_node = fmp_nodes[0]\n\n return active_node\n\n\ndef set_neopixel(np, color):\n '''Write color to NeoPixel node'''\n np[0] = color\n np.write()\n\n\n# Continuous Search\nactive_node = None\nsignal_strength = None\n\nwhile(True):\n active_node = find_nodes(active_node)\n\n if active_node:\n if not signal_strength:\n signal_strength = MEASURE_AVG * [active_node[3]]\n else:\n signal_strength[1:] = signal_strength[:-1]\n signal_strength[0] = active_node[3]\n\n if signal_strength[0] >= MEASURE_THRESHOLD:\n print('Partner node found :) ' + str(signal_strength[0]))\n\n # Set green LED\n set_neopixel(np, (0, 255, 0))\n\n else:\n prev_signal_strength = (sum(signal_strength[1:]) /\n (len(signal_strength) - 1))\n d_signal_strength = signal_strength[0] - prev_signal_strength\n getting_closer = (d_signal_strength > 0)\n\n if d_signal_strength > 2:\n # Set red LED when getting closer\n set_neopixel(np, (255, 0, 0))\n elif d_signal_strength < -2:\n # Set blue LED when getting farther away\n set_neopixel(np, (0, 0, 255))\n else:\n # Set purple LED when just found a node or signal didn't varry\n set_neopixel(np, (155, 0, 255))\n\n print(d_signal_strength)\n\n else:\n signal_strength = None\n print('No node found :(')\n\n # Set yellow LED\n set_neopixel(np, (200, 160, 0))\n\n time.sleep_ms(SLEEP_TIME_MS)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"629217202","text":"import cvxpy as cp\nimport numpy as np\nfrom scipy import integrate\nfrom scipy.fft import fft\nimport math\nimport scipy.io as sio\nimport gurobipy\nimport mosek\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import csr_matrix\nfrom datetime import datetime\nimport os\n\ndef get_a_num(dq):\n return r*dq\n\ndef get_B_num(dtau):\n return -r*np.diag(dtau)\n\ndef get_c_num(ddq):\n return r*ddq\n\ndef get_D_num(dtau, ddtau):\n data_len = len(dtau)\n D_1 = np.zeros((data_len, data_len))\n for idx in range(0, data_len):\n cidx=(idx+1)%data_len\n D_1[idx][cidx]=1\n cidx=(idx+data_len-1)%data_len\n D_1[idx][cidx]=-1\n\n D_1 = D_1*(1/(2*dt))\n return -r*np.diag(ddtau)-r*(np.diag(dtau)@D_1)\n\ndef get_e_num(a, c, tau):\n return I_m*c+b_m*a-(1/r)*tau\n\ndef get_F_num(B, D):\n return I_m*D+b_m*B\n\ndef get_coef_SEA(t, dq, ddq, tau, dtau, ddtau):\n \"\"\"\n Returns the a, b, and c coefficients for SEA optimization using the definition from (8) in ICORR19 paper\n \"\"\"\n gam1 = -(I_m*ddtau*r + b_m*dtau*r)\n gam2 = I_m*ddq*r + b_m*dq*r - tau/r\n a = np.trapz( gam1**2/K_m**2 + b_m*r**2*dtau**2, t)\n b = np.trapz( 2*gam1*gam2/K_m**2 - 2*b_m*r**2*dq*dtau, t)\n c = np.trapz( gam2**2/K_m**2 + b_m*dq**2*r**2 - dq*tau, t)\n return a, b, c\n\ndef get_G_num(B, F):\n return dt*((1/(K_m*K_m))*(F.T @ F) + b_m*(B.T @ B))\n\ndef get_h_num(a, B, e, F):\n return dt*((2/(K_m*K_m))*(e.T @ F) + 2*b_m*(a.T @ B))\n\ndef get_w_num(a, e, dq, tau):\n return dt*((1/(K_m*K_m))*(e.T @ e) + b_m*(a.T @ a) - tau.T @ dq)\n\ndef get_elong_matr(tau, dtau, argidx):\n mintauidx=argidx[0]\n n=len(tau)\n i=np.zeros(len(argidx))\n for idx in range(0, len(argidx)):\n i[idx]=idx\n\n ordMatr = csr_matrix((np.ones(len(argidx)), (i, argidx)), shape = (n, n)).toarray()\n elo_mat = np.zeros((n,n))\n elo_mat[1][0]=dtau[0];\n elo_mat[1][1]=dtau[1];\n for i in range(2, len(dtau)):\n for j in range(0,n):\n elo_mat[i][j]=elo_mat[i-1][j]\n elo_mat[i][i] = dtau[i]\n\n for i in range(0,n):\n elo_mat[i][0]=elo_mat[i][0]/2\n\n for i in range(0,n):\n elo_mat[i][i]=elo_mat[i][i]/2\n\n del_vector = np.zeros(n)\n for i in range(0,n):\n del_vector[i] = elo_mat[mintauidx][i]\n\n for i in range(0, len(dtau)):\n for j in range(0, n):\n elo_mat[i][j] = elo_mat[i][j] - del_vector[j]\n\n elo_mat = dt*elo_mat\n elo_mat = ordMatr@elo_mat\n return elo_mat\n\ndef get_L_num(dtau_s):\n data_size = np.shape(dtau_s)\n data_len = data_size[0]\n L = np.zeros((data_len, data_len))\n L[1][0]=dtau_s[0]\n L[1][1]=dtau_s[1]\n for idx in range(2, data_len):\n for cidx in range(0, idx+1):\n if cidx==0 or cidx==idx:\n L[idx][cidx]=dtau_s[cidx]\n else:\n L[idx][cidx]=2*dtau_s[cidx]\n\n return (dt/2)*L\n\ndef get_diff_mat(n, argidx):\n D_M = np.zeros((n-1, n))\n for ridx in range(0, n-1):\n minus_idx = argidx[ridx]\n add_idx = argidx[ridx+1]\n D_M[ridx][minus_idx]=-1\n D_M[ridx][add_idx]=1\n \n return D_M\n\ndef get_L_diff_mat(L, n):\n L_star = np.zeros((n-1, n))\n L_pl = np.zeros((n-1, n))\n rcount = 0\n for ridx in range(1, n):\n for cidx in range(0, n):\n L_star[rcount][cidx]=L[ridx][cidx]\n\n rcount=rcount+1\n\n rcount = 0\n for ridx in range(0, n-1):\n for cidx in range(0, n):\n L_pl[rcount][cidx]=L[ridx][cidx]\n\n rcount=rcount+1\n\n return L_star-L_pl\n\ndef get_elo_diff_matr(L_e):\n L_e_f = np.zeros((data_len-2,data_len-1))\n L_e_r = np.zeros((data_len-2,data_len-1))\n for i in range(0, data_len-2):\n for j in range(0, data_len-1):\n L_e_f[i][j]=L_e[i+1][j]\n L_e_r[i][j]=L_e[i][j]\n return -(L_e_f - L_e_r)\n\ndef get_spr_int_vec(tau):\n difftau=np.diff(tau)\n int_vec = np.append(difftau,[0])+np.insert(difftau,0,[0])\n int_vec[0] = int_vec[0]/2\n int_vec[-1] = int_vec[-1]/2\n int_vec = int_vec*tau\n return int_vec\n\ndef FitTrigPoly(output, input, order):\n \"\"\"\n Fit trigonometric polynomial to the values of `output` as a function of `input`. Order defines the order for the\n sin/cos.\n\n The function assumes that `input` is periodic when `output` goes from 0-1.\n \"\"\"\n input = input/input[-1] # Normalizing data points from (0-1)\n #------------------------------------------- Generate regressor matrix A\n n = int(1 + order*2)\n m = input.size\n A = np.empty([m, n]) # 1 constant term plus sin and cos for each order\n \n A[:, 0] = np.ones(m)\n for i in range(1, order+1):\n A[:, i*2-1] = np.cos(2*np.pi*i*input)\n A[:, i*2] = np.sin(2*np.pi*i*input)\n \n #------------------------------------------- Fit model to data using cvxpy\n x = cp.Variable(n)\n constraints = []\n # Form objective.\n obj = cp.Minimize( cp.norm(output - A@x, p = 2) )\n # Form and solve problem.\n prob = cp.Problem(obj, constraints)\n prob.solve(solver=cp.MOSEK) # Returns optimal value \n if (prob.status == 'optimal'):\n #-------------------------------------- Generate analytical function\n def fun(phase):\n \"\"\"\n Analytical expression for the fourier series (input is normalized from 0-1)\n \"\"\"\n acc = x.value[0]\n for i in range(1, order+1):\n cosIdx = i*2-1\n sinIdx = i*2\n acc = acc + x.value[cosIdx]*np.cos(2*np.pi*i*phase)\n acc = acc + x.value[sinIdx]*np.sin(2*np.pi*i*phase)\n return acc\n return fun(input)\n else:\n raise NameError('Optimization program was not optimal')\n\ndef get_harmonics(y, pas):\n size=np.shape(y)\n N=size[0]\n Y=fft(y)\n size=np.shape(Y)\n \n w = np.zeros(N)\n for i in range(0,N):\n w[i]=(2*math.pi/(N*pas))*i\n \n w0 = w[1]\n nc2 = math.trunc(N/2)\n ak = np.zeros(nc2)\n bk = np.zeros(nc2)\n for l in range(2, nc2+2):\n ak[l-2]=np.real(Y[l-1]+Y[N-l+1])/N\n bk[l-2]=-np.imag(Y[l-1]-Y[N-l+1])/N\n\n a0=2*np.real(Y[0])/N;\n return w0, a0, ak, bk\n\n\n# Global Variables:---------------GLOBAL VARIABLES CHECKED\nI_m = 1.2e-4 # Inertia of the motor [Kg*m^2]\nb_m = 0.16e-3 # Drag torque [Nm / (rad/s)]\nr = 50 # reduction ratio\nK_t = 0.14 # Torque constant motor [Nm/A]\nR_m = 0.186 # Terminal resistance [ohms]\nK_m = K_t/math.sqrt(R_m) # Motor constant\nV_m = 36 # Voltage power supply [Volts]\ndq_max = V_m/K_t # Max motor velocity [rad/sec]\ntau_m_max = 28.7*K_t # Peak torque [Nm]\ntau_m_RMS = 7.7*K_t # Max. continuous current [Nm]\ndelta_s_max = 90*math.pi/180 # Max. spring elongation [rad]\n\nmc_no = 1000\nerror = 0.2\ncadence='normal'\njoint='ankle'\n\nmat_fname = 'InputData/level_' + cadence + '_' + joint + '.mat'\nmat_contents = sio.loadmat(mat_fname)\nt_data = mat_contents['t'][0]\nbody_mass= mat_contents['m'][0]\npos_dataRaw = mat_contents['position'][0]*(math.pi/180)\ntrq_dataRaw = mat_contents['torque'][0]*body_mass\nomega0_q, a0_q, ak_q, bk_q = get_harmonics(pos_dataRaw, t_data[1]-t_data[0])\nomega0_tau, a0_tau, ak_tau, bk_tau = get_harmonics(trq_dataRaw, t_data[1]-t_data[0])\ndata_size = np.shape(pos_dataRaw)\ndata_len = data_size[0]\nt = np.linspace(0, 2*math.pi/omega0_q, num=data_len)\ndt = t[1]-t[0]\npos_data = np.zeros(data_len)+a0_q/2\ntrq_data = np.zeros(data_len)+a0_tau/2\nvel_data = np.zeros(data_len)\ndtrq_data = np.zeros(data_len)\nacc_data = np.zeros(data_len)\nddtrq_data = np.zeros(data_len)\n\nfor idx in range(0, 6):\n pos_data = pos_data + ak_q[idx]*np.cos((idx+1)*omega0_q*t) + bk_q[idx]*np.sin((idx+1)*omega0_q*t)\n trq_data = trq_data + ak_tau[idx]*np.cos((idx+1)*omega0_tau*t) + bk_tau[idx]*np.sin((idx+1)*omega0_tau*t)\n vel_data = vel_data - ((idx+1)*omega0_q)*ak_q[idx]*np.sin((idx+1)*omega0_q*t) + ((idx+1)*omega0_q)*bk_q[idx]*np.cos((idx+1)*omega0_q*t)\n dtrq_data = dtrq_data - ((idx+1)*omega0_tau)*ak_tau[idx]*np.sin((idx+1)*omega0_tau*t) + ((idx+1)*omega0_tau)*bk_tau[idx]*np.cos((idx+1)*omega0_tau*t)\n acc_data = acc_data - ((idx+1)*omega0_q)**2*ak_q[idx]*np.cos((idx+1)*omega0_q*t) - ((idx+1)*omega0_q)**2*bk_q[idx]*np.sin((idx+1)*omega0_q*t)\n ddtrq_data = ddtrq_data - ((idx+1)*omega0_tau)**2*ak_tau[idx]*np.cos((idx+1)*omega0_tau*t) - ((idx+1)*omega0_tau)**2*bk_tau[idx]*np.sin((idx+1)*omega0_tau*t)\n \n\nvel_dataRaw = np.gradient(pos_dataRaw, t)\nacc_dataRaw = np.gradient(vel_dataRaw, t)\ndtrq_dataRaw = np.gradient(trq_dataRaw, t)\nddtrq_dataRaw = np.gradient(dtrq_dataRaw, t)\n\n# Plotting.\nfig, axs = plt.subplots(3, 1)\naxs[0].plot(t, pos_dataRaw, label = 'Raw')\naxs[0].plot(t, pos_data, '--o', label = 'Fourier')\naxs[0].legend()\naxs[0].set_xlabel('Time [s]')\naxs[0].set_ylabel('Knee Angle [rad] (+) Flexion')\n# axs[1].plot(t, trq_dataRaw, label = 'Raw - (+) Extension')\naxs[1].plot(t, -trq_data, '--o', label = 'Fourier (+) Flexion')\naxs[1].legend()\naxs[1].set_xlabel('Time [s]')\naxs[1].set_ylabel('Torque [N-m] (+) Flexion')\naxs[2].plot(t, -vel_data*trq_data)\naxs[2].set_xlabel('Time [s]')\naxs[2].set_ylabel('Power [W] - (+) Generation')\naxs[2].grid()\naxs[2].text(0.2, -20, f\"Energy per cycle (Provided from the motor to the load): {np.trapz(-vel_data*trq_data, t):3.2f} [J]\")\n# plt.show()\n\nfig, axs = plt.subplots(3, 1)\naxs[0].plot(t, pos_dataRaw, label = 'Raw')\naxs[0].plot(t, pos_data, '--', label = 'Fourier')\naxs[0].legend()\naxs[0].set_xlabel('Time [s]')\naxs[0].set_ylabel('Angle [rad] (+) Flexion')\naxs[0].grid()\naxs[1].plot(t, vel_dataRaw, label = 'Raw')\naxs[1].plot(t, vel_data, '--', label = 'Fourier')\naxs[1].legend()\naxs[1].set_xlabel('Time [s]')\naxs[1].set_ylabel('Angular Velocity [rad/s] (+) Flexion')\naxs[1].grid()\naxs[2].plot(t, acc_dataRaw, label = 'Raw')\naxs[2].plot(t, acc_data, '--', label = 'Fourier')\naxs[2].legend()\naxs[2].set_xlabel('Time [s]')\naxs[2].set_ylabel('Angular Acceleration [rad/s^2] (+) Flexion')\naxs[2].grid()\n\nfig, axs = plt.subplots(3, 1)\naxs[0].plot(t, trq_dataRaw, label = 'Raw')\naxs[0].plot(t, trq_data, '--', label = 'Fourier')\naxs[0].legend()\naxs[0].set_xlabel('Time [s]')\naxs[0].set_ylabel('Torque [N-m] (+) Extension')\naxs[0].grid()\naxs[1].plot(t, dtrq_dataRaw, label = 'Raw')\naxs[1].plot(t, dtrq_data, '--', label = 'Fourier')\naxs[1].legend()\naxs[1].set_xlabel('Time [s]')\naxs[1].set_ylabel('Power [N-m/s] (+) Extension')\naxs[1].grid()\naxs[2].plot(t, ddtrq_dataRaw, label = 'Raw')\naxs[2].plot(t, ddtrq_data, '--', label = 'Fourier')\naxs[2].legend()\naxs[2].set_xlabel('Time [s]')\naxs[2].set_ylabel('ddTrq/dt^2 [N-m/s^2] (+) Extension')\naxs[2].grid()\n# plt.show()\n\n\ngamma_1 = -r*(I_m*ddtrq_data+b_m*dtrq_data)\ngamma_2 = I_m*r*acc_data+b_m*r*vel_data-(1/r)*trq_data\n\ntau_m_0 = (I_m*r*acc_data + b_m*r*vel_data - (1/r)*trq_data)\ndq_m_0 = r*vel_data\nEm_0 = integrate.simpson((1/(K_m*K_m))*tau_m_0**2 + tau_m_0*dq_m_0, t)\n\npos_data_opt = np.zeros(data_len-1)\ntrq_data_opt = np.zeros(data_len-1)\nvel_data_opt = np.zeros(data_len-1)\ndtrq_data_opt = np.zeros(data_len-1)\nacc_data_opt = np.zeros(data_len-1)\nddtrq_data_opt = np.zeros(data_len-1)\n\nfor i in range(0, data_len-1):\n pos_data_opt[i] = pos_data[i]\n trq_data_opt[i] = trq_data[i]\n vel_data_opt[i] = vel_data[i]\n dtrq_data_opt[i] = dtrq_data[i]\n acc_data_opt[i] = acc_data[i]\n ddtrq_data_opt[i] = ddtrq_data[i]\n\na = get_a_num(vel_data_opt)\nB_num = get_B_num(dtrq_data_opt)\nc = get_c_num(acc_data_opt)\nD_num = get_D_num(dtrq_data_opt, ddtrq_data_opt)\ne = get_e_num(a, c, trq_data_opt)\nF_num = get_F_num(B_num, D_num)\nG_num = get_G_num(B_num, F_num)\nh = get_h_num(a, B_num, e, F_num)\nw_num = get_w_num(a, e, vel_data_opt, trq_data_opt)\nL_num = get_L_num(-dtrq_data_opt)\nidxsorted = np.argsort(trq_data_opt)\nL_e = get_elong_matr(trq_data_opt, dtrq_data_opt, idxsorted)\ndiff_mat = get_diff_mat(data_len-1, idxsorted)\nL_diff = get_L_diff_mat(L_num, data_len-1)\nL_elo_diff = get_elo_diff_matr(L_e)\ntau_dtau = (-trq_data)*(-dtrq_data)\nL_tau_mat = get_L_num(tau_dtau)\nL_tau_vec = get_spr_int_vec(trq_data)\na_num = np.zeros((data_len-1, 1))\nc_num = np.zeros((data_len-1, 1))\ne_num = np.zeros((data_len-1, 1))\nh_num = np.zeros((data_len-1, 1))\nfor i in range(0, data_len-1):\n a_num[i][0]=a[i]\n c_num[i][0]=c[i]\n e_num[i][0]=e[i]\n h_num[i][0]=h[i]\n\nfeas_judge = 0\n\n# Nonlinear SEA Optimization\n# Create scalar optimization variable - the compliance:\nalpha_s = cp.Variable((data_len-1, 1))\n\n# Create constraints.\nconstraints = []\n\n# # alpha_s >= 0\nconstraints.append(diff_mat @ (L_num @ alpha_s) <= np.zeros((data_len-2,1)))\n\n# # E_s=0\nconstraints.append(L_tau_vec @ cp.vstack((alpha_s,alpha_s[np.newaxis,0])) <= 0)\nconstraints.append(-L_tau_vec @ cp.vstack((alpha_s,alpha_s[np.newaxis,0])) <= 0)\n\n\n# ------- Actuator Constraints -------\nconstraints.append(L_e @ alpha_s <= np.ones((data_len-1, 1))*delta_s_max)\nconstraints.append(-L_e @ alpha_s <= np.ones((data_len-1, 1))*delta_s_max)\nconstraints.append(B_num @ alpha_s <= np.ones((data_len-1, 1))*dq_max - a_num)\nconstraints.append(-B_num @ alpha_s <= np.ones((data_len-1, 1))*dq_max + a_num)\n\nconstraints.append(F_num @ alpha_s <= np.ones((data_len-1, 1))*tau_m_max - e_num)\nconstraints.append(-F_num @ alpha_s <= np.ones((data_len-1, 1))*tau_m_max + e_num)\n\nconstraints.append((F_num+(K_t**2/R_m)*B_num) @ alpha_s <= np.ones((data_len-1, 1))*(K_t*V_m/R_m) - e_num - a_num*(K_t**2/R_m))\nconstraints.append((F_num-(K_t**2/R_m)*B_num) @ alpha_s <= np.ones((data_len-1, 1))*(K_t*V_m/R_m) - e_num + a_num*(K_t**2/R_m))\nconstraints.append((-F_num+(K_t**2/R_m)*B_num) @ alpha_s <= np.ones((data_len-1, 1))*(K_t*V_m/R_m) + e_num - a_num*(K_t**2/R_m))\nconstraints.append((-F_num-(K_t**2/R_m)*B_num) @ alpha_s <= np.ones((data_len-1, 1))*(K_t*V_m/R_m) + e_num + a_num*(K_t**2/R_m))\n\np_1 = np.ones((data_len-1, 1))*dq_max - a_num\np_2 = np.ones((data_len-1, 1))*dq_max + a_num\np_3 = np.ones((data_len-1, 1))*tau_m_max - e_num\np_4 = np.ones((data_len-1, 1))*tau_m_max + e_num\np_5 = np.ones((data_len-1, 1))*(K_t*V_m/R_m) - e_num - a_num*(K_t**2/R_m)\np_6 = np.ones((data_len-1, 1))*(K_t*V_m/R_m) - e_num + a_num*(K_t**2/R_m)\np_7 = np.ones((data_len-1, 1))*(K_t*V_m/R_m) + e_num - a_num*(K_t**2/R_m)\np_8 = np.ones((data_len-1, 1))*(K_t*V_m/R_m) + e_num + a_num*(K_t**2/R_m)\n\nM_num = np.vstack([B_num, -B_num, F_num, -F_num, F_num+(K_t**2/R_m)*B_num, F_num-(K_t**2/R_m)*B_num, -F_num+(K_t**2/R_m)*B_num, -F_num-(K_t**2/R_m)*B_num])\np_num = np.vstack((p_1, p_2, p_3, p_4, p_5, p_6, p_7, p_8))\n\nu, s, vh = np.linalg.svd(F_num, full_matrices=True)\n# FF = vh.T.dot(np.diag(s)**2).dot(vh)\nFF = cp.Parameter((data_len-1, data_len-1), PSD=True)\nFF.value = vh.T @ np.diag(s)**2 @ vh\n# FF.value = F_num.T @ F_num\n# FF = F_num.T @ F_num\n\neF = e_num.T @ F_num\nee = e_num.T @ e_num\nconstraints.append(cp.quad_form(alpha_s, FF) + (2*eF)@alpha_s + ee <= (data_len-1)*(tau_m_RMS)**2)\n\n# Form objective.\nobj = cp.Minimize(cp.quad_form(alpha_s, G_num) + h_num.T @ alpha_s + w_num)\n\n# Form and solve problem.\nprob = cp.Problem(obj, constraints)\nprint(f\"1st: SEA Optimization\")\nprint(\"Problem is DCP:\", prob.is_dcp())\nprob.solve(solver=cp.MOSEK)\nprint(\"Status:\", prob.status)\nif prob.status == 'infeasible':\n feas_judge = 1\nelse:\n \n fig, axs = plt.subplots(1, 1)\n POS = np.zeros((data_len-1, 1))\n TRQ = np.zeros((data_len-1, 1))\n TRQ_s = np.zeros(data_len-1)\n ALP = np.zeros((data_len-1, 1))\n DISP = np.zeros((data_len-1, 1))\n DISPDot = np.zeros((data_len-1, 1))\n dTRQ_s = np.zeros(data_len-1)\n delta_s = np.zeros(data_len-1)\n \n for i in range(0, data_len-1):\n POS[i][0]=pos_data[i]\n TRQ[i][0]=-trq_data[i]\n TRQ_s[i] = -trq_data[i]\n ALP[i][0]=alpha_s.value[i][0]\n dTRQ_s[i]=-dtrq_data[i]\n \n elong = POS-(1/r)*(r*POS-r*(np.diag(-TRQ_s)@ALP))\n DISP[0][0]=POS[0][0]-(1/r)*(r*POS[0][0]-r*(TRQ_s[0]*ALP[0][0]))\n DISPDot[0][0]=vel_data[0]-(1/r)*(r*vel_data[0]-r*((-dtrq_data[0])*ALP[0][0]))\n for i in range(1, data_len-1):\n DISP[i][0]=DISP[i-1][0]+ALP[i-1][0]*(TRQ_s[i]-TRQ_s[i-1])\n DISPDot[i][0]=vel_data[i]-(1/r)*(r*vel_data[i]-r*((-dtrq_data[i])*ALP[i][0]))\n\n EL = np.zeros(data_len-1)\n for i in range(0, data_len-1):\n EL[i] = DISP[i][0]\n ALP_mask = np.gradient(EL, TRQ_s)\n delta_s[0]=0\n for i in range(1, data_len-1):\n DISPDot_list = np.zeros(i)\n t_set = np.zeros(i)\n for j in range(0, i): \n DISPDot_list[j]=DISPDot[j][0]\n t_set[j] = t[j]\n\n delta_s[i]=integrate.simpson(DISPDot_list, t_set)\n\n ALPHA_vec = np.zeros(data_len)\n for i in range(0, data_len-1):\n ALPHA_vec[i]=alpha_s.value[i][0]\n\n ALPHA_vec[-1]=alpha_s.value[0][0]\n a_opt = get_a_num(vel_data_opt)\n B_opt = get_B_num(dtrq_data_opt)\n c_opt = get_c_num(acc_data_opt)\n D_opt = get_D_num(dtrq_data_opt, ddtrq_data_opt)\n vel_m_opt_2d = a_num + B_num @ alpha_s.value\n acc_m_opt_2d = c_num + D_num @ alpha_s.value\n vel_m_opt_2d = np.vstack((vel_m_opt_2d, vel_m_opt_2d[0][0]))\n acc_m_opt_2d = np.vstack((acc_m_opt_2d, acc_m_opt_2d[0][0]))\n vel_m_opt = np.zeros(data_len)\n acc_m_opt = np.zeros(data_len)\n for i in range(0, data_len):\n vel_m_opt[i]=vel_m_opt_2d[i][0]\n acc_m_opt[i]=acc_m_opt_2d[i][0]\n tau_m_opt = I_m*acc_m_opt+b_m*vel_m_opt-(1/r)*trq_data\n Em_true = integrate.simpson((1/(K_m*K_m))*tau_m_opt**2 + tau_m_opt*vel_m_opt, t)\n Em_per = (Em_true-Em_0)*100/Em_0\n print(f\"Em_obj: {prob.value:.6f}; Em_true: {Em_true:.6f} ({Em_per:.1f}%)\")\n\n Em_new = np.zeros(mc_no)\n vel_data_opt_rms = np.sqrt(np.mean(vel_data_opt**2))\n acc_data_opt_rms = np.sqrt(np.mean(acc_data_opt**2))\n trq_data_rms = np.sqrt(np.mean(trq_data**2))\n dtrq_data_opt_rms = np.sqrt(np.mean(dtrq_data_opt**2))\n ddtrq_data_opt_rms = np.sqrt(np.mean(ddtrq_data_opt**2))\n for j in range(0, mc_no):\n vel_data_new = vel_data_opt + vel_data_opt_rms*2*error*(np.random.rand(data_len-1)-0.5)\n acc_data_new = acc_data_opt + acc_data_opt_rms*2*error*(np.random.rand(data_len-1)-0.5)\n trq_data_new = trq_data + trq_data_rms*2*error*(np.random.rand(data_len)-0.5)\n dtrq_data_new = dtrq_data_opt + dtrq_data_opt_rms*2*error*(np.random.rand(data_len-1)-0.5)\n ddtrq_data_new = ddtrq_data_opt + ddtrq_data_opt_rms*2*error*(np.random.rand(data_len-1)-0.5)\n a_new_1d = get_a_num(vel_data_new)\n B_new = get_B_num(dtrq_data_new)\n c_new_1d = get_c_num(acc_data_new)\n D_new = get_D_num(dtrq_data_new, ddtrq_data_new)\n a_new = a_new_1d[:, np.newaxis]\n c_new = c_new_1d[:, np.newaxis]\n\n vel_m_new_2d = a_new + B_new @ alpha_s.value\n acc_m_new_2d = c_new + D_new @ alpha_s.value\n vel_m_new_2d = np.vstack((vel_m_new_2d, vel_m_new_2d[0][0]))\n acc_m_new_2d = np.vstack((acc_m_new_2d, acc_m_new_2d[0][0]))\n vel_m_new = np.squeeze(vel_m_new_2d)\n acc_m_new = np.squeeze(acc_m_new_2d)\n \n tau_m_new = I_m*acc_m_new+b_m*vel_m_new-(1/r)*trq_data\n dq_m_new = vel_m_new\n Em_new[j] = integrate.simpson((1/(K_m*K_m))*tau_m_new**2 + tau_m_new*dq_m_new, t)\n\n Em_trial = np.mean(Em_new)\n Em_std = np.std(Em_new)\n\n Em_act_per = (Em_trial-Em_0)*100/Em_0\n Em_std_act = (Em_trial+2*Em_std-Em_0)*100/Em_0 - Em_act_per\n print(f\"Em_trial: {Em_act_per:.1f}%; stdev: {Em_std_act:.1f}%\")\n tidx = np.argmin(np.abs(TRQ_s))\n delta_s = delta_s - delta_s[tidx]\n axs.plot(delta_s, TRQ_s, 'o', label = 'nominal nonlinear')\n axs.legend()\n axs.set_xlabel('delta_s [rad]')\n axs.set_ylabel('tau_s [N-m]')\n plt.show()\n \n\n log_file_name = os.path.join('logs', 'sealog_' + cadence + '_' + joint + '_' + datetime.now().strftime(\"%m%d_%H%M%S\") + '.txt')\n with open(log_file_name, 'a') as f:\n for idx in range(0, data_len-1):\n f.write(f'{alpha_s.value[idx][0]},\\n')\n\n\n","sub_path":"python/sea_nonlin_cvxpy.py","file_name":"sea_nonlin_cvxpy.py","file_ext":"py","file_size_in_byte":19164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"402060514","text":"#encode: UTF-8\n\n#Autor: Natalia Meraz Tostado A01745008\n#Descripción: desarrollar un programa que imprima el rendimiento del auto en km/l, mi/gal y los litros de gasolina necesarios\n\nmilla = float(1.609344)\nlitro = float(0.264172051)\n\nkmRecorridos = float(input(\"Teclea el número de km recorridos: \"))\ngasolina = float(input(\"Teclea el número de litros de gasolina usados: \"))\nkmRecorrer = float(input(\"¿Cuántos kilómetros vas a recorrer? \"))\n\ndef kilometrosEntreLitros(kmRecorridos, gasolina): #Calcula el rendimiento del auto en km/l\n kml = kmRecorridos / gasolina\n return kml\n\ndef millasEntreGalon(milla, litro, kml): #Calcula el rendimiento del auto en mi/gal\n migal = kml / (milla * litro)\n return migal\n\ndef kmPorRecorrer(kmRecorrer, gasolina, kmRecorridos): #calcula la gasolina que va a necesitar para ciertos km\n litrosGas = (kmRecorrer * gasolina) / kmRecorridos\n return litrosGas\n\ndef main():\n kml = kilometrosEntreLitros(kmRecorridos, gasolina)\n migal = millasEntreGalon(milla, litro, kml)\n litrosGas = kmPorRecorrer(kmRecorrer, gasolina, kmRecorridos)\n print(\"\")\n print(\"Si recorres\",kmRecorridos, \"kms con\", gasolina, \"litros de gasolina, el rendimiento es:\")\n print(\"%.2f km/l\" % kml)\n print(\"%.2f mi/gal\" % migal)\n print(\"\")\n print(\"Para recorrer\", kmRecorrer, \"km. necesitas %.2f litros de gasolina\" % litrosGas)\n\nmain()\n","sub_path":"autos.py","file_name":"autos.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"214197983","text":"\"\"\"Scanning functions for netCDF files.\"\"\"\n\n# This file is part of the 'tomate' project\n# (http://github.com/Descanonge/tomate) and subject\n# to the MIT License as defined in the file 'LICENSE',\n# at the root of this project. © 2020 Clément HAËCK\n\n\nfrom typing import Any, Dict, List, Optional, Tuple\n\ntry:\n import netCDF4 as nc\nexcept ImportError:\n pass\n\nfrom tomate.filegroup.coord_scan import CoordScan\nfrom tomate.filegroup.filegroup_netcdf import FilegroupNetCDF\n\n\ndef scan_in_file(cs: CoordScan, file: nc.Dataset,\n values: Optional[List[float]]) -> Tuple[List[float], List[int]]:\n \"\"\"Scan netCDF file for coordinates values and in-file index.\n\n Convert time values to CS units. Variable name must\n be 'time'.\n \"\"\"\n nc_var = file[cs.name]\n in_values = list(nc_var[:])\n in_idx = list(range(len(in_values)))\n return in_values, in_idx\n\n\ndef scan_variables(cs: CoordScan, file: nc.Dataset,\n values: List[float]) -> Tuple[List[str]]:\n \"\"\"Scan netCDF file for variables names.\"\"\"\n variables = [var for var in file.variables.keys()\n if var not in file.dimensions]\n return variables, variables\n\n\ndef scan_variables_attributes(fg: FilegroupNetCDF, file: nc.Dataset,\n variables: List[str]) -> Dict[str, Dict[str, Any]]:\n \"\"\"Scan variables attributes in netCDF files.\"\"\"\n attrs = {}\n for var in variables:\n attrs_var = {}\n nc_var = file[var]\n attributes = nc_var.ncattrs()\n for attr in attributes:\n attrs_var[attr] = nc_var.getncattr(attr)\n\n attrs[var] = attrs_var\n return attrs\n\n\ndef scan_infos(fg: FilegroupNetCDF, file: nc.Dataset) -> Dict[str, Any]:\n \"\"\"Scan for general attributes in a netCDF file.\"\"\"\n infos = {}\n for name in file.ncattrs():\n value = file.getncattr(name)\n infos[name] = value\n return infos\n\n\ndef scan_units(cs: CoordScan, file: nc.Dataset) -> Dict[str, str]:\n \"\"\"Scan for the units of the time variable.\"\"\"\n nc_var = file[cs.name]\n units = nc_var.getncattr('units')\n return {'units': units}\n","sub_path":"src/tomate/scan_library/nc.py","file_name":"nc.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"640959631","text":"import io\nimport xlsxwriter\nfrom . import models\nfrom datetime import datetime\nimport decimal\n\n\ndef date_parse(str, fmt='%Y-%m-%d %H:%M:%S'):\n if str == None:\n return None\n return datetime.strptime(str, fmt)\n\n\ndef cell(i, j):\n char = \"A\"\n char = chr(ord(char[0]) + j - 1)\n return f'{char}{i}'\n\n\ndef date_fmt(date):\n if date == None:\n return None\n return date.strftime(\"%d/%m/%Y\")\n\n\ndef get_doc_ref(sale, doc_type):\n aggr = True if sale.aggregate else False\n objs_aggr = models.AggregateDocument.objects\n objs = models.Document.objects\n doc_ref = None\n if aggr:\n doc = objs.filter(doc_type=doc_type, sale=sale).first()\n if not doc:\n doc = objs_aggr.filter(doc_type=doc_type, aggregate_sale=sale.aggregate).first()\n if doc:\n doc_ref = doc.ref_number\n\n else:\n doc = objs.filter(doc_type=doc_type, sale=sale).first()\n if doc:\n doc_ref = doc.ref_number\n return doc_ref\n\n\ndef get_refs(sale):\n exit_ref = get_doc_ref(sale, models.Document.DOC_EXIT)\n c2_ref = get_doc_ref(sale, models.Document.DOC_C2)\n c2_ref = 'As per TRA comment' if not c2_ref and sale.docs_flag == 2 else c2_ref\n assessment_ref = get_doc_ref(sale, models.Document.DOC_ASSESSMENT)\n\n return [c2_ref, assessment_ref, exit_ref]\n\n\ndef export_report(request, sales):\n output = io.BytesIO()\n workbook = xlsxwriter.Workbook(output)\n\n main = workbook.add_worksheet(\"Report\")\n headers = ['ID', 'TRANS_DATE', 'CUSTOMER', 'DELIVERY NOTE', 'VEH#',\n 'TAX INVOICE', 'SO#', 'PRODUCT', 'QTY(TONS)', 'VALUE', 'DESTINATION', 'VEH# TRAILER', 'AGENT', 'C2', 'ASSESSMENT', 'EXIT/RELEASE', 'ASSIGN#', 'INVOICE NO']\n rows = []\n\n for prj in sales:\n row = []\n row.append(prj.id)\n row.append(date_fmt(date_parse(prj.transaction_date)))\n row.append(prj.customer_name)\n row.append(prj.delivery_note)\n row.append(prj.vehicle_number)\n row.append(prj.tax_invoice)\n row.append(prj.sales_order)\n row.append(prj.product_name)\n row.append(float(prj.quantity))\n row.append(float(prj.total_value))\n row.append(prj.destination)\n row.append(prj.vehicle_number_trailer)\n row.append(prj.agent.code if prj.agent else 'None')\n row.extend(get_refs(prj))\n row.append(prj.assign_no)\n row.append(prj.invoice.number if prj.invoice else 'None')\n rows.append(row)\n\n for j, col in enumerate(headers, start=1):\n main.write(f'{cell(1, j)}', col)\n\n for i, row in enumerate(rows, start=2):\n for j, col in enumerate(row, start=1):\n main.write(f'{cell(i, j)}', col)\n workbook.close()\n xlsx_data = output.getvalue()\n return xlsx_data\n\n\ndef export_customers(request, customers):\n output = io.BytesIO()\n workbook = xlsxwriter.Workbook(output)\n\n main = workbook.add_worksheet(\"Report\")\n headers = ['CUSTOMER', 'COUNT', 'FACTORY VALUE', 'FACTORY VOLUME', 'BORDER VALUE', 'BORDER VOLUME', '% VOLUME']\n # columns = ['customer_name', 'qty', 'total_value', 'total_volume', 'total_value2', 'total_volume2']\n rows = []\n\n for prj in customers:\n row = []\n vol2 = prj['total_volume2'] if prj['total_volume2'] else 0\n val2 = prj['total_value2'] if prj['total_value2'] else 0\n pct = 100*(vol2/prj['total_volume'])\n row.append(prj['customer_name'])\n row.append(prj['qty'])\n row.append(prj['total_value'])\n row.append(prj['total_volume'])\n row.append(val2)\n row.append(vol2)\n row.append(float(f'{pct:.2f}'))\n\n rows.append(row)\n\n for j, col in enumerate(headers, start=1):\n main.write(f'{cell(1, j)}', col)\n\n for i, row in enumerate(rows, start=2):\n for j, col in enumerate(row, start=1):\n main.write(f'{cell(i, j)}', col)\n workbook.close()\n xlsx_data = output.getvalue()\n return xlsx_data\n","sub_path":"backend_rest/sales/exports.py","file_name":"exports.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"454639416","text":"import xml.etree.ElementTree as ET\nfrom src.models.project_singleton import *\nfrom src.models.production_line import *\nfrom src.models.machine import *\nfrom src.list.production_line.production_line_list import *\nfrom src.models.product import *\nfrom src.list.products.products_list import *\n\nclass MachineController:\n\n def __init__(self):\n self.file_path = ProjectSingleton().file_machine\n ProjectSingleton().machine = Machine(\n qt_production_lines = self.production_lines_qt(),\n production_lines_list = self.build_production_line_list(),\n products_list = self.build_products_list()\n )\n\n def production_lines_qt(self):\n tree = ET.parse(self.file_path)\n root = tree.getroot()\n for element in root:\n if element.tag == \"CantidadLineasProduccion\":\n return int(element.text)\n\n def build_production_line_list(self):\n tree = ET.parse(self.file_path)\n root = tree.getroot()\n production_line_list = ProductionLineList()\n for element in root:\n \n if element.tag == \"ListadoLineasProduccion\":\n\n for production_line in element:\n\n pr_l = ProductionLine()\n for production_element in production_line:\n\n if production_element.tag == \"Numero\":\n pr_l.number = int(production_element.text)\n elif production_element.tag == \"CantidadComponentes\":\n pr_l.qt_components = int(production_element.text)\n elif production_element.tag == \"TiempoEnsamblaje\":\n pr_l.assembly_time = int(production_element.text)\n pr_l.missing_assembly_time = int(production_element.text) - 1\n \n production_line_list.insert(production_line = pr_l)\n\n return production_line_list\n\n def build_products_list(self):\n tree = ET.parse(self.file_path)\n root = tree.getroot()\n products_list = ProductsList()\n for element in root:\n\n if element.tag == \"ListadoProductos\":\n \n for product in element:\n \n prod = Product()\n for product_element in product:\n \n if product_element.tag == \"nombre\":\n prod.name = str(product_element.text)\n elif product_element.tag == \"elaboracion\":\n prod.build_instructions = str(product_element.text)\n\n products_list.insert(product = prod)\n\n return products_list","sub_path":"src/controllers/machine_controller.py","file_name":"machine_controller.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"571529247","text":"import sys\nimport os\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nfrom readablepyomo.readablepyomo import *\nfrom readablepyomo.glpk import Glpk\n\nFood = Set(\"F\")\nNutrients = Set(\"N\")\n\nc = Parameter(\"c\").over(Food).within(NonNegativeReals)\na = Parameter(\"a\").over(Food, Nutrients).within(NonNegativeReals)\nNmin = Parameter(\"Nmin\").over(Nutrients).within(NonNegativeReals).with_default(0.0)\nNmax = Parameter(\"Nmax\").over(Nutrients).within(NonNegativeReals).with_default(float('inf'))\nV = Parameter(\"V\").over(Food).within(NonNegativeReals)\nVmax = Parameter(\"Vmax\").within(NonNegativeReals)\n\nx = Variable(\"x\").over(Food).within(NonNegativeIntegers)\n\nGlpk.solve(\n\tgiven(\n\t\t\tsets(Food, Nutrients),\n\t\t\tparameters(c, a, Nmin, Nmax, V, Vmax),\n\t\t\tvariables(x)\n\t\t) \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t.minimize(sum_over(Food)(c * x)) \t\t\t\t\t\t\t\t\t\\\n\t\t.such_that(sum_over(Food)(a * x).is_within(Nmin, Nmax)) \t\t\t\\\n\t\t.such_that(sum_over(Food)(V * x).is_less_than_or_equal_to(Vmax)),\n\t\t\"diet.dat\"\n\t).write()","sub_path":"test/readable-diet.py","file_name":"readable-diet.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"464073691","text":"'''\n Copyright 2010 Ryan Svihla\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n'''\n\nmock_func_calls = dict()\nfunc_stubs = dict()\noriginal_func = dict() \noriginal_classdef = dict()\nmockinstancecalls = dict()\nmockinstancestubs = dict()\n\nclass MethodCall(object):\n \n def __init__(self,methodname, args):\n self.methodname = methodname; self.args = args\n \nclass ClassStubs(object):\n \"\"\"default domain object that represents stubs\"\"\"\n def __init__(self, methodname, returns = None, args= None, times = None):\n \"\"\"ideally stubs should always have returns set, otherwise they're not stubs. \n args is used to match against later on asserts. \n times is currently a place holder and not used at this time\n \"\"\"\n self.methodname = methodname; self.returns = returns;self.args = args;self.times = times;\n ","sub_path":"cert/cert/mock/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"562030808","text":"import numpy as np\nfrom keras.layers import Activation, Dense, Input, concatenate, LSTM\nfrom keras.models import Model, Sequential\nfrom keras.optimizers import Adam\nfrom keras.utils import to_categorical\n\nclass A2CAgent:\n def __init__(self, game_length, action_size, n_options, hid_size):\n self.render = True\n self.load_model = False\n self.game_length = game_length\n self.action_size = action_size\n self.value_size = 1\n self.n_options = n_options\n self.hid_size = hid_size\n\n self.discount_factor = 0.99\n self.actor_lr = 0.001\n self.critic_lr = 0.005\n\n self.actor = self.build_actor()\n self.critic = self.build_critic()\n\n if self.load_model:\n self.actor.load_weights(\"./save_model/Cowbull_actor.h5\")\n self.critic.load_weights(\"./save_model/Cowbull_critic.h5\")\n\n # approximate policy and value using Neural Network\n # actor: state is input and probability of each action is output of model\n def build_actor(self):\n state = Input(\n shape=((\n self.game_length * (1 + self.action_size) * self.n_options),1,))\n x = LSTM(\n self.hid_size, activation='tanh', kernel_initializer='he_uniform')(state)\n \n x1 = Dense(\n self.n_options,\n activation='softmax',\n kernel_initializer='he_uniform')(x)\n x2 = Dense(\n self.n_options,\n activation='softmax',\n kernel_initializer='he_uniform')(x)\n x3 = Dense(\n self.n_options,\n activation='softmax',\n kernel_initializer='he_uniform')(x)\n x4 = Dense(\n self.n_options,\n activation='softmax',\n kernel_initializer='he_uniform')(x)\n\n output = concatenate([x1, x2, x3, x4])\n\n actor = Model(inputs=state, outputs=output)\n\n actor.summary()\n actor.compile(\n loss='categorical_crossentropy', optimizer=Adam(lr=self.actor_lr))\n return actor\n\n # critic: state is input and value of state is output of model\n def build_critic(self):\n state = Input(\n shape=((\n self.game_length * (1 + self.action_size) * self.n_options),1,))\n x = LSTM(\n self.hid_size, activation='tanh', kernel_initializer='he_uniform')(state)\n output = Dense(\n self.value_size,\n activation='linear',\n kernel_initializer='he_uniform')(x)\n\n critic = Model(inputs=state, outputs=output)\n\n critic.summary()\n critic.compile(loss=\"mse\", optimizer=Adam(lr=self.critic_lr))\n\n return critic\n\n # using the output of policy network, pick action stochastically\n def get_action(self, state):\n\n action = []\n l1 = to_categorical(\n state[:, :self.action_size], num_classes=self.n_options)\n l2 = np.zeros((self.game_length, 1, self.n_options))\n l2[:, 0, 0] = state[:, self.action_size]\n state = np.concatenate((l1, l2), axis=1)\n state = np.reshape(\n state,\n (1, (self.game_length * (1 + self.action_size) * self.n_options), 1))\n\n policy = self.actor.predict(state, batch_size=1).flatten()\n for i in range(self.action_size):\n\n action.append(\n np.random.choice(\n np.arange(0, self.n_options),\n p=policy[i * self.n_options:(i + 1) * self.n_options]))\n\n return action\n\n # update policy network every episode\n def train_model(self, state, action, reward, next_state):\n\n l1 = to_categorical(\n state[:, :self.action_size], num_classes=self.n_options)\n l2 = np.zeros((self.game_length, 1, self.n_options))\n l2[:, 0, 0] = state[:, self.action_size]\n state = np.concatenate((l1, l2), axis=1)\n\n l1 = to_categorical(\n next_state[:, :self.action_size], num_classes=self.n_options)\n l2 = np.zeros((self.game_length, 1, self.n_options))\n l2[:, 0, 0] = next_state[:, self.action_size]\n next_state = np.concatenate((l1, l2), axis=1)\n\n state = np.reshape(\n state,\n (1, (self.game_length * (1 + self.action_size) * self.n_options), 1))\n next_state = np.reshape(\n next_state,\n (1, (self.game_length * (1 + self.action_size) * self.n_options), 1))\n\n target = np.zeros((1, self.value_size))\n advantages = np.zeros((self.action_size, self.n_options))\n\n value = self.critic.predict(state)[0]\n\n next_value = self.critic.predict(next_state)[0]\n\n for i in range(self.action_size):\n advantages[i][action[i]] = reward + self.discount_factor * (\n next_value) - value\n\n advantages = np.reshape(advantages,\n (1, (self.action_size * self.n_options)))\n\n target[0][0] = reward + self.discount_factor * next_value\n\n self.actor.fit(state, advantages, epochs=1, verbose=0)\n self.critic.fit(state, target, epochs=1, verbose=0)","sub_path":"approach_2/A2CAgent.py","file_name":"A2CAgent.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"75113909","text":"import os\n\nimport pytest\nfrom django.test.client import Client\nfrom django.urls import reverse\nfrom pytest_django.asserts import assertFormError\n\nfrom hawc.apps.lit import constants, models\n\n\n@pytest.mark.vcr\n@pytest.mark.django_db\ndef test_pubmed_search(db_keys):\n # Check when searching, the same number of identifiers and refs are\n # created, with refs fully-qualified with identifiers and searches\n\n # setup\n assessment_pk = db_keys.assessment_working\n client = Client()\n assert client.login(username=\"pm@pm.com\", password=\"pw\") is True\n data = {\n \"source\": 1, # PubMed\n \"title\": \"pm search\",\n \"slug\": \"pm-search\",\n \"description\": \"search description\",\n \"search_string\": \"1998 Longstreth health risks ozone depletion\",\n }\n\n # get initial counts\n initial_searches = models.Search.objects.count()\n initial_identifiers = models.Identifiers.objects.count()\n initial_refs = models.Reference.objects.count()\n\n # term returns 200+ literature\n data[\n \"search_string\"\n ] = \"\"\"(monomethyl OR MEP OR mono-n-butyl OR MBP OR mono (3-carboxypropyl) OR mcpp OR monobenzyl OR mbzp OR mono-isobutyl OR mibp OR mono (2-ethylhexyl) OR mono (2-ethyl-5-oxohexyl) OR meoph OR mono (2-ethyl-5-carboxypentyl) OR mecpp OR mepp OR mono (2-ethyl-5-hydroxyhexyl) OR mehp OR mono (2-ethyl-5-oxyhexyl) OR mono (2-ethyl-4-hydroxyhexyl) OR mono (2-ethyl-4-oxyhexyl) OR mono (2-carboxymethyl) OR mmhp OR mehp OR dehp OR 2-ethylhexanol OR (phthalic acid)) AND (liver OR hepato* OR hepat*) AND ((cell proliferation) OR (cell growth) OR (dna replication) OR (dna synthesis) OR (replicative dna synthesis) OR mitosis OR (cell division) OR (growth response) OR hyperplasia OR hepatomegaly) AND (mouse OR rat OR hamster OR rodent OR murine OR Mus musculus or Rattus)\"\"\"\n\n # check successful post\n url = reverse(\"lit:search_new\", kwargs={\"pk\": assessment_pk})\n response = client.post(url, data)\n assert response.status_code in [200, 302]\n\n # run search\n search = models.Search.objects.latest()\n url = reverse(\"lit:search_query\", kwargs={\"pk\": assessment_pk, \"slug\": search.slug})\n response = client.get(url, data)\n assert response.status_code in [200, 302]\n\n assert models.Search.objects.count() == initial_searches + 1\n i_count = models.Identifiers.objects.count()\n added_ids = i_count - initial_identifiers\n assert added_ids > 200\n assert models.Reference.objects.count() == added_ids + initial_refs\n\n # make sure all each reference has an identifier\n i_pks = models.Identifiers.objects.values_list(\"pk\", flat=True)\n assert models.Reference.objects.filter(identifiers__in=i_pks).count() == i_count\n\n\n@pytest.mark.vcr\n@pytest.mark.django_db\ndef test_pubmed_import(db_keys):\n # ensure successful PubMed import\n # setup\n assessment_pk = db_keys.assessment_working\n client = Client()\n assert client.login(username=\"pm@pm.com\", password=\"pw\") is True\n data = {\n \"source\": 1, # PubMed\n \"title\": \"pm search\",\n \"slug\": \"pm-search\",\n \"description\": \"search description\",\n \"search_string\": \"1998 Longstreth health risks ozone depletion\",\n }\n\n # get initial counts\n initial_searches = models.Search.objects.count()\n initial_identifiers = models.Identifiers.objects.count()\n initial_refs = models.Reference.objects.count()\n\n data[\n \"search_string\"\n ] = \"10357793, 20358181, 6355494, 8998951, 3383337, 12209194, 6677511, 11995694, 1632818, 12215663, 3180084, 14727734, 23625783, 11246142, 10485824, 3709451, 2877511, 6143560, 3934796, 8761421\"\n\n # check successful post\n url = reverse(\"lit:import_new\", kwargs={\"pk\": assessment_pk})\n response = client.post(url, data)\n assert response.status_code in [200, 302]\n\n # check new counts\n assert models.Search.objects.count() == initial_searches + 1\n assert models.Identifiers.objects.count() == initial_identifiers + 20\n assert models.Reference.objects.count() == initial_refs + 20\n\n # make sure all each reference has an identifier\n i_pks = models.Identifiers.objects.values_list(\"pk\", flat=True)\n assert i_pks.count() == initial_identifiers + 20\n assert (\n models.Reference.objects.filter(identifiers__in=i_pks).count() == initial_identifiers + 20\n )\n\n\n@pytest.mark.vcr\n@pytest.mark.django_db\ndef test_successful_single_hero_id(db_keys):\n \"\"\"\n Test that a single hero ID can be added. Confirm:\n 1) Reference created\n 2) Reference associated with search\n 3) Reference associated with literature\n \"\"\"\n # setup\n assessment_pk = db_keys.assessment_working\n client = Client()\n assert client.login(username=\"pm@pm.com\", password=\"pw\") is True\n data = {\n \"source\": 2, # HERO\n \"title\": \"example search\",\n \"slug\": \"example-search\",\n \"description\": \"search description\",\n \"search_string\": \"51001\",\n }\n\n # get initial counts\n initial_searches = models.Search.objects.count()\n initial_identifiers = models.Identifiers.objects.count()\n initial_refs = models.Reference.objects.count()\n\n # check successful post\n url = reverse(\"lit:import_new\", kwargs={\"pk\": assessment_pk})\n response = client.post(url, data)\n assert response.status_code in [200, 302]\n\n # check expected results\n assert models.Search.objects.count() == initial_searches + 1\n assert models.Identifiers.objects.count() == initial_identifiers + 1\n assert models.Reference.objects.count() == initial_refs + 1\n\n search = models.Search.objects.get(assessment=assessment_pk, title=\"example search\")\n ref = models.Reference.objects.get(title=\"Effect of thyroid hormone on growth and development\")\n ident = models.Identifiers.objects.get(unique_id=\"51001\", database=constants.HERO)\n\n assert ref.searches.all()[0] == search\n assert ref.identifiers.all()[0] == ident\n\n\n@pytest.mark.vcr\n@pytest.mark.django_db\ndef test_failed_hero_id(db_keys):\n \"\"\"\n Test that a hero ID that doesn't exist fails gracefully. Confirm:\n 1) Search created\n 2) No reference created, no literature\n \"\"\"\n # setup\n assessment_pk = db_keys.assessment_working\n client = Client()\n assert client.login(username=\"pm@pm.com\", password=\"pw\") is True\n data = {\n \"source\": 2, # HERO\n \"title\": \"example search\",\n \"slug\": \"example-search\",\n \"description\": \"search description\",\n \"search_string\": \"1200\",\n }\n\n # get initial counts\n initial_searches = models.Search.objects.count()\n\n # known hero ID that doesn't exist\n data[\"search_string\"] = \"9999999\"\n url = reverse(\"lit:import_new\", kwargs={\"pk\": assessment_pk})\n response = client.post(url, data)\n\n assertFormError(\n response,\n \"form\",\n \"search_string\",\n \"Import failed; the following HERO IDs could not be imported: 9999999\",\n )\n assert models.Search.objects.count() == initial_searches\n\n\n@pytest.mark.vcr\n@pytest.mark.django_db\ndef test_existing_pubmed_hero_add(db_keys):\n \"\"\"\n Check that search is complete, new identifier is created, but is\n associated with existing PubMed Reference\n \"\"\"\n # setup\n assessment_pk = db_keys.assessment_working\n client = Client()\n assert client.login(username=\"pm@pm.com\", password=\"pw\") is True\n data = {\n \"source\": 2, # HERO\n \"title\": \"example search\",\n \"slug\": \"example-search\",\n \"description\": \"search description\",\n \"search_string\": \"1200\",\n }\n pm_data = {\n \"source\": 1, # PubMed\n \"title\": \"pm search\",\n \"slug\": \"pm-search\",\n \"description\": \"search description\",\n \"search_string\": \"1998 Longstreth health risks ozone depletion\",\n }\n\n # get initial counts\n initial_searches = models.Search.objects.count()\n initial_identifiers = models.Identifiers.objects.count()\n initial_refs = models.Reference.objects.count()\n\n # build PubMed\n url = reverse(\"lit:search_new\", kwargs={\"pk\": assessment_pk})\n response = client.post(url, pm_data)\n assert response.status_code in [200, 302]\n\n # Run PubMed Query\n url_run_query = reverse(\n \"lit:search_query\", kwargs={\"pk\": assessment_pk, \"slug\": pm_data[\"slug\"]},\n )\n response = client.get(url_run_query)\n assert response.status_code in [200, 302]\n\n # assert that one object was created\n assert models.Search.objects.count() == initial_searches + 1\n assert models.Identifiers.objects.count() == initial_identifiers + 1\n assert models.Reference.objects.count() == initial_refs + 1\n\n # build HERO\n data[\"search_string\"] = \"1200\"\n url = reverse(\"lit:import_new\", kwargs={\"pk\": assessment_pk})\n response = client.post(url, data)\n assert response.status_code in [200, 302]\n\n # assert that search & identifier created but not new reference\n assert models.Search.objects.count() == initial_searches + 2\n assert models.Identifiers.objects.count() == initial_identifiers + 2\n assert models.Reference.objects.count() == initial_refs + 1\n\n ref = models.Reference.objects.get(authors_short=\"Longstreth J et al.\")\n assert ref.searches.count() == 2\n assert ref.identifiers.count() == 2\n\n\nclass RisFile:\n def __init__(self, fn):\n self.path = fn\n\n\n@pytest.mark.vcr\n@pytest.mark.django_db\ndef test_ris_import(db_keys):\n # setup\n assessment_id = db_keys.assessment_working\n search = models.Search.objects.create(\n assessment_id=assessment_id,\n search_type=\"i\",\n source=constants.RIS,\n title=\"ris\",\n slug=\"ris\",\n description=\"-\",\n )\n search.import_file = RisFile(os.path.join(os.path.dirname(__file__), \"data/single_ris.txt\"))\n\n # get initial counts\n initial_identifiers = models.Identifiers.objects.count()\n initial_refs = models.Reference.objects.count()\n\n search.run_new_import()\n ris_ref = models.Reference.objects.filter(\n title=\"Early alterations in protein and gene expression in rat kidney following bromate exposure\"\n ).first()\n assert models.Reference.objects.count() == initial_refs + 1\n assert models.Identifiers.objects.count() == initial_identifiers + 3\n assert ris_ref.identifiers.count() == 3\n\n assert ris_ref.identifiers.filter(database=constants.PUBMED).count() == 1\n assert ris_ref.identifiers.filter(database=constants.RIS).count() == 1\n assert ris_ref.identifiers.filter(database=constants.DOI).count() == 1\n\n # assert Pubmed XML content is loaded\n assert (\n \"\" in ris_ref.identifiers.filter(database=constants.PUBMED).first().content\n )\n\n\n@pytest.mark.django_db\ndef test_ris_import_with_existing(db_keys):\n # setup\n assessment_id = db_keys.assessment_working\n\n # get initial counts\n initial_identifiers = models.Identifiers.objects.count()\n initial_refs = models.Reference.objects.count()\n\n # ris file should contain the two identifiers above\n search = models.Search.objects.create(\n assessment_id=assessment_id,\n search_type=\"i\",\n source=constants.RIS,\n title=\"ris\",\n slug=\"ris\",\n description=\"-\",\n )\n search.import_file = RisFile(os.path.join(os.path.dirname(__file__), \"data/single_ris.txt\"))\n\n # create existing identifiers\n models.Identifiers.objects.create(database=constants.PUBMED, unique_id=\"19425233\", content=\"\")\n models.Identifiers.objects.create(\n database=constants.DOI, unique_id=\"10.1016/j.fct.2009.02.003\", content=\"\",\n )\n search.run_new_import()\n\n ris_ref = models.Reference.objects.filter(\n title=\"Early alterations in protein and gene expression in rat kidney following bromate exposure\"\n ).first()\n assert (\n models.Reference.objects.count() == initial_refs + 1\n ) # only one copy of ref should be made\n assert (\n models.Identifiers.objects.count() == initial_identifiers + 3\n ) # should be 3 different identifiers\n assert ris_ref.identifiers.count() == 3\n\n # ensure new ones aren't created\n assert ris_ref.identifiers.filter(database=constants.PUBMED).count() == 1\n assert ris_ref.identifiers.filter(database=constants.RIS).count() == 1\n assert ris_ref.identifiers.filter(database=constants.DOI).count() == 1\n","sub_path":"tests/hawc/apps/lit/test_lit_imports.py","file_name":"test_lit_imports.py","file_ext":"py","file_size_in_byte":12268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"81329463","text":"# Given an integer array nums, find the contiguous subarray (containing at least one number)\r\n# which has the largest sum and return its sum.\r\n\r\n# Example:\r\n# Input: [-2,1,-3,4,-1,2,1,-5,4],\r\n# Output: 6\r\n# Explanation: [4,-1,2,1] has the largest sum = 6.\r\n\r\n# Follow up:\r\n# (1)If you have figured out the O(n) solution, try coding another solution using the divide and conquer \r\n# approach, which is more subtle.\r\n# (2) return the start and end index of max subarray and the max subarray\r\n\r\n\r\n# Method 1: brute force\r\nimport sys\r\nclass Solution(object):\r\n def maxSubArray(self, nums):\r\n res = -sys.maxsize\r\n for i in range(0, len(nums)):\r\n s = 0\r\n for j in range (i, len(nums)):\r\n s += nums[j]\r\n res = max(res, s)\r\n\r\n return res\r\n\r\n# Time: O(n^2)\r\n# Space: O(n^2)\r\n\r\n\r\n# Method 2: Divide and Conquer\r\nclass Solution(object):\r\n def maxSubArray(self, nums):\r\n return self.helper(nums, 0, len(nums)-1)\r\n \r\n def helper(self, nums, left, right): \r\n if left == right:\r\n return nums[left]\r\n \r\n mid = (left + right) // 2\r\n \r\n left_sum = self.helper(nums, left, mid)\r\n right_sum = self.helper(nums, mid+1, right)\r\n cross_sum = self.cross_sum(nums, left, right, mid)\r\n \r\n return max(left_sum, right_sum, cross_sum)\r\n \r\n \r\n def cross_sum(self, nums, left, right, mid):\r\n if left == right:\r\n return nums[left]\r\n\r\n left_subsum = float('-inf')\r\n curr_sum = 0\r\n for i in range(mid, left-1, -1): # from mid to left-1\r\n curr_sum += nums[i]\r\n left_subsum = max(left_subsum, curr_sum)\r\n\r\n right_subsum = float('-inf')\r\n curr_sum = 0\r\n for j in range(mid+1, right+1):\r\n curr_sum += nums[j]\r\n right_subsum = max(right_subsum, curr_sum)\r\n\r\n return left_subsum + right_subsum\r\n \r\n# Time: O(NlogN)\r\n# Space: O(logN) to keep the recursion stack\r\n\r\n\r\n\r\n# Method 3: Greedy algorithm\r\nclass Solution(object):\r\n def maxSubArray(self, nums):\r\n res = nums[0]\r\n curr_sum = 0\r\n for item in nums:\r\n curr_sum = max(curr_sum + item, item) # curr_sum = curr_sum + item only if curr_sum > 0\r\n res = max(res, curr_sum)\r\n return res\r\n \r\n# nums =[-2, 1, -3, 4, -1, 2, 1, -5, 4]\r\n# curr_sum = -2, 1, -2, 4, 3, 5, 6, 1, 5 --> to see 'accumulate add' or 'restart from curr item' \r\n# result = -2, 1, 1, 4, 4, 5, 6, 6, 6\r\n\r\n# Time: O(N)\r\n# Space: O(1)\r\n\r\n\r\n# Method 4: Dynamic Programming\r\nclass Solution:\r\n def maxSubArray(self, nums):\r\n res = nums[0]\r\n \r\n for i in range(1, len(nums)):\r\n if nums[i-1] > 0: # nums[i]: record the curr_sum by now\r\n nums[i] += nums[i-1]\r\n res = max(res, nums[i])\r\n\r\n return res\r\n \r\n# Time: O(N)\r\n# Space: O(1)\r\n\r\n\r\n# nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\r\n# nums[i] = -2, 1, -3, 4, 3, 5, 6, 1, 5\r\n# res = -2, 1, 1, 4, 4, 5, 6, 6, 6\r\n\r\n\r\n\r\n# [TRANSFORMATION]\r\n# Find the start and end index of the maximum subarray\r\nclass Solution:\r\n def maxSubArray(self, nums):\r\n dp = nums.copy()\r\n \r\n res = dp[0]\r\n \r\n for i in range(1, len(dp)):\r\n if dp[i-1] > 0: # nums[i]: record the curr_sum by now\r\n dp[i] += dp[i-1]\r\n if dp[i] > res:\r\n res = dp[i]\r\n end_index = i\r\n \r\n j = end_index\r\n temp = 0\r\n while temp != res and j >= 0:\r\n temp += nums[j]\r\n j -= 1\r\n \r\n print(nums[j+1 : end_index+1]) \r\n return res\r\n\r\n# Time: O(N)\r\n# Space: O(1)\r\n\r\n# if __name__ == \"__main__\":\r\n# nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\r\n# print(Solution().maxSubArray(nums))\r\n\r\n# [4, -1, 2, 1]\r\n# 6","sub_path":"01 Array/53. Maximum Subarray.py","file_name":"53. Maximum Subarray.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"543160333","text":"\"\"\"\nPanel detection class\n\"\"\"\n\nimport numpy as np\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\nimport cv2\nimport matplotlib.pyplot as plt\nfrom skimage.transform import hough_line, hough_line_peaks\nfrom matplotlib import cm\nimport requests\nfrom PIL import Image\nfrom os import path\n\npanel_seg_model_path = path.join(path.dirname(__file__), 'VGG16Net_ConvTranpose_complete.h5')\npanel_classification_model_path = path.join(path.dirname(__file__), 'VGG16_classification_model.h5')\n\nclass PanelDetection():\n '''\n A class for training a deep learning architecture, \n detecting solar arrays from a satellite image, performing spectral\n clustering, and predicting the Azimuth.\n '''\n def __init__(self, model_file_path = './VGG16Net_ConvTranpose_complete.h5', \n classifier_file_path = './VGG16_classification_model.h5'):\n \n #This is the model used for detecting if there is a panel or not\n self.classifier = load_model(classifier_file_path, \n custom_objects=None, \n compile=False)\n \n self.model = load_model(model_file_path, \n custom_objects=None, \n compile=False)\n \n \n def generateSatelliteImage(self,latitude, longitude, \n file_name_save, google_maps_api_key):\n \"\"\"\n Generates satellite image via Google Maps, using the passed lat-long coordinates.\n \n Parameters\n -----------\n latitude: Float. Latitude coordinate of the site.\n longitude: Float. Longitude coordinate of the site.\n file_name_save: String. File path that we want to save the image to. PNG file.\n google_maps_api_key: String. Google Maps API Key for automatically \n pulling satellite images.\n \n Returns\n ----------- \n Returned satellite image.\n \"\"\"\n #Check input variable for types\n if type(latitude) != float:\n raise TypeError(\"latitude variable must be of type float.\")\n if type(longitude) != float:\n raise TypeError(\"longitude variable must be of type float.\") \n if type(file_name_save) != str:\n raise TypeError(\"file_name_save variable must be of type string.\")\n if type(google_maps_api_key) != str:\n raise TypeError(\"google_maps_api_key variable must be of type string.\")\n #Build up the lat_long string from the latitude-longitude coordinates\n lat_long = str(latitude)+ \", \"+ str(longitude)\n # get method of requests module \n # return response object \n r = requests.get(\"https://maps.googleapis.com/maps/api/staticmap?maptype=satellite¢er=\" + lat_long + \"&zoom=18&size=35000x35000&key=\"+google_maps_api_key,\n verify= False) \n #Raise an exception if the satellite image is not successfully returned\n if r.status_code != 200:\n raise ValueError(\"Response status code \" + str(r.status_code) + \": Image not pulled successfully from API.\")\n # wb mode is stand for write binary mode \n f = open(file_name_save, 'wb') \n # r.content gives content, \n # in this case gives image \n f.write(r.content) \n # close method of file object \n # save and close the file \n f.close()\n #Read in the image and return it via the console\n return Image.open(file_name_save) \n\n\n def diceCoeff(self,y_true, y_pred, smooth=1):\n \"\"\"\n This function is used as the metric of similarity between the \n predicted mask and ground truth. \n \n Parameters\n -----------\n y_true - (numpy array of floats) \n the true mask of the image \n y_pred - (numpy array of floats) \n the predicted mask of the data\n smooth - (int): \n a parameter to ensure we are not dividing by zero and also a smoothing parameter. \n For back propagation. If the prediction is hard threshold to 0 and 1, it is difficult to back\n propagate the dice loss gradient. We add this parameter to actually smooth out the loss function, \n making it differentiable.\n \n Returns\n -----------\n dice: - float: retuns the metric of similarity between prediction and ground truth\n \"\"\"\n #Ensure that the inputs are of the correct type\n if type(y_true) != np.ndarray:\n raise TypeError(\"Variable y_true should be of type np.ndarray.\")\n if type(y_pred) != np.ndarray:\n raise TypeError(\"Variable y_pred should be of type np.ndarray.\")\n if type(smooth) != int:\n raise TypeError(\"Variable smooth should be of type int.\")\n #If variable types are correct, continue with function\n intersection = K.sum(y_true * y_pred, axis=[1,2,3])\n union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])\n dice = K.mean((2. * intersection + smooth)/(union + smooth), axis=0)\n return dice\n\n \n def diceCoeffLoss(self, y_true, y_pred):\n \"\"\"\n This function is a loss function that can be used when training the segmentation model.\n This loss function can be used in place of binary crossentropy,\n which is the current loss function in the training stage \n \n Parameters\n -----------\n y_true - (numpy array of floats) \n the true mask of the image \n y_pred - (numpy array of floats)\n the predicted mask of the data\n \n Returns\n -----------\n float: retuns the loss metric between prediction and ground truth\n \n \"\"\"\n #Ensure that the inputs are of the correct type\n if type(y_true) != np.ndarray:\n raise TypeError(\"Variable y_true should be of type np.ndarray.\")\n if type(y_pred) != np.ndarray:\n raise TypeError(\"Variable y_pred should be of type np.ndarray.\")\n return 1-self.dice_coef(y_true, y_pred)\n \n\n def testBatch(self, test_data, test_mask=None, BATCH_SIZE = 16, model =None):\n \"\"\"\n This function is used to predict the mask of a batch of test satellite images.\n Use this to test a batch of images greater than 4\n \n Parameters\n -----------\n 'test_data': (nparray float) \n the satellite images \n 'test_mask': (nparray int/float) \n the mask ground truth corresponding to the test_data\n 'batch_size': (int) \n the batch size of the test_data. \n 'model': (tf.keras.model.object)\n a custom model can be provided as input or we can use the initialized model\n \n Returns\n -----------\n 'test_res': (nparray float) \n retuns the predicted masks.\n 'accuracy': (float) \n returns the accuarcy of prediction as compared with the ground truth if provided\n \"\"\"\n #Ensure that the inputs are of the correct type\n if type(test_data) != np.ndarray:\n raise TypeError(\"Variable test_data should be of type np.ndarray.\")\n if type(BATCH_SIZE) != int:\n raise TypeError(\"Variable BATCH_SIZE should be of type int.\") \n test_datagen = image.ImageDataGenerator(rescale=1./255,dtype='float32')\n test_image_generator = test_datagen.flow(\n test_data,\n batch_size = BATCH_SIZE, shuffle=False)\n if model != None:\n test_res = model.predict(test_image_generator)\n else :\n test_res = self.model.predict(test_image_generator)\n if test_mask != None: \n test_mask = test_mask/np.max(test_mask)\n accuracy = self.dice_coef(test_mask,test_res) \n return test_res,accuracy\n else:\n return test_res\n\n def testSingle(self, test_data, test_mask=None, model =None):\n \"\"\"\n This function is used to predict the mask corresponding to a single test image. \n It takes as input the test_data (a required parameter) and two non-required parameters- test_mask and model\n \n Use this to test a single image.\n\n Parameters\n -----------\n 'test_data': (nparray int or float) \n the satellite image. dimension is (640,640,3) or (a,640,640,3) \n 'test_mask': (nparray int/flaot) \n the ground truth of what the mask should be \n 'model': (tf.keras model object) \n a custom model can be provided as input or we can use the initialized model\n \n Returns\n -----------\n 'test_res': (nparray float) \n retuns the predicted mask of the single image. The dimension is (640,640 or (a,640,640))\n 'accuracy': (float) \n returns the accuarcy of prediction as compared with the ground truth if provided\n \n \"\"\"\n #check that the inputs are correct\n if type(test_data) != np.ndarray:\n raise TypeError(\"Variable test_data must be of type Numpy ndarray.\")\n #Test that the input array has 2 to 3 channels\n if (len(test_data.shape) > 3) | (len(test_data.shape) < 2):\n raise ValueError(\"Numpy array test_data shape should be 2 or 3 dimensions.\")\n #Once the array passes checks, run the sequence\n test_data = test_data/255\n test_data = test_data[np.newaxis, :]\n if model != None:\n test_res = model.predict(test_data)\n else :\n test_res = self.model.predict(test_data)\n test_res = (test_res[0].reshape(640,640))\n if test_mask != None: \n test_mask = test_mask/np.max(test_mask)\n accuracy = self.dice_coef(test_mask,test_res) \n return test_res,accuracy\n else:\n return test_res \n \n\n def hasPanels(self, test_data):\n \"\"\"\n This function is used to predict if there is a panel in an image or not. \n Note that it uses a saved classifier model we have trained and not the \n segmentation model. \n \n Parameters\n -----------\n test_data: (nparray float or int) \n the satellite image. The shape should be [a,640,640,3] where \n 'a' is the number of data or (640,640,3) if it is a single image\n \n Returns\n -----------\n Boolean. Returns True if solar array is detected in an image, and False otherwise.\n \"\"\"\n #Check that the input is correct\n if type(test_data) != np.ndarray:\n raise TypeError(\"Variable test_data must be of type Numpy ndarray.\")\n #Test that the input array has 3 to 4 channels\n if (len(test_data.shape) > 4) | (len(test_data.shape) < 3):\n raise ValueError(\"Numpy array test_data shape should be 3 dimensions if a single image, or 4 dimensions if a batch of images.\") \n test_data = test_data/255\n #This ensures the first dimension is the number of test data to be predicted\n if test_data.ndim == 3:\n test_data = test_data[np.newaxis, :]\n prediction = self.classifier.predict(test_data)\n #index 0 is for no panels while index 1 is for panels\n if prediction[0][1] > prediction[0][0]:\n return True \n else:\n return False\n \n\n def detectAzimuth(self, in_img, number_lines=5):\n \"\"\"\n This function uses canny edge detection to first extract the edges of the input image. \n To use this function, you have to first predict the mask of the test image \n using testSingle function. Then use the cropPanels function to extract the solar \n panels from the input image using the predicted mask. Hence the input image to this \n function is the cropped image of solar panels.\n \n After edge detection, Hough transform is used to detect the most dominant lines in\n the input image and subsequently use that to predict the azimuth of a single image\n \n Parameters\n -----------\n in_img: (nparray uint8) \n The image containing the extracted solar panels with other pixels zeroed off. Dimension is [1,640,640,3]\n number_lines: (int) \n This variable tells the function the number of dominant lines it should examine.\n We currently inspect the top 10 lines.\n \n Returns\n -----------\n azimuth: (int) \n The azimuth of the panel in the image.\n \"\"\"\n #Check that the input variables are of the correct type\n if type(in_img) != np.ndarray:\n raise TypeError(\"Variable in_img must be of type Numpy ndarray.\")\n if type(number_lines) != int:\n raise TypeError(\"Variable number_lines must be of type int.\")\n #Run through the function\n edges = cv2.Canny(in_img[0],50,150,apertureSize=3)\n tested_angles = np.linspace(-np.pi / 2, np.pi / 2, 360)\n h, theta, d = hough_line(edges, theta=tested_angles)\n origin = np.array((0, edges.shape[1]))\n ind =0\n azimuth = 0\n az = np.zeros((number_lines))\n # Classic straight-line Hough transform\n # Set a precision of 0.5 degree. \n for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=number_lines, threshold =0.25*np.max(h))):\n y0, y1 = (dist - origin * np.cos(angle)) / np.sin(angle)\n \n deg_ang = int(np.rad2deg(angle))\n if deg_ang >= 0:\n az[ind] = 90+deg_ang\n else:\n az[ind] = 270 + deg_ang\n ind =ind+1\n unique_elements, counts_elements = np.unique(az, return_counts=True)\n check = counts_elements[np.argmax(counts_elements)]\n if check == 1:\n for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=1, threshold =0.25*np.max(h))):\n deg_ang = int(np.rad2deg(angle))\n if deg_ang >= 0:\n azimuth = 90+deg_ang\n else:\n azimuth = 270 + deg_ang\n else:\n azimuth = (unique_elements[np.argmax(counts_elements)])\n return azimuth \n\n \n def cropPanels(self, test_data, test_res):\n \"\"\"\n This function basically isolates regions with solar panels in a \n satellite image using the predicted mask. It zeros out other pixels that does not \n contain a panel.\n You can use this for a single test data or multiple test data. \n \n Parameters \n ----------\n test_data: (nparray float)\n This is the input test data. This can be a single image or multiple image. Hence the \n dimension can be (640,640,3) or (a,640,640,3)\n test_res: (nparray float) \n This is the predicted mask of the test images passed as an input and used to crop out the \n solar panels. dimension is (640,640)\n \n Returns \n ----------\n new_test_res: (nparray uint8) \n This returns images here the solar panels have been cropped out and the background zeroed. \n It has the same shape as test data. The dimension is [a,640,640,3] where a is the number of\n input images\n \n \"\"\"\n #Check that the input variables are of the correct type\n if type(test_data) != np.ndarray:\n raise TypeError(\"Variable test_data must be of type Numpy ndarray.\")\n if type(test_res) != np.ndarray:\n raise TypeError(\"Variable test_res must be of type Numpy ndarray.\") \n #Convert the test_data array from 3D to 4D\n if test_data.ndim == 3:\n test_data = test_data[np.newaxis, :]\n new_test_res = np.uint8(np.zeros((test_data.shape[0],640,640,3)))\n for ju in np.arange(test_data.shape[0]):\n try:\n in_img = test_res[ju].reshape(640,640)\n except:\n in_img = test_res.reshape(640,640)\n in_img[in_img < 0.9] = 0\n in_img[in_img >= 0.9] = 1\n in_img = np.uint8(in_img)\n test2 = np.copy(test_data[ju])\n test2[(1-in_img).astype(bool),0] = 0\n test2[(1-in_img).astype(bool),1] = 0\n test2[(1-in_img).astype(bool),2] = 0\n new_test_res[ju] = test2 \n return new_test_res\n \n \n def plotEdgeAz(self, test_results, no_lines=5, \n no_figs=1, save_img_file_path = None,\n plot_show = False):\n \"\"\"\n This function is used to generate plots of the image with its azimuth\n It can generate three figures or one. For three figures, that include the \n input image, the hough transform space and the input images with detected lines.\n For single image, it only outputs the input image with detected lines.\n \n Parameters \n ----------\n test_results: (nparray float64 or unit8) \n 8-bit input image. This variable represents the predicted images from the segmentation model. Hence the \n dimension must be [a,b,c,d] where [a] is the number of images, [b,c] are the dimensions\n of the image - 640 x 640 in this case and [d] is 3 - RGB\n no_lines: (int) \n default is 10. This variable tells the function the number of dominant lines it should examine. \n no_figs: (int) \n 1 or 3. If the number of figs is 1. It outputs the mask with Hough lines and the predicted azimuth\n However, if the number of lines is 3, it gives three plots. \n 1. The input image,\n 2. Hough transform search space\n 3. Unput image with houghlines and the predicted azimuth\n \n save_img_file_path: (string) \n You can pass as input the location to save the plots\n plot_show: Boolen: If False, it will supress the plot as an output and just save the plots in a folder\n \n Returns \n ----------\n Plot of the masked image, with detected Hough Lines and azimuth estimate.\n \"\"\"\n #Check that the input variables are of the correct type\n if type(test_results) != np.ndarray:\n raise TypeError(\"Variable test_results must be of type Numpy ndarray.\")\n if type(no_lines) != int:\n raise TypeError(\"Variable no_lines must be of type int.\") \n if type(no_figs) != int:\n raise TypeError(\"Variable no_figs must be of type int.\") \n if type(plot_show) != bool:\n raise TypeError(\"Variable no_figs must be of type boolean.\") \n \n for ii in np.arange(test_results.shape[0]):\n #This changes the float64 to uint8\n if (test_results.dtype is np.dtype(np.float64)):\n in_img = test_results[ii].reshape(640,640)\n in_img[in_img < 0.9] = 0\n in_img[in_img >= 0.9] = 1\n in_img = np.uint8(in_img)\n\n in_img = test_results[ii]\n #Edge detection\n edges = cv2.Canny(in_img,50,150,apertureSize=3)\n tested_angles = np.linspace(-np.pi / 2, np.pi / 2, 360)\n h, theta, d = hough_line(edges, theta=tested_angles)\n az = np.zeros((no_lines))\n origin = np.array((0, edges.shape[1]))\n ind =0\n # Generating figure 1 \n fig, ax = plt.subplots(1, no_figs, figsize=(10, 6))\n if no_figs == 1:\n ax.imshow(edges)# cmap=cm.gray)\n for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=no_lines, threshold =0.25*np.max(h))):\n y0, y1 = (dist - origin * np.cos(angle)) / np.sin(angle)\n deg_ang = int(np.rad2deg(angle))\n if deg_ang >= 0:\n az[ind] = 90+deg_ang\n else:\n az[ind] = 270 + deg_ang\n ind =ind+1\n ax.plot(origin, (y0, y1), '-r')\n ax.set_xlim(origin)\n ax.set_ylim((edges.shape[0], 0))\n ax.set_axis_off()\n unique_elements, counts_elements = np.unique(az, return_counts=True)\n \n check = counts_elements[np.argmax(counts_elements)]\n \n if check == 1:\n for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=1, threshold =0.25*np.max(h))):\n deg_ang = int(np.rad2deg(angle))\n if deg_ang >= 0:\n azimuth = 90+deg_ang\n else:\n azimuth = 270 + deg_ang\n else:\n azimuth = (unique_elements[np.argmax(counts_elements)])\n #print(np.asarray((unique_elements, counts_elements)))\n ax.set_title('Azimuth = %i' %azimuth)\n #save the image\n if save_img_file_path != None:\n plt.savefig(save_img_file_path + '/crop_mask_az_'+str(ii),\n dpi=300)\n #Show the plot if plot_show = True\n if plot_show == True:\n plt.tight_layout()\n plt.show() \n elif no_figs == 3:\n ax = ax.ravel()\n\n ax[0].imshow(in_img, cmap=cm.gray)\n ax[0].set_title('Input image')\n ax[0].set_axis_off()\n \n\n ax[1].imshow(np.log(1 + h),\n extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]],\n cmap=cm.gray, aspect=1/1.5)\n ax[1].set_title('Hough transform')\n ax[1].set_xlabel('Angles (degrees)')\n ax[1].set_ylabel('Distance (pixels)')\n ax[1].axis('image')\n\n ax[2].imshow(in_img)# cmap=cm.gray)\n origin = np.array((0, edges.shape[1]))\n ind =0\n for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=no_lines, threshold =0.25*np.max(h))):\n y0, y1 = (dist - origin * np.cos(angle)) / np.sin(angle)\n \n deg_ang = int(np.rad2deg(angle))\n if deg_ang >= 0:\n az[ind] = 90+deg_ang\n else:\n az[ind] = 270 + deg_ang\n ind =ind+1\n ax.plot(origin, (y0, y1), '-r')\n ax[2].set_xlim(origin)\n ax[2].set_ylim((edges.shape[0], 0))\n ax[2].set_axis_off()\n unique_elements, counts_elements = np.unique(az, return_counts=True)\n \n check = counts_elements[np.argmax(counts_elements)]\n \n if check == 1:\n for _, angle, dist in zip(*hough_line_peaks(h, theta, d, num_peaks=1, threshold =0.25*np.max(h))):\n deg_ang = int(np.rad2deg(angle))\n if deg_ang >= 0:\n azimuth = 90+deg_ang\n else:\n azimuth = 270 + deg_ang\n else:\n azimuth = (unique_elements[np.argmax(counts_elements)])\n #print(np.asarray((unique_elements, counts_elements)))\n ax[2].set_title('Azimuth = %i' %azimuth)\n #save the image\n if save_img_file_path != None:\n plt.savefig(save_img_file_path + '/crop_mask_az_'+str(ii),\n dpi=300)\n #Show the plot if plot_show = True\n if plot_show == True:\n plt.tight_layout()\n plt.show() \n else:\n print(\"Enter valid parameters\")\n \n\n def clusterPanels(self, test_mask, fig=False):\n '''\n This function uses connected component algorithm to cluster the panels\n\n Parameters\n ----------\n test_mask : (bool) or (float)\n The predicted mask. Dimension is (640,640) or can be converted to RGB (640,640,3)\n fig : (bool)\n shows the clustering image if fig = True\n\n Returns\n -------\n (uint8)\n Masked image containing detected clusters each of dimension(640,640,3)\n \n (uint8)\n The optimal number of clusters\n '''\n #Check that the input variables are of the correct type\n if type(test_mask) != np.ndarray:\n raise TypeError(\"Variable test_mask must be of type Numpy ndarray.\")\n if type(fig) != bool:\n raise TypeError(\"Variable fig must be of type bool.\") \n #Continue running through the function if all the inputs are correct\n if (len(test_mask.shape) < 3):\n test_mask = cv2.cvtColor(test_mask,cv2.COLOR_GRAY2RGB)\n test_mask = test_mask.reshape(640,640,3) \n # Converting those pixels with values 0-0.5 to 0 and others to 1\n img = cv2.threshold(test_mask, 0.5, 1, cv2.THRESH_BINARY)[1]\n # Applying cv2.connectedComponents() \n num_labels, labels = cv2.connectedComponents(img[:,:,2].reshape(640,640)) \n # Map component labels to hue val, 0-179 is the hue range in OpenCV\n label_hue = np.uint8(179*labels/np.max(labels))\n blank_ch = 255*np.ones_like(label_hue)\n labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])\n # Converting cvt to BGR\n labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)\n # set background label to black\n labeled_img[label_hue==0] = 0\n #Initialize each clusters\n clusters = np.uint8(np.zeros((num_labels-1, 640, 640,3)))\n #starting from 1 to ignore background\n for i in np.arange(1,num_labels):\n clus = np.copy(test_mask)\n c_mask = labels==i\n #clus_label = np.zeros((640,640,3))\n clus[(1-c_mask).astype(bool),0] = 0\n clus[(1-c_mask).astype(bool),1] = 0\n clus[(1-c_mask).astype(bool),2] = 0\n #clus_label = np.stack((clus_label,)*3, axis=-1)\n clusters[i-1] = clus\n # Loop through each cluster, and detect number of non-zero values\n # in each cluster.\n clusters_list_keep = []\n for cluster_number in range(clusters.shape[0]):\n cluster = clusters[cluster_number]\n # Get the number of non-zero values as a ratio of total pixels\n pixel_count = len(cluster[cluster>0])\n total_pixels = cluster.shape[0] * cluster.shape[1] * cluster.shape[2]\n # Must greater than 3% non-zero pixels or we omit the cluster\n print(pixel_count / total_pixels)\n if (pixel_count / total_pixels) >= 0.0015:\n clusters_list_keep.append(cluster_number)\n # Filter clusters\n clusters = clusters[clusters_list_keep]\n if fig == True:\n #Showing Image after Component Labeling\n plt.figure()\n plt.imshow(cv2.cvtColor(labeled_img, cv2.COLOR_BGR2RGB))\n plt.axis('off')\n plt.title(\"Image after Component Labeling\")\n plt.show()\n return len(clusters),clusters\n \n \n\n \n","sub_path":"panel_segmentation/panel_detection.py","file_name":"panel_detection.py","file_ext":"py","file_size_in_byte":27773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"196061316","text":"import time\nimport random\n\nword_its = '''IT'S'''\n\nword_time = ''' TIME'''\n\nword_for = ''' FOR...'''\n\ntitle1 = ''' ██╗ █████╗ ██████╗ ██████╗ ██╗ ██╗ ██████╗ ██╗ ██╗███████╗███████╗████████╗'''\ntitle2 = ''' ██║ ██╔══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝██╔═══██╗██║ ██║██╔════╝██╔════╝╚══██╔══╝'''\ntitle3 = ''' ██║ ███████║██████╔╝██████╔╝ ╚████╔╝ ██║ ██║██║ ██║█████╗ ███████╗ ██║ '''\ntitle4 = ''' ██║ ██╔══██║██╔══██╗██╔══██╗ ╚██╔╝ ██║▄▄ ██║██║ ██║██╔══╝ ╚════██║ ██║ '''\ntitle5 = ''' ███████╗██║ ██║██║ ██║██║ ██║ ██║ ╚██████╔╝╚██████╔╝███████╗███████║ ██║ '''\ntitle6 = ''' ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚══▀▀═╝ ╚═════╝ ╚══════╝╚══════╝ ╚═╝ '''\n\ntext1 = ''' Somewhere, in the outer reaches of deep space, a janitor named Larry could count down\nthe days to retirement on one hand.\n\n \"It's hard to believe I've got less than a week left,\" Larry muttered to himself while\nfinishing one last mop of the mess hall.\n \n While he enjoyed having the base almost completely to himself, there was something\nabout being this close to the end that made him wonder how things would've turned out if\nhe'd made it all the way through The Academy. Still, he had a level of job security most\nfolks this far out into space could only dream of. And only a few days of it left to boot.\n\n He did have a bit of company though: His robot pal, Rusty. Larry had grown fond of his\nagency-appointed helper, so much so that he even named it. Rusty was definitely outdated,\nbut that didn't matter to Larry. He enjoyed the familiarity of \"Trusty Rusty\" and the robot\nreminded him of a time when things seemed to move a little bit slower. Maintaining an older\nrobot also helped pass the time and Larry figured that if his buddy had made it this far,\nhe may very well be indestructable.\n\n \"Well, I guess that's it for the year, Rusty,\" said Larry.\n \n \"01010100 01101001 01101101 01100101 00100000 01100110 01101111 01110010 00100000 \n01100001 00100000 01100011 01101111 01101100 01100100 00100000 01101111 01101110 01100101\n00100001,\" Rusty beeped.\n \n \"Boy is it ever! I'll head over to the Officer's Quarters and see if they left any\nbottles of suds behind in the fridge. That sure was one hell of a party...\"\n\n'''\n\n# (Press \"Enter\" to move Larry to the Officer's Quarters.)\n\ntext2 = '''\n The best part about being the senior janitor was that Larry's keycard granted him full\naccess to the entire base. (Another alien specimen exploded in the lab you say? \"Someone go\nfind Larry.\" Someone puked in the anti-gravity chamber again? \"Say no more! Larry's on it!\")\nThe Officer's Quarters were all the way on the other side of the facility, so Larry headed\nover that way while Rusty stayed behind to straighten up their neck of the woods.\n\n As he was making his way down one of the now-dimly-lit corridors, a dark figure in the\ndistance startled Larry something fierce.\n\n \"Hey! Who's that?!?\", shouted Larry.\n\n \"Huh? Oh... It's me, Dave!\"\n\n Dave was one of the medics at the base and a good friend of Larry's. A welcomed sight,\nfor sure.\n\n \"Terribly sorry about that, bud,\" said Dave. \"They must've turned the lights out to save\npower over the break. Damn... I guess I overslept and missed the shuttle. Well anyway, what\nare you doing all the way out here? I thought they closed this wing down before the party.\"\n\n \"I'm headed over to the Officer's Quarters to see if they left any beers in that mini-\nfridge that they think is a secret.\"\n\n \"Yeah, they aren't foolin' anyone... But aren't you worried about them finding out? The\nsecurity cameras are still on and that constitutes as stealing from an officer,\" Dave noted.\n\n \"What are they gonna do, fire me?\"\n\n \"Good point, Larry. Let's go find some beers and drink to your retirement.\"\n\n The old pals made their way up the hill and quipped back and forth about how much nicer\nthe accomodations were on this side of the base (for agency standards, at least). The outer\ndoor of the Officer's Quarters proved to be no obstacle for Larry's keycard and the two\nfriends paraded around feeling like kings, if only for a short while. The mini-fridge was\n\"hidden\" right where they knew it was and sure enough, the brewski gods shined bright upon \nLarry and Dave on this particular day.\n\n'''\n\n# (Press \"Enter\" to make Larry raid the mini-fridge.)\n\ntext3 = '''\n \"Light beer sure hits differently when it isn't yours,\" posited Larry.\n\n \"You said it, man. The tastiest style of beer is free beer.\"\n\n The two shared stories about their time working on moon base CRM-114, all the nonsense\nthey both had to endure that simply didn't matter in the grand scheme of things, and then\nchatted about what Larry's life outside of the agency might look like. Larry wondered if\nthey even made fishing rods anymore now that all the meat back on Earth was lab-grown, but\nbefore he could get that thought out, Dave noticed something through one of the large bay\nwindows.\n\n \"Hold that thought, Larry. A ship just landed in the maintenance dock...\"\n\n \"That's odd. No one's supposed to return until after the New Year. Let's go check and\nsee who it is.\"\n\n \"Yeah. Let's bolt before anyone finds out what we're up to.\"\n\n The two made haste back to Larry's side of the base, finishing their last sips of oat\nsoda along the way. As they got closer to the airlock by the maintenance dock, Larry\nnoticed that his janitor cart wasn't properly stowed back in the closet.\n\n \"Huh... Rusty didn't finish cleaning up for the day,\" said Larry.\n\n \"Yeah, that robot's probably nearing the end there. I honestly don't see why you never\nupgraded. But I guess it doesn't really matter now.\"\n\n \"This is different. He would never forget to do something this basic. Oh wait... Here\nhe comes.\"\n\n \"01010000 01010010 01000101 01010000 01000001 01010010 01000101 00100000 01010100 \n01001111 00100000 01000100 01001001 01000101 00101100 00100000 01001000 01010101 01001101\n01000001 01001110 01010011 00100001 00100001 00100001,\" beeped Rusty, much louder than\nbefore.\n\n \"Oh, shit! Dave, RUN!!!\" Larry yelled, grabbing Dave's arm.\n\n \"What'd he say?!?\"\n\n \"Just find something to hide behind!\"\n\n'''\n\n# (Press \"Enter\" to make Larry run for cover.)\n\ntext4 = '''\n Dave found a corner of the dock that would keep him safe for the moment and Larry dove\nbehind the only thing he could find: his janitor cart. Go figure... The one thing that\nsymbolized his feeling of being trapped in a dead end job for so many years may actually\nbe what saved him after all. He had everything he needed: A broom to use as a weapon, some\nspray bottles of cleaner that might do something, and a mobile shield in the cart itself.\n\n As he was taking stock of his surroundings, the real threat made itself known: Alien\nscouts. They must have intercepted transmissions talking about the break and figured that\nit would be the perfect time to try and commandeer the base.\n\n \"Dave, can you hear me?\"\n\n \"Yeah. What do we do?\"\n\n \"I'm all set here with some weapons to fend them off for a bit. Are there any med\nstations close by?\" asked Larry.\n\n \"Definitely. It'll take me a minute to run and get supplies, but I restocked all of\nthem before everyone left. What happened with Rusty?\"\n\n \"Those bastards must've rewired him or something. I might be able to fix him back\nthough. Look, I'll hold down the fort here. Just grab what you can and get back here\nASAP!\"\n\n \"Got it. I'll be back in a bit!\"\n\n Larry turned to fight, knowing that these three aliens and that old rust bucket were\nthe only things standing between him and a lifetime of sipping mojitos while lounging\npoolside...\n\n'''\n\ntext5 = '''\n \"Hey assholes!!!\", shouted Larry.\n\n He threw his empty beer bottle at the scouts as hard as he could, hitting the first\nalien square in the head. He figured that making the first move couldn't hurt, being that\nhe could almost taste the mojitos...\n\n'''\n\ntext_win = \"You won! (Write something longer.)\"\n\ntext_lose = \"Larry retired prematurely. (Write something longer.)\"\n\n# Text Printing Functions\ndef type_print(string):\n for i in string:\n print(i, end = '', flush = True)\n time.sleep(0.0325)\n\ndef fast_type_print(string):\n for i in string:\n print(i, end = '', flush = True)\n time.sleep(0.01)\n\n# Parent Character Classes\nclass Human():\n def __init__(self, health, broom_power, spray_power):\n self.health = health\n self.broom_power = broom_power\n self.spray_power = spray_power\n\n def alive(self, health):\n self.health = health\n life = True\n if self.health <= 0:\n life = False\n return life\n\nclass Alien():\n def __init__(self, health, armor, power):\n self.health = health\n self.armor = armor\n self.power = power\n\n def alive(self, health):\n self.health = health\n life = True\n if self.health <= 0:\n life = False\n return life\n\nclass Robot():\n def __init__(self, battery, power):\n self.battery = battery\n self.power = power\n\n# Child Characters\nclass Larry(Human):\n def attack_alien1(self, alien1):\n hit = random.randint(1, 4)\n if hit != 2:\n alien1.health -= self.broom_power\n fast_type_print(f\" *** Larry does {self.broom_power} damage to the first alien. ***\\n\\n\")\n else:\n fast_type_print(\" *** Larry misses. ***\\n\\n\")\n\n def attack_alien2(self, alien2):\n hit = random.randint(1, 4)\n if hit != 2:\n alien2.health -= self.broom_power\n fast_type_print(f\" *** Larry does {self.broom_power} damage to the second alien. ***\\n\\n\")\n else:\n fast_type_print(\" *** Larry misses. ***\\n\\n\")\n\n def attack_alien3(self, alien3):\n hit = random.randint(1, 4)\n if hit != 2:\n alien3.health -= self.broom_power\n fast_type_print(f\" *** Larry does {self.broom_power} damage to the third alien. ***\\n\\n\")\n else:\n fast_type_print(\" *** Larry misses. ***\\n\\n\")\n \n def spray(self, alien1, alien2, alien3):\n if spray.ammo > 0:\n alien1.armor -= self.spray_power\n alien2.armor -= self.spray_power\n alien3.armor -= self.spray_power\n spray.ammo -= 25\n fast_type_print(f\" *** Larry's various cleaning products reduce each alien's armor by {self.spray_power}. ***\\n\\n\")\n\n def print_status(self):\n fast_type_print(f\"--> Larry has {self.health} health. His broom deals {self.broom_power} damage.\\n\")\n\nclass Dave(Human):\n pass\n # def attack(self, alien1, alien2, alien3):\n # alien1.health -= self.power\n # alien2.health -= self.power\n # alien3.health -= self.power\n # print(f\"Dave does {self.power} damage to the aliens.\\n\")\n # if alien1.health <= 0:\n # fast_type_print(\"The first alien is dead.\\n\")\n # if alien2.health <= 0:\n # fast_type_print(\"The second alien is dead.\\n\")\n # if alien3.health <= 0:\n # fast_type_print(\"The third alien is dead.\\n\")\n\n def print_status(self):\n fast_type_print(f\"--> Dave is holding {self.health} medpack(s) and {self.power} spray bottle refill(s).\\n\")\n\nclass Alien1(Alien):\n def attack_larry(self, larry):\n if self.health > 0:\n hit = random.randint(1, 3)\n if hit != 2:\n larry.health -= self.power\n fast_type_print(f\" *** The first alien does {self.power} damage to Larry. ***\\n\\n\")\n if larry.health <= 0:\n type_print(text_lose)\n print()\n print()\n exit()\n else:\n fast_type_print(\" *** The first alien misses. ***\\n\\n\")\n else:\n fast_type_print(\" *** The first alien is dead. ***\\n\\n\")\n\n def attack_cart(self, cart):\n cart.cart_life -= 1\n\n def print_status(self):\n if self.health > 0:\n fast_type_print(f\"--> The first alien has {self.health} health, {self.armor} armor, and deals {self.power} damage.\\n\")\n else:\n fast_type_print(\"--> The first alien is dead.\\n\")\n\nclass Alien2(Alien):\n def attack_larry(self, larry):\n if self.health > 0:\n hit = random.randint(1, 3)\n if hit != 2:\n larry.health -= self.power\n fast_type_print(f\" *** The second alien does {self.power} damage to Larry. ***\\n\\n\")\n if larry.health <= 0:\n type_print(text_lose)\n print()\n print()\n exit()\n else:\n fast_type_print(\" *** The second alien misses. ***\\n\\n\")\n else:\n fast_type_print(\" *** The second alien is dead. ***\\n\\n\")\n\n def attack_cart(self, cart):\n cart.cart_life -= 1\n\n def print_status(self):\n if self.health > 0:\n fast_type_print(f\"--> The second alien has {self.health} health, {self.armor} armor, and deals {self.power} damage.\\n\")\n else:\n fast_type_print(\"--> The second alien is dead.\\n\")\n\nclass Alien3(Alien):\n def attack_larry(self, larry):\n if self.health > 0:\n hit = random.randint(1, 3)\n if hit != 2:\n larry.health -= self.power\n fast_type_print(f\" *** The third alien does {self.power} damage to Larry. ***\\n\\n\")\n if larry.health <= 0:\n type_print(text_lose)\n print()\n print()\n exit()\n else:\n fast_type_print(\" *** The third alien misses. ***\\n\\n\")\n else:\n fast_type_print(\" *** The third alien is dead. ***\\n\\n\")\n\n def attack_cart(self, cart):\n cart.cart_life -= 1\n\n def print_status(self):\n if self.health > 0:\n fast_type_print(f\"--> The third alien has {self.health} health, {self.armor} armor, and deals {self.power} damage.\\n\")\n else:\n fast_type_print(\"--> The third alien is dead.\\n\")\n\nclass Rusty(Robot):\n def friendly(self):\n rusty.friendly = False\n return rusty.friendly\n\n def attack_larry(self, larry):\n if self.battery > 0:\n self.battery -= 5\n hit = random.randint(1, 3)\n if hit != 2:\n larry.health -= self.power\n fast_type_print(f\" *** Rusty does {self.power} damage to Larry. ***\\n\\n\")\n if larry.health <= 0:\n type_print(text_lose)\n print()\n print()\n exit()\n else:\n fast_type_print(f\" *** Rusty's battery is at 0% and cannot attack. ***\\n\\n\")\n\n def attack_cart(self, cart):\n if self.battery > 0:\n self.battery -= 5\n cart.cart_life -= 1\n fast_type_print(f\" *** Rusty also does {self.power} damage to Larry's cart. ***\\n\\n\")\n else:\n fast_type_print(f\" *** Rusty's battery is at 0% and cannot attack. ***\\n\\n\")\n\n def attack_alien1(self, alien1):\n if self.battery > 0:\n self.battery -= 5\n hit = random.randint(1, 4)\n if hit != 2:\n alien1.health -= self.power\n fast_type_print(f\" *** Rusty does {self.power} damage to the first alien. ***\\n\\n\")\n else:\n fast_type_print(\" *** Rusty misses. ***\\n\\n\")\n else:\n fast_type_print(f\" *** Rusty's battery is at 0% and cannot attack. ***\\n\\n\")\n\n def attack_alien2(self, alien2):\n if self.battery > 0:\n self.battery -= 5\n hit = random.randint(1, 4)\n if hit != 2:\n alien2.health -= self.power\n fast_type_print(f\" *** Rusty does {self.power} damage to the first alien. ***\\n\\n\")\n else:\n fast_type_print(\" *** Rusty misses. ***\\n\\n\")\n else:\n fast_type_print(f\" *** Rusty's battery is at 0% and cannot attack. ***\\n\\n\")\n\n def attack_alien3(self, alien3):\n if self.battery > 0:\n self.battery -= 5\n hit = random.randint(1, 4)\n if hit != 2:\n alien3.health -= self.power\n fast_type_print(f\" *** Rusty does {self.power} damage to the first alien. ***\\n\\n\")\n else:\n fast_type_print(\" *** Rusty misses. ***\\n\\n\")\n else:\n fast_type_print(f\" *** Rusty's battery is at 0% and cannot attack. ***\\n\\n\")\n\n def print_status(self):\n if self.battery > 0:\n fast_type_print(f\"--> Rusty has {self.battery}% battery and deals {self.power} damage.\\n\")\n else:\n fast_type_print(\"--> Rusty needs to be recharged.\\n\")\n\n# Items\nclass Medpack():\n def __init__(self, health):\n self.health = health\n\n def use_medpack(self):\n larry.health += self.health\n fast_type_print(f\" *** Larry's health increases to {larry.health}. ***\\n\\n\")\n fast_type_print(f\" *** In turn, each alien does 1 damage to Larry's cart. ***\\n\\n\")\n\nclass Spray_bottle():\n def __init__(self, ammo):\n self.ammo = ammo\n\n def refill_bottles(self):\n self.ammo = 100\n fast_type_print(f\" *** Dave refills Larry's spray bottles to {self.ammo}%. ***\\n\\n\")\n fast_type_print(f\" *** In turn, each alien does 1 damage to Larry's cart. ***\\n\\n\")\n \n def print_status(self):\n fast_type_print(f\"--> Larry's spray bottles are at {spray.ammo}%.\\n\")\n\nclass Battery():\n pass\n\n# Larry's Cart\nclass Cart():\n def __init__(self, cart_life):\n self.cart_life = cart_life\n \n def print_status(self):\n fast_type_print(f\"--> Larry's cart can take {self.cart_life} more hits.\\n\")\n\n# Main Gameplay Loop\nlarry = Larry(10, 2, 1)\ndave = Dave(10, 1, 0)\nalien1 = Alien1(5, 5, 1)\nalien2 = Alien2(6, 5, 1)\nalien3 = Alien3(6, 5, 1)\nrusty = Rusty(0, 1)\ncart = Cart(25)\nmedpack = Medpack(2)\nspray = Spray_bottle(100)\nrusty_is_friend = False\n\nfast_type_print(\"\"\"\n\nThis game requires a Terminal with a width of at least 92 characters and a height of at \nleast 42 lines. If you are experiencing formatting errors, please resize your window now.\n\n\n\"\"\")\n\ndummy_key = input('Press \"Enter\" to continue.')\n\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print(word_its)\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print(word_time)\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print(word_for)\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print(title1)\n# time.sleep(0.6)\n# print(title2)\n# time.sleep(0.6)\n# print(title3)\n# time.sleep(0.6)\n# print(title4)\n# time.sleep(0.6)\n# print(title5)\n# time.sleep(0.6)\n# print(title6)\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# print()\n# time.sleep(0.6)\n# type_print(text1)\n# dummy_key = input(''' Press \"Enter\" to move Larry to the Officer\\'s Quarters.''')\n# type_print(text2)\n# dummy_key = input(''' Press \"Enter\" to make Larry raid the mini-fridge.''')\n# type_print(text3)\n# dummy_key = input(''' Press \"Enter\" to make Larry run for cover.''')\n# type_print(text4)\n# dummy_key = input(''' Press \"Enter\" to make Larry throw his empty beer bottle.''')\n# type_print(text5)\n# type_print(\"(((***)))---------------------------------------------(((***)))\\n\\n\")\n\nwhile (alien1.alive(alien1.health) == True or alien2.alive(alien2.health) == True or alien3.alive(alien3.health) == True) and larry.alive(larry.health) == True:\n larry.print_status()\n cart.print_status()\n spray.print_status()\n # dave.print_status()\n alien1.print_status()\n alien2.print_status()\n alien3.print_status()\n rusty.print_status()\n print()\n fast_type_print(\"\\n (((--- WHAT SHOULD LARRY DO? ---)))\\n\\n\\n\")\n fast_type_print(\" OFFENSE:\\n\")\n fast_type_print(\" 1. Whack the first alien with his broom\\n\")\n fast_type_print(\" 2. Whack the second alien with his broom\\n\")\n fast_type_print(\" 3. Whack the third alien with his broom\\n\")\n fast_type_print(\" 4. Spray the aliens with various cleaning products\\n\\n\")\n fast_type_print(\" DEFENSE:\\n\")\n fast_type_print(\" 5. Get a medpack from Dave and use it behind his cart\\n\")\n fast_type_print(\" 6. Get Dave to refill Larry's spray bottles\\n\")\n fast_type_print(\" 7. Send Dave out to grab more supplies\\n\\n\")\n fast_type_print(\" MISC:\\n\")\n fast_type_print(\" 8. Attempt to rewire Rusty back to being friendly\\n\")\n fast_type_print(\" 9. Have Dave swap out Rusty's battery\\n\")\n fast_type_print(\" 10. Surrender\\n\\n\")\n user_input = input(\"Enter a number: \")\n print()\n if user_input == \"1\":\n larry.attack_alien1(alien1)\n alien1.attack_larry(larry)\n alien2.attack_larry(larry)\n alien3.attack_larry(larry)\n if rusty_is_friend == False:\n rusty.attack_larry(larry)\n else:\n rusty.attack_alien1(alien1)\n elif user_input == \"2\":\n larry.attack_alien2(alien2)\n alien1.attack_larry(larry)\n alien2.attack_larry(larry)\n alien3.attack_larry(larry)\n if rusty_is_friend == False:\n rusty.attack_larry(larry)\n else:\n rusty.attack_alien2(alien2)\n elif user_input == \"3\":\n larry.attack_alien3(alien3)\n alien1.attack_larry(larry)\n alien2.attack_larry(larry)\n alien3.attack_larry(larry)\n if rusty_is_friend == False:\n rusty.attack_larry(larry)\n else:\n rusty.attack_alien3(alien3)\n elif user_input == \"4\":\n larry.spray(alien1, alien2, alien3)\n alien1.attack_larry(larry)\n alien2.attack_larry(larry)\n alien3.attack_larry(larry)\n if rusty_is_friend == False:\n rusty.attack_larry(larry)\n else:\n pass\n elif user_input == \"5\":\n medpack.use_medpack()\n alien1.attack_cart(cart)\n alien2.attack_cart(cart)\n alien3.attack_cart(cart)\n if rusty_is_friend == False:\n rusty.attack_cart(cart)\n else:\n pass\n elif user_input == \"6\":\n spray.refill_bottles()\n alien1.attack_cart(cart)\n alien2.attack_cart(cart)\n alien3.attack_cart(cart)\n if rusty_is_friend == False:\n rusty.attack_cart(cart)\n else:\n pass\n elif user_input == \"7\":\n # Send Dave out for supplies (code)\n alien1.attack_cart(cart)\n alien2.attack_cart(cart)\n alien3.attack_cart(cart)\n if rusty_is_friend == False:\n rusty.attack_cart(cart)\n else:\n pass\n elif user_input == \"8\":\n if rusty.battery > 0 and rusty_is_friend == False:\n rusty.attack_larry(larry)\n elif rusty_is_friend == False:\n rusty_is_friend = True\n fast_type_print(' *** Larry did it! \"Trusty Rusty\" is back on his side! ***\\n\\n')\n else:\n fast_type_print(\" *** Rusty is already on your side. Choose again. ***\\n\\n\")\n elif user_input == \"9\":\n if rusty_is_friend == True:\n rusty.battery = 100\n fast_type_print(f\" *** Rusty is back to {rusty.battery}% battery power! ***\\n\\n\")\n alien1.attack_cart(cart)\n alien2.attack_cart(cart)\n alien3.attack_cart(cart)\n fast_type_print(f\" *** In turn, each alien does 1 damage to Larry's cart. ***\\n\\n\")\n else:\n fast_type_print(\" *** Rusty is still an ememy. Choose again. ***\\n\\n\")\n elif user_input == \"10\":\n fast_type_print(\" *** Never give up! Never surrender! ***\\n\\n\")\n else:\n fast_type_print(f\"Invalid input: {user_input}\\n\\n\")\n fast_type_print(\"(((***)))---------------- END OF TURN ----------------(((***)))\\n\")\n print()\n\ntype_print(text_win)\nprint()\nprint()","sub_path":"larryquest-no-intro.py","file_name":"larryquest-no-intro.py","file_ext":"py","file_size_in_byte":25026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"590555863","text":"import numpy as np\n\ndef fictitious(n,m,A,B,T,x0,y0):\n x = x0\n y = y0\n # For 10000 iterations run fictitious play dynamics\n for t in range(T):\n # Calculate the utility of the row and column players\n # based on the current empirical play of opponent and\n # for each possible strategy\n ur = A.dot(y)\n uc = x.transpose().dot(B)\n\n # Find the maximum utility strategy for each player\n it = ur.argmax()\n jt = uc.argmax()\n\n # Update the counts of each player\n x[it] += 1\n y[jt] += 1\n return (x/(T+1),y/(T+1))\n\n\n\n#########################\n### Matching pennies\n#########################\nn = 2\nm = 2\nA = np.matrix('1. -1.; -1. 1.')\nB = - A\nT = 1000\n# Initial strategies of both players\nx0 = np.zeros((n,1))\nx0[1,0] = 1\ny0 = np.zeros((m,1))\ny0[1,0] = 1\n\n# Run fictitious play algorithm\n(x,y) = fictitious(n,m,A,B,T,x0,y0)\n\n# Print results\nprint('Matching pennies')\nprint(x.transpose())\nprint(y.transpose())\n\n\n#########################\n#### Rock paper scissors\n#########################\nn = 3\nm = 3\nA = np.matrix('0. -1. 1; 1. 0. -1.; -1 1 0')\nB = - A\n\n# Initial strategies of both players\nx0 = np.zeros((n,1))\nx0[1,0] = 1\ny0 = np.zeros((m,1))\ny0[1,0] = 1\n\n(x,y) = fictitious(n,m,A,B,T,x0,y0)\n\nprint('Rock-paper-scissors')\nprint(x.transpose())\nprint(y.transpose())\n\n \n################################\n## Modified Rock paper scissors\n################################\nn = 3\nm = 3\nA = np.matrix('0. 1. 0.; 0. 0. 1.; 1. 0. 0.')\nB = np.matrix('0. 0. 1.; 1. 0. 0.; 0. 1. 0.')\nT = 1000\n\n# Running empirical average of the two players\n# initialized for one player to play (1,1) strategy\n# These are column vectors\nx0 = np.zeros((n,1))\nx0[1,0] = 1\ny0 = np.zeros((m,1))\ny0[2,0] = 1\n\n(x,y) = fictitious(n,m,A,B,T,x0,y0)\n\nprint('Modified Rock Paper Scissors') \nprint(x.transpose())\nprint(y.transpose())\n \n \n#########################\n## Prisoners dilemma\n#########################\nn = 2\nm = 2\nA = np.matrix('.5 1.; 0. .2')\nB = np.matrix('.5 0.; 1. .2')\nT = 100\n\n# Running empirical average of the two players\n# initialized for one player to play (1,1) strategy\n# These are column vectors\nx0 = np.zeros((n,1))\nx0[1,0] = 1\ny0 = np.zeros((m,1))\ny0[1,0] = 1\n\n(x,y) = fictitious(n,m,A,B,T,x0,y0)\n\nprint('Prisoner\\'s Dilemma')\nprint(x.transpose())\nprint(y.transpose())\n\n","sub_path":"week4/game_theory/fictitious.py","file_name":"fictitious.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"425256645","text":"import glob\nimport logging\nfrom importlib import import_module\nfrom os.path import basename, isdir, isfile\nfrom pathlib import Path\n\nfrom aiogram import Dispatcher\n\n\nclass ModuleManager:\n\n def __init__(self, dp: Dispatcher):\n self.dp = dp\n self.root = Path(__file__).parent.parent\n\n def load_path(self, path: str):\n\n mod_paths = glob.glob(f\"{self.root}/{path}/*.py\")\n\n all_modules = [\n basename(module)[:-3]\n for module in mod_paths\n if isfile(module) and module.endswith(\".py\")\n ]\n\n for module in all_modules:\n self.load(path.replace(\"/\", \".\") + f\".{module}\")\n\n def load(self, module: str):\n\n try:\n imp_module = import_module(\"app.\" + module)\n except ModuleNotFoundError:\n logging.error(f\"Module <{module}> was not found.\")\n raise SystemExit()\n\n if not hasattr(imp_module, \"setup\"):\n logging.error(f\"Module <{module}> doesn't have .\")\n raise SystemExit()\n\n if not callable(imp_module.setup):\n logging.error(f\"Module <{module}> doesn't have callable .\")\n raise SystemExit()\n\n try:\n imp_module.setup(self.dp)\n except Exception as error:\n logging.exception(f\"An error occured in <{module}>: {error}\")\n raise SystemExit()\n\n logging.debug(f\"Module <{module}> was loaded.\")\n return module\n\n def load_all(self, modules: list):\n \"\"\"\n Iterates through modules and loads them.\n \"\"\"\n\n for module in modules:\n\n # Shortcut for %module%.__init__\n if module.startswith(\"$\"):\n self.load(f\"{module[1:]}.__init__\")\n\n elif isdir(f\"{self.root}/{module}/\"):\n self.load_path(module)\n\n else:\n self.load(module)\n","sub_path":"@ander000_bot/app/misc/modular.py","file_name":"modular.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"357980549","text":"# YesかNoの場合ランダムでも半分は正解する\n\ni1=lambda : input()\ni2=lambda : int(input())\ni3=lambda : map(int,input().split())\ni4=lambda : list(map(int,input().split()))\ni5=lambda n : [list(map(int,input().split())) for _ in range(n)]\ni6=lambda n : [list(input())for _ in range(n)]\n\nfrom heapq import heappop, heappush\nfrom collections import deque\n\ndef main():\n N,M=i3()\n\n A=[[]]\n q=[]\n mem=[[] for _ in range(N+1)]\n for i in range(M):\n k=i2()\n *t,=i4()\n t=t[::-1] # 逆転させる\n A.append(t)\n mem[t[-1]].append(i+1) # 逆転させたから末尾が先頭\n\n# N,M=2,2\n# A=[[], [2, 1], [2, 1]]\n# # 毎回Aを探索するは時間がかかる→ボールiがどこにあるのかを辞書にメモしておけばよい\n# mem=[[], [1, 2], []]\n \n q=deque()\n for i in range(1,N+1):\n if len(mem[i])==2:\n q.append(i)\n \n while q:\n v = q.pop() # v:pipes\n for p in mem[v]: #p:pipes\n A[p].pop()\n if len(A[p])!=0:\n mem[A[p][-1]].append(p)\n if len(mem[A[p][-1]])==2:\n q.append(A[p][-1])\n\n for p in A:\n if len(p)!=0:\n print('No')\n return\n print('Yes')\n \nmain()","sub_path":"TLE/ABC216_D_Pair of Ball.py","file_name":"ABC216_D_Pair of Ball.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"552932028","text":"from webauthn import webauthn\nfrom django.apps import AppConfig\nfrom django.conf import settings\n\n\nclass TwoFactorConfig(AppConfig):\n name = 'two_factor'\n verbose_name = \"Django Two Factor Authentication\"\n\n defaults = {\n 'TWO_FACTOR_DEVICE_PREFERENCE': {\n # a lower value means higher priority when computing user's default preference\n 'two_factor.models.WebauthnDevice': 10,\n 'django_otp.plugins.otp_totp.models.TOTPDevice': 20,\n 'two_factor.models.PhoneDevice': 30,\n 'django_otp.plugins.otp_static.models.StaticDevice': 40,\n },\n 'TWO_FACTOR_WEBAUTHN_TRUSTED_ATTESTATION_ROOT': webauthn.DEFAULT_TRUST_ANCHOR_DIR,\n 'TWO_FACTOR_WEBAUTHN_TRUSTED_ATTESTATION_CERT_REQUIRED': True,\n 'TWO_FACTOR_WEBAUTHN_SELF_ATTESTATION_PERMITTED': False,\n 'TWO_FACTOR_WEBAUTHN_UV_REQUIRED': False,\n 'TWO_FACTOR_WEBAUTHN_RP_NAME': None,\n }\n\n def ready(self):\n for name, default in self.defaults.items():\n value = getattr(settings, name, default)\n setattr(settings, name, value)\n\n if getattr(settings, 'TWO_FACTOR_PATCH_ADMIN', True):\n from .admin import patch_admin\n patch_admin()\n","sub_path":"two_factor/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"66551033","text":"from utils_cv.common.gpu import db_num_workers, which_processor\nfrom utils_cv.common.data import unzip_url\nfrom utils_cv.classification.data import Urls\nfrom utils_cv.classification.widget import ResultsWidget\nfrom utils_cv.classification.plot import plot_pr_roc_curves\nfrom utils_cv.classification.model import TrainMetricsRecorder\nfrom fastai.vision import (\n models, ImageList, imagenet_stats, partial, cnn_learner, ClassificationInterpretation, to_np,\n)\nfrom fastai.metrics import accuracy\nimport fastai\n\nfrom pathlib import Path\nimport numpy as np\nimport sys\n\n\n# fastai and torch\n\n# local modules\n\nprint(f\"Fast.ai version = {fastai.__version__}\")\nwhich_processor()\n\nEPOCHS = 10\nLEARNING_RATE = 1e-4\nIM_SIZE = 300\n\nBATCH_SIZE = 16\nARCHITECTURE = models.resnet18\npath = Path('/app/classifier_data/')\n\ndata = (\n ImageList.from_folder(path)\n .split_by_rand_pct(valid_pct=0.2, seed=10)\n .label_from_folder()\n .transform(size=IM_SIZE)\n .databunch(bs=BATCH_SIZE, num_workers=db_num_workers())\n .normalize(imagenet_stats)\n)\n\nprint(f'number of classes: {data.c}')\nprint(data.classes)\n\nlearn = cnn_learner(\n data,\n ARCHITECTURE,\n metrics=[accuracy],\n callback_fns=[partial(TrainMetricsRecorder, show_graph=True)]\n)\nlearn.unfreeze()\nlearn.fit(EPOCHS, LEARNING_RATE)\nlearn.export(file=Path(\n \"/app/classifier_model.pkl\"))\n_, validation_accuracy = learn.validate(\n learn.data.valid_dl, metrics=[accuracy])\nprint(f'Accuracy on validation set: {100*float(validation_accuracy):3.2f}')\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"268291933","text":"# -*- coding: utf-8 -*-\nimport random\nimport time\nimport unittest\nimport allure\nfrom src.functions.functions import Functions as Selenium\nimport HtmlTestRunner\n\n@allure.feature(u'Carga de documentos')\n@allure.testcase(u'[Flujo carga Doc] Cuadro de resumen')\n@allure.severity(allure.severity_level.NORMAL)\n@allure.description(u\"\"\"validaciones:
\nAl rellenar la segunda pantalla y clickar sobre el boton 'SIGUIENTE', deberia de aparecer un cuadro de resumen,\nel cual contenga toda la informacion anteriormente ingresada. Validar la informacion que aparece en el cuadro de resumen \n

\"\"\")\n\nclass test_flow_006(Selenium, unittest.TestCase):\n\n def setUp(self):\n with allure.step(u'PASO 1 : Ingresar al navegador'):\n Selenium.open_browser(self, navegador=\"CHROME\")\n self.dataRoles = ['felipe.bravo', 'juan.suaza', 'dvalero84', 'nadia.gallardo'] #USUARIOS PARA EL FLUJO\n self.dataComentario = ['Hola necesitamos que en conjunto pongamos mas de nuestra parte', 'No tengo ningun comentario',\n 'Por favor poner ojo con esto', 'Te asigne un par de días', 'Necesito aprobación de esto lo antes posible',\n 'Estamos haciendo unas pruebas', 'Estos son test', 'Comentarios de pruebas', 'Es necesario aprobar esto ahora',\n 'Genial aprobación']\n\n @allure.title(u'Cuadro de resumen')\n @allure.story(u'Validar nombres, roles, nombre del archivo, fecha, etc.')\n def test_resumen(self):\n with allure.step(u'PASO 2 : Ingresar con el usuario Admin'):\n usuario = ['juan.suaza', 'nadia.gallardo', 'felipe.bravo', 'dvalero84'] #USUARIOS PARA INICIAR SESIÓN\n nomUser = random.choice(usuario)\n Selenium.get_signin_administrator(self, nomUser) #Cambiar el usuario colocar alguno diferente del admin\n\n with allure.step(u'PASO 3 : Rellenar formulario'):\n names = Selenium.carga_doc_controlado(self)\n names\n\n with allure.step(u'PASO 4 : Realizar el llenado y validaciones.'):\n Selenium.get_json_file(self, \"flujoCargaDocumento\")\n campos = ['Input nombre', 'Input dias', 'Input comentario']\n roles = ['owner', 'coAutor', 'Stakeholder', 'Reviewed', 'Approved', 'released']\n for x in range(6):\n x += 1\n Selenium.check_element(self, f\"button {x}\")\n Selenium.check_visibility_element_located(self, f\"button {x}\")\n self.driver.execute_script('arguments[0].scrollIntoView(true);', Selenium.get_elements(self, f\"button {x}\"))\n if x > 1 and x < 6:\n Selenium.check_visibility_element_located(self, f\"button {x}\")\n Selenium.get_elements(self, f\"button {x}\").click()\n if x == 6:\n Selenium.foto(self, \"Botones\")\n\n for a in range(6):\n for b in range(3):\n check = Selenium.check_element(self, campos[b] + \" \" + roles[a])\n assert check == True, f\"Error, no se encontro el {campos[b]}\" f\"{roles[a]}\"\n if a >= 0 and a <= 5 and not b == 2:\n Selenium.get_elements(self, 'Button Siguiente').click()\n check = Selenium.check_exists_by_xpath(self, \"//p[contains(text(), 'Campo requerido')]\")\n if check == False:\n Selenium.foto(self, \"Campos requeridos\")\n assert check == True, f\"Error el campo {campos[b]} {roles[a]}, no tiene la validacion 'Campos requeridos'\"\n if b == 0:\n rol = random.choice(self.dataRoles)\n if b == 0 and a == 0:\n while rol == nomUser:\n rol = random.choice(self.dataRoles)\n Selenium.get_elements(self, campos[b] + \" \" + roles[a]).send_keys(rol)\n time.sleep(0.5)\n Selenium.send_especific_keys(self, campos[b] + \" \" + roles[a], \"Enter\")\n if b == 1:\n Selenium.get_elements(self, campos[b] + \" \" + roles[a]).send_keys(random.randint(1,99))\n if b == 2:\n Selenium.get_elements(self, campos[b] + \" \" + roles[a]).send_keys(random.choice(self.dataComentario))\n Selenium.get_elements(self, \"textbox\").send_keys(random.choice(self.dataComentario))\n enabled = Selenium.get_elements(self, 'Button Siguiente').is_enabled()\n if enabled == False:\n Selenium.foto(self, \"Boton siguiente bloqueado\")\n assert enabled == True, \"El boton siguiente al parecer esta bloqueado\"\n Selenium.get_elements(self, 'Button Siguiente').click()\n\n data = []\n for a in range(6):\n for b in range(3):\n Selenium.check_element(self, campos[b] + \" \" + roles[a])\n if b == 0:\n data.append(roles[a])\n value = Selenium.get_elements(self, campos[b] + \" \" + roles[a]).get_attribute(\"value\")\n data.append(value)\n if b == 1:\n valu = Selenium.get_elements(self, campos[b] + \" \" + roles[a]).get_attribute(\"value\")\n data.append(valu + \" días\")\n if b == 2:\n value = Selenium.get_elements(self, campos[b] + \" \" + roles[a]).get_attribute(\"value\")\n data.append(value)\n\n xpath1 = \"//*[@id='body']/div[2]/div[3]/div/div[2]/div[1]/div/div/table/tbody/tr/td\" #PRIMERA TABLA DEL CUADRO DE RESUMEN\n check1 = Selenium.check_exists_by_xpath(self, xpath1)\n if check1 == False:\n Selenium.foto(self, \"tabla\")\n assert check1 == True, \"No se encuentra la tabla de informacion\"\n elements1 = self.driver.find_elements_by_xpath(xpath1)\n for td in range(len(elements1)):\n td += 1\n element = self.driver.find_element_by_xpath(f\"//*[@id='body']/div[2]/div[3]/div/div[2]/div[1]/div/div/table/tbody/tr/td[{str(td)}]\").text\n if td == 1:\n self.assertIn(element, names[0], f\"Error los elementos no coinciden con el valor ingresado='{names[0]}'\")\n if td == 2:\n self.assertIn(element, (\"/\"+names[1]), f\"Error los elementos no coinciden con el valor ingresado='{names[1]}'\")\n if td == 3:\n if not element == Selenium.textDateEnvironmentReplace(self, \"hoy\"):\n Selenium.foto(self, \"foto\")\n assert element == Selenium.textDateEnvironmentReplace(self, \"hoy\"), \"La fecha no es igual a la ingresada\"\n if td == 4:\n if not element == usuario:\n Selenium.foto(self, \"foto\")\n assert element == nomUser, \"El usuario no es el mismo con el cual se esta ingresando\"\n if td == 5:\n if not element == \"1.0\":\n Selenium.foto(self, \"foto\")\n assert element == \"1.0\", f\"La version ya es la numero = {element}\"\n\n xpath2 = \"//*[@id='body']/div[2]/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr\"\n check2 = Selenium.check_exists_by_xpath(self, xpath2)\n if not check2:\n Selenium.foto(self, \"tabla\")\n assert check2, \"No se encuentra la tabla de informacion\"\n elements2 = len(self.driver.find_elements_by_xpath(xpath2))\n dataResumen = []\n for tr in range(elements2):\n tr += 1\n tds = len(self.driver.find_elements_by_xpath(f\"//*[@id='body']/div[2]/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[{str(tr)}]/td\")) #SEGUNDA TABLA DEL CUADRO DE RESUMEN\n for td in range(tds):\n td += 1\n info = self.driver.find_element_by_xpath(f\"//*[@id='body']/div[2]/div[3]/div/div[2]/div[2]/div/div/table/tbody/tr[{str(tr)}]/td[{str(td)}]\").text\n\n dataResumen.append(info)\n\n Selenium.foto(self, \"Cuadro de resumen\")\n for d in range(len(data)):\n if not dataResumen[d].lower() == data[d].lower():\n Selenium.foto(self, \"Los datos no son iguales\")\n\n self.assertIn(dataResumen[d].lower(), data[d].lower(), \"Los datos visualizados en el cuadro de resumen no son correctos\")\n\n def tearDown(self):\n Selenium.tearDown(self)\n\nif __name__ == '__main__':\n unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='report'))","sub_path":"src/tests/test_document_upload/test_upload_flow/test_flow_006.py","file_name":"test_flow_006.py","file_ext":"py","file_size_in_byte":8835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"422663407","text":"# with <3 by Jason Le\n\nimport pygame as pi\nfrom random import randint\ndp_width = 800\ndp_height = 500\n\npi.init()\n\nscreen = pi.display.set_mode((dp_width, dp_height))\npi.display.set_caption('Amar.PI by Jason')\n\nmap_width = 1000\nmap_height = 1000\n\n# [map x, map y, radius, color]\nplayer = [[500, 500, 10, (250, 227, 68)]]\nspeed = .05\nmousePosition = [dp_width // 2, dp_height // 2]\n\nblobs = []\n\nfor i in range(100):\n blobs.append([])\n blobs[-1].append(randint(0, map_width))\n blobs[-1].append(randint(0, map_height))\n\ndef movement(mousePosition, player, speed, map_width, map_height):\n if mousePosition[0] < dp_width // 2:\n player[0][0] -= speed\n else:\n player[0][0] += speed\n\n if mousePosition[1] < dp_height // 2:\n player[0][1] -= speed\n else:\n player[0][1] += speed\n return player[0][0], player[0][1]\n\ndef blobers(blobs, player, dp_width, dp_height):\n for i in blobs:\n print(blobs[i][0], player[0][0])\n if 0 < blobs[i][0] - player[0][0] < dp_width and 0 < blobs[i][1] - player[0][1] < dp_height:\n pi.draw.circle(screen, (0, 255, 0), (blobs[i][0] - player[0][0], blobs[i][1] - player[0][1]), 10)\nwhile True:\n for event in pi.event.get():\n mousePosition[0], mousePosition[1] = pi.mouse.get_pos()\n\n blobers(blobs, player, dp_width, dp_height)\n player[0][0], player[0][1] = movement(mousePosition, player, speed, map_width, map_height)\n\n screen.fill((255, 255, 255))\n\n # Draw player\n pi.draw.circle(screen, player[0][3], (dp_width // 2, dp_height // 2), player[0][2])\n print(player[0][0], player[0][1])\n\n pi.display.flip()\n","sub_path":"AmarPI/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"314847235","text":"from zeit.cms.i18n import MessageFactory as _\nimport gocept.form.grouped\nimport pysolr\nimport zeit.cms.interfaces\nimport zeit.content.cp.browser.blocks.teaser\nimport zeit.content.cp.browser.view\nimport zeit.content.cp.interfaces\nimport zeit.edit.browser.block\nimport zeit.find.search\nimport zope.formlib.form\nimport zope.formlib.interfaces\nimport zope.formlib.widgets\n\n\nclass ViewletManager(zeit.edit.browser.block.BlockViewletManager):\n\n @property\n def css_class(self):\n classes = super(ViewletManager, self).css_class\n visible = 'block-visible-off' if not self.context.visible else ''\n return ' '.join(['editable-area', visible, classes])\n\n\nclass AreaViewletManager(ViewletManager):\n\n @property\n def css_class(self):\n classes = super(AreaViewletManager, self).css_class\n\n if not zeit.content.cp.interfaces.\\\n automatic_area_can_read_teasers_automatically(self.context):\n automatic = 'block-automatic-not-possible'\n else:\n if self.context.automatic:\n automatic = 'block-automatic-on'\n else:\n automatic = 'block-automatic-off'\n\n return ' '.join(['editable-area', automatic, classes])\n\n\nclass EditCommon(zeit.content.cp.browser.view.EditBox):\n\n form_fields = zope.formlib.form.Fields(\n zeit.content.cp.interfaces.IArea).select(\n 'supertitle', 'title', 'read_more', 'read_more_url', 'image',\n 'visible_mobile')\n\n\nclass EditOverflow(zeit.content.cp.browser.view.EditBox):\n\n form_fields = zope.formlib.form.Fields(\n zeit.content.cp.interfaces.IArea).select(\n 'block_max', 'overflow_into')\n\n\nclass SolrQueryWidget(zope.formlib.widgets.TextAreaWidget):\n\n def _toFieldValue(self, value):\n value = super(SolrQueryWidget, self)._toFieldValue(value)\n try:\n zeit.find.search.search(value, rows=1)\n except pysolr.SolrError:\n raise zope.formlib.interfaces.ConversionError(\n _('Invalid solr query'), value)\n return value\n\n\nclass EditAutomatic(zeit.content.cp.browser.blocks.teaser.EditCommon):\n\n form_fields = zope.formlib.form.FormFields(\n zeit.content.cp.interfaces.IArea).select(\n 'count', 'query', 'query_order', 'raw_query', 'raw_order',\n 'automatic', 'automatic_type', 'referenced_cp', 'hide_dupes')\n form_fields['raw_query'].custom_widget = SolrQueryWidget\n\n field_groups = (\n # XXX Kludgy: ``automatic`` must come after ``count``, since setting\n # automatic to True needs to know the teaser count. Thus, we order the\n # form_fields accordingly, and alter the _display_ order here.\n gocept.form.grouped.Fields(\n '', ('automatic_type', 'automatic', 'count', 'hide_dupes')),\n gocept.form.grouped.Fields(\n _('automatic-area-type-centerpage'), ('referenced_cp',)),\n gocept.form.grouped.Fields(\n _('automatic-area-type-channel'), ('query', 'query_order')),\n gocept.form.grouped.Fields(\n _('automatic-area-type-query'), ('raw_query', 'raw_order')),\n )\n\n template = zope.browserpage.ViewPageTemplateFile(\n 'blocks/teaser.edit-common.pt')\n\n def setUpWidgets(self, *args, **kw):\n super(EditAutomatic, self).setUpWidgets(*args, **kw)\n self.widgets['automatic'].reversed = False\n\n\nclass ChangeLayout(zeit.content.cp.browser.blocks.teaser.ChangeLayout):\n\n interface = zeit.content.cp.interfaces.IArea\n\n\nclass SchematicPreview(object):\n\n prefix = 'http://xml.zeit.de/data/cp-area-schemas/{}.svg'\n\n def areas(self):\n region = zeit.content.cp.interfaces.IRegion(self.context)\n return region.values()\n\n def preview(self, area):\n content = zeit.cms.interfaces.ICMSContent(\n self.prefix.format(area.kind))\n return content.open().read()\n\n def css_class(self, area):\n classes = ['area-preview-image']\n if area == self.context:\n classes.append('active')\n return ' '.join(classes)\n","sub_path":"src/zeit/content/cp/browser/area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"536816150","text":"# Autor: Mariana Brito Rodrigues - britormariana@gmail.com\r\n \r\n\r\n# Function to parse the number to find if it's bouncy. The variable s represent the result of the convertion.\r\ndef is_bouncy(num):\r\n increasing, decreasing, s = False, False, str(num) #I only use str(valor), len(valor) to demonstrate python's methods use :) I can do the same result without this.\r\n for i in range (len(s)-1):\r\n if s[i+1] > s[i]: increasing = True\r\n elif s[i+1] < s[i]: decreasing = True\r\n if increasing and decreasing: return True\r\n return False\r\n\r\n# For this specific result I begin at the 90% point specified in the problem description and iterate through numbers until the bouncy count is 99% of the total count\r\nnum, proportion = 21780, 0.90\r\nbouncy = num * proportion\r\n\r\nwhile proportion != 0.99:\r\n num += 1\r\n if is_bouncy(num): bouncy += 1\r\n proportion = bouncy/num\r\n\r\nprint (\"The number is: \", num)","sub_path":"myAnswer.py","file_name":"myAnswer.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"347241743","text":"# -*- coding: UTF-8 -*-\n'''\nCreated on 2020/2/26\n@File : test_get_symptom_similarity.py\n@author: ZL\n@Desc :\n'''\n\nimport os\nimport requests\nimport time\nfrom tqdm import tqdm\nfrom commonfunc.change_data_type import ChangeDataType\nfrom commonfunc.common_function import CommonFunction\nfrom algorithm.algorithm_func import Binary\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\n\n\nclass GetSymptomSimilarity:\n\n def get_symptom_similarity(self, api_url, test_data_file, result_file):\n test_data = ChangeDataType.csv_to_dict(rootPath + \"\\\\testdata\\\\apidata\\\\\" + test_data_file)\n lb_list, re_label_list, normal_sys_list, tf_list = [], [], [], []\n for idx, temp in tqdm(test_data.iterrows()):\n label = int(temp[\"label\"])\n str1 = temp[\"普通症状\"]\n str2 = temp[\"标准症状\"]\n url = api_url.format(str1)\n try:\n r = requests.get(url, timeout=1000)\n print(r)\n result = r.json()\n normal_sys = result[\"standard\"]\n re_label = CommonFunction.get_sys_similary_tf(normal_sys, str2)\n tf = CommonFunction.get_tf(re_label, label)\n except Exception as e:\n score = \"bad request\"\n print(e)\n # self.logging.info(\"症状1:\" + str1 + \"---症状2:\" + str2 + \"---预期分数:\"\n # + str(label) + \"---实际分数:\" + str(re_score) + \"---是否一致:\" + tf)\n normal_sys_list.append(normal_sys)\n # score_list.append(score)\n re_label_list.append(re_label)\n tf_list.append(tf)\n lb_list.append(label)\n test_data[\"normal_sys\"] = normal_sys_list\n test_data[\"re_label\"] = re_label_list\n test_data = CommonFunction.get_collection_1(test_data, tf_list)\n Binary.binary_plot_curve(lb_list, re_label_list)\n now = time.strftime('%y_%m_%d-%H_%M_%S')\n test_data.to_excel(rootPath + '\\\\testresults\\\\resultfile\\\\' + now + result_file, index=False,\n encoding=\"utf-8\")\n\n\nif __name__ == '__main__':\n GetSymptomSimilarity().get_symptom_similarity(\"http://192.168.1.74:1122/demo?sentence={}\",\n \"similary\\\\gynaecology_sym_test_1740.csv\",\n \"gynaecology_symptom_similary_test_result.xls\")\n","sub_path":"api/get_symptom_similarity.py","file_name":"get_symptom_similarity.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"267029094","text":"#A6\r\nrehber=open('C:/Users/PC/Desktop/rehber.txt','r')\r\nlines = rehber.read().split(',')\r\nisim=input('Bir isim giriniz...')\r\nisim=isim.capitalize()\r\nsoyisim=input('Bir soyisim giriniz...')\r\nsoyisim=soyisim.capitalize()\r\nkisi=isim+' '+soyisim\r\nif kisi in lines:\r\n numarası=lines.index(kisi)+1\r\n print(kisi+\" adlı kişinin numarası=\"+lines[numarası])\r\nelse:\r\n print(\"Böyle bir kişi rehberde yoktur...\")\r\n","sub_path":"2.Week/A6.py","file_name":"A6.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"512835794","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport pytest\nfrom pandas import DataFrame, to_datetime\n\nfrom superset.exceptions import QueryObjectValidationError\nfrom superset.utils.pandas_postprocessing import resample\nfrom tests.unit_tests.fixtures.dataframes import timeseries_df\n\n\ndef test_resample():\n df = timeseries_df.copy()\n df.index.name = \"time_column\"\n df.reset_index(inplace=True)\n\n post_df = resample(df=df, rule=\"1D\", method=\"ffill\", time_column=\"time_column\",)\n assert post_df[\"label\"].tolist() == [\"x\", \"y\", \"y\", \"y\", \"z\", \"z\", \"q\"]\n\n assert post_df[\"y\"].tolist() == [1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 4.0]\n\n post_df = resample(\n df=df, rule=\"1D\", method=\"asfreq\", time_column=\"time_column\", fill_value=0,\n )\n assert post_df[\"label\"].tolist() == [\"x\", \"y\", 0, 0, \"z\", 0, \"q\"]\n assert post_df[\"y\"].tolist() == [1.0, 2.0, 0, 0, 3.0, 0, 4.0]\n\n\ndef test_resample_with_groupby():\n \"\"\"\nThe Dataframe contains a timestamp column, a string column and a numeric column.\n__timestamp city val\n0 2022-01-13 Chicago 6.0\n1 2022-01-13 LA 5.0\n2 2022-01-13 NY 4.0\n3 2022-01-11 Chicago 3.0\n4 2022-01-11 LA 2.0\n5 2022-01-11 NY 1.0\n \"\"\"\n df = DataFrame(\n {\n \"__timestamp\": to_datetime(\n [\n \"2022-01-13\",\n \"2022-01-13\",\n \"2022-01-13\",\n \"2022-01-11\",\n \"2022-01-11\",\n \"2022-01-11\",\n ]\n ),\n \"city\": [\"Chicago\", \"LA\", \"NY\", \"Chicago\", \"LA\", \"NY\"],\n \"val\": [6.0, 5.0, 4.0, 3.0, 2.0, 1.0],\n }\n )\n post_df = resample(\n df=df,\n rule=\"1D\",\n method=\"asfreq\",\n fill_value=0,\n time_column=\"__timestamp\",\n groupby_columns=(\"city\",),\n )\n assert list(post_df.columns) == [\n \"__timestamp\",\n \"city\",\n \"val\",\n ]\n assert [str(dt.date()) for dt in post_df[\"__timestamp\"]] == (\n [\"2022-01-11\"] * 3 + [\"2022-01-12\"] * 3 + [\"2022-01-13\"] * 3\n )\n assert list(post_df[\"val\"]) == [3.0, 2.0, 1.0, 0, 0, 0, 6.0, 5.0, 4.0]\n\n # should raise error when get a non-existent column\n with pytest.raises(QueryObjectValidationError):\n resample(\n df=df,\n rule=\"1D\",\n method=\"asfreq\",\n fill_value=0,\n time_column=\"__timestamp\",\n groupby_columns=(\"city\", \"unkonw_column\",),\n )\n\n # should raise error when get a None value in groupby list\n with pytest.raises(QueryObjectValidationError):\n resample(\n df=df,\n rule=\"1D\",\n method=\"asfreq\",\n fill_value=0,\n time_column=\"__timestamp\",\n groupby_columns=(\"city\", None,),\n )\n","sub_path":"tests/unit_tests/pandas_postprocessing/test_resample.py","file_name":"test_resample.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"184116339","text":"############################################################\n#\n# do_no34_trend_plot.py\n#\n############################################################\n#\n# Author: Seb Viret \n#\n# November 23, 2009\n#\n# Goal: \n# Compute an history plot for the partitions variation\n#\n# Input parameters are:\n#\n# -> part: the partition number (0=LBA, 1=LBC, 2=EBA, 3=EBC) you want to plot.\n# DEFAULT VAL = -1 : produces all the plots \n#\n# -> limit: the maximum tolerable variation (in %). If this variation\n# is excedeed the plots will have a RED background\n#\n# -> doWiki: used by laser experts to update the status webpage\n#\n# -> doEps: provide eps plots in addition to default png graphics\n#\n# -> nDays: how many days before the last run do you want to check the partition\n# DEFAULT VAL = -1 : all the range\n#\n# For more info on the LASER system : http://atlas-tile-laser.web.cern.ch\n#\n#############################################################\n\nfrom src.oscalls import *\nfrom src.GenericWorker import *\nimport src.MakeCanvas\nimport time\nimport math\n\n# For using the MIB tools\nfrom src.MIB.toolbox import *\n\nclass do_prescale_trend_plot(GenericWorker):\n \"Compute history plot\"\n\n c1 = src.MakeCanvas.MakeCanvas()\n\n def __init__(self, pixcut=0, doEps=False):\n self.doEps = doEps\n self.bit = 5\n self.pixc = pixcut\n self.dir = getPlotDirectory()\n self.events1 = set()\n self.events2 = set()\n self.run_list = []\n self.BBTool = MIBTools()\n self.origin = ROOT.TDatime()\n \n self.time_max = 0\n self.time_min = 10000000000000000\n\n\n #\n # Here we collect all the relevant information\n #\n \n def ProcessRegion(self, region):\n \n for event in region.GetEvents():\n\n [type, bit, beam] = self.BBTool.GetNumber(event.data['region'])\n \n if type!=2: # \n continue\n\n if self.bit != bit:\n continue\n\n if event.runNumber not in self.run_list:\n self.run_list.append(event.runNumber)\n\n if event.data.has_key('is_OK') and event.data['t_start']!=0:\n\n if beam == 1: \n self.events1.add(event)\n\n if self.time_min>event.data['t_start']:\n self.time_min = event.data['t_start'] \n \n if self.time_max\") \r\n\r\n\r\n\r\ndef DFS(graph,rootNode): \r\n\r\n\t\tvisitNodes = [] #visit nodes are represented with true and unvisited nodes are represented with false.Also,node n is in (n-1).index\r\n\t\ti = 0\r\n\t\twhile i < len(graph): #len(graph) give us node count and there must be node count visitNodes\r\n\t\t\tvisitNodes.append(False) #at the beginning, there aren't visited nodes, so all visitNodes indeces must be filled with False.\r\n\t\t\ti=i+1\r\n\r\n\t\t# Call the recursive helper function to print \r\n\t\t# DFS traversal \r\n\t\tDFSHelper(graph,rootNode,visitNodes)#helper method is called\r\n\r\n\r\ndef DFSHelper(graph,v,visitNodes): \r\n\r\n\t\t\r\n\t\tvisitNodes[v-1]= True #root node visited so update it with True\r\n\t\t\r\n\t\t# iterated nodes are printed\r\n\t\tif False in visitNodes: #if we are not in last iteration so , need to append arrow\r\n\t\t\tprint (v, end = \"->\")\r\n\t\telse:\t\t\t\t\t #if we are in last iteration so ,no need to append arrow\r\n\t\t\tprint (v, end = \"\")\r\n\r\n\t\tfor i in graph[v]: #traverse the adjacent of the node v and if there is an unvisited node send this node to travering its adjacents.\r\n\t\t\tif visitNodes[i-1] == False:\r\n\t\t\t\tDFSHelper(graph,i,visitNodes)\r\n\r\n\r\n#Driver code\r\ngraph = { }\r\nrootNode = readExcelFillTheGraph(graph)\r\nprint(\"BFS: \",end='') \r\nBFS(graph,rootNode) #1->2->3->4->5->8->6->9->10->7\r\nprint('\\n')\r\nprint(\"DFS: \",end='') \r\nDFS(graph,rootNode) #1->2->4->5->6->7->8->9->10->3\r\n","sub_path":"hw1/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"289528638","text":"from flask_restful import Resource, reqparse\nfrom flask import current_app as app\nfrom flask import abort\nfrom EyeTrack import runner\nfrom pathlib import Path\n\nimport os\nimport json\n\n\nclass Test(Resource):\n\n \"\"\"\n This class is used to represent our data folders so that the user can see\n what they have available to them.\n\n Supported API calls: GET (List), POST (Create).\n \"\"\"\n\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('test')\n self.parser.add_argument('name')\n self.parser.add_argument('dataArch')\n self.parser.add_argument('modelLoc')\n self.parser.add_argument('data')\n self.parser.add_argument('v')\n self.parser.add_argument('epoch')\n self.parser.add_argument('batch_size')\n self.parser.add_argument('type')\n self.parser.add_argument('screenSizeX')\n self.parser.add_argument('screenSizeX')\n self.parser.add_argument('gridRowSize')\n self.parser.add_argument('gridColSize')\n\n super().__init__()\n\n def get(self):\n \"\"\"\n Returns all files in TEST_LOC dir.\n\n Returns: \n (json) All the files in TEST_LOC\n \"\"\"\n path = app.config['TEST_LOC']\n files = os.listdir(path)\n return_value = {'File': []}\n for f in files:\n return_value['File'].append({'Name': f})\n return return_value\n\n def post(self):\n \"\"\"\n Create the test flags for passing to the model.\n\n Returns: \n (json) The test data of the model.\n \"\"\"\n kwargs = self.parser.parse_args()\n\n args = ['--test']\n path = app.config['DATA_LOC']\n\n for i in ['type', 'data', 'modelLoc']:\n if not kwargs.get(i):\n raise ValueError('Missing {} flag'.format(i))\n\n args.append('--data={}'.format(path + '\\\\' + kwargs['data']))\n args.append('--type={}'.format(kwargs.get('type')))\n args.append('--modelLoc={}'.format(app.config['MODEL_LOC'] + '\\\\' + kwargs['modelLoc'].split('.')[0]))\n\n if kwargs.get('v'):\n args.append('-v')\n\n for i in ['dataArch', 'epoch', 'batch_size', 'screenSizeX', 'screenSizeY', 'gridRowSize', 'gridColSize', 'name']:\n if kwargs.get(i):\n args.append('--{}={}'.format(i, kwargs.get(i)))\n\n return runner.main(from_app=args)\n\n def put(self):\n \"\"\"\n Not supported for Data.\n \"\"\"\n return abort(405)\n\n\nclass TestFile(Resource):\n\n \"\"\"\n This class is used to represent TestFiles so that users can access the file \n later.\n\n Supported API calls: GET (List)\n \"\"\"\n\n def get(self, test_file, **kwargs):\n \"\"\"\n Return a file in the TEST_LOC directory and read the file content.\n\n Raises:\n 404 (HTTP Status code) if the file is missing.\n Returns: \n (json) The file content.\n \"\"\"\n path = app.config['TEST_LOC']\n l_file = Path('{}/{}'.format(path, test_file))\n if not l_file.is_file():\n abort(404)\n\n data = {'file_name': test_file}\n\n with open(l_file) as j_file:\n data.update(json.load(j_file))\n\n return data\n\n def post(self):\n \"\"\"\n Not supported for Data.\n \"\"\"\n return abort(405)\n\n def put(self):\n \"\"\"\n Not supported for Data.\n \"\"\"\n return abort(405)\n","sub_path":"dependencies/Model/EyeTrackFlask/Resources/Tester.py","file_name":"Tester.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"508780884","text":"import urllib\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import ugettext as _\n\nfrom brouwers.albums.models import Album\n\n\nclass UserMigration(models.Model):\n username = models.CharField(max_length=50) #actually 20\n username_clean = models.CharField(max_length=50) #lowercase version\n email = models.EmailField(max_length=254)\n hash = models.CharField(max_length=256, blank=True, null=True)\n\n class Meta:\n ordering = ['username_clean']\n\n def __unicode__(self):\n return u\"%s\" % self.username\n\n def save(self, *args, **kwargs):\n if not self.username_clean:\n self.username_clean = self.username.lower()\n super(UserMigration, self).save(*args, **kwargs)\n\n @property\n def url(self):\n params = {'hash': self.hash, 'forum_nickname': self.username}\n query_string = urllib.urlencode(dict([k, v] for k, v in params.items()))\n return u\"http://modelbrouwers.nl/confirm_account/?%s\" % (query_string)\n\nclass AlbumUserMigration(models.Model):\n username = models.CharField(max_length=50)\n email = models.EmailField(max_length=254)\n django_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)\n\n class Meta:\n verbose_name = _(\"album user migration\")\n verbose_name_plural = _(\"album user migrations\")\n\n def __unicode__(self):\n if self.django_user:\n django_user = self.django_user.__unicode__() + \" (%s)\" % self.django_user.email\n else:\n django_user = \"[django user not found]\"\n return u\"%s (%s) -> %s\" % (self.username, self.email, django_user)\n\nclass AlbumMigration(models.Model):\n title = models.CharField(max_length=1024)\n description = models.CharField(max_length=1024, blank=True)\n owner = models.ForeignKey(AlbumUserMigration)\n migrated = models.NullBooleanField(blank=True, null=True)\n new_album = models.ForeignKey(Album, blank=True, null=True)\n\n class Meta:\n ordering = ('owner', 'title')\n\n def __unicode__(self):\n return u\"%s\" % self.title\n\nclass PhotoMigration(models.Model):\n album = models.ForeignKey(AlbumMigration)\n filepath = models.CharField(max_length=80)\n filename = models.CharField(max_length=256)\n pwidth = models.PositiveIntegerField(blank=True, null=True)\n pheight = models.PositiveIntegerField(blank=True, null=True)\n owner = models.ForeignKey(AlbumUserMigration)\n title = models.CharField(max_length=512, blank=True)\n caption = models.CharField(max_length=1024, blank=True)\n migrated = models.NullBooleanField()\n\n class Meta:\n ordering = ('album',)\n\n def __unicode__(self):\n return u\"%(path)s%(filename)s\" % {'path': self.filepath, 'filename': self.filename}\n","sub_path":"src/brouwers/migration/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"375761114","text":"MLB_team = {\n 'Colorado': 'Rockies',\n 'Boston': 'Red Sox',\n 'Minnesota': 'Twins',\n 'Milwaukee': 'Brewers',\n 'Seattle': 'Mariners'\n}\n\nfor value in MLB_team.values(): # looping through the values\n print(value)\nfor key in MLB_team.keys(): # looping through the keys\n print(key)\n\nfor key, value in MLB_team.items(): #two looping variables\n print(key, value)\n\n\n\n# print(MLB_team)\n","sub_path":"dictionaries/iterating.py","file_name":"iterating.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"568306961","text":"import torch\nimport torch.nn as nn\nimport torch.utils as utils\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport torchvision\nimport os\nimport numpy as np\nimport imageio\nfrom random import *\n\n\ndef Loss(loss = 'BCELoss'):\n if loss == 'BCELoss':\n return nn.BCELoss()\n elif loss == 'MSELoss':\n return nn.MSELoss()\n elif loss == 'L1Loss':\n return nn.L1Loss()\n\n\ndef optim(m, lr, optim = 'Adam', betas = (0.5, 0.99)):\n if optim == 'Adam':\n return torch.optim.Adam(m.parameters(), lr = lr, betas = betas)\n elif optim == 'SGD':\n return troch.optim.SGD(m.parameters(), lr = lr, momentum = betas[0])\n\n\n\n\n \ndef PresentationExperience(epoch,num , stop, **kargw):\n sentence = '\\r[ epoch : %d ] [ num : %d ]'\n for i in range(len(kargw)):\n sentence += '[ %s : %.4f ] '\n print(sentence % (epoch, num, *[i for a in kargw for i in [a, kargw[a]]] ) , end = ' ')\n if num % stop == 0:\n print()\n \ndef Accuracy(X, Y):\n correct = 0\n for i in range(X.size(0)):\n if X[i][Y[i]] == X[i].max():\n correct += 1\n return correct/X.size(0)\n \ndef init_weight(net, init_type='normal', init_gain=0.02):\n '''\n ========================================\n parameters\n mean = 0. sd = 0.02\n \n Conv = Normal(0, 0.02)\n BatchNorm = Normal(1.0, 0.02)\n ========================================\n '''\n def init_func(m): # define the initialization function\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n init.normal_(m.weight.data, 0.0, init_gain)\n elif init_type == 'xavier':\n init.xavier_normal_(m.weight.data, gain=init_gain)\n elif init_type == 'kaiming':\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n init.orthogonal_(m.weight.data, gain=init_gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n \n if hasattr(m, 'bias') and m.bias is not None:\n init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n init.normal_(m.weight.data, 1.0, init_gain)\n init.constant_(m.bias.data, 0.0)\n elif classname.find('InstanceNorm2d') != -1: # InstanceNorm Layer's weight is not a matrix; only normal distribution applies.\n init.normal_(m.weight.data, 1.0, init_gain)\n init.constant_(m.bias.data, 0.0)\n \n return init_func(net)\n \n","sub_path":"[4] CycleGAN/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"585043699","text":"class RSA:\n \n def __init__(self):\n from random import randrange\n from random import randint\n \n def ismillerprime(self, n, k):\n if n == 1:\n return False\n if n in [2, 3, 5, 7, 11, 13, 17, 19]:\n return True\n for p in [2, 3, 5, 7, 11, 13, 17, 19]:\n if n % p == 0:\n return False\n r = 0\n s = n - 1\n while s % 2 == 0:\n r += 1\n s //= 2\n for i in range(k):\n a = randrange(2, n - 1)\n x = pow(a, s, n)\n if x == 1 or x == n - 1:\n continue\n for j in range(r - 1):\n x = pow(x, 2, n)\n if x == n - 1:\n break\n else:\n return False\n return True\n \n def randomprime(self, length, millerrounds):\n length -= 1\n start = randint(10 ** length, 10 ** length * 9)\n if start % 2 == 0:\n start += 1\n counter = 0\n isloop = True\n while isloop:\n testnumber = start + (counter * 2)\n if ismillerprime(testnumber, millerrounds):\n isloop = False\n counter += 1\n return testnumber\n \n def generatekeys(self, length, millerrounds):\n p = randomprime(length // 2, millerrounds)\n q = randomprime(length // 2, millerrounds)\n while p == q:\n q = randomprime(length // 2, millerrounds)\n n = p * q\n phin = (p - 1) * (q - 1)\n e = randomprime(length // 2, millerrounds)\n while phin % e == 0 or n % e == 0:\n e = randomprime(length // 2, millerrounds)\n d = pow(e, -1, phin)\n del p\n del q\n return [[e, n], [d, n]]\n \n def encrypt(self, number, publickey):\n cipher = pow(number, publickey[0], publickey[1])\n return cipher\n \n \n def decrypt(self, cipher, privatekey):\n number = pow(cipher, privatekey[0], privatekey[1])\n return number\n \n def createsignature(self, message, privatekey):\n signature = pow(message, privatekey[0], privatekey[1])\n return signature\n \n def checksignature(self, signature, publickey):\n message = pow(signature, publickey[0], publickey[1])\n return message\n","sub_path":"copy-rsa.py","file_name":"copy-rsa.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"139469115","text":"from typing import Sequence, Optional, Tuple\n\nimport zarr\nimport numpy as np\nfrom numpy.typing import ArrayLike\nfrom arbol.arbol import aprint, asection\n\nfrom dexp.datasets.base_dataset import BaseDataset\nfrom dexp.processing.backends.best_backend import BestBackend\nfrom dexp.processing.backends.backend import Backend\nfrom dexp.processing.filters.fft_convolve import fft_convolve\nfrom dexp.utils.misc import compute_num_workers\nfrom scipy import ndimage as ndi\n\n\nfrom joblib import Parallel, delayed\n\n\ndef _estimate_crop(array: ArrayLike) -> Sequence[Tuple[int]]:\n window_size = 31\n step = 4\n shape = array.shape\n with BestBackend():\n xp = Backend.get_xp_module()\n array = Backend.to_backend(array[::step,::step,::step], dtype=xp.float16)\n array = xp.clip(array - xp.mean(array), 0, None) # removing background noise\n kernel = xp.ones((window_size, window_size, window_size)) / (window_size ** 3)\n kernel = kernel.astype(xp.float16)\n array = fft_convolve(array, kernel, in_place=True)\n lower = xp.mean(array)\n aprint('Estimated lower threshold', lower)\n array = array > lower\n array, _ = ndi.label(Backend.to_numpy(array))\n slices = ndi.find_objects(array)\n \n largest_slice = None\n largest_size = 0\n for slicing in slices:\n size = np.prod(tuple((s.stop - s.start) for s in slicing))\n if size > largest_size:\n largest_slice = slicing\n largest_size = size\n\n if largest_slice is None:\n raise RuntimeError('Could not detect any objects')\n\n return tuple((s.start * step, min(s.stop * step, d)) # fixing possible mismatch due to step\n for s, d in zip(largest_slice, shape))\n\n\ndef compute_crop_slicing(array: zarr.Array, time_points: Sequence[int]) -> Sequence[slice]:\n # N x D x 2\n ranges = np.array(tuple(_estimate_crop(array[t]) for t in time_points))\n lower = np.min(ranges[..., 0], axis=0)\n upper = np.max(ranges[..., 1], axis=0)\n return tuple(slice(int(l), int(u)) for l, u in zip(lower, upper))\n\n\ndef dataset_crop(dataset: BaseDataset,\n dest_path: str,\n reference_channel: str,\n channels: Sequence[str],\n store: str = 'dir',\n chunks: Optional[Sequence[int]] = None,\n compression: str = 'zstd',\n compression_level: int = 3,\n overwrite: bool = False,\n workers: int = 1,\n check: bool = True,\n stop_at_exception: bool = True,\n ):\n\n # Create destination dataset:\n from dexp.datasets.zarr_dataset import ZDataset\n mode = 'w' + ('' if overwrite else '-')\n dest_dataset = ZDataset(dest_path, mode, store, parent=dataset)\n\n with asection(\"Estimating region of interest\"):\n slicing = compute_crop_slicing(dataset.get_array(reference_channel), [0, -1])\n aprint('Estimated slicing of', slicing)\n volume_shape = tuple(s.stop - s.start for s in slicing)\n translation = {\n k: s.start for k, s in zip(('tz', 'ty', 'tx'), slicing)\n }\n dest_dataset.append_metadata(translation)\n\n # Process each channel:\n for channel in dataset._selected_channels(channels):\n with asection(f\"Cropping channel {channel}:\"):\n array = dataset.get_array(channel)\n\n dtype = array.dtype\n dest_dataset.add_channel(name=channel,\n shape=(len(array),) + volume_shape,\n dtype=dtype,\n chunks=chunks,\n codec=compression,\n clevel=compression_level)\n\n def process(tp):\n try:\n aprint(f\"Processing time point: {tp} ...\")\n tp_array = array[tp][slicing]\n dest_dataset.write_stack(channel=channel,\n time_point=tp,\n stack_array=tp_array)\n except Exception as error:\n aprint(error)\n aprint(f\"Error occurred while copying time point {tp} !\")\n import traceback\n traceback.print_exc()\n if stop_at_exception:\n raise error\n\n if workers == 1:\n for i in range(len(array)):\n process(i)\n else:\n n_jobs = compute_num_workers(workers, len(array))\n\n parallel = Parallel(n_jobs=n_jobs)\n parallel(delayed(process)(i) for i in range(len(array)))\n\n # Dataset info:\n aprint(dest_dataset.info())\n\n # Check dataset integrity:\n if check:\n dest_dataset.check_integrity()\n\n # close destination dataset:\n dest_dataset.close()\n","sub_path":"dexp/datasets/operations/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"237593879","text":"from six.moves.urllib.request import urlopen, Request\nfrom six.moves.urllib.error import HTTPError, URLError\nfrom six.moves.urllib.parse import urlencode, urljoin\nimport socket\nimport time\nimport logging\nfrom datetime import timedelta\ntry:\n import io\nexcept ImportError:\n pass\nimport six\n\nfrom .error import (\n ServiceNotAvailable, ResultNotReady\n)\nfrom .backend.rucaptcha import RucaptchaBackend\nfrom .backend.twocaptcha import TwocaptchaBackend\nfrom .backend.antigate import AntigateBackend\nfrom .backend.browser import BrowserBackend\n\n\nBACKEND_ALIAS = {\n 'rucaptcha': RucaptchaBackend,\n 'twocaptcha': TwocaptchaBackend,\n 'antigate': AntigateBackend,\n 'browser': BrowserBackend,\n}\nlogger = logging.getLogger('decaptcher.service')\n\n\nclass Service(object):\n network_errors = (URLError, socket.error)\n network_config = {\n 'read_timeout': 5,\n }\n\n def __init__(self, backend, **kwargs):\n assert isinstance(self.network_errors, tuple)\n\n if isinstance(backend, str):\n backend_cls = BACKEND_ALIAS[backend]\n else:\n backend_csl = backend\n self.backend = backend_cls(**kwargs)\n\n def submit_task(self, data, options=None):\n req = self.backend.build_task_request(\n data, options=options\n )\n return self.backend.parse_task_response(\n self.process_network_request(\n req['url'], \n req['data'],\n timeout=self.network_config['read_timeout'],\n )\n )\n\n def check_result(self, data):#, options=None):\n req = self.backend.build_result_request(\n data#, options=options,\n )\n return self.backend.parse_result_response(\n self.process_network_request(\n req['url'], \n req['data'],\n timeout=self.network_config['read_timeout'],\n )\n )\n\n def process(\n self,\n data=None,\n submit_timeout=30,\n submit_retry_delay=5,\n check_initial_delay=10,\n check_timeout=120,\n check_retry_delay=5,\n network_retry_delay=1,\n verbose=False,\n task_options=None,\n #result_options=None,\n ):\n\n if six.PY2:\n is_file = isinstance(data, file)\n else:\n is_file = isinstance(data, io.IOBase)\n if is_file:\n data = data.read()\n start = time.time()\n retry_count = 0\n while True:\n retry_count += 1\n try:\n if retry_count > 1:\n retry_str = ', retry #%d' % retry_count\n else:\n retry_str = ''\n logger.debug('Submitting task%s', retry_str)\n task = self.submit_task(data, task_options)\n except ServiceNotAvailable:\n if time.time() > start + submit_timeout:\n raise\n else:\n time.sleep(submit_retry_delay)\n except self.network_errors:\n if time.time() > start + submit_timeout: \n raise\n else:\n time.sleep(network_retry_delay)\n else:\n break\n\n time.sleep(check_initial_delay)\n\n start = time.time()\n retry_count = 0\n while True:\n retry_count += 1\n try:\n if retry_count > 1:\n retry_str = ', retry #%d' % retry_count\n else:\n retry_str = ''\n logger.debug('Checking task%s', retry_str)\n result = self.check_result(\n task['task_id']#, result_options,\n )\n except (ServiceNotAvailable, ResultNotReady):\n if time.time() > start + check_timeout:\n raise\n else:\n time.sleep(check_retry_delay)\n except (URLError, socket.error):\n if time.time() > start + check_timeout:\n raise\n else:\n time.sleep(network_retry_delay)\n else:\n break\n\n if verbose:\n result['task_id'] = task['task_id']\n return result\n else:\n return result['result']\n\n def process_file(self, path, **kwargs):\n with open(path, 'rb') as inp:\n return self.process(inp.read(), **kwargs)\n\n def process_network_request(self, url, data, timeout):\n if data:\n for key in data.keys():\n if isinstance(data[key], six.text_type):\n data[key] = data[key].encode('utf-8')\n\n req_data = urlencode(data).encode('utf-8')\n else:\n req_data = None\n req = Request(url, req_data)\n try:\n response = urlopen(req, timeout=timeout)\n body = response.read()\n code = response.getcode()\n except HTTPError as ex:\n code = ex.code\n body = ex.fp.read()\n return {\n 'code': code,\n 'body': body,\n 'url': url,\n }\n","sub_path":"decaptcher/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"486733804","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom NonLinearOptimization import reduced_gradient_Wolfe\nfrom colgen import create_colors\n\n\ndef feasible_region_indicator_linear(x, A, b):\n result = np.array(np.ones_like(A[0, 0] * x[0]), dtype=bool)\n for i in range(A.shape[0]):\n sum = 0\n for j in range(A.shape[1]):\n sum += A[i, j] * x[j]\n result = np.logical_and(sum <= b[i], result)\n return np.array(result, dtype=float)\n\n\ndef feasible_region_indicator(x, g):\n result = np.array(np.ones_like(g[0](x)), dtype=bool)\n for i in range(len(g)):\n result = np.logical_and(g[i](x) <= 0, result)\n return np.array(result, dtype=float)\n\n\ndef remove_nearly_same_points(points, eps=1e-3):\n results = [points[0].copy()]\n for i in range(len(points) - 1):\n if np.linalg.norm(results[0] - points[i]) > eps:\n results.insert(0, points[i].copy())\n results.insert(0, points[len(points) - 1])\n return np.array(results[::-1])\n\n\ndef f(x):\n return (x[0] - 2) ** 4 + ((x[0] - 2) ** 2) * x[1] ** 2 + (x[1] + 1) ** 2\n\n\nif __name__ == '__main__':\n\n feasible_region_colors = ('lightgreen', 'blue', 'lightblue', 'magenta', 'cyan', 'indigo', 'orange')\n levels_colors = ('indigo', 'darkblue', 'blue', 'green', 'lightgreen', 'orange', 'red')\n color_index = np.random.randint(0, len(feasible_region_colors))\n colors = ('white', feasible_region_colors[color_index])\n point_seq_style, exact_solution_style, way_style = 'ko', 'ro', 'k-'\n x_min, x_max, y_min, y_max = -0.25, 5.25, -0.5, 5.0\n dot_num = 10000\n figsize = (15, 7.5)\n A = np.array([[-1, -1], [1, 4], [11, -4]])\n b = np.array([-4, 16, 44])\n x0, y0 = 3.0, 3.0\n exact_solution = np.array([3.0, 1.0])\n A_modified = np.array([[-1, -1, 1, 0, 0], [1, 4, 0, 1, 0], [11, -4, 0, 0, 1]])\n initial_additional_variables = np.linalg.solve(A_modified[:, 2:], b - np.dot(A_modified[:, :2], [x0, y0]))\n initial_approximation = np.concatenate(([x0, y0], initial_additional_variables))\n points_seq = reduced_gradient_Wolfe(f, initial_approximation, A_modified, target='min', iter_lim=100000,\n calc_epsilon=1e-4)\n # print(len(points))\n # for point in points:\n # print('%.4f, %.4f, %.4f, %.4f, %.4f' % (point[0], point[1], point[2], point[3], point[4]))\n points_seq = remove_nearly_same_points(points_seq)\n argmin = points_seq[len(points_seq) - 1, :2]\n print('%.16f' % np.linalg.norm(exact_solution - argmin))\n x, y = np.linspace(x_min, x_max, dot_num), np.linspace(y_min, y_max, dot_num)\n xx, yy = np.meshgrid(x, y)\n z = feasible_region_indicator_linear(np.array([xx, yy]), A, b)\n plt.figure(figsize=figsize)\n plt.grid(True, alpha=0.5)\n plt.contourf(x, y, z, 1, cmap=ListedColormap(colors), alpha=0.2)\n plt.contour(x, y, z, 1, cmap=ListedColormap(colors[::-1]))\n levels = np.concatenate(([f([5.0, 2.75])], [f([4.0, 3.0])], f([points_seq[:4, 0], points_seq[:4, 1]]),\n [f(exact_solution)]))[::-1]\n numerical_contour = plt.contour(x, y, f([xx, yy]), levels=levels, colors=levels_colors)\n plt.clabel(numerical_contour, inline=1, fontsize=10, inline_spacing=2.0)\n plt.plot(points_seq[:, 0], points_seq[:, 1], point_seq_style, label=u\"Наближення\")\n for i in range(points_seq.shape[0] - 1):\n plt.plot([points_seq[i][0], points_seq[i + 1][0]], [points_seq[i][1], points_seq[i + 1][1]], way_style)\n plt.plot(exact_solution[0], exact_solution[1], exact_solution_style, label=u\"Розв'язок\")\n plt.legend(loc=\"best\")\n plt.xlabel(r\"$x_1$\")\n plt.ylabel(r\"$x_2$\")\n plt.show()\n plt.close()\n","sub_path":"Numerical Optimization/DiplomaProject/reduced_gradient_of_Wolfe_test.py","file_name":"reduced_gradient_of_Wolfe_test.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"131356471","text":"# coding=utf-8\n# Copyright (c) DIRECT Contributors\n\nimport argparse\nimport logging\nimport os\nimport pathlib\nimport sys\nfrom collections import namedtuple\nfrom typing import Callable, Optional, Tuple, Union\n\nimport omegaconf\nimport torch\nfrom omegaconf import OmegaConf\nfrom torch.utils import collect_env\n\nimport direct.utils.logging\nfrom direct.utils.logging import setup\nfrom direct.config.defaults import DefaultConfig, InferenceConfig, TrainingConfig, ValidationConfig\nfrom direct.utils import communication, count_parameters, str_to_class\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_model_config_from_name(model_name):\n \"\"\"\n Load specific configuration module for\n\n Parameters\n ----------\n model_name : path to model relative to direct.nn\n\n Returns\n -------\n model configuration.\n \"\"\"\n module_path = f\"direct.nn.{model_name.split('.')[0].lower()}.config\"\n model_name += \"Config\"\n config_name = model_name.split(\".\")[-1]\n try:\n model_cfg = str_to_class(module_path, config_name)\n except (AttributeError, ModuleNotFoundError) as e:\n logger.error(f\"Path {module_path} for config_name {config_name} does not exist (err = {e}).\")\n sys.exit(-1)\n return model_cfg\n\n\ndef load_model_from_name(model_name):\n module_path = f\"direct.nn.{'.'.join([_.lower() for _ in model_name.split('.')[:-1]])}\"\n module_name = model_name.split(\".\")[-1]\n try:\n model = str_to_class(module_path, module_name)\n except (AttributeError, ModuleNotFoundError) as e:\n logger.error(f\"Path {module_path} for model_name {module_name} does not exist (err = {e}).\")\n sys.exit(-1)\n\n return model\n\n\ndef load_dataset_config(dataset_name):\n dataset_config = str_to_class(\"direct.data.datasets_config\", dataset_name + \"Config\")\n return dataset_config\n\n\ndef build_operators(cfg) -> Tuple[Callable, Callable]:\n # Get the operators\n forward_operator = str_to_class(\"direct.data.transforms\", cfg.forward_operator)\n backward_operator = str_to_class(\"direct.data.transforms\", cfg.backward_operator)\n return forward_operator, backward_operator\n\n\ndef setup_logging(machine_rank, output_directory, run_name, cfg_filename, cfg, debug):\n # Setup logging\n log_file = output_directory / f\"log_{machine_rank}_{communication.get_local_rank()}.txt\"\n\n setup(\n use_stdout=communication.is_main_process() or debug,\n filename=log_file,\n log_level=(\"INFO\" if not debug else \"DEBUG\"),\n )\n logger.info(f\"Machine rank: {machine_rank}.\")\n logger.info(f\"Local rank: {communication.get_local_rank()}.\")\n logger.info(f\"Logging: {log_file}.\")\n logger.info(f\"Saving to: {output_directory}.\")\n logger.info(f\"Run name: {run_name}.\")\n logger.info(f\"Config file: {cfg_filename}.\")\n logger.info(f\"CUDA {torch.version.cuda} - cuDNN {torch.backends.cudnn.version()}.\")\n logger.info(f\"Environment information: {collect_env.get_pretty_env_info()}.\")\n logger.info(f\"DIRECT version: {direct.__version__}.\")\n git_hash = direct.utils.git_hash()\n logger.info(f\"Git hash: {git_hash if git_hash else 'N/A'}.\")\n logger.info(f\"Configuration: {OmegaConf.to_yaml(cfg)}.\")\n\n\ndef load_models_into_environment_config(cfg_from_file):\n # Load the configuration for the models\n cfg = {\"model\": cfg_from_file.model}\n\n if \"additional_models\" in cfg_from_file:\n cfg = {**cfg, **cfg_from_file.additional_models}\n # Parse config of additional models\n # TODO: Merge this with the normal model config loading.\n models_config = {}\n models = {}\n for curr_model_name in cfg:\n if \"model_name\" not in cfg[curr_model_name]:\n logger.error(f\"Model {curr_model_name} has no model_name.\")\n sys.exit(-1)\n\n curr_model_cfg = cfg[curr_model_name]\n model_name = curr_model_cfg.model_name\n models[curr_model_name] = load_model_from_name(model_name)\n\n models_config[curr_model_name] = OmegaConf.merge(load_model_config_from_name(model_name), curr_model_cfg)\n\n models_config = OmegaConf.merge(models_config)\n return models, models_config\n\n\ndef initialize_models_from_config(cfg, models, forward_operator, backward_operator, device):\n # Create the model\n logger.info(\"Building models.\")\n # TODO(jt): Model name is not used here.\n additional_models = {}\n _model = None\n for k, v in cfg.additional_models.items():\n # Remove model_name key\n curr_model = models[k]\n curr_model_cfg = {kk: vv for kk, vv in v.items() if kk != \"model_name\"}\n additional_models[k] = curr_model(**curr_model_cfg)\n\n model = models[\"model\"](\n forward_operator=forward_operator,\n backward_operator=backward_operator,\n **{k: v for (k, v) in cfg.model.items()},\n ).to(device)\n\n # Log total number of parameters\n count_parameters({\"model\": model, **additional_models})\n return model, additional_models\n\n\ndef setup_engine(\n cfg,\n device,\n model,\n additional_models: dict,\n forward_operator: Optional[Union[Callable, object]] = None,\n backward_operator: Optional[Union[Callable, object]] = None,\n mixed_precision: bool = False,\n):\n # Setup engine.\n # There is a bit of repetition here, but the warning provided is more descriptive\n # TODO(jt): Try to find a way to combine this with the setup above.\n model_name_short = cfg.model.model_name.split(\".\")[0]\n engine_name = cfg.model.model_name.split(\".\")[-1] + \"Engine\"\n\n try:\n engine_class = str_to_class(\n f\"direct.nn.{model_name_short.lower()}.{model_name_short.lower()}_engine\",\n engine_name,\n )\n except (AttributeError, ModuleNotFoundError) as e:\n logger.error(f\"Engine does not exist for {cfg.model.model_name} (err = {e}).\")\n sys.exit(-1)\n\n engine = engine_class( # noqa\n cfg,\n model,\n device=device,\n forward_operator=forward_operator,\n backward_operator=backward_operator,\n mixed_precision=mixed_precision,\n **additional_models,\n )\n return engine\n\n\ndef extract_names(cfg):\n cfg = cfg.copy()\n if isinstance(cfg, omegaconf.dictconfig.DictConfig):\n if \"name\" not in cfg:\n raise ValueError(\"`name` needs to be present in config.\")\n curr_name = cfg[\"name\"]\n\n elif isinstance(cfg, omegaconf.listconfig.ListConfig):\n return [extract_names(v) for v in cfg]\n\n else:\n raise ValueError(f\"Expected DictConfig or ListConfig. Got {type(cfg)}.\")\n\n return curr_name, cfg\n\n\ndef setup_common_environment(\n run_name,\n base_directory,\n cfg_filename,\n device,\n machine_rank,\n mixed_precision,\n debug=False,\n):\n\n # Shutup all loggers\n logger = logging.getLogger()\n\n experiment_dir = base_directory / run_name\n if communication.get_local_rank() == 0:\n # Want to prevent multiple workers from trying to write a directory\n # This is required in the logging below\n experiment_dir.mkdir(parents=True, exist_ok=True)\n communication.synchronize() # Ensure folders are in place.\n\n # Load configs from YAML file to check which model needs to be loaded.\n cfg_from_file = OmegaConf.load(cfg_filename)\n\n # Load the default configs to ensure type safety\n cfg = OmegaConf.structured(DefaultConfig)\n\n models, models_config = load_models_into_environment_config(cfg_from_file)\n cfg.model = models_config.model\n del models_config[\"model\"]\n cfg.additional_models = models_config\n\n # Setup everything for training\n cfg.training = TrainingConfig\n cfg.validation = ValidationConfig\n cfg.inference = InferenceConfig\n\n cfg_from_file_new = cfg_from_file.copy()\n for key in cfg_from_file:\n # TODO: This does not really do a full validation.\n # BODY: This will be handeled once Hydra is implemented.\n if key in [\"models\", \"additional_models\"]: # Still handled separately\n continue\n\n if key in [\"training\", \"validation\", \"inference\"]:\n if not cfg_from_file[key]:\n logger.info(f\"key {key} missing in config.\")\n continue\n\n if key in [\"training\", \"validation\"]:\n dataset_cfg_from_file = extract_names(cfg_from_file[key].datasets)\n for idx, (dataset_name, dataset_config) in enumerate(dataset_cfg_from_file):\n cfg_from_file_new[key].datasets[idx] = dataset_config\n cfg[key].datasets.append(load_dataset_config(dataset_name)) # pylint: disable = E1136\n else:\n dataset_name, dataset_config = extract_names(cfg_from_file[key].dataset)\n cfg_from_file_new[key].dataset = dataset_config\n cfg[key].dataset = load_dataset_config(dataset_name) # pylint: disable = E1136\n\n cfg[key] = OmegaConf.merge(cfg[key], cfg_from_file_new[key]) # pylint: disable = E1136, E1137\n # sys.exit()\n # Make configuration read only.\n # TODO(jt): Does not work when indexing config lists.\n # OmegaConf.set_readonly(cfg, True)\n setup_logging(machine_rank, experiment_dir, run_name, cfg_filename, cfg, debug)\n forward_operator, backward_operator = build_operators(cfg.physics)\n\n model, additional_models = initialize_models_from_config(cfg, models, forward_operator, backward_operator, device)\n\n engine = setup_engine(\n cfg,\n device,\n model,\n additional_models,\n forward_operator=forward_operator,\n backward_operator=backward_operator,\n mixed_precision=mixed_precision,\n )\n\n environment = namedtuple(\n \"environment\",\n [\"cfg\", \"experiment_dir\", \"engine\"],\n )\n return environment(cfg, experiment_dir, engine)\n\n\ndef setup_training_environment(\n run_name,\n base_directory,\n cfg_filename,\n device,\n machine_rank,\n mixed_precision,\n debug=False,\n):\n\n env = setup_common_environment(\n run_name,\n base_directory,\n cfg_filename,\n device,\n machine_rank,\n mixed_precision,\n debug=debug,\n )\n # Write config file to experiment directory.\n config_file_in_project_folder = env.experiment_dir / \"config.yaml\"\n logger.info(f\"Writing configuration file to: {config_file_in_project_folder}.\")\n if communication.is_main_process():\n with open(config_file_in_project_folder, \"w\") as f:\n f.write(OmegaConf.to_yaml(env.cfg))\n communication.synchronize()\n\n return env\n\n\ndef setup_testing_environment(\n run_name,\n base_directory,\n device,\n machine_rank,\n mixed_precision,\n debug=False,\n):\n\n cfg_filename = base_directory / run_name / \"config.yaml\"\n\n if not cfg_filename.exists():\n raise OSError(f\"Config file {cfg_filename} does not exist.\")\n\n env = setup_common_environment(\n run_name,\n base_directory,\n cfg_filename,\n device,\n machine_rank,\n mixed_precision,\n debug=debug,\n )\n\n out_env = namedtuple(\n \"environment\",\n [\"cfg\", \"engine\"],\n )\n return out_env(env.cfg, env.engine)\n\n\ndef setup_inference_environment(\n run_name,\n base_directory,\n device,\n machine_rank,\n mixed_precision,\n debug=False,\n):\n\n env = setup_testing_environment(run_name, base_directory, device, machine_rank, mixed_precision, debug=debug)\n\n out_env = namedtuple(\n \"environment\",\n [\"cfg\", \"engine\"],\n )\n return out_env(env.cfg, env.engine)\n\n\nclass Args(argparse.ArgumentParser):\n \"\"\"\n Defines global default arguments.\n \"\"\"\n\n def __init__(self, epilog=None, **overrides):\n \"\"\"\n Args:\n **overrides (dict, optional): Keyword arguments used to override default argument values\n \"\"\"\n super().__init__(epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)\n\n self.add_argument(\n \"--device\",\n type=str,\n default=\"cuda\",\n help='Which device to train on. Set to \"cuda\" to use the GPU.',\n )\n self.add_argument(\"--seed\", default=42, type=int, help=\"Seed for random number generators.\")\n self.add_argument(\"--num-workers\", type=int, default=4, help=\"Number of workers.\")\n self.add_argument(\"--mixed-precision\", help=\"Use mixed precision.\", action=\"store_true\")\n self.add_argument(\"--debug\", help=\"Set debug mode true.\", action=\"store_true\")\n\n self.add_argument(\"--num-gpus\", type=int, default=1, help=\"# GPUs per machine.\")\n self.add_argument(\"--num-machines\", type=int, default=1, help=\"# of machines.\")\n self.add_argument(\n \"--machine-rank\",\n type=int,\n default=0,\n help=\"the rank of this machine (unique per machine).\",\n )\n self.add_argument(\n \"--initialization-images\",\n help=\"Path to images which will be used as initialization to the model. \"\n \"The filenames assumed to be the same as the images themselves. If these are h5 files, \"\n \"the key to read in the h5 has to be set in the configuration in the dataset.input_image_key.\",\n required=False,\n nargs=\"+\",\n type=pathlib.Path,\n )\n self.add_argument(\n \"--initialization-kspace\",\n help=\"Path to kspace which will be used as initialization to the model. \"\n \"The filenames assumed to be the same as the images themselves. If these are h5 files, \"\n \"the key to read in the h5 has to be set in the configuration in the dataset.input_image_key.\",\n required=False,\n nargs=\"+\",\n type=pathlib.Path,\n )\n self.add_argument(\n \"--noise\",\n help=\"Path to json file mapping relative filename to noise estimates. \"\n \"Path to training and validation data\",\n required=False,\n nargs=\"+\",\n type=pathlib.Path,\n )\n\n # Taken from: https://github.com/facebookresearch/detectron2/blob/bd2ea475b693a88c063e05865d13954d50242857/detectron2/engine/defaults.py#L49 # noqa\n # PyTorch still may leave orphan processes in multi-gpu training.\n # Therefore we use a deterministic way to obtain port,\n # so that users are aware of orphan processes by seeing the port occupied.\n port = 2 ** 15 + 2 ** 14 + hash(os.getuid()) % 2 ** 14\n self.add_argument(\n \"--dist-url\",\n default=f\"tcp://127.0.0.1:{port}\",\n help=\"initialization URL for pytorch distributed backend. See \"\n \"https://pytorch.org/docs/stable/distributed.html for details.\",\n )\n\n self.set_defaults(**overrides)\n","sub_path":"direct/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":14691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"304567095","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport cv2\nfrom keras.models import load_model\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nimport random\nimport time\nimport numpy as np\n\n#Initializing the negative weights\nangry_weight=1\nfear_weight=1\ndisgust_weight=1\nsad_weight=1\nalpha = 5\n#Initializing the positive weights\nhappy_weight=-1\nsurprise_weight=-1\n#neutral_weight=random.uniform(-0.5, 0.5)\n\n#Initializing the parameters\nCapture_per_minute=250\nThreshold = 1000\nt_old=Threshold\nt_new = 0\nwindows = 0\npre_windows = [] \ntotal_stress=0\niterations=1\nflag = 0\n\n#Loading the pretrained weights\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.1\nset_session(tf.Session(config=config))\n\n''' Keras took all GPU memory so to limit GPU usage, I have add those lines'''\nfaceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\n\nvideo_capture = cv2.VideoCapture(0)\nmodel = load_model('keras_model/model_5-49-0.62.hdf5')\nmodel.get_config()\n\ntarget = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']\nexpressions=['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise']\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\ndata=[]\nt_max=[]\ntotal_count=0;\nterms_count={}\nterms_count['angry'] = 0\nterms_count['sad'] = 0\nterms_count['disgust'] = 0\nterms_count['fear'] = 0\nterms_count['happy'] = 0\nterms_count['surprise'] = 0\nprevious_threshold = []\n\npartially_negative=['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise','disgust','sad']\npartially_positive=['happy', 'sad', 'surprise','happy','surprise']\n\niter2=[]\nstress=[]\n\ni=0\ndata=[]\ntot_str=0\niter2.append(i)\nstress.append(tot_str)\nu=0\nstart_time=time.time()\nt_store =Threshold\npartially_negative=['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise','disgust','sad']\npartially_positive=['happy', 'sad', 'surprise','happy','surprise']\n\niter2=[]\nstress=[]\n \nfont = cv2.FONT_HERSHEY_SIMPLEX\n#Initialize alpha\n#Do plotting\n#Find proper data for validation\n\n\ndef f(windows, pre_windows, alpha):\n t_max = int(sum(pre_windows)/len(pre_windows))\n t_ite = windows\n t = alpha**(-1*(t_ite/t_max))\n return t\n \nstart_time=time.time() \nstress1 = 0\nwhile(1):\n ret, frame = video_capture.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1)\n\n # Draw a rectangle around the faces\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2, 5)\n face_crop = frame[y:y + h, x:x + w]\n face_crop = cv2.resize(face_crop, (48, 48))\n face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)\n face_crop = face_crop.astype('float32') / 255\n face_crop = np.asarray(face_crop)\n face_crop = face_crop.reshape(1, 1, face_crop.shape[0], face_crop.shape[1])\n result = target[np.argmax(model.predict(face_crop))]\n data.append(result) \n if(result == 'happy' or result =='surprise'):\n result = \"Positive_Emotion\"\n elif(result == 'neutral'):\n result = \"Neutral\"\n else:\n result = \"Negative_Emotion\"\n cv2.putText(frame, result, (x, y), font, 1, (200, 0, 0), 3, cv2.LINE_AA)\n if(len(data)>Capture_per_minute):\n stress1+=(data.count('angry')*(angry_weight)+\n data.count('fear')*(fear_weight)+\n data.count('sad')*(sad_weight)\n +data.count('disgust')*(disgust_weight)+\n data.count('happy')*(happy_weight)+\n data.count('surprise')*(surprise_weight))\n tot_str = tot_str+stress1\n data=[]\n print('my tot_str variable',tot_str)\n i=i+1\n #time.sleep(60)\n if(flag ==0):\n if(tot_str<=0):\n tot_str=0\n windows = 0\n start_time = time.time()\n stress.append(tot_str)\n iter2.append(i)\n if(tot_str>0 and tot_strThreshold): \n end_time = time.time()\n t_new = end_time- start_time\n print(\"Have a change\")\n tot_str=0\n flag = 1\n previous_threshold.append(Threshold)\n pre_windows.append(windows+1)\n Threshold = t_old+ (t_new - t_old)*f(0, pre_windows,alpha)\n t_store = Threshold\n t_old = sum(previous_threshold)/len(previous_threshold)\n start_time = time.time()\n windows = 0\n previous_threshold = [Threshold]\n else:\n if(tot_str<=0):\n tot_str = 0\n windows = 0\n start_time = time.time()\n stress.append(tot_str)\n iter2.append(i)\n previous_threshold = [t_store]\n if(tot_str>0 and tot_strThreshold): \n end_time = time.time()\n t_new = end_time- start_time\n print(\"Have a change\")\n tot_str=0 \n pre_windows.append(windows+1)\n Threshold = t_old+ (t_new - t_old)*f(0, pre_windows, alpha)\n t_old = sum(previous_threshold)/len(previous_threshold)\n t_store = Threshold\n windows = 0\n previous_threshold = [Threshold]\n print(i, windows, tot_str, Threshold)\n stress1 = 0\n #time.sleep(5)\n cv2.imshow('Video', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()","sub_path":"Dynamic_Demo.py","file_name":"Dynamic_Demo.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"471072579","text":"from train_nn import forward_nn\nimport numpy as np\nimport pickle\n\nwith open('weight_file.dump', 'rb') as f:\n network = pickle.load(f)\nwith open('id_file.dump', 'rb') as g:\n ids = pickle.load(g)\n\nfor line in open('../../data/titles-en-test.word', 'r'):\n features = np.zeros(len(ids))\n for word in line.strip('\\n').split():\n if word in ids:\n features[ids[word]] += 1\n polarity = 1 if forward_nn(network, features)[2][0] > 0 else -1\n print(str(polarity) + '\\t' + line.strip('\\n'))\n","sub_path":"Yamagishi/tutorial07/test_nn.py","file_name":"test_nn.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"284512698","text":"\nimport time\nimport bisect\nimport copy\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nimport scipy\nimport scipy.optimize\nimport scipy as sp\nimport os, math\nimport pickle\nimport matplotlib.pyplot as plt\nfrom joblib import Parallel, delayed\nfrom pathos.multiprocessing import ProcessingPool as Pool\n\nfrom lib.dynamics import DiseaseModel\nfrom lib.priorityqueue import PriorityQueue\nfrom lib.measures import (MeasureList, BetaMultiplierMeasure,\n SocialDistancingForAllMeasure, BetaMultiplierMeasureByType,\n SocialDistancingForPositiveMeasure, SocialDistancingByAgeMeasure, SocialDistancingForSmartTracing, ComplianceForAllMeasure)\n\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\nfrom lib.mobilitysim import MobilitySimulator\n\n# Comment this in if you want to do map plots\nSTORE_MOB = False\n\npp_legal_states = ['susc', 'expo', 'ipre', 'isym', 'iasy', 'posi', 'nega', 'resi', 'dead', 'hosp']\n\n\nclass ParallelSummary(object):\n \"\"\"\n Summary class of several restarts\n \"\"\"\n\n def __init__(self, max_time, repeats, n_people, n_sites, site_loc, home_loc):\n\n self.max_time = max_time\n self.random_repeats = repeats\n self.n_people = n_people\n self.n_sites = n_sites\n self.site_loc = site_loc\n self.home_loc = home_loc\n \n self.state = {\n 'susc': np.ones((repeats, n_people), dtype='bool'),\n 'expo': np.zeros((repeats, n_people), dtype='bool'),\n 'ipre': np.zeros((repeats, n_people), dtype='bool'),\n 'isym': np.zeros((repeats, n_people), dtype='bool'),\n 'iasy': np.zeros((repeats, n_people), dtype='bool'),\n 'posi': np.zeros((repeats, n_people), dtype='bool'),\n 'nega': np.zeros((repeats, n_people), dtype='bool'),\n 'resi': np.zeros((repeats, n_people), dtype='bool'),\n 'dead': np.zeros((repeats, n_people), dtype='bool'),\n 'hosp': np.zeros((repeats, n_people), dtype='bool'),\n }\n\n self.state_started_at = {\n 'susc': - np.inf * np.ones((repeats, n_people), dtype='float'),\n 'expo': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'ipre': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'isym': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'iasy': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'posi': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'nega': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'resi': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'dead': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'hosp': np.inf * np.ones((repeats, n_people), dtype='float'),\n }\n self.state_ended_at = {\n 'susc': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'expo': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'ipre': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'isym': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'iasy': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'posi': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'nega': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'resi': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'dead': np.inf * np.ones((repeats, n_people), dtype='float'),\n 'hosp': np.inf * np.ones((repeats, n_people), dtype='float'),\n }\n \n self.measure_list = []\n self.mob = []\n \n self.people_age = np.zeros((repeats, n_people), dtype='int')\n\n self.children_count_iasy = np.zeros((repeats, n_people), dtype='int')\n self.children_count_ipre = np.zeros((repeats, n_people), dtype='int')\n self.children_count_isym = np.zeros((repeats, n_people), dtype='int')\n\n\ndef create_ParallelSummary_from_DiseaseModel(sim):\n\n summary = ParallelSummary(sim.max_time, 1, sim.n_people, sim.mob.n_sites, sim.mob.site_loc, sim.mob.home_loc)\n\n for code in pp_legal_states:\n summary.state[code][0, :] = sim.state[code]\n summary.state_started_at[code][0, :] = sim.state_started_at[code]\n summary.state_ended_at[code][0, :] = sim.state_ended_at[code]\n\n summary.measure_list.append(sim.measure_list)\n if STORE_MOB:\n summary.mob.append(sim.mob)\n \n summary.people_age[0, :] = sim.mob.people_age\n \n summary.children_count_iasy[0, :] = sim.children_count_iasy\n summary.children_count_ipre[0, :] = sim.children_count_ipre\n summary.children_count_isym[0, :] = sim.children_count_isym\n return summary\n\n\ndef pp_launch(r, kwargs, distributions, params, initial_counts, testing_params, measure_list, max_time):\n\n mob = MobilitySimulator(**kwargs)\n mob.simulate(max_time=max_time)\n\n sim = DiseaseModel(mob, distributions)\n\n sim.launch_epidemic(\n params=params,\n initial_counts=initial_counts,\n testing_params=testing_params,\n measure_list=measure_list,\n verbose=False)\n\n result = {\n 'state' : sim.state,\n 'state_started_at': sim.state_started_at,\n 'state_ended_at': sim.state_ended_at,\n 'measure_list' : copy.deepcopy(sim.measure_list),\n 'people_age' : sim.mob.people_age,\n 'children_count_iasy': sim.children_count_iasy,\n 'children_count_ipre': sim.children_count_ipre,\n 'children_count_isym': sim.children_count_isym,\n }\n if STORE_MOB:\n result['mob'] = sim.mob\n\n return result\n\n\ndef launch_parallel_simulations(mob_settings, distributions, random_repeats, cpu_count, params, \n initial_seeds, testing_params, measure_list, max_time, num_people, num_sites, site_loc, home_loc, \n verbose=True, synthetic=False):\n \n\n with open(mob_settings, 'rb') as fp:\n kwargs = pickle.load(fp)\n\n mob_setting_list = [copy.deepcopy(kwargs) for _ in range(random_repeats)]\n distributions_list = [copy.deepcopy(distributions) for _ in range(random_repeats)]\n measure_list_list = [copy.deepcopy(measure_list) for _ in range(random_repeats)]\n params_list = [copy.deepcopy(params) for _ in range(random_repeats)]\n initial_seeds_list = [copy.deepcopy(initial_seeds) for _ in range(random_repeats)]\n testing_params_list = [copy.deepcopy(testing_params) for _ in range(random_repeats)]\n max_time_list = [copy.deepcopy(max_time) for _ in range(random_repeats)]\n repeat_ids = list(range(random_repeats))\n\n if verbose:\n print('Launching simulations...')\n\n with ProcessPoolExecutor(cpu_count) as ex:\n res = ex.map(pp_launch, repeat_ids, mob_setting_list, distributions_list, params_list,\n initial_seeds_list, testing_params_list, measure_list_list, max_time_list)\n \n # collect all result (the fact that mob is still available here is due to the for loop)\n summary = ParallelSummary(max_time, random_repeats, num_people, num_sites, site_loc, home_loc)\n \n for r, result in enumerate(res):\n\n for code in pp_legal_states:\n summary.state[code][r, :] = result['state'][code]\n summary.state_started_at[code][r, :] = result['state_started_at'][code]\n summary.state_ended_at[code][r, :] = result['state_ended_at'][code]\n \n summary.measure_list.append(result['measure_list'])\n\n if STORE_MOB:\n summary.mob.append(result['mob']) \n\n summary.people_age[r, :] = result['people_age']\n \n summary.children_count_iasy[r, :] = result['children_count_iasy']\n summary.children_count_ipre[r, :] = result['children_count_ipre']\n summary.children_count_isym[r, :] = result['children_count_isym']\n\n return summary\n","sub_path":"sim/lib/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":7834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"144234541","text":"from QtCore import *\nfrom QtGui import *\n\nclass Player(QObject):\n\n COLORS = [QColor(Qt.gray).darker(),\n QColor(80, 130, 250), QColor(255, 255, 80),\n QColor(100, 255, 50), QColor(200, 80, 250),\n QColor(250, 70, 70), QColor(255, 150, 20)]\n\n def __init__(self, id, name):\n super(Player, self).__init__()\n self.id = id\n self.name = name\n self.host = None\n self.port = None\n self.color = None\n self.countries = 0\n self.weapon = 0\n self.readyFlag = False\n\n ready = Signal(bool)\n\n def setColor(self, color):\n self.color = color\n\n @Slot()\n def _setReady(self, ready = True):\n self.readyFlag = ready\n self.ready.emit(ready)\n\n","sub_path":"core/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"556863971","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)\n#\n# (1) Kamaelia Contributors are listed in the AUTHORS file and at\n# http://www.kamaelia.org/AUTHORS - please extend this file,\n# not this notice.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# -------------------------------------------------------------------------\n\n\"\"\"\\\n===========================\nGeneric 3D Topology Viewer\n===========================\n\nA 3D version of TopologyViewer plus hierarchy topology support, pygame based \ndisplay of graph topologies. Rendering and physics laws can be customised \nfor specific applications.\n\n\n\nExample Usage\n-------------\nA simple console driven topology viewer::\n\n Pipeline( ConsoleReader(),\n lines_to_tokenlists(),\n TopologyViewer3D(),\n ).run()\n\nThen at runtime try typing these commands to change the topology in real time::\n\n >>> DEL ALL\n >>> ADD NODE 1 \"1st node\" (0,0,-10) teapot\n >>> ADD NODE 2 \"2nd node\" randompos sphere\n >>> ADD NODE 3 \"3rd node\" randompos -\n >>> ADD NODE 1:1 \"1st child node of the 1st node\" \" ( 0 , 0 , -10 ) \" -\n >>> ADD NODE 1:2 \"2nd child node of the 1st node\" randompos -\n >>> ADD LINK 1 2\n >>> ADD LINK 3 2\n >>> DEL LINK 1 2\n >>> ADD LINK 1:1 1:2\n >>> DEL NODE 1\n\n\n\nUser Interface\n--------------\n\nTopologyViewer3D manifests as a pygame OpenGL display surface. As it is sent\ntopology information, nodes and links between them will appear.\n\nYou can click a node with the mouse to select it. Depending on the application,\nthis may display additional data or, if integrated into another app, have some\nother effect.\n\nClick and drag with the left mouse button to move nodes around. Note that a\nsimple physics model or repulsion and attraction forces is always active. This\ncauses nodes to move around to help make it visually clearer, however you may\nstill need to drag nodes about to tidy it up.\n\nFor hierarchy topology, double-click a particle (or select one then press return key)\nto show its child topology; right-click (or press backspace key) to show last level's \ntopology.\n\n\n\nOperations supported:\n\n * esc --- quit\n \n * a --- viewer position moves left\n * d --- viewer position moves right\n * w --- viewer position moves up\n * s --- viewer position moves down\n * pgup --- viewer position moves forward (zoom in)\n * pgdn --- viewer position moves backward (zoom out)\n \n * left --- rotate selected particles to left around y axis (all particles if none of them is selected)\n * right --- rotate selected particles to right around y axis (all particles if none of them is selected)\n * up --- rotate selected particles to up around x axis (all particles if none of them is selected)\n * down --- rotate selected particles to down around x axis (all particles if none of them is selected)\n * < --- rotate selected particles anticlock-wise around z axis (all particles if none of them is selected)\n * > --- rotate selected particles clock-wise around z axis (all particles if none of them is selected)\n * return --- show next level's topology of the selected particle when only one particle is selected\n * backspace --- show last level's topology\n \n * Mouse click --- click particle to select one, click empty area to deselect all\n * Mouse drag --- move particles\n * Mouse double-click --- show next level's topology of the particle clicked\n * Mouse right-click --- show last level's topology\n \n * shift --- multi Select Mode; shift+click for multiple selection/ deselection\n * ctrl --- rotation Mode; when ctrl is pressed, mouse motion will rotate the selected particle \n (all particles if none of them is selected)\n\n\n\nHow does it work?\n-----------------\n\nTopologyViewer3D is a Kamaeila component which renders Topology on a pygame OpenGL display surface.\n\nA 3D topology (graph) of nodes and links between them is rendered to the surface.\n\nYou can specify an initial topology by providing a list of instantiated\nparticles and another list of pairs of those particles to show how they are \nlinked.\n\nTopologyViewer3D responds to commands arriving at its \"inbox\" inbox\ninstructing it on how to change the topology. A command is a list/tuple.\n\nCommands recognised are:\n\n [ \"ADD\", \"NODE\", , , , ]\n Add a node, using:\n \n - id -- a unique ID used to refer to the particle in other topology commands. Cannot be None.\n For hierarchy topology, the id is joined by its parent id with \":\" to represent the \n hierarchy structure.\n E.g., suppose the topology has 3 levels. The id of a particle in the 1st level is 1Node;\n it has a child particle whose id is 2Node; 2Node also has a child particle whose id is 3Node;\n then their ids are represented as\n 1Node\n 1Node:2Node\n 1Node:2Node:3Node \n - name -- string name label for the particle\n - posSpec -- string describing initial (x,y,z) (see _generateXY); spaces are allowed\n within the tuple, but quotation is needed in this case.\n E.g., \" ( 0 , 0 , -10 ) \"\n - particleType -- particle type (default provided is \"-\", unless custom types are provided - see below)\n currently supported: \"-\" same as cuboid, cuboid, sphere and teapot\n Note: it would be much slower than cuboid if either sphere or teapot is used.\n \n [ \"DEL\", \"NODE\", ]\n Remove a node (also removes all links to and from it)\n \n [ \"ADD\", \"LINK\", , ]\n Add a link, directional from fromID to toID\n \n [ \"DEL\", \"LINK\", , ]\n Remove a link, directional from fromID to toID\n \n [ \"DEL\", \"ALL\" ]\n Clears all nodes and links\n\n [ \"GET\", \"ALL\" ]\n Outputs the current topology as a list of commands, just like\n those used to build it. The list begins with a 'DEL ALL'.\n\n [ \"UPDATE_NAME\", \"NODE\", , ]\n If the node does not already exist, this does NOT cause it to be created.\n\n [ \"GET_NAME\", \"NODE\", ]\n Returns UPDATE_NAME NODE message for the specified node\n\nCommands are processed immediately, in the order in which they arrive. You\ntherefore cannot refer to a node or linkage that has not yet been created, or\nthat has already been destroyed.\n\nIf a stream of commands arrives in quick succession, rendering and physics will\nbe temporarily stopped, so commands can be processed more quickly. This is\nnecessary because when there is a large number of particles, physics and\nrendering starts to take a long time, and will therefore bottleneck the\nhandling of commands.\n\nHowever, there is a 1 second timeout, so at least one update of the visual\noutput is guaranteed per second.\n\nTopologyViewer sends any output to its \"outbox\" outbox in the same\nlist/tuple format as used for commands sent to its \"inbox\" inbox. The following\nmay be output:\n\n [ \"SELECT\", \"NODE\", ]\n Notification that a given node has been selected.\n \n [ \"SELECT\", \"NODE\", None ]\n Notificaion that *no node* is now selected. \n \n [ \"TOPOLOGY\", ]\n List of commands needed to build the topology, as it currently stands.\n The list will start with a (\"DEL\",\"ALL\") command.\n This is sent in response to receiving a (\"GET\",\"ALL\") command.\n\nError and tip information is printed out directly when applied.\n\nFor hierarchy topology, the id of particles should be joined by its parent id with \":\" \nto represent the hierarchy structure. See \"ADD NODE\" command above for more information.\n\n\n\nTermination\n-----------\n\nIf a shutdownMicroprocess message is received on this component's \"control\"\ninbox, it will pass it on out of its \"signal\" outbox and immediately\nterminate.\n\nNOTE: Termination is currently rather cludgy - it raises an exception which\nwill cause the rest of a kamaelia system to halt. Do not rely on this behaviour\nas it will be changed to provide cleaner termination at some point.\n\n\n\nCustomising the 3D topology viewer\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nYou can customise:\n\n- the 'types' of particles (nodes)\n- visual appearance of particles (nodes) and the links between them;\n- the physics laws used to assist with layout\n\nUse the particleTypes argument of the initialiser to specify classes that\nshould be instantiated to render each type of particle (nodes). particleTypes \nshould be a dictionary mapping names for particle types to the respective \nclasses, for example::\n\n { \"major\" : BigParticle, \"minor\" : SmallParticle }\n\nSee below for information on how to write your own particle classes.\n\nLayout of the nodes on the surface is assisted by a physics model, provided\nby an instance of the Kamaelia.Support.Particles.ParticleSystem class. Freeze them\nif you want to make some particles not subject to the law (particle.freeze()).\n\nCustomise the laws used for each particle type by providing a\nKamaelia.Phyics.Simple.MultipleLaws object at initialisation.\n\n\n\nWriting your own particle class\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nshould inherit from Kamaelia.PhysicsGraph3D.Particles3D.Particle3D \nand implement the following method (for rendering purposes):\n\n draw()\n draw OpenGL particles and links in this method.\n\n\n\nTODO: Reduce CPU usage, improve responsive speed\n\n\n\nReferences: 1. Kamaelia.Visualisation.PhysicsGraph.TopologyViewer\n2. Kamaelia.UI.OpenGL.OpenGLComponent\n3. Kamaelia.UI.OpenGL.MatchedTranslationInteractor\n\"\"\"\n\nimport math, random\nimport time\nimport re\nimport sys\nimport pygame\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\n\nimport Axon\nimport Kamaelia.Support.Particles\n\nfrom Kamaelia.UI.OpenGL.OpenGLDisplay import OpenGLDisplay\nfrom Kamaelia.UI.OpenGL.Vector import Vector\nfrom Kamaelia.UI.OpenGL.Intersect import Intersect\n\n_cat = Axon.CoordinatingAssistantTracker\n\nfrom Kamaelia.Visualisation.PhysicsGraph3D.Particles3D import CuboidParticle3D, SphereParticle3D, TeapotParticle3D\nfrom Kamaelia.Support.Particles.ParticleSystem import ParticleSystem\n\n \nclass TopologyViewer3D(Axon.Component.component):\n \"\"\"\\\n TopologyViewer3D(...) -> new TopologyViewer3D component.\n \n A component that takes incoming topology (change) data and displays it live\n using pygame OpenGL. A simple physics model assists with visual layout. Particle\n types, appearance and physics interactions can be customised.\n \n Keyword arguments (in order):\n \n - screensize -- (width,height) of the display area (default = (800,600))\n - fullscreen -- True to start up in fullscreen mode (default = False)\n - caption -- Caption for the pygame window (default = \"3D Topology Viewer\")\n - particleTypes -- dict(\"type\" -> klass) mapping types of particle to classes used to render them (default = {\"-\":CuboidParticle3D})\n - initialTopology -- (nodes,bonds) where bonds=list((src,dst)) starting state for the topology (default=([],[]))\n - laws -- Physics laws to apply between particles (default = SimpleLaws(bondlength=2))\n - simCyclesPerRedraw -- number of physics sim cycles to run between each redraw (default=1)\n - border -- Minimum distance from edge of display area that new particles appear (default=0)\n \"\"\"\n \n Inboxes = { \"inbox\" : \"Topology (change) data describing an Axon system\",\n \"control\" : \"Shutdown signalling\",\n \"callback\" : \"for the response after a displayrequest\",\n \"events\" : \"Place where we recieve events from the outside world\",\n }\n \n Outboxes = { \"signal\" : \"Control signalling\",\n \"outbox\" : \"Notification and topology output\",\n \"display_signal\" : \"Requests to Pygame Display service\",\n }\n \n \n def __init__(self, screensize = (800,600),\n fullscreen = False, \n caption = \"3D Topology Viewer\", \n particleTypes = None,\n initialTopology = None,\n laws = None,\n simCyclesPerRedraw = 1,\n border = 0):\n \"\"\"x.__init__(...) initializes x; see x.__class__.__doc__ for signature\"\"\"\n \n super(TopologyViewer3D, self).__init__()\n \n glutInit(sys.argv)\n \n tracker = _cat.coordinatingassistanttracker.getcat()\n try:\n self.display = tracker.retrieveService(\"ogl_display\")[0]\n except KeyError:\n self.display = OpenGLDisplay(width=screensize[0], height=screensize[1],fullscreen=fullscreen,\n title=caption)\n self.display.activate()\n OpenGLDisplay.setDisplayService(self.display, tracker)\n self.display = OpenGLDisplay.getDisplayService()[0] \n self.link((self,\"display_signal\"), (self.display,\"notify\"))\n self.link((self.display,\"signal\"), (self,\"control\"))\n \n self.border = border\n \n if particleTypes == None:\n self.particleTypes = {\"-\":CuboidParticle3D, \"cuboid\":CuboidParticle3D, \"sphere\":SphereParticle3D,\n \"teapot\":TeapotParticle3D}\n else:\n self.particleTypes = particleTypes\n \n if initialTopology == None:\n initialTopology = ([],[])\n self.initialNodes = list(initialTopology[0])\n self.initialBonds = list(initialTopology[1])\n \n self.hitParticles = []\n self.multiSelectMode = False\n self.selectedParticles = []\n self.grabbed = False\n self.rotationMode = False \n \n if laws==None:\n self.laws = Kamaelia.Support.Particles.SimpleLaws(bondLength=2)\n else:\n self.laws = laws\n \n self.physics = ParticleSystem(self.laws, [], 0)\n self.biggestRadius = 0\n \n # Do interaction\n self.simCyclesPerRedraw = simCyclesPerRedraw\n self.lastIdleTime = time.time()\n \n # Tell if new node is added; if true, new id needs adding to OpenGLDisplay list\n self.isNewNode = False\n \n # For hierarchy structure\n self.maxLevel = 0\n self.currentLevel = 0\n self.previousParentParticleID = self.currentParentParticleID = ''\n self.viewerOldPos = Vector()\n self.levelViewerPos = {}\n # The Physics particle system of current display level for display\n self.currentDisplayedPhysics = ParticleSystem(self.laws, [], 0)\n \n # For double click\n self.lastClickPos = (0,0)\n self.lastClickTime = time.time()\n self.dClickRes = 0.3\n \n \n def initialiseComponent(self):\n \"\"\"Initialises.\"\"\"\n self.addListenEvents( [pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION, pygame.KEYDOWN, pygame.KEYUP ])\n # For key holding handling\n pygame.key.set_repeat(100,100)\n \n for node in self.initialNodes:\n self.addParticle(*node)\n\n for source,dest in self.initialBonds:\n self.makeBond(source, dest)\n \n \n def main(self):\n \"\"\"Main loop.\"\"\"\n # Make display request for event listening purpose\n self.size = Vector(0,0,0)\n disprequest = { \"OGL_DISPLAYREQUEST\" : True,\n \"objectid\" : id(self),\n \"callback\" : (self,\"callback\"),\n \"events\" : (self, \"events\"),\n \"size\": self.size\n }\n # send display request\n self.send(disprequest, \"display_signal\") \n # Wait for response on displayrequest and get identifier of the viewer\n while not self.dataReady(\"callback\"): yield 1\n self.identifier = self.recv(\"callback\")\n \n self.initialiseComponent()\n \n while True:\n # Process incoming messages\n if self.dataReady(\"inbox\"):\n message = self.recv(\"inbox\")\n self.doCommand(message)\n\n # Wait for response on displayrequest and get identifier of the particle\n if self.isNewNode:\n while not self.dataReady(\"callback\"): yield 1\n self.physics.particles[-1].identifier = self.recv(\"callback\")\n self.isNewNode = False\n else:\n self.lastIdleTime = 0\n \n yield 1 \n \n if self.lastIdleTime + 1.0 < time.time():\n #Freeze selected particles so that they are not subject to the physics law\n for particle in self.selectedParticles:\n particle.freeze()\n # Do interaction between particles\n self.currentDisplayedPhysics.run(self.simCyclesPerRedraw)\n # Unfreeze selected particles\n for particle in self.selectedParticles:\n particle.unFreeze()\n \n # Draw particles if new or updated\n for particle in self.currentDisplayedPhysics.particles:\n if particle.needRedraw:\n self.drawParticles(particle)\n \n self.handleEvents()\n \n # Perform transformation\n for particle in self.currentDisplayedPhysics.particles:\n transform_update = particle.applyTransforms()\n if transform_update is not None:\n self.send(transform_update, \"display_signal\")\n \n self.lastIdleTime = time.time()\n else:\n yield 1\n if self.dataReady(\"control\"):\n msg = self.recv(\"control\")\n if isinstance(msg, Axon.Ipc.shutdownMicroprocess):\n self.quit(msg)\n \n \n def quit(self,msg=Axon.Ipc.shutdownMicroprocess()):\n \"\"\"Cause termination.\"\"\"\n print ('Shut down...')\n self.send(msg, \"signal\")\n self.scheduler.stop()\n \n \n def draw(self):\n \"\"\"\\\n Dummy method reserved for future use\n \n Invoke draw() and save its commands to a newly generated displaylist.\n \n The displaylist name is then sent to the display service via a\n \"DISPLAYLIST_UPDATE\" request.\n \"\"\"\n pass\n \n \n def drawParticles(self, *particles):\n \"\"\"\\\n Sends particles drawing opengl command to the display service.\n \"\"\"\n for particle in particles:\n # Display list id\n displaylist = glGenLists(1)\n # Draw object to its displaylist\n glNewList(displaylist, GL_COMPILE)\n particle.draw()\n glEndList()\n \n # Send displaylist\n dl_update = { \"DISPLAYLIST_UPDATE\": True,\n \"objectid\": id(particle),\n \"displaylist\": displaylist\n }\n self.send(dl_update, \"display_signal\")\n \n \n def addListenEvents(self, events):\n \"\"\"\\\n Sends listening request for pygame events to the display service.\n The events parameter is expected to be a list of pygame event constants.\n \"\"\"\n for event in events:\n self.send({\"ADDLISTENEVENT\":event, \"objectid\":id(self)}, \"display_signal\")\n \n \n def removeListenEvents(self, events):\n \"\"\"\\\n Sends stop listening request for pygame events to the display service.\n The events parameter is expected to be a list of pygame event constants.\n \"\"\"\n for event in events:\n self.send({\"REMOVELISTENEVENT\":event, \"objectid\":id(self)}, \"display_signal\") \n \n \n def handleEvents(self):\n \"\"\"Handle events.\"\"\"\n while self.dataReady(\"events\"):\n event = self.recv(\"events\")\n if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONUP:\n self.handleMouseEvents(event)\n elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:\n self.handleKeyEvents(event)\n \n # Scroll if self.display.viewerposition changes\n if self.display.viewerposition.copy() != self.viewerOldPos:\n self.scroll()\n self.viewerOldPos = self.display.viewerposition.copy()\n\n \n def handleMouseEvents(self, event):\n \"\"\"Handle mouse events.\"\"\"\n if event.type == pygame.MOUSEBUTTONDOWN or pygame.MOUSEMOTION and self.grabbed:\n if not self.rotationMode:\n for particle in self.hitParticles:\n p1 = Vector(*particle.pos).copy()\n p1.x += 10\n p2 = Vector(*particle.pos).copy()\n p2.y += 10\n # Get the position of mouse\n z = Intersect.ray_Plane(Vector(0,0,0), event.direction, [Vector(*particle.pos)-Vector(0,0,self.display.viewerposition.z), p1-Vector(0,0,self.display.viewerposition.z), p2-Vector(0,0,self.display.viewerposition.z)])\n newpoint = event.direction * z\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n # Handle double click\n clickPos = event.pos\n currentTime = time.time()\n elapsedTime = currentTime - self.lastClickTime\n # If it's a double-click\n if clickPos == self.lastClickPos and elapsedTime self.maxLevel:\n print (\"Warning: max hierarchy level has reached!\")\n elif self.currentLevel + dlevel < 0:\n print (\"Warning: The first hierarchy level has reached!\")\n else:\n if dlevel < 0: # Go to the last dlevel level\n self.previousParentParticleID = self.currentParentParticleID\n items = self.currentParentParticleID.split(':')\n for _ in range(-dlevel):\n items.pop()\n self.currentParentParticleID = ':'.join(items)\n isValid = True\n if dlevel == 1: # It only makes sense if dlevel == 1 when go to next dlevel level\n if len(self.selectedParticles) == 1:\n hasChildParticles = False\n for particle in self.physics.particles:\n if particle.ID.find(self.selectedParticles[0].ID) == 0 and particle.ID != self.selectedParticles[0].ID:\n hasChildParticles = True\n break\n if hasChildParticles:\n self.previousParentParticleID = self.currentParentParticleID\n self.currentParentParticleID = self.selectedParticles[0].ID\n isValid = True\n else:\n print ('Warning: The particle you double-clicked has no children!')\n else:\n print (\"Tips: To extend a node, please double-click the node you want to extend\")\n # Show the specified display level if valid\n if isValid: \n # Save current level's viewer position\n self.levelViewerPos[self.currentLevel, self.previousParentParticleID] = self.display.viewerposition.copy()\n # Deselect all\n self.deselectAll()\n # Display next level\n self.currentLevel += dlevel\n # Reset viewer position to previous\n try:\n self.display.viewerposition = self.levelViewerPos[self.currentLevel, self.currentParentParticleID].copy()\n except KeyError:\n self.display.viewerposition = self.levelViewerPos[self.currentLevel, self.currentParentParticleID] = Vector()\n # Remove current displayed particles\n for particle in self.currentDisplayedPhysics.particles:\n self.display.ogl_displaylists.pop(id(particle))\n self.display.ogl_transforms.pop(id(particle))\n self.currentDisplayedPhysics.removeByID(*self.currentDisplayedPhysics.particleDict.keys())\n \n # Add current level's particles to self.currentDisplayedPhysics.particles for display\n self.currentDisplayedPhysics.particles = []\n if self.physics.particles != []:\n for particle in self.physics.particles:\n if self.currentParentParticleID == '': # If no parent, it's the top level \n if ':' not in particle.ID:\n self.currentDisplayedPhysics.add( particle )\n particle.oldpos = particle.initialpos\n # The child particles of self.currentParentParticleID\n elif particle.ID.find(self.currentParentParticleID) == 0 and particle.ID.count(':') == self.currentLevel:\n self.currentDisplayedPhysics.add( particle )\n particle.oldpos = particle.initialpos\n \n \n def doCommand(self, msg):\n \"\"\"\\\n Proceses a topology command tuple:\n [ \"ADD\", \"NODE\", , , , ] \n [ \"DEL\", \"NODE\", ]\n [ \"ADD\", \"LINK\", , ]\n [ \"DEL\", \"LINK\", , ]\n [ \"DEL\", \"ALL\" ]\n [ \"GET\", \"ALL\" ]\n \"\"\" \n if len(msg) >= 2:\n cmd = msg[0].upper(), msg[1].upper()\n \n # Add default arguments when they are not provided\n if cmd == (\"ADD\", \"NODE\"):\n if len(msg) == 4:\n msg += ['randompos', '-']\n elif len(msg) == 5:\n msg += ['-']\n\n if cmd == (\"ADD\", \"NODE\") and len(msg) == 6:\n if msg[2] in [p.ID for p in self.physics.particles]:\n print (\"Node exists, please use a new node ID!\")\n else:\n if ( msg[5] in self.particleTypes ):\n ptype = self.particleTypes[msg[5]]\n ident = msg[2]\n name = msg[3]\n \n posSpec = msg[4]\n pos = self._generatePos(posSpec)\n \n particle = ptype(position = pos, ID=ident, name=name)\n particle.originaltype = msg[5]\n \n self.addParticle(particle)\n self.isNewNode = True\n\n elif cmd == (\"DEL\", \"NODE\") and len(msg) == 3:\n ident = msg[2]\n self.removeParticle(ident) \n \n elif cmd == (\"ADD\", \"LINK\") and len(msg) == 4:\n src = msg[2]\n dst = msg[3]\n self.makeBond(src, dst)\n \n elif cmd == (\"DEL\", \"LINK\") and len(msg) == 4:\n src = msg[2]\n dst = msg[3]\n self.breakBond(src, dst)\n \n elif cmd == (\"DEL\", \"ALL\") and len(msg) == 2:\n self.removeParticle(*self.physics.particleDict.keys())\n self.currentLevel = 0\n self.currentParentParticleID = ''\n \n elif cmd == (\"GET\", \"ALL\") and len(msg) == 2:\n topology = [(\"DEL\",\"ALL\")]\n topology.extend(self.getTopology())\n self.send( (\"TOPOLOGY\", topology), \"outbox\" )\n \n elif cmd == (\"UPDATE_NAME\", \"NODE\") and len(msg) == 4:\n node_id = msg[2]\n new_name = msg[3]\n self.updateParticleLabel(node_id, new_name)\n self.send( (\"UPDATE_NAME\", \"NODE\", node_id, new_name), \"outbox\" )\n elif cmd == (\"GET_NAME\", \"NODE\") and len(msg) == 3:\n node_id = msg[2]\n name = self.getParticleLabel(node_id)\n self.send( (\"GET_NAME\", \"NODE\", node_id, name), \"outbox\" ) \n else:\n print (\"Command Error: please check your command format!\")\n else:\n print (\"Command Error: not enough parameters!\")\n \n \n def _generatePos(self, posSpec):\n \"\"\"\\\n generateXY(posSpec) -> (x,y,z) or raises ValueError\n \n posSpec == \"randompos\" or \"auto\" -> random (x,y,z) within the surface (specified border distance in from the edege)\n posSpec == \"(XXX,YYY,ZZZ)\" -> specified x,y,z (positive or negative integers)\n spaces are allowed within the tuple, but quotation is needed in this case.\n E.g., \" ( 0 , 0 , -10 ) \"\n \"\"\"\n posSpec = posSpec.lower()\n if posSpec == \"randompos\" or posSpec == \"auto\" :\n zLim = self.display.nearPlaneDist, self.display.farPlaneDist \n z = -1*random.randrange(int((zLim[1]-zLim[0])/20)+self.border,int((zLim[1]-zLim[0])/8)-self.border,1)\n yLim = z*math.tan(self.display.perspectiveAngle*math.pi/360.0), -z*math.tan(self.display.perspectiveAngle*math.pi/360.0) \n xLim = yLim[0]*self.display.aspectRatio, yLim[1]*self.display.aspectRatio\n y = random.randrange(int(yLim[0])+self.border,int(yLim[1])-self.border,1)\n x = random.randrange(int(xLim[0])+self.border,int(xLim[1])-self.border,1)\n # Apply camera/ viewer transformation\n x += self.display.viewerposition.x\n y += self.display.viewerposition.y\n z += self.display.viewerposition.z\n return x,y,z \n else: # given specified position\n posSpec = posSpec.strip()\n # Use triple tuple format for position\n match = re.match(\"^\\( *([+-]?\\d+) *, *([+-]?\\d+) *, *([+-]?\\d+) *\\)$\", posSpec)\n if match:\n x = int(match.group(1))\n y = int(match.group(2))\n z = int(match.group(3))\n return x,y,z \n \n raise ValueError(\"Unrecognised position specification\")\n\n \n def addParticle(self, *particles):\n \"\"\"Add particles to the system\"\"\"\n for p in particles:\n if p.radius > self.biggestRadius:\n self.biggestRadius = p.radius\n pLevel = p.ID.count(':')\n if self.maxLevel < pLevel:\n self.maxLevel = pLevel\n # Make display request for every particle added\n disprequest = { \"OGL_DISPLAYREQUEST\" : True,\n \"objectid\" : id(p),\n \"callback\" : (self,\"callback\"),\n \"events\" : (self, \"events\"),\n \"size\": p.size\n }\n # Send display request\n self.send(disprequest, \"display_signal\")\n self.physics.add( *particles )\n \n # Add new particles to self.currentDisplayedPhysics\n for particle in particles:\n if self.currentParentParticleID == '': # If no parent, it's the top level \n if ':' not in particle.ID:\n self.currentDisplayedPhysics.add( particle )\n particle.oldpos = particle.initialpos\n # The child particles of self.currentParentParticleID\n elif particle.ID.find(self.currentParentParticleID) == 0 and particle.ID.count(':') == self.currentLevel:\n self.currentDisplayedPhysics.add( particle )\n particle.oldpos = particle.initialpos\n \n \n def removeParticle(self, *ids):\n \"\"\"\\\n Remove particle(s) specified by their ids.\n\n Also breaks any bonds to/from that particle.\n \"\"\"\n for ident in ids:\n self.physics.particleDict[ident].breakAllBonds()\n try:\n self.display.ogl_objects.remove(id(self.physics.particleDict[ident]))\n self.display.ogl_names.pop(id(self.physics.particleDict[ident]))\n self.display.ogl_displaylists.pop(id(self.physics.particleDict[ident]))\n self.display.ogl_transforms.pop(id(self.physics.particleDict[ident]))\n except KeyError: pass\n self.physics.removeByID(*ids)\n for ident in ids:\n try:\n self.currentDisplayedPhysics.removeByID(ident)\n except KeyError: pass\n \n \n def selectParticle(self, particle):\n \"\"\"Select the specified particle.\"\"\"\n if self.multiSelectMode:\n if particle not in self.selectedParticles:\n particle.select()\n self.selectedParticles.append(particle)\n self.send( \"('SELECT', 'NODE', '\"+particle.name+\"')\", \"outbox\" )\n else:\n particle.deselect()\n self.selectedParticles.remove(particle)\n self.send( \"('DESELECT', 'NODE', '\"+particle.name+\"')\", \"outbox\" )\n else:\n self.deselectAll()\n self.selectedParticles = []\n particle.select()\n self.selectedParticles.append(particle)\n self.send( \"('SELECT', 'NODE', '\"+particle.name+\"')\", \"outbox\" )\n\n\n def deselectAll(self):\n \"\"\"Deselect all particles.\"\"\"\n for particle in self.selectedParticles:\n particle.deselect()\n self.selectedParticles = []\n \n \n def makeBond(self, source, dest):\n \"\"\"Make a bond from source to destination particle, specified by IDs\"\"\"\n self.physics.particleDict[source].makeBond(self.physics.particleDict, dest)\n self.physics.particleDict[source].needRedraw = True\n\n\n def breakBond(self, source, dest):\n \"\"\"Break a bond from source to destination particle, specified by IDs\"\"\"\n self.physics.particleDict[source].breakBond(self.physics.particleDict, dest)\n self.physics.particleDict[source].needRedraw = True\n \n \n def updateParticleLabel(self, node_id, new_name):\n \"\"\"\\\n updateParticleLabel(node_id, new_name) -> updates the given nodes name & visual label if it exists\n \n node_id - an id for an already existing node\n new_name - a string (may include spaces) defining the new node name\n \"\"\"\n for p in self.physics.particles:\n if p.ID == node_id:\n p.set_label(new_name)\n p.needRedraw = True\n return\n\n\n def getParticleLabel(self, node_id):\n \"\"\"\\\n getParticleLabel(node_id) -> particle's name\n \n Returns the name/label of the specified particle.\n \"\"\"\n for p in self.physics.particles:\n if p.ID == node_id:\n return p.name\n \n \n def getTopology(self):\n \"\"\"getTopology() -> list of command tuples that would build the current topology\"\"\"\n topology = []\n \n # first, enumerate the particles\n for particle in self.physics.particles:\n topology.append( ( \"ADD\",\"NODE\",\n particle.ID,\n particle.name,\n \"random\",\n particle.originaltype\n ) )\n \n # now enumerate the linkages\n for particle in self.physics.particles:\n for dst in particle.getBondedTo():\n topology.append( ( \"ADD\",\"LINK\", particle.ID, dst.ID ) )\n \n return topology\n \n\n\n__kamaelia_components__ = ( TopologyViewer3D, ) \n\n\n \nif __name__ == \"__main__\":\n from Kamaelia.Util.DataSource import DataSource\n from Kamaelia.Visualisation.PhysicsGraph.lines_to_tokenlists import lines_to_tokenlists\n from Kamaelia.Util.Console import ConsoleEchoer,ConsoleReader\n from Kamaelia.Chassis.Graphline import Graphline\n \n # Data can be from both DataSource and console inputs\n print (\"Please type the command you want to draw\")\n Graphline(\n CONSOLEREADER = ConsoleReader(\">>> \"),\n# DATASOURCE = DataSource(['ADD NODE 1Node 1Node randompos -', 'ADD NODE 2Node 2Node randompos -',\n# 'ADD NODE 3Node 3Node randompos -', 'ADD NODE 4Node 4Node randompos -',\n# 'ADD LINK 1Node 2Node','ADD LINK 2Node 3Node', 'ADD LINK 3Node 4Node',\n# 'ADD LINK 4Node 1Node']),\n DATASOURCE = DataSource(['ADD NODE 1Node 1Node randompos teapot',\n 'ADD NODE 2Node 2Node randompos -',\n 'ADD NODE 3Node 3Node randompos sphere', 'ADD NODE 4Node 4Node randompos -',\n 'ADD NODE 5Node 5Node randompos sphere', 'ADD NODE 6Node 6Node randompos -',\n 'ADD NODE 7Node 7Node randompos sphere',\n 'ADD LINK 1Node 2Node',\n 'ADD LINK 1Node 3Node', 'ADD LINK 1Node 4Node',\n 'ADD LINK 1Node 5Node','ADD LINK 1Node 6Node', 'ADD LINK 1Node 7Node',\n 'ADD NODE 1Node:1Node 1Node:1Node randompos -', 'ADD NODE 1Node:2Node 1Node:2Node randompos -',\n 'ADD NODE 1Node:3Node 1Node:3Node randompos -', 'ADD NODE 1Node:4Node 1Node:4Node randompos -',\n 'ADD LINK 1Node:1Node 1Node:2Node', 'ADD LINK 1Node:2Node 1Node:3Node',\n 'ADD LINK 1Node:3Node 1Node:4Node', 'ADD LINK 1Node:4Node 1Node:1Node',\n 'ADD NODE 1Node:1Node:1Node 1Node:1Node:1Node randompos -',\n 'ADD NODE 1Node:1Node:2Node 1Node:1Node:2Node randompos -',\n 'ADD LINK 1Node:1Node:1Node 1Node:1Node:2Node',\n 'ADD NODE 5Node:1Node 5Node:1Node randompos sphere',\n 'ADD NODE 5Node:2Node 5Node:2Node randompos sphere',\n 'ADD LINK 5Node:1Node 5Node:2Node'\n ]),\n TOKENS = lines_to_tokenlists(),\n VIEWER = TopologyViewer3D(),\n CONSOLEECHOER = ConsoleEchoer(),\n linkages = {\n (\"CONSOLEREADER\",\"outbox\") : (\"TOKENS\",\"inbox\"),\n (\"DATASOURCE\",\"outbox\") : (\"TOKENS\",\"inbox\"),\n (\"TOKENS\",\"outbox\") : (\"VIEWER\",\"inbox\"),\n (\"VIEWER\",\"outbox\") : (\"CONSOLEECHOER\",\"inbox\"),\n }\n).run()\n \n# Licensed to the BBC under a Contributor Agreement: CL\n","sub_path":"Kamaelia/Visualisation/PhysicsGraph3D/TopologyViewer3D.py","file_name":"TopologyViewer3D.py","file_ext":"py","file_size_in_byte":48393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"631997203","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n@author:dodio\n@description:\n@file:function.py\n@time:2021/03/30\n\"\"\"\nimport random\n\n\ndef bin_weight_random(out1, out2, weight): # 二元权重随机\n r = random.random()\n if r < weight:\n return out1\n else:\n return out2\n\n\ndef gen_names(list1, list2, list3, list4):\n l = len(list1) - 1\n num1 = 0\n num2 = 0\n while num1 == num2:\n num1 = random.randint(0, l)\n num2 = random.randint(0, l)\n name_en = list3[num1] + '·' + list1[num2]\n name_zh = list4[num1] + '·' + list2[num2]\n name = [name_en, name_zh]\n return name\n\n\ndef gen_birth():\n year = random.randint(1960, 1999)\n month = random.randint(1, 12)\n day = random.randint(1, 29)\n return [year, month, day]\n\n\ndef gen_gen():\n m = '男'\n f = '女'\n gen = bin_weight_random(m, f, 0.8)\n return gen\n","sub_path":"RandomCharacterGenerator_En/scripts/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"556015094","text":"\"\"\"\n Bast Web Framework\n (c) Majiyagbe Oluwole \n\n For full copyright and license information, view the LICENSE distributed with the Source Code\n\"\"\"\n\nimport os\n\nfrom git import Repo\n\nfrom .bast import __version__\nfrom .migration import CreateMigration, Migration\n\ntry:\n from configparser import ConfigParser\nexcept ImportError:\n import ConfigParser\nimport bcrypt\nimport shutil\nimport click\nimport re\n\n\"\"\" Handles the CLI commands and their respective Arguments \"\"\"\n\n\n@click.group()\n@click.version_option(__version__)\ndef main():\n config_path = os.path.abspath('.') + \"/config/config.ini\"\n if not os.path.exists(config_path):\n return\n\n config = ConfigParser()\n config.read(config_path)\n\n # config section\n os.environ['APP_NAME'] = config['CONFIG']['APP_NAME']\n os.environ['APP_KEY'] = config['CONFIG']['APP_KEY']\n\n os.environ['DB_TYPE'] = config['DATABASE']['DB_TYPE']\n os.environ['DB_NAME'] = config['DATABASE']['DB_NAME']\n os.environ['DB_HOST'] = config['DATABASE']['DB_HOST']\n os.environ['DB_USER'] = config['DATABASE']['DB_USER']\n os.environ['DB_PASSWORD'] = config['DATABASE']['DB_PASSWORD']\n os.environ['DB_PREFIX'] = config['DATABASE']['DB_PREFIX']\n\n # print(os.environ['APP_NAME'])\n # pass\n\n\n@main.command('create:controller', short_help='Creates a Controller File')\n@click.argument('filename', required=1)\ndef controller_creatr(filename):\n \"\"\"Name of the controller file to be created\"\"\"\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the create:controller command')\n return\n\n path = os.path.abspath('.') + '/controller'\n if not os.path.exists(path):\n os.makedirs(path)\n\n file_name = str(filename + '.py')\n controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')\n compose = \"from bast import Controller\\n\\nclass \" + filename + \"(Controller):\\n pass\"\n controller_file.write(compose)\n controller_file.close()\n click.echo(\"\\033[1;32;40m Modes/Controller \" + filename + \" created successfully\")\n\n\n@main.command('create:middleware', short_help=\"Creates a Middleware\")\n@click.argument('filename', required=1)\ndef middleware_creatr(filename):\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the create:middleware command')\n return\n\n path = os.path.abspath('.') + '/middleware'\n if not os.path.exists(path):\n os.makedirs(path)\n\n file_name = str(filename) + '.py'\n middleware_file = open(os.path.abspath('.') + '/middleware/' + file_name, 'w+')\n compose = \"class \" + filename + \":\\n def handle(self, request):\\n return True\"\n middleware_file.write(compose)\n middleware_file.close()\n click.echo(\"\\033[1;32;40m Modes/Middleware \" + filename + \" created successfully\")\n\n\n@main.command('create:view', short_help=\"Create a View File\")\n@click.argument('filename', required=1)\ndef view_creatr(filename):\n \"\"\"Name of the View File to be created\"\"\"\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the create:view command')\n return\n\n path = os.path.abspath('.') + '/public/templates'\n if not os.path.exists(path):\n os.makedirs(path)\n\n filename_ = str(filename + \".html\").lower()\n view_file = open(path + \"/\" + filename_, 'w+')\n view_file.write(\"\")\n view_file.close()\n\n\n@main.command('run', short_help=\"Run your Bast Server\")\n@click.option('--serverfile', help=\"Name of the file to run\", default='server.py')\ndef run(serverfile):\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to use the \"run\" command')\n return\n\n cmd = 'python ' + serverfile\n os.system(cmd)\n\n\n@main.command('new', short_help=\"Create a new Bast Project\")\n@click.argument('projectname', required=1)\ndef create_new(projectname):\n \"\"\"Name of the project\"\"\"\n git_url = \"https://github.com/moluwole/Bast_skeleton\"\n path = os.path.abspath('.') + \"/\" + projectname\n if not os.path.exists(path):\n os.makedirs(path)\n click.echo(\"\\033[1;32;40m Creating Project at %s.... \" % path)\n click.echo(\"\\033[1;32;40m Pulling Project Skeleton from Repo\")\n Repo.clone_from(git_url, path)\n\n click.echo(\"\\033[1;32;40m Setting up project\")\n\n # Setting up the Config File\n config_path = path + \"/config/config.ini\"\n\n shutil.rmtree(path + \"/.git\")\n os.remove(path + \"/.gitignore\")\n\n config = ConfigParser()\n config.read(config_path)\n\n config.set('CONFIG', 'APP_NAME', projectname)\n hash_ = bcrypt.hashpw(str(projectname).encode('utf-8'), bcrypt.gensalt(12))\n config.set('CONFIG', 'APP_KEY', str(hash_))\n\n with open(config_path, 'w') as config_file:\n config.write(config_file)\n\n click.echo(\"\\033[1;32;40m New Bast Project created at %s \" % path)\n\n\n@main.command('create:migration', short_help=\"Create a migration file\")\n@click.argument('migration_file', required=1)\n@click.option('--create', default=True, help=\"Create the table. OPTIONAL\")\n@click.option('--table', default=None, help=\"Name of the table to be created. OPTIONAL\")\ndef migration_creatr(migration_file, create, table):\n \"\"\"Name of the migration file\"\"\"\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the create:migration command')\n return\n\n migration = CreateMigration()\n if table is None:\n table = snake_case(migration_file)\n file = migration.create_file(snake_case(migration_file), table=table, create=create)\n click.echo('Migration file created at %s' % file)\n\n\n@main.command('migration:run', short_help=\"Run Migration\")\n@click.option('--pretend', default=False, help=\"Simulates the Migration\")\ndef migration_run(pretend):\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the migration:run command')\n return\n\n migration = Migration()\n migration.run_(pretend)\n click.echo('Migration Run successful')\n\n\n@main.command('migration:rollback', short_help=\"Roll Back last Migration\")\n@click.option('--pretend', default=False, help=\"Simulates the Migration\")\ndef migration_rollback(pretend):\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the migration:rollback command')\n return\n\n migration = Migration()\n count = migration.rollback_(pretend)\n click.echo('Roll Back Executed. %s migrations rolled back' % count)\n\n\n@main.command('migration:reset', short_help=\"Reset Migration\")\n@click.option('--pretend', default=False, help=\"Simulate the Migration\")\ndef migration_reset(pretend):\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the migration:rollback command')\n return\n\n migration = Migration()\n count = migration.reset_(pretend)\n click.echo('Migration Reset successful. %s migrations has been reset' % count)\n\n\n@main.command('create:model', short_help=\"Create Model File\")\n@click.argument('model_file', required=1)\n@click.option('--migration', default=True, help=\"Generate Migration File Also\")\ndef model_creatr(model_file, migration):\n bast_app = os.path.abspath('.') + '/config/config.ini'\n if not os.path.exists(bast_app):\n click.echo('ERROR: Ensure you are in a bast app to run the create:model command')\n return\n\n filename = snake_case(model_file) + \".py\"\n\n directory_path = os.path.abspath('.') + '/models/'\n if not os.path.exists(directory_path):\n os.makedirs(directory_path)\n\n path = os.path.abspath('.') + '/models/' + filename\n file_open = open(path, 'w+')\n compose = 'from bast import Models\\n\\nclass %s(Models):\\n __table__ = \\'%s\\'' \\\n % (model_file, snake_case(model_file))\n file_open.write(compose)\n file_open.close()\n if migration:\n migrate = CreateMigration()\n migrate.create_file(name=snake_case(model_file), table=snake_case(model_file), create=True)\n click.echo('%s has been created at /models' % filename)\n\n\ndef snake_case(string_name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', string_name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n","sub_path":"bast/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"310790543","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport math\nimport numpy as np\nimport torch\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom progress.bar import Bar\nfrom models.data_parallel import DataParallel\nfrom utils.utils import AverageMeter, freeze_bn\n\n\nclass ModleWithLoss(torch.nn.Module):\n def __init__(self, model, loss):\n super(ModleWithLoss, self).__init__()\n self.model = model\n self.loss = loss\n \n def forward(self, batch):\n outputs = self.model(batch['input'])\n loss, loss_stats = self.loss(outputs, batch)\n return outputs[-1], loss, loss_stats\n\nclass BaseTrainer(object):\n def __init__(\n self, opt, model, optimizer=None):\n self.opt = opt\n if opt.amp:\n from torch.cuda.amp import autocast, GradScaler\n self.autocast = autocast\n self.scaler = GradScaler()\n print('Using Mixed Precision Training...')\n self.optimizer = optimizer\n # Scheduler https://arxiv.org/pdf/1812.01187.pdf\n self.lf = lambda x: (((1 + math.cos(x * math.pi / opt.num_epochs)) / 2) ** 1.0) * 0.9 + 0.1 # cosine\n self.scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=self.lf)\n\n self.loss_stats, self.loss = self._get_losses(opt)\n self.model_with_loss = ModleWithLoss(model, self.loss)\n self.nbs = opt.nbs # nominal batch size\n self.accumulate = max(round(self.nbs / opt.batch_size), 1) # accumulate loss before optimizing\n\n def set_device(self, gpus, chunk_sizes, device):\n if len(gpus) > 1:\n self.model_with_loss = DataParallel(\n self.model_with_loss, device_ids=gpus, \n chunk_sizes=chunk_sizes).to(device)\n else:\n self.model_with_loss = self.model_with_loss.to(device)\n \n for state in self.optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(device=device, non_blocking=True)\n\n def run_epoch(self, phase, epoch, data_loader):\n model_with_loss = self.model_with_loss\n if phase == 'train':\n model_with_loss.train()\n if self.opt.freeze_bn:\n model_with_loss.apply(freeze_bn)\n else:\n if len(self.opt.gpus) > 1:\n model_with_loss = self.model_with_loss.module\n model_with_loss.eval()\n torch.cuda.empty_cache()\n\n opt = self.opt\n results = {}\n data_time, batch_time = AverageMeter(), AverageMeter()\n avg_loss_stats = {l: AverageMeter() for l in self.loss_stats}\n num_iters = len(data_loader) if opt.num_iters < 0 else opt.num_iters\n n_burn = max(3 * num_iters, 1e3) # burn-in iterations, max(3 epochs, 1k iterations)\n bar = Bar('{}/{}'.format(opt.task, opt.exp_id), max=num_iters)\n end = time.time()\n\n self.optimizer.zero_grad()\n for iter_id, batch in enumerate(data_loader):\n ni = iter_id + num_iters * (epoch - 1) # number integrated batches (since train start)\n if iter_id >= num_iters:\n break\n data_time.update(time.time() - end)\n\n for k in batch:\n if k != 'meta':\n batch[k] = batch[k].to(device=opt.device, non_blocking=True)\n\n if ni <= n_burn:\n xi = [0, n_burn] # x interp\n accumulate = max(1, np.interp(ni, xi, [1, self.opt.nbs / self.opt.batch_size]).round())\n for j, x in enumerate(self.optimizer.param_groups):\n x['lr'] = np.interp(ni, xi, [0.0, x['initial_lr'] * self.lf(epoch - 1)])\n\n if opt.amp:\n with self.autocast():\n output, loss, loss_stats = model_with_loss(batch)\n loss = loss.mean()\n if phase == 'train':\n self.scaler.scale(loss).backward()\n if ni & self.accumulate == 0:\n self.scaler.step(self.optimizer)\n self.scaler.update()\n self.optimizer.zero_grad()\n else:\n output, loss, loss_stats = model_with_loss(batch)\n loss = loss.mean()\n if phase == 'train':\n loss.backward()\n if ni & self.accumulate == 0:\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n batch_time.update(time.time() - end)\n end = time.time()\n\n Bar.suffix = '{phase}: [{0}][{1}/{2}]|Tot: {total:} |ETA: {eta:} |LR: {lr:.7f}'.format(\n epoch, iter_id, num_iters, phase=phase,\n total=bar.elapsed_td, eta=bar.eta_td, lr=self.optimizer.param_groups[0]['lr'])\n for l in avg_loss_stats:\n avg_loss_stats[l].update(\n loss_stats[l].mean().item(), batch['input'].size(0))\n Bar.suffix = Bar.suffix + '|{} {:.4f} '.format(l, avg_loss_stats[l].avg)\n if not opt.hide_data_time:\n Bar.suffix = Bar.suffix + '|Data {dt.val:.3f}s({dt.avg:.3f}s) ' \\\n '|Net {bt.avg:.3f}s'.format(dt=data_time, bt=batch_time)\n if opt.print_iter > 0:\n if iter_id % opt.print_iter == 0:\n print('{}/{}| {}'.format(opt.task, opt.exp_id, Bar.suffix)) \n else:\n bar.next()\n \n if opt.debug > 0:\n self.debug(batch, output, iter_id)\n \n if opt.test:\n self.save_result(output, batch, results)\n del output, loss, loss_stats\n \n # Scheduler\n if phase == 'train':\n self.scheduler.step()\n\n bar.finish()\n ret = {k: v.avg for k, v in avg_loss_stats.items()}\n ret['time'] = bar.elapsed_td.total_seconds() / 60.\n return ret, results\n \n def debug(self, batch, output, iter_id):\n raise NotImplementedError\n\n def save_result(self, output, batch, results):\n raise NotImplementedError\n\n def _get_losses(self, opt):\n raise NotImplementedError\n \n def val(self, epoch, data_loader):\n return self.run_epoch('val', epoch, data_loader)\n\n def train(self, epoch, data_loader):\n return self.run_epoch('train', epoch, data_loader)","sub_path":"src/lib/trains/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":5709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"213081068","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom downward import suites\nfrom common_setup import IssueConfig, IssueExperiment\n\n\nREVS = [\"issue551-base\", \"issue551-v3\"]\nBENCHMARKS = os.path.expanduser('~/downward-benchmarks')\nSUITE = suites.suite_optimal_strips()\n\nCONFIGS = [\n IssueConfig(\"seq-opt-bjolp\", [], driver_options=[\"--alias\", \"seq-opt-bjolp\"]),\n]\n\nexp = IssueExperiment(\n revisions=REVS,\n benchmarks_dir=BENCHMARKS,\n suite=SUITE,\n configs=CONFIGS,\n processes=4,\n email=\"manuel.heusner@unibas.ch\"\n)\n\nexp.add_comparison_table_step()\n\nexp()\n","sub_path":"rovers/fastdownward/experiments/issue551/v3-lama-opt.py","file_name":"v3-lama-opt.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"569983250","text":"from config import bot, loop, plgns\nfrom amanobot.aio.loop import MessageLoop\n\nfor i in plgns:\n exec('from plugins.{0} import {0}'.format(i))\n\nif __name__ == '__main__':\n loop.create_task(MessageLoop(bot, dict(chat=handle,\n callback_query=callback,\n inline_query=inline,\n chosen_inline_result=chosen)).run_forever())\n loop.run_forever()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"588738098","text":"# nohup /bin/bash run.sh > out.txt 2>&1 &\n# tail -f out.txt\n\n# nohup python run_one.py > out.txt 2>&1 &\n# python -u run_one.py\n\nprint(\"----------------------------\")\nprint(\"\\nNew iteration\\n\")\nprint(\"imports\")\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import Adam, SGD\nfrom keras.utils import to_categorical\nfrom keras.models import load_model\nfrom keras.callbacks import CSVLogger\nimport datetime\nimport os\nfrom lib import features_from_table,generate_table\nimport signal, sys\n\n\nprint(datetime.datetime.now().strftime(\"%H:%M:%S.%f\"))\nprint(\"code start\")\n\n# load validation feature boards\nX2 = np.load(\"data/KRPvKRP_16f_10K_random_test_v2_02.npy\")\nX2 = np.swapaxes(X2,1,2)\nX2 = np.swapaxes(X2,2,3)\n\n# load validation result array\ndf2=pd.read_hdf(\"data/KRPvKRP_table_10K_random_test_v2_02.h5\", 'df1')\ny2=np.zeros((len(df2.index),5))\ny2[:,0] = (df2[\"wdl\"]==-2)*1\ny2[:,1] = (df2[\"wdl\"]==-1)*1\ny2[:,2] = (df2[\"wdl\"]==0)*1\ny2[:,3] = (df2[\"wdl\"]==1)*1\ny2[:,4] = (df2[\"wdl\"]==2)*1\n\n# load the previous model\nm=load_model(r\"data/model20KRPvKRP.h5\")\n\n# change the learning rate\n#adam=Adam()\nsgd = SGD(lr=0.0001, momentum=0.9)\n#m.compile(loss='categorical_crossentropy', optimizer=adam) #sgd) #adam)\n\nacc_hist = []\nval_acc_hist = []\nloss_hist = []\nval_loss_hist = []\n\ndef exit_gracefully(signum, frame):\n print(\"\\n\\nAll Python Iterations\\nloss\\nval_loss\\nacc\\nval_acc\")\n _ = [print(x) for x in loss_hist]\n print()\n _ = [print(x) for x in val_loss_hist]\n print()\n _ = [print(x) for x in acc_hist]\n print()\n _ = [print(x) for x in val_acc_hist]\n print()\n sys.exit()\n\n\ndef print_current_results(signum, frame):\n print(\"\\n\\nAll Python Iterations\\nloss\\nval_loss\\nacc\\nval_acc\")\n _ = [print(x) for x in loss_hist]\n print()\n _ = [print(x) for x in val_loss_hist]\n print()\n _ = [print(x) for x in acc_hist]\n print()\n _ = [print(x) for x in val_acc_hist]\n print()\n\nsignal.signal(signal.SIGINT, exit_gracefully)\nsignal.signal(signal.SIGTERM, exit_gracefully)\n#signal.signal(signal.SIGUSR1, print_current_results)\n\nfor i_data_epochs in range(1000000):\n print(\"\\nPython iteration number: \", i_data_epochs)\n # generate table with positions and results (wdl) in parallel to calculation\n os.system(\"nohup python -u gen_iter.py > gen_out.txt 2>&1 &\")\n #os.system(\"START python -u gen_iter.py > gen_out.txt\")\n\n #load table calculated in the previous iteration\n df = pd.read_hdf(\"data/KRPvKRP_table_10M_random_iter.h5\")\n #if i_data_epochs == 0:\n #df = df[:500000]\n # generate feature boards from the table above\n start_time = datetime.datetime.now()\n X=features_from_table(df)\n end_time = datetime.datetime.now()\n #print(\"Feature boards generation time: \",end_time - start_time)\n\n # swap axis for Keras\n X = np.swapaxes(X,1,2)\n X = np.swapaxes(X,2,3)\n\n # generate 5 arrays of results for each wdl (-2,-1,0,1,2)\n y=np.zeros((len(df.index),5))\n y[:,0] = (df[\"wdl\"]==-2)*1\n y[:,1] = (df[\"wdl\"]==-1)*1\n y[:,2] = (df[\"wdl\"]==0)*1\n y[:,3] = (df[\"wdl\"]==1)*1\n y[:,4] = (df[\"wdl\"]==2)*1\n\n csv_logger = CSVLogger('training.log', append=True)\n\n # calculate epochs and calculate execution time\n start_time = datetime.datetime.now()\n #print(start_time.strftime(\"%Y-%m-%d %H:%M:%S.%f\"))\n hist = m.fit(X, y, batch_size=256, epochs=7, validation_data=(X2,y2), callbacks=[csv_logger])\n end_time = datetime.datetime.now()\n os.remove(r\"data/model20KRPvKRP.h5\")\n m.save(r\"data/model20KRPvKRP.h5\")\n #print(end_time.strftime(\"%Y-%m-%d %H:%M:%S.%f\"))\n #print(\"Training time: \",end_time - start_time)\n\n # calculate and print training, test loss, accuracy\n #y_train = m.predict(X2, batch_size=1024*2, verbose=1)\n #y_train_cat=np.argmax(y_train,1)-2\n #acc = np.sum(y_train_cat==df2.wdl)/y_train_cat.shape[0]\n #n_errors = y_train_cat.shape[0] - np.sum(y_train_cat==df2.wdl)\n #print(\"\\n\\nloss\\nval_loss\\nacc\")\n #_ = [print(x) for x in hist.history[\"loss\"]]\n #_ = [print(x) for x in hist.history[\"val_loss\"]]\n #print(acc)\n acc_hist.append(hist.history[\"acc\"][0])\n val_acc_hist.append(hist.history[\"val_acc\"][0])\n loss_hist.append(hist.history[\"loss\"][0])\n val_loss_hist.append(hist.history[\"val_loss\"][0])\n\nprint(\"\\n\\nAll Python Iterations\\nloss\\nval_loss\\nacc\\nval_acc\")\n_ = [print(x) for x in loss_hist]\nprint()\n_ = [print(x) for x in val_loss_hist]\nprint()\n_ = [print(x) for x in acc_hist]\nprint()\n_ = [print(x) for x in val_acc_hist]\nprint()\n","sub_path":"run_one.py","file_name":"run_one.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"354043458","text":"from django.contrib import messages\nimport dj_database_url\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nCSRF_COOKIE_SECURE = bool(int(os.environ.get('CSRF_COOKIE_SECURE', 1)))\n\n\"\"\"Redirect for now until we disable app\"\"\"\nREDIRECT_EVENTS_URL = os.environ.get(\n 'REDIRECT_EVENTS_URL',\n 'https://ourrevolution.com/organizing-hub/event/'\n)\nREDIRECT_SLACK_URL = os.environ.get(\n 'REDIRECT_SLACK_URL',\n 'http://ourrev.us/join-us-on-slack'\n)\n\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('SECRET_KEY', None)\n\nSESSION_COOKIE_SECURE = bool(int(os.environ.get('SESSION_COOKIE_SECURE', 1)))\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nALLOWED_HOSTS = '*'\n\n\n# Application definition\n\nINSTALLED_APPS = [\n\n # core Django\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.gis',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # dev niceties\n 'anymail',\n 'bootstrap3',\n 'cacheops',\n 'debug_toolbar',\n 'espresso',\n\n # Hydra specific\n 'chowda',\n 'bsd',\n 'groups',\n 'hydra',\n]\n\n\n# Mailgun\n\n\nMAILGUN_ACCESS_KEY = os.environ.get('MAILGUN_API_KEY', None)\nMAILGUN_SERVER_NAME = os.environ.get('MAILGUN_API_DOMAIN', None)\nMAILGUN_DOMAIN = os.environ.get('MAILGUN_DOMAIN', None)\n\n\nANYMAIL = {\n 'MAILGUN_API_KEY': MAILGUN_ACCESS_KEY,\n 'MAILGUN_SENDER_DOMAIN': MAILGUN_SERVER_NAME\n}\n\nDEFAULT_FROM_EMAIL = \"info@ourrevolution.com\"\n\n\n# espresso settings\n\nif DEBUG:\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nelse:\n EMAIL_BACKEND = os.environ.get('EMAIL_BACKEND', 'anymail.backends.mailgun.MailgunBackend')\n\n\nDRIP_TEMPLATES = (\n (None, 'None (Plain Text)'),\n ('our_revolution_email.html', 'Our Revolution'),\n)\n\n\n# debug / email reporting settings\n\nADMINS = [\n ('Our Revolution Tech Team', 'tech-team@ourrevolution.com'),\n]\n\nSERVER_EMAIL = \"bugtroll@ourrevolution.com\"\n\nINTERNAL_IPS = ['24.18.176.26', '24.158.161.75']\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TOOLBAR_CALLBACK': 'hydra.settings.LOAD_BALANCER_FRIENDLY_SHOW_TOOLBAR'\n}\n\n\nDEBUG_TOOLBAR_PANELS = [\n # 'debug_toolbar.panels.profiling.ProfilingPanel',\n 'debug_toolbar.panels.versions.VersionsPanel',\n 'debug_toolbar.panels.timer.TimerPanel',\n 'debug_toolbar.panels.settings.SettingsPanel',\n 'debug_toolbar.panels.headers.HeadersPanel',\n 'debug_toolbar.panels.request.RequestPanel',\n 'debug_toolbar.panels.sql.SQLPanel',\n 'debug_toolbar.panels.staticfiles.StaticFilesPanel',\n 'debug_toolbar.panels.templates.TemplatesPanel',\n 'debug_toolbar.panels.cache.CachePanel',\n 'debug_toolbar.panels.signals.SignalsPanel',\n 'debug_toolbar.panels.logging.LoggingPanel',\n 'debug_toolbar.panels.redirects.RedirectsPanel',\n]\n\n\ndef LOAD_BALANCER_FRIENDLY_SHOW_TOOLBAR(request):\n\n if request.META.get('REMOTE_ADDR', None) not in INTERNAL_IPS and request.META.get('HTTP_X_FORWARDED_FOR', None) not in INTERNAL_IPS:\n return False\n\n if request.is_ajax():\n return False\n\n return bool(DEBUG)\n\n\n\nMIDDLEWARE = [\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'hydra.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n 'builtins': [\n 'espresso.templatetags.clean_spaces'\n ]\n },\n },\n]\n\nWSGI_APPLICATION = 'hydra.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n\nBSD_API_HOST = os.environ.get('BSD_API_HOST')\nBSD_API_ID = os.environ.get('BSD_API_ID')\nBSD_API_SECRET = os.environ.get('BSD_API_SECRET')\n\nDATABASES = {\n\n # Postgres / default\n 'default': dj_database_url.config(),\n\n 'groups': dj_database_url.parse(os.environ.get('GROUP_DATABASE_URL', '')),\n\n # Blue State Digital read-only replica, for majortom\n 'BSD': {\n 'ENGINE': \"bsd.mysql\", # hack.\n 'NAME': os.environ.get('BSD_DATABASE_NAME'),\n 'USER': os.environ.get('BSD_DATABASE_USER'),\n 'HOST': os.environ.get('BSD_DATABASE_HOST'),\n 'PASSWORD': os.environ.get('BSD_DATABASE_PASSWORD'),\n 'OPTIONS': {\n 'ssl': {\n 'ca': os.path.join(BASE_DIR, os.environ.get('BSD_DATABASE_PATH_TO_CA_CERT', '')),\n 'cipher': \"DHE-RSA-AES256-SHA\",\n 'verify_server_cert': False\n }\n }\n }\n\n}\n\nDATABASE_ROUTERS = ['bsd.routers.BSDRouter']\n\nAUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'bsd.backends.BSDAuthenticationBackend',)\n\nLOGIN_URL = '/login/'\nLOGIN_REDIRECT_URL = '/'\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATIC_ROOT = os.path.join(BASE_DIR, '.static')\n\nMESSAGE_TAGS = {\n messages.ERROR: 'danger'\n}\n\n\nCACHEOPS_REDIS = { 'host': os.environ.get('REDIS_HOST', None), 'db': 1 }\n\nCACHEOPS = {\n 'bsd.EventType': {'ops': ('fetch',), 'timeout': 60*60},\n 'bsd.Constituent': {'ops': ('get', 'fetch'), 'timeout': 60*60},\n # 'bsd.Event': {'ops': ('all,'), 'timeout': 10, 'cache_on_save': True}\n}\n\nCACHEOPS_DEGRADE_ON_FAILURE = True\n\n\nif not DEBUG:\n MIDDLEWARE.remove('debug_toolbar.middleware.DebugToolbarMiddleware')\n INSTALLED_APPS.remove('debug_toolbar')\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler',\n 'include_html': True,\n },\n 'console': {\n 'level': 'NOTSET',\n 'class': 'logging.StreamHandler',\n },\n 'file': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': 'django-debug.log',\n },\n 'SysLog': {\n \t\t'level': 'NOTSET',\n \t\t'class': 'logging.handlers.SysLogHandler',\n \t\t'formatter': 'simple',\n \t\t'address': ('logs6.papertrailapp.com', 17716)\n \t},\n },\n 'formatters': {\n \t'simple': {\n \t\t'format': '%(asctime)s events.ourrevolution.com: %(message)s',\n 'datefmt': '%Y-%m-%dT%H:%M:%S',\n \t},\n },\n 'loggers': {\n '': {\n 'handlers': ['console'],\n 'level': 'NOTSET',\n },\n 'django.request': {\n 'handlers': ['mail_admins', 'console', 'SysLog'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'hydra': {\n 'handlers': ['console', 'SysLog'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'bsd': {\n 'handlers': ['console', 'SysLog'],\n 'level': 'DEBUG',\n 'propagate': True,\n }\n },\n}\n","sub_path":"hydra/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"389863658","text":"import torch\nimport math\n\n\n###########-----------------DMOG------------------############################\n\ndef evaluate_mog_at_action(mog_pi, mog_mu, mog_sigma, actions):\n assert mog_pi.shape[0] == actions.shape[0]\n\n batch_size = mog_pi.shape[0]\n num_gaussian = mog_pi.shape[1]\n\n # Expand actions into (batch_size, N, 1).\n action_index = actions[..., None].expand(batch_size, num_gaussian, 1)\n\n # Calculate quantile values at specified actions.\n mog_pi_sa = mog_pi.gather(dim=2, index=action_index)\n mog_mu_sa = mog_mu.gather(dim=2, index=action_index)\n mog_sigma_sa = mog_sigma.gather(dim=2, index=action_index)\n\n return mog_pi_sa, mog_mu_sa, mog_sigma_sa\n\n\ndef cdf_gauss(x, mu, sigma):\n return 0.5 * (1 + torch.erf((x - mu) / (torch.sqrt(torch.tensor(2.0)) * sigma)))\n\n\ndef calculate_dmog_loss(pi, mu, sigma,\n tar_pi, tar_mu, tar_sigma,\n eta, beta, delta,\n weight):\n dmog_loss = 0\n\n # cramer distance\n\n return dmog_loss\n\n\n# ======================================\n# From ICLR paper: A Distributional Perspective on Actor-Critic Framework\n# ======================================\n\ndef _sqdiff(mu1, sig1, w1, mu2, sig2, w2):\n _mu = torch.abs(mu1.unsqueeze(1) - mu2.unsqueeze(2))\n _var = sig1.unsqueeze(1).pow(2) + sig2.unsqueeze(2).pow(2)\n mu = (torch.sqrt(_var * 2 / math.pi)\n * torch.exp(-_mu.pow(2) / (2 * _var + 1e-8))\n + _mu * torch.erf(_mu / (torch.sqrt(2 * _var) + 1e-8)))\n d = mu\n summ = w1.unsqueeze(1) * w2.unsqueeze(2) * d\n return summ.sum(-1).sum(-1, keepdim=True)\n\n\ndef Cramer(mu1, sig1, w1, mu2, sig2, w2):\n mu2 = mu2.detach()\n sig2 = sig2.detach()\n w2 = w2.detach()\n loss = (2 * _sqdiff(mu1, sig1, w1, mu2, sig2, w2)\n - _sqdiff(mu1, sig1, w1, mu1, sig1, w1)\n - _sqdiff(mu2, sig2, w2, mu2, sig2, w2))\n return loss\n\n\ndef huber_quantile_loss(input, target, quantiles):\n n_quantiles = quantiles.size(-1)\n diff = target.unsqueeze(2) - input.unsqueeze(1)\n taus = quantiles.unsqueeze(-1).unsqueeze(1)\n taus = taus.expand(-1, n_quantiles, -1, -1)\n loss = diff.pow(2) * (taus - (diff < 0).float()).abs()\n return loss.squeeze(3).sum(-1).mean(-1)\n\n\ndef sample_cramer(samples1, samples2):\n d = (2 * _sqdiff_sample(samples1, samples2)\n - _sqdiff_sample(samples1, samples1)\n - _sqdiff_sample(samples2, samples2))\n return d\n\n\ndef _sqdiff_sample(samples1, samples2):\n assert samples1.size() == samples2.size()\n assert len(samples1.size()) == 2\n diff = samples1.unsqueeze(1) - samples2.unsqueeze(2)\n return diff.abs().mean(-1, keepdim=True)\n","sub_path":"DMoGDiscrete/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"113987869","text":"\ndef mutate (item, residue_indices=None, to_residue_names=None, engine='PDBFixer', verbose=False):\n\n if engine==\"PDBFixer\":\n if syntaxis==\"PDBFixer\":\n\n if not hasattr(residue_indices, '__iter__'):\n residue_indices = [residue_indices]\n if not hasattr(to_residue_names, '__iter__'):\n to_residue_names = [to_residue_names]\n\n form_in = _get_form(item)\n tmp_item = _convert(item, \"pdbfixer.PDBFixer\")\n\n for residue_index, to_residue_name in zip(residue_indices, to_residue_names):\n\n from_residue_name = _get(tmp_item, element='residue', index=residue_index,\n residue_name=True)\n\n in_chain_id = _get(tmp_item, element='residue', index=residue_index,\n chain_id=True)\n\n mutation_string = \"-\".join([from_residue_name,str(residue_index),to_residue_name])\n if verbose: print(mutation_string)\n tmp_item.applyMutations([mutation_string], in_chain_id)\n\n tmp_item = _convert(tmp_item, form_in)\n\n return tmp_item\n\n else:\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n","sub_path":"molmodmt/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"301062893","text":"from bs4 import BeautifulSoup\nimport requests\n\nfrom lesson_16.currency import currency\n\n\nclass ObmenkaPoint:\n __URL = 'https://obmenka.od.ua/'\n __NAME = 'ObmenkaPoint'\n\n def __get_html(self):\n response = requests.get(self.__URL)\n return response.text\n\n def get_name(self):\n return self.__NAME\n\n def get_currency_rate(self):\n currency_rate = {\n 'rate': []\n\n }\n\n html = self.__get_html()\n soup = BeautifulSoup(html, 'lxml')\n\n contents = soup.find_all('li', class_='currencies__block')\n for line in contents:\n currency_name = line.find('span', class_='currencies__block-name').text\n if not currency_name.upper().endswith('/UAH') or currency_name[:3].lower() not in currency:\n continue\n\n currency_name = currency.get(currency_name[:currency_name.find('/')].lower())\n purchase = (\n line.\n find('span', class_='currencies__block-buy').\n find('div', class_='currencies__block-num').\n text.strip()\n )\n\n sale = (\n line.\n find('span', class_='currencies__block-sale').\n find('div', class_='currencies__block-num').\n text.strip()\n )\n\n currency_rate['rate'].append(\n {\n 'currency': currency_name,\n 'purchase_rate': str(round(float(purchase), 2)),\n 'sale_rate': str(round(float(sale), 2))\n }\n )\n\n return currency_rate\n\n\nif __name__ == '__main__':\n bank = ObmenkaPoint()\n print(bank.get_currency_rate())","sub_path":"lesson_16/obmenka.py","file_name":"obmenka.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"621236251","text":"#https://www.dataquest.io/blog/web-scraping-tutorial-python/\n\nimport requests\nimport bs4\nfrom morphological import getwords\n\n#URLからページをスクレイプする\nres = requests.get('https://gunosy.com/articles/aC2GF')\nres.raise_for_status()\n\n#Titleを取り出す\nsoup = bs4.BeautifulSoup(res.text, \"html.parser\")\n#print (soup.title)\n\n#h2タグを取り出す\n#print (soup.prettify())\n\nw = ()\nfor i in soup.find_all('p'):\n word = getwords(i.get_text())\n w += word\nprint (w)\n\n'''\ntext_box = soup.find('', attr={ \"data-gtm\":\"article_media\"})\nprint (text_box)\n'''\n","sub_path":"ArticleCategolize/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"417956089","text":"\"\"\"studentmanager URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/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\"\"\"\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.views import LogoutView, LoginView\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'studentmanager'\nurlpatterns = [\n path('', views.IndexView.as_view(), name='index'),\n path('student/', login_required(views.StudentListView.as_view()), name='student'),\n path('student//delete/', login_required(views.StudentDeleteView.as_view()), name='student-delete'),\n path('student/add/', login_required(views.StudentCreateView.as_view()), name='add'),\n path('exam/', login_required(views.ExamListView.as_view()), name='exam'),\n path('exam/add/', login_required(views.ExamCreateView.as_view()), name='exam-add'),\n path('exam//delete/', login_required(views.ExamDeleteView.as_view()), name='exam-delete'),\n path('result/', login_required(views.ResultListView.as_view()), name='result'),\n path('result/add/', login_required(views.ResultCreateView.as_view()), name='result-add'),\n path('result///delete', login_required(views.ResultDeleteView.as_view()),\n name='result-delete'),\n path('login/', LoginView.as_view(), {'next_page': settings.LOGIN_REDIRECT_URL}, name='login'),\n path('logout/', LogoutView.as_view(), {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout'),\n]\n","sub_path":"studentmanager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"212447503","text":"#!/usr/bin/env python\n#\n# Run me as follows:\n# cd tests/\n# nosetests\n\nfrom nose.tools import assert_raises\nfrom types import ModuleType\nimport numpy.testing as npt\nimport os\n\n# Msaf imports\nimport msaf\nfrom msaf.features import Features\n\n# Global vars\naudio_file = os.path.join(\"fixtures\", \"chirp.mp3\")\nlong_audio_file = os.path.join(\"..\", \"datasets\", \"Sargon\", \"audio\",\n \"01-Sargon-Mindless.mp3\")\nfake_module_name = \"fake_name_module\"\n\n\ndef test_get_boundaries_module():\n # Check that it returns modules for all the existing MSAF boundaries algos\n bound_ids = msaf.io.get_all_boundary_algorithms()\n for bound_id in bound_ids:\n bound_module = msaf.run.get_boundaries_module(bound_id)\n assert isinstance(bound_module, ModuleType)\n\n # Check that \"gt\" returns None\n assert msaf.run.get_boundaries_module(\"gt\") is None\n\n # Check that a AttributeError is raised when calling it with non-existent\n # boundary id\n assert_raises(RuntimeError,\n msaf.run.get_boundaries_module, fake_module_name)\n\n # Check that a RuntimeError is raised when calling it with invalid\n # boundary id\n assert_raises(RuntimeError,\n msaf.run.get_boundaries_module, \"fmc2d\")\n\n\ndef test_get_labels_module():\n # Check that it returns modules for all the existing MSAF boundaries algos\n label_ids = msaf.io.get_all_label_algorithms()\n for label_id in label_ids:\n label_module = msaf.run.get_labels_module(label_id)\n assert isinstance(label_module, ModuleType)\n\n # Check that None returns None\n assert msaf.run.get_labels_module(None) is None\n\n # Check that a AttributeError is raised when calling it with non-existent\n # labels id\n assert_raises(RuntimeError,\n msaf.run.get_labels_module, fake_module_name)\n\n # Check that a RuntimeError is raised when calling it with invalid\n # labels id\n assert_raises(RuntimeError,\n msaf.run.get_labels_module, \"foote\")\n\n\ndef test_run_algorithms():\n \"\"\"Test running all the algorithms.\"\"\"\n bound_ids = msaf.io.get_all_boundary_algorithms()\n label_ids = msaf.io.get_all_label_algorithms()\n\n # Add ground truth to boundary id\n bound_ids += [\"gt\"]\n\n # Add None to labels\n label_ids += [None]\n\n # Config params\n feature = \"pcp\"\n annot_beats = False\n framesync = False\n file_struct = msaf.io.FileStruct(audio_file)\n file_struct.features_file = msaf.config.features_tmp_file\n\n # Running all algorithms on a file that is too short\n for bound_id in bound_ids:\n for label_id in label_ids:\n config = msaf.io.get_configuration(feature, annot_beats, framesync,\n bound_id, label_id)\n config[\"hier\"] = False\n config[\"features\"] = Features.select_features(\n feature, file_struct, annot_beats, framesync)\n est_times, est_labels = msaf.run.run_algorithms(\n file_struct, bound_id, label_id, config)\n assert len(est_times) == 2\n assert len(est_labels) == 1\n npt.assert_almost_equal(est_times[0], 0.0, decimal=2)\n npt.assert_almost_equal(est_times[-1], config[\"features\"].dur,\n decimal=2)\n\n # Commpute and save features for long audio file\n file_struct = msaf.io.FileStruct(long_audio_file)\n file_struct.features_file = msaf.config.features_tmp_file\n\n def _test_run_msaf(bound_id, label_id, hier=False):\n config = msaf.io.get_configuration(feature, annot_beats, framesync,\n bound_id, label_id)\n config[\"hier\"] = hier\n config[\"features\"] = Features.select_features(\n feature, file_struct, annot_beats, framesync)\n est_times, est_labels = msaf.run.run_algorithms(\n file_struct, bound_id, label_id, config)\n\n # Take the first level if hierarchy algorithm\n if hier:\n est_times = est_times[0]\n est_labels = est_labels[0]\n\n npt.assert_almost_equal(est_times[0], 0.0, decimal=2)\n assert len(est_times) - 1 == len(est_labels)\n npt.assert_almost_equal(est_times[-1], config[\"features\"].dur,\n decimal=2)\n\n # Running all boundary algorithms on a relatively long file\n for bound_id in bound_ids:\n if bound_id == \"gt\":\n continue\n yield (_test_run_msaf, bound_id, None, False)\n\n # Combining boundaries with labels\n for bound_id in bound_ids:\n if bound_id == \"gt\":\n continue\n for label_id in label_ids:\n yield (_test_run_msaf, bound_id, label_id, False)\n\n # Test the hierarchical algorithms\n hier_ids = [\"olda\", \"scluster\"]\n for hier_id in hier_ids:\n yield (_test_run_msaf, hier_id, None, True)\n","sub_path":"tests/test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"154388546","text":"import pymysql,time,datetime\n\nclass Mysql:\n\n\tconn = None\n\tcursor = None\n\n\tdef __init__(self):\n\t\tif self.conn ==None:\n\t\t\tself.conn = pymysql.connect(host=\"gisgeo-m.dbsit.sfdc.com.cn\",port=3306,user='gisgeo',passwd='Onywij3NM5',db='gisgeo',charset='utf8')\n\t\t\tself.cursor = self.conn.cursor(pymysql.cursors.DictCursor)\n\n\n\tdef __del__(self):\n\t\tif self.cursor:\n\t\t\tself.cursor.close()\n\t\tif self.conn:\n\t\t\tself.conn.close()\n\n\n\tdef get(self,uid=0):\n\t\tsql='select * from tb_geo_white_address where uid=%s' % uid\n\t\tn = self.cursor.execute(sql)\n\t\tdata = self.cursor.fetchall(sql)\n\t\tuserinfo = []\n\t\tfor info in data:\n\t\t\tif info['addtime']:\n\t\t\t\tinfo['addtime'] = info['addtime'].strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\tif info['modtime']:\n\t\t\t\tinfo['modtime'] = info['modtime'].strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\tuserinfo.append(info)\n\t\treturn userinfo[0]\n\n\tdef add(self,params={}):\n\t\tuid = int(time.time())\n\t\tsql='insert into user_info set uid=%s' % str(uid)\n\t\tfor k,v in params.items():\n\t\t\tsql += ',`%s`=\"%s\"' % (k,v)\n\t\tsql = sql.rstrip(',')\n\t\tsql += \",`modtime`='%s' \" % (time.strftime('%Y-%m-%d %H:%M:%S'),)\n\t\tn = self.cursor.execute(sql)\n\t\tself.conn.commit()\n\t\tif n>0:\n\t\t\ttime.sleep(1)\n\t\t\treturn uid\n\t\telse:\n\t\t\treturn 0\n\n\tdef set(self,uid,params):\n\t\tif len(params)==0:\n\t\t\treturn False\n\t\tsql='update user_info set'\n\t\tfor k,v in params.items():\n\t\t\tsql += ' `%s`=\"%s\",' % (k,v)\n\t\tsql = sql[:-1]\n\t\t#print sql\n\t\tsql += \",`modtime`='%s' where uid=%s\" % (time.strftime('%Y-%m-%d %H:%M:%S'),uid)\n\t\tn = self.cursor.execute(sql)\n\t\tself.conn.commit()\n\t\treturn True\n\n\tdef delete(self,uid=0):\n\t\tsql='delete from user_info where uid=%s' % uid\n\t\tn = self.cursor.execute(sql)\n\t\tself.conn.commit()\n\t\treturn True\n","sub_path":"lib/mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"503814445","text":"import sys\n\nimport cv2\n\nclass Get_face:\n\n def __init__(self):\n self.flag = True#用于判断摄像机的使用权在不在后台\n super()\n\n \n\n\n def CatchPICFromVideo(self ,path_name, window_name=\"GET_FACE\", camera_idx=0, catch_pic_num=100):\n cv2.namedWindow(window_name)\n\n # 视频来源,可以来自一段已存好的视频,也可以直接来自USB摄像头\n cap = cv2.VideoCapture(camera_idx)\n\n # 告诉OpenCV使用人脸识别分类器\n classfier = cv2.CascadeClassifier(\"/home/lwl/code/python/opencv/face_rec/haarcascade_frontalface_default.xml\")\n\n # 识别出人脸后要画的边框的颜色,RGB格式\n\n color = (0, 255, 0)\n\n num = 1\n last = 1\n while cap.isOpened():\n ok, frame = cap.read() # 读取一帧数据\n if not ok:\n break\n\n grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 将当前桢图像转换成灰度图像\n\n # 人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数\n faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\n if len(faceRects) > 0: # 大于0则检测到人脸\n count =0\n for faceRect in faceRects: # 单独框出每一张人脸\n count = count+1\n x, y, w, h = faceRect\n\n # 将当前帧保存为图片\n img_name = '%s/%d.jpg' % (path_name, num)#踩坑,对文件重命名时,最后一个空格也算作字符\n image = frame[y - 10 : y + h + 10, x - 10 : x + w + 10]\n\n #print(image.shape) #打印图片形状\n\n\n cv2.imwrite(img_name, image)\n num += 1\n if num > (catch_pic_num): # 如果超过指定最大保存数量退出循环\n break\n print(\"the index of the picture \" + str(num))\n if False:\n # 画出矩形框\n cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)\n\n # 显示当前捕捉到了多少人脸图片了,这样站在那里被拍摄时心里有个数,不用两眼一抹黑傻等着\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame, 'num:%d' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4)\n\n # 超过指定最大保存数量结束程序\n if num > (catch_pic_num): \n break\n\n # 显示图像\n cv2.imshow(window_name, frame)\n c = cv2.waitKey(10)\n if c & 0xFF == ord('q'):\n break\n\n # 释放摄像头并销毁所有窗口\n cap.release()\n cv2.destroyAllWindows()\n\n def sendMessage(self, name=\"某人\"):\n pritn('发送消息给用户有人来啦'+ name) \n\n\nif __name__ == '__main__':\n c = Get_face()\n c.CatchPICFromVideo('/home/lwl/code/python/opencv/face_rec/data/other')","sub_path":"get_facePic.py","file_name":"get_facePic.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"293994910","text":"file = open('A-large.in')\r\nlines = file.readlines()\r\n\r\nt = int(lines[0])\r\n\r\nfor i in range(0, int(t)):\r\n var = 0\r\n \r\n\r\n listNums = [0,1,2,3,4,5,6,7,8,9]\r\n number = lines[1 + i]\r\n number = number.strip()\r\n \r\n x = 0\r\n ogNumber = number\r\n if number == \"0\":\r\n var = \"INSOMNIA\"\r\n print('Case #{}: {}'.format(i+1, var))\r\n continue\r\n \r\n while listNums:\r\n x += 1\r\n number = int(ogNumber) * x\r\n ch = 0\r\n ch = int(ch)\r\n \r\n for ch in list(map(int, str(number))):\r\n try:\r\n listNums.remove(ch)\r\n var += 1\r\n except:\r\n pass\r\n if listNums == []:\r\n var = number\r\n \r\n print('Case #{}: {}'.format(i+1, var))\r\n \r\n\r\n '''\r\n while listNums:\r\n\r\n x += 1\r\n ch = 0\r\n ch = int(ch)\r\n for ch in list(map(int, str(x * number))):\r\n try:\r\n listNums.remove(int(ch))\r\n var += 1\r\n except:\r\n pass\r\n'''\r\n # print('Case #{}: {}'.format(i+1, var))\r\n'''\r\n\r\n z = int(z)\r\n number = 1234\r\n for z in str(number):\r\n print(z)\r\n x += 1\r\n for lel in str(int(z) * int(x)):\r\n #for each digit in int(z) * int(x) remove!\r\n try:\r\n listNums.remove(int(lel))\r\n var += 1\r\n except:\r\n pass\r\n\r\n'''\r\n\r\n \r\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_dsg2806_QUALONE.py","file_name":"16_0_1_dsg2806_QUALONE.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"282201179","text":"from flask import Flask\nfrom flask import jsonify\nfrom time import sleep\nfrom threading import Thread\nimport aiming_controller as ac\nimport os\napp = Flask(__name__)\naiming = ac.AimingController(0.1, 0.2)\n\n@app.route(\"/\", methods=[\"POST\"])\ndef handle_numbers(numbers):\n\tresult = {}\n\t\n\ttry:\n\t\tint(numbers)\n\texcept ValueError:\n\t\tresult = {\"result\" : \"invalid input\"}\n\t\treturn jsonify(result)\n\t\n\tif not check_valid_numbers(numbers):\n\t\tresult = {\"result\" : \"invalid set of numbers\"}\n\t\treturn jsonify(result)\n\t\n\tif aiming.is_busy():\n\t\tresult = {\"result\" : \"busy\"}\n\t\t\n\telse:\n\t\taiming.start_aiming(numbers)\n\t\tresult = {\"result\" : \"success\"}\n\t\n\treturn jsonify(result)\n\t\ndef check_valid_numbers(numbers):\n\tcounter = 0\n\tfor i in numbers:\n\t\tif int(i) == 8:\n\t\t\tcounter += 1\n\t\n\tif counter >=3:\n\t\treturn False\n\telse:\n\t\treturn True\n\t\n\t\t\nif __name__ == \"__main__\":\n\tapp.run(host=\"0.0.0.0\")\n\n","sub_path":"servo_controller_fast.py","file_name":"servo_controller_fast.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"124969254","text":"from flask import Flask, render_template, request, url_for, redirect, session\nimport os # only needed if session being used\n\n\napp = Flask(__name__)\napp.secret_key = os.urandom(24)\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n return render_template(\"landing.html\")\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef login():\n # user is coming here from a post request\n if request.method == \"POST\":\n # extract the value entered into the email field\n email = request.form[\"email\"]\n # some logic here - database ?\n # send page back with data inserted\n return render_template(\"landing.html\", username = email)\n else:\n return render_template(\"login.html\")\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"flask_template.py","file_name":"flask_template.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"65609085","text":"from .models import ExtraInfo\nfrom django import forms\nfrom django.forms import ModelForm\nimport re\n\nRGX_NUMBER = re.compile(r\"(?:\\+234)?(?:070|080|081|090)\\d{8}\")\n\ndef validate_number(value):\n if not RGX_NUMBER.match(value):\n raise forms.ValidationError('Please enter a valid phone number')\n\nclass NigerianField(forms.CharField):\n \"\"\"\n A CharField that allows only nigerian phone numbers\n \"\"\"\n\n default_validators = [validate_number]\n\n def __init__(self, *args, **kwargs):\n super(NigerianField, self).__init__(\n min_length=11,\n max_length=15,\n error_messages={\n \"required\": \"You need to set this number field\",\n \"min_length\": \"Your phone number is too short\",\n \"max_length\": \"Your phone number is too big\",\n }\n )\n\n\nclass ExtraInfoForm(ModelForm):\n \"\"\"\n The fields on this form are derived from the ExtraInfo model in models.py.\n \"\"\"\n \n number = forms.CharField(validators=[validate_number], help_text=\"Phone number\",\n widget=forms.TextInput(attrs={'placeholder':'Phone number'}),\n label='Phone number')\n \n code = forms.CharField(help_text=\"Enter your registration code\",\n widget=forms.TextInput(attrs={'placeholder':'0000'}),\n label='code', required=False)\n \n def __init__(self, *args, **kwargs):\n super(ExtraInfoForm, self).__init__(*args, **kwargs)\n self.fields['number'].error_messages = {\n \"required\": u\"Please give us your number.\",\n \"invalid\": u\"Please use a valid nigerian phone number.\",\n }\n \n\n class Meta(object):\n model = ExtraInfo\n fields = ('number', 'code')\n labels = {'number':'Mobile phone number'}\n","sub_path":"custom_reg_form/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"540561800","text":"import numpy as np\n\nfrom idbd_bio_utils import NcbiTaxonomy\n\nclass SampleCompParser(object):\n def __init__(self, sample_composition_path, ncbi_tax=None,\n ctrl_taxa=None):\n if ncbi_tax is None:\n self.ncbi_tax = NcbiTaxonomy()\n else:\n self.ncbi_tax = ncbi_tax\n if isinstance(ctrl_taxa, list):\n if not all([isinstance(taxid, int) for taxid in ctrl_taxa]):\n raise ValueError('ctrl_taxa must be int or list of ints.')\n self.ctrl_taxa = ctrl_taxa\n elif isinstance(ctrl_taxa, int):\n self.ctrl_taxa = list(ctrl_taxa)\n else:\n raise ValueError('ctrl_taxa must be int or list of ints.')\n self.composition_dict = self._load_sample_composition(\n sample_composition_path)\n self.total_reads = np.sum(list(self.composition_dict.values()))\n self.organism_counts = self._get_organism_counts()\n\n def _load_sample_composition(self, sample_composition_path):\n with open(sample_composition_path) as infile:\n composition_dict = {}\n for line in infile:\n data = line.strip().split('\\t')\n composition_dict.update({int(data[0]): int(data[1])})\n return composition_dict\n\n def _get_organism_counts(self):\n human_taxid = 9606\n bacteria_taxid = 2\n virus_taxid = 10239\n eukaryota_taxid = 2759\n parasite_taxids = {\n 7563,\n 188941,\n 6029,\n 5653,\n 6935,\n 6178,\n 5794,\n 6308,\n 31277,\n 119088,\n 6199,\n 85819,\n 33083,\n 33084,\n 75966,\n 41165,\n 7509,\n 6236,\n 198624,\n 33634,\n 5988,\n 6249,\n 5738,\n 1489900,\n 740972,\n 1485168,\n 37104,\n 10232\n }\n fungus_taxid = 4751\n\n human_count = 0\n bacteria_count = 0\n virus_count = 0\n parasite_count = 0\n fungus_count = 0\n unclassified_count = 0\n for taxid, count in self.composition_dict.items():\n if taxid in self.ctrl_taxa:\n continue\n taxid_path = self.ncbi_tax.get_path(taxid)\n if human_taxid in taxid_path:\n human_count += count\n elif fungus_taxid in taxid_path:\n fungus_count += count\n elif parasite_taxids.intersection(set(taxid_path)) != set():\n parasite_count += count\n elif bacteria_taxid in taxid_path:\n bacteria_count += count\n elif virus_taxid in taxid_path:\n virus_count += count\n else:\n unclassified_count += count\n count_dict = {\n 'human': human_count,\n 'bacteria': bacteria_count,\n 'virus': virus_count,\n 'parasite': parasite_count,\n 'fungus': fungus_count,\n 'unclassified': unclassified_count\n }\n return count_dict\n\n def get_total_reads(self):\n return self.total_reads\n\n def get_taxid_reads(self, taxid):\n if not isinstance(taxid, int):\n try:\n taxid = int(taxid)\n except:\n raise ValueError('taxid must be int')\n if taxid not in self.composition_dict:\n reads = 0\n else:\n reads = self.composition_dict[taxid]\n return reads\n\n def get_taxid_nr(self, taxid, normalizer=1e7):\n if not isinstance(taxid, int):\n try:\n taxid = int(taxid)\n except:\n raise ValueError('taxid must be int')\n if taxid not in self.composition_dict:\n nr = 0\n else:\n nr = normalizer * self.composition_dict[taxid] / self.total_reads\n return nr\n\n def get_org_comp_abs(self):\n return self.organism_counts\n\n def get_org_comp_rel(self):\n count_dict = {}\n for org, count in self.organism_counts.items():\n count_dict.update({org: 100 * count / self.total_reads})\n return count_dict\n\n def get_org_comp_nr(self, normalizer=1e7):\n count_dict = {}\n for org, count in self.organism_counts.items():\n count_dict.update({org: normalizer * count / self.total_reads})\n return count_dict\n","sub_path":"20200214_extraction_comparison/sample_composition_utils.py","file_name":"sample_composition_utils.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"141806372","text":"from tasks import Takeoff, Hover\nfrom agents import DeepDPGAgent\n\nfrom helpers import learn_agent\n\n# Setup learning parameters\nDeepDPGAgent.tau = 0.01\nDeepDPGAgent.gamma = 0.99\nDeepDPGAgent.learning_rate = 0.0001\nDeepDPGAgent.batch_size = 64\n\n# Create task and agent\n# task = Takeoff()\ntask = Hover(simplified=True)\ntask.task_name = 'emulate_' + task.task_name\n\nagent = DeepDPGAgent(task, batch_size=128)\n\nnum_episodes = 2000\n\n\nlearn_agent(20, agent, task, log_episode_every=10)","sub_path":"test_learn.py","file_name":"test_learn.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"336181192","text":"from flask import (Flask, render_template, redirect, request, flash,\n session, jsonify)\nfrom templates.__init__ import app\nfrom templates.begin.views import hello_blueprint, oauth, auth0, requires_auth\n\nimport math\nimport time\nimport json\nimport random\nimport string\nimport datetime\nimport threading\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import (update, asc, desc)\nfrom model import User, Contact, AlertSet, Alert, CheckIn, ReqCheck, connect_to_db, db\nimport requests\nimport logging\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///besafe'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\ndb = SQLAlchemy()\ndb.app = app\n\ndb.init_app(app)\n\n# Required to use Flask sessions and the debug toolbar\napp.secret_key = \"ABC\"\n\n# Causes error messages for undefined variables in jinja\napp.jinja_env.undefined = StrictUndefined\n\n\n################################################################\n\n@app.route('/callback')\ndef callback_handling():\n # Handles response from token endpoint\n auth0.authorize_access_token()\n resp = auth0.get('userinfo')\n userinfo = resp.json()\n # Store the user information in flask session.\n session['jwt_payload'] = userinfo\n session['profile'] = {\n 'user_id': userinfo['sub'],\n 'name': userinfo['name'],\n 'picture': userinfo['picture'],\n 'email': userinfo['email']\n }\n\n #Sets the 'current_user' value in the session to the user's e-mail\n session['current_user'] = userinfo['email']\n\n #User Table is Queried to see if User already exists in dB\n user = User.query.filter_by(email=userinfo['email']).all()\n \n #If the user isn't in the dBase, they are added\n if user == []:\n new_user = User(name=userinfo['name'], email=userinfo['email'], username=userinfo['nickname'], fname=userinfo['given_name'], lname=userinfo['family_name'], created_at=datetime.datetime.now())\n db.session.add(new_user)\n \n #The dBase changes are committed\n db.session.commit()\n\n #Redirects to the User Profile\n return redirect('/')\n\n\n@app.route(\"/logout\")\ndef logout():\n \"\"\"Logs user out and deletes them from the session (Tested)\"\"\"\n\n # Clear session stored data\n session.clear\n\n # Redirect user to logout endpoint\n params = {'returnTo': url_for('go_home', _external=True), 'client_id': '78rUTjeVusqU3vYXyvNpOQiF8jEacf55'}\n return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))\n\n#################################################################\nif __name__ == '__main__':\n app.config.from_object('configurations.DevelopmentConfig')\n app.run()","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"420306775","text":"'''\n\n2016-10-21\n\n对应 v4_statistics.py 代码\n\n将此大程序拆分成几个小程序\n\n'''\n\n#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n#======================================================================\n\n#========== 1. 所 选 某 钢 种 占 全 部 钢 种 的 比 例 ============\n\n#========== 2. 结 论 输 出 =======================================\n\n#======================================================================\n#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n#from sys import argv \n#script, filename = argv \n\nfrom . import input_\nfrom . import sql_space\nfrom . import sql_time\nfrom . import sql_trade\nfrom . import sql_customer\nfrom . import sql_customer2\nfrom . import max_min_average\nfrom . import conclusion\nfrom . import save_txt\nimport math\nfrom functools import reduce\nfrom . import mysql\nconn_mysql=mysql.MySQL();\n\n\ndef sql_market_share(startYear,startMonth,endYear,endMonth):\n #========================【 输 入 】===========================\n #获取数据\n #print (\"开始执行 market_share_sql 函数\")\n sql_province = \"select a.province,sum(a.salesWeight),sum(a.qdisSalesWeight),(sum(a.qdisSalesWeight)/sum(a.salesWeight))*100 from data_new_sales_space_comparsion a where a.year >= \" + startYear + \" and a.year <= \" + endYear + \" and a.month >= \" + startMonth + \" and a.month <= \" + endMonth + \" group by a.province\"\n\n province_salesWeight_list = conn_mysql.select(sql_province) #得到的是一个tuple\n #print (type(province_salesWeight_list))\n print (province_salesWeight_list)\n\n ratio_dictionary = {}\n salesWeight_dictionary = {}\n qdisSalesWeight_dictionary = {}\n all_list = []\n conclusion_province = \"\"\n conclusion = startYear + \"年\" + startMonth + \"月至\" + startYear + \"年\" + startMonth + \"月内,全国各省份市场容量及占比如下:\\n\"\n for province_salesWeight in province_salesWeight_list: #所选钢种\n ratio_dictionary[province_salesWeight[0]] = float(province_salesWeight[3])\n salesWeight_dictionary[province_salesWeight[0]] = float(province_salesWeight[1])\n qdisSalesWeight_dictionary[province_salesWeight[0]] = float(province_salesWeight[2])\n all_list.append([province_salesWeight[0],float(province_salesWeight[1]),float(province_salesWeight[2]),float(province_salesWeight[3])])\n conclusion_province = province_salesWeight[0] + \"省市场容量为:\" + str(province_salesWeight[1]) + \"吨,我公司在该省销量为:\" + str(province_salesWeight[2]) + \"吨,占比:\" + str(province_salesWeight[3]) + \" %。\\n\"\n conclusion = conclusion + conclusion_province\n print (\"比例字典:\\n\",ratio_dictionary)\n print (\"\\n\")\n print (\"市场容量字典:\\n\",salesWeight_dictionary)\n print (\"\\n\")\n print (\"青钢销量字典:\\n\",qdisSalesWeight_dictionary)\n print (\"\\n\")\n print (\"全部信息列表:\\n\",all_list)\n print (\"\\n\")\n\n all_dictionary = {'全部信息list': all_list,'比例字典': ratio_dictionary,'市场容量字典': salesWeight_dictionary,'青钢销量字典': qdisSalesWeight_dictionary}\n print (all_dictionary)\n print (\"\\n\")\n print (\"结论:\\n\",conclusion)\n print (\"\\n\")\n\n return ratio_dictionary,conclusion,all_dictionary\n\n\n\n\n\nif __name__ == '__market_share_sql__':\n\n ratio_dictionary,conclusion,all_dictionary = sql_market_share(startYear,startMonth,endYear,endMonth)\n #print(\"market_share_sql.py 执行完毕\")\n #print (module,tradeNo)\n\n\n\n\n\n\n\n\n","sub_path":"data_import/liusinuo/sql_market_share.py","file_name":"sql_market_share.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"563492631","text":"# pylint: disable=import-error\nimport io\nimport base64\nfrom PIL import Image\n\n# pylint: enable=import-error\n\nDATA_URL_PREFIX = \"data:image/jpeg;base64,\"\n\n\ndef image_to_bytes(img):\n stream = io.BytesIO()\n img.save(stream, \"JPEG\")\n return stream.getvalue()\n\n\ndef image_to_base64(img, prefix=\"\"):\n bytes_ = image_to_bytes(img) if type(img) is not bytes else img\n return prefix + str(base64.b64encode(bytes_), \"utf-8\")\n\n\ndef base64_to_image(bytes_):\n bytes_ = bytes_.split(\",\")[-1] # Remove the dataurl prefix\n decoded = base64.b64decode(bytes_)\n return bytes_to_image(decoded)\n\n\ndef bytes_to_image(bytes_):\n img = Image.open(io.BytesIO(bytes_))\n img.verify()\n img = Image.open(io.BytesIO(bytes_)).convert(\"RGB\")\n return img\n\n\ndef bytes_to_bytesIO(bytes_):\n img = Image.open(io.BytesIO(bytes_))\n img.verify()\n return io.BytesIO(bytes_)\n\n\ndef base64_to_bytesIO(bytes_):\n bytes_ = bytes_.split(\",\")[-1] # Remove the dataurl prefix\n decoded = base64.b64decode(bytes_)\n return bytes_to_bytesIO(decoded)\n\n\ndef decode_image(src):\n if type(src) is bytes:\n return bytes_to_image(src)\n return base64_to_image(src)\n\n\ndef resize_image(image, max_dim=1800):\n w, h = image.size\n if w > h:\n ratio = max_dim / w\n w = max_dim\n h = int(h * ratio)\n else:\n ratio = max_dim / h\n h = max_dim\n w = int(w * ratio)\n return image.resize([w, h])\n\n","sub_path":"utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"344369935","text":"import logging; logger = logging.getLogger(\"morse.\" + __name__)\nfrom morse.core.sensor import Sensor\nfrom morse.helpers.components import add_data, add_property\nfrom morse.core import blenderapi\n\nclass Collision(Sensor):\n \"\"\"\n Sensor to detect objects colliding with the current object,\n with more settings than the Touch sensor\n \"\"\"\n _name = \"Collision\"\n _short_desc = \"Detect objects colliding with the current object.\"\n\n add_data('collision', False, \"bool\", \"objects colliding with the current object\")\n add_data('objects', \"\", \"string\", \"A list of colliding objects.\")\n\n # These properties are not used directly in the logic, but are used\n # in the builder to create the radar properly.\n # These value cannot be changed dynamically in bge.\n add_property('_collision_property', \"\", 'collision_property', 'string',\n 'Only look for objects with this property, '\n 'default \"\" (all objects)')\n\n def __init__(self, obj, parent=None):\n \"\"\" Constructor method.\n\n Receives the reference to the Blender object.\n The second parameter should be the name of the object's parent.\n \"\"\"\n logger.info('%s initialization' % obj.name)\n # Call the constructor of the parent class\n Sensor.__init__(self, obj, parent)\n\n logger.info('Component initialized, runs at %.2f Hz', self.frequency)\n\n def default_action(self):\n \"\"\" Is currently in collision \"\"\"\n controller = blenderapi.controller()\n sensor = controller.sensors[-1]\n \n # see hitObjectList and hitObject for last collided object(s)\n self.local_data['collision'] = sensor.positive\n self.local_data['objects'] = ','.join([o.name for o in sensor.hitObjectList])\n # logger.debug(self.local_data['objects'])\n","sub_path":"src/ACTR_3D/sensors/Collision.py","file_name":"Collision.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"146640011","text":"import unittest\ncase_path = r'.'\n\n\ndef get_allcase():\n discover = unittest.defaultTestLoader.discover(case_path, pattern=\"*test*.py\")\n suite = unittest.TestSuite()\n suite.addTest(discover)\n return suite\n\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(get_allcase())\n\n\n\n\n\n\n","sub_path":"unitrun/suite_run.py","file_name":"suite_run.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"537646449","text":"import sys\nimport serial\nimport string\nimport time\nfrom serial import SerialException\n\nPORT = \"/dev/serial0\"\nBAUD_RATE = 9600\n\ndef read_data():\n\tbuf =[]\n\twhile True :\n\t\ttmp = ser.read(1)\n\t\tif tmp ==\"\\r\":\n\t\t\tbreak;\n\t\tbuf.append(tmp)\n\tres =''.join(buf)\n\tprint(\"%s pH\" % res)\n\ndef send_cmd(cmd):\n\tbuf = cmd+'\\r'\n\ttry : \n\t\tser.write(buf.encode('utf-8'))\n\texcept SerialException as e:\n\t\tprint(\"Error : \" , e)\n\ndef init():\n\tsend_cmd(\"R\")\t\n\twhile True :\n\t\ttmp = ser.read(1)\n\t\tif tmp ==\"\\r\":\n\t\t\tbreak;\n\t\nif __name__ == \"__main__\":\n\n\tprint(\"Opening Serial port\")\n\ttry : \n\t\tser = serial.Serial(PORT, BAUD_RATE, timeout=0)\n\texcept serial.SerialException as e :\n\t\tprint(\"Error : \", e)\n\t\tsys.exit(0)\n\t\n\t#Perfom a R cmd to handle the first garbage data\n\tinit()\n\n\tprint(\"1. R\" )\n\tprint(\"2. C,n\")\n\tprint(\"3. Cal\")\n\tprint(\"4. Quit\")\n\n\t# Get command\n\twhile True :\n\t\tcmd = raw_input(\"Command : \")\n\t\n\t\tif cmd == \"Quit\" :\n\t\t\tprint(\"BYE~\")\n\t\t\tbreak\n\t\telse :\n\t\t\twhatCmd = cmd.split(',')\n\t\t\tsend_cmd(cmd)\n\n\t\t\t# Cont - Reading\n\t\t\tif whatCmd[0] == \"C\" :\n\t\t\t\tprint(\"Start Reading\")\n\t\t\t\twhile True:\n\t\t\t\t\ttry :\n\t\t\t\t\t\ttime.sleep(0.8)\n\t\t\t\t\t\tread_data()\n\t\t\t\t\texcept KeyboardInterrupt :\n\t\t\t\t\t\tsend_cmd(\"C,0\")\n\t\t\t\t\t\tbreak\n\t\t\t\n\t\t\t# 1 Reading \n\t\t\telif whatCmd[0] ==\"R\" :\n\t\t\t\ttime.sleep(0.8)\n\t\t\t\tread_data()\n\n\t\t\telif whatCmd[0]==\"Cal\" :\n\t\t\t\tprint (\"Calibration done\")\n","sub_path":"UART/PH_UART.py","file_name":"PH_UART.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"160157412","text":"import numpy as np\nimport netCDF4 as ncdf\n\n#*****************************************************************************************************************\n# Module containing functions to interpolate from theta to pressure levels\n# ...and pressure to pressure levels\n# AB 2015\n\n#*****************************************************************************************************************\n\"\"\" \nINPUT(S):\nvtheta\t= variable to interpolate\nptheta = pressure on theta levels\nptarget = pressures to interpolate onto\nlats = latitudes\n\nOUTPUT(S):\nvpres\n\"\"\"\n\ndef interpolate_theta_to_p(vtheta,ptheta,ptarget,lats):\n len_ptarget = len(ptarget)\n len_ptheta = len(ptheta)\n len_lats = len(lats)\n\n # empty array for output\n vpres = np.empty([len_ptarget,len_lats])\t\t\n\n # log-pressure\n lptheta = np.log(ptheta)\n lptarget = np.log(ptarget)\n\n for ilat in range(len_lats):\n for ip in range(len_ptarget):\n for ihgt in range(len_ptheta-1):\n if ptarget[ip]ptheta[ihgt+1,ilat]:\n vpres[ip,ilat] = vtheta[ihgt,ilat] + \\\n ((lptarget[ip]-lptheta[ihgt,ilat])/(lptheta[ihgt+1,ilat]-lptheta[ihgt,ilat]))*(vtheta[ihgt+1,ilat]-vtheta[ihgt,ilat])\n\n return vpres\n\n\"\"\" \nINPUT(S):\nvpres1\t= variable to interpolate\npin = pressures to interpolate from\npout = pressures to interpolate onto\n\nOUTPUT(S):\nvpres2\n\"\"\"\n\ndef interpolate_p_to_p(vpres1,pin,pout,lats):\n len_pin = len(pin)\n len_pout = len(pout)\n len_lats = len(lats)\n\n # empty array for output\n vpres2 = np.empty([len_pout,len_lats])\t\t\n\n # log-pressure\n lpin = np.log(pin)\n lpout = np.log(pout)\n\n for ilat in range(len_lats):\n for ip in range(len_pout):\n for ihgt in range(len_pin-1):\n if pout[ip]==pin[ihgt]:\n vpres2[ip,ilat] = vpres1[ihgt,ilat]\n continue\n if pout[ip]pin[ihgt+1]:\n vpres2[ip,ilat] = vpres1[ihgt,ilat] + \\\n ((lpout[ip]-lpin[ihgt])/(lpin[ihgt+1]-lpin[ihgt]))*(vpres1[ihgt+1,ilat]-vpres1[ihgt,ilat])\n\n return vpres2\n","sub_path":"interpolate_to_plevs.py","file_name":"interpolate_to_plevs.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"17419437","text":"import requests\nimport scrapy\nfrom scrapy.http import TextResponse\nfrom datetime import datetime, timedelta\n\ndef get_urls(category='105'):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'\n }\n date = (datetime.today() - timedelta(1)).strftime('%Y%m%d')\n last_p, urls = '', []\n for page in range(1, 1000, 10):\n # 마지막 페이지로 \n url = 'https://news.naver.com/main/list.nhn?mode=LSD&mid=sec&listType=title&sid1={}&date={}&page={}'.format(category, date, page)\n req = requests.get(url, headers=headers)\n resp = TextResponse(req.url, body=req.text, encoding='utf-8')\n\n try:\n chk_next = resp.xpath('//div[@class=\"paging\"]/a[@class=\"next nclicks(fls.page)\"]/text()')[0].extract()\n except:\n chk_next = '끝'\n\n if chk_next == '끝':\n # 마지막 페이지가 여러개일때\n # 마지막 페이지가 1개일때\n pages = resp.xpath('//a[@class=\"nclicks(fls.page)\"]/text()' |\n '//div[@class=\"paging\"]/strong').extract() \n last_p = pages[-1]\n print(last_p)\n break\n\n for page in range(1, int(last_p)+1):\n urls.append('https://news.naver.com/main/list.nhn?mode=LSD&mid=sec&listType=title&sid1={}&date={}&page={}'.format(category, date, page))\n return urls","sub_path":"01_crawling/scrapy_naver_news_everyday/scrapy_naver_news_everyday/spiders/get_url_check_last_page.py","file_name":"get_url_check_last_page.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"436771061","text":"# import connection requests library\nfrom mongoDATA import MongoClient\n\n# Create a new connection to a single MongoDB instance at host:port.\nconnection = MongoClient()\n\n# Create and get a data base (db) from this connection\ndb = connection.test\n\n# Create and get a collection named \"collect\" from the data base named \"db\" from the connection named \"connection\"\ncollection = db.collect\n\n# Create an entry and insert in the collection\nage = 30\nentry = {\"Name\": \"Ralph\",\n \"Address\": \"16, Av Foch\",\n \"Age in Years\": age}\ncollection.insert(entry)\n\n# Print out the inserted entry\nprint(list(collection.find()))\n\n# close connection\nconnection.close()\n","sub_path":"untitled1/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"160133971","text":"# Write a function is_even that will return true if the passed-in number is even.\n\n# YOUR CODE HERE\n\n# Read a number from the keyboard\n\n# Print out \"Even!\" if the number is even. Otherwise print \"Odd\"\n\ndef is_even():\n '''\n Asks user for a number and prints whether it is even or odd\n '''\n\n # takes user input string\n num = input(\"Enter a number: \")\n \n # converts user input string to an int\n num = int(num)\n if num % 2 == 0:\n print(f\"{num} is an even number\")\n else:\n print(f\"{num} is an odd number\")\n\nis_even()\n","sub_path":"src/10_functions.py","file_name":"10_functions.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"190739954","text":"class Boolean_algebra:\n def __init__(self, original):\n self.original = original\n self.stack = \"\"\n self.operator = [] # contain Operator\n self.operate = [] # contain Operate\n self.operate_unique = [] # contain Operate but every element are unique\n self.original_list = [] # contain a expreesion is split already\n self.op = [\"+\", \"&\", \"!\"]\n\n def split_expreesion(self):\n self.no_space()\n Str = self.original\n\n for i, j in zip( Str, range(len(Str)) ):\n if(i == \"(\"):\n self.original_list.append(i)\n pass\n elif(i in self.op or i == \")\"): #if found \")\" or operator lets get them to that list!!\n if(i != \")\"):\n self.operator.append(i)\n\n if(len(self.stack) != 0): # for filter in case that have operator next to bracket\n self.operate.append(self.stack)\n self.original_list.append(self.stack)\n\n if( self.stack not in self.operate_unique):\n self.operate_unique.append(self.stack)\n\n self.original_list.append(i)\n\n self.stack = \"\" # and reset stack for other operate\n else:\n self.stack += i # contain operate that have numbers after alphabet on stack\n # in case without bracket in lastest word. I have to append stack on original_list\n if( len(Str) == j+1 and len(self.stack) != 0 ):\n self.operate.append(self.stack)\n self.original_list.append(self.stack)\n\n if( self.stack not in self.operate_unique):\n self.operate_unique.append(self.stack)\n\n return self.original_list\n\n def no_space(self):\n Str = \"\"\n for i in self.original: # skip space\n if(i == \" \"):\n pass\n else:\n Str += i\n self.original = Str\n\n def get_operator(self):\n return self.operator\n\n def get_operate(self):\n return self.operate\n\n def get_original_list(self):\n return self.original_list\n\n# ----------------Testing class--------------------\nif( __name__ == \"__main__\" ):\n testing_data_set = ( \"!(1+0)\" # index 0\n , \"!(!(0+I0&1))\" # index 1\n , \"(I0+!I1+!(I2))&(!I0+I1+I2)\" # index 2\n , \"!(I0&I1)+!(I1+I2)\" # index 3\n , \"(((I0&I1&!I2)+!I1)+I3)\" # index 4\n , \"ก10 + ข10\") # index 5\n\n for test in testing_data_set:\n Testing = Boolean_algebra(test)\n print(test,\"==>\",Testing.split_expreesion())\n print(test,\"==>\",Testing.operate)\n print(test,\"==>\",Testing.operate_unique)\n print(\"-\"*100)","sub_path":"Boolean expression string/Tree/New Version/Saturn_2/SplitExpression_V2.py","file_name":"SplitExpression_V2.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"87816791","text":"#!/usr/bin/env python\n###\n# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n###\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom builtins import range\nfrom future import standard_library\nstandard_library.install_aliases()\nimport sys\n\nPYTHON_VERSION = sys.version_info[:3]\nPY2 = (PYTHON_VERSION[0] == 2)\nif PY2:\n if PYTHON_VERSION < (2, 7, 9):\n raise Exception('Must use Python 2.7.9 or later')\nelif PYTHON_VERSION < (3, 4):\n raise Exception('Must use Python 3.4 or later')\n\nimport hpOneView as hpov\nfrom pprint import pprint\nimport json\nfrom hpOneView.common import uri\n\n\ndef acceptEULA(con):\n # See if we need to accept the EULA before we try to log in\n con.get_eula_status()\n try:\n if con.get_eula_status() is True:\n print('EULA display needed')\n con.set_eula('no')\n except Exception as e:\n print('EXCEPTION:')\n print(e)\n\n\ndef login(con, credential):\n # Login with given credentials\n try:\n con.login(credential)\n except:\n print('Login failed')\n\n\ndef get_eg_from_arg(srv, name):\n if srv and name:\n if name.startswith('/rest') and uri['enclosureGroups'] in name:\n return name\n else:\n egs = srv.get_enclosure_groups()\n for eg in egs:\n if eg['name'] == name:\n return eg['uri']\n return None\n\n\ndef get_sht_from_arg(srv, name): \n if srv and name:\n if name.startswith('/rest') and uri['server-hardware-types'] in name:\n return name\n else:\n shts = srv.get_server_hardware_types()\n for sht in shts:\n if sht['name'] == name:\n return sht['uri']\n return None\n\n\ndef define_profile_template(\n srv,\n name,\n desc,\n sp_desc,\n server_hwt,\n enc_group,\n affinity,\n hide_flexnics,\n conn_list):\n \n if conn_list:\n # read connection list from file\n conn = json.loads(open(conn_list).read())\n else:\n conn = []\n \n profile_template = srv.create_server_profile_template(\n name=name,\n description=desc,\n serverProfileDescription=sp_desc,\n serverHardwareTypeUri=server_hwt,\n enclosureGroupUri=enc_group,\n affinity=affinity,\n hideUnusedFlexNics=hide_flexnics,\n profileConnectionV4=conn)\n\n if 'serialNumberType' in profile_template:\n print('\\n\\nName: ', profile_template['name'])\n print('Type: ', profile_template['type'])\n print('Description: ', profile_template['description']) \n print('serialNumberType: ', profile_template['serialNumberType'])\n print('Connections:')\n for connection in profile_template['connections']:\n print(' name: ', connection['name'])\n print(' functionType: ', connection['functionType'])\n print(' networkUri: ', connection['networkUri'])\n print('Firmware:')\n print(' manageFirmware: ', profile_template['firmware']['manageFirmware'])\n print(' forceInstallFirmware: ', profile_template['firmware']['forceInstallFirmware'])\n print(' firmwareBaselineUri: ', profile_template['firmware']['firmwareBaselineUri'])\n print('Bios:')\n print(' manageBios: ', profile_template['bios']['manageBios'])\n print(' overriddenSettings: ', profile_template['bios']['overriddenSettings'])\n print('Boot:')\n print(' manageBoot: ', profile_template['boot']['manageBoot'])\n print(' order: ', profile_template['boot']['order'], '\\n')\n else:\n pprint(profile_template)\n\n\ndef main():\n parser = argparse.ArgumentParser(add_help=True,\n formatter_class=argparse.RawTextHelpFormatter,\n description='''\n Define a server profile template''')\n parser.add_argument('-a', dest='host', required=True,\n help='''\n HP OneView Appliance hostname or IP address''')\n parser.add_argument('-u', dest='user', required=False,\n default='Administrator',\n help='''\n HP OneView Username''')\n parser.add_argument('-p', dest='passwd', required=True,\n help='''\n HP OneView Password''')\n parser.add_argument('-c', dest='cert', required=False,\n help='''\n Trusted SSL Certificate Bundle in PEM (Base64 Encoded DER) Format''')\n parser.add_argument('-y', dest='proxy', required=False,\n help='''\n Proxy (host:port format''')\n parser.add_argument('-n', dest='name',\n required=True,\n help='''\n Name of the profile template''')\n parser.add_argument('-d', dest='desc',\n required=False,\n help='''\n Description for the server profile template''')\n parser.add_argument('-spd', dest='sp_desc',\n required=False,\n help='''\n Server profile description''')\n parser.add_argument('-sht', dest='server_hwt', required=True,\n help='''\n Server hardware type is required for defining an unassigned profile. Note\n the Server Hardware Type must be present in the HP OneView appliance\n before it can be used. For example, a single server with the specific server\n hardware type must have been added to OneView for that hardware type to\n be used. The example script get-server-hardware-types.py with the -l\n argument can be used to get a list of server hardware types that have\n been imported into the OneView appliance''')\n parser.add_argument('-eg', dest='enc_group', required=True,\n help='''\n Identifies the enclosure group for which the Server Profile Template\n was designed. The enclosureGroupUri is determined when the profile\n template is created and cannot be modified\n ''')\n parser.add_argument('-af', dest='affinity',\n required=False, choices=['Bay', 'BayAndServer'],\n default='Bay',\n help='''\n This identifies the behavior of the server profile when the server\n hardware is removed or replaced.\n\n . Bay: This profile remains with the device bay when the server\n hardware is removed or replaced.\n\n . BayAndServer This profile is pinned to both the device bay and\n specific server hardware.''')\n parser.add_argument('-hn', dest='hide_flexnics',\n required=False, choices=['true', 'false'],\n help='''\n This setting controls the enumeration of physical functions that do not\n correspond to connections in a profile. Using this flag will SHOW unused\n FlexNICs to the Operating System. Changing this setting may alter the order\n of network interfaces in the Operating System. This option sets the 'Hide\n Unused FlexNICs' to disabled, eight FlexNICs will be enumerated in the\n Operating System as network interfaces for each Flex-10 or FlexFabric\n adapter. Configuring Fibre Channel connections on a FlexFabric adapter may\n enumerate two storage interfaces, reducing the number of network interfaces\n to six. The default (this option is not selected) enables 'Hide Unused\n FlexNICs' and may suppress enumeration of FlexNICs that do not correspond\n to profile connections. FlexNICs are hidden in pairs, starting with the 4th\n pair. For instance, if the 4th FlexNIC on either physical port corresponds\n to a profile connection, all eight physical functions are enumerated. If a\n profile connection corresponds to the 2nd FlexNIC on either physical port,\n but no connection corresponds to the 3rd or 4th FlexNIC on either physical\n port, only the 1st and 2nd physical functions are enumerated in the\n Operating System.''')\n parser.add_argument('-cl', dest='conn_list',\n required=False,\n help='''\n File with list of connections for this profile in JSON format. This file\n can be created with multiple calls to define-connection-list.py''')\n \n args = parser.parse_args()\n credential = {'userName': args.user, 'password': args.passwd}\n\n con = hpov.connection(args.host)\n srv = hpov.servers(con)\n\n if args.proxy:\n con.set_proxy(args.proxy.split(':')[0], args.proxy.split(':')[1])\n if args.cert:\n con.set_trusted_ssl_bundle(args.cert)\n\n login(con, credential)\n acceptEULA(con)\n\n eg = get_eg_from_arg(srv, args.enc_group)\n \n sht = get_sht_from_arg(srv, args.server_hwt)\n\n define_profile_template(\n srv,\n args.name,\n args.desc,\n args.sp_desc,\n sht,\n eg,\n args.affinity,\n args.hide_flexnics,\n args.conn_list)\n\n\nif __name__ == '__main__':\n import argparse\n sys.exit(main())\n\n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n","sub_path":"examples/scripts/define-profile-template.py","file_name":"define-profile-template.py","file_ext":"py","file_size_in_byte":10985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"340096979","text":"useFixture(default)\n\ndef test():\n\tfrom Modules import commonBits\n\tjava_recorded_version = '1.5.0_11'\n\n\tif window('Record Editor'):\n\t\tselect('FileChooser', commonBits.sampleDir() + 'Ams_LocDownload_20041228.txt')\n\t\tcommonBits.setRecordLayout(select, 'ams Store')\n\t\tclick('Edit1')\n\t\tassert_p('Table', 'Text', 'DC - Taras Ave', '10 - 35|Loc Name,0')\n\t\tassert_p('Table', 'Text', 'Bankstown', '10 - 35|Loc Name,4')\n\t\tdoubleclick('BaseDisplay$HeaderToolTips', '10 - 35|Loc Name')\n\t\tassert_p('Table', 'Text', 'Airport West', '10 - 35|Loc Name,0')\n\t\tassert_p('Table', 'Text', 'Bass Hill', '10 - 35|Loc Name,5')\n\t\tcommonBits.closeWindow(click)\n\t\t##click('BasicInternalFrameTitlePane$NoFocusButton2')\n\n\t\tif window(r'Save Changes to file: ' + commonBits.sampleDir() + 'Ams_LocDownload_20041228.txt'):\n\t\t\tclick('No')\n\t\tclose()\n\tclose()\n","sub_path":"Build/Instalation/GeneralDb/Marathon/MarathonTests_1.1/LargeFile_Edit/TestCases/Editor/FullEdit_old_Basic2a.py","file_name":"FullEdit_old_Basic2a.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"383791580","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 21 14:05:55 2018\r\n\r\n@author: top40ub\r\n\"\"\"\r\n\r\n\"\"\"\r\nNavigation in 3D is a non-trivial task. Due to the anisotropic definition of spherical coordinate\r\nsystems, rotations and movement along isolines or fixed points are tricky. A way to do this a bit\r\neasier is to use an old concept from particle physics called quaternions. To be true, their\r\nmathematical formulation exceeds those of vectors in terms of age. They are common standard\r\nin computer vision.\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n\r\n\r\n\"\"\"\r\nFunction name : vec_to_quat()\r\n***Description***\r\n\r\nTransformation of 3d vectors to 4 dimensional quaternions\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z])\r\nOutput:\r\n\ta) np.array([0,x,y,z])\r\n\r\nInline output: Raises an Error raise Exception('Error the vector is not a 3D vector [x,y,z]') if vector is not of shape (3,) \r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef vec_to_quat(vec):\r\n if vec.shape[0] == 3:\r\n quat = np.append([0], vec)\r\n return quat\r\n\r\n else:\r\n raise Exception('Error the vector is not a 3D vector [x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name : quat_conjug()\r\n***Description***\r\n\r\nCalculate the conjugate quaternion of given quaternion\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([w,x,y,z])\r\nOutput:\r\n\ta) np.array([w,-x,-y,-z])\r\n\r\nInline output: Raises an Error raise Exception('Error the quaternion is not a 4D [w,x,y,z]') if quaternion is not of shape (4,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_conjug(quat):\r\n if quat.shape[0] == 4:\r\n w, x, y, z = quat\r\n quatconjung = np.array([w, -x, -y, -z])\r\n return quatconjung\r\n else:\r\n raise Exception('Error the quaternion is not a 4D [w,x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name : vec_normal()\r\n***Description***\r\n\r\nNormalisation of given vector within a certain tolerance\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z])\r\n\r\nOutput:\r\n\ta) np.array([x,y,z]) with x² + y² + z² = 1\r\n\r\nInline output: Raises an Error Exception('Error the vector is not a 3D vector [x,y,z]') if vector is not of shape (3,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef vec_normal(vec, tolerance=0.00001):\r\n if vec.shape[0] == 3:\r\n \tvec_len_quad = np.sum([n * n for n in vec])\r\n \tif abs(vec_len_quad - 1.0) > tolerance:\r\n \tvec_len = np.sqrt(vec_len_quad)\r\n \tvec = vec/vec_len\r\n \treturn vec\r\n else:\r\n raise Exception('Error the vector is not a 3D vector [x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name : quat_mult()\r\n***Description***\r\n\r\nThis function defins how to quaternions multiplicate. The multiplication core\r\ncan be interpreted as a kind of rotation. For deeper information read the\r\ncoresponding wikipedia page or one of the plenty graphical visualition books\r\nabout computer vision like I' ve done :)\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([w1,x1,y1,z1]), np,array([w2,x2,y2,z2])\r\nOutput:\r\n\ta) np.array([w_mult,x_mult,y_mult,z_mult])\r\n\r\nInline output: Raises an error Exception('Error one quaternion is not a 4D [w,x,y,z]') if quaternion is not of shape (4,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_mult(quat1, quat2):\r\n if quat1.shape[0] == 4 and quat2.shape[0] ==4:\r\n w1, x1, y1, z1 = quat1\r\n w2, x2, y2, z2 = quat2\r\n w_mult = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2\r\n x_mult = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2\r\n y_mult = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2\r\n z_mult = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2\r\n quat_mult = np.array([w_mult, x_mult, y_mult, z_mult])\r\n return quat_mult\r\n else:\r\n raise Exception('Error one quaternion is not a 4D [w,x,y,z]')\r\n \r\n\r\n\"\"\"\r\nFunction name : quat_vec_mult()\r\n***Description***\r\n\r\nQuaternionic multiplication between quaternion and vector. The vector\r\nis transformed. A second quaternionc multiplication with the conjugate of given\r\nquaternion returns the three vector compoments [1:] of the operation.\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x1,y1,z1]), np,array([w2,x2,y2,z2])\r\nOutput:\r\n\ta) np.array([w_mult,x_mult,y_mult,z_mult])\r\n\r\n\r\nInline output: Raises an error Exception('Error the quaternion is not a 4D [w,x,y,z] or the vector is not 3D [x,y,z]') if quaternion or vector are not of shape (4,) or (3,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_vec_mult(vec1, quat1):\r\n if vec1.shape[0] == 3 and quat1.shape[0] ==4:\r\n \tquat2 = vec_to_quat(vec1)\r\n \treturn quat_mult(quat_mult(quat1, quat2), quat_conjug(quat1))[1:]\r\n else:\r\n raise Exception('Error the quaternion is not a 4D [w,x,y,z] or the vector is not 3D [x,y,z]')\r\n \r\n\r\n\"\"\"\r\nFunction name : axisangle_to_quat()\r\n***Description***\r\n\r\nCalcuation to transform a unit vector or any vector that will be normalsied \r\ninto a quaternion that elements are object to a rotation around half theta.\r\n!Theta needs to be of type degree!\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z]), np.array([theta])\r\n\r\nOutput:\r\n\ta) np.array([w_a,x_a,y_a,z_a])\r\n\r\nInline output: Raises an error Exception('Error the vector is not 3D [x,y,z] or the angle 1D [theta]') if vector or angle are not of shape(3,) or (1,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef axisangle_to_quat(vec, theta):\r\n if vec.shape[0] == 3 and theta.shape[0] == 1:\r\n vec = vec_normal(vec)\r\n x, y, z = vec\r\n theta = theta[0]/2\r\n theta = np.deg2rad(theta)\r\n w_a = np.cos(theta)\r\n x_a = x * np.sin(theta)\r\n y_a = y * np.sin(theta)\r\n z_a = z * np.sin(theta)\r\n quat_a = np.array([w_a, x_a, y_a, z_a])\r\n return quat_a\r\n else:\r\n raise Exception('Error the vector is not 3D [x,y,z] or the angle 1D [theta]')\r\n \r\n \r\n\r\n\"\"\"\r\nFunction name : quat_to_axisangle()\r\n***Description***\r\n\r\nThe opposite function of axisangle_to_quat, it returns the axisangle the \r\ncorresponding unit vector of a given quaternion.\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([w,x,y,z])\r\n\r\nOutput:\r\n\ta) np.array([x_a,y_a,z_a]), np.arra([theta])\r\n\r\nInline output: Raises an error Exception('Error the quaternion is not a 4D [w,x,y,z]') if quaternion is not of shape (4,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef quat_to_axisangle(quat):\r\n if quat.shape[0] == 4: \r\n \tw, vec = quat[0], quat[1:]\r\n \ttheta = np.rad2deg(np.arccos(w) * 2.0)\r\n \treturn vec_normal(vec), theta\r\n \r\n else:\r\n raise Exception('Error the quaternion is not a 4D [w,x,y,z]')\r\n\r\n\r\n\"\"\"\r\nFunction name :vec_angle_rot()\r\n***Description***\r\n\r\nMain function for the quaternionic rotation of 3D vectors:\r\nA vector (vec) is rotated around a second vector a_unit with angle theta. \r\na_unit is a axisvector but mostly a basis vector of given cartesic coordinate\r\nsystem. In case of a cartesic basis vector we have the rotation around \r\ncoordinate axsis.\r\n\r\n***I/O***\r\nInput parameter: \r\n\ta) np.array([x,y,z]), np.array([theta]), \r\n np.array(x2,y2,z2) with x2² + y2² + z2² = 1\r\n\r\nOutput:\r\n\ta) np.array([x1_rot,y1_rot,z1_rot])\r\n\r\nInline output: Raises an error Exception('Error one vector is not 3D [x,y,z] or the angle 1D [theta]') if vector or angle are not of shape (3,) or (1,)\r\nPlot output:\r\nSave file:\r\n\"\"\"\r\ndef vec_angle_rot(vec,theta,a_unit):\r\n if vec.shape[0] == 3 and theta.shape[0] == 1 and vec.shape[0] == 3:\r\n \tquat1 = vec_to_quat(vec)\r\n \tquat_a = axisangle_to_quat(a_unit,theta)\r\n \tv_rot = quat_mult(quat_mult(quat_a,quat1),quat_conjug(quat_a))[1:]\r\n \treturn v_rot\r\n else:\r\n raise Exception('Error one vector is not 3D [x,y,z] or the angle 1D [theta]')\r\n\r\n\r\nif __name__=='__main__':\r\n\tpass\r\n","sub_path":"Math_and_Simulation/Quaternions.py","file_name":"Quaternions.py","file_ext":"py","file_size_in_byte":7523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"528670073","text":"import Ex1 as Ex1\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Loading given txt into an array\nvelArray = np.loadtxt(\"velocities.txt\", float)\n\n#This creates an array of just the times\n#The : means take all values\ntime = velArray[:,0]\n\n#This creates an array of just the velocities\nvel = velArray[:,1]\n\n#len means length of that array\nposTrap = np.zeros(len(time))\nposSimp = np.zeros(len(time))\ndistTrap = np.zeros(len(time))\ndistSimp = np.zeros(len(time))\n\n#First is trapezodial rule\n#Must start at 2 in order for [0:2] means [0, 1]\ni = 2\nwhile i < len(time):\n\tposAtTrap = Ex1.trapez(time[0:i], vel[0:i])\n\tdistAtTrap = Ex1.trapez(abs(vel[0:i]), time[0:i])\n\tposTrap[i] = posAtTrap\n\tdistTrap[i] = distAtTrap\n\ti += 1\n\n#Now for simpson's rule\ni = 2\nwhile i < len(time):\n\tposAtSimp = Ex1.simpson(time[0:i], vel[0:i])\n\tdistAtSimp = Ex1.simpson(abs(vel[0:i]), time[0:i])\n\tposSimp[i] = posAtSimp\n\tdistSimp[i] = distAtSimp\n\ti += 1\n\n#This will sum up the distance array's of each to give a total distance\ntotalDisTrap = np.array([sum(distTrap)])\ntotalDisSimp = np.array([sum(distSimp)])\n\n#These will save the files of total distances\nnp.savetxt('Total Distance Trap.txt', totalDisTrap)\nnp.savetxt('Total Distance Simp.txt', totalDisSimp)\n\n\n#This plots the velocity vs time and position vs time on same figure\nplt.subplot(2,1,1)\nplt.plot(time, posTrap, color='red')\nplt.xlabel('Time (s)')\nplt.ylabel('Position (m)')\nplt.suptitle('Time Versus Position and Velocity')\nplt.subplot(2,1,2)\nplt.plot(time, vel)\nplt.xlabel('Time (s)')\nplt.ylabel('Velocity (m/s)')\nplt.show()\n\n","sub_path":"Week2/Ex2update.py","file_name":"Ex2update.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"486244760","text":"import xarray\r\nimport os\r\nimport glob\r\nimport pandas as pd\r\nfrom datetime import datetime, timedelta\r\n\r\nstations = pd.read_csv(\"NCDC_Selected_Raingauge.csv\")\r\n\r\n# create dataframe to store all precip record\r\nstart_date = datetime(1950, 1, 1)\r\nend_date = datetime(2100, 12, 31)\r\ndays = pd.date_range(start_date, end_date, freq='D')\r\n\r\n\r\n# data_folders = [\"Historical\", \"RCP26\", \"RCP45\", \"RCP85\"]\r\ndata_folders = [\"Historical\", \"RCP85\"]\r\n\r\nmain_folder = \"Z:/Projects/Bridges Climate Change Project/Statistical Analysis/Climate DATA/Climate Models/RCMs_NA_Cordex_i/\"\r\n\r\nfor folder in data_folders[1:]:\r\n if os.path.isfile(main_folder + folder + \"/GCMs.csv\"):\r\n GCMs = open(main_folder + folder + \"/GCMs.csv\", \"r\")\r\n for model in GCMs:\r\n precip = pd.DataFrame({'date': days})\r\n precip = precip.set_index('date')\r\n\r\n for stats_ID in stations[\"ID\"]:\r\n if stats_ID != \"ID\":\r\n precip[stats_ID] = 0.0\r\n\r\n model_folder = model.split()[0]\r\n\r\n for filename in glob.glob(os.path.join(main_folder + data_folders[0] + \"/\" + model_folder, '*.nc')):\r\n print(filename)\r\n ds_hist = xarray.open_dataset(filename)\r\n pr_hist = ds_hist['pr']\r\n time_hist = ds_hist['time']\r\n\r\n for stats_ID in stations[\"ID\"]:\r\n station_name = stats_ID\r\n lat = stations.loc[stations[\"ID\"] == stats_ID, \"LATITUDE\"].iloc[0]\r\n lon = stations.loc[stations[\"ID\"] == stats_ID, \"LONGITUDE\"].iloc[0]\r\n print(station_name + \" \" + str(lat) + \" \" + str(lon))\r\n pr_p_hist = pr_hist.sel(lat=lat, lon=lon, method='nearest')\r\n pr_p_hist = pr_p_hist * 60.0 * 60.0 * 24.0\r\n pr_hist_values = [float(x) for x in pr_p_hist]\r\n time_hist_values = [x.values for x in time_hist]\r\n\r\n i = 0\r\n for date in time_hist_values:\r\n if \" \" in str(date):\r\n date_val = str(date).split(\" \")[0].split(\"-\")\r\n elif \"T\" in str(date):\r\n date_val = str(date).split(\"T\")[0].split(\"-\")\r\n\r\n date_val = datetime(int(date_val[0]), int(date_val[1]), int(date_val[2]))\r\n if date_val >= start_date and date_val <= end_date:\r\n precip.loc[date_val, station_name] = pr_hist_values[i]\r\n i += 1\r\n ds_hist.close()\r\n\r\n for filename in glob.glob(os.path.join(main_folder + folder + \"/\" + model_folder, '*.nc')):\r\n print(filename)\r\n ds_ftr = xarray.open_dataset(filename)\r\n pr_ftr = ds_ftr['pr']\r\n time_ftr = ds_ftr['time']\r\n\r\n for stats_ID in stations[\"ID\"]:\r\n station_name = stats_ID\r\n lat = stations.loc[stations[\"ID\"] == stats_ID, \"LATITUDE\"].iloc[0]\r\n lon = stations.loc[stations[\"ID\"] == stats_ID, \"LONGITUDE\"].iloc[0]\r\n print(station_name + \" \" + str(lat) + \" \" + str(lon))\r\n pr_p_ftr = pr_ftr.sel(lat=lat, lon=lon, method='nearest')\r\n pr_p_ftr = pr_p_ftr * 60.0 * 60.0 * 24.0\r\n pr_ftr_values = [float(x) for x in pr_p_ftr]\r\n time_ftr_values = [x.values for x in time_ftr]\r\n\r\n i = 0\r\n for date in time_ftr_values:\r\n if \" \" in str(date):\r\n date_val = str(date).split(\" \")[0].split(\"-\")\r\n elif \"T\" in str(date):\r\n date_val = str(date).split(\"T\")[0].split(\"-\")\r\n\r\n date_val = datetime(int(date_val[0]), int(date_val[1]), int(date_val[2]))\r\n if date_val >= start_date and date_val <= end_date:\r\n precip.loc[date_val, station_name] = pr_ftr_values[i]\r\n i += 1\r\n ds_ftr.close()\r\n\r\n if not os.path.exists(folder):\r\n os.makedirs(folder)\r\n precip.to_csv(folder + \"/\" + filename.split(\"\\\\\")[-1] + \".csv\")\r\n\r\nprint(\"Data extracted for all station locations!\")\r\n","sub_path":"statisticalAnalysis/preprocessing/RCMs_data_extraction_time_series_MultiStations.py","file_name":"RCMs_data_extraction_time_series_MultiStations.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"116174459","text":"# -*- coding: utf-8 -*-\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom pages.Common import Page, Element\n\n\ndef move_element(driver,elem):\n actions = ActionChains(driver)\n actions.move_to_element(elem)\n actions.perform()\n\n\nclass OtvetPageQuestion(Page):\n QUESTION_CLASS = \"question\"\n LIKES_CLASS = \"action--mark\"\n DISLIKES_CLASS = \"action--unmark\"\n SUBSCRIBE_XPATH = \"//button[@title='Подписаться']\"\n UNSUBSCRIBE_XPATH = \"//button[@title='Отписаться']\"\n\n def like(self):\n WebDriverWait(self.driver, 10) \\\n .until(expected_conditions.presence_of_element_located((By.CLASS_NAME, self.LIKES_CLASS)))\n el = self.driver.find_element_by_class_name(self.QUESTION_CLASS).find_element_by_class_name(self.LIKES_CLASS)\n move_element(self.driver, el)\n el.click()\n WebDriverWait(self.driver, 10)\\\n .until(expected_conditions.presence_of_element_located((By.CLASS_NAME, self.DISLIKES_CLASS)))\n\n\n\n def dislike(self):\n el = self.driver.find_element_by_class_name(self.QUESTION_CLASS).find_element_by_class_name(self.DISLIKES_CLASS)\n move_element(self.driver, el)\n el.click()\n WebDriverWait(self.driver, 10) \\\n .until(expected_conditions.presence_of_element_located((By.CLASS_NAME, self.LIKES_CLASS)))\n\n def is_liked(self):\n return self.driver.find_element_by_class_name(self.QUESTION_CLASS).find_element_by_class_name(self.DISLIKES_CLASS) is not None\n\n def is_unliked(self):\n return self.driver.find_element_by_class_name(self.QUESTION_CLASS).find_element_by_class_name(self.LIKES_CLASS) is not None\n\n def subscribe(self):\n el = self.driver.find_element_by_xpath(self.SUBSCRIBE_XPATH)\n move_element(self.driver, el)\n el.click()\n WebDriverWait(self.driver, 10) \\\n .until(expected_conditions.presence_of_element_located((By.XPATH, self.UNSUBSCRIBE_XPATH)))\n\n def unsubscribe(self):\n el = self.driver.find_element_by_xpath(self.UNSUBSCRIBE_XPATH)\n move_element(self.driver, el)\n el.click()\n WebDriverWait(self.driver, 10) \\\n .until(expected_conditions.presence_of_element_located((By.XPATH, self.SUBSCRIBE_XPATH)))\n\n def is_subscribed(self):\n return self.driver.find_element_by_xpath(self.UNSUBSCRIBE_XPATH) is not None\n\n def is_unsubscribed(self):\n return self.driver.find_element_by_xpath(self.SUBSCRIBE_XPATH) is not None\n\n def answer_form(self):\n return AnswerForm(self.driver)\n\n\nclass AnswerForm(Element):\n FORM_CLASS = \"form--padding\"\n TEXT_AREA_CLASS = \"form--text\"\n IMAGE_ADD_CLASS = \"action--upload-photo\"\n SUBMIT_CLASS = \"action--save\"\n COUNT_SYMBOLS_CLASS = \"count-symbol-number\"\n MAX_SYMBOLS = 3800\n\n def __init__(self, driver):\n super(AnswerForm, self).__init__(driver)\n WebDriverWait(self.driver, 10) \\\n .until(expected_conditions.presence_of_element_located((By.CLASS_NAME, self.FORM_CLASS)))\n self.form = self.driver.find_element_by_class_name(self.FORM_CLASS)\n move_element(self.driver, self.form)\n\n def set_text(self, text):\n el = self.form.find_element_by_class_name(self.TEXT_AREA_CLASS)\n move_element(self.driver, el)\n el.send_keys(text)\n\n def submit(self):\n el = self.form.find_element_by_class_name(self.SUBMIT_CLASS)\n WebDriverWait(self.driver, 10) \\\n .until(expected_conditions.visibility_of_element_located((By.CLASS_NAME, self.SUBMIT_CLASS)))\n move_element(self.driver, el)\n el.click()\n\n def count_symbols_value(self):\n return self.form.find_element_by_class_name(self.COUNT_SYMBOLS_CLASS).text","sub_path":"pages/AnswerQuestion.py","file_name":"AnswerQuestion.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"400594949","text":"import numpy as np\nimport itertools\nfrom numpy.polynomial import chebyshev as cheb\n\n\"\"\"\nModule for defining the class of Chebyshev polynomials, as well as various related \nclasses and methods, including:\n\n Classes:\n -------\n\n Polynomial: Superclass for MultiPower and MultiCheb. Contains methods and \n attributes applicable to both subclasses\n\n MultiCheb: Chebyshev polynomials in arbitrary dimension.\n\n Term: Terms are just tuples of exponents with the degrevlex ordering\n\n Methods:\n --------\n\n match_poly_dimensions(polys): Matches the dimensions of a list of polynomials.\n\n mon_combos_highest(mon, numLeft): Find all the monomials of a given degree and \n returns them. Works recursively.\n\n mon_combos(mon, numLeft): Finds all the monomials _up to_ a given degree and \n returns them. Works recursively.\n\n sort_polys_by_degree(polys): Sorts the polynomials by their degree.\n\n get_var_list(dim): Return a list of tuples corresponding to the variables \n [x_1, x_2, ..., x_n]. The tuple for x_1 is (1,0,0,...,0), and for x_i \n the 1 is in the ith slot.\n\n slice_bottom(arr):Gets the nd slices needed to slice an array into the bottom \n corner of another. There is probably a better (vectorized) way to do this.\n\n slice_top(arr): Construct a list of slices needed to put an array into the upper \n left corner of another. There is probably a better way to do this.\n\n match_size(a,b): Reshape two coefficient ndarrays to have the same shape.\n \n makePolyCoeffMatrix(inputString): Take a string input of a polynomaial and \n return the coefficient matrix for it. Usefull for making things of high \n degree of dimension so you don't have to make it by hand.\n\n\n\"\"\"\n\nclass Polynomial(object):\n '''\n Superclass for MultiPower and MultiCheb. Contains methods and attributes\n that are applicable to both subclasses.\n\n Attributes\n ----------\n coeff\n The coefficient matrix represented in the object.\n dim\n The number of dimensions of the coefficient matrix\n order\n Ordering type given as a string\n shape\n The shape of the coefficient matrix\n lead_term\n The polynomial term with the largest total degree\n degree\n The total degree of the lead_term\n lead_coeff\n The coeff of the lead_term\n\n Parameters\n ----------\n coeff : ndarray\n Coefficients of the polynomial\n order : string\n lead_term : Tuple\n Default is None. Accepts tuple or tuple-like inputs\n clean_zeros : bool\n Default is True. If True, all extra rows, columns, etc of all zeroes are\n removed from matrix of coefficients.\n\n Methods\n -------\n clean_coeff\n Removes extra rows, columns, etc of zeroes from end of matrix of coefficients\n match_size\n Matches the shape of two matrices.\n monomialList\n Creates a list of monomials that make up the polynomial in degrevlex order.\n monSort\n Calls monomial list.\n update_lead_term\n Finds the lead_term of a polynomial\n __call__\n Evaluates a polynomial at a certain point.\n __eq__\n Checks if two polynomials are equal.\n __ne__\n Checks if two polynomials are not equal.\n\n '''\n def __init__(self, coeff, order='degrevlex', lead_term=None, clean_zeros=True):\n '''\n order : string\n Term order to use for the polynomial. degrevlex is default. \n Currently no other order is implemented.\n '''\n if isinstance(coeff,np.ndarray):\n self.coeff = coeff\n elif isinstance(coeff,str):\n self.coeff = makePolyCoeffMatrix(coeff)\n else:\n raise ValueError('coeff must be an np.array or a string!')\n if clean_zeros:\n self.clean_coeff()\n self.dim = self.coeff.ndim\n self.order = order\n self.jac = None\n self.shape = self.coeff.shape\n if lead_term is None:\n self.update_lead_term()\n else:\n self.lead_term = tuple(lead_term)\n self.degree = sum(self.lead_term)\n self.lead_coeff = self.coeff[self.lead_term]\n\n def clean_coeff(self):\n \"\"\"\n Remove 0s on the outside of the coeff matrix. Acts in place.\n \"\"\"\n\n for axis in range(self.coeff.ndim):\n change = True\n while change:\n change = False\n if self.coeff.shape[axis] == 1:\n continue\n axisCount = 0\n slices = list()\n for i in self.coeff.shape:\n if axisCount == axis:\n s = slice(i-1,i)\n else:\n s = slice(0,i)\n slices.append(s)\n axisCount += 1\n if np.sum(abs(self.coeff[slices])) == 0:\n self.coeff = np.delete(self.coeff,-1,axis=axis)\n change = True\n\n def update_lead_term(self):\n \"\"\"\n Update the lead term of the polynomial.\n \"\"\"\n \n non_zeros = list()\n for i in zip(*np.where(self.coeff != 0)):\n non_zeros.append(Term(i))\n if len(non_zeros) != 0:\n self.lead_term = max(non_zeros).val\n self.degree = sum(self.lead_term)\n self.lead_coeff = self.coeff[self.lead_term]\n else:\n self.lead_term = None\n self.lead_coeff = 0\n self.degree = -1\n\n def __call__(self, point):\n '''\n Evaluate the polynomial at 'point'. This method is overridden\n by the MultiPower and MultiCheb classes, so this definition only\n checks if the polynomial can be evaluated at the given point.\n\n Parameters\n ----------\n point : array-like\n the point at which to evaluate the polynomial\n\n Returns\n -------\n __call__ : complex\n value of the polynomial at the given point\n '''\n if len(point) != len(self.coeff.shape):\n raise ValueError('Cannot evaluate polynomial in {} variables at point {}'\\\n .format(self.dim, point))\n\n def grad(self, point):\n '''\n Evaluates the gradient of the polynomial at 'point'. This method is \n overridden by the MultiPower and MultiCheb classes, so this definition only\n checks if the polynomial can be evaluated at the given point.\n\n Parameters\n ----------\n point : array-like\n the point at which to evaluate the polynomial\n\n Returns\n -------\n grad : ndarray\n Gradient of the polynomial at the given point.\n '''\n if len(point) != len(self.coeff.shape):\n raise ValueError('Cannot evaluate polynomial in {} variables at point {}'\\\n .format(self.dim, point))\n\n def __eq__(self,other):\n '''\n Check if coeff matrices of 'self' and 'other' are the same.\n '''\n \n if self.shape != other.shape:\n return False\n return np.allclose(self.coeff, other.coeff)\n\n def __ne__(self,other):\n '''\n Check if coeff matrices of 'self' and 'other' are not the same.\n '''\n return not (self == other)\n\n\n###############################################################################\n\n#### MULTI_CHEB ###############################################################\n\nclass MultiCheb(Polynomial):\n \"\"\"\n A Chebyshev polynomial.\n\n Attributes\n ----------\n coeff: ndarray\n A tensor of coefficients whose i_1,...,i_{dim} entry \n corresponds to the coefficient of the term \n T_{i_1}(x_1)...T_{i_{dim}}(x_{dim}) \n dim:\n The number of variables, dimension of polynomial.\n order: string\n Term order \n shape: tuple of ints\n The shape of the coefficient array.\n lead_term:\n The term with the largest total degree. \n degree: int\n The total degree of lead_term.\n lead_coeff\n The coefficient of the lead_term.\n terms : int\n Highest term of single-variable polynomials. The polynomial has \n degree at most terms+1 in each variable.\n\n\n\n Parameters\n ----------\n coeff : list(terms**dim) or np.array ([terms,] * dim)\n coefficents in given ordering.\n order : string\n Term order for Groebner calculations. Default = 'degrevlex'\n lead_term : list\n The index of the current leading coefficent. If None, this is computed at initialization.\n clean_zeros: boolean\n If True, strip off any rows or columns of zeros on the outside of the coefficient array.\n\n Methods\n -------\n\n __add__\n Add two MultiCheb polynomials.\n __sub__\n Subtract two MultiCheb polynomials.\n mon_mult\n Multiply a MultiCheb monomial by a MultiCheb polynomial.\n __call__\n Evaluate a MultiCheb polynomial at a point.\n\n \"\"\"\n def __init__(self, coeff, order='degrevlex', lead_term=None, clean_zeros = True):\n super(MultiCheb, self).__init__(coeff, order, lead_term, clean_zeros)\n\n def __add__(self,other):\n '''\n Addition of two MultiCheb polynomials.\n\n Parameters\n ----------\n other : MultiCheb\n\n Returns\n -------\n MultiCheb\n The sum of the coeff of self and coeff of other.\n\n '''\n if self.shape != other.shape:\n new_self, new_other = match_size(self.coeff,other.coeff)\n else:\n new_self, new_other = self.coeff, other.coeff\n\n return MultiCheb(new_self + new_other,clean_zeros = False)\n\n def __sub__(self,other):\n '''\n Subtraction of two MultiCheb polynomials.\n\n Parameters\n ----------\n other : MultiCheb\n\n Returns\n -------\n MultiCheb\n The coeff values are the result of self.coeff - other.coeff.\n '''\n if self.shape != other.shape:\n new_self, new_other = match_size(self.coeff,other.coeff)\n else:\n new_self, new_other = self.coeff, other.coeff\n return MultiCheb((new_self - (new_other)), clean_zeros = False)\n\n \n \n def _fold_in_i_dir(coeff_array, dim, fdim, size_in_fdim, fold_idx):\n \"\"\"Find coeffs corresponding to T_|m-n| (referred to as 'folding' in\n some of this documentation) when multiplying a monomial times\n a Chebyshev polynomial.\n\n Multiplying the monomial T_m(x_i) times T_n(x_i) gives \n (T_{m+n}(x_i) + T_{|n-m|}(x_i))/2\n So multipying T_m(x_i) times polynomial P with coefficients \n in coeff_array results in a new coefficient array sol that has \n coeff_array in the bottom right corner plus a 'folded' copy of \n coeff_array in locations corresponding to |n-m|. This method \n returns the folded part (not dividing by 2)\n\n Parameters\n ----------\n coeff_array : ndarray\n coefficients of the polynomial.\n dim : int\n The number of dimensions in coeff_array.\n fdim : int\n The dimension being folded ('i' in the explanation above)\n size_in_fdim : int\n The size of the solution matrix in the dimension being folded.\n fold_idx : int\n The index to fold around ('m' in the explanation above)\n\n Returns\n -------\n sol : ndarray\n\n \"\"\"\n if fold_idx == 0:\n return coeff_array\n\n target = np.zeros_like(coeff_array) # Array of zeroes in which to insert\n # the new values.\n\n ## Compute the n-m part for n >= m\n\n # slice source and target in the dimension of interest (i = fdim)\n target_slice = slice(0,size_in_fdim-fold_idx,None) # n-m for n>=m\n source_slice = slice(fold_idx,size_in_fdim,None) # n for n>=m\n\n # indexers have a slice index for every dimension.\n source_indexer = [slice(None)]*dim\n source_indexer[fdim] = source_slice\n target_indexer = [slice(None)]*dim\n target_indexer[fdim] = target_slice\n\n # Put the appropriately indexed source into the target\n target[target_indexer] = coeff_array[source_indexer]\n\n ## Compute the m-n part for n < m\n\n # slice source and target in the dimension of interest (i = fdim)\n target_slice = slice(fold_idx, 0 , -1) # m-n for n < m\n source_slice = slice(None, fold_idx, None) # n for n < m\n\n # indexers have a slice index for every dimension.\n source_indexer = [slice(None)]*dim\n source_indexer[fdim] = source_slice\n target_indexer = [slice(None)]*dim\n target_indexer[fdim] = target_slice\n\n # Add the appropriately indexed source to the target\n target[target_indexer] += coeff_array[source_indexer]\n\n return target\n\n\n def _mon_mult1(coeff_array, monom, mult_idx):\n \"\"\"\n Monomial multiply in one dimension, that is, T_m(x_i) * P(x_1,...,x_n), \n where P is a Chebyshev polynomial and T_m(x_i) is a Chebyshev monomial \n in the lone variable x_i.\n\n Parameters\n ----------\n coeff_array : array_like\n Coefficients of a Chebyshev polynomial (denoted P above).\n\n monom : tuple of ints\n Index of the form (0,0,...,0,m,0...,0) of a \n monomial of one variable\n\n mult_idx : int\n The location (denoted i above) of the non-zero value in monom. \n\n Returns\n -------\n ndarray\n Coeffs of the new polynomial T_m(x_i)*P. \n\n \"\"\"\n \n p1 = np.zeros(coeff_array.shape + monom)\n p1[slice_bottom(coeff_array)] = coeff_array # terms corresp to T_{m+n}\n\n largest_idx = [i-1 for i in coeff_array.shape]\n new_shape = [max(i,j) for i,j in\n itertools.zip_longest(largest_idx, monom, fillvalue = 0)]\n if coeff_array.shape[mult_idx] <= monom[mult_idx]:\n add_a = [i-j for i,j in itertools.zip_longest(new_shape, largest_idx, fillvalue = 0)]\n add_a_list = np.zeros((len(new_shape),2))\n #change the second column to the values of add_a and add_b.\n add_a_list[:,1] = add_a\n #use add_a_list and add_b_list to pad each polynomial appropriately.\n coeff_array = np.pad(coeff_array,add_a_list.astype(int),'constant')\n\n number_of_dim = coeff_array.ndim\n shape_of_self = coeff_array.shape\n\n if monom[mult_idx] != 0:\n coeff_array = MultiCheb._fold_in_i_dir(coeff_array,number_of_dim,\n mult_idx, shape_of_self[mult_idx],\n monom[mult_idx])\n if p1.shape != coeff_array.shape:\n monom = [i-j for i,j in zip(p1.shape,coeff_array.shape)]\n\n result = np.zeros(np.array(coeff_array.shape) + monom)\n result[slice_top(coeff_array)] = coeff_array\n coeff_array = result\n Pf = p1 + coeff_array\n return .5*Pf\n\n def mon_mult(self, monom, return_type = 'Poly'):\n \"\"\"\n Multiply a Chebyshev polynomial by a monomial\n\n Parameters\n ----------\n monom : tuple of ints\n The index of the monomial to multiply self by.\n return_type : str\n If 'Poly' then returns a polynomial object.\n\n Returns\n -------\n MultiCheb object if return_type is 'Poly'.\n ndarray if return_type is \"Matrix\".\n\n \"\"\"\n coeff_array = self.coeff\n monom_zeros = np.zeros(len(monom),dtype = int)\n for i in range(len(monom)):\n monom_zeros[i] = monom[i]\n coeff_array = MultiCheb._mon_mult1(coeff_array, monom_zeros, i)\n monom_zeros[i] = 0\n if return_type == 'Poly':\n return MultiCheb(coeff_array, lead_term = self.lead_term + np.array(monom), clean_zeros = False)\n elif return_type == 'Matrix':\n return coeff_array\n\n def __call__(self, point):\n '''\n Evaluate the polynomial at 'point'.\n\n Parameters\n ----------\n point : array-like\n point at which to evaluate the polynomial\n\n Returns\n -------\n c : complex\n value of the polynomial at the given point\n '''\n super(MultiCheb, self).__call__(point)\n\n c = self.coeff\n n = len(c.shape)\n c = cheb.chebval(point[0],c)\n for i in range(1,n):\n c = cheb.chebval(point[i],c,tensor=False)\n return c\n\n def grad(self, point):\n '''\n Evaluates the gradient of the polynomial at the given point.\n\n Parameters\n ----------\n point : array-like\n the point at which to evaluate the polynomial\n\n Returns\n -------\n out : ndarray\n Gradient of the polynomial at the given point.\n '''\n super(MultiCheb, self).__call__(point)\n\n out = np.empty(self.dim,dtype=\"complex_\")\n if self.jac is None:\n jac = list()\n for i in range(self.dim):\n jac.append(cheb.chebder(self.coeff,axis=i))\n self.jac = jac\n spot = 0\n for i in self.jac:\n out[spot] = chebvalnd(point,i)\n spot+=1\n return out\n\n###############################################################################\n\ndef chebvalnd(x,c):\n \"\"\"\n Evaluate a MultiCheb object at a point x\n\n Parameters\n ----------\n x : ndarray\n Point to evaluate at\n c : ndarray\n Tensor of Chebyshev coefficients\n\n Returns\n -------\n c : float\n Value of the MultiCheb polynomial at x\n \"\"\"\n x = np.array(x)\n n = len(c.shape)\n c = cheb.chebval(x[0],c)\n for i in range(1,n):\n c = cheb.chebval(x[i],c,tensor=False)\n return c\n\ndef polyList(deg,dim,Type = 'random'):\n \"\"\"\n Creates random polynomials for root finding.\n\n Parameters\n ----------\n deg : int\n Desired degree of the polynomials.\n dim : int\n Desired number of dimensions for the polynomials\n Type : str\n Either 'random' or 'int.\n\n Returns\n ----------\n polys : list\n polynomial objects that are used to test the root finding.\n\n \"\"\"\n deg += 1\n polys = []\n if Type == 'random':\n for i in range(dim):\n polys.append(np.random.random_sample(deg*np.ones(dim, dtype = int)))\n elif Type == 'int':\n Range = 10\n for i in range(dim):\n polys.append(np.random.randint(-Range,Range,deg*np.ones(dim, dtype = int)))\n for i,j in np.ndenumerate(polys[0]):\n if np.sum(i) >= deg:\n for h in range(len(polys)):\n polys[h][i] = 0\n for i in range(len(polys)):\n polys[i] = MultiCheb(polys[i])\n return polys\n\n\n\n\n############# Cheb Utils ####################3\n\n\nclass TVBError(RuntimeError):\n pass\n\nclass Term(object):\n '''\n Terms are just tuples of exponents with the degrevlex ordering\n '''\n def __init__(self,val):\n self.val = tuple(val)\n\n def __repr__(self):\n return str(self.val) + ' with degrevlex order'\n\n def __lt__(self, other, order = 'degrevlex'):\n '''\n Redfine less-than according to term order\n '''\n if order == 'degrevlex': #Graded Reverse Lexographical Order\n if sum(self.val) < sum(other.val):\n return True\n elif sum(self.val) > sum(other.val):\n return False\n else:\n for i,j in zip(reversed(self.val),reversed(other.val)):\n if i < j:\n return False\n if i > j:\n return True\n return False\n elif order == 'lexographic': #Lexographical Order\n for i,j in zip(self.val,other.val):\n if i < j:\n return True\n if i > j:\n return False\n return False\n elif order == 'grlex': #Graded Lexographical Order\n if sum(self.val) < sum(other.val):\n return True\n elif sum(self.val) > sum(other.val):\n return False\n else:\n for i,j in zip(self.val,other.val):\n if i < j:\n return True\n if i > j:\n return False\n return False\n\n\ndef match_poly_dimensions(polys):\n '''Matches the dimensions of a list of polynomials.\n\n Parameters\n ----------\n polys : list\n Polynomials of possibly different dimensions.\n\n Returns\n -------\n new_polys : list\n The same polynomials but of the same dimensions.\n '''\n dim = max(poly.dim for poly in polys)\n new_polys = list()\n for poly in polys:\n if poly.dim != dim:\n coeff_shape = list(poly.shape)\n for i in range(dim - poly.dim):\n coeff_shape.insert(0,1)\n poly.__init__(poly.coeff.reshape(coeff_shape))\n new_polys.append(poly)\n return new_polys\n\n\n\n\ndef mon_combos_highest(mon, numLeft, spot = 0):\n '''Find all the monomials of a given degree and returns them. Works recursively.\n\n Very similar to mon_combos, but only returns the monomials of the desired degree.\n\n Parameters\n --------\n mon: list\n A list of zeros, the length of which is the dimension of the desired monomials. Will change\n as the function searches recursively.\n numLeft : int\n The degree of the monomials desired. Will decrease as the function searches recursively.\n spot : int\n The current position in the list the function is iterating through. Defaults to 0, but increases\n in each step of the recursion.\n\n Returns\n -----------\n answers : list\n A list of all the monomials.\n '''\n answers = list()\n if len(mon) == spot+1: #We are at the end of mon, no more recursion.\n mon[spot] = numLeft\n answers.append(mon.copy())\n return answers\n if numLeft == 0: #Nothing else can be added.\n answers.append(mon.copy())\n return answers\n temp = mon.copy() #Quicker than copying every time inside the loop.\n for i in range(numLeft+1): #Recursively add to mon further down.\n temp[spot] = i\n answers += mon_combos_highest(temp, numLeft-i, spot+1)\n return answers\n\n\n\ndef mon_combos(mon, numLeft, spot = 0):\n '''Finds all the monomials up to a given degree and returns them. Works recursively.\n\n Parameters\n --------\n mon: list\n A list of zeros, the length of which is the dimension of the desired monomials. Will change\n as the function searches recursively.\n numLeft : int\n The degree of the monomials desired. Will decrease as the function searches recursively.\n spot : int\n The current position in the list the function is iterating through. Defaults to 0, but increases\n in each step of the recursion.\n\n Returns\n -----------\n answers : list\n A list of all the monomials.\n '''\n answers = list()\n if len(mon) == spot+1: #We are at the end of mon, no more recursion.\n for i in range(numLeft+1):\n mon[spot] = i\n answers.append(mon.copy())\n return answers\n if numLeft == 0: #Nothing else can be added.\n answers.append(mon.copy())\n return answers\n temp = mon.copy() #Quicker than copying every time inside the loop.\n for i in range(numLeft+1): #Recursively add to mon further down.\n temp[spot] = i\n answers += mon_combos(temp, numLeft-i, spot+1)\n return answers\n\ndef sort_polys_by_degree(polys, ascending = True):\n '''Sorts the polynomials by their degree.\n\n Parameters\n ----------\n polys : list.\n A list of polynomials.\n ascending : bool\n Defaults to True. If True the polynomials are sorted in order of ascending degree. If False they\n are sorted in order of descending degree.\n Returns\n -------\n sorted_polys : list\n A list of the same polynomials, now sorted.\n '''\n degs = [poly.degree for poly in polys]\n argsort_list = np.argsort(degs)\n sorted_polys = list()\n for i in argsort_list:\n sorted_polys.append(polys[i])\n if ascending:\n return sorted_polys\n else:\n return sorted_polys[::-1]\n\n \ndef makePolyCoeffMatrix(inputString):\n '''\n Takes a string input of a polynomaial and returns the coefficient matrix for it. Usefull for making things of high\n degree of dimension so you don't have to make it by hand.\n\n All strings must be of the following syntax. Ex. '3x0^2+2.1x1^2*x2+-14.73x0*x2^3'\n\n 1. There can be no spaces.\n 2. All monomials must be seperated by a '+'. If the coefficient of the monomial is negative then the '-' sign\n should come after the '+'. This is not needed for the first monomial.\n 3. All variables inside a monomial are seperated by a '*'.\n 4. The power of a variable in a monomial is given folowing a '^' sign.\n '''\n matrixSpots = list()\n coefficients = list()\n for monomial in inputString.split('+'):\n coefficientString = monomial[:first_x(monomial)]\n if coefficientString == '-':\n coefficient = -1\n elif coefficientString == '':\n coefficient = 1\n else:\n coefficient = float(coefficientString)\n mons = monomial[first_x(monomial):].split('*')\n matrixSpot = [0]\n for mon in mons:\n stuff = mon.split('^')\n if len(stuff) == 1:\n power = 1\n else:\n power = int(stuff[1])\n if stuff[0] == '':\n varDegree = -1\n else:\n varDegree = int(stuff[0][1:])\n if varDegree != -1:\n if len(matrixSpot) <= varDegree:\n matrixSpot = np.append(matrixSpot, [0]*(varDegree - len(matrixSpot)+1))\n matrixSpot[varDegree] = power\n matrixSpots.append(matrixSpot)\n coefficients.append(coefficient)\n #Pad the matrix spots so they are all the same length.\n length = max(len(matrixSpot) for matrixSpot in matrixSpots)\n for i in range(len(matrixSpots)):\n matrixSpot = matrixSpots[i]\n if len(matrixSpot) < length:\n matrixSpot = np.append(matrixSpot, [0]*(length - len(matrixSpot)))\n matrixSpots[i] = matrixSpot\n matrixSize = np.maximum.reduce([matrixSpot for matrixSpot in matrixSpots])\n matrixSize = matrixSize + np.ones_like(matrixSize)\n matrixSize = matrixSize[::-1] #So the variables are in the right order.\n matrix = np.zeros(matrixSize)\n for i in range(len(matrixSpots)):\n matrixSpot = matrixSpots[i][::-1] #So the variables are in the right order.\n coefficient = coefficients[i]\n matrix[tuple(matrixSpot)] = coefficient\n return matrix\n\n\ndef match_size(a,b):\n '''\n Matches the shape of two ndarrays.\n\n Parameters\n ----------\n a, b : ndarray\n Arrays whose size is to be matched.\n\n Returns\n -------\n a, b : ndarray\n Arrays of equal size.\n '''\n new_shape = np.maximum(a.shape, b.shape)\n\n a_new = np.zeros(new_shape)\n a_new[slice_top(a)] = a\n b_new = np.zeros(new_shape)\n b_new[slice_top(b)] = b\n return a_new, b_new\n\n\ndef slice_top(arr):\n '''Construct a list of slices needed to put an array into the upper left \n corner of another. \n\n Parameters\n ----------\n arr : ndarray\n The array of interest.\n Returns\n -------\n slices : list\n Each value of the list is a slice of the array in some dimension. \n It is exactly the size of the array.\n '''\n slices = list()\n for i in arr.shape:\n slices.append(slice(0,i))\n return slices\n\ndef slice_bottom(arr):\n ''' Gets the n-d slices needed to slice an array into the bottom \n corner of another.\n\n Parameters\n ----------\n arr : ndarray\n The array of interest.\n\n Returns\n -------\n slices : list\n Each value of the list is a slice of the array in some dimension. \n It is exactly the size of the array.\n '''\n slices = list()\n for i in arr.shape:\n slices.append(slice(-i,None))\n return slices\n\n\ndef get_var_list(dim):\n '''Return a list of tuples corresponding to the \n variables [x_1, x_2, ..., x_n]. The tuple for x_1 \n is (1,0,0,...,0), and for x_i the 1 is in the ith slot.\n '''\n \n _vars = []\n var = [0]*dim\n for i in range(dim):\n var[i] = 1\n _vars.append(tuple(var))\n var[i] = 0\n return _vars\n\n\n","sub_path":"CHEBYSHEV/TVB_Method/cheb_class.py","file_name":"cheb_class.py","file_ext":"py","file_size_in_byte":28922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"241226581","text":"import socket\nimport os\n\nclass FTPClient(object):\n\n BASE_FOLDER = os.path.dirname(os.path.abspath(__file__))\n FILENAME='mata1027'\n def __init__(self, server_address,reuseAddr=True):\n self.server_address = server_address\n self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n if reuseAddr:\n self.client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.client_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT,1)\n def start_client(self):\n try:\n self.client_socket.connect(self.server_address)\n print(\"[*] Just connected at {}:{}\".format(self.server_address[0], self.server_address[1]))\n self.download_file(FTPClient.FILENAME)\n except OSError:\n print(\"[*] Couldn`t connect.\")\n\n def download_file(self, filename):\n with open(filename,'w') as f:\n print(\"file opened...\")\n self.rec_data=''\n self.size=1\n while self.size:\n self.size=\"\"\n print(\"reciving data...\")\n self.data = self.client_socket.recv(1024)\n self.data = self.data.decode('utf-8')\n self.size=self.data\n self.rec_data+=self.data\n f.write(self.rec_data)\n self.client_socket.close()\n\nif __name__ == \"__main__\":\n ftp = FTPClient((\"127.0.0.1\", 8089))\n ftp.start_client()\n","sub_path":"FTPClient.py","file_name":"FTPClient.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"487399494","text":"from unittest import TestCase\n\nfrom p0016 import sumDigits\n\nclass TestSumDigits(TestCase):\n\n def testSumDigits(self):\n for data in self.__createTestData():\n n = data[\"n\"]\n expected = data[\"expected\"]\n\n with self.subTest(n = n, expected = expected):\n self.assertEqual(expected, sumDigits(n))\n\n def testSumDigitsWithNegativeNFails(self):\n with self.assertRaises(AssertionError):\n sumDigits(-1)\n\n def __createTestData(self):\n\n return [\n {\"n\" : 0, \"expected\" : 0}\n , {\"n\" : 1, \"expected\" : 1}\n , {\"n\" : 2, \"expected\" : 2}\n , {\"n\" : 10, \"expected\" : 1}\n , {\"n\" : 11, \"expected\" : 2}\n , {\"n\" : 12, \"expected\" : 3}\n , {\"n\" : 2 ** 15, \"expected\" : 26}\n , {\"n\" : 2 ** 1000, \"expected\" : 1366}]\n","sub_path":"python/test/testP0016.py","file_name":"testP0016.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"471857192","text":"from django.shortcuts import render, redirect, reverse\nfrom ..login.models import User\n\n\ndef current_user(request):\n\treturn User.objects.get(id=request.session['user_id'])\n\ndef index(request):\n\ttry:\n\t\trequest.session['user_id']\n\texcept KeyError:\n\t\treturn redirect('/')\n\tcontext = {\n\t\t'user': User.objects.get(id=request.session['user_id'])\n\t}\n\treturn render(request, 'wall/index.html', context)\n\n# def personal(request, user):\n# \tcontext = {\n# \t\t'quote': Quote.objects.get(id=id)\n# \t}\n# \treturn render(request, 'wall/personal.html')\n\ndef quotes(request):\n\tif request.method == \"POST\":\n\t\t#Validate form data\n\t\terrors = Water.objects.validate(request.POST)\n\n\t\t#if no errors\n\t\tif not errors:\n\t\t\t#Get the currently logged in user\n\t\t\tuser = current_user(request)\n\t\t\t#Create the new post\n\t\t\tquote = Quote.objects.create_quote(request.POST, user)\n\t\t\t#Redirect back to same page \n\t\t\treturn redirect(reverse('dashboard'))\n\n\t\t#flash errors\n\n\treturn redirect(reverse('dashboard')) ","sub_path":"apps/wall/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"35664262","text":"import torch\nfrom torch.utils.data import Dataset\nimport random\nimport cv2\nimport os\nimport os.path as osp\nimport glob\nimport sys\nsys.path.insert(0, '../../')\nfrom src.data_utils import random_resize, random_flip, random_crop_new, random_crop_edges, random_rotate, colorjitter\nfrom IPython import embed\nimport numpy as np\nimport pickle\n\ndef edge(img):\n blurred = cv2.GaussianBlur(img,(3,3),0)\n gray=cv2.cvtColor(blurred,cv2.COLOR_RGB2GRAY)\n xgrad=cv2.Sobel(gray,cv2.CV_16SC1,1,0)\n ygrad=cv2.Sobel(gray,cv2.CV_16SC1,0,1)\n edge_output=cv2.Canny(xgrad,ygrad,50,150)\n return edge_output[:,:,None]\n\nclass DataLoader(Dataset):\n def __init__(self, args):\n super(DataLoader, self).__init__()\n self.crop_size = args.crop_size\n self.group_dir = args.group_dir\n self.nframes = args.nframes\n \n self.imglist = pickle.load(open(osp.join(self.group_dir, 'trainvallist_aug.pkl'), 'rb'))\n random.shuffle(self.imglist)\n self.length = len(self.imglist)\n print(\"Dataset Length: {}\".format(self.length))\n \n def aug(self, img, label):\n img, label = random_crop_new(img, label, self.crop_size, 0, 0)\n img, label = random_flip(img, label)\n return img, label\n \n def __getitem__(self,index):\n index = index % self.length\n lr_img = []\n hr_img = []\n for i in range(self.nframes):\n lr_img.append(cv2.imread(self.imglist[index][0][i]))\n hr_img.append(cv2.imread(self.imglist[index][1][i]))\n lr_img = np.stack(lr_img, -1)\n hr_img = np.stack(hr_img, -1)\n lr_img, hr_img = random_crop_new(lr_img, hr_img, self.crop_size)\n lr_img, hr_img = random_flip(lr_img, hr_img)\n edges = edge(lr_img[:,:,:,self.nframes//2]).transpose(2, 0 ,1) / 255\n lr_img = lr_img.transpose(3, 2, 0, 1) / 255\n hr_img = hr_img.transpose(3, 2, 0, 1) / 255\n hr_img = hr_img[self.nframes//2]\n return lr_img, hr_img, edges\n \n def __len__(self):\n return self.length","sub_path":"config/EDVR_with_canny_edge/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"473428366","text":"def column_to_list(data, index):\n \"\"\"\n This function convert a column to a list\n\n Keyword arguments:\n data: the data base list\n index: the index of the column based on the first line's list of the data\n \"\"\"\n\n column_list = []\n # Dica: Você pode usar um for para iterar sobre as amostras, pegar a feature pelo seu índice, e dar append para uma lista\n for n in range(0,len(data)):\n column_list.append(data[n][index])\n return column_list\n\ndef count_word(list_column, word):\n \"\"\"\n This function returns the number of especific word in a list\n\n Keyword arguments:\n list_column: defined by the list your willing to analyze\n word: is the word that is willing to be counted\n \"\"\"\n counter = 0\n\n for i in range(0,len(list_column)):\n if list_column[i] == word:\n counter +=1\n return counter\n\ndef count_items(column_list):\n \"\"\" This function creates a dataset with the types of strings in a database.\n Then it counts the frequency of each type.\n It returns the types and the frequency in the format: types,counts\n\n Keyword Arguments:\n column_list: a list with data from a column from data_list\n \"\"\"\n item_types = list(set(column_list))\n count_items = []\n for i in range(0,len(item_types)):\n count_items.append(0)\n for j in range(0,len(column_list)):\n if column_list[j] == item_types[i]:\n count_items[i] += 1\n \n return item_types, count_items\n\n\n\ndef selectData(data_list,index,condition):\n \n new_data_list = []\n \n for i in range(0,len(data_list)):\n if data_list[i][index] == condition:\n new_data_list.append(data_list[i])\n \n return new_data_list","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"68607530","text":"import click\nfrom bokeh.io import output_file, save, show\nfrom bokeh.layouts import gridplot\nfrom functools import partial\n\nfrom desafio_iafront.jobs.graphics.utils import compare_plot,hist_plot,scaled_hist_plot\nfrom desafio_iafront.data.dataframe_utils import read_partitioned_json,read_data_partitions\nfrom desafio_iafront.jobs.common import filter_date\n\n\n@click.command()\n@click.option('--data-path', type=click.Path(exists=True))\n@click.option('--x_axis')\n@click.option('--data-inicial', type=click.DateTime(formats=[\"%d/%m/%Y\"]))\n@click.option('--data-final', type=click.DateTime(formats=[\"%d/%m/%Y\"]))\n@click.option('--file_output_name')\n@click.option('--transformation')\ndef main(data_path: str, x_axis:str, data_inicial , data_final, file_output_name : str, transformation: str):\n\n filter_function = partial(filter_date, data_inicial=data_inicial, data_final=data_final)\n\n dataframe = read_partitioned_json(file_path=data_path, filter_function=filter_function)\n \n scatter=compare_plot(dataframe, x_axis, x_axis+\": valores brutos x transformados pelo metodo \"+transformation)\n hist_antes=hist_plot(dataframe, x_axis, title='valores brutos de '+x_axis)\n hist_depois=scaled_hist_plot(dataframe, x_axis, title='valores de '+x_axis+' transformados pela '+transformation)\n\n output_file(str(file_output_name)+x_axis+\"_\"+transformation+\".html\" )\n\n show(gridplot([[scatter,hist_antes,hist_depois]]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"codigo/desafio_iafront/jobs/graphics/job_compare.py","file_name":"job_compare.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"284358601","text":"def print_matrix(matrix):\r\n for i in range(len(matrix)):\r\n for j in range(len(matrix[0])):\r\n print(\"\\t\", matrix[i][j], end=\" \")\r\n print(\"\\n\")\r\n\r\n\r\ndef main():\r\n m = int(input(\"Enter number of rows: \"));\r\n n = int(input(\"Enter number of columns:\"));\r\n\r\n matrix1 = [[0 for j in range(0, n)] for i in range(0, m)]\r\n matrix2 = [[0 for j in range(0, n)] for i in range(0, m)]\r\n res_matrix = [[0 for j in range(0, n)] for i in range(0, m)]\r\n print(\"enter first matrix elements\")\r\n for i in range(0, m):\r\n for j in range(0, n):\r\n matrix1[i][j] = int(input(\"enter an element\"))\r\n print(\"enter second matrix elements \")\r\n for i in range(0, m):\r\n for j in range(0, n):\r\n matrix2[i][j] = int(input(\"enter an element\"))\r\n\r\n for i in range(0, m):\r\n for j in range(0, n):\r\n res_matrix[i][j] = matrix1[i][j] + matrix2[i][j]\r\n\r\n\r\n print(\" matrix 1\")\r\n print_matrix(matrix1)\r\n print(\" matrix 2\")\r\n print_matrix(matrix2)\r\n\r\n\r\n print(\"resultant matrix after adding\")\r\n print_matrix(res_matrix)\r\n\r\n\r\nmain()","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"216117023","text":"import subprocess,nmap3\r\n\r\ndef python_subprocess_shell():\r\n target = input('Enter Target: ')\r\n portn_num = input('Enter the port Number/s to scan (443,1-6535)')\r\n nmap = nmap3.Nmap()\r\n ports = nmap.PortScanner()\r\n port_scan = ports.scan(target,port_num)\r\n while True:\r\n try:\r\n command = input('Enter command to execute: ')\r\n subprocess.call(command)\r\n except KeyboardInterrupt:\r\n break\r\n\r\npython_subprocess_shell()\r\n","sub_path":"PYFiles/python3_shell.py","file_name":"python3_shell.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"39343399","text":"from __future__ import absolute_import, unicode_literals\nfrom celery import shared_task\nimport nmap\nfrom index.util.scan import domian_scan\nfrom index.models import Subdomain, Target, Ipinfo\n\nfrom celery.signals import worker_process_init\nfrom multiprocessing import current_process\n\n@worker_process_init.connect\ndef fix_multiprocessing(**kwargs):\n try:\n current_process()._config\n except AttributeError:\n current_process()._config = {'semprefix': '/mp'}\n\n\n@shared_task\ndef startscan(target_id):\n target_obj = Target.objects.get(id=target_id)\n print(target_obj.main_host)\n target_obj.status = 1\n target_obj.save()\n domain_list = (target_obj.main_host.split(';'))\n for domain in domain_list:\n print('开始扫描域名:' + domain)\n a, b, c = domian_scan(domain)\n\n for i in range(len(a)):\n obj = Subdomain(target_id=target_id, first_domain=domain, sub_domain=a[i], ip=b[i], ip_addr=c[i])\n obj.save()\n\n ipobj = Subdomain.objects.filter(target_id=target_id).values('ip').distinct()\n\n for i in ipobj:\n host = i['ip']\n\n if not host:\n continue\n print(\"start scan:\" + host)\n nm = nmap.PortScanner()\n nm.scan(host,arguments='-sS -T4 -Pn --top-ports 1000',sudo=True)\n if nm[host].state()!='up':\n print(host+':down')\n obj = Ipinfo(target_id=target_id, ip=host, host_state='down', port=0, protocol=\"-\", port_state=\"-\",\n name=\"-\", version=\"-\")\n obj.save()\n continue\n\n try:\n for proto in nm[host].all_protocols():\n lport = nm[host][proto].keys()\n lport = sorted(lport)\n for port in lport:\n portocols = proto\n port_state = nm[host][proto][port]['state']\n name = nm[host][proto][port]['name']\n product = nm[host][proto][port]['product']\n temp_version = nm[host][proto][port]['version']\n extrainfo = nm[host][proto][port]['extrainfo']\n version = product + \"-\" + temp_version + \"-\" + extrainfo\n print(product+'--'+version)\n obj = Ipinfo(target_id=target_id, ip=i['ip'], host_state='up', port=port, protocol=portocols,\n port_state=port_state, name=name, version=version)\n obj.save()\n except:\n print(host + \":scna error\")\n obj = Ipinfo(target_id=target_id, ip=host, host_state='error', port=0, protocol=\"-\", port_state=\"-\",\n name=\"-\", version=\"-\")\n\n obj.save()\n # scan done\n target_obj.status = 2\n target_obj.save()\n\n\n\n","sub_path":"index/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"51501990","text":"\"\"\"\n\nAnalyze basic stats of hipchat data.\n\n\"\"\"\n\nimport markovify\nimport numpy as np\nimport operator\nimport pandas as pd\nfrom pathlib import Path\nimport re\nfrom sklearn.feature_extraction.text import CountVectorizer\n\npath_data = Path.cwd() / 'data' / 'data.pkl'\n\ndf = pd.read_pickle(str(path_data))\n\n# Drop useless columns\ndf.drop(columns=['data_filename', 'data_filepath', 'file.name', 'file.size', 'file.url'], inplace=True)\n\n# See messages of specific user\n# df.message[df['from.name'] == 'commercetools GmbH · Docker Monitor'].values.tolist()\n\n# Drop automated messages\nbots = ['GitHub', 'Docker Monitor', 'TeamCity', 'Jenkins', 'JIRA', 'Sphere CI', 'Frontend Bot', 'Travis CI',\n 'Prometheus · AlertManager', 'Sphere Staging', 'Sphere Production', 'Subversion', 'Grafana', 'grafana',\n 'Standup', 'AnomalyDetector', 'PagerDuty', 'UserVoice', 'Confluence', 'MMS',\n 'commercetools GmbH · Docker Monitor', 'Frontend Production', 'Mailroom', 'Stackdriver',\n 'Prometheus alerts · AlertManager', 'LaunchDarkly', 'Mailroom · system@iron.io', 'Ru Bot',\n 'logentries-alerts', 'HipGif', 'commercetools GmbH · GitHub', 'Status IO', 'StatusPage.io', 'ROSHAMBO!',\n 'commercetools GmbH · TeamCity', 'appear.in', 'commercetools GmbH · Travis CI', 'Integrations',\n 'Sphere Frontend', 'commercetools GmbH · Datadog', 'commercetools GmbH · Jenkins', 'System',\n 'commercetools GmbH · Automation', 'commercetools GmbH · Auto Mation', 'commercetools GmbH · akamel',\n 'commercetools GmbH · Subversion', 'commercetools GmbH · Heroku', 'Send from CLI',\n 'AgileZen', 'Log Entries', 'Link', 'Guggy', 'Automation', 'lunchbot']\ndf = df[~df['from.name'].isin(bots)]\n\n# Deal with multiple and trailing whitespaces, exclude empty messages\ndf.message = df.message.apply(lambda x: re.sub(' +',' ', x).strip())\ndf = df[~df.message.isin(['', ' '])]\n# TODO remove automated messages from users like Simons \"@here The ES Listing Validator has news, but...\"\n\n# Number of total messages\nlen(df)\n\n# Most active users\nn = 20\ntop_users = pd.DataFrame(df['from.name'].value_counts())\ntop_users.reset_index(inplace=True)\ntop_users.rename(columns={'index': 'user', 'from.name': 'messageCount'}, inplace=True)\ntop_users.head(n)\n\n# Most active rooms\nn = 20\ntop_rooms = pd.DataFrame(df['room'].value_counts())\ntop_rooms.reset_index(inplace=True)\ntop_rooms.rename(columns={'index': 'room', 'room': 'messageCount'}, inplace=True)\ntop_rooms.head(n)\n\n# Most common messages\nn = 20\ntop_messages = pd.DataFrame(df['message'].value_counts())\ntop_messages.reset_index(inplace=True)\ntop_messages.rename(columns={'index': 'message', 'from.name': 'messageCount'}, inplace=True)\ntop_messages.head(n)\n\n# Most common messages of top users\nn = 10\nfor user in top_users.user.values[:n]:\n print(f'------- User: {user} -------')\n top_messages = pd.DataFrame(df.message[df['from.name'] == user].value_counts())\n top_messages.reset_index(inplace=True)\n top_messages.rename(columns={'index': 'message', 'message': 'messageCount'}, inplace=True)\n print(top_messages.head(20))\n\n# Most common messages of top rooms\nn = 10\nfor room in top_rooms.room.values[:n]:\n print(f'------- Room: {room} -------')\n top_messages = pd.DataFrame(df.message[df['room'] == room].value_counts())\n top_messages.reset_index(inplace=True)\n top_messages.rename(columns={'index': 'message', 'message': 'messageCount'}, inplace=True)\n print(top_messages.head(20))\n\n# Most common words\n# TODO improve preprocessing with spacy\nn = 20\nvectorizer = CountVectorizer(stop_words='english')\nmessages = vectorizer.fit_transform(df.message.values)\nvocab = vectorizer.vocabulary_\nvocab_sorted = sorted(vocab.items(), reverse=True, key=operator.itemgetter(1))\ntop_words = pd.DataFrame(vocab_sorted)\ntop_words.reset_index(inplace=True)\ntop_words.rename(columns={'index': 'message', 'from.name': 'messageCount'}, inplace=True)\ntop_words.head(n)\n\n# Most common emoji\nn = 20\ntop_emojis = df[df.message.str.match(r'^\\(\\w+\\)$')]\ntop_emojis = pd.DataFrame(top_emojis['message'].value_counts())\ntop_emojis.reset_index(inplace=True)\ntop_emojis.rename(columns={'index': 'message', 'from.name': 'messageCount'}, inplace=True)\ntop_emojis.head(n)\n\n# Markov model to generate characteristic messages\nmodel = markovify.Text(df.message.values)\nfor i in range(10):\n print(model.make_sentence())\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"645224405","text":"import os\n\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn import metrics\n\nimport convenience\n\n\nif __name__ == \"__main__\":\n training_sentences, training_targets, training_multitargets, test_sentences, test_targets, test_multitargets = convenience.get_training_and_test_data()\n\n pipelines = dict()\n \n for cat in convenience.categories:\n pipelines[cat] = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n # ('clf', SGDClassifier(loss='hinge', penalty='elasticnet',\n # alpha=1e-3, max_iter=5, tol=None)),\n ('clf', OneVsRestClassifier(SGDClassifier(loss='hinge', penalty='elasticnet',\n alpha=1e-3, max_iter=5, tol=None))),\n ])\n\n \n\n # pipelines[cat] = Pipeline([\n # ('features', FeatureUnion([\n # ('ngram_tf_idf', Pipeline([\n # ('counts_ngram', CountVectorizer()),\n # ('tf_idf_ngram', TfidfTransformer())\n # ])),\n # ('pos_tf_idf', Pipeline([\n # ('pos', customtransformer()), \n # ('counts_pos', CountVectorizer()),\n # ('tf_idf_pos', TfidfTransformer())\n # ])),\n # ])),\n # ('clf', SGDClassifier(loss='hinge', penalty='elasticnet',\n # alpha=1e-3, max_iter=10, tol=None)),\n # ])\n\n for cat in convenience.categories:\n pipelines[cat].fit(training_sentences, training_targets[cat])\n\n predictions = dict()\n \n for cat in convenience.categories:\n cat_predictions = pipelines[cat].predict(test_sentences)\n\n predictions[cat] = [0] * len(cat_predictions)\n\n for i, pred in enumerate(cat_predictions):\n predictions[cat][i] = pred\n\n print(cat)\n print(metrics.confusion_matrix(test_targets[cat], predictions[cat]))\n print(metrics.classification_report(test_targets[cat], predictions[cat], digits=3))\n\n results = []\n results_multi = []\n\n for i in range(len(test_sentences)):\n temp_results = [0] * 5\n num_labels = 0\n\n for j, cat in enumerate(convenience.categories):\n if test_targets[cat][i]:\n num_labels += 1\n if predictions[cat][i] == test_targets[cat][i]:\n temp_results[j] = 1\n if all(temp_results):\n results.append(1)\n else:\n results.append(0)\n if num_labels > 1:\n if all(temp_results):\n results_multi.append(1)\n else:\n results_multi.append(0)\n\n print(\"Results SGD Classifier\")\n print(\"Accuracy all:\", results.count(1) / len(results))\n print(\"Accuracy only for sentences with multiple labels:\", results_multi.count(1) / len(results_multi))","sub_path":"classification/sgd_classifier.py","file_name":"sgd_classifier.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"311154925","text":"from tkinter import *\nfrom tkinter.ttk import * \n\nBOARD = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']\n\ndef main():\n \n window = Tk()\n \n top_frame = Frame(window)\n top_frame.grid(row=0, column=0, pady=10, padx=5)\n \n bot_frame = Frame(window, borderwidth=2, relief=RAISED)\n bot_frame.grid(row=1, column=0, pady=5, padx=5)\n \n #Top Frame\n entry = Entry(top_frame, width=43)\n button = Button(top_frame, text=\"Clear\")\n \n entry.grid(row=0, column=0)\n button.grid(row=0, column=1) \n \n \n #Bottom Frame\n \n for row, data in enumerate(BOARD):\n row_frame = Frame(bot_frame)\n row_frame.grid(row=row, column=0)\n for col, letter in enumerate(data):\n button_frame = Frame(row_frame, borderwidth=1, relief=RAISED, width=32, height=32)\n button_frame.grid_propagate(False)\n button_frame.grid(row=0, column=col, padx=1)\n button_frame.columnconfigure(0, weight=1)\n button_frame.rowconfigure(0, weight=1)\n\n\n button = Button(button_frame, text=letter)\n button.grid(sticky=\"NSEW\")\n \n window.mainloop()\n \nmain()\n \n \n \n ","sub_path":"Lab 01/cosc368q3.py","file_name":"cosc368q3.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"621785038","text":"#use python3\nimport pygame\nimport random\n#from queue import *\nimport heapq\n\nwidth = 800\nheight = 600\n\nTILE_SIZE = 10\nBORDER_SIZE = 1\n\nAGENTS = 10\n\n#The share of blocked tiles\nshare = 1200\ntileNumber = (width/TILE_SIZE) * (height/TILE_SIZE)\n\n#start = (0,0)\n\n#goal = (width-TILE_SIZE, height-TILE_SIZE)\n#goal = ((random.randint(0, (width/TILE_SIZE))*TILE_SIZE), (random.randint(0, (height/TILE_SIZE))*TILE_SIZE))\n\ngameDisplay = pygame.display.set_mode((width,height))\npygame.display.set_caption(\"nice to meet ya!\")\nclock = pygame.time.Clock()\nbackground = pygame.Surface((width,height))\n\n#Colors in rgb\nblack = (0,0,0)\nwhite = (255,255,255)\nred = (255,0,0)\ngreen = (0,255,0)\nblue = (0,0,255)\n\nclass PriorityQueue:\n def __init__(self):\n self.elements = []\n \n def empty(self):\n return len(self.elements) == 0\n \n def put(self, item, priority):\n heapq.heappush(self.elements, (priority, item))\n \n def get(self):\n return heapq.heappop(self.elements)[1]\n\nclass Tile(object):\n def __init__(self, x, y):\n self.pos = (x, y)\n self.size = TILE_SIZE\n\n # if ((x,y) == start):\n # self.start = True\n # else:\n # self.start = False\n\n # if ((x,y) == goal):\n # self.goal = True\n # else:\n # self.goal = False\n \n\n def setColor(self, color):\n self.color = color\n\n\n def setObsticle(self, obsticle):\n self.obsticle = obsticle\n if (obsticle):\n self.color = black\n #elif (self.start):\n # self.color = green\n #elif (self.goal):\n # self.color = red\n else:\n self.color = white\n\nclass Agent():\n def __init__(self):\n self.goal = ((random.randint(0, (width/TILE_SIZE))*TILE_SIZE), (random.randint(0, (height/TILE_SIZE))*TILE_SIZE))\n self.start = ((random.randint(0, (width/TILE_SIZE))*TILE_SIZE), (random.randint(0, (height/TILE_SIZE))*TILE_SIZE))\n self.color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))\n show(green, self.start[0],self.start[1])\n show(red, self.goal[0],self.goal[1])\n\n def path(self, path):\n self.path = path\n \n def getPath(self):\n return self.path\n\ndef main():\n pygame.init()\n grid = []\n \n \n for i in range(0, width//TILE_SIZE):\n grid.append([])\n for j in range(0, height//TILE_SIZE):\n tile = Tile(i*TILE_SIZE, j*TILE_SIZE)\n rand = random.randint(0,tileNumber)\n if (rand < share ):#and not tile.start and not tile.goal):\n obsticle = True\n else:\n obsticle = False\n tile.setObsticle(obsticle)\n \n pygame.draw.rect(background, tile.color, (tile.pos[0], tile.pos[1], TILE_SIZE-BORDER_SIZE, TILE_SIZE-BORDER_SIZE))\n\n grid[i].append(tile)\n\n\n gameDisplay.blit(background,(0,0)) #draws background\n\n agents = []\n #paths = []\n\n for i in range(0, AGENTS):\n agent = Agent()\n agents.append(agent)\n aStar(grid, agent)\n #paths.append(agent.getPath)\n\n for a in agents:\n #show(agent.color, grid[temp[0]][temp[1]].pos[0], grid[temp[0]][temp[1]].pos[1])\n #def show(color, x,y):\n #print (a.getPath())\n for coord in a.getPath():\n show(a.color, grid[coord[0]][coord[1]].pos[0], grid[coord[0]][coord[1]].pos[1])\n #print (coord)\n #show(green, grid[coord[0]][coord[1]].pos[0], grid[coord[0]][coord[1]].pos[0])\n\n #gridGoal = (goal[0]/TILE_SIZE, goal[1]/TILE_SIZE)\n #route = aStar(grid, start, gridGoal)\n while 1:\n \n #Loops through all the events that happened \n #in the last frame (often only one)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n return\n\n \n\n pygame.display.update()\n clock.tick(60) #Limits the frame rate to 60 frames per second\n\n pygame.quit()\n quit()\n\n#if __name__ == '__main__': main()\n\ndef aStar(grid, agent): #start, goal):\n goal = (agent.goal[0]//TILE_SIZE, agent.goal[1]//TILE_SIZE)\n start = (agent.start[0]//TILE_SIZE, agent.start[1]//TILE_SIZE)\n print (start)\n print (goal)\n frontier = PriorityQueue()\n frontier.put(start, 0)\n came_from = {}\n cost_so_far = {}\n came_from[start] = None\n cost_so_far[start] = 0\n path = []\n \n \n\n while not frontier.empty():\n current = frontier.get()\n if current == goal:\n break\n\n #show(blue, grid[current[0]][current[1]].pos[0], grid[current[0]][current[1]].pos[1])\n \n for node in neighbours(grid, current):\n new_cost = cost_so_far[current] + 1\n if node not in cost_so_far or new_cost < cost_so_far[node]:\n cost_so_far[node] = new_cost\n prio = new_cost + heuristic(goal, node)\n frontier.put(node, prio)\n came_from[node] = current\n \n\n temp = current\n while (temp in came_from):\n #show(agent.color, grid[temp[0]][temp[1]].pos[0], grid[temp[0]][temp[1]].pos[1])\n path.append(temp)\n temp = came_from[temp]\n agent.path = path\n #print (path)\n pass\n\ndef neighbours(grid, node):\n neigh = []\n if ((0 <= (node[0]+1) < width/TILE_SIZE) and (0 <= (node[1]) < height/TILE_SIZE)):\n if not grid[node[0]+1][node[1]].obsticle:\n neigh.append(((node[0]+1),(node[1])))\n if ((0 <= (node[0]-1) < width/TILE_SIZE) and (0 <= (node[1]) < height/TILE_SIZE)):\n if not grid[node[0]-1][node[1]].obsticle:\n neigh.append(((node[0]-1),(node[1])))\n if ((0 <= (node[0]) < width/TILE_SIZE) and (0 <= (node[1]+1) < height/TILE_SIZE)):\n if not grid[node[0]][node[1]+1].obsticle:\n neigh.append(((node[0]),(node[1]+1)))\n if ((0 <= (node[0]) < width/TILE_SIZE) and (0 <= (node[1]-1) < height/TILE_SIZE)):\n if not grid[node[0]][node[1]-1].obsticle:\n neigh.append(((node[0]),(node[1]-1)))\n \n return neigh\n\n#calculated an estimated distance to the goal\ndef heuristic(goal, node):\n (x1, y1) = goal\n (x2, y2) = node\n return abs(x1-x2) + abs(y1-y2)\n\n\n#Pygame syntax in order to draw outside the main loop\ndef show(color, x,y):\n pygame.draw.rect(background, color, (x, y, TILE_SIZE-BORDER_SIZE, TILE_SIZE-BORDER_SIZE))\n gameDisplay.blit(background,(0,0))\n events = pygame.event.get()\n pygame.display.update()\n #clock.tick(60)\n\n\nif __name__ == '__main__': main()\n","sub_path":"multiAgentPathFinding.py","file_name":"multiAgentPathFinding.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"260463854","text":"#!/usr/bin/env python3 \n\nimport os\nimport sys\nfrom cmd import Cmd\nfrom datetime import datetime\nimport getdata\nimport session_stats\nimport user_stats\nimport subprocess\nimport check_for_test_users\nimport general_stats\n\n\nclass MyCmd(Cmd):\n\n def __init__(self, working_dir, outxls, prompt='> '):\n # initialize the base class\n Cmd.__init__(self)\n\n # set class vars\n self.working_dir = working_dir\n self.outxls = os.path.join(self.working_dir, outxls)\n self.pickles = {}\n self.prompt = '(CMS) '\n self.intro = '%s\\n\\tCUAHSI Metrics Shell\\n%s' + \\\n '\\nEnter a command or \"help\" to list options' + \\\n (40*'-')\n\n def do_collect_hs_data(self, args):\n \"\"\"\n Collect metrics data for HydroShare\n usage: collect_hs_data\n - no args\n \"\"\"\n\n res = getdata.get_stats_data(dirname=self.working_dir)\n self.pickles = res\n\n# def do_set_output_xls(self, args):\n# path = os.path.join(self.working_dir, args.strip())\n# if path == '':\n# print('invalid input arguments.')\n# print('see \\'help save_to_xls\\' for more info')\n# return\n#\n# # check that outpath is in the correct format\n# if path[-3:] != 'xlsx':\n# print('Argument must have the \\'xlsx\\' extension, e.g. mydata.xlsx')\n# print('see \\'help save_to_xls\\' for more info')\n# return\n#\n# print('\\n\\tcurrent output xls path is %s' % (self.outxls))\n\n# def do_save_to_xls(self, args):\n# \"\"\"\n# Save summarized metrics data to excel file. The output will be saved\n# in the working directory.\n#\n# usage: save_to_xls\n# - no args\n# \"\"\"\n#\n# # save user data, check that pickle files exist before saving\n# if not os.path.exists(os.path.join(self.working_dir, 'users.pkl')):\n# print('\\n\\tcould not find \\'users.pkl\\', skipping.'\n# '\\n\\trun \\'collect_hs_data\\' to retrieve these missing data')\n# else:\n# # call the save function\n# save_stats.save_anon_users(self.working_dir, self.outxls)\n#\n# # save resource data, check that pickle files exist before saving\n# if not os.path.exists(os.path.join(self.working_dir, 'resources.pkl')):\n# print('\\n\\tcould not find \\'resources.pkl\\', skipping.'\n# '\\n\\trun \\'collect_hs_data\\' to retrieve these missing data')\n# else:\n# # call the save function\n# save_stats.save_anon_resources(self.working_dir, self.outxls)\n\n def do_calculate_session_stats(self, args):\n \"\"\"\n Calculate session statistics from activity logs.\n\n usage: calculate_session_stats [a] [b]\n - a: start date, MM-DD-YYYY\n - b: end date, MM-DD-YYYY\n \"\"\"\n\n # parse the start and end dates\n dates = args.split()\n if len(dates) < 2:\n et = datetime.now().strftime('%m-%d-%Y')\n # set large date range\n dates = ['01-01-2000',\n et]\n\n # check date formats\n try:\n st = datetime.strptime(dates[0].strip(), '%m-%d-%Y')\n et = datetime.strptime(dates[1].strip(), '%m-%d-%Y')\n except ValueError:\n print('\\tincorrect date format')\n return\n\n # save user data, check that pickle files exist before saving\n if not os.path.exists(os.path.join(self.working_dir, 'activity.pkl')):\n print('\\n\\tcould not find \\'activity.pkl\\', skipping.'\n '\\n\\trun \\'collect_hs_data\\' to retrieve these missing data')\n return\n\n # generate statistics\n session_stats.sessions_by_month(self.working_dir, self.outxls, st, et)\n session_stats.fig_session_by_month(self.working_dir, st, et)\n session_stats.fig_actions_by_university(self.working_dir, st, et)\n\n def do_calculate_resource_stats(self, args):\n \"\"\"\n Calculate session statistics from activity logs.\n\n usage: calculate_session_stats [a] [b]\n - a: start date, MM-DD-YYYY\n - b: end date, MM-DD-YYYY\n \"\"\"\n\n # parse the start and end dates\n dates = args.split()\n if len(dates) < 2:\n # set large date range\n et = datetime.now().strftime('%m-%d-%Y')\n dates = ['01-01-2000',\n et]\n\n # check date formats\n try:\n st = datetime.strptime(dates[0].strip(), '%m-%d-%Y')\n et = datetime.strptime(dates[1].strip(), '%m-%d-%Y')\n except ValueError:\n print('\\tincorrect date format')\n return\n\n # save user data, check that pickle files exist before saving\n if not os.path.exists(os.path.join(self.working_dir, 'activity.pkl')):\n print('\\n\\tcould not find \\'activity.pkl\\', skipping.'\n '\\n\\trun \\'collect_hs_data\\' to retrieve these missing data')\n return\n\n # generate statistics\n session_stats.resource_types_by_month(self.working_dir, self.outxls, st, et)\n\n def do_general_statistics(self, args):\n \"\"\"\n Computes general statistics, ideal for NSF reporting.\n usage: general_stats\n \"\"\"\n general_stats.run(self.working_dir, 1)\n\n\n def do_check_test_accounts(self, args):\n \"\"\"\n Run a check on test user accounts.\n\n usage: check_test_accounts [userdata.csv]\n - userdata.csv: a csv file containing \"usr_id\", \"username\", \"first_name\",\n and \"last_name\". This file is collected by exporting the \n auth_user table in the production dbshell.\n \"\"\"\n arguments = args.split()\n print(arguments)\n userdata = None\n if len(arguments) == 0:\n print('--> [userdata.csv] not provided. Looking for it in the current'\n ' directory... ', end='', flush=True)\n default_path = os.path.join(self.working_dir, 'userdata.csv')\n if not os.path.exists(default_path):\n print('\\n--> ERROR: Could not find userdata.csv. This file must'\n ' be collected from prod dbshell before continuing')\n return\n userdata = default_path\n print('done')\n else:\n userdata = arguments[1]\n\n check_for_test_users.run_check(self.working_dir, userdata)\n\n\n\n def do_user(self, args):\n\n \"\"\"\n Generate User Statistics from HydroShare logs.\n\n usage: users [function] [st] [et]\n - function: user function to invoke: \n - overview [options] [args]: create a summary users\n - options\n -c: aggregation integer\n -n: aggregation descriptor\n - args\n all: create an overview of all users\n active: create an overview of active users\n\n - stats: generate statistics summary table\n \n X- all: all user plots\n X- save: save data to xlsx\n X- overview: general overview of users\n X- new: summary of new users\n X- retained: summary of retained users\n - st: start date (optional), MM-DD-YYYY\n - et: end date (optional), MM-DD-YYYY\n \"\"\"\n funcs = ['all',\n 'save',\n 'overview',\n 'retained',\n 'new',\n 'stats',\n 'read-activity']\n\n kwargs = {}\n fargs = []\n arguments = args.split()\n if len(arguments) < 1:\n self.do_help('users')\n return\n elif arguments[0] not in funcs:\n print('Unrecognized command: \"%s\"' % arguments[0])\n return\n if len(arguments) > 1:\n ar = arguments[1:]\n try:\n while len(ar) > 0:\n k = ar.pop(0)\n if k[0] != '-':\n fargs.append(k)\n continue\n v = ar.pop(0)\n kwargs[k[1:]] = v\n except:\n print('Error parsing arguments\\n--> %s' % ' '.join(arguments))\n self.do_help('users')\n return\n\n\n# # parse the start and end dates\n# if len(arguments) != 3:\n# # set large date range\n# et = datetime.now().strftime('%m-%d-%Y')\n# arguments = [arguments[0],\n# '01-01-2000',\n# et]\n\n # check date formats\n st_str = kwargs.get('st', '01-01-2000')\n et_str = kwargs.get('et', datetime.now().strftime('%m-%d-%Y'))\n\n try:\n st = datetime.strptime(st_str, '%m-%d-%Y')\n except ValueError:\n st = datetime.strptime('01-01-2000', '%m-%d-%Y')\n print('\\tincorrect start date format, using default start date: 01-01-2000')\n try:\n et = datetime.strptime(et_str, '%m-%d-%Y')\n except ValueError:\n et = datetime.now()\n print('\\tincorrect end date format, using default start date: %s' % et.strftime('%m-%d-%Y'))\n\n # save user data, check that pickle files exist before saving\n if not os.path.exists(os.path.join(self.working_dir, 'activity.pkl')):\n print('\\n\\tcould not find \\'activity.pkl\\', skipping.'\n '\\n\\trun \\'collect_hs_data\\' to retrieve these missing data')\n return\n\n # generate statistics\n user = user_stats.Users(self.working_dir, self.outxls, st, et)\n \n func = arguments[0]\n# if func == 'all':\n# user.all()\n# elif func == 'save':\n# user.save()\n# elif func == 'overview':\n# user.users_over_time()\n if func == 'overview':\n user.generate_user_overview(*fargs, **kwargs)\n# elif func == 'new':\n# user.get_new_users()\n# elif func == 'retained':\n# user.users_retained()\n elif func == 'stats':\n user.user_stats()\n elif func == 'read-activity':\n return user.read_user_activity(**kwargs)\n\n def do_cwd(self, workingdir):\n \"\"\"\n Change working directory to another existing path\n\n usage: cwd [path]\n - path: an valid filepath\n\n \"\"\"\n\n if not os.path.exists(workingdir):\n print('\\n\\tpath does not exist: %s' % (workingdir))\n else:\n self.working_dir = workingdir\n\n print('\\n\\tcurrent working directory is %s' % (self.working_dir))\n\n\n# def do_del(self, name):\n# print('Deleted {}'.format(name))\n\n def do_ll(self, args):\n \"\"\"\n List files in your working directory\n \"\"\"\n result = subprocess.run(['ls', '-l', self.working_dir],\n stdout=subprocess.PIPE).stdout.decode('utf-8')\n print(result)\n\n def do_rm(self, args):\n \"\"\"\n Remove files within the working directory\n \"\"\"\n fmt_args = []\n for a in args.split(' '):\n # turn all non flags into paths relative to the working dir\n if a[0] != '-':\n a = os.path.join(self.working_dir, a)\n fmt_args.append(a)\n cmd = 'rm ' + ' '.join(fmt_args)\n result = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n out, err = result.communicate()\n if out != '': print(out.decode('utf-8'))\n if err != '': print(err.decode('utf-8'))\n\n def do_q(self, args):\n \"\"\"\n Exits the shell\n \"\"\"\n raise SystemExit()\n\nif __name__ == \"__main__\":\n dirname = None\n if len(sys.argv[1:]) > 0:\n if os.path.exists(sys.argv[1]):\n dirname = sys.argv[1]\n\n if dirname is None:\n\n # create a directory for these data\n dirname = datetime.now().strftime('%m.%d.%Y')\n\n i = 2\n while os.path.exists(dirname):\n dirname = dirname[:10] + '_%d' % i\n i += 1\n os.makedirs(dirname)\n\n app = MyCmd(dirname, 'stats.xlsx')\n app.cmdloop(40*'-' + '\\n\\tCUAHSI Metrics Shell\\n' + 40*'-' +\n '\\nEnter a command or \"help\" to list options' +\n '\\n\\nA directory for your session has been created at: %s'\n % dirname)\n","sub_path":"scripts/cms.py","file_name":"cms.py","file_ext":"py","file_size_in_byte":12494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"304674321","text":"import time\nimport mysql.connector\nimport keyboard\nimport os\nfrom pynput.keyboard import Key, Controller\nfrom mysql.connector import Error\nfrom array import array\nfrom threading import Thread\n\ndef listToString(s):\n str1 = ''\n for element in s:\n str1 += element[0] + '\\n'\n return str1\n\ntry:\n connection = mysql.connector.connect(\n host='localhost',\n database='enterprice',\n user='root',\n password=''\n )\n\n if connection.is_connected():\n db_info = connection.get_server_info()\n sql_select_Query = \"select name from countries\"\n cursor = connection.cursor()\n cursor.execute(sql_select_Query)\n records = cursor.fetchall()\n\nexcept mysql.connector.Error as error:\n records = \"Se conecto de forma erronea\"\nfinally:\n\n while True:\n try:\n if keyboard.is_pressed('f7'):\n\n keyboard_aux = Controller()\n\n text_list = listToString(records)\n\n for char in text_list:\n keyboard_aux.press(char)\n keyboard_aux.release(char)\n time.sleep(0.02)\n if keyboard.is_pressed('f8'):\n break\n if keyboard.is_pressed('f6'):\n while(keyboard.is_pressed('f7') == False):\n pass\n break\n\n except KeyboardInterrupt:\n\n break\n","sub_path":"InputRobot.py","file_name":"InputRobot.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"162754786","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nTC = 10\nfor tc in range(1):\n mynode, myline = map(int, input().split()) # 노드수, 간선수,\n mymap = [[0] * (mynode + 1) for i in range(mynode + 1)] # 2차원 맵 생성\n # 간선정보입력\n data = list(map(int, input().split())) # 2 1 1 3\n n = int(len(data) / 2) # 나누기 결과는 실수 -> 정수로 변환\n for i in range(n):\n start = data[i * 2] # 짝수 0,2,4,6,8\n end = data[i * 2 + 1] # 홀수 1,3,5,7,9\n mymap[end][start] = 1\n # print(mymap)\n result = [] # 작업경로 저장\n while True:\n if len(result) == mynode: # 전체 노드가 경로에 모두 저장되면 검색 중단\n break\n start_col = [] #\n for col in range(1, len(mymap)): # 모든 칼럼을 검색\n if 1 not in mymap[col] and col not in result: # 작업경로에 등록안된\n start_col.append(col) # 출발가능한 노드 등록\n\n for col in start_col:\n result.append(col) # 출발가능한 노드를 작업경로에 등록\n for row in range(len(mymap)):\n mymap[row][col] = 0 # 출발하는 노드로 연결되는 정보 삭제\n\n print(\"#%d\" % tc, end=\" \")\n for i in result:\n print(\"%d\" % i, end=\" \")\n print()","sub_path":"d6/1267_작업순서/guide.py","file_name":"guide.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"230813028","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Glances.\n#\n# Copyright (C) 2015 Nicolargo \n#\n# Glances is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser 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# Glances 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see .\n\n\"\"\"Curses interface class.\"\"\"\n\n# Import system lib\nimport sys\n\n# Import Glances lib\nfrom glances.core.glances_globals import is_mac, is_windows\nfrom glances.core.glances_logging import logger\nfrom glances.core.glances_logs import glances_logs\nfrom glances.core.glances_processes import glances_processes\nfrom glances.core.glances_timer import Timer\n\n# Import curses lib for \"normal\" operating system and consolelog for Windows\nif not is_windows:\n try:\n import curses\n import curses.panel\n from curses.textpad import Textbox\n except ImportError:\n logger.critical(\"Curses module not found. Glances cannot start in standalone mode.\")\n sys.exit(1)\nelse:\n from glances.outputs.glances_colorconsole import WCurseLight\n curses = WCurseLight()\n\n\nclass _GlancesCurses(object):\n\n \"\"\"\n This class manages the curses display (and key pressed).\n Note: It is a private class, use GlancesCursesClient or GlancesCursesBrowser\n \"\"\"\n\n def __init__(self, args=None):\n # Init args\n self.args = args\n\n # Init windows positions\n self.term_w = 80\n self.term_h = 24\n\n # Space between stats\n self.space_between_column = 3\n self.space_between_line = 2\n\n # Init the curses screen\n self.screen = curses.initscr()\n if not self.screen:\n logger.critical(\"Cannot init the curses library.\\n\")\n sys.exit(1)\n\n # Set curses options\n if hasattr(curses, 'start_color'):\n curses.start_color()\n if hasattr(curses, 'use_default_colors'):\n curses.use_default_colors()\n if hasattr(curses, 'noecho'):\n curses.noecho()\n if hasattr(curses, 'cbreak'):\n curses.cbreak()\n self.set_cursor(0)\n\n # Init colors\n self.hascolors = False\n if curses.has_colors() and curses.COLOR_PAIRS > 8:\n self.hascolors = True\n # FG color, BG color\n if args.theme_white:\n curses.init_pair(1, curses.COLOR_BLACK, -1)\n else:\n curses.init_pair(1, curses.COLOR_WHITE, -1)\n curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED)\n curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN)\n curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)\n curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA)\n curses.init_pair(6, curses.COLOR_RED, -1)\n curses.init_pair(7, curses.COLOR_GREEN, -1)\n curses.init_pair(8, curses.COLOR_BLUE, -1)\n try:\n curses.init_pair(9, curses.COLOR_MAGENTA, -1)\n except Exception:\n if args.theme_white:\n curses.init_pair(9, curses.COLOR_BLACK, -1)\n else:\n curses.init_pair(9, curses.COLOR_WHITE, -1)\n try:\n curses.init_pair(10, curses.COLOR_CYAN, -1)\n except Exception:\n if args.theme_white:\n curses.init_pair(10, curses.COLOR_BLACK, -1)\n else:\n curses.init_pair(10, curses.COLOR_WHITE, -1)\n\n else:\n self.hascolors = False\n\n if args.disable_bold:\n A_BOLD = curses.A_BOLD\n else:\n A_BOLD = 0\n\n self.title_color = A_BOLD\n self.title_underline_color = A_BOLD | curses.A_UNDERLINE\n self.help_color = A_BOLD\n if self.hascolors:\n # Colors text styles\n self.no_color = curses.color_pair(1)\n self.default_color = curses.color_pair(3) | A_BOLD\n self.nice_color = curses.color_pair(9) | A_BOLD\n self.ifCAREFUL_color = curses.color_pair(4) | A_BOLD\n self.ifWARNING_color = curses.color_pair(5) | A_BOLD\n self.ifCRITICAL_color = curses.color_pair(2) | A_BOLD\n self.default_color2 = curses.color_pair(7) | A_BOLD\n self.ifCAREFUL_color2 = curses.color_pair(8) | A_BOLD\n self.ifWARNING_color2 = curses.color_pair(9) | A_BOLD\n self.ifCRITICAL_color2 = curses.color_pair(6) | A_BOLD\n self.filter_color = curses.color_pair(10) | A_BOLD\n else:\n # B&W text styles\n self.no_color = curses.A_NORMAL\n self.default_color = curses.A_NORMAL\n self.nice_color = A_BOLD\n self.ifCAREFUL_color = curses.A_UNDERLINE\n self.ifWARNING_color = A_BOLD\n self.ifCRITICAL_color = curses.A_REVERSE\n self.default_color2 = curses.A_NORMAL\n self.ifCAREFUL_color2 = curses.A_UNDERLINE\n self.ifWARNING_color2 = A_BOLD\n self.ifCRITICAL_color2 = curses.A_REVERSE\n self.filter_color = A_BOLD\n\n # Define the colors list (hash table) for stats\n self.colors_list = {\n 'DEFAULT': self.no_color,\n 'UNDERLINE': curses.A_UNDERLINE,\n 'BOLD': A_BOLD,\n 'SORT': A_BOLD,\n 'OK': self.default_color2,\n 'FILTER': self.filter_color,\n 'TITLE': self.title_color,\n 'PROCESS': self.default_color2,\n 'STATUS': self.default_color2,\n 'NICE': self.nice_color,\n 'CAREFUL': self.ifCAREFUL_color2,\n 'WARNING': self.ifWARNING_color2,\n 'CRITICAL': self.ifCRITICAL_color2,\n 'OK_LOG': self.default_color,\n 'CAREFUL_LOG': self.ifCAREFUL_color,\n 'WARNING_LOG': self.ifWARNING_color,\n 'CRITICAL_LOG': self.ifCRITICAL_color\n }\n\n # Init main window\n self.term_window = self.screen.subwin(0, 0)\n\n # Init refresh time\n self.__refresh_time = args.time\n\n # Init process sort method\n self.args.process_sorted_by = 'auto'\n\n # Init edit filter tag\n self.edit_filter = False\n\n # Catch key pressed with non blocking mode\n self.term_window.keypad(1)\n self.term_window.nodelay(1)\n self.pressedkey = -1\n\n # History tag\n self.reset_history_tag = False\n self.history_tag = False\n if args.enable_history:\n logger.info('Stats history enabled with output path %s' %\n args.path_history)\n from glances.exports.glances_history import GlancesHistory\n self.glances_history = GlancesHistory(args.path_history)\n if not self.glances_history.graph_enabled():\n args.enable_history = False\n logger.error(\n 'Stats history disabled because MatPlotLib is not installed')\n\n def set_cursor(self, value):\n \"\"\"Configure the curse cursor apparence\n 0: invisible\n 1: visible\n 2: very visible\n \"\"\"\n if hasattr(curses, 'curs_set'):\n try:\n curses.curs_set(value)\n except Exception:\n pass\n\n def get_key(self, window):\n # Catch ESC key AND numlock key (issue #163)\n keycode = [0, 0]\n keycode[0] = window.getch()\n keycode[1] = window.getch()\n\n if keycode != [-1, -1]:\n logger.debug(\"Keypressed (code: %s)\" % keycode)\n\n if keycode[0] == 27 and keycode[1] != -1:\n # Do not escape on specials keys\n return -1\n else:\n return keycode[0]\n\n def __catch_key(self, return_to_browser=False):\n # Catch the pressed key\n self.pressedkey = self.get_key(self.term_window)\n\n # Actions...\n if self.pressedkey == ord('\\x1b') or self.pressedkey == ord('q'):\n # 'ESC'|'q' > Quit\n if return_to_browser:\n logger.info(\"Stop Glances client and return to the browser\")\n else:\n self.end()\n logger.info(\"Stop Glances\")\n sys.exit(0)\n elif self.pressedkey == 10:\n # 'ENTER' > Edit the process filter\n self.edit_filter = not self.edit_filter\n elif self.pressedkey == ord('1'):\n # '1' > Switch between CPU and PerCPU information\n self.args.percpu = not self.args.percpu\n elif self.pressedkey == ord('2'):\n # '2' > Enable/disable left sidebar\n self.args.disable_left_sidebar = not self.args.disable_left_sidebar\n elif self.pressedkey == ord('/'):\n # '/' > Switch between short/long name for processes\n self.args.process_short_name = not self.args.process_short_name\n elif self.pressedkey == ord('a'):\n # 'a' > Sort processes automatically\n self.args.process_sorted_by = 'auto'\n glances_processes.resetsort()\n elif self.pressedkey == ord('b'):\n # 'b' > Switch between bit/s and Byte/s for network IO\n # self.net_byteps_tag = not self.net_byteps_tag\n self.args.byte = not self.args.byte\n elif self.pressedkey == ord('c'):\n # 'c' > Sort processes by CPU usage\n self.args.process_sorted_by = 'cpu_percent'\n glances_processes.setmanualsortkey(self.args.process_sorted_by)\n elif self.pressedkey == ord('d'):\n # 'd' > Show/hide disk I/O stats\n self.args.disable_diskio = not self.args.disable_diskio\n elif self.pressedkey == ord('D'):\n # 'D' > Show/hide Docker stats\n self.args.disable_docker = not self.args.disable_docker\n elif self.pressedkey == ord('e'):\n # 'e' > Enable/Disable extended stats for top process\n self.args.enable_process_extended = not self.args.enable_process_extended\n if not self.args.enable_process_extended:\n glances_processes.disable_extended()\n else:\n glances_processes.enable_extended()\n elif self.pressedkey == ord('F'):\n # 'F' > Switch between FS available and free space\n self.args.fs_free_space = not self.args.fs_free_space\n elif self.pressedkey == ord('f'):\n # 'f' > Show/hide fs stats\n self.args.disable_fs = not self.args.disable_fs\n elif self.pressedkey == ord('g'):\n # 'g' > History\n self.history_tag = not self.history_tag\n elif self.pressedkey == ord('h'):\n # 'h' > Show/hide help\n self.args.help_tag = not self.args.help_tag\n elif self.pressedkey == ord('i'):\n # 'i' > Sort processes by IO rate (not available on OS X)\n self.args.process_sorted_by = 'io_counters'\n glances_processes.setmanualsortkey(self.args.process_sorted_by)\n elif self.pressedkey == ord('l'):\n # 'l' > Show/hide log messages\n self.args.disable_log = not self.args.disable_log\n elif self.pressedkey == ord('m'):\n # 'm' > Sort processes by MEM usage\n self.args.process_sorted_by = 'memory_percent'\n glances_processes.setmanualsortkey(self.args.process_sorted_by)\n elif self.pressedkey == ord('n'):\n # 'n' > Show/hide network stats\n self.args.disable_network = not self.args.disable_network\n elif self.pressedkey == ord('p'):\n # 'p' > Sort processes by name\n self.args.process_sorted_by = 'name'\n glances_processes.setmanualsortkey(self.args.process_sorted_by)\n elif self.pressedkey == ord('r'):\n # 'r' > Reset history\n self.reset_history_tag = not self.reset_history_tag\n elif self.pressedkey == ord('R'):\n # 'R' > Hide RAID plugins\n self.args.disable_raid = not self.args.disable_raid\n elif self.pressedkey == ord('s'):\n # 's' > Show/hide sensors stats (Linux-only)\n self.args.disable_sensors = not self.args.disable_sensors\n elif self.pressedkey == ord('t'):\n # 't' > Sort processes by TIME usage\n self.args.process_sorted_by = 'cpu_times'\n glances_processes.setmanualsortkey(self.args.process_sorted_by)\n elif self.pressedkey == ord('T'):\n # 'T' > View network traffic as sum Rx+Tx\n self.args.network_sum = not self.args.network_sum\n elif self.pressedkey == ord('u'):\n # 'u' > View cumulative network IO (instead of bitrate)\n self.args.network_cumul = not self.args.network_cumul\n elif self.pressedkey == ord('w'):\n # 'w' > Delete finished warning logs\n glances_logs.clean()\n elif self.pressedkey == ord('x'):\n # 'x' > Delete finished warning and critical logs\n glances_logs.clean(critical=True)\n elif self.pressedkey == ord('z'):\n # 'z' > Enable/Disable processes stats (count + list + monitor)\n # Enable/Disable display\n self.args.disable_process = not self.args.disable_process\n # Enable/Disable update\n if self.args.disable_process:\n glances_processes.disable()\n else:\n glances_processes.enable()\n # Return the key code\n return self.pressedkey\n\n def end(self):\n \"\"\"Shutdown the curses window.\"\"\"\n if hasattr(curses, 'echo'):\n curses.echo()\n if hasattr(curses, 'nocbreak'):\n curses.nocbreak()\n if hasattr(curses, 'curs_set'):\n try:\n curses.curs_set(1)\n except Exception:\n pass\n curses.endwin()\n\n def init_line_column(self):\n \"\"\"Init the line and column position for the curses inteface\"\"\"\n self.line = 0\n self.column = 0\n self.next_line = 0\n self.next_column = 0\n\n def init_line(self):\n \"\"\"Init the line position for the curses inteface\"\"\"\n self.line = 0\n self.next_line = 0\n\n def init_column(self):\n \"\"\"Init the column position for the curses inteface\"\"\"\n self.column = 0\n self.next_column = 0\n\n def new_line(self):\n \"\"\"New line in the curses interface\"\"\"\n self.line = self.next_line\n\n def new_column(self):\n \"\"\"New column in the curses interface\"\"\"\n self.column = self.next_column\n\n def display(self, stats, cs_status=\"None\"):\n \"\"\"Display stats on the screen.\n\n stats: Stats database to display\n cs_status:\n \"None\": standalone or server mode\n \"Connected\": Client is connected to a Glances server\n \"SNMP\": Client is connected to a SNMP server\n \"Disconnected\": Client is disconnected from the server\n\n Return:\n True if the stats have been displayed\n False if the help have been displayed\n \"\"\"\n # Init the internal line/column for Glances Curses\n self.init_line_column()\n\n # Get the screen size\n screen_x = self.screen.getmaxyx()[1]\n screen_y = self.screen.getmaxyx()[0]\n\n # No processes list in SNMP mode\n if cs_status == 'SNMP':\n # so... more space for others plugins\n plugin_max_width = 43\n else:\n plugin_max_width = None\n\n # Update the stats messages\n ###########################\n\n # Update the client server status\n self.args.cs_status = cs_status\n stats_system = stats.get_plugin(\n 'system').get_stats_display(args=self.args)\n stats_uptime = stats.get_plugin('uptime').get_stats_display()\n if self.args.percpu:\n stats_percpu = stats.get_plugin('percpu').get_stats_display()\n else:\n stats_cpu = stats.get_plugin('cpu').get_stats_display()\n stats_load = stats.get_plugin('load').get_stats_display()\n stats_mem = stats.get_plugin('mem').get_stats_display()\n stats_memswap = stats.get_plugin('memswap').get_stats_display()\n stats_network = stats.get_plugin('network').get_stats_display(\n args=self.args, max_width=plugin_max_width)\n stats_diskio = stats.get_plugin(\n 'diskio').get_stats_display(args=self.args)\n stats_fs = stats.get_plugin('fs').get_stats_display(\n args=self.args, max_width=plugin_max_width)\n stats_raid = stats.get_plugin('raid').get_stats_display(\n args=self.args)\n stats_sensors = stats.get_plugin(\n 'sensors').get_stats_display(args=self.args)\n stats_now = stats.get_plugin('now').get_stats_display()\n stats_docker = stats.get_plugin('docker').get_stats_display(\n args=self.args)\n stats_processcount = stats.get_plugin(\n 'processcount').get_stats_display(args=self.args)\n stats_monitor = stats.get_plugin(\n 'monitor').get_stats_display(args=self.args)\n stats_alert = stats.get_plugin(\n 'alert').get_stats_display(args=self.args)\n\n # Adapt number of processes to the available space\n max_processes_displayed = screen_y - 11 - \\\n self.get_stats_display_height(stats_alert) - \\\n self.get_stats_display_height(stats_docker)\n if self.args.enable_process_extended and not self.args.process_tree:\n max_processes_displayed -= 4\n if max_processes_displayed < 0:\n max_processes_displayed = 0\n if glances_processes.get_max_processes() is None or \\\n glances_processes.get_max_processes() != max_processes_displayed:\n logger.debug(\"Set number of displayed processes to %s\" %\n max_processes_displayed)\n glances_processes.set_max_processes(max_processes_displayed)\n\n stats_processlist = stats.get_plugin(\n 'processlist').get_stats_display(args=self.args)\n\n # Display the stats on the curses interface\n ###########################################\n\n # Help screen (on top of the other stats)\n if self.args.help_tag:\n # Display the stats...\n self.display_plugin(\n stats.get_plugin('help').get_stats_display(args=self.args))\n # ... and exit\n return False\n\n # Display first line (system+uptime)\n self.new_line()\n l = self.get_stats_display_width(\n stats_system) + self.get_stats_display_width(stats_uptime) + self.space_between_column\n self.display_plugin(stats_system, display_optional=(screen_x >= l))\n self.new_column()\n self.display_plugin(stats_uptime)\n\n # Display second line (CPU|PERCPU+LOAD+MEM+SWAP+
)\n # CPU|PERCPU\n self.init_column()\n self.new_line()\n if self.args.percpu:\n l = self.get_stats_display_width(stats_percpu)\n else:\n l = self.get_stats_display_width(stats_cpu)\n l += self.get_stats_display_width(stats_load) + self.get_stats_display_width(\n stats_mem) + self.get_stats_display_width(stats_memswap)\n # Space between column\n space_number = int(stats_load['msgdict'] != [\n ]) + int(stats_mem['msgdict'] != []) + int(stats_memswap['msgdict'] != [])\n if space_number == 0:\n space_number = 1\n if screen_x > (space_number * self.space_between_column + l):\n self.space_between_column = int((screen_x - l) / space_number)\n # Display\n if self.args.percpu:\n self.display_plugin(stats_percpu)\n else:\n self.display_plugin(stats_cpu, display_optional=(screen_x >= 80))\n self.new_column()\n self.display_plugin(stats_load)\n self.new_column()\n self.display_plugin(stats_mem, display_optional=(\n screen_x >= (space_number * self.space_between_column + l)))\n self.new_column()\n self.display_plugin(stats_memswap)\n # Space between column\n self.space_between_column = 3\n\n # Backup line position\n self.saved_line = self.next_line\n\n # Display left sidebar (NETWORK+DISKIO+FS+SENSORS+Current time)\n self.init_column()\n if (not (self.args.disable_network and self.args.disable_diskio\n and self.args.disable_fs and self.args.disable_raid\n and self.args.disable_sensors)) \\\n and not self.args.disable_left_sidebar:\n self.new_line()\n self.display_plugin(stats_network)\n self.new_line()\n self.display_plugin(stats_diskio)\n self.new_line()\n self.display_plugin(stats_fs)\n self.new_line()\n self.display_plugin(stats_raid)\n self.new_line()\n self.display_plugin(stats_sensors)\n self.new_line()\n self.display_plugin(stats_now)\n\n # If space available...\n if screen_x > 52:\n # Restore line position\n self.next_line = self.saved_line\n\n # Display right sidebar\n # ((DOCKER)+PROCESS_COUNT+(MONITORED)+PROCESS_LIST+ALERT)\n self.new_column()\n self.new_line()\n self.display_plugin(stats_docker)\n self.new_line()\n self.display_plugin(stats_processcount)\n if glances_processes.get_process_filter() is None and cs_status == 'None':\n # Do not display stats monitor list if a filter exist\n self.new_line()\n self.display_plugin(stats_monitor)\n self.new_line()\n self.display_plugin(stats_processlist,\n display_optional=(screen_x > 102),\n display_additional=(not is_mac),\n max_y=(screen_y - self.get_stats_display_height(stats_alert) - 2))\n self.new_line()\n self.display_plugin(stats_alert)\n\n # History option\n # Generate history graph\n if self.history_tag and self.args.enable_history:\n self.display_popup(\n _(\"Generate graphs history in %s\\nPlease wait...\") % self.glances_history.get_output_folder())\n self.display_popup(\n _(\"Generate graphs history in %s\\nDone: %s graphs generated\") % (self.glances_history.get_output_folder(), self.glances_history.generate_graph(stats)))\n elif self.reset_history_tag and self.args.enable_history:\n self.display_popup(_(\"Reset history\"))\n self.glances_history.reset(stats)\n elif (self.history_tag or self.reset_history_tag) and not self.args.enable_history:\n try:\n self.glances_history.graph_enabled()\n except Exception:\n self.display_popup(\n _(\"History disabled\\nEnable it using --enable-history\"))\n else:\n self.display_popup(\n _(\"History disabled\\nPlease install MatPlotLib\"))\n self.history_tag = False\n self.reset_history_tag = False\n\n # Display edit filter popup\n # Only in standalone mode (cs_status == 'None')\n if self.edit_filter and cs_status == 'None':\n new_filter = self.display_popup(_(\"Process filter pattern: \"),\n is_input=True,\n input_value=glances_processes.get_process_filter())\n glances_processes.set_process_filter(new_filter)\n elif self.edit_filter and cs_status != 'None':\n self.display_popup(\n _(\"Process filter only available in standalone mode\"))\n self.edit_filter = False\n\n return True\n\n def display_popup(self, message,\n size_x=None, size_y=None,\n duration=3,\n is_input=False,\n input_size=30,\n input_value=None):\n \"\"\"\n If is_input is False:\n Display a centered popup with the given message during duration seconds\n If size_x and size_y: set the popup size\n else set it automatically\n Return True if the popup could be displayed\n If is_input is True:\n Display a centered popup with the given message and a input field\n If size_x and size_y: set the popup size\n else set it automatically\n Return the input string or None if the field is empty\n \"\"\"\n\n # Center the popup\n sentence_list = message.split('\\n')\n if size_x is None:\n size_x = len(max(sentence_list, key=len)) + 4\n # Add space for the input field\n if is_input:\n size_x += input_size\n if size_y is None:\n size_y = len(sentence_list) + 4\n screen_x = self.screen.getmaxyx()[1]\n screen_y = self.screen.getmaxyx()[0]\n if size_x > screen_x or size_y > screen_y:\n # No size to display the popup => abord\n return False\n pos_x = int((screen_x - size_x) / 2)\n pos_y = int((screen_y - size_y) / 2)\n\n # Create the popup\n popup = curses.newwin(size_y, size_x, pos_y, pos_x)\n\n # Fill the popup\n popup.border()\n\n # Add the message\n y = 0\n for m in message.split('\\n'):\n popup.addnstr(2 + y, 2, m, len(m))\n y += 1\n\n if is_input and not is_windows:\n # Create a subwindow for the text field\n subpop = popup.derwin(1, input_size, 2, 2 + len(m))\n subpop.attron(self.colors_list['FILTER'])\n # Init the field with the current value\n if input_value is not None:\n subpop.addnstr(0, 0, input_value, len(input_value))\n # Display the popup\n popup.refresh()\n subpop.refresh()\n # Create the textbox inside the subwindows\n self.set_cursor(2)\n textbox = GlancesTextbox(subpop, insert_mode=False)\n textbox.edit()\n self.set_cursor(0)\n if textbox.gather() != '':\n logger.debug(\n \"User enters the following process filter patern: %s\" % textbox.gather())\n return textbox.gather()[:-1]\n else:\n logger.debug(\"User clears the process filter patern\")\n return None\n else:\n # Display the popup\n popup.refresh()\n curses.napms(duration * 1000)\n return True\n\n def display_plugin(self, plugin_stats,\n display_optional=True,\n display_additional=True,\n max_y=65535):\n \"\"\"Display the plugin_stats on the screen.\n\n If display_optional=True display the optional stats\n If display_additional=True display additionnal stats\n max_y do not display line > max_y\n \"\"\"\n # Exit if:\n # - the plugin_stats message is empty\n # - the display tag = False\n if not plugin_stats['msgdict'] or not plugin_stats['display']:\n # Exit\n return 0\n\n # Get the screen size\n screen_x = self.screen.getmaxyx()[1]\n screen_y = self.screen.getmaxyx()[0]\n\n # Set the upper/left position of the message\n if plugin_stats['align'] == 'right':\n # Right align (last column)\n display_x = screen_x - self.get_stats_display_width(plugin_stats)\n else:\n display_x = self.column\n if plugin_stats['align'] == 'bottom':\n # Bottom (last line)\n display_y = screen_y - self.get_stats_display_height(plugin_stats)\n else:\n display_y = self.line\n\n # Display\n x = display_x\n x_max = x\n y = display_y\n for m in plugin_stats['msgdict']:\n # New line\n if m['msg'].startswith('\\n'):\n # Go to the next line\n y = y + 1\n # Return to the first column\n x = display_x\n continue\n # Do not display outside the screen\n if x < 0:\n continue\n if not m['splittable'] and (x + len(m['msg']) > screen_x):\n continue\n if y < 0 or (y + 1 > screen_y) or (y > max_y):\n break\n # If display_optional = False do not display optional stats\n if not display_optional and m['optional']:\n continue\n # If display_additional = False do not display additional stats\n if not display_additional and m['additional']:\n continue\n # Is it possible to display the stat with the current screen size\n # !!! Crach if not try/except... Why ???\n try:\n self.term_window.addnstr(y, x,\n m['msg'],\n # Do not disply outside the screen\n screen_x - x,\n self.colors_list[m['decoration']])\n except Exception:\n pass\n else:\n # New column\n try:\n # Python 2: we need to decode to get real screen size because utf-8 special tree chars\n # occupy several bytes\n offset = len(m['msg'].decode(\"utf-8\"))\n except AttributeError:\n # Python 3: strings are strings and bytes are bytes, all is\n # good\n offset = len(m['msg'])\n x = x + offset\n if x > x_max:\n x_max = x\n\n # Compute the next Glances column/line position\n self.next_column = max(self.next_column, x_max + self.space_between_column)\n self.next_line = max(self.next_line, y + self.space_between_line)\n\n def erase(self):\n \"\"\"Erase the content of the screen.\"\"\"\n self.term_window.erase()\n\n def flush(self, stats, cs_status=\"None\"):\n \"\"\"Clear and update the screen.\n\n stats: Stats database to display\n cs_status:\n \"None\": standalone or server mode\n \"Connected\": Client is connected to the server\n \"Disconnected\": Client is disconnected from the server\n \"\"\"\n self.erase()\n self.display(stats, cs_status=cs_status)\n\n def update(self, stats, cs_status=\"None\", return_to_browser=False):\n \"\"\"Update the screen.\n\n Wait for __refresh_time sec / catch key every 100 ms.\n\n INPUT\n stats: Stats database to display\n cs_status:\n \"None\": standalone or server mode\n \"Connected\": Client is connected to the server\n \"Disconnected\": Client is disconnected from the server\n return_to_browser:\n True: Do not exist, return to the browser list\n False: Exit and return to the shell\n\n OUPUT\n True: Exit key has been pressed\n False: Others cases...\n \"\"\"\n # Flush display\n self.flush(stats, cs_status=cs_status)\n\n # Wait\n exitkey = False\n countdown = Timer(self.__refresh_time)\n while not countdown.finished() and not exitkey:\n # Getkey\n pressedkey = self.__catch_key(return_to_browser=return_to_browser)\n # Is it an exit key ?\n exitkey = (pressedkey == ord('\\x1b') or pressedkey == ord('q'))\n if not exitkey and pressedkey > -1:\n # Redraw display\n self.flush(stats, cs_status=cs_status)\n # Wait 100ms...\n curses.napms(100)\n\n return exitkey\n\n def get_stats_display_width(self, curse_msg, without_option=False):\n \"\"\"Return the width of the formatted curses message.\n\n The height is defined by the maximum line.\n \"\"\"\n try:\n if without_option:\n # Size without options\n c = len(max(''.join([(i['msg'] if not i['optional'] else \"\")\n for i in curse_msg['msgdict']]).split('\\n'), key=len))\n else:\n # Size with all options\n c = len(max(''.join([i['msg']\n for i in curse_msg['msgdict']]).split('\\n'), key=len))\n except Exception:\n return 0\n else:\n return c\n\n def get_stats_display_height(self, curse_msg):\n r\"\"\"Return the height of the formatted curses message.\n\n The height is defined by the number of '\\n' (new line).\n \"\"\"\n try:\n c = [i['msg'] for i in curse_msg['msgdict']].count('\\n')\n except Exception:\n return 0\n else:\n return c + 1\n\n\nclass GlancesCursesStandalone(_GlancesCurses):\n\n \"\"\"Class for the Glances' curse standalone\"\"\"\n\n pass\n\n\nclass GlancesCursesClient(_GlancesCurses):\n\n \"\"\"Class for the Glances' curse client\"\"\"\n\n pass\n\n\nclass GlancesCursesBrowser(_GlancesCurses):\n\n \"\"\"Class for the Glances' curse client browser\"\"\"\n\n def __init__(self, args=None):\n # Init the father class\n _GlancesCurses.__init__(self, args=args)\n\n _colors_list = {\n 'UNKNOWN': self.no_color,\n 'SNMP': self.default_color2,\n 'ONLINE': self.default_color2,\n 'OFFLINE': self.ifCRITICAL_color2,\n 'PROTECTED': self.ifWARNING_color2,\n }\n self.colors_list.update(_colors_list)\n\n # First time scan tag\n # Used to display a specific message when the browser is started\n self.first_scan = True\n\n # Init refresh time\n self.__refresh_time = args.time\n\n # Init the cursor position for the client browser\n self.cursor_init()\n\n # Active Glances server number\n self.set_active()\n\n def set_active(self, index=None):\n \"\"\"Set the active server or None if no server selected\"\"\"\n self.active_server = index\n return self.active_server\n\n def get_active(self):\n \"\"\"Return the active server (the one display in front) or None if it is the browser list\"\"\"\n return self.active_server\n\n def cursor_init(self):\n \"\"\"Init the cursor position to the top of the list\"\"\"\n return self.cursor_set(0)\n\n def cursor_set(self, pos):\n \"\"\"Set the cursor position and return it\"\"\"\n self.cursor_position = pos\n return self.cursor_position\n\n def cursor_get(self):\n \"\"\"Return the cursor position\"\"\"\n return self.cursor_position\n\n def cursor_up(self, servers_list):\n \"\"\"Set the cursor to position N-1 in the list\"\"\"\n if self.cursor_position > 0:\n self.cursor_position -= 1\n else:\n self.cursor_position = len(servers_list) - 1\n return self.cursor_position\n\n def cursor_down(self, servers_list):\n \"\"\"Set the cursor to position N-1 in the list\"\"\"\n if self.cursor_position < len(servers_list) - 1:\n self.cursor_position += 1\n else:\n self.cursor_position = 0\n return self.cursor_position\n\n def __catch_key(self, servers_list):\n # Catch the browser pressed key\n self.pressedkey = self.get_key(self.term_window)\n\n # Actions...\n if self.pressedkey == ord('\\x1b') or self.pressedkey == ord('q'):\n # 'ESC'|'q' > Quit\n self.end()\n logger.info(\"Stop Glances client browser\")\n sys.exit(0)\n elif self.pressedkey == 10:\n # 'ENTER' > Run Glances on the selected server\n logger.debug(\"Server number %s selected\" % (self.cursor_get() + 1))\n self.set_active(self.cursor_get())\n elif self.pressedkey == 259:\n # 'UP' > Up in the server list\n logger\n self.cursor_up(servers_list)\n elif self.pressedkey == 258:\n # 'DOWN' > Down in the server list\n self.cursor_down(servers_list)\n\n # Return the key code\n return self.pressedkey\n\n def update(self, servers_list):\n \"\"\"Update the servers' list screen.\n\n Wait for __refresh_time sec / catch key every 100 ms.\n\n servers_list: Dict of dict with servers stats\n \"\"\"\n # Flush display\n self.flush(servers_list)\n\n # Wait\n exitkey = False\n countdown = Timer(self.__refresh_time)\n while not countdown.finished() and not exitkey:\n # Getkey\n pressedkey = self.__catch_key(servers_list)\n # Is it an exit or select server key ?\n exitkey = (\n pressedkey == ord('\\x1b') or pressedkey == ord('q') or pressedkey == 10)\n if not exitkey and pressedkey > -1:\n # Redraw display\n self.flush(servers_list)\n # Wait 100ms...\n curses.napms(100)\n\n return self.get_active()\n\n def flush(self, servers_list):\n \"\"\"Update the servers' list screen.\n servers_list: List of dict with servers stats\n \"\"\"\n self.erase()\n self.display(servers_list)\n\n def display(self, servers_list):\n \"\"\"Display the servers list\n Return:\n True if the stats have been displayed\n False if the stats have not been displayed (no server available)\n \"\"\"\n # Init the internal line/column for Glances Curses\n self.init_line_column()\n\n # Get the current screen size\n screen_x = self.screen.getmaxyx()[1]\n screen_y = self.screen.getmaxyx()[0]\n\n # Init position\n x = 0\n y = 0\n\n # Display top header\n if len(servers_list) == 0:\n if self.first_scan and not self.args.disable_autodiscover:\n msg = _(\"Glances is scanning your network (please wait)...\")\n self.first_scan = False\n else:\n msg = _(\"No Glances servers available\")\n elif len(servers_list) == 1:\n msg = _(\"One Glances server available\")\n else:\n msg = _(\"%d Glances servers available\" %\n len(servers_list))\n if self.args.disable_autodiscover:\n msg += ' ' + _(\"(auto discover is disabled)\")\n self.term_window.addnstr(y, x,\n msg,\n screen_x - x,\n self.colors_list['TITLE'])\n\n if len(servers_list) == 0:\n return False\n\n # Display the Glances server list\n #================================\n\n # Table of table\n # Item description: [stats_id, column name, column size]\n column_def = [\n ['name', _('Name'), 16],\n ['alias', None, None],\n ['load_min5', _('LOAD'), 6],\n ['cpu_percent', _('CPU%'), 5],\n ['mem_percent', _('MEM%'), 5],\n ['status', _('STATUS'), 8],\n ['ip', _('IP'), 15],\n # ['port', _('PORT'), 5],\n ['hr_name', _('OS'), 16],\n ]\n y = 2\n\n # Display table header\n cpt = 0\n xc = x + 2\n for c in column_def:\n if xc < screen_x and y < screen_y and c[1] is not None:\n self.term_window.addnstr(y, xc,\n c[1],\n screen_x - x,\n self.colors_list['BOLD'])\n xc += c[2] + self.space_between_column\n cpt += 1\n y += 1\n\n # If a servers has been deleted from the list...\n # ... and if the cursor is in the latest position\n if self.cursor_get() > len(servers_list) - 1:\n # Set the cursor position to the latest item\n self.cursor_set(len(servers_list) - 1)\n\n # Display table\n line = 0\n for v in servers_list:\n # Get server stats\n server_stat = {}\n for c in column_def:\n try:\n server_stat[c[0]] = v[c[0]]\n except KeyError as e:\n logger.debug(\n \"Cannot grab stats {0} from server (KeyError: {1})\".format(c[0], e))\n server_stat[c[0]] = '?'\n # Display alias instead of name\n try:\n if c[0] == 'alias' and v[c[0]] is not None:\n server_stat['name'] = v[c[0]]\n except KeyError as e:\n pass\n\n # Display line for server stats\n cpt = 0\n xc = x\n\n # Is the line selected ?\n if line == self.cursor_get():\n # Display cursor\n self.term_window.addnstr(y, xc,\n \">\",\n screen_x - xc,\n self.colors_list['BOLD'])\n\n # Display alias instead of name\n server_stat\n\n # Display the line\n xc += 2\n for c in column_def:\n if xc < screen_x and y < screen_y and c[1] is not None:\n # Display server stats\n self.term_window.addnstr(y, xc,\n \"%s\" % server_stat[c[0]],\n c[2],\n self.colors_list[v['status']])\n xc += c[2] + self.space_between_column\n cpt += 1\n # Next line, next server...\n y += 1\n line += 1\n\n return True\n\n\nif not is_windows:\n class GlancesTextbox(Textbox):\n\n def __init__(*args, **kwargs):\n Textbox.__init__(*args, **kwargs)\n\n def do_command(self, ch):\n if ch == 10: # Enter\n return 0\n if ch == 127: # Enter\n return 8\n return Textbox.do_command(self, ch)\n","sub_path":"usr/lib/python3/dist-packages/glances/outputs/glances_curses.py","file_name":"glances_curses.py","file_ext":"py","file_size_in_byte":42576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"645732134","text":"import psycopg2\nimport psycopg2.extras\n\n\nclass DBInterface():\n\n def __init__(self, connection):\n self.connection = connection\n\n def get_cursor(self):\n return self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n def existing_ads(self):\n cursor = self.get_cursor()\n existing_ad_query = \"select archive_id, ad_delivery_stop_time from ads\"\n cursor.execute(existing_ad_query)\n ads_to_end_time_map = dict()\n for row in cursor:\n ad_stop_time = row['ad_delivery_stop_time']\n ads_to_end_time_map[row['archive_id']] = ad_stop_time\n return ads_to_end_time_map\n\n def existing_pages(self):\n cursor = self.get_cursor()\n existing_pages_query = \"select page_id, page_name from pages;\"\n cursor.execute(existing_pages_query)\n existing_pages = set()\n for row in cursor:\n existing_pages.add(row['page_id'])\n return existing_pages\n\n def existing_funding_entities(self):\n cursor = self.get_cursor()\n existing_funder_query = \"select funder_id, funder_name from funder_metadata;\"\n cursor.execute(existing_funder_query)\n existing_funders = dict()\n for row in cursor:\n existing_funders[row['funder_name']] = row['funder_id']\n return existing_funders\n\n def all_archive_ids_that_need_scrape(self):\n \"\"\"Get ALL ad archive IDs marked as needs_scrape in ad_snapshot_metadata.\n\n Args:\n cursor: pyscopg2.Cursor DB cursor for query execution.\n Returns:\n list of archive IDs (str).\n \"\"\"\n cursor = self.get_cursor()\n archive_ids_sample_query = cursor.mogrify(\n 'SELECT archive_id from ad_snapshot_metadata '\n 'WHERE needs_scrape = TRUE')\n cursor.execute(archive_ids_sample_query)\n results = cursor.fetchall()\n return [row['archive_id'] for row in results]\n\n def n_archive_ids_that_need_scrape(self, max_archive_ids=200):\n \"\"\"Get N number of archive IDs marked as needs_scrape in ad_snapshot_metadata.\n Args:\n cursor: pyscopg2.Cursor DB cursor for query execution.\n max_archive_ids: int, limit on how many IDs to query DB for.\n Returns:\n list of archive IDs (str).\n \"\"\"\n cursor = self.get_cursor()\n archive_ids_sample_query = cursor.mogrify(\n 'SELECT archive_id from ad_snapshot_metadata '\n 'WHERE needs_scrape = TRUE LIMIT %s;' % max_archive_ids)\n cursor.execute(archive_ids_sample_query)\n results = cursor.fetchall()\n return [row['archive_id'] for row in results]\n\n def duplicate_ad_creative_text_simhashes(self):\n \"\"\"Returns list of ad creative text simhashes appearing 2 or more times.\n \"\"\"\n cursor = self.get_cursor()\n duplicate_simhash_query = (\n 'select text_sim_hash from ad_creatives group by text_sim_hash having count(*) > 1'\n )\n cursor.execute(duplicate_simhash_query)\n results = cursor.fetchall()\n return [row['text_sim_hash'] for row in results]\n\n def archive_ids_with_ad_creative_text_simhash(self, simhash):\n \"\"\"Returns list of archive_id with specified body text simhash.\n\n Args:\n simhash: simhash (hex value as string (without leading 0x) to look\n for.\n Returns:\n list of archive_id (str) where ads_creatives.text_sim_hash matches\n specified simhash.\n \"\"\"\n cursor = self.get_cursor()\n ids_with_simhash_query_template = (\n 'SELECT archive_id FROM ad_creatives WHERE text_sim_hash = %s')\n cursor.execute(ids_with_simhash_query_template, (simhash,))\n return [row['archive_id'] for row in cursor.fetchall()]\n\n def ad_creative_ids_with_text_simhash(self, simhash):\n \"\"\"Returns list of ad_creative_id with specified body text simhash.\n\n Args:\n simhash: simhash (hex value as string (without leading 0x) to look\n for.\n Returns:\n list of ad_creative_id (str) where ads_creatives.text_sim_hash\n matches specified simhash.\n \"\"\"\n cursor = self.get_cursor()\n ids_with_simhash_query_template = (\n 'SELECT ad_creative_id FROM ad_creatives WHERE text_sim_hash = %s')\n cursor.execute(ids_with_simhash_query_template, (simhash,))\n return [row['ad_creative_id'] for row in cursor.fetchall()]\n\n def all_ad_creative_ids_with_duplicated_simhash(self):\n \"\"\"Returns map of ad creative body simhash -> ad_creative_id for\n simhashes that appear 2 or more times in database.\n\n Returns: dict of simhash (str) -> ad_creative_id (str) where all\n ad_creative_body simhash match the simhash key. Dict only hash simhashes\n that appear 2 or more times in database.\n \"\"\"\n duplicate_simhashes = self.duplicate_ad_creative_text_simhashes()\n simhash_to_id = {}\n for simhash in duplicate_simhashes:\n simhash_to_id[simhash] = self.ad_creative_ids_with_text_simhash(\n simhash)\n return simhash_to_id\n\n def insert_funding_entities(self, new_funders):\n cursor = self.get_cursor()\n insert_funder_query = \"INSERT INTO funder_metadata(funder_name) VALUES %s;\"\n insert_template = \"(%s)\"\n psycopg2.extras.execute_values(cursor,\n insert_funder_query,\n new_funders,\n template=insert_template,\n page_size=250)\n\n def insert_pages(self, new_pages):\n cursor = self.get_cursor()\n insert_page_query = (\"INSERT INTO pages(page_id, page_name) VALUES %s \"\n \"on conflict (page_id) do nothing;\")\n insert_template = \"(%(id)s, %(name)s)\"\n new_page_list = [x._asdict() for x in new_pages]\n\n psycopg2.extras.execute_values(cursor,\n insert_page_query,\n new_page_list,\n template=insert_template,\n page_size=250)\n\n def insert_page_metadata(self, new_page_metadata):\n cursor = self.get_cursor()\n insert_page_metadata_query = (\n \"INSERT INTO page_metadata(page_id, page_url, federal_candidate) VALUES %s \"\n \"on conflict (page_id) do nothing;\")\n insert_template = \"(%(id)s, %(url)s, %(federal_candidate)s)\"\n new_page_metadata_list = [x._asdict() for x in new_page_metadata]\n psycopg2.extras.execute_values(\n cursor, insert_page_metadata_query, new_page_metadata_list, template=insert_template, page_size=250)\n\n\n def insert_new_ads(self, new_ads):\n cursor = self.get_cursor()\n ad_insert_query = (\n \"INSERT INTO ads(archive_id, ad_creative_body, ad_creation_time, \"\n \"ad_delivery_start_time, ad_delivery_stop_time, page_id, currency, \"\n \"ad_creative_link_caption, ad_creative_link_title, ad_creative_link_description, \"\n \"ad_snapshot_url, funding_entity) VALUES %s on conflict (archive_id) do nothing;\"\n )\n insert_template = (\n \"(%(archive_id)s, %(ad_creative_body)s, %(ad_creation_time)s, \"\n \"%(ad_delivery_start_time)s, %(ad_delivery_stop_time)s, %(page_id)s, %(currency)s, \"\n \"%(ad_creative_link_caption)s, %(ad_creative_link_title)s, \"\n \"%(ad_creative_link_description)s, %(ad_snapshot_url)s, %(funding_entity)s)\"\n )\n new_ad_list = [x._asdict() for x in new_ads]\n psycopg2.extras.execute_values(cursor,\n ad_insert_query,\n new_ad_list,\n template=insert_template,\n page_size=250)\n\n ad_insert_query = (\n \"INSERT INTO ad_countries(archive_id, country_code) VALUES %s on conflict (archive_id, \"\n \"country_code) do nothing;\")\n insert_template = (\"(%(archive_id)s, %(country_code)s)\")\n psycopg2.extras.execute_values(cursor,\n ad_insert_query,\n new_ad_list,\n template=insert_template,\n page_size=250)\n\n # Mark newly found archive_id as needing scrape.\n snapshot_metadata_insert_query = (\n \"INSERT INTO ad_snapshot_metadata (archive_id, needs_scrape) \"\n \"VALUES %s on conflict (archive_id) do nothing;\")\n insert_template = (\"(%(archive_id)s, TRUE)\")\n psycopg2.extras.execute_values(cursor,\n snapshot_metadata_insert_query,\n new_ad_list,\n template=insert_template,\n page_size=250)\n\n def insert_new_impressions(self, new_impressions):\n cursor = self.get_cursor()\n impressions_insert_query = (\n \"INSERT INTO impressions(archive_id, ad_status, min_spend, max_spend, min_impressions, \"\n \"max_impressions) VALUES %s on conflict (archive_id) do update set \"\n \"ad_status = EXCLUDED.ad_status, min_spend = EXCLUDED.min_spend, \"\n \"max_spend = EXCLUDED.max_spend, min_impressions = EXCLUDED.min_impressions, \"\n \"max_impressions = EXCLUDED.max_impressions;\")\n\n insert_template = (\n \"(%(archive_id)s, %(ad_status)s , %(spend__lower_bound)s, %(spend__upper_bound)s, \"\n \"%(impressions__lower_bound)s , %(impressions__upper_bound)s)\")\n new_impressions_list = ([\n impression._asdict() for impression in new_impressions\n ])\n\n psycopg2.extras.execute_values(cursor,\n impressions_insert_query,\n new_impressions_list,\n template=insert_template,\n page_size=250)\n\n def insert_new_impression_demos(self, new_ad_demo_impressions):\n demo_impressions_list = ([\n impression._asdict() for impression in new_ad_demo_impressions\n ])\n cursor = self.get_cursor()\n impression_demo_insert_query = (\n \"INSERT INTO demo_impressions(archive_id, age_group, gender, spend_percentage) \"\n \"VALUES %s on conflict on constraint unique_demos_per_ad do update set \"\n \"spend_percentage = EXCLUDED.spend_percentage;\")\n insert_template = (\n '(%(archive_id)s, %(age_range)s, %(gender)s, %(spend_percentage)s)')\n\n psycopg2.extras.execute_values(cursor,\n impression_demo_insert_query,\n demo_impressions_list,\n template=insert_template,\n page_size=250)\n\n impression_demo_result_insert_query = (\n \"INSERT INTO demo_impression_results(archive_id, age_group, gender, min_impressions, \"\n \"min_spend, max_impressions, max_spend) \"\n \"VALUES %s on conflict on constraint unique_demo_results do update \"\n \"set min_impressions = EXCLUDED.min_impressions, \"\n \"min_spend = EXCLUDED.min_spend, max_impressions = EXCLUDED.max_impressions, \"\n \"max_spend = EXCLUDED.max_spend;\")\n insert_template = (\n \"(%(archive_id)s, %(age_range)s, %(gender)s, %(min_impressions)s, %(min_spend)s, \"\n \"%(max_impressions)s , %(max_spend)s)\")\n psycopg2.extras.execute_values(cursor,\n impression_demo_result_insert_query,\n demo_impressions_list,\n template=insert_template,\n page_size=250)\n\n def insert_new_impression_regions(self, new_ad_region_impressions):\n region_impressions_list = ([\n impression._asdict() for impression in new_ad_region_impressions\n ])\n cursor = self.get_cursor()\n impression_region_insert_query = (\n \"INSERT INTO region_impressions(archive_id, region, spend_percentage) \"\n \"VALUES %s on conflict on constraint unique_regions_per_ad \"\n \"do update set spend_percentage = EXCLUDED.spend_percentage;\")\n insert_template = (\"(%(archive_id)s, %(region)s, %(spend_percentage)s)\")\n psycopg2.extras.execute_values(cursor,\n impression_region_insert_query,\n region_impressions_list,\n template=insert_template,\n page_size=250)\n impression_region_insert_query = (\n \"INSERT INTO region_impression_results(archive_id, region, min_impressions, min_spend, \"\n \"max_impressions, max_spend) VALUES %s on conflict on constraint unique_region_results \"\n \"do update set min_impressions = EXCLUDED.min_impressions, \"\n \"min_spend = EXCLUDED.min_spend, max_impressions = EXCLUDED.max_impressions, \"\n \"max_spend = EXCLUDED.max_spend;\")\n insert_template = (\n \"(%(archive_id)s, %(region)s, %(min_impressions)s, %(min_spend)s, %(max_impressions)s, \"\n \"%(max_spend)s)\")\n psycopg2.extras.execute_values(cursor,\n impression_region_insert_query,\n region_impressions_list,\n template=insert_template,\n page_size=250)\n\n def update_ad_snapshot_metadata(self, ad_snapshot_metadata_records):\n cursor = self.get_cursor()\n ad_snapshot_metadata_record_list = [x._asdict() for x in ad_snapshot_metadata_records]\n\n # Update ad_snapshot_metadata.needs_scrape to False now that ad_creatives have been scraped\n # and stored.\n update_query = (\n 'UPDATE ad_snapshot_metadata SET snapshot_fetch_time = %(snapshot_fetch_time)s, '\n 'needs_scrape = FALSE, snapshot_fetch_status = %(snapshot_fetch_status)s '\n 'WHERE archive_id = %(archive_id)s')\n psycopg2.extras.execute_batch(cursor,\n update_query,\n ad_snapshot_metadata_record_list,\n page_size=250)\n\n\n def insert_ad_creative_records(self, ad_creative_records):\n cursor = self.get_cursor()\n # First insert ad creatives to ad_creatives table.\n insert_query = (\n 'INSERT INTO ad_creatives(archive_id, ad_creative_body, ad_creative_link_url, '\n 'ad_creative_link_title, ad_creative_link_caption, ad_creative_link_description, '\n 'text_sha256_hash, text_sim_hash, image_downloaded_url, image_bucket_path, '\n 'image_sim_hash, image_sha256_hash) VALUES %s ON CONFLICT (archive_id, '\n 'text_sha256_hash, image_sha256_hash) DO NOTHING')\n insert_template = (\n '(%(archive_id)s, %(ad_creative_body)s, %(ad_creative_link_url)s, '\n '%(ad_creative_link_title)s, %(ad_creative_link_caption)s, '\n '%(ad_creative_link_description)s, %(text_sha256_hash)s, %(text_sim_hash)s, '\n '%(image_downloaded_url)s, %(image_bucket_path)s, %(image_sim_hash)s, '\n '%(image_sha256_hash)s)')\n ad_creative_record_list = [x._asdict() for x in ad_creative_records]\n psycopg2.extras.execute_values(cursor,\n insert_query,\n ad_creative_record_list,\n template=insert_template,\n page_size=250)\n","sub_path":"db_functions.py","file_name":"db_functions.py","file_ext":"py","file_size_in_byte":16076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"339569385","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom django.forms import ModelForm\r\nfrom django.forms.widgets import Select\r\n\r\nfrom stopnie.models import Kandydat\r\n\r\n\r\nclass KandydatForm(ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = Kandydat\r\n\t\tfields = ['imie', 'nazwisko', 'kierunek', 'lokalizacja', 'mail', 'telefon', 'zgoda']\r\n\t\t\r\n\t\tlabels = {\r\n\t\t\t\t'zgoda': 'Wyrażam zgodę na przeprowadzenie ankiety',\r\n\t\t\t\t'mail': 'E-mail',\r\n\t\t\t\t}\r\n\t\t\r\n\t\twidgets = {\r\n\t\t\t\t'kierunek': Select()\r\n\t\t\t\t}","sub_path":"stopnie/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"66818473","text":"import os.path\nimport sys\nimport time\nimport pickle\nimport h5py\nimport numpy as np\n\nfrom keras.models import Model\nfrom keras.layers import Flatten, Dense, Input, Conv1D, AveragePooling1D, BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import to_categorical\nfrom sklearn import preprocessing\nfrom exploit_pred import *\nfrom clr import OneCycleLR\n\n### Scripts based on ASCAD github : https://github.com/ANSSI-FR/ASCAD\n\ndef check_file_exists(file_path):\n if os.path.exists(file_path) == False:\n print(\"Error: provided file path '%s' does not exist!\" % file_path)\n sys.exit(-1)\n return\n\ndef shuffle_data(profiling_x,label_y):\n l = list(zip(profiling_x,label_y))\n random.shuffle(l)\n shuffled_x,shuffled_y = list(zip(*l))\n shuffled_x = np.array(shuffled_x)\n shuffled_y = np.array(shuffled_y)\n return (shuffled_x, shuffled_y)\n\n### CNN Best model\ndef cnn_architecture(input_size=700,learning_rate=0.00001,classes=256):\n \n # Personal design\n input_shape = (input_size,1)\n img_input = Input(shape=input_shape)\n\n # 1st convolutional block\n x = Conv1D(32, 1, kernel_initializer='he_uniform', activation='selu', padding='same', name='block1_conv1')(img_input)\n x = BatchNormalization()(x)\n x = AveragePooling1D(2, strides=2, name='block1_pool')(x)\n \n # 2nd convolutional block\n x = Conv1D(64, 50, kernel_initializer='he_uniform', activation='selu', padding='same', name='block2_conv1')(x)\n x = BatchNormalization()(x)\n x = AveragePooling1D(50, strides=50, name='block2_pool')(x)\n \n # 3rd convolutional block\n x = Conv1D(128, 3, kernel_initializer='he_uniform', activation='selu', padding='same', name='block3_conv1')(x) \n x = BatchNormalization()(x)\n x = AveragePooling1D(2, strides=2, name='block3_pool')(x)\n \n x = Flatten(name='flatten')(x)\n\n # Classification part\n x = Dense(20, kernel_initializer='he_uniform', activation='selu', name='fc1')(x)\n x = Dense(20, kernel_initializer='he_uniform', activation='selu', name='fc2')(x)\n x = Dense(20, kernel_initializer='he_uniform', activation='selu', name='fc3')(x)\n\n # Logits layer\n x = Dense(classes, activation='softmax', name='predictions')(x)\n\n # Create model\n inputs = img_input\n model = Model(inputs, x, name='cnn_best')\n optimizer = Adam(lr=learning_rate)\n model.compile(loss='categorical_crossentropy',optimizer=optimizer, metrics=['accuracy'])\n return model\n\n#### ASCAD helper to load profiling and attack data (traces and labels) (source : https://github.com/ANSSI-FR/ASCAD)\n# Loads the profiling and attack datasets from the ASCAD database\ndef load_ascad(ascad_database_file, load_metadata=False):\n check_file_exists(ascad_database_file)\n # Open the ASCAD database HDF5 for reading\n try:\n in_file = h5py.File(ascad_database_file, \"r\")\n except:\n print(\"Error: can't open HDF5 file '%s' for reading (it might be malformed) ...\" % ascad_database_file)\n sys.exit(-1)\n # Load profiling traces\n X_profiling = np.array(in_file['Profiling_traces/traces'], dtype=np.float64)\n # Load profiling labels\n Y_profiling = np.array(in_file['Profiling_traces/labels'])\n # Load attacking traces\n X_attack = np.array(in_file['Attack_traces/traces'], dtype=np.float64)\n # Load attacking labels\n Y_attack = np.array(in_file['Attack_traces/labels'])\n if load_metadata == False:\n return (X_profiling, Y_profiling), (X_attack, Y_attack)\n else:\n return (X_profiling, Y_profiling), (X_attack, Y_attack), (in_file['Profiling_traces/metadata']['plaintext'], in_file['Attack_traces/metadata']['plaintext'])\n\n\n#### Training model\ndef train_model(X_profiling, Y_profiling, X_test, Y_test, model, save_file_name, epochs=150, batch_size=100, max_lr=1e-3):\n check_file_exists(os.path.dirname(save_file_name))\n # Save model every epoch\n save_model = ModelCheckpoint(save_file_name)\n\n # Get the input layer shape\n input_layer_shape = model.get_layer(index=0).input_shape\n\n # Sanity check\n if input_layer_shape[1] != len(X_profiling[0]):\n print(\"Error: model input shape %d instead of %d is not expected ...\" % (input_layer_shape[1], len(X_profiling[0])))\n sys.exit(-1)\n\n Reshaped_X_profiling, Reshaped_X_test = X_profiling.reshape((X_profiling.shape[0], X_profiling.shape[1], 1)),X_test.reshape((X_test.shape[0], X_test.shape[1], 1))\n \n #One cycle policy\n lr_manager = OneCycleLR(max_lr=max_lr, end_percentage=0.2, scale_percentage=0.1, maximum_momentum=None, minimum_momentum=None,verbose=True)\n \n callbacks=[save_model, lr_manager] \n history = model.fit(x=Reshaped_X_profiling, y=to_categorical(Y_profiling, num_classes=256), validation_data=(Reshaped_X_test, to_categorical(Y_test, num_classes=256)), batch_size=batch_size, verbose = 1, epochs=epochs, callbacks=callbacks)\n return history\n\n\n#################################################\n#################################################\n\n##### Initialization ######\n\n#################################################\n#################################################\n\n# Our folders\nroot = \"./\"\nASCAD_data_folder = root+\"ASCAD_dataset/\"\nASCAD_trained_models_folder = root+\"ASCAD_trained_models/\"\nhistory_folder = root+\"training_history/\"\npredictions_folder = root+\"model_predictions/\"\n\n# Choose the name of the model\nnb_epochs = 50\nbatch_size = 256\ninput_size = 700\nlearning_rate = 1e-2\nnb_traces_attacks = 400\nnb_attacks = 100\nreal_key = np.load(ASCAD_data_folder + \"key.npy\")\n\nstart = time.time()\n\n# Load the profiling traces\n(X_profiling, Y_profiling), (X_attack, Y_attack), (plt_profiling, plt_attack) = load_ascad(ASCAD_data_folder + \"ASCAD_desync100.h5\", load_metadata=True)\n\n# Shuffle data\n(X_profiling, Y_profiling) = shuffle_data(X_profiling, Y_profiling)\n\nX_profiling = X_profiling.astype('float32')\nX_attack = X_attack.astype('float32')\n\nX_attack = X_attack.reshape((X_attack.shape[0], X_attack.shape[1], 1))\n\n#################################################\n#################################################\n\n#### Training ######\n\n#################################################\n#################################################\n\n# Choose your model\nmodel = cnn_architecture(input_size=input_size, learning_rate=learning_rate)\nmodel_name=\"ASCAD_desync100\"\n\nprint('\\n Model name = '+model_name)\n\n\nprint(\"\\n############### Starting Training #################\\n\")\n\n# Record the metrics\nhistory = train_model(X_profiling[:45000], Y_profiling[:45000], X_profiling[45000:], Y_profiling[45000:], model, ASCAD_trained_models_folder + model_name, epochs=nb_epochs, batch_size=batch_size, max_lr=learning_rate)\n\n\nend=time.time()\nprint('Temps execution = %d'%(end-start))\n\nprint(\"\\n############### Training Done #################\\n\")\n\n# Save the metrics\nwith open(history_folder + 'history_' + model_name, 'wb') as file_pi:\n pickle.dump(history.history, file_pi)\n\n\n#################################################\n#################################################\n\n#### Prediction ######\n\n#################################################\n#################################################\n\nprint(\"\\n############### Starting Predictions #################\\n\")\n\npredictions = model.predict(X_attack)\n\nprint(\"\\n############### Predictions Done #################\\n\")\n\nnp.save(predictions_folder + 'predictions_' + model_name +'.npy', predictions)\n\n\n#################################################\n#################################################\n\n#### Perform attacks ######\n\n#################################################\n#################################################\n\nprint(\"\\n############### Starting Attack on Test Set #################\\n\")\n\navg_rank = perform_attacks(nb_traces_attacks, predictions, nb_attacks, plt=plt_attack, key=real_key, byte=2, filename=model_name)\n\nprint(\"\\n t_GE = \")\nprint(np.where(avg_rank<=0))\nprint(\"\\n############### Attack on Test Set Done #################\\n\")\n","sub_path":"ASCAD/N0=100/cnn_architecture.py","file_name":"cnn_architecture.py","file_ext":"py","file_size_in_byte":8280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"94797398","text":"#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n# @Time : 2019/6/6 10:24\n# @Author: Jtyoui@qq.com\n\n\"\"\"统计指标:混淆矩阵\nTrue Positive(真正,TP):将正类预测为正类数\nTrue Negative(真负,TN):将负类预测为负类数\nFalse Positive(假正,FP):将负类预测为正类数\nFalse Negative(假负,FN):将正类预测为负类数\nP=TP+FP 预测对的\nN=FN+TN 预测错的\nPP=TP+FN 实际上是对的\nNN=FP+TN 实际上是错误的\nALL=P+N=PP+NN=所有\n\"\"\"\n\n\ndef confusion_matrix(simple, pred):\n \"\"\"混淆矩阵\n\n :param simple: 实际样本分类列表\n :param pred: 预测样本分类列表\n :return: TP,TN,FP,FN\n \"\"\"\n tp, tn, fp, fn = 0, 0, 0, 0\n for s, p in zip(simple, pred):\n if s == p == 1: # 将正类预测为正类数\n tp += 1\n elif s == p == 0: # 将负类预测为负类数\n tn += 1\n elif s == 1 and p == 0: # 将正类预测为负类数\n fn += 1\n else: # 将负类预测为正类数\n fp += 1\n return tp, tn, fp, fn\n\n\ndef precision(tp, tn, fp, fn):\n \"\"\"精确率=(TP+TN)/(TP+TN+FP+FN)\"\"\"\n return (tp + tn) / (tp + tn + fp + fn)\n\n\ndef recall(tp, tn, fp, fn):\n \"\"\"召回率=TP/(TP+FN)\"\"\"\n return tp / (tp + fn)\n\n\ndef f_measure(tp, tn, fp, fn):\n \"\"\"综合评价指标=(2*P*R)/(P+R)\"\"\"\n p = precision(tp, tn, fp, fn)\n r = recall(tp, tn, fp, fn)\n return (2 * p * r) / (p + r)\n\n\nif __name__ == '__main__':\n simples = [1, 1, 0, 0, 0, 0, 1, 0, 0, 1] # 实际分类的值\n prediction = [0, 1, 0, 1, 1, 0, 1, 1, 0, 1] # 预测分类的值\n m = confusion_matrix(simple=simples, pred=prediction) # 混淆矩阵\n p_ = precision(*m) # 准确率\n r_ = recall(*m) # 召回率\n f_ = f_measure(*m) # f值\n print(p_, r_, f_) # 0.6 0.75 0.6666666666666665\n","sub_path":"jtyoui/statistics/analysis/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"607577209","text":"# from django.conf.urls import url\nfrom django.urls import path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\napp_name = 'accounts'\n\nurlpatterns = [\n path('login/',\n auth_views.LoginView.as_view(template_name='accounts/login.html'),\n name='login'\n ),\n path('logout/', auth_views.LogoutView.as_view(), name='logout'),\n # path('signup/', views.SignUp.as_view(), name='signup'),\n path('signup/', views.signup_view, name='signup'),\n path('sent/', views.activation_sent_view, name=\"activation_sent\"),\n path('activate///', views.activate, name='activate'),\n\n]\n# urlpatterns = [\n# url(r'login/$',\n# auth_views.LoginView.as_view(template_name='accounts/login.html'),\n# name='login'\n# ),\n# url(r'logout/$', auth_views.LogoutView.as_view(), name='logout'),\n# url(r'signup/$', views.SignUp.as_view(), name='signup')\n# ]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"95375835","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 1/6/21 3:39 PM\n@Author : Justin Jiang\n@Email : jw_jiang@pku.edu.com\n\"\"\"\n\n\ndef reorderLogFiles(logs):\n digitLog = []\n letterLog = []\n for s in logs:\n if s.split(\" \")[1][0].isdigit():\n digitLog.append(s)\n if s.split(\" \")[1][0].isalpha():\n letterLog.append(s)\n letterLog = sorted(letterLog, key=lambda s: s.split(\" \")[0])\n letterLog = sorted(letterLog, key=lambda s: \" \".join(s.split(\" \")[1:]))\n result = letterLog + digitLog\n return result\n\n\nif __name__ == '__main__':\n logs = [\"a1 9 2 3 1\", \"g1 act car\", \"zo4 4 7\", \"ab1 off key dog\", \"a8 act zoo\"]\n print(reorderLogFiles(logs))\n logs = [\"j je\", \"b fjt\", \"7 zbr\", \"m le\", \"o 33\"]\n print(reorderLogFiles(logs)) # [\"b fjt\",\"j je\",\"m le\",\"7 zbr\",\"o 33\"]\n","sub_path":"20201029/937_reorderLogFiles.py","file_name":"937_reorderLogFiles.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"407812076","text":"\"\"\"\nTests for `pyinaturalist` module.\n\"\"\"\nimport json\nimport os\nfrom datetime import datetime, timedelta\n\nimport pytest\nimport requests_mock\nfrom requests import HTTPError\n\nfrom pyinaturalist.node_api import get_observation\nfrom pyinaturalist.rest_api import get_access_token, get_all_observation_fields, \\\n get_observation_fields, update_observation, create_observations, put_observation_field_values, delete_observation\nfrom pyinaturalist.exceptions import AuthenticationError, ObservationNotFound\n\n\ndef _sample_data_path(filename):\n return os.path.join(os.path.dirname(__file__), 'sample_data', filename)\n\ndef _load_sample_json(filename):\n with open(_sample_data_path(filename), encoding='utf-8') as fh:\n return json.load(fh)\n\nPAGE_1_JSON_RESPONSE = _load_sample_json('get_observation_fields_page1.json')\nPAGE_2_JSON_RESPONSE = _load_sample_json('get_observation_fields_page2.json')\n\nclass TestNodeApi(object):\n @requests_mock.Mocker(kw='mock')\n def test_get_observation(self, **kwargs):\n mock = kwargs['mock']\n mock.get('https://api.inaturalist.org/v1/observations?id=16227955',\n json=_load_sample_json('get_observation.json'), status_code=200)\n\n obs_data = get_observation(observation_id=16227955)\n assert obs_data['quality_grade'] == 'research'\n assert obs_data['id'] == 16227955\n assert obs_data['user']['login'] == 'niconoe'\n assert len(obs_data['photos']) == 2\n\n @requests_mock.Mocker(kw='mock')\n def test_get_non_existent_observation(self, **kwargs):\n mock = kwargs['mock']\n mock.get('https://api.inaturalist.org/v1/observations?id=99999999',\n json=_load_sample_json('get_nonexistent_observation.json'), status_code=200)\n with pytest.raises(ObservationNotFound):\n get_observation(observation_id=99999999)\n\nclass TestRestApi(object):\n @requests_mock.Mocker(kw='mock')\n def test_get_observation_fields(self, **kwargs):\n \"\"\" get_observation_fields() work as expected (basic use)\"\"\"\n mock = kwargs['mock']\n\n mock.get('https://www.inaturalist.org/observation_fields.json?q=sex&page=2',\n json=PAGE_2_JSON_RESPONSE, status_code=200)\n\n obs_fields = get_observation_fields(search_query=\"sex\", page=2)\n assert obs_fields == PAGE_2_JSON_RESPONSE\n\n\n @requests_mock.Mocker(kw='mock')\n def test_get_all_observation_fields(self, **kwargs):\n \"\"\"get_all_observation_fields() is able to paginate, accepts a search query and return correct results\"\"\"\n mock = kwargs['mock']\n\n mock.get('https://www.inaturalist.org/observation_fields.json?q=sex&page=1',\n json=PAGE_1_JSON_RESPONSE, status_code=200)\n\n mock.get('https://www.inaturalist.org/observation_fields.json?q=sex&page=2',\n json=PAGE_2_JSON_RESPONSE, status_code=200)\n\n page_3_json_response = []\n mock.get('https://www.inaturalist.org/observation_fields.json?q=sex&page=3',\n json=page_3_json_response, status_code=200)\n\n\n all_fields = get_all_observation_fields(search_query=\"sex\")\n assert all_fields == PAGE_1_JSON_RESPONSE + PAGE_2_JSON_RESPONSE\n\n @requests_mock.Mocker(kw='mock')\n def test_get_all_observation_fields_noparam(self, **kwargs):\n \"\"\"get_all_observation_fields() can also be called without a search query without errors\"\"\"\n\n mock = kwargs['mock']\n mock.get('https://www.inaturalist.org/observation_fields.json?page=1',\n json=[], status_code=200)\n\n get_all_observation_fields()\n\n @requests_mock.Mocker(kw='mock')\n def test_get_access_token_fail(self, **kwargs):\n \"\"\" If we provide incorrect credentials to get_access_token(), an AuthenticationError is raised\"\"\"\n\n mock = kwargs['mock']\n rejection_json = {'error': 'invalid_client', 'error_description': 'Client authentication failed due to '\n 'unknown client, no client authentication '\n 'included, or unsupported authentication '\n 'method.'}\n mock.post('https://www.inaturalist.org/oauth/token', json=rejection_json, status_code=401)\n\n with pytest.raises(AuthenticationError):\n get_access_token('username', 'password', 'app_id', 'app_secret')\n\n @requests_mock.Mocker(kw='mock')\n def test_get_access_token(self, **kwargs):\n \"\"\" Test a successful call to get_access_token() \"\"\"\n\n mock = kwargs['mock']\n accepted_json = {'access_token': '604e5df329b98eecd22bb0a84f88b68a075a023ac437f2317b02f3a9ba414a08',\n 'token_type': 'Bearer', 'scope': 'write', 'created_at': 1539352135}\n mock.post('https://www.inaturalist.org/oauth/token', json=accepted_json, status_code=200)\n\n token = get_access_token('valid_username', 'valid_password', 'valid_app_id', 'valid_app_secret')\n\n assert token == '604e5df329b98eecd22bb0a84f88b68a075a023ac437f2317b02f3a9ba414a08'\n\n @requests_mock.Mocker(kw='mock')\n def test_update_observation(self, **kwargs):\n mock = kwargs['mock']\n mock.put('https://www.inaturalist.org/observations/17932425.json',\n json=_load_sample_json('update_observation_result.json'),\n status_code=200)\n\n p = {'ignore_photos': 1,\n 'observation': {'description': 'updated description v2 !'}}\n r = update_observation(observation_id=17932425, params=p, access_token='valid token')\n\n # If all goes well we got a single element representing the updated observation, enclosed in a list.\n assert len(r) == 1\n assert r[0]['id'] == 17932425\n assert r[0]['description'] == 'updated description v2 !'\n\n @requests_mock.Mocker(kw='mock')\n def test_update_nonexistent_observation(self, **kwargs):\n \"\"\"When we try to update a non-existent observation, iNat returns an error 410 with \"obs does not longer exists\". \"\"\"\n mock = kwargs['mock']\n mock.put('https://www.inaturalist.org/observations/999999999.json',\n json={\"error\":\"Cette observation n’existe plus.\"},\n status_code=410)\n\n p = {'ignore_photos': 1,\n 'observation': {'description': 'updated description v2 !'}}\n\n with pytest.raises(HTTPError) as excinfo:\n update_observation(observation_id=999999999, params=p, access_token='valid token')\n assert excinfo.value.response.status_code == 410\n assert excinfo.value.response.json() == {\"error\":\"Cette observation n’existe plus.\"}\n\n @requests_mock.Mocker(kw='mock')\n def test_update_observation_not_mine(self, **kwargs):\n \"\"\"When we try to update the obs of another user, iNat returns an error 410 with \"obs does not longer exists\".\"\"\"\n mock = kwargs['mock']\n mock.put('https://www.inaturalist.org/observations/16227955.json',\n json={\"error\": \"Cette observation n’existe plus.\"},\n status_code=410)\n\n p = {'ignore_photos': 1,\n 'observation': {'description': 'updated description v2 !'}}\n\n with pytest.raises(HTTPError) as excinfo:\n update_observation(observation_id=16227955, params=p, access_token='valid token for another user')\n assert excinfo.value.response.status_code == 410\n assert excinfo.value.response.json() == {\"error\": \"Cette observation n’existe plus.\"}\n\n @requests_mock.Mocker(kw='mock')\n def test_create_observation(self, **kwargs):\n mock = kwargs['mock']\n\n mock.post('https://www.inaturalist.org/observations.json',\n json=_load_sample_json('create_observation_result.json'), status_code=200)\n\n\n params = {'observation':\n {'species_guess': 'Pieris rapae'},\n }\n\n r = create_observations(params=params, access_token='valid token')\n assert len(r) == 1 # We added a single one\n assert r[0]['latitude'] is None # We have the field, but it's none since we didn't submitted anything\n assert r[0]['taxon_id'] == 55626 # Pieris Rapae @ iNaturalist\n\n @requests_mock.Mocker(kw='mock')\n def test_create_observation_fail(self, **kwargs):\n mock = kwargs['mock']\n params = {'observation':\n {'species_guess': 'Pieris rapae',\n # Some invalid data so the observation is rejected...\n 'observed_on_string': (datetime.now() + timedelta(days=1)).isoformat(),\n 'latitude': 200,\n }\n }\n\n mock.post('https://www.inaturalist.org/observations.json',\n json=_load_sample_json('create_observation_fail.json'), status_code=422)\n\n with pytest.raises(HTTPError) as excinfo:\n create_observations(params=params, access_token='valid token')\n assert excinfo.value.response.status_code == 422\n assert 'errors' in excinfo.value.response.json() # iNat also give details about the errors\n\n @requests_mock.Mocker(kw='mock')\n def test_put_observation_field_values(self, **kwargs):\n mock = kwargs['mock']\n mock.put('https://www.inaturalist.org/observation_field_values/31',\n json=_load_sample_json('put_observation_field_value_result.json'),\n status_code=200)\n\n r = put_observation_field_values(observation_id=18166477,\n observation_field_id=31, # Animal behavior\n value='fouraging',\n access_token='valid token')\n\n assert r['id'] == 31\n assert r['observation_field_id'] == 31\n assert r['observation_id'] == 18166477\n assert r['value'] == 'fouraging'\n\n def test_delete_observation(self):\n pass","sub_path":"test/test_pyinaturalist.py","file_name":"test_pyinaturalist.py","file_ext":"py","file_size_in_byte":10018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"471140889","text":"#!/usr/bin/python3\n\nfrom glob import glob\nfrom lxml import html\nimport re\n\nfiles = glob('*.html')\noutput = open('list.csv', 'w', encoding='utf-8')\npattern = r'\\d+'\nfor page in files:\n # if directly use html.parse(file), encode error occurs\n with open(page, 'r') as raw:\n raw = raw.read()\n data = html.fromstring(raw)\n table = data.xpath('//*[@id=\"dataTable\"]/tbody')[0]\n all_a = table.findall('*//a')\n for a in all_a:\n text = a.text_content()\n name = text\n find = re.search(pattern, a.attrib['href'])\n if find is not None:\n nameid = find.group()\n # name = text.strip()\n name_list = name.split(' ')\n genus, author, *etc = name_list\n if genus == '×':\n genus = ''.join([genus, author])\n author = ''.join(etc)\n else:\n author = ' '.join([author, *etc])\n output.write('{}\\t{}\\t{}\\n'.format(nameid, genus, author))\n","sub_path":"checklist/parse_genus.py","file_name":"parse_genus.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"39808330","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n\nclass ProcesadoraKardexLines(models.Model):\n _inherit = 'stock.move.line'\n x_costo = fields.Float('Costo', compute=\"_costokardex\",store=True )\n x_existencia = fields.Float('Existencia despues del Movimiento', digits=(12,3),store=True)\n x_pruebas = fields.Char('para pruebas',)\n #x_afectado_kardex = fields.Boolean('Movimiento considerado para el kardex', store=True, default=False)\n x_documento_final = fields.Char('Documento', compute=\"_documento_final\", store=False)\n\n #Se agrega un campo x_documento_final para contenga el documento final de la operación factura de compra o\n #factura de venta, se dejo en store=False porque al ponerlo en True manda un error\n @api.depends('x_documento_final')\n def _documento_final(self):\n for record in self:\n if record.picking_id.purchase_id:\n record['x_documento_final']=record.picking_id.purchase_id.invoice_ids[0].name\n elif record.picking_id.sale_id:\n record['x_documento_final'] = record.picking_id.sale_id.invoice_ids[0].name\n else:\n record['x_documento_final'] = ''\n \n\n @api.depends('state')\n def _kardexstock(self):\n for record in self:\n if record.state == 'done':\n record['x_existencia'] = record.product_id.qty_available\n \n @api.depends('state') \n def _costokardex(self):\n for record in self:\n costo = 0\n if record.state == 'done':\n ##if record.move_id: \n ## costo = abs(record.picking_id.sale_id.purchase_price)\n ##elif record.move_id.purchase_line_id:\n ## costo = abs(record.picking_id.purchase_id.price_unit)\n ##else:\n ## costo = abs(record.move_id.price_unit)\n costo = abs(record.move_id.price_unit)\n record['x_costo'] = costo\n","sub_path":"procesadora_rocio/models/kardex.py","file_name":"kardex.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"477842331","text":"import math\nimport random\nimport time\nfrom datetime import datetime\n\nanimals = ['Duck', 'Jackal', 'Hippo', 'Aardvark',\n 'Cat', 'Flamingo', 'Iguana', 'Giraffe', 'Elephant', 'Bear']\n\n###########\n# 0(1) - constant time operation\n###########\n\n# return the name of all animals -\n\n\ndef getAnimals(): # constant time operation - doesn't matter if its a long or small list\n return animals # returning a pointer to the start of our list\n\n\n# time complexity is 0(1) operation - performance stays constant as inputs get larger\nprint(getAnimals())\n\n\n###########\n# 0(n) - linear - straight line. as you add more inputs the performance wil increase linearly. always drop constant coefficents.\n###########\n\n# Return the number of animals\n\n\ndef countAnimals():\n num_animals = 0\n for animal in animals:\n print(f\"num animals: {num_animals}\")\n num_animals += 1\n return num_animals\n# how many operations are we doing? doing this operation 10 times. our input is size n, and for each of these inputs we need to do something, which is incrementing our counter by 1. if we had 20 animals, 1000 animals we would need to do it whatever n amount of times. the number of operations we need to do it linear.\n\n\nprint(countAnimals())\n","sub_path":"Lecture_IterativeSorting.py","file_name":"Lecture_IterativeSorting.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"256786659","text":"\"\"\"\n@Author - Ayan Mukhopadhyay\nPoisson Regression Forecaster -- Inherits from Forecaster class\n\"\"\"\n\nfrom forecasters.base import Forecaster\nfrom forecasters.Resampling import Resampling_Func, Balance_Adjuster\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nfrom patsy import dmatrices\nfrom copy import deepcopy\nfrom scipy.special import factorial\nfrom scipy import stats\nfrom scipy.special import gamma\nfrom sklearn.metrics import precision_recall_curve\n\n\n\ndef create_default_meta(df, static_features=None):\n \"\"\"\n Creates default set of metadata if user supplied data is missing\n @param df: dataframe of incidents\n @param static_features: set of static features used in clustering\n @return: metadata dictionary\n \"\"\"\n metadata = {'start_time_train': df['time'].min(), 'end_time_train': df['time'].max()}\n if static_features is None:\n static_features = list(df.columns)\n if 'cluster_label' in static_features:\n static_features.remove('cluster_label')\n metadata['features_ALL'] = static_features\n return metadata\n\n\nclass GLM_Model(Forecaster):\n#This is the main GLM_Model calss, and all GLM fall into this category \n def __init__(self,model_name):\n self.model_name = model_name\n self.model_params = {}\n self.model_stats = {}\n self.model_threshold= {}\n\n def fit(self, df, metadata=None,sampling_name='No_Resample'):\n \"\"\"\n Fits regression model to data\n @param df: dataframe of incidents in regression format\n @param metadata: dictionary with start and end dates, columns to regress on, cluster labels etc.\n see github documentation for details\n @return: _\n \"\"\"\n # if metadata is none, use standard parameters\n if metadata is None:\n metadata = create_default_meta(df)\n # get regression expression\n expr = self.get_regression_expr(metadata,metadata['features_ALL'])\n \n \n split_point = metadata['train_verification_split']\n mask=df.index.isin(df.sample(int(split_point*len(df)),replace=False).index) \n \n \n BalanceFactor=Balance_Adjuster(df[mask],metadata) #caclulate the Balance ratio between each cluster for resampling\n clusters = sorted(df.cluster_label.unique())\n for temp_cluster in clusters:\n print('temp_cluster',temp_cluster)\n df_cluster = df.loc[df.cluster_label == temp_cluster]\n df_cluster_Y, df_cluster_X= dmatrices(expr, df_cluster, return_type='dataframe')\n #Unbalanced_Correction=0\n #Unbalanced_Correction_Type='SMOTE'\n if sampling_name in ['RUS','ROS','SMOTE']:\n sampling= Resampling_Func(sampling_name,BalanceFactor[temp_cluster] )\n try:\n df_cluster_X_train,df_cluster_Y_train = sampling.fit_resample(df_cluster_X[mask],df_cluster_Y[mask])\n except:\n print('Warning: prediction column is not binary for resampling')\n df_cluster_X_train,_ = sampling.fit_resample(df_cluster_X[mask],df_cluster_Y[mask]>0)\n df_cluster_Y_train,_ = sampling.fit_resample(df_cluster_Y[mask],df_cluster_Y[mask]>0)\n else:\n df_cluster_X_train=df_cluster_X[mask]\n df_cluster_Y_train=df_cluster_Y[mask]\n \n # fit model\n if (self.model_name == 'Poisson_Regression'):\n model = sm.GLM(df_cluster_Y_train, df_cluster_X_train, family=sm.families.Poisson(sm.families.links.log())).fit()\n elif self.model_name == 'Logistic_Regression':\n np.random.seed(seed=0) \n \n model = sm.GLM(df_cluster_Y_train, df_cluster_X_train, family=sm.families.Binomial(sm.families.links.logit())).fit(method=\"lbfgs\") #lbfgs #bfgs irls\n df_cluster_Y_verif_hat= model.predict(df_cluster_X[~mask])\n precision, recall, thresholds = precision_recall_curve(df_cluster_Y[~mask], df_cluster_Y_verif_hat)\n fscore = (2 * precision * recall) / (precision + recall)\n ix = np.nanargmax(fscore)\n #ix = np.argmax(fscore)\n \n print('for Cluaster=%.0f, best Threshold=%f, F-Score=%.5f' % (temp_cluster, thresholds[ix], fscore[ix])) \n if np.isnan(fscore[ix])==True:\n self.model_threshold[temp_cluster] = 0.5\n else:\n self.model_threshold[temp_cluster] = thresholds[ix] \n \n elif self.model_name == 'Simple_Regression': \n try:\n model = sm.GLM(df_cluster_Y_train, df_cluster_X_train, family=sm.families.Gaussian(sm.families.links.identity())).fit() #the the dependent variable is exactly the same as one of the features, it will run into an error\n except:\n model = sm.OLS(df_cluster_Y_train, df_cluster_X_train).fit()\n elif (self.model_name == 'Negative_Binomial_Regression'):\n model = sm.GLM(df_cluster_Y_train, df_cluster_X_train, family=sm.families.Poisson(sm.families.links.log())).fit() \n y_train_predicted=deepcopy(df_cluster_Y_train)\n y_train_predicted.columns=['y']\n y_train_predicted['p']=model.predict(x_train) \n y_train_predicted['error']=(y_train_predicted['y']-y_train_predicted['p'])\n ancillary = sm.OLS(y_train_predicted['error']**2-y_train_predicted['p'], y_train_predicted['p']**2).fit().params[0] \n try:\n model=sm.GLM(df_cluster_Y_train, df_cluster_X_train, family=sm.families.NegativeBinomial(alpha=ancillary)).fit()\n except:\n print('Warning! ancilalary is considered 1')\n model=sm.GLM(df_cluster_Y_train, df_cluster_X_train, family=sm.families.NegativeBinomial(alpha=1)).fit() \n elif (self.model_name == 'Zero_Inflated_Poisson_Regression'):\n print('===================')\n #model = sm.ZeroInflatedPoisson(endog=df_cluster_Y_train, exog=df_cluster_X_train, exog_infl=df_cluster_X_train, inflation='logit').fit(method=\"bfgs\",maxiter=500,full_output=True,disp=True) #method=\"nm\" method='bfgs' lbfgs #https://www.statsmodels.org/stable/generated/statsmodels.discrete.count_model.ZeroInflatedPoisson.fit.html\n model = sm.ZeroInflatedPoisson(endog=df_cluster_Y_train, exog=df_cluster_X_train, inflation='logit').fit(method=\"bfgs\",maxiter=200) #method=\"nm\"\n print('But did it converge? checking the mle_retvals: ', model.mle_retvals[\"converged\"])\n print('===================')\n print('\\n \\n') \n print(model.summary())\n self.model_params[temp_cluster] = model \n self.update_model_stats()\n print('Finished Learning {} model'.format(self.model_name))\n\n def prediction(self, df, metadata):\n \"\"\"\n Predicts E(y|x) for a set of x, where y is the concerned dependent variable.\n @param df: dataframe of incidents in regression format\n @param metadata: dictionary with start and end dates, columns to regress on, cluster labels etc.\n see github documentation for details\n @return: updated dataframe with predicted values, Sigma2, ancillary and information regarding llf and MSE\n \"\"\"\n df_complete_predicted=df.copy()\n df_complete_predicted['predicted']=0\n df_complete_predicted['Sigma2']=0\n df_complete_predicted['ancillary']=0\n features = metadata['features_ALL']\n \n clusters = sorted(df.cluster_label.unique())\n for temp_cluster in clusters:\n print('temp_cluster',temp_cluster)\n #df_cluster = df.loc[df.cluster_label == temp_cluster]\n if (self.model_name == 'Zero_Inflated_Poisson_Regression'):\n #df_complete_predicted.loc[df.cluster_label == temp_cluster,'predicted'] = self.model_params[temp_cluster].predict( df[df.cluster_label == temp_cluster][features],exog_infl= df[df.cluster_label == temp_cluster][features])\n df_complete_predicted.loc[df.cluster_label == temp_cluster,'predicted'] = self.model_params[temp_cluster].predict( df[df.cluster_label == temp_cluster][features],exog_infl= np.ones((len(df[df.cluster_label == temp_cluster][features]),1)))\n \n else:\n #df_cluster['predicted'] = self.model_params[temp_cluster].predict(df_cluster[features])\n df_complete_predicted.loc[df.cluster_label == temp_cluster,'predicted'] = self.model_params[temp_cluster].predict(df[df.cluster_label == temp_cluster][features])\n #df_cluster['predicted'].replace(to_replace=0, value=1/1e8)\n #df_complete_predicted['predicted'].replace(to_replace=0, value=1/1e8)\n #df_complete_predicted.loc[df.cluster_label==temp_cluster,'predicted']=deepcopy(df_cluster['predicted'])\n df_complete_predicted.loc[df.cluster_label==temp_cluster,'Sigma2']=self.model_params[temp_cluster].scale/self.model_params[temp_cluster].nobs*self.model_params[temp_cluster].df_resid\n if self.model_name == 'Logistic_Regression': \n df_complete_predicted.loc[df.cluster_label==temp_cluster,'threshold']=self.model_threshold[temp_cluster]\n else : \n df_complete_predicted.loc[df.cluster_label==temp_cluster,'threshold']=0.5\n \n #if self.model_name == 'Logistic_Regression': \n ##df_complete_predicted['predicted_TF']=df_complete_predicted['predicted']>0.5\n #df_complete_predicted['predicted_TF']=df_complete_predicted['predicted']>df_complete_predicted['threshold']\n df_complete_predicted['predicted_TF']=df_complete_predicted['predicted']>df_complete_predicted['threshold']\n \n if metadata['pred_name'] in df.columns:\n df_complete_predicted['error']=df_complete_predicted[metadata['pred_name']]-df_complete_predicted['predicted']\n for temp_cluster in clusters:\n df_complete_predicted.loc[df.cluster_label==temp_cluster,'ancillary']= sm.OLS(df_complete_predicted.loc[df.cluster_label==temp_cluster,'error']**2-\n df_complete_predicted.loc[df.cluster_label==temp_cluster,'predicted'],\n df_complete_predicted.loc[df.cluster_label==temp_cluster,'predicted']**2).fit().params[0] \n test_likelihood_all, test_likelihood, df = self.Likelihood(df_complete_predicted, metadata)\n df_complete_predicted['llf']=df['llf']\n MSE_all, MSE = self.MSE(df_complete_predicted, metadata) \n return [df_complete_predicted,test_likelihood_all,test_likelihood,MSE_all, MSE]\n else:\n return [df_complete_predicted,None,None,None]\n \n def get_regression_expr(self, metadata,features):\n \"\"\"\n Creates regression expression in the form of a patsy expression\n @param features: x features to regress on\n @return: string expression\n \"\"\"\n expr = metadata['pred_name']+'~'\n for i in range(len(features)):\n # patsy expects 'weird columns' to be inside Q\n if ' ' in features[i]:\n expr += \"Q('\" + features[i] + \"')\"\n else:\n expr += features[i]\n if i != len(features) - 1:\n expr += '+'\n expr += '-1'\n return expr\n\n def Likelihood(self, df, metadata):\n #smv:checked\n \"\"\"\n Return the likelihood of model for the incidents in df for prediction\n @df: dataframe of incidents to calculate likelihood on\n @param metadata: dictionary with feature names, cluster labels.\n @return: likelihood value for each sample and the total summation as well the updated df which includes llf\n \"\"\" \n \n # fit model\n if self.model_name == 'Poisson_Regression':\n df['llf']=np.log(stats.poisson.pmf(k=df[metadata['pred_name']], mu=df['predicted']))\n if self.model_name == 'Logistic_Regression':\n df['llf']=np.log(stats.bernoulli.pmf(k=df[metadata['pred_name']], p=df['predicted']))\n elif self.model_name == 'Simple_Regression':\n #df['llf']=np.log(stats.norm.pdf(df[metadata['pred_name']], df['predicted'],self.model_params[df['cluster_label']].scale) )\n df['llf']=np.log(stats.norm.pdf(df[metadata['pred_name']], df['predicted'],df['Sigma2']**0.5) )\n elif self.model_name == 'Negative_Binomial_Regression':\n df['llf']=np.log(self.get_likelihood_NB(df,metadata))\n elif self.model_name == 'Zero_Inflated_Poisson_Regression':\n df['llf']=np.log(self.get_likelihood_ZIP(df,metadata))\n \n test_likelihood_all=df[['llf','cluster_label']].groupby(['cluster_label'], as_index=False).sum().sort_values(by='cluster_label', ascending=True)\n test_likelihood=sum(test_likelihood_all['llf'])\n return [(test_likelihood_all['llf'].values).tolist(),test_likelihood,df]\n \n \n def MSE(self, df, metadata):\n #smv:checked\n \"\"\"\n Return the Mean Square Error (MSE) of model for the incidents in df for prediction\n @df: dataframe of incidents to calculate likelihood on\n @param metadata: dictionary with feature names, cluster labels.\n @return: likelihood value for each sample and the total summation as well the updated df which includes llf\n \"\"\" \n df['error2']=df['error']**2\n MSE=np.mean(df['error2']) \n MSE_all=df[['error2','cluster_label']].groupby(['cluster_label'], as_index=False).mean().sort_values(by='cluster_label', ascending=True)\n return [(MSE_all['error2'].values).tolist(),MSE]\n \n\n def update_model_stats(self):\n #smv:checked\n \"\"\"\n Store the the summation of log likelihood of the training set, AIC value.\n @return: _\n \"\"\"\n train_likelihood = []\n aic = []\n for temp_cluster in self.model_params.keys():\n train_likelihood.append(self.model_params[temp_cluster].llf ) #llf: Value of the loglikelihood function evalued at params.\n aic.append( self.model_params[temp_cluster].aic)\n\n self.model_stats['train_likelihood'] = sum(train_likelihood)\n self.model_stats['aic'] = sum(aic)\n self.model_stats['train_likelihood_all']=train_likelihood\n self.model_stats['aic_all']=aic\n\n\n\n def get_likelihood_NB(self, df,metadata):\n \"\"\"\n Return the likelihood of NB model for the incidents in df for prediction\n @df: dataframe of incidents to calculate likelihood on\n @return: list of likelihood values for each sample\n \"\"\" \n \n method=2\n if method==1:\n ##method1: \n l_temp=(stats.nbinom.pmf(df[metadata['pred_name']],\n 1/df['ancillary'],\n 1 /(1+df['predicted']*df['ancillary'])))\n if method==2:\n ##method2: \n l_temp = gamma(df[metadata['pred_name']] + 1/df['ancillary']) / (gamma(1/df['ancillary']) * gamma(df[metadata['pred_name']]+1))\n l_temp *= (1 / (1 + df['ancillary'] * df['predicted'])) ** (1/df['ancillary'])\n l_temp *= ((df['ancillary'] * df['predicted']) / (1 + df['ancillary'] * df['predicted'])) ** df[metadata['pred_name']]\n\n \n return l_temp\n \n \n \n \n \n \n \n def get_likelihood_ZIP(self, df,metadata):\n \n \"\"\"\n Return the likelihood of ZIP model for the incidents in df for prediction\n @df: dataframe of incidents to calculate likelihood on\n @return: list of likelihood values for each sample\n \"\"\" \n \n \"\"\"\n Calculate the likelihood of a zero-inflated poisson model. The likelihood of the inflated model is calculated\n through coefficients marked with 'inflate_'\n @param df: dataframe whose likelihood needs to be calculated\n @param param: set of regression coefficients\n @return: likelihood value\n \"\"\"\n sigmoid = lambda x: 1 / (1 + np.exp(-1 * x))\n \n def parse_inflate_model(coef):\n \"\"\"\n Seperate the coefficients for inflated part and the Poission regression part through coefficients marked with 'inflate_'\n @param coef: all the coefficients\n @return: coef_inflate and coef_reg which represent the coefficients for inflated part and the Poission regression part, respectively\n \"\"\" \n coef_reg = {}\n coef_inflate = {}\n for k,v in coef.items():\n if 'inflate_' in k:\n coef_inflate[k] = v\n else:\n coef_reg[k] = v\n return coef_reg, coef_inflate \n \n \n \n def lik_calc(x,metadata):\n \"\"\"\n calculate the likelihood for each sample point\n @param x: a row of the incdient df which includes the features and predicted values\n @return: likelihood\n \"\"\" \n \n \n temp_inflate = 0\n temp_poisson = 0\n \n for key, val in coef_inflate.items():\n feature = key.split('inflate_')[1] # retrieve the part after \"inflate_\"\n temp_inflate += coef_inflate[key] * x[feature]\n \n for key, val in coef_reg.items():\n try:\n temp_poisson += coef_reg[key] * x[key]\n except KeyError:\n # if intercept is not in the features\n temp_poisson += coef_reg[key] * 1\n \n p_lambda = np.exp(temp_poisson)\n p_logistic = sigmoid(temp_inflate)\n \n if x[metadata['pred_name']] == 0: # use embedded inflated model (logistic regression usually)\n L = p_logistic + (1-p_logistic) * np.exp(-1 * p_lambda)\n \n else: # use embedded inflated model for P(y|x) != 0 * P(count=y|x)\n L = (1 - p_logistic) * (p_lambda ** x[metadata['pred_name']]) * np.exp(-1 * p_lambda) / np.math.factorial(x[metadata['pred_name']])\n return L\n \n \n \n \n clusters = df.cluster_label.unique()\n for temp_cluster in clusters:\n df_cluster = df.loc[df.cluster_label == temp_cluster]\n coef_reg, coef_inflate = parse_inflate_model(self.model_params[temp_cluster].params)\n df.loc[df.cluster_label==temp_cluster,'llf']=df_cluster.apply(lambda x: lik_calc(x,metadata), axis=1)\n return df['llf']","sub_path":"forecasters/reg_forecaster_draft.py","file_name":"reg_forecaster_draft.py","file_ext":"py","file_size_in_byte":19079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"590901455","text":"import gc\nimport os\nimport sys\nimport utime\n\nfrom uhttp_signature.authed_urequests import make_validated_request, RequestError, SignatureException\n\nfrom pozetron_config import *\nfrom credentials import KEY_ID, HMAC_SECRET\nfrom logger import log, exc_logline\n\nif isinstance(KEY_ID, bytes):\n KEY_ID = KEY_ID.decode('utf-8')\n\ndebug = False\n\n# Module name for references\npozetron = sys.modules[__name__]\n\n# Was POST checkin successful?\n# See also post_checkin\n_on_startup_checkin_done = False\nlast_refreshed_scripts = None\nlast_checked_commands = None\nforget_network_time = None\n\n# Some commands must be executed before others (when processed as a batch)\nCOMMAND_ORDER = {\n 'log_mode': 0,\n 'forget_network': 1,\n 'reboot': 2\n}\n\none_second = const(1000)\none_minute = const(60000)\nfive_minutes = const(300000)\none_day = const(24*60*60*1000)\n\n\n\n\ndef epilog():\n # We're trying to be cooperative here.\n utime.sleep_ms(0)\n now = utime.ticks_ms()\n\n # In the case of an signature error (client or server) try update the system time in\n # case the clock has skewed significantly\n for attempt in range(3):\n try:\n # Check commands before refreshing scripts so reboot remains a viable failsafe\n if utime.ticks_diff(now, pozetron.last_checked_commands) > one_minute or pozetron.last_checked_commands is None:\n try:\n check_commands()\n pozetron.last_checked_commands = now\n flush_logs()\n except SignatureException as ex:\n raise ex\n except RequestError:\n pass\n\n if utime.ticks_diff(now, pozetron.last_refreshed_scripts) > one_minute or pozetron.last_refreshed_scripts is None:\n try:\n refresh_scripts()\n pozetron.last_refreshed_scripts = now\n flush_logs()\n except SignatureException as ex:\n raise ex\n except RequestError:\n pass\n except SignatureException:\n # Try to set the time through NTP, but not too hard\n try:\n import ntptime\n ntptime.settime()\n except:\n pass\n finally:\n ntptime = None\n del(ntptime)\n else:\n break\n\n\n# Wrapper for make_validated_request, for brevity\ndef request(url, **kw):\n result = make_validated_request(url, KEY_ID, HMAC_SECRET, debug=debug, **kw)\n # Successful request -> we can disable backoff\n reset_backoff()\n return result\n\n\n# We must write \"Failure sending logs...\" message only once\n# until the next flush_logs success\n_logs_lost = False\n\n\n# This function does not raise\ndef flush_logs():\n global _logs_lost\n import logger\n url = API_BASE + '/logs/'\n try:\n if should_backoff():\n return\n\n # If log is empty, then we don't have to flush anything\n if not logger.file_size:\n logs = logger._logs\n if len(logs) == 0:\n return\n else:\n try:\n if os.stat(logger._LOG_FILE)[6] == 0: # size == 0\n return\n except OSError: # No file = no logs = no problem\n return\n # Post logs to API\n try:\n try:\n # NOTE: when API is available again after failure, this will not execute\n # if log is empty, until some other message is logged.\n if _logs_lost:\n request(url, method='POST', json=[{'text': 'Failure sending logs, truncated logs have been lost'}])\n _logs_lost = False\n # TODO: In the future, find a way to compute the HMAC on the file rather piece by piece than after\n # loading the list to memory.\n if not logger.file_size:\n json = [{'text': x} for x in logger._logs]\n if logger._overflow_errors:\n json.append({'text': '{} failed writes to log file due to logger.file_size={}'.format(logger._overflow_errors, logger.file_size)})\n request(url, method='POST', json=json)\n del json\n else:\n # If there are overflow errors we send them separately to make sure they get there.\n if logger._overflow_errors:\n json = [{'text': '{} failed writes to log file due to logger.file_size={}'.format(logger._overflow_errors, logger.file_size)}]\n request(url, method='POST', json=json)\n del json\n logger._overflow_errors = 0\n # If there were no overflow errors we just send the log file.\n request(url, method='POST', in_file=logger._LOG_FILE)\n # Success - clear logs\n logger._overflow_errors = 0\n logger._send_fails = 0\n if not logger.file_size:\n logger._logs.clear()\n else:\n _truncate_file(logger._LOG_FILE)\n except RequestError as ex:\n # NOTE: API will accept logs even if they are corrupted\n print(ex)\n set_backoff()\n raise ex\n #finally:\n # Delete variable\n # The follow call to del causes:\n # MemoryError: memory allocation failed, allocating 1073672184 bytes\n #del logs\n except Exception as ex:\n log(exc_logline.format('send logs', ex))\n logger._send_fails += 1\n # If too many fails, reset log\n if logger._send_fails >= 3:\n clear_logs()\n _logs_lost = True\n except Exception as o:\n sys.print_exception(o)\n finally:\n del url\n del logger\n\n\n# No truncate() so we use a workaround.\n# Don't physically write if file is already empty, to save flash.\ndef _truncate_file(filename):\n try:\n if os.stat(filename)[6] > 0:\n with open(filename, 'w'):\n pass\n except OSError:\n pass\n\n\ndef clear_logs():\n import logger\n logger._overflow_errors = 0\n logger._send_fails = 0\n logger._logs.clear()\n _truncate_file(logger._LOG_FILE)\n del logger\n\n\n# Exponential backoff: don't do requests to API for some time,\n# increasing that time after every subsequent failure.\n_backoff_until = None\n_backoff_factor = 0\n_backoff_factor_max = 7 # max wait depends on this and on timeout below\n_backoff_timeout_ms = const(10000) # max wait is about 20 minutes\n\n\ndef set_backoff(timeout=None):\n global _backoff_until, _backoff_factor\n if not timeout:\n # We randomize backoff period by 25% to avoid \"thundering herd\" problem\n import urandom\n timeout = (_backoff_timeout_ms * 2**_backoff_factor) * (1024 + (256 - urandom.getrandbits(9))) // 1024\n del urandom\n # Increase backoff factor\n _backoff_factor = min(_backoff_factor + 1, _backoff_factor_max)\n # next try at (now + timeout)\n _backoff_until = utime.ticks_add(utime.ticks_ms(), timeout)\n\n\n# Return True if backoff is in effect and we should come later\ndef should_backoff():\n global _backoff_until\n if _backoff_until is None:\n return False\n diff = utime.ticks_diff(_backoff_until, utime.ticks_ms())\n # Check for wrap around\n if not (-one_day < diff < one_day):\n diff = 0\n # Are we still waiting?\n if diff > 0:\n return True\n # Reset wait, but don't reset factor. Factor is reset on first successful request.\n _backoff_until = None\n return False\n\n\n# Reset back-off mechanism after successful request.\ndef reset_backoff():\n global _backoff_factor\n _backoff_factor = 0\n\n\ndef makesubdir(path, subdir):\n # Replacement for os.makedirs\n if path[-1] != '/':\n path += '/'\n items = subdir.strip('/').split('/')\n for x in items:\n path += x + '/'\n try:\n os.mkdir(path)\n except OSError:\n pass\n del x, items\n\n\ndef autocollect(function):\n def autocollect_decorator(*args, **kwargs):\n try:\n return function(*args, **kwargs)\n finally:\n gc.collect()\n return autocollect_decorator\n\n\ndef post_checkin():\n # Returns True if checkin is successful, False otherwise.\n global _on_startup_checkin_done\n if should_backoff():\n return False\n try:\n request(API_BASE + '/checkin/', method='POST', data=' ')\n except RequestError as ex:\n print(exc_logline.format('post checkin', ex))\n set_backoff()\n return False\n _on_startup_checkin_done = True\n return True\n\n\n@autocollect\ndef on_startup():\n # This function MUST be called once on device startup.\n post_checkin()\n #log('on_startup completed')\n\n\ndef _reboot():\n log('Rebooting')\n flush_logs()\n import machine\n machine.reset()\n\n\n@autocollect\ndef check_commands(debug=pozetron.debug):\n # Get list of commands from server and execute them.\n global _on_startup_checkin_done, forget_network_time\n if not _on_startup_checkin_done:\n if not post_checkin():\n return\n if should_backoff():\n return\n try:\n commands = request(API_BASE + '/checkin/')\n # Because SignatureException is a type of RequestError we have to\n # catch it here and raise it explicitly.\n except SignatureException as ex:\n raise ex\n except RequestError as ex:\n print(ex)\n set_backoff()\n return\n commands = commands.json()\n import logger\n try:\n # Commands must be executed in a particular order\n if len(commands) > 1:\n commands.sort(key=lambda x: COMMAND_ORDER.get(x['type'], 0))\n for command in commands:\n # set error= and it will be reported to server\n error = ''\n if command['type'] == 'log_mode':\n # Log enable/disable\n old_send_logs = logger._send_logs\n logger._send_logs = command['data']['enable']\n # If being disabled, flush remaining lines\n if old_send_logs and not logger._send_logs:\n flush_logs()\n # Change log mode\n new_size = None\n if command['data'].get('mode') == 'memory':\n new_size = 0\n elif command['data'].get('mode') == 'file' and 'file_size' in command['data']:\n new_size = command['data']['file_size']\n if new_size is not None and new_size != logger.file_size:\n # Flush unconditionally, to keep it simple.\n flush_logs()\n # Flush failed? Force clear.\n # (this is not relevant if mode is still \"file\")\n if logger._send_fails and (logger.file_size == 0 or new_size == 0): # memory <-> file\n clear_logs()\n logger.file_size = new_size # so that following line goes to new destination\n global _logs_lost\n _logs_lost = True\n logger.file_size = new_size\n del new_size\n if logger._send_logs != old_send_logs:\n log('Log mode enabled' if logger._send_logs else 'Log mode disabled')\n # Save log mode to file, to be used on next reboot\n _save_log_mode()\n elif command['type'] == 'reboot':\n # Make sure there is 1 second delay between forget-network and reboot\n if forget_network_time is not None:\n utime.sleep_ms(one_second - utime.ticks_diff(utime.ticks_ms(), forget_network_time))\n _reboot()\n continue # reboot is special, we send confirmation AFTER reboot\n elif command['type'] == 'forget_network' and forget_network_time is None:\n try:\n os.remove('/network_config.py')\n forget_network_time = utime.ticks_ms()\n log('Removed network config')\n except OSError: # no file = do nothing\n print('forget-network is a no-op')\n else:\n error = 'Unknown command'\n # Confirm command execution\n request(API_BASE + '/command/', method='POST',\n json={\n 'command': command,\n 'success': error == '',\n 'error': error\n })\n finally:\n del logger\n\n\ndef check_file_signature(in_file, signature, secret):\n try:\n from ubinascii import unhexlify\n import uhmac\n try:\n # Try and just read the entire file into memory to HMAC it\n hmac_instance = uhmac.new(unhexlify(secret), digestmod=\"sha256\")\n content = in_file.read()\n hmac_instance.update(content)\n except MemoryError:\n try:\n del(hmac_instance)\n del(content)\n except NameError:\n pass\n hmac_instance = uhmac.new(unhexlify(secret), digestmod=\"sha256\")\n # If we don't have enough memory to fit the file, try and optimize the largest buffer size\n # to minimize the number of times we call update on the HMAC.\n mem_free = gc.mem_free()\n if mem_free > 2048 + 48:\n buf_size = 2048\n elif mem_free > 1024 + 48:\n buf_size = 1024\n if mem_free > 512 + 48:\n buf_size = 512\n else:\n buf_size = 256\n in_file.seek(0)\n content = in_file.read(buf_size)\n while content:\n hmac_instance.update(content)\n content = in_file.read(buf_size)\n return uhmac.compare_digest(unhexlify(signature), hmac_instance.digest())\n finally:\n del(unhexlify)\n\n\n@autocollect\ndef refresh_scripts(debug=pozetron.debug):\n if should_backoff():\n return\n # Update local scripts according to latest info from the server.\n scripts_url = API_BASE + '/scripts/'\n # Get latest script list from the server\n try:\n scripts = request(scripts_url).json()\n except Exception as ex:\n print(exc_logline.format('make request to refresh scripts', ex))\n set_backoff()\n raise ex\n # Update local scripts and cache\n with ScriptStore() as script_store:\n update_list = script_store.get_update_list(scripts)\n delete_list = script_store.get_delete_list(scripts)\n if not update_list and not delete_list:\n log('No changes to deployed scripts')\n return\n script_store.delete_scripts(delete_list)\n subdirs = set() # created or existing subdirs (this is for optimization)\n for script in update_list:\n try:\n script_info = request(scripts_url + script['id'] + '/').json()\n except Exception as ex:\n log(exc_logline.format('get script info', ex))\n raise ex\n try:\n script_secret = request(scripts_url + script['id'] + '/secret/').json()['secret']\n except Exception as ex:\n log(exc_logline.format('get script secret', ex))\n raise ex\n # Try to stop people overriding pozetron functionality\n print(script_info['name'])\n if script_info['name'].startswith('pozetron'):\n return\n # Pre-create subdirectories if necessary\n if '/' in script_info['name']:\n subdir, _ = script_info['name'].rsplit('/', 1)\n if subdir not in subdirs:\n makesubdir(SCRIPTS_DIR, subdir)\n subdirs.add(subdir)\n del subdir, _\n # Added an outfile option to urequests to avoid extra allocations\n tmpname = SCRIPTS_DIR + script_info['name'] + '.tmp'\n if script_info['url']:\n import urequests\n urequests.get(script_info['url'], out_file=tmpname)\n del urequests\n else:\n # Empty file, such as __init__.py\n with open(tmpname, 'w'):\n pass\n filename = script_info['name']\n if not filename.endswith('.py') and not filename.endswith('.mpy'):\n filename += '.py'\n pyname = SCRIPTS_DIR + filename\n # Check signature and finally write *.py file\n with open(tmpname, 'rb') as script:\n if check_file_signature(script, script_info['signature'], script_secret):\n try:\n os.rename(tmpname, pyname)\n except OSError:\n os.remove(pyname)\n os.rename(tmpname, pyname)\n script_store.update_script(script_info['id'], filename, script_info['signature'])\n log('Added: {} {}'.format(script_info['id'], script_info['name']))\n else:\n log('ERROR: signature mismatch: {} {}'.format(script_info['id'], script_info['name']))\n os.remove(tmpname)\n del script_info, script_secret, tmpname, pyname, filename\n\n\nclass ScriptStore:\n # Encapsulates scripts cache and filesystem.\n\n def __init__(self):\n self._cache = {}\n self._changed = False\n with open(CACHE_FILE_NAME, 'a'):\n pass\n try:\n os.listdir(SCRIPTS_DIR.split('/')[1])\n except OSError:\n os.mkdir(SCRIPTS_DIR.split('/')[1])\n with open(CACHE_FILE_NAME, 'r') as file:\n for line in file:\n line = line.strip()\n if not line:\n continue\n id, filename, signature = line.split(',', 2)\n # File does not exists - remove from cache\n # (later it will be re-downloaded from server if necessary)\n try:\n with open(SCRIPTS_DIR + filename):\n pass\n # On some platforms FileNotFoundError doesn't exist\n except OSError:\n continue\n self._cache[id] = (filename, signature)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.write_cache()\n\n def get_update_list(self, scripts):\n result = []\n for script in scripts:\n value = self._cache.get(script['id'])\n # script doesn't have a signature. That would require a second network call with the way the\n # API is today\n if value is None:# or value[1] != script['signature']:\n result.append(script)\n return result\n\n def update_script(self, id, filename, signature):\n self._cache[id] = (filename, signature)\n self._changed = True\n\n def get_delete_list(self, scripts):\n result = []\n ids = set(x['id'] for x in scripts)\n for x in self._cache.keys():\n if x not in ids:\n result.append(x)\n del ids\n return result\n\n def delete_scripts(self, ids):\n for id in ids:\n try:\n filename, hash = self._cache[id]\n self._cache.pop(id)\n self._changed = True\n except KeyError:\n continue\n try:\n os.remove(SCRIPTS_DIR + filename)\n log('Removed: {} {}'.format(id, filename))\n except OSError:\n pass\n\n def write_cache(self):\n if not self._changed:\n return\n with open(CACHE_FILE_NAME, 'w') as file:\n for key, value in self._cache.items():\n # id, module_name, hash\n file.write(','.join([key, value[0], value[1]]) + '\\n')\n\n\n# Get log mode on reboot\ndef get_log_mode():\n import logger\n try:\n logger._send_logs = LOG_SEND\n logger.file_size = LOG_FILE_SIZE\n except NameError:\n logger._send_logs = False\n logger.file_size = 1024\n try:\n data = request(API_BASE + '/log-mode/').json()\n logger._send_logs = data['enable']\n if data['mode'] == 'file':\n logger.file_size = data['file_size']\n else:\n logger.file_size = 0\n except Exception as ex:\n print('Failed to get log mode from API: {}'.format(ex))\n del logger\n\n\n# Save current log mode to file, to be used on next restart.\n# Return True if file was changed\ndef _save_log_mode():\n import logger\n log_file_size = 'LOG_FILE_SIZE = {!r}\\n'.format(logger.file_size)\n log_send = 'LOG_SEND = {!r}\\n'.format(logger._send_logs)\n del logger\n changed = False\n with open('/pozetron_config.py', 'r') as file:\n lines = file.readlines()\n # Replace existing lines\n for i in range(len(lines)):\n if lines[i].startswith('LOG_FILE_SIZE'):\n if lines[i] != log_file_size:\n lines[i] = log_file_size\n changed = True\n log_file_size = None\n elif lines[i].startswith('LOG_SEND'):\n if lines[i] != log_send:\n lines[i] = log_send\n changed = True\n log_send = None\n # Add new lines\n if log_file_size:\n lines.append(log_file_size)\n changed = True\n if log_send:\n lines.append(log_send)\n changed = True\n # Rewrite file only if changed\n if changed:\n with open('/pozetron_config.py', 'w') as file:\n for line in lines:\n file.write(line)\n del log_file_size, log_send\n return changed\n\n\n# Write whatever is passed in as data to the datalogger\ndef datapoint(data):\n try:\n request(API_BASE + '/data/', method='POST', json=data)\n except Exception as ex:\n print('Unable to post data to datalogger: {}'.format(ex))\n\n\n# This is a convenient callable that takes any arguments and always returns True\nalways_true = lambda *a, **k: True\n\nfrom ucollections import namedtuple\nSubscriber = namedtuple('Subscriber', ('topic','filter','action'))\n\n# This is the list of subscribers for the Events system\nsubscribers = set()\n\n\ndef subscribe(topic,filter,action):\n subscriber = Subscriber(topic,filter,action)\n global subscribers\n subscribers.add(subscriber)\n\n\ndef unsubscribe(topic,filter,action):\n subscriber = Subscriber(topic,filter,action)\n global subscribers\n subscribers.remove(subscriber)\n\n\n# Write whatever is passed in as data to the eventlogger\ndef event(data):\n try:\n for subscriber in pozetron.subscribers:\n if (subscriber.topic == '*' or subscriber.topic == data.get('topic', None)) and subscriber.filter(data):\n subscriber.action(data)\n except Exception as ex:\n log(exc_logline.format('run subscribers', ex))\n try:\n request(API_BASE + '/events/', method='POST', json=data)\n except Exception as ex:\n log(exc_logline.format('send event', ex))\n","sub_path":"ports/esp32/modules/pozetron.py","file_name":"pozetron.py","file_ext":"py","file_size_in_byte":23271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"511731792","text":"\"\"\"\nSimple \"Hello, World\" application using Flask\n\"\"\"\n\nimport sqlite3\nfrom flask import Flask, render_template, request, abort, g\nfrom mbta_helper import find_stop_near\n\napp = Flask(__name__)\n\nDATABASE = 'webapp.db'\n\n\ndef get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\n\ndef init_db():\n with app.app_context():\n db = get_db()\n db.execute(\n \"create table if not exists mbta(address text, vehicle text, name text, wheelchair integer)\"\n )\n db.commit()\n\n\n@app.route('/')\ndef hello():\n return render_template('index.html')\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef search_failed(e):\n return render_template('500.html'), 500\n\n\n@app.route('/nearest_mbta', methods=['GET', 'POST'])\ndef nearest_mbta():\n if request.method == 'POST':\n form = request.form\n address = form['address']\n vehicles = list()\n for key in form.keys():\n if key != 'address':\n vehicles.append(key)\n vehicle_types = ','.join(vehicles)\n db = get_db()\n cur = db.cursor()\n cur.execute('select * from mbta where address = ? and vehicle = ?',\n [address, vehicle_types])\n result = cur.fetchone()\n cur.close()\n if not result:\n try:\n name, wheelchair_accessibility = find_stop_near(\n address, vehicle_types)\n except IndexError:\n abort(500)\n cur = get_db().cursor()\n cur.execute(\n 'insert into mbta (address, vehicle, name, wheelchair) values (?, ?, ?, ?)',\n (address, vehicle_types, name, wheelchair_accessibility))\n cur.close()\n db.commit()\n else:\n name = result[2]\n wheelchair_accessibility = result[3] == 1\n return render_template('mbta_station.html',\n name=name,\n wheelchair_accessibility=wheelchair_accessibility)\n\n\nif __name__ == '__main__':\n init_db()\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"491442682","text":"\nfrom utils.log import logger\nfrom core.http.response import res_code, ResCode\nfrom apps.user.models import Users,Token,Role\n\n\ndef get_user(request):\n \"\"\"\n Return the user model instance associated with the given request session.\n If no user is retrieved, return an instance of `AnonymousUser`.\n \"\"\"\n\n token = request.META.get('HTTP_AUTHORIZATION')\n if not token:\n return (None,'token不存在,请退出后重新登录!', 200, ResCode.Token_Missing)\n\n try:\n result=Token.objects.get(key=token)\n except Token.DoesNotExist:\n return (None,'token已失效,请退出后重新登录!', 200, ResCode.Token_Missing)\n\n user=Users.objects.get(userid=result.userid)\n user.rolename = Role.objects.get(rolecode=user.rolecode).name\n if user.status == 1:\n return (None, '登录账号不存在!',200, ResCode.Token_Missing)\n elif user.status == 2:\n return (None, '已冻结!', 200, ResCode.Token_Missing)\n\n return (user,'操作成功!', 200, ResCode.Success)\n","sub_path":"libs/auth/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"102260140","text":"from sklearn.linear_model import LinearRegression\nimport pandas as pd\nimport numpy as np\nimport os\nimport warnings\n\nwarnings.filterwarnings(action=\"ignore\", module=\"scipy\", message=\"^internal gelsd\")\n\nif __name__ == '__main__':\n\n fn = 'TSLA.csv'\n if os.path.exists(fn):\n dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d')\n df = pd.read_csv(fn, parse_dates=['Date'], date_parser=dateparse, index_col='Date')\n # df.index = pd.to_datetime(df.Date)\n # Drop rows with missing values\n df = df.dropna()\n\n df['S_3'] = df['Close'].shift(1).rolling(window=3).mean()\n df['S_9'] = df['Close'].shift(1).rolling(window=9).mean()\n df = df.dropna()\n X = df[['S_3', 'S_9']]\n # print(X.head())\n y = df['Close']\n t = .8\n t = int(t * len(df))\n # Train dataset\n X_train = X[:t]\n y_train = y[:t]\n # Test dataset\n X_test = X[t:]\n # print(X_test)\n y_test = y[t:]\n\n linear = LinearRegression().fit(X, y)\n # linear = LinearRegression().fit(X_train, y_train)\n\n print(\" y =\", round(linear.coef_[0], 2),\n \"* 3 Days Moving Average\", round(linear.coef_[1], 2),\n \"* 9 Days Moving Average +\", round(linear.intercept_, 2))\n\n # predicted_price = linear.predict(X_test)\n # predicted_price = pd.DataFrame(predicted_price, index=y_test.index, columns=['price'])\n # # print(predicted_price.head)\n # # predicted_price.plot(x='Date', y='price', figsize=(10, 5))\n # predicted_price.plot(figsize=(10, 5))\n # y_test.plot()\n # plt.legend(['预测值', '实际值'])\n # plt.ylabel(ticker + \" 数值\")\n # # plt.show()\n #\n # r2_score = linear.score(X[t:], y[t:]) * 100\n # print(float(\"{0:.2f}\".format(r2_score)))\n","sub_path":"fit_test/pred.py","file_name":"pred.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"522152026","text":"import json\nimport os\nfile_path = './output/result0.json'\nfile_path_for_js = './output2/result0.txt'\ndir_path= './output/'\nout_dir_path = './output2/'\ndef read_file_routes(file,count):\n with open(dir_path + file, 'r') as fp:\n with open(out_dir_path + 'result' + str(count)+'.txt', 'w') as out:\n data = json.load(fp)\n for trajectory in data:\n parsed_data = json.loads(trajectory)\n try:\n out.write(parsed_data['paths'][0]['points'] + '\\n')\n except Exception:\n print(parsed_data)\ndef read_routes():\n count = 0\n file_list = os.listdir('./output')\n for file in file_list:\n read_file_routes(file,count)\n count+=1\n print('file'+str(count)+' is output2')\ndef count():\n file_path = './output/result0.json'\n with open(file_path, 'r') as fp:\n data = json.load(fp)\n print(len(data))\n\nif __name__ == '__main__':\n read_routes()\n","sub_path":"routing/pc/read_route.py","file_name":"read_route.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"414863406","text":"import datetime\nimport pandas as pd\n\nfrom pytrends.request import TrendReq\nfrom mwviews.api import PageviewsClient\n\n\nclass WebAnalysis:\n def __init__(self):\n pass\n\n @staticmethod\n def retrieve_google_trends(kw_list, date_range):\n \"\"\"Retrieve Google trends for a search term within a date range.\n\n See https://github.com/GeneralMills/pytrends for documentation of pytrends\n\n Parameters\n ----------\n kw_list : list of strings\n Keywords to get data for. Up to five terms in a list.\n date_range : list\n List containing start and stop date for the trend. Date is in format '%Y-%m-%d'.\n Example: ['2017-01-01', '2017-12-31']\n\n Returns\n -------\n pandas.DataFrame\n DataFrame containing the trend data\n\n \"\"\"\n # From: https://github.com/WillKoehrsen/Data-Analysis/tree/master/stocker\n # Set up the trend fetching object\n pytrends = TrendReq(hl='en-US', tz=360)\n\n try:\n # Create the search object\n timeframe = date_range[0] + ' ' + date_range[1]\n pytrends.build_payload(kw_list, cat=0, timeframe=timeframe, geo='', gprop='news')\n\n # Retrieve the interest over time\n trends = pytrends.interest_over_time()\n\n related_queries = pytrends.related_queries()\n\n except Exception as e:\n print('\\nGoogle Search Trend retrieval failed.')\n print(e)\n return\n\n return trends, related_queries\n\n @staticmethod\n def retrieve_wikipedia_trends(search, date_range, locale='en', granularity='daily'):\n \"\"\"Retrieve article views from Wikipedia.\n\n Parameters\n ----------\n search : str\n Search string (article name)\n date_range : list\n List containing start and stop date for the trend. Date is in format '%Y-%m-%d'.\n Example: ['2017-01-01', '2017-12-31']\n locale : str\n Defines which Wikipedia locale to use, e.g. 'en' searches in English Wikipedia,\n 'de' searches in German Wikipedia.\n granularity : str\n Granularity of the article views, e.g. 'daily', 'monthly'\n\n Returns\n -------\n pandas.DataFrame\n DataFrame containing the trend data\n\n \"\"\"\n # convert date in format \"YYYY-MM-DD\" to format \"YYYYMMDD\"\n start_date = datetime.datetime.strptime(date_range[0], '%Y-%m-%d').strftime('%Y%m%d')\n end_date = datetime.datetime.strptime(date_range[1], '%Y-%m-%d').strftime('%Y%m%d')\n\n p = PageviewsClient('dummy')\n data = p.article_views(locale+'.wikipedia', search, granularity=granularity,\n start=start_date, end=end_date)\n\n # p.article_views returns a nested dict. The following extracts the data from this dict and converts it to a\n # pandas.DataFrame.\n data_date = list(data.keys())\n data_trend = [list(d.values())[0] for d in list(data.values())]\n df = pd.DataFrame({'date': data_date, 'views': data_trend})\n\n return df\n","sub_path":"WebAnalysis.py","file_name":"WebAnalysis.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"536903177","text":"#!/usr/bin/env python\nimport os\n\nfrom distutils.core import setup\n\nfrom setuptools import find_packages\n\ndjango_base_dir = 'djangobase/project_template'\n\ndata_files = []\nfor dirpath, dirnames, filenames in os.walk(django_base_dir):\n file_list = [os.path.join(dirpath, f) for f in filenames]\n data_files.append([dirpath, file_list])\n\nsetup(\n name='Django-base',\n version='0.91',\n url=\"https://github.com/macmichael01/django-base\",\n author='Chris McMichael',\n author_email='macmichael01@gmail.com',\n description='Django-base project setup',\n install_requires=('jinja2',),\n packages = ['djangobase/'],\n data_files = data_files,\n scripts = ['djangobase/scripts/mkdjango'],\n license=\"BSD\",\n keywords=\"django python setup\",\n long_description=\"Django base project setup\",\n)","sub_path":"pypi_install_script/Django-base-0.91.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"507015369","text":"import komand\nfrom .schema import CreateAddressObjectInput, CreateAddressObjectOutput, Input, Output, Component\n\n# Custom imports below\nfrom komand.exceptions import PluginException\nimport ipaddress\nfrom icon_fortinet_fortigate.util.util import Helpers\n\n\nclass CreateAddressObject(komand.Action):\n def __init__(self):\n super(self.__class__, self).__init__(\n name=\"create_address_object\",\n description=Component.DESCRIPTION,\n input=CreateAddressObjectInput(),\n output=CreateAddressObjectOutput(),\n )\n\n def run(self, params={}):\n host = params.get(Input.ADDRESS)\n name = params.get(Input.ADDRESS_OBJECT, \"\")\n whitelist = params.get(Input.WHITELIST)\n skip_rfc1918 = params.get(Input.SKIP_RFC1918)\n helper = Helpers(self.logger)\n\n type_ = helper.determine_address_type(host)\n if type_ == \"ipmask\":\n host = helper.ipmask_converter(host)\n # White_list expects a IP rather than a CIDR, The rest of this action requires a CIRD\n # whitelist_ref will save a version of the host without the CIRD\n whitelist_ref = host\n if host.endswith(\"/32\"):\n whitelist_ref = host[:-3]\n\n ip_address = ipaddress.ip_network(host)\n\n if type_ == \"ipmask\" and skip_rfc1918 is True and ip_address.is_private:\n return {\n Output.SUCCESS: False,\n Output.RESPONSE_OBJECT: {\n \"message\": f\"The IP address specified ({host}) is private and will be ignored as per \"\n f\"the action configuration.\"\n },\n }\n\n found = False\n if whitelist:\n found = helper.match_whitelist(whitelist_ref, whitelist)\n if not found:\n payload = {\"name\": name if name else host, \"type\": type_, \"subnet\": host}\n\n if ip_address.version == \"4\":\n endpoint = f\"https://{self.connection.host}/api/v2/cmdb/firewall/address\"\n else:\n endpoint = f\"https://{self.connection.host}/api/v2/cmdb/firewall/address6\"\n\n response = self.connection.session.post(endpoint, json=payload, verify=self.connection.ssl_verify)\n try:\n json_response = response.json()\n except ValueError:\n raise PluginException(\n cause=\"Data sent by FortiGate was not in JSON format.\\n\",\n assistance=\"Contact support for help.\",\n data=response.text,\n )\n helper.http_errors(json_response, response.status_code)\n\n return {Output.SUCCESS: True, Output.RESPONSE_OBJECT: json_response}\n\n return {\n Output.SUCCESS: False,\n Output.RESPONSE_OBJECT: {\"message\": \"IP matched whitelist, skipping block action.\"},\n }\n","sub_path":"fortinet_fortigate/icon_fortinet_fortigate/actions/create_address_object/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"236026758","text":"\"\"\"\nVerify that deleting invalid resources does\nnot raise exceptions\n\"\"\"\nimport random\nimport string\nfrom unittest.mock import MagicMock\nfrom src.utils import config\nfrom src import grant\n\n\n\ndef get_random_string(length=8):\n \"\"\"randome string for tests\"\"\"\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(length))\n\ndef test_create_grant(monkeypatch):\n \"\"\"\n Test that we can create an existing grant without failing\n \"\"\"\n tenant = 'mmm-dev.auth0.com'\n name = f'e2e-test-{get_random_string()}'\n audience = f'https://{name}.co'\n client_id = None\n api_id = None\n monkeypatch.setenv('ENVIRON', 'qa')\n\n provider = config.get_provider(tenant)\n\n\n try:\n client_id, _ = provider.create_application(**{\n 'name': name,\n 'description': 'e2e test application',\n 'app_type': 'spa',\n })\n\n api_id = provider.create_api(**{\n 'name': name,\n 'identifier': audience,\n })\n event = {\n 'ResourceProperties': {\n 'ApplicationId': client_id,\n 'Audience': audience,\n 'Tenant': tenant,\n }\n }\n grant.create(event, {}, MagicMock())\n grant.update(event, {}, MagicMock())\n except Exception as error:\n print('test is failing')\n teardown_resources(\n provider=provider,\n client_id=client_id,\n api_id=api_id,\n )\n raise error\n\n teardown_resources(\n provider=provider,\n client_id=client_id,\n api_id=api_id,\n )\n\ndef teardown_resources(provider, client_id, api_id):\n \"\"\"given client id and api id it will try to\n tear these things down\"\"\"\n if client_id:\n provider.delete_application(client_id)\n if api_id:\n provider.delete_api(api_id)\n","sub_path":"tests/e2e/test_create_grant_twice.py","file_name":"test_create_grant_twice.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"444560676","text":"from freezegun import freeze_time\nfrom django_swagger_utils.utils.test import CustomAPITestCase\nfrom project_management_portal import models\nfrom project_management_portal.utils.factories\\\n import\\\n DeveloperFactory,\\\n StateFactory,\\\n ChecklistFactory, TransitionFactory,\\\n WorkflowFactory, ProjectFactory,\\\n TaskFactory\n\nclass CustomTestUtils(CustomAPITestCase):\n\n def reset(self):\n StateFactory.reset_sequence(1)\n ChecklistFactory.reset_sequence(1)\n TransitionFactory.reset_sequence(1)\n WorkflowFactory.reset_sequence(1)\n ProjectFactory.reset_sequence(1)\n TaskFactory.reset_sequence(1)\n DeveloperFactory.reset_sequence(1)\n # ProjectFactory.created_by_id.reset()\n ProjectFactory.project_type.reset()\n # WorkflowFactory.created_by_id.reset()\n TaskFactory.issue_type.reset()\n\n def remove_token(self):\n from oauth2_provider.models import AccessToken\n # AccessToken.objects.filter(user_id=1).delete()\n print(AccessToken.objects.all())\n\n @freeze_time(\"2020-06-26\")\n def create_workflow(self):\n from project_management_portal.models import Transition\n self.reset()\n states = StateFactory.create_batch(size=4)\n checklist = ChecklistFactory.create_batch(size=5)\n TransitionFactory(from_state_id=1, to_state_id=2, checklist=checklist)\n TransitionFactory(from_state_id=2, to_state_id=3, checklist=checklist)\n TransitionFactory(from_state_id=3, to_state_id=4, checklist=checklist)\n TransitionFactory(from_state_id=2, to_state_id=1, checklist=checklist)\n TransitionFactory(from_state_id=3, to_state_id=1, checklist=checklist)\n\n transitions = Transition.objects.all()\n workflow = WorkflowFactory.create(\n states=states,\n transitions=transitions)\n\n return workflow\n\n @freeze_time(\"2020-06-26\")\n def create_project(self):\n self.reset()\n ProjectFactory.project_type.reset()\n\n workflow = self.create_workflow()\n DeveloperFactory.create_batch(size=2, project_id=1)\n ProjectFactory(workflow=workflow)\n TaskFactory.create_batch(size=5,\n project_id=1,\n assignee_id=1,\n state_id=1)\n\n def create_task(self):\n self.reset()\n checklist = ChecklistFactory.create_batch(size=5)\n TaskFactory(state_id=1,\n conditions_satisfied = checklist\n )\n\n def create_workflows(self):\n self.reset()\n WorkflowFactory.create_batch(size=5, created_by_id=1)\n\n @freeze_time(\"2020-06-26\")\n def create_projects(self, user_id=None):\n self.reset()\n\n if not user_id:\n user_id = 1\n\n workflow = self.create_workflow()\n ProjectFactory.create_batch(size=6,\n workflow=workflow,\n created_by_id=user_id)\n DeveloperFactory.create_batch(size=4, user_id=user_id)\n \n def make_user_admin(self):\n from user_app.models import User\n User.objects.filter(user_id=1).update(is_admin=True)\n","sub_path":"project_management_portal/utils/custom_test_utils.py","file_name":"custom_test_utils.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"596938515","text":"import os\nfrom unittest.mock import call, patch\n\nfrom django.conf import settings\nfrom django.test import TestCase\n\nfrom jarbas.chamber_of_deputies.management.commands.reimbursements import Command\nfrom jarbas.chamber_of_deputies.models import Reimbursement\n\n\nclass TestCommand(TestCase):\n\n def setUp(self):\n self.command = Command()\n\n\nclass TestCreate(TestCommand):\n\n @patch.object(Command, 'print_count')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.print')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.create_or_update_reimbursement')\n def test_create_or_update(self, create, print_, print_count):\n reimbursements = (\n dict(ahoy=42, document_id=1),\n dict(ahoy=84, document_id=2)\n )\n self.command.create_or_update(reimbursements)\n create.delay.assert_has_calls((call(r) for r in reimbursements))\n\n\nclass TestMarkNonUpdated(TestCommand):\n\n @patch.object(Reimbursement.objects, 'filter')\n def test_mark_available_in_latest_dataset(self, filter_):\n self.command.started_at = 42\n self.command.mark_not_updated_reimbursements()\n filter_.assert_called_once_with(last_update__lt=self.command.started_at)\n filter_.return_value.update.assert_called_once_with(available_in_latest_dataset=False)\n\n\nclass TestConventionMethods(TestCommand):\n\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.reimbursements')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.create_or_update')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.mark_not_updated_reimbursements')\n def test_handler_without_options(self, mark, create, reimbursements):\n reimbursements.return_value = (1, 2, 3)\n self.command.handle(dataset='reimbursements.xz')\n create.assert_called_once_with(reimbursements)\n self.assertEqual('reimbursements.xz', self.command.path)\n mark.assert_called_once_with()\n\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.reimbursements')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.create_or_update')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.drop_all')\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.Command.mark_not_updated_reimbursements')\n def test_handler_with_options(self, mark, drop_all, create, reimbursements):\n self.command.handle(dataset='reimbursements.xz', drop=True)\n drop_all.assert_called_once_with(Reimbursement)\n create.assert_called_once_with(reimbursements)\n mark.assert_called_once_with()\n\n\nclass TestFileLoader(TestCommand):\n\n @patch('jarbas.chamber_of_deputies.management.commands.reimbursements.print')\n def test_reimbursement_property(self, print_):\n self.command.path = os.path.join(\n settings.BASE_DIR,\n 'jarbas',\n 'core',\n 'tests',\n 'fixtures',\n 'reimbursements.xz'\n )\n output = tuple(self.command.reimbursements)\n expected = {\n 'applicant_id': '13',\n 'batch_number': '9',\n 'cnpj_cpf': '11111111111111',\n 'congressperson_document': '2',\n 'congressperson_id': '1',\n 'congressperson_name': 'Roger That',\n 'document_id': '42',\n 'document_number': '6',\n 'document_type': '7',\n 'document_value': '8.90',\n 'installment': '7',\n 'issue_date': '2014-02-12T00:00:00',\n 'leg_of_the_trip': '8',\n 'month': '1',\n 'net_values': '1.99,2.99',\n 'party': 'Partido',\n 'passenger': 'John Doe',\n 'reimbursement_numbers': '10,11',\n 'reimbursement_values': '12.13,14.15',\n 'remark_value': '1.23',\n 'state': 'UF',\n 'subquota_description': 'Subquota description',\n 'subquota_group_description': 'Subquota group desc',\n 'subquota_group_id': '5',\n 'subquota_number': '4',\n 'supplier': 'Acme',\n 'term': '1970',\n 'term_id': '3',\n 'total_net_value': '4.56',\n 'reimbursement_value_total': '',\n 'year': '1970'\n }\n self.assertEqual(output[0], expected)\n","sub_path":"jarbas/chamber_of_deputies/tests/test_reimbursements_command.py","file_name":"test_reimbursements_command.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"48836138","text":"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"\n\nimport os\nfrom django.test import TestCase\nfrom picture_contest.models import GameUser, Team, Participant, Category, ImageFile\nfrom django.core.urlresolvers import reverse\nfrom django.core.files import File as DjangoFile\nfrom django.conf import settings\nfrom shutil import rmtree\n\n\nclass ModelTests(TestCase):\n def setUp(self):\n self.test_user = GameUser.objects.create_user(username='test_user',\n email='test@mail.com',\n password='test_pass',\n team_name='test_team')\n\n self.test_team = Team.objects.create(name='test_team')\n\n self.test_participant = Participant.objects.create(user=self.test_user,\n team=self.test_team)\n\n self.test_category = Category.objects.create(name='test_category')\n\n def test_game_user_model(self):\n \"\"\"Game User test.\"\"\"\n\n game_users_count = GameUser.objects.all().count()\n GameUser.objects.create_user(username='test_user2',\n email='test@mail.com',\n password='test_pass',\n team_name='test_team')\n self.assertEqual(game_users_count+1, GameUser.objects.all().count())\n\n def test_team_model(self):\n \"\"\"Team tests.\"\"\"\n\n teams_count = Team.objects.all().count()\n Team.objects.create(name='test_team2')\n\n self.assertEqual(teams_count+1, Team.objects.all().count())\n self.assertEqual(unicode(self.test_team), u\"%s\" % self.test_team.name)\n\n def test_participant_model(self):\n \"\"\"Participant tests.\"\"\"\n\n participants_count = Participant.objects.all().count()\n\n test_user = GameUser.objects.create_user(username='test_user2',\n email='test@mail.com',\n password='test_pass',\n team_name='test_team')\n Participant.objects.create(user=test_user, team=self.test_team)\n\n self.assertEqual(participants_count+1, Participant.objects.all().count())\n self.assertEqual(unicode(self.test_participant), u\"%s\" % self.test_participant.user.username)\n\n def test_category_model(self):\n \"\"\"Category tests.\"\"\"\n\n categories_count = Category.objects.all().count()\n Category.objects.create(name='test_category2')\n\n self.assertEqual(categories_count+1, Category.objects.all().count())\n self.assertEqual(unicode(self.test_category), u\"%s\" % self.test_category.name)\n\n def test_image_file_model(self):\n \"\"\"ImageFiles tests.\"\"\"\n\n image_files_count = ImageFile.objects.all().count()\n\n fd = open('test_file.jpg', 'w+')\n file_path = os.path.abspath(fd.name)\n\n file_image = DjangoFile(fd, 'test_file_name')\n\n ImageFile.objects.create(\n image=file_image,\n name='test_file',\n team=self.test_team,\n category=self.test_category\n )\n test_image_file = ImageFile.objects.get(name='test_file')\n\n self.assertEqual(image_files_count+1, ImageFile.objects.all().count())\n self.assertEqual(unicode(test_image_file), u\"%s\" % test_image_file.name)\n\n #File and Directory cleanup after file upload.\n fd.close()\n os.remove(file_path)\n\n base_dir = os.path.join(settings.MEDIA_ROOT, 'files', self.test_team.name)\n\n rmtree(base_dir)\n\n\nclass ViewTests(TestCase):\n def test_home_view(self):\n \"\"\"Test that Home view is working as inspected.\"\"\"\n\n response = self.client.get(reverse('home'))\n self.assertContains(response, text=\"Home\", status_code=200)\n\n def test_views(self):\n response = self.client.get(reverse('send_email'))\n self.assertEqual(response.status_code, 200) # this is not enough\n\n response = self.client.get(reverse('db_setup'))\n self.assertEqual(response.status_code, 200)\n","sub_path":"picture_contest/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"628802558","text":"# 연습문제 5번\nprint(\"기호를 입력하시오: \")\nc = input()\nprint(\"중간에 삽입할 문자열을 입력하시오 : \")\nd = input()\nprint(c[0]+d+c[1])\n\n# 연습문제 6번\nlist = ['1','2','3','4']\nsum = int(list[0])+int(list[1])+int(list[2])+int(list[3])\nprint(\"리스트 숫자들의 합 = \",sum) \n\n# 연습문제 7번\nimport turtle\nt = turtle.Turtle()\nt.shape(\"turtle\")\n\ncolor = [0] * 3\ncolor[0] = input(\"색상 1을 입력:\")\ncolor[1] = input(\"색상 2을 입력:\")\ncolor[2] = input(\"색상 3을 입력:\")\n\nt.fillcolor(color[0])\nt.begin_fill()\nt.circle(50)\nt.end_fill()\n\nt.up()\nt.fd(100)\nt.down()\n\nt.fillcolor(color[1])\nt.begin_fill()\nt.circle(50)\nt.end_fill()\n\nt.up()\nt.fd(100)\nt.down()\n\nt.fillcolor(color[2])\nt.begin_fill()\nt.circle(50)\nt.end_fill()\n\n","sub_path":"파이썬프로그래밍-수업/4주차/4주차-6번째-연습문제.py","file_name":"4주차-6번째-연습문제.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"161336163","text":"from modules.aux.io import log\nfrom modules.aux.parser import matrixPolarToCartesian\n\n\n'Triangulação da parte posterior'\ndef backTriangulation(heights, angles):\n triangulation = list()\n for i in range(heights-1):\n for j in range(angles-1):\n v1 = i*angles + j\n v2 = i*angles + j + angles + 1\n v3 = i*angles + j + angles\n triangulation.append([v1, v2, v3])\n v3 = v2\n v2 = i*angles + j + 1\n triangulation.append([v1, v2, v3])\n return triangulation\n\n\n'Triangulação do lado direito'\ndef rightTriangulation(heights, angles):\n triangulation = list()\n for i in range(heights-1):\n v1 = i*angles\n v2 = i*angles + angles\n v3 = angles*heights + i\n triangulation.append([v1, v2, v3])\n v1 = v3\n v3 = angles*heights + i + 1\n triangulation.append([v1, v2, v3])\n return triangulation\n\n\n'Triangulação do lado esquerdo'\ndef leftTriangulation(heights, angles):\n triangulation = list()\n for i in range(1, heights):\n v1 = i*angles - 1\n v2 = heights*angles + i - 1\n v3 = heights*angles + i\n triangulation.append([v1, v2, v3])\n v2 = v3\n v3 = (i+1)*angles - 1\n triangulation.append([v1, v2, v3])\n return triangulation\n\n\n'Triangulação da parte superior'\ndef upperTriangulation(heights, angles):\n triangulation = list()\n for i in range(angles-1):\n v1 = i\n v2 = heights*angles\n v3 = i + 1\n triangulation.append([v1, v2, v3])\n return triangulation\n\n\n'Triangulação da parte inferior'\ndef bottomTriangulation(heights, angles):\n triangulation = list()\n for i in range(angles-1):\n v1 = angles*heights + heights - 1\n v2 = (heights-1)*angles + i\n v3 = (heights-1)*angles + i + 1\n triangulation.append([v1, v2, v3])\n return triangulation\n\n\n'Função que adiciona pontos médios em cada altura'\ndef getHeightMean(shape):\n shape_xyz = list()\n for i in range(len(shape)):\n m = 0\n for j in range(len(shape[i])):\n m += shape[i][j][2]\n shape_xyz.append([0, 0, m/len(shape[0])])\n return shape_xyz\n\n\n'Função principal do módulo'\ndef reconstruct(shape, max_range, lateral=True, bottom=True, upper=True, cloud=False):\n log('Reconstruindo o modelo')\n\n triangulation = list()\n heights = len(shape)\n angles = len(shape[0])\n\n shape = matrixPolarToCartesian(shape)\n\n shape_xyz = list()\n for i in range(len(shape)):\n for j in range(len(shape[i])):\n shape_xyz.append(shape[i][j])\n shape_xyz += getHeightMean(shape)\n\n if cloud:\n return shape_xyz\n\n triangulation = backTriangulation(heights, angles)\n if lateral:\n triangulation += rightTriangulation(heights, angles)\n triangulation += leftTriangulation(heights, angles)\n if bottom:\n triangulation += bottomTriangulation(heights, angles)\n if upper:\n triangulation += upperTriangulation(heights, angles)\n\n return shape_xyz, triangulation","sub_path":"modules/reconstruction.py","file_name":"reconstruction.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"402783009","text":"import gym\n\nfrom treys.card import Card\nfrom treys.deck import Deck\n\nfrom .player import Player\nfrom .evaluator import Evaluator\n\n\nclass HeartsEnv(gym.Env):\n\n def __init__(self, endgame_score=100):\n self._number_of_players = 4\n self._number_of_hand_card_per_player = 52 // self._number_of_players\n self._evaluator = Evaluator()\n self._deck = Deck()\n self._deck.shuffle()\n self._players = [Player(i, self._deck.draw(self._number_of_hand_card_per_player)) for i in range(self._number_of_players)]\n self._trick = 0\n self._round = 0 # each round has 13 trick when we have 4 players\n self._playing_cards = []\n self._playing_ids = []\n self._current_player_id = 0\n self._endgame_score = endgame_score\n\n def get_observation(self):\n ob = {}\n ob['scores'] = [player.get_score() for player in self._players]\n ob['playing_cards'] = self._playing_cards.copy()\n ob['playing_ids'] = self._playing_ids.copy()\n ob['hand_cards'] =self._players[self._current_player_id].get_hand_cards()\n if len(self._playing_cards) == 0:\n ob['valid_hand_cards'] = ob['hand_cards']\n else:\n trick_suit = Card.get_suit_int(self._playing_cards[0])\n ob['valid_hand_cards'] = [card for card in ob['hand_cards'] if Card.get_suit_int(card) == trick_suit]\n if len(ob['valid_hand_cards']) == 0:\n ob['valid_hand_cards'] = ob['hand_cards']\n return ob\n\n def step(self, action_card):\n if len(self._playing_cards) == self._number_of_players:\n self._playing_cards.clear()\n self._playing_ids.clear()\n self._players[self._current_player_id].remove_hand_card(action_card)\n self._playing_cards.append(action_card)\n self._playing_ids.append(self._current_player_id)\n if len(self._playing_cards) == self._number_of_players:\n self._trick += 1\n punish_score, punish_player_id = self._evaluator.evaluate(self._playing_cards, self._playing_ids)\n self._players[punish_player_id].add_score(punish_score)\n rewards = [0] * self._number_of_players\n info = {}\n if len(self._playing_cards) == self._number_of_players:\n self._current_player_id = punish_player_id\n rewards[punish_player_id] = punish_score\n else:\n self._current_player_id += 1\n self._current_player_id = self._current_player_id % 4\n done = False\n if self._trick == self._number_of_hand_card_per_player:\n scores = [player.get_score() for player in self._players]\n for score in scores:\n if score >= 100:\n done = True\n break\n if done is False:\n self._start_new_round()\n observation = self.get_observation()\n return observation, rewards, done, info\n\n def _start_new_round(self):\n self._deck = Deck()\n self._deck.shuffle()\n for player in self._players:\n player.reset_hand_cards(self._deck.draw(self._number_of_hand_card_per_player))\n self._trick = 0\n self._playing_cards = []\n self._playing_ids = []\n self._current_player_id = 0\n self._round += 1\n\n def reset(self):\n self._deck = Deck()\n self._deck.shuffle()\n for player in self._players:\n player.reset(self._deck.draw(self._number_of_hand_card_per_player))\n self._trick = 0\n self._playing_cards = []\n self._playing_ids = []\n self._current_player_id = 0\n self._round = 0\n\n def render(self, mode='human', close=False):\n print(\"-------PLAYER------\")\n for i in range(self._number_of_players):\n print(\"player {}\".format(i))\n Card.print_pretty_cards(self._players[i].get_hand_cards())\n print(\"score: {}\".format(self._players[i].get_score()))\n print(\"--------BOARD-------\")\n Card.print_pretty_cards(self._playing_cards)\n print(\"--------------------\")\n","sub_path":"gymhearts/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"175813715","text":"# Vamos criar a estrutura de uma Locadora de filmes...\n\n# definindo as variáveis compostas:\n\nlocadora = []\n\nfilme0 = {\n 'Titulo':'Star Wars',\n 'Ano':1977,\n 'Diretor':'George Lucas'\n}\n\nfilme1 = {\n 'Titulo':'Avengers',\n 'Ano':2012,\n 'Diretor':'Joss Wendom'\n}\n\nfilme2 = {\n 'Titulo': 'Matrix',\n 'Ano':1999,\n 'Diretor':'Wachowski'\n}\n\nlocadora.append(filme0,filme1,filme2)\n","sub_path":"AulasTeoricas/Aula19/exemp02.py","file_name":"exemp02.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"299084103","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nsales_data = pd.read_csv('sales.csv')\nprint(sales_data)\ntype(sales_data)\n\n#Read data headers\nprint(sales_data.columns)\n\n#Summary statistics of data, including mean, min and max.\nprint(sales_data.describe())\n\n#Sum of sales across the year:\ntotal_sales = sales_data['sales'].sum()\nprint('The total sales across 2018 are:')\nprint(total_sales)\n\n#Plot of sales and expenditure over 2018:\nplt.plot(sales_data.month, sales_data.sales)\nplt.plot(sales_data.month, sales_data.expenditure)\nplt.title('Sales & Expenditure across 2018')\nplt.xlabel('Month')\nplt.ylabel('Sales/Expenditure')\nplt.grid(True)\nplt.show()\n\n\n\n","sub_path":"pandas-practice.py","file_name":"pandas-practice.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"471746968","text":"#encoding: utf-8\nimport ctypes \nfrom ctypes import windll, create_string_buffer, memmove, memset, c_char_p,c_float\nimport Constant\nimport threading\nimport time\nimport ThreadControl\nfrom ThreadControl import ThreadPool as tp, ThreadPool\n\nclass Trader():\n def __init__(self,trader_ip,trader_port,trader_user,trader_password,trader_txword,trader_yyb,dll_path,trader_version = None,**kwargs):\n #使用的dll 设置系列参数\n self.dll = None\n self.trader_ip = trader_ip\n self.trader_port = trader_port\n self.trader_user= trader_user\n self.trader_psword= trader_password\n self.trader_txword= trader_txword\n self.trader_yyb= trader_yyb \n if trader_version == None:\n self.trader_version = \"2.28\"\n else:\n self.trader_version = trader_version\n #为 一块 String内存地址指针 ,用于保存各类信息的返回值\n self.trader_Ree = create_string_buffer(1024*1024) #为Ree变量申请一个内存块,用于返回数据\n #登陆后生的 login_code \n self.login_code = self.login()\n #用户股东代号用于交易send_order\n self.holder_number = {}\n #用户交易股票计划列表\n self.trade_stock_list = {}\n #用户交易账户下单历史\n #{股票代号:股票交易记录}\n self.trade_record_list = {}\n self._init_registration(dll_path)\n# print(kwargs)\n if kwargs:\n self.init_holder_number(kwargs['sh_code'],kwargs['sz_code'])\n #交易记录锁\n self.trade_record_lock = threading.RLock()\n #交易股票锁\n self.trade_stock_lock = threading.RLock()\n #线程池\n self.thread_pool = ThreadPool(5)\n \n #获取相应的股票交易列表\n def get_trade_stock_list(self):\n return self.trade_stock_list\n\n #设置相应的交易股票列表 \n def set_trade_stock_list(self,trade_stock_list):\n self.trade_stock_list = trade_stock_list\n\n #获取相应的交易股票\n #从相应的trade_stock_list中放回一个股票\n def get_trade_stock(self):\n self.trade_stock_lock.acquire()\n if len(self.trade_stock_list) != 0:\n trade_stock = self.trade_stock_list.popitem()\n self.trade_stock_lock.release()\n return trade_stock\n else:\n self.trade_record_lock.release()\n return False \n #修改相应的trade_record_list\n def append_trade_record(self,book_order):\n self.trade_record_lock.acquire()\n book_config = {}\n book_config['stock_code'] = book_order['stock_code']\n book_config['side'] = book_order['side']\n self.trade_record_list[book_order['book_code']] = book_config\n self.trade_record_lock.release()\n\n #获得相应的交易记录\n def get_trade_record(self):\n self.trade_record_lock.acquire()\n book_info = self.trade_record_list.popitem()\n print(book_info[0])\n self.trade_record_lock.release()\n\n #交易股票\n def trade_single_stock(self):\n trade_stock = self.get_trade_stock()\n trade_config = trade_stock[1]\n trade_code = trade_stock[0]\n if trade_stock != False:\n #卖出股票\n stock_code = trade_stock[0]\n print(stock_code)\n stock_price = trade_config['price']\n stock_amount = trade_config['amount']\n book_config = {}\n print(\"stock_code:\",stock_code,\"stock_price:\",stock_price,\"stock_amount:\",stock_amount)\n if trade_config['side'] == 0:\n #买入\n book_code = self.buy_stock(stock_code, stock_price, stock_amount)\n #获得相应下单的单号\n book_config['book_code'] = book_code\n book_config['side'] = 0 \n print(\"buy stock :\",stock_code,stock_amount,time.time())\n else:\n #卖出 \n book_code = self.sell_stock(stock_code, stock_price, stock_amount)\n book_config['book_code'] = book_code\n book_config['side'] = 1\n book_config['stock_code'] = stock_code\n print(\"sell stock :\",stock_code,stock_amount,time.time())\n self.append_trade_record(book_config)\n\n #执行交易计划\n def apply_trade_plan(self):\n for i in range(len(self.trade_stock_list)):\n self.thread_pool.run(func=self.trade_single_stock,args=())\n self.thread_pool.close()\n \n #取消当前所有交易\n def cancel_all_trade(self):\n for i in range(len(self.trade_record_list)):\n self.thread_pool.run(func=self.get_trade_record,args=())\n self.thread_pool.close()\n\n \n #查看相应的股票持仓\n #返回Boolean成功查询返回True 非False\n def query_positions(self,query_type):\n self.login_code = self.login()\n #清空信息缓存\n memset(ctypes.byref(self.trader_Ree),0x0,1024*1024)\n if self.login_code != None and self.login_code != 0:\n self.dll.JL_QueryData(self.login_code,bytes(str(self.trader_user), 'ascii'),query_type,self.trader_Ree) # 这里是查询函数 104 是查询资金的编码,查询结果保存在Ree里\n if self.trader_Ree != None:\n self.trader_Ree.value.decode('gbk', 'ignore').split('|')\n return True\n else:\n pass\n return False\n\n #发送相应的下单命令\n #stock_code 交易股票代号\n #stock_price 交易股票价格\n #stock_amount 交易股票数量\n #trade_side 交易方向\n #holder_code 用户股东账号\n def send_order(self,stock_code,stock_price,stock_amount,trade_side,holder_code):\n if self.login_code == None:\n self.login_code = self.login()\n memset(ctypes.byref(self.trader_Ree),0x0,1024*1024)\n self.dll.JL_SendOrder(self.login_code,\n trade_side,\n bytes(self.trader_user, 'ascii'),\n bytes(holder_code,'ascii'),\n bytes(stock_code, 'ascii'),\n stock_amount,\n c_float(stock_price),\n self.trader_Ree)\n result = self.trader_Ree.value.decode('gbk','ignore')\n return result\n\n #取消下单 \n #order_code 下单编号\n #exchange_type 交易市场\n def cancel_order(self,order_code,exchange_type):\n if self.login_code == None:\n self.login_code = self.login()\n memset(ctypes.byref(self.trader_Ree),0x0,1024*1024)\n cancel = self.dll.JL_CancelOrder(self.login_code,\n bytes(self.trader_user,'ascii'),\n bytes(order_code,'ascii'),\n exchange_type, \n self.trader_Ree)\n return cancel \n \n #购买股票 \n #stock_code 股票代号 \n #stock_price 购买价格 \n #stock_amount 购买数量 \n def buy_stock(self,stock_code,stock_price,stock_amount):\n if stock_code[0] == \"3\" or stock_code[0] == \"0\":\n holder_code = self.holder_number['SZ']\n else:\n holder_code = self.holder_number['SH']\n self.send_order(stock_code, stock_price, stock_amount,Constant.SEND_BUY, holder_code)\n return self.trader_Ree.value.decode('gbk','ignore')\n \n \n #卖出股票 \n #stock_code 股票代号 \n #stock_price 购买价格 \n #stock_amount 购买数量 \n def sell_stock(self,stock_code,stock_price,stock_amount):\n if stock_code[0] == \"3\" or stock_code[0] == \"0\":\n holder_code = self.holder_number['SZ']\n else:\n holder_code = self.holder_number['SH']\n book_order = self.send_order(stock_code, stock_price, stock_amount,Constant.SEND_SELL, holder_code)\n if type(book_order).__name__ == 'int':\n return book_order\n else:\n return False\n \n #获取当前价格买卖5档\n def get_stock_price(self,stock_code):\n memset(ctypes.byref(self.trader_Ree),0x0,1024*1024)\n if self.login_code == None:\n self.login_code = self.login()\n elif self.login_code == 0:\n return False\n else:\n res = self.dll.JL_GetPrice(self.login_code,bytes(stock_code,'ascii'),self.trader_Ree)\n if res == 1:\n return True\n else:\n return False\n\n #登陆帐号\n def login(self):\n try:\n #返回相应的用户账号\n login_user_code = self.dll.JL_Login(bytes(self.trader_ip, 'ascii'),\n self.trader_port,\n bytes(self.trader_version, 'ascii'), \n bytes(self.trader_user, 'ascii'),\n bytes(self.trader_psword, 'ascii'),\n bytes(self.trader_txword, 'ascii'),\n bytes(self.trader_yyb, 'ascii'))\n return login_user_code\n except Exception as e:\n return None\n\n #注册相应用户信息 \n #dll_path 相应的注册dll路径\n #type 为加载的dll类型 \n def init_holder_number(self,sh_code='',sz_code=''):\n self.holder_number['SH'] = sh_code\n self.holder_number['SZ'] = sz_code\n \n #初始化函数 连接 相应dll\n def _init_registration(self,dll_path,type = None):\n #加载相应的dll\n if type == None:\n self.dll=windll.LoadLibrary(dll_path) #载入DLL\n\n #退出登录 \n def quit_login(self):\n if self.login_code == '':\n return True\n else:\n jl_out = self.dll.JL_Out(self.login_code)\n if jl_out != '':\n return True\n else:\n return False","sub_path":"src/Trader.py","file_name":"Trader.py","file_ext":"py","file_size_in_byte":10121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"20408115","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\n\nclass GroupJSONPresenter(object):\n \"\"\"Present a group in the JSON format returned by API requests.\"\"\"\n\n def __init__(self, group, route_url=None):\n self.group = group\n self._route_url = route_url\n\n def asdict(self):\n return self._model(self.group)\n\n def _model(self, group):\n model = {\n 'name': group.name,\n 'id': group.pubid,\n 'public': group.is_public,\n 'scoped': True if group.scopes else False,\n 'type': group.type\n }\n model = self._inject_urls(group, model)\n return model\n\n def _inject_urls(self, group, model):\n model['urls'] = {}\n if not self._route_url:\n return model\n\n model['url'] = self._route_url('group_read',\n pubid=group.pubid,\n slug=group.slug)\n model['urls']['group'] = model['url']\n return model\n\n\nclass GroupsJSONPresenter(object):\n \"\"\"Present a list of groups as JSON\"\"\"\n\n def __init__(self, groups, route_url=None):\n self.groups = groups\n self._route_url = route_url\n\n def asdicts(self):\n return [GroupJSONPresenter(group, self._route_url).asdict() for group in self.groups]\n","sub_path":"h/presenters/group_json.py","file_name":"group_json.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"242732405","text":"# coding=utf-8\n\n\ndef get_cars(system_data_dict):\n return system_data_dict.get('placemarks', [])\n\n\ndef get_car_basics(car):\n return car['vin'], car['coordinates'][1], car['coordinates'][0]\n\n\ndef get_car(car):\n result = {}\n\n vin, lat, lng = get_car_basics(car)\n\n result['vin'] = vin\n result['license_plate'] = car['name']\n\n result['model'] = 'smart fortwo'\n\n result['lat'] = lat\n result['lng'] = lng\n\n result['address'] = car['address']\n\n result['fuel'] = car['fuel']\n result['fuel_type'] = car['engineType']\n result['electric'] = (car['engineType'] == 'ED')\n result['charging'] = car.get('charging', False)\n\n result['transmission'] = 'A'\n\n result['cleanliness_interior'] = car['interior']\n result['cleanliness_exterior'] = car['exterior']\n\n return result\n\n\ndef get_range(car):\n if 'fuel' not in car:\n car = get_car(car)\n\n # Wikipedia quotes full charge range 135 km (NEDC), car2go quotes 130 km.\n # Use 130 km.\n # car2go policy is that less than 20% charge remaining requires ending\n # trip at a charging point. Use 20% as indicator for minimum charge level.\n\n if car['fuel'] > 20:\n car_range = int(1.3 * (car['fuel']-20))\n else:\n car_range = 0\n\n return car_range\n","sub_path":"electric2go/systems/car2go/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"27426281","text":"import sys\nimport os\nimport glob\nimport logging\nimport shutil\nimport click\nimport collections\nimport re\nimport pandas as pd\n\nfrom dbclients.basicclient import NotFoundError\nfrom dbclients.tantalus import TantalusApi\nfrom dbclients.colossus import ColossusApi\nfrom datamanagement.add_generic_results import add_generic_results\nfrom utils.constants import LOGGING_FORMAT\n\n\n# library_id = \"A96146A\"\n# source_dir = '/shahlab/archive/single_cell_indexing/Cellenone/Cellenone_images/20180831_A96146A'\n# source_dir = '/shahlab/archive/single_cell_indexing/Cellenone/Cellenone_images/20171019_A95664B'\n# destination_dir = '/shahlab/amcpherson/temp123'\n\n\ndef clean_filename(filename):\n prefix = '=HYPERLINK(\"'\n suffix = '\")'\n\n if not filename.startswith(prefix) or not filename.endswith(suffix):\n raise ValueError(f'unknown format for filename {filename}')\n\n filename = filename[len(prefix):-len(suffix)]\n\n return filename\n\n\ndef generate_new_filename(row):\n library_id = row['library_id']\n chip_row = row['chip_row']\n chip_column = row['chip_column']\n\n new_filename = f'{library_id}_R{chip_row:02d}_C{chip_column:02d}.png'\n\n return new_filename\n\n\ndef read_cellenone_isolated_files(source_dir):\n \"\"\"Read the isolated.xls files in a cellenone directory.\n \n Args:\n source_dir (str): Path to the cellenone output\n \"\"\"\n logging.info(f'processing directory {source_dir}')\n\n isolated_filenames = glob.glob(os.path.join(source_dir, '*', '*isolated.xls'))\n\n catalog = []\n\n for isolated_filename in isolated_filenames:\n logging.info(f'processing {isolated_filename}')\n\n data = pd.read_csv(isolated_filename, sep='\\t')\n\n data = data.dropna(subset=['XPos', 'YPos', 'X', 'Y'])\n\n if data.empty:\n logging.info(f'no useful data in {isolated_filename}')\n continue\n\n # Clean spaces from column names\n data.columns = [a.strip() for a in data.columns]\n\n # Images subdirectory for the run given by this isolated.xls\n images_dir = os.path.basename(os.path.dirname(isolated_filename))\n\n # Clean hyperlink tag from original filename\n data['original_filename'] = data['ImageFile'].apply(clean_filename)\n\n # Original filename relative to root cellenone directory\n data['original_filename'] = [os.path.join(images_dir, a) for a in data['original_filename']]\n\n # Chip row and column as YPos and XPos\n data['chip_row'] = data['YPos']\n data['chip_column'] = data['XPos']\n\n catalog.append(data)\n\n if len(catalog) == 0:\n return pd.DataFrame()\n\n catalog = pd.concat(catalog, ignore_index=True)\n\n logging.info(f'found {len(catalog.index)} entries for {source_dir}')\n\n return catalog\n\n\ndef catalog_images(library_id, source_dir, destination_dir):\n \"\"\" Catalog cellenone images and organize into a new directory\n \n Args:\n library_id (str): DLP Library ID\n source_dir (str): Source Cellenone directory\n destination_dir (str): Destination catalogued images directory\n \"\"\"\n\n catalog = read_cellenone_isolated_files(source_dir)\n\n if catalog.empty:\n raise ValueError(f'empty catalog, cellenone data incompatible')\n\n # Add library id to catalog, required for pretty filename\n catalog['library_id'] = library_id\n\n # Generate a pretty filename\n catalog['filename'] = catalog.apply(generate_new_filename, axis=1)\n\n # Report duplicate chip wells\n cols = ['chip_row', 'chip_column']\n dup = catalog[cols].duplicated()\n if dup.any():\n dup_values = list(catalog.loc[dup, cols].values)\n logging.error(f'column {cols} has duplicates {dup_values}')\n logging.error(f'removing {len(dup_values)} duplicate wells')\n\n # Remove duplicate chip wells\n catalog = catalog[~catalog[['chip_row', 'chip_column']].duplicated(keep=False)]\n\n # Fail on any other duplicate columns\n assert not catalog[['original_filename']].duplicated().any()\n assert not catalog[['filename']].duplicated().any()\n\n # List of filepaths of newly created files\n filepaths = []\n\n # Move the image files into the source directory\n for idx in catalog.index:\n new_filename = catalog.loc[idx, 'filename']\n new_filepath = os.path.join(destination_dir, new_filename)\n\n original_filename = catalog.loc[idx, 'original_filename']\n original_filepath = os.path.join(source_dir, original_filename)\n\n shutil.copyfile(original_filepath, new_filepath)\n\n filepaths.append(new_filepath)\n\n # Save the catalog\n catalog_filepath = os.path.join(destination_dir, 'catalog.csv')\n catalog.to_csv(catalog_filepath, index=False)\n\n filepaths.append(catalog_filepath)\n\n return filepaths\n\n\ndef process_cellenone_images(\n library_id,\n source_dir,\n storage_name,\n tag_name=None,\n update=False,\n remote_storage_name=None,\n ):\n\n tantalus_api = TantalusApi()\n\n results_name = 'CELLENONE_IMAGES_{}'.format(library_id)\n results_type = 'CELLENONE_IMAGES'\n results_version = 'v1'\n\n try:\n existing_results = tantalus_api.get('results', name=results_name)\n except NotFoundError:\n existing_results = None\n\n if existing_results is not None and not update:\n logging.info(f'results for {library_id} exist, not processing')\n return\n\n storage = tantalus_api.get('storage', name=storage_name)\n storage_directory = storage['storage_directory']\n\n destination_dir = os.path.join(\n storage_directory,\n 'single_cell_indexing',\n 'Cellenone',\n 'Cellenone_processed',\n library_id,\n results_version,\n )\n\n try:\n os.makedirs(destination_dir)\n except:\n pass\n\n filepaths = catalog_images(library_id, source_dir, destination_dir)\n\n results_dataset = add_generic_results(\n filepaths=filepaths,\n storage_name=storage_name,\n results_name=results_name,\n results_type=results_type,\n results_version=results_version,\n library_ids=[library_id],\n recursive=False,\n tag_name=tag_name,\n update=update,\n remote_storage_name=remote_storage_name,\n )\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.argument('filepaths', nargs=-1)\n@click.option('--storage_name')\n@click.option('--tag_name')\n@click.option('--update', is_flag=True)\n@click.option('--remote_storage_name')\ndef glob_cellenone_data(filepaths, storage_name, tag_name=None, update=False, remote_storage_name=None):\n\n tantalus_api = TantalusApi()\n\n for filepath in filepaths:\n match = re.match(r\".*/single_cell_indexing/Cellenone/Cellenone_images/(\\d+)_(A\\d+[A-Z]*)\", filepath)\n if match is None:\n logging.warning('skipping malformed {}'.format(filepath))\n continue\n\n fields = match.groups()\n date = fields[0]\n library_id = fields[1]\n\n try:\n tantalus_api.get('dna_library', library_id=library_id)\n except NotFoundError:\n logging.warning('skipping file with unknown library {}'.format(filepath))\n continue\n\n try:\n process_cellenone_images(\n library_id,\n filepath,\n storage_name,\n tag_name=tag_name,\n update=update,\n remote_storage_name=remote_storage_name,\n )\n except ValueError:\n logging.exception(f'unable to process {library_id}, {filepath}')\n\n\n@cli.command()\n@click.argument('library_id')\n@click.argument('cellenone_filepath')\n@click.argument('storage_name')\n@click.option('--tag_name')\n@click.option('--update', is_flag=True)\n@click.option('--remote_storage_name')\ndef add_cellenone_data(\n library_id,\n cellenone_filepath,\n storage_name,\n tag_name=None,\n update=False,\n remote_storage_name=None):\n\n tantalus_api = TantalusApi()\n\n process_cellenone_images(\n library_id,\n cellenone_filepath,\n storage_name,\n tag_name=tag_name,\n update=update,\n remote_storage_name=remote_storage_name,\n )\n\n\nif __name__=='__main__':\n logging.basicConfig(format=LOGGING_FORMAT, stream=sys.stderr, level=logging.INFO)\n cli()\n\n","sub_path":"datamanagement/catalog_cellenone_images.py","file_name":"catalog_cellenone_images.py","file_ext":"py","file_size_in_byte":8294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"257036413","text":"#!/usr/bin/python\n\nimport numpy as np\nimport pyhs2\n\nclass HiveClient:\n def __init__(self, db_host, user, password, database, port=10000, authMechanism='PLAIN'):\n \"\"\"\n create connection to hive server2\n \"\"\"\n self.conn = pyhs2.connect(host=db_host, port=port, authMechanism=authMechanism, user=user, password=password, database=database)\n\n def query(self, sql):\n \"\"\"\n query\n \"\"\"\n with self.conn.cursor() as cursor:\n cursor.execute(sql)\n return cursor.fetch()\n\n def close(self):\n \"\"\"\n close connection\n \"\"\"\n self.conn.close()\n\n\ndef readUid():\n fn = open('/home/ubuntu/wade/uid_target_new.txt', 'r')\n textList = []\n\n for line in fn.readlines():\n line = line.strip().split('\\t')\n textList.append(line)\n\n useridList = [a[0] for a in textList]\n\n return useridList\n\n\ndef part_screen_name(result):\n \n screen_nameList = ['order_confirm', 'personal_settings', 'invite_contact', 'myorders', 'bill_repay_detail', 'personal', 'live_chat', 'my_prize', 'register_step1', 'personal_address_edit', 'item_detail', 'service_question', 'home_credit_pending', 'lucky_draw', 'share_friends', 'customer_service', 'personal_profile', 'activity', 'bills', 'repay_method', 'choose_address', 'personal_refer_code', 'bill_repay_details', 'personal_pwd_manage', 'install_apply', 'personal_address', 'referral_code', 'personal_history', 'payment_confirm', 'more_chances_draw', 'home_credit_reject', 'orderdetail', 'akulaku', 'Login', 'personal_coupons', 'bill_details', 'category_leaf', 'register', 'category_search', 'mybills', 'login', 'complete_page']\n\n partResult = []\n for res in result:\n if res[1] in screen_nameList:\n partResult.append(res)\n \n return partResult\n\ndef first_isenter(sna_list):\n\n segment_list = []\n while(len(sna_list) > 0):\n if 'leave' in sna_list:\n \n leave_index = sna_list.index('leave')\n tmp = sna_list[0:(leave_index+1)]\n \n #print(tmp)\n \n \n ##deal with 'enter' too much\n while(tmp.count('enter') >= tmp.count('leave')+2):\n \n enter_idx = sna_list.index('enter')\n #print(enter_idx)\n enter_next_idx = sna_list.index('enter', enter_idx+1)\n #print(enter_next_idx)\n sna_list = sna_list[enter_next_idx:]\n\n leave_index = sna_list.index('leave') #leave_index changed\n\n tmp = sna_list[0:(leave_index+1)] ##leave_index changed\n #print(tmp.count('enter'))\n #print(tmp.count('leave'))\n #print(tmp)\n \n\n while(tmp.count('enter') > tmp.count('leave')):\n if 'leave' in sna_list[(leave_index+1):]:\n new_leave_index = sna_list.index('leave', leave_index+1)\n tmp = sna_list[0:(new_leave_index+1)] \n \n ###if have 2 'enter' between 'leave', we seq\n if sna_list[leave_index:new_leave_index].count('enter') >= 2:\n leave_index = sna_list.index('enter', leave_index) #find first 'enter' after 'leave'\n break\n\n leave_index = new_leave_index\n\n else:\n #sna_list = sna_list[(leave_index+1):]\n break \n \n segment_list.append(sna_list[0:(leave_index+1)])\n sna_list = sna_list[(leave_index+1):]\n \"\"\"\n while(tmp.count('enter') > tmp.count('leave')):\n if 'leave' in sna_list[(leave_index+1):]:\n leave_index = sna_list.index('leave', leave_index+1)\n tmp = sna_list[0:(leave_index+1)] \n\n else:\n #sna_list = sna_list[(leave_index+1):]\n break\n \n segment_list.append(sna_list[0:(leave_index+1)])\n \n sna_list = sna_list[(leave_index+1):]\n \"\"\" \n else:\n break\n \n #return segment_list\n\ndef test(sna_list):\n\n #print(len(sna_list))\n #print(len(sna_list[0]))\n\n seq_list = []\n #enter_nums = 0; leave_nums = 0\n #enter_seq_nums = 0\n enter_index_list = []; leave_index_list = []\n #first = 0; end = 0\n\n for i in range(len(sna_list)):\n if sna_list[i][2] == 'enter':\n\n #print(len(sna_list[i]))\n #print(enter_index_list[0])i\n\n if len(enter_index_list) == 0:\n enter_index_list.append(i)\n continue\n\n if sna_list[i][4] - sna_list[enter_index_list[0]][4] >= 1200000 and len(leave_index_list) > 0:\n \"\"\"\n print(\"is more 0\")\n print(enter_index_list[0])\n print(leave_index_list[-1])\n \"\"\"\n\n seq_list.append(sna_list[enter_index_list[0]:(leave_index_list[-1]+1)])\n enter_index_list = []\n enter_index_list.append(i)\n leave_index_list = []\n \n if sna_list[i][4] - sna_list[enter_index_list[0]][4] >= 1200000 and len(leave_index_list) == 0:\n \"\"\"\n print('is 0')\n print(enter_index_list[0])\n print(enter_index_list[-1])\n #if i == enter_index_list[0]\n \"\"\"\n\n seq_list.append(sna_list[enter_index_list[0]:(enter_index_list[-1]+1)])\n enter_index_list = []\n enter_index_list.append(i)\n leave_index_list = []\n\n if sna_list[i][4] - sna_list[enter_index_list[0]][4] < 1200000:\n enter_index_list.append(i)\n \"\"\"\n elif len(leave_index_list) == 0:\n \n print(enter_index_list[0])\n print(enter_index_list[-1]+1)\n\n seq_list.append(sna_list[enter_index_list[0]:(enter_index_list[-1]+1)])\n enter_index_list = []\n enter_index_list.append(i)\n leave_index_list = []\n \n else:\n enter_index_list.append(i)\n \"\"\"\n \n elif sna_list[i][2] == 'leave':\n #leave_nums += 1\n leave_index_list.append(i)\n \n else:\n continue\n \n \"\"\"\n if i == (len(sna_list)-1):\n seq_list.append(sna_list[enter_index_list])\n \"\"\"\n\n #if time too long:\n\n if len(enter_index_list) <= len(leave_index_list) and len(enter_index_list) != 0:\n \"\"\"\n print(\"!=0\")\n print(enter_index_list[0])\n print(leave_index_list[-1])\n \"\"\"\n if enter_index_list[0] == (leave_index_list[-1]+1):\n enter_index_list = []\n leave_index_list = []\n continue\n\n seq_list.append(sna_list[enter_index_list[0]:(leave_index_list[-1]+1)])\n enter_index_list = []\n leave_index_list = [] \n \n if i == (len(sna_list)-1) and len(enter_index_list) != 0:\n seq_list.append(sna_list[enter_index_list[0]:(i+1)])\n \n \"\"\"\n output = open('t_27.txt', 'w+')\n for seq in seq_list:\n for se in seq:\n output.write(se[2] + ',')\n output.write('\\n')\n output.close()\n \"\"\"\n\n return seq_list\n\ndef statist(seq_list):\n \n #output = open('r_27.txt', 'w+')\n\n count = len(seq_list)\n sum_page = 0; sum_seq_time = 0; sum_stop_time = 0\n oldtime = 0\n\n for seq in seq_list:\n \n if len(seq) == 0:\n #print(\"continue\")\n continue\n\n #print(len(seq))\n #print(len(seq[0]))\n #print(len(seq[-1]))\n\n sum_stop_time += (seq[-1][4]-seq[0][4])\n #print(sum_stop_time)\n if oldtime == 0:\n oldtime = seq[-1][4]\n else:\n sum_seq_time += (seq[0][4]-oldtime)\n oldtime = seq[-1][4]\n #count = len(seq)\n #sum_page = 0; sum_seq_time = 0; sum_stop_time = 0\n for se in seq:\n if se[2] == 'enter':\n sum_page += 1\n #sum_stop_time += se\n\n return count, sum_page, sum_stop_time, sum_seq_time\n\ndef main():\n\n #output = open('/home/ubuntu/data/wade/test1.txt', 'w+')\n output = open('r_27.txt', 'w+')\n \"\"\"main function\"\"\"\n\n hive_client = HiveClient(db_host='172.31.26.221', user='root', password='', database='default', port=10001)\n\n useridList = readUid()\n #contentList = extractFeature()\n \n for uid in useridList:\n #print(uid)\n result = hive_client.query(\"select * from wade_201702 where uid = %d order by md_time\" % long(uid))\n #result = hive_client.query(\"select * from wade_201611_target_screen_name where uid = %d\" % 101108) \n \n if len(result) == 0:\n continue \n\n \"\"\"\n prt = part_screen_name(result)\n \n if len(prt) == 0:\n continue\n\n sna_list = [] #add all screen_action to list\n\n for pt in prt:\n sna_list.append(pt[2])\n #dict_sna_mt[pt[2]] = pt[4]\n \n for u in sg_list:\n for i in u:\n output.write(i + ' ' + ',')\n output.write('\\n')#lastcolumn is label \n \"\"\"\n\n sg_list = test(result)\n #print(\"test\")\n count, sum_page, sum_stop_time, sum_seq_time = statist(sg_list)\n #print(\"statist\")\n if count == 0:\n continue\n output.write(str(uid)+'\\t')\n output.write(str(count)+'\\t')\n output.write(str(sum_page/float(count))+'\\t')\n output.write(str(sum_stop_time/float(count))+'\\t')\n output.write(str(sum_seq_time/float(count))+'\\n')\n output.close()\n \"\"\"\n #result = hive_client.query(\"select * from wade_alt_part where uid = 189786 and part_month = 'r_action_log_201702' order by md_time\")\n result = hive_client.query(\"select * from wade_201702 where uid = 189786 order by md_time\")\n #result = hive_client.query(\"select * from wade_201611_target_screen_name where uid = %d\" % 101108) \n \n slist = test(result)\n statist(slist)\n \"\"\"\n #prt = part_screen_name(result)\n \n ##sds.modify 3_27\n hive_client.close()\n\nif __name__ =='__main__':\n main()\n\n","sub_path":"processData.py","file_name":"processData.py","file_ext":"py","file_size_in_byte":10405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"606060274","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\n\nimport roslib\n\nroslib.load_manifest('team503')\nimport sys\n# import tensorflow\nimport rospy\nimport cv2\nimport numpy as np\nimport message_filters\nfrom std_msgs.msg import Float32\nfrom sensor_msgs.msg import CompressedImage\nimport csv\nimport time\n\n# from utils import preprocess\n# from tensorflow.keras import load_model\nfrom model import build_model, get_seg\n\nfrom DepthProcessing import get_sign\n\npub_steer = rospy.Publisher('team1/set_angle', Float32, queue_size=10)\npub_speed = rospy.Publisher('team1/set_speed', Float32, queue_size=10)\n\n# pub_steer = rospy.Publisher('Team1_steerAngle', Float32, queue_size=10)\n# pub_speed = rospy.Publisher('Team1_speed', Float32, queue_size=10)\n\nrospy.init_node('control', anonymous=True)\nmsg_speed = Float32()\nmsg_speed.data = 50\nmsg_steer = Float32()\nmsg_steer.data = 0\n\ndepth_np = 0\ndepth_hist = 0\n\nfrom tf_bisenet.BiSeNet_Loader import BiseNet_Loader\nfrom SegProcessing import get_steer, binary_sign\n\nmodel = BiseNet_Loader()\n\n# init_classifier()\nmsg_speed = Float32()\nmsg_speed.data = 20\nmsg_steer = Float32()\nmsg_steer.data = 0\n\nsmooth = cv2.imread(\"/home/sonduong/catkin_ws/src/beginner_tutorials/scripts/hi.png\", 0)\n\n\n# sign_rect = []\ndef bias_callback(depth_data):\n # global angle_bias\n # global depth_np\n # global depth_hist\n # global sign_rect\n depth_arr = np.fromstring(depth_data.data, np.uint8)\n depth_np = cv2.imdecode(depth_arr, cv2.IMREAD_GRAYSCALE)\n sign_rect = get_sign(depth_np)\n # depth_np = cv2.absdiff(depth_np, smooth)\n # depth_hist = get_collums_hist(depth_np[120: 220, :])\n # angle_bias = (get_weights(depth_np[120: 220, :]))\n\n # cv2.waitKey(1)\n\n\nstart_time = time.time()\n\n\ndef drive_callback(rgb_data):\n global start_time\n global model\n\n if (time.time() - start_time > 0.01):\n np_arr = np.fromstring(rgb_data.data, np.uint8)\n # print(np_arr.shape)\n image_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)\n # cv2.imshow('cv_img', image_np)\n pr_mask = model.predict(image_np)\n # cv2.imshow('pr_mask', pr_mask)\n speed, angle = get_steer(-1, pr_mask)\n msg_steer.data = float(angle)\n msg_speed.data = float(speed)\n pub_steer.publish(msg_steer)\n pub_speed.publish(msg_speed)\n cv2.waitKey(1)\n # print(time.time() - start_time)\n start_time = time.time()\n\n\nclass sync_listener:\n def __init__(self):\n self.depth_sub = message_filters.Subscriber('team503/camera/depth/compressed', CompressedImage)\n self.image_sub = message_filters.Subscriber('team503/camera/rgb/compressed', CompressedImage)\n self.ts = message_filters.ApproximateTimeSynchronizer([self.image_sub, self.depth_sub], queue_size=4,\n slop=1) # Changed code\n self.ts.registerCallback(self.callback)\n\n def callback(self, image, depth):\n global start_time\n global model\n\n if (time.time() - start_time > 0.04):\n print(\"start processing ... \")\n\n # print(\"start processing rgb data... \")\n np_arr = np.fromstring(image.data, np.uint8)\n image_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)\n # print(\"start showing image ... \")\n # cv2.imshow('view', image_np)\n\n pr_mask = model.predict(image_np)\n speed, angle = get_steer(-1, pr_mask)\n msg_steer.data = float(angle)\n msg_speed.data = float(speed)\n pub_steer.publish(msg_steer)\n pub_speed.publish(msg_speed)\n # cv2.waitKey(1)\n # print(time.time() - start_time)\n start_time = time.time()\n\n\ndef listener():\n # rospy.Subscriber('team1/camera/depth/compressed', CompressedImage, bias_callback)\n rospy.Subscriber('team503/camera/rgb/compressed', CompressedImage, drive_callback, buff_size=2 ** 24)\n # rospy.Subscriber('Team1_image/compressed', CompressedImage, drive_callback, buff_size=2**24)\n # ls = sync_listener()\n # depth_sub = message_filters.Subscriber('team1/camera/depth/compressed', CompressedImage)\n # image_sub = message_filters.Subscriber('team1/camera/rgb/compressed', CompressedImage)\n\n # ts = message_filters.TimeSynchronizer([image_sub, depth_sub], 10)\n # ts.registerCallback(callback)\n\n # spin() simply keeps python from exiting until this node is stopped\n\n rospy.spin()\n\n\nif __name__ == '__main__':\n listener()\n","sub_path":"src/team503/scripts/Thu.py","file_name":"Thu.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"9547639","text":"from botocore.errorfactory import ClientError\nfrom typing import Optional, List, Union, Tuple\nimport s3fs\nfrom returns.result import Result, Success, Failure\nfrom s3fs import S3FileSystem\n\nfrom mason.clients.aws_client import AWSClient\nfrom mason.clients.response import Response\nfrom mason.engines.storage.models.path import Path, construct\nfrom mason.util.exception import message\nfrom mason.util.list import get\n\nclass S3Client(AWSClient):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n def client(self) -> S3FileSystem:\n s3 = s3fs.S3FileSystem(key=self.access_key, secret=self.secret_key, client_kwargs={'region_name': self.aws_region})\n return s3\n\n def parse_responses(self, s3_response: dict):\n error = s3_response.get('Error', {}).get('Code', '')\n status = s3_response.get('ResponseMetadata', {}).get('HTTPStatusCode')\n message = s3_response.get('Error', {}).get('Message')\n return error, status, message\n\n\n def parse_table_list_data(self, s3_response: dict):\n single_items = list(map(lambda x: self.parse_item(x), s3_response.get('Contents', [])))\n prefixes = list(map(lambda x: self.parse_prefixes(x), s3_response.get('CommonPrefixes', [])))\n return {\n \"items\": single_items,\n \"prefixes\": prefixes\n }\n\n def parse_prefixes(self, s3_response: dict):\n return s3_response.get(\"Prefix\")\n\n def parse_item(self, s3_response: dict):\n table_parsed = {\n \"name\": s3_response.get(\"Key\"),\n \"updated_at\": s3_response.get(\"LastModified\"),\n \"size\": s3_response.get(\"Size\")\n }\n return table_parsed\n\n def parse_items(self, s3_response: dict):\n return list(map(lambda x: self.parse_item(x), s3_response.get('Contents', [])))\n\n def list_objects(self, database_name: str, response: Response) -> Tuple[Result[dict, str], Response]:\n try:\n split = database_name.split(\"/\", 1)\n result = self.client().s3.list_objects(Bucket=split[0], Prefix=(get(split, 1) or '/'), Delimiter='/')\n response.add_response(result)\n return Success(result), response\n except Exception as e:\n if isinstance(e, ClientError):\n result = e.response\n error = result.get(\"Error\", {})\n code = error.get(\"Code\", \"\")\n if code == \"NoSuchBucket\":\n response.set_status(404)\n return Failure(f\"The specified bucket does not exist: {database_name}\"), response\n return Failure(message(e)), response\n \n def expand_path(self, path: Path, response: Response = Response(), sample_size: int = 3) -> Tuple[List[Path], Response]:\n paths: List[Path] = []\n full_path = path.full_path()\n response.add_info(f\"Fetching keys at {full_path}\")\n keys = self.client().find(full_path)\n response.add_response({'keys': keys})\n\n if len(keys) > 0:\n paths = list(map(lambda k: Path(k, \"s3\"), keys))\n\n if sample_size:\n import random\n try:\n ss = int(sample_size)\n except TypeError:\n response.add_warning(f\"Invalid sample size (int): {sample_size}\")\n ss = 3\n\n response.add_warning(f\"Sampling keys to determine schema. Sample size: {ss}.\")\n if ss < len(paths):\n paths = random.sample(paths, ss)\n\n return paths, response\n \n def table_path(self, database_name: str, table_name: str) -> Path:\n return construct([database_name, table_name], \"s3\")\n\n def save_to(self, inpath: Path, outpath: Path, response: Response):\n try:\n self.client().upload(inpath.path_str, outpath.path_str)\n except Exception as e:\n response.add_error(f\"Error saving {inpath} to {outpath.path_str}\")\n response.add_error(message(e))\n \n return response\n \n \n","sub_path":"mason/clients/s3/s3_client.py","file_name":"s3_client.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"378733789","text":"import random\nimport re\nfrom datetime import datetime\n\nimport icalendar\nimport pytz\nimport requests\nfrom bs4 import BeautifulSoup\nfrom icalendar import Event\nfrom icalendar import vCalAddress, vText\n\nfrom DateReceiver import DateReceiver\n\n\nclass RaplaExtractor:\n def __init__(self, key, year):\n self.key = key\n self.year = year\n self.url = \"https://rapla.dhbw-stuttgart.de/rapla?\"\n self.lectures = []\n self.dates = []\n self.compute()\n\n def compute(self):\n dr = DateReceiver(int(self.year))\n days = dr.getAllMondays()\n\n cal = icalendar.cal.Calendar()\n cal.add('prodid', self.url + 'key=' + self.key)\n cal.add('version', '2.0')\n\n for day in days:\n try:\n t_url = self.compose_url(self.url, self.key, str(day[0]), str(day[1]), self.year)\n print(t_url)\n self.get_html_from_url(t_url, cal)\n except KeyError:\n print(t_url + ' failed.')\n\n f = open('data/example.ics', 'wb')\n f.write(cal.to_ical())\n f.close()\n\n def create_events(self, cal, room, person, lecture_name, time_start, time_end, day):\n try:\n event = Event()\n event.add('summary', lecture_name[0].contents[0])\n event.add('dtstart', datetime(2019, int(day[0][1]), int(day[0][0]), int(time_start[1]), int(time_start[2]), 0, tzinfo=pytz.timezone('Europe/Berlin')))\n event.add('dtend', datetime(2019, int(day[0][1]), int(day[0][0]), int(time_end[1]), int(time_end[2]), 0, tzinfo=pytz.timezone('Europe/Berlin')))\n event.add('dtstamp', datetime.now())\n\n organizer = vCalAddress('MAILTO:platzhalter@lehre.dhbw-stuttgart.de')\n\n organizer.params['cn'] = vText(lecture_name[-1].contents[0])\n organizer.params['role'] = vText('CHAIR')\n event['organizer'] = organizer\n event['location'] = vText(lecture_name[-2].contents[0])\n\n event['uid'] = random.random() * 1000000000000000\n event.add('priority', 5)\n\n cal.add_component(event)\n except TypeError:\n return False\n\n def get_html_from_url(self, t_url, cal):\n \"\"\"\n\n :param t_url: str\n \"\"\"\n result = requests.get(url=t_url)\n f = open('data/rapla.html', 'wb')\n f.write(result.content)\n f.close()\n soup = BeautifulSoup(result.content, features='html.parser')\n\n samples = soup.find_all(attrs={'class': 'week_block'})\n date = soup.find_all(attrs={'class': 'week_header'})\n dates = {}\n # Creates list with assigned days FORMAT: MO -> {01,01}\n for x in date:\n if 'Mo' in x.text:\n dates['Mo'] = re.findall('(\\d\\d).(\\d\\d)', x.text)\n if 'Di' in x.text:\n dates['Di'] = re.findall('(\\d\\d).(\\d\\d)', x.text)\n if 'Mi' in x.text:\n dates['Mi'] = re.findall('(\\d\\d).(\\d\\d)', x.text)\n if 'Do' in x.text:\n dates['Do'] = re.findall('(\\d\\d).(\\d\\d)', x.text)\n if 'Fr' in x.text:\n dates['Fr'] = re.findall('(\\d\\d).(\\d\\d)', x.text)\n\n for lec in samples:\n room = lec.find_all('span', attrs={'class': 'resource'})\n person = lec.find('span', attrs={'class': 'person'})\n lecture_name = lec.find_all('td', attrs={'class': 'value'})\n day = lec.find_all('div')\n day_exact = re.findall(\"\\w\\w \", day[-1].contents[0])\n dayA = dates[day_exact[0].strip()]\n time = re.findall(\"((\\d{2}):(\\d{2}))\", lec.contents[0].text)\n time_start = time[0]\n time_end = time[1]\n try:\n self.create_events(cal, room, person, lecture_name, time_start, time_end, dayA)\n except TypeError:\n return False\n\n def compose_url(self, t_url, t_key, t_day, t_month, t_year):\n \"\"\"\n Composes the url\n :param t_url: str\n :param t_key: str\n :param t_day: str\n :param t_month: str\n :param t_year: str\n :return:\n \"\"\"\n return t_url + \"key=\" + t_key + \"&day=\" + t_day + \"&month=\" + t_month + \"&year=\" + t_year","sub_path":"RaplaExtractor.py","file_name":"RaplaExtractor.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"166847591","text":"# -*- coding: UTF-8 -*-\n\nimport re\nimport base64\n\nfrom six import ensure_text\nfrom six.moves.urllib_parse import parse_qs, urlparse, urlencode\n\nfrom resources.lib.modules import client\nfrom resources.lib.modules import cleantitle\nfrom resources.lib.modules import log_utils\nfrom resources.lib.modules import source_utils\n\n\nclass source:\n def __init__(self):\n self.results = []\n self.domains = ['123movies.net']\n self.base_link = 'https://123movies.net'\n self.search_link = '/search-movies/%s.html'\n\n\n def movie(self, imdb, title, localtitle, aliases, year):\n try:\n url = {'title': title, 'year': year}\n url = urlencode(url)\n return url\n except:\n #log_utils.log('movie', 1)\n return\n\n\n def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):\n try:\n url = {'tvshowtitle': tvshowtitle, 'year': year}\n url = urlencode(url)\n return url\n except:\n #log_utils.log('tvshow', 1)\n return\n\n\n def episode(self, url, imdb, tvdb, title, premiered, season, episode):\n try:\n if url is None:\n return\n url = parse_qs(url)\n url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])\n url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode\n url = urlencode(url)\n return url\n except:\n #log_utils.log('episode', 1)\n return\n\n\n def sources(self, url, hostDict):\n try:\n if url is None:\n return self.results\n data = parse_qs(url)\n data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])\n title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']\n title = cleantitle.geturl(title)\n year = data['premiered'].split('-')[0] if 'tvshowtitle' in data else data['year']\n query = '%s-season-%s' % (title, data['season']) if 'tvshowtitle' in data else title\n url = self.base_link + self.search_link % (query.replace('-', '+'))\n html = client.scrapePage(url).text\n results = client.parseDOM(html, 'div', attrs={'class': 'ml-item'})\n results = [(client.parseDOM(i, 'a', ret='href'), re.findall('(.+?)', i), re.findall('Release:\\s*(\\d+)', i)) for i in results]\n results = [(i[0][0], i[1][0], i[2][0]) for i in results if len(i[0]) > 0 and len(i[1]) > 0 and len(i[2]) > 0]\n url = [i[0] for i in results if query == cleantitle.geturl(i[1]) and year == i[2]][0]\n if 'tvshowtitle' in data:\n sepi = 'season-%1d/episode-%1d.html' % (int(data['season']), int(data['episode']))\n data = client.scrapePage(url).text\n link = client.parseDOM(data, 'a', ret='href')\n url = [i for i in link if sepi in i][0]\n r = client.scrapePage(url).text\n try:\n v = re.findall(r'document.write\\(Base64.decode\\(\"(.+?)\"\\)', r)[0]\n b64 = base64.b64decode(v)\n b64 = ensure_text(b64, errors='ignore')\n link = client.parseDOM(b64, 'iframe', ret='src')[0]\n link = link.replace('\\/', '/')\n host = re.findall('([\\w]+[.][\\w]+)$', urlparse(link.strip().lower()).netloc)[0]\n host = client.replaceHTMLCodes(host)\n valid, host = source_utils.is_host_valid(host, hostDict)\n if valid:\n self.results.append({'source': host, 'quality': 'SD', 'url': link, 'direct': False})\n except:\n #log_utils.log('sources', 1)\n pass\n try:\n r = client.parseDOM(r, 'div', {'class': 'server_line'})\n r = [(client.parseDOM(i, 'a', ret='href')[0], client.parseDOM(i, 'p', attrs={'class': 'server_servername'})[0]) for i in r]\n if r:\n for i in r:\n host = re.sub('Server|Link\\s*\\d+', '', i[1]).lower()\n host = client.replaceHTMLCodes(host)\n if 'other' in host:\n continue\n if host in str(self.results):\n continue\n link = i[0].replace('\\/', '/')\n valid, host = source_utils.is_host_valid(host, hostDict)\n if valid:\n self.results.append({'source': host, 'quality': 'SD', 'url': link, 'direct': False})\n except:\n #log_utils.log('sources', 1)\n pass\n return self.results\n except:\n #log_utils.log('sources', 1)\n return self.results\n\n\n def resolve(self, url):\n if any(x in url for x in self.domains):\n try:\n r = client.scrapePage(url).text\n try:\n v = re.findall(r'document.write\\(Base64.decode\\(\"(.+?)\"\\)', r)[0]\n b64 = base64.b64decode(v)\n b64 = ensure_text(b64, errors='ignore')\n try:\n url = client.parseDOM(b64, 'iframe', ret='src')[0]\n except:\n url = client.parseDOM(b64, 'a', ret='href')[0]\n url = url.replace('///', '//')\n except:\n u = client.parseDOM(r, 'div', attrs={'class': 'player'})\n url = client.parseDOM(u, 'a', ret='href')[0]\n except:\n #log_utils.log('resolve', 1)\n pass\n return url\n else:\n return url\n\n\n","sub_path":"HAX/18.CocoJoe/plugin.video.scrubsv2/resources/lib/sources/working/123moviesnet.py","file_name":"123moviesnet.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"455166513","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\nclass SinglyLinkedListNode:\n def __init__(self, node_data):\n self.data = node_data\n self.next = None\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert_node(self, node_data):\n node = SinglyLinkedListNode(node_data)\n\n if not self.head:\n self.head = node\n else:\n self.tail.next = node\n\n\n self.tail = node\n\ndef print_singly_linked_list(node, sep, print):\n while node:\n print(str(node.data))\n\n node = node.next\n\n if node:\n print(sep)\n\n\n\n\n\n\ndef mergeLists(head1, head2):\n current1=head1\n current2=head2\n newList=SinglyLinkedList()\n while current1 or current2:\n if not current1:\n newList.insert_node(current2.data)\n current2=current2.next\n continue\n if not current2:\n newList.insert_node(current1.data)\n current1=current1.next\n continue\n\n if current1.dataVisit the charts blueprint.'\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5002)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"526538695","text":"alphabet = list(\"abcdefghijklmnopqrstuvwxyz \")\n\npermutation = list(input().strip() + \" \")\nencr = list(input().strip())\n\ndecr = []\nfor i in range(len(encr)):\n c = encr[i]\n decr.append(permutation[alphabet.index(c)])\n\nprint(\"\".join(decr))\n","sub_path":"2016-anzac1/D_pen_pals.py","file_name":"D_pen_pals.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"557400579","text":"from imblearn.over_sampling import SMOTE\nfrom scipy.stats import chi2\nfrom sklearn.metrics import roc_auc_score, recall_score, precision_score, confusion_matrix\nimport os\nfrom scipy.stats import iqr, zscore\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import IsolationForest, AdaBoostClassifier\nfrom imblearn.pipeline import Pipeline\nfrom sklearn.svm import OneClassSVM\n\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score, GridSearchCV, cross_val_predict\nfrom sklearn.svm import SVC\nfrom catboost import CatBoostClassifier\nfrom retraining_after_lableing.params import param_grid_p3b as param_grid\nfrom sklearn.preprocessing import OneHotEncoder, PowerTransformer\nfrom xgboost import XGBClassifier\nfrom sklearn.feature_selection import RFE, SelectFromModel\nfrom sklearn.decomposition import PCA\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.preprocessing import StandardScaler\n\nrandom_state = 41\n\nerp_name = 'both'\ntargets = ['miscatch_P3a_novel', 'miscatch_P3b_target']\ninput_path = r\"S:\\Data_Science\\Core\\FDA_submission_10_2019\\08-Reports\\STAR_reports\\Labeling_project\\kaggle_miscatches\\both\"\n\n\ndef reference_get_agebins(x):\n reference_ages = []\n if (x.gender == 'Female') & (x.ageV1 <= 16):\n reference_ages.append(\"aob_12-16F\")\n\n if (x.gender == 'Male') & (x.ageV1 <= 16):\n reference_ages.append(\"aob_12-16M\")\n\n if (x.gender == 'Female') & (x.ageV1 > 14) & (x.ageV1 <= 19):\n reference_ages.append(\"aob_14-19F\")\n\n if (x.gender == 'Male') & (x.ageV1 > 14) & (x.ageV1 <= 19):\n reference_ages.append(\"aob_14-19M\")\n\n if (x.ageV1 > 18) & (x.ageV1 <= 25):\n reference_ages.append(\"aob_18-25\")\n\n if (x.ageV1 > 25) & (x.ageV1 <= 39):\n reference_ages.append(\"aob_25-39\")\n\n if (x.ageV1 > 35) & (x.ageV1 <= 50):\n reference_ages.append(\"aob_35-50\")\n\n if (x.ageV1 > 50) & (x.ageV1 <= 65):\n reference_ages.append(\"aob_50-65\")\n\n if (x.ageV1 > 65) & (x.ageV1 <= 75):\n reference_ages.append(\"aob_65-75\")\n\n if x.ageV1 > 75:\n reference_ages.append(\"aob_75-85\")\n\n return str(reference_ages).strip('[]')\n\n\n\ndef get_agebin(x):\n if (x.gender == 'Female') & (x.ageV1 <= 15.39):\n return \"aob_12-16F\"\n\n if (x.gender == 'Male') & (x.ageV1 <= 14.8):\n return \"aob_12-16M\"\n\n if (x.gender == 'Female') & (x.ageV1 > 15.39) & (x.ageV1 <= 18.63):\n return \"aob_14-19F\"\n\n if (x.gender == 'Male') & (x.ageV1 > 14.8) & (x.ageV1 <= 18.63):\n return \"aob_14-19M\"\n\n if (x.ageV1 > 18.63) & (x.ageV1 <= 25):\n return \"aob_18-25\"\n\n if (x.ageV1 > 25) & (x.ageV1 <= 37.19):\n return \"aob_25-39\"\n\n if (x.ageV1 > 37.19) & (x.ageV1 <= 50):\n return \"aob_35-50\"\n\n if (x.ageV1 > 50) & (x.ageV1 <= 65):\n return \"aob_50-65\"\n\n if (x.ageV1 > 65) & (x.ageV1 <= 75):\n return \"aob_65-75\"\n\n if x.ageV1 > 75:\n return \"aob_75-85\"\n\n\nX_train = pd.read_csv(os.path.join(input_path, \"X_train.csv\"))\ny_train = pd.read_csv(os.path.join(input_path, \"y_train.csv\"))\n\nfeatures_p3a = ['P3a_Delta_Novel_similarity_spatial',\n 'P3a_Delta_Novel_similarity_locationLR',\n 'P3a_Delta_Novel_similarity_locationPA',\n 'P3a_Delta_Novel_similarity_timing',\n 'P3a_Delta_Novel_similarity_amplitude',\n 'P3a_Delta_Novel_matchScore',\n 'P3a_Delta_Novel_attr_timeMSfromTriger',\n 'P3a_Delta_Novel_attr_leftRight',\n 'P3a_Delta_Novel_attr_posteriorAnterior',\n 'P3a_Delta_Novel_attr_amplitude',\n 'P3a_Delta_Novel_topo_topographicCorrCoeffAligned',\n 'P3a_Delta_Novel_topo_topographicSimilarity']\n\nfeatures_p3b = ['P3b_Delta_Target_similarity_spatial',\n #'P3b_Delta_Target_similarity_locationLR',\n 'P3b_Delta_Target_similarity_locationPA',\n 'P3b_Delta_Target_similarity_timing',\n 'P3b_Delta_Target_similarity_amplitude',\n 'P3b_Delta_Target_matchScore',\n 'P3b_Delta_Target_attr_timeMSfromTriger',\n #'P3b_Delta_Target_attr_leftRight',\n #'P3b_Delta_Target_attr_posteriorAnterior',\n #'P3b_Delta_Target_attr_amplitude',\n 'P3b_Delta_Target_topo_topographicCorrCoeffAligned',\n 'P3b_Delta_Target_topo_topographicSimilarity']\n\n# splitting to agebins should be done here\ndf = pd.merge(y_train, X_train, on='taskData._id.$oid')\n\ndf = df[(df['agebin'] == \"aob_12-16F\") | (df['agebin'] == \"aob_12-16M\") | (df['agebin'] == \"aob_14-19F\") | (df['agebin'] == \"aob_14-19M\")]\n\ndq_df = pd.read_csv(r\"S:\\Data_Science\\Core\\FDA_submission_10_2019\\06-Data\\02-Preprocessed_data\\2020-02-18\\AOB\\AOB_Target.csv\")\ndq_df = dq_df[features_p3b+['taskData.elm_id']].merge(pd.read_csv(r\"S:\\Data_Science\\Core\\FDA_submission_10_2019\\06-Data\\02-Preprocessed_data\\2020-02-18\\AOB\\AOB_Novel.csv\"), on='taskData.elm_id')\ndq_df['agebin'] = dq_df.apply(get_agebin, axis=1)\nfeatures = features_p3b + [i for i in dq_df.columns if ('P3a' in i) and ('miscatch' not in i)]\n\n\nnew_p3a = pd.read_csv(r\"C:\\Users\\nogag\\aob-miscatch-detection\\retraining_after_lableing\\data\\complete_lower25.csv\")\ndq_df = dq_df[dq_df['taskData.elm_id'].isin(new_p3a['taskData._id.$oid'])]\ndq_df = dq_df[features+['taskData.elm_id', 'visit']].merge(new_p3a[['taskData._id.$oid', 'miscatch_P3a_novel']], left_on='taskData.elm_id', right_on='taskData._id.$oid')\ndq_df['miscatch_P3a_novel'] = dq_df['miscatch_P3a_novel'].apply(lambda x: 1 if x=='yes' else 0)\ndf = df.append(dq_df)\ncv = StratifiedKFold(4)\ndq_df = dq_df.dropna(subset=features)\ndq_df = dq_df[dq_df.visit==1]\ndf = df.dropna(subset=features)\ndf = df[df.visit == 1]\n\n## remove DQ list\ndq = pd.read_csv(r\"C:\\Users\\nogag\\aob-miscatch-detection\\DQ\\AOB_Novel_remove.csv\")\ndf = df[~df['taskData._id.$oid'].isin(dq['taskData.elm_id'])]\n\n\npipeline = Pipeline(steps=[\n (\"preprocess\", StandardScaler()),\n (\"feature_selection\", RFE(LogisticRegression(max_iter=500, penalty=\"l1\", solver='liblinear'))),\n (\"estimator\", CatBoostClassifier(verbose=0))\n ])\n\ngrid_search = GridSearchCV(pipeline, param_grid=param_grid, scoring='f1', cv=StratifiedKFold(10))\ngrid_search.fit(df[features], df[\"miscatch_P3a_novel\"], estimator__early_stopping_rounds=15)\nclf = grid_search.best_estimator_\npredictions = cross_val_predict(clf, df[features], df[\"miscatch_P3a_novel\"], cv=StratifiedKFold(10), fit_params={\"estimator__early_stopping_rounds\":3})\nprint(grid_search.best_params_)\nprint('auc', roc_auc_score(df[\"miscatch_P3a_novel\"], predictions))\nprint('recall', recall_score(df[\"miscatch_P3a_novel\"], predictions))\nprint('precision', precision_score(df[\"miscatch_P3a_novel\"], predictions))\nprint('confusion martix\\n', confusion_matrix(df[\"miscatch_P3a_novel\"], predictions), '\\n')\n\ndf[predictions==1]['taskData._id.$oid'].to_csv(fr'C:\\Users\\nogag\\aob-miscatch-detection\\retraining_after_lableing\\exports_p3a\\pred_miscatches_lower25_cv__gridsearch.csv', index=False, header=['taskData.elm_id'])\ndf[(predictions == 1) & (df[\"miscatch_P3b_target\"]==0)]['taskData._id.$oid'].to_csv(\n fr'C:\\Users\\nogag\\aob-miscatch-detection\\retraining_after_lableing\\exports_p3a\\false positive_miscatches_lower25_cv__gridsearch.csv',\n index=False, header=['taskData.elm_id'])\ndf[(predictions == 1) & (df[\"miscatch_P3b_target\"]==0)]['taskData._id.$oid'].to_csv(\n fr'C:\\Users\\nogag\\aob-miscatch-detection\\retraining_after_lableing\\exports_p3a\\false negative_miscatches_lower25_cv__gridsearch.csv',\n index=False, header=['taskData.elm_id'])\n\n\nall_data = pd.read_csv(r\"S:\\Data_Science\\Core\\FDA_submission_10_2019\\06-Data\\02-Preprocessed_data\\2020-02-18\\AOB\\AOB_Novel.csv\")\n\nall_data = all_data[features_p3a+['taskData.elm_id']].merge(pd.read_csv(r\"S:\\Data_Science\\Core\\FDA_submission_10_2019\\06-Data\\02-Preprocessed_data\\2020-02-18\\AOB\\AOB_Target.csv\"), on='taskData.elm_id')\nall_data['agebin'] = all_data.apply(get_agebin, axis=1)\nall_data = all_data[(all_data['agebin'] == \"aob_12-16F\") | (all_data['agebin'] == \"aob_12-16M\") | (all_data['agebin'] == \"aob_14-19F\") | (all_data['agebin'] == \"aob_14-19M\") | (all_data['agebin'] == \"aob_18-25\")]\ndf = df.dropna(subset=features)\nall_data = all_data.dropna(subset=features)\nall_data = all_data[all_data.visit==1]\nall_data = all_data[~all_data['taskData.elm_id'].isin(dq['taskData.elm_id'])]\n\nX_pred = all_data[~all_data['taskData.elm_id'].isin(df['taskData._id.$oid'])]\ngrid_search = GridSearchCV(pipeline, param_grid=param_grid, scoring='f1', cv=StratifiedKFold(10))\ngrid_search.fit(df[features], df[\"miscatch_P3a_novel\"], estimator__early_stopping_rounds=3)\nprint(df[[features]].columns)\ny_pred = grid_search.best_estimator_.fit(df[features], df[\"miscatch_P3a_novel\"]).predict(X_pred)\nprint(grid_search.best_params_)\n\n\nX_pred[y_pred==1]['taskData.elm_id'].to_csv(fr'C:\\Users\\nogag\\aob-miscatch-detection\\retraining_after_lableing\\exports_p3a\\pred_miscatches_lower25_unlabeleddata.csv', index=False, header=['taskData.elm_id'])\n","sub_path":"retraining_after_lableing/lower25.py","file_name":"lower25.py","file_ext":"py","file_size_in_byte":9154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"401295197","text":"import os\nimport csv\nimport numpy as np\nimport sounddevice as sd\nimport librosa\nfrom keras.models import load_model as load_model_CNNLSTM\n\nimport feature_extraction_scripts.feature_extraction_functions as featfun\nimport feature_extraction_scripts.prep_noise as pn\n\nimport torch\nimport torch.nn.functional as F\n\nimport pandas as pd\nimport math\nimport os\nimport configure as c\n\nfrom DB_wav_reader import read_feats_structure\nfrom SR_Dataset import read_MFB, ToTensorTestInput\nfrom model.model import background_resnet\n\nimport speech_recognition as sr\nimport pickle\nimport numpy as np\n\nfrom python_speech_features import logfbank, fbank\nfrom feature_extraction_scripts.feature_extraction_functions import get_stft,get_mfcc,get_cqt\n\nfrom feature_extraction_scripts.custom_functions import normalize_frames\n\nimport datetime\n\ndef get_date():\n time = datetime.datetime.now()\n time_str = \"{}d{}h{}m{}s\".format(time.day,time.hour,time.minute,time.second)\n return(time_str)\n\ndef record_sound(sec,message):\n sr = 16000\n print(message+\" for {} seconds..\".format(sec))\n sound = sd.rec(int(sec*sr),samplerate=sr,channels=1)\n sd.wait()\n return sound, sr\n\ndef str2bool(bool_string):\n bool_string = bool_string==\"True\"\n return bool_string\n\ndef load_model_dvector(use_cuda, log_dir, cp_num, embedding_size, n_classes):\n model = background_resnet(embedding_size=embedding_size, num_classes=n_classes)\n if use_cuda:\n model.cuda()\n print('=> loading checkpoint')\n # original saved file with DataParallel\n checkpoint = torch.load(log_dir + '/checkpoint_' + str(cp_num) + '.pth')\n # create new OrderedDict that does not contain `module.`\n model.load_state_dict(checkpoint['state_dict'])\n model.eval()\n return model\n\n\ndef split_enroll_and_test(dataroot_dir):\n DB_all = read_feats_structure(dataroot_dir)\n enroll_DB = pd.DataFrame()\n test_DB = pd.DataFrame()\n\n enroll_DB = DB_all[DB_all['filename'].str.contains('enroll.p')]\n test_DB = DB_all[DB_all['filename'].str.contains('test.p')]\n\n # Reset the index\n enroll_DB = enroll_DB.reset_index(drop=True)\n test_DB = test_DB.reset_index(drop=True)\n return enroll_DB, test_DB\n\n\ndef load_enroll_embeddings(embedding_dir):\n embeddings = {}\n for f in os.listdir(embedding_dir):\n spk = f.replace('.pth', '')\n # Select the speakers who are in the 'enroll_spk_list'\n embedding_path = os.path.join(embedding_dir, f)\n tmp_embeddings = torch.load(embedding_path)\n embeddings[spk] = tmp_embeddings\n\n return embeddings\n\n\ndef get_embeddings(use_cuda, filename, model, test_frames):\n input, label = read_MFB(filename) # input size:(n_frames, n_dims)\n\n tot_segments = math.ceil(len(input) / test_frames) # total number of segments with 'test_frames'\n activation = 0\n with torch.no_grad():\n for i in range(tot_segments):\n temp_input = input[i * test_frames:i * test_frames + test_frames]\n\n TT = ToTensorTestInput()\n temp_input = TT(temp_input) # size:(1, 1, n_dims, n_frames)\n\n if use_cuda:\n temp_input = temp_input.cuda()\n temp_activation, _ = model(temp_input)\n activation += torch.sum(temp_activation, dim=0, keepdim=True)\n\n activation = l2_norm(activation, 1)\n\n return activation\n\n\ndef l2_norm(input, alpha):\n input_size = input.size() # size:(n_frames, dim)\n buffer = torch.pow(input, 2) # 2 denotes a squared operation. size:(n_frames, dim)\n normp = torch.sum(buffer, 1).add_(1e-10) # size:(n_frames)\n norm = torch.sqrt(normp) # size:(n_frames)\n _output = torch.div(input, norm.view(-1, 1).expand_as(input))\n output = _output.view(input_size)\n # Multiply by alpha = 10 as suggested in https://arxiv.org/pdf/1703.09507.pdf\n output = output * alpha\n return output\n\n\ndef perform_identification(use_cuda, model, embeddings, test_filename, test_frames, spk_list,file_name):\n # print(embeddings)\n print(test_filename)\n # print(model)\n # print(test_frames)\n test_embedding = get_embeddings(use_cuda, test_filename, model, test_frames)\n max_score = -10 ** 8\n best_spk = None\n score_array = []\n for spk in spk_list:\n score = F.cosine_similarity(test_embedding, embeddings[spk])\n score = score.data.cpu().numpy()\n print(\"speaker : \" + str(spk) + \" , Score : \" + str(score[0]))\n score_array.append(score[0])\n if score > max_score:\n max_score = score\n best_spk = spk\n # print(\"Speaker identification result : %s\" %best_spk)\n true_spk = file_name\n print(\"\\n=== Speaker identification ===\")\n print(\"True speaker : %s\" % (true_spk))\n return score_array\n\ndef get_date():\n time = datetime.datetime.now()\n time_str = \"{}d{}h{}m{}s\".format(time.day, time.hour, time.minute, time.second)\n return (time_str)\n\ndef record_sound(file_name, path):\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Say Bed-Bird-Cat-Dog-Down!\")\n audio = r.listen(source, phrase_time_limit=5)\n timestamp = get_date()\n result_name = str(file_name) + \"_\" + str(timestamp)\n print(result_name)\n\n # write audio to a WAV file\n if not os.path.exists(path):\n os.makedirs(path)\n with open(path + \"/\" + result_name + \".wav\", \"wb\") as f:\n f.write(audio.get_wav_data())\n print(result_name + \" : Finish !\")\n return result_name\n\ndef main(project_head_folder,model_name):\n log_dir = 'model_saved' # Where the checkpoints are saved\n embedding_dir = 'enroll_embeddings' # Where embeddings are saved\n test_dir = 'feat_logfbank_nfilt40/test/' # Where test features are saved\n\n spk_list = []\n people_list = os.listdir(embedding_dir)\n\n for file in people_list:\n spk_list.append(file.split('.')[0])\n print(\"등록 되어있는 사용자들\")\n print(spk_list)\n print(\"훈련 되어있는 사용자들\")\n people_train_list = os.listdir(\"feat_logfbank_nfilt40/train/\")\n print(people_train_list)\n\n recording_folder = \"./recording_mic\"\n # file_name = str(input(\"What is your Name?\"))\n # if not(any(file_name in spk_list for people_name in spk_list)):\n # print(\"존재하지 않는 사용자.\")\n # return None\n # result_file = record_sound(file_name, recording_folder)\n\n # speech_filename = recording_folder + \"/\" + result_file + \".wav\"\n\n # === FOR CNNLSTM ===\n head_folder_beg = \"./ml_speech_projects/\"\n head_folder_curr_project = head_folder_beg + project_head_folder\n\n # load the information related to features and model of interest\n features_info_path = head_folder_curr_project + \"/features_log.csv\"\n encoded_label_path = head_folder_curr_project + \"/labels_encoded.csv\"\n model_path = head_folder_curr_project + \"/models/{}.h5\".format(model_name)\n model_log_path = head_folder_curr_project + \"/model_logs/{}.csv\".format(model_name)\n\n # find out the settings for feature extraction\n with open(features_info_path, mode='r') as infile:\n reader = csv.reader(infile)\n feats_dict = {rows[0]: rows[1] for rows in reader}\n feature_type = feats_dict['features']\n num_filters = int(feats_dict['num original features'])\n num_feature_columns = int(feats_dict['num total features'])\n delta = str2bool(feats_dict[\"delta\"])\n dom_freq = str2bool(feats_dict[\"dominant frequency\"])\n noise = str2bool(feats_dict[\"noise\"])\n vad = str2bool(feats_dict[\"beginning silence removal\"])\n timesteps = int(feats_dict['timesteps'])\n context_window = int(feats_dict['context window'])\n frame_width = context_window * 2 + 1\n\n # prepare the dictionary to find out the assigned label\n with open(encoded_label_path, mode='r') as infile:\n reader = csv.reader(infile)\n dict_labels_encoded = {rows[0]: rows[1] for rows in reader}\n\n print(dict_labels_encoded)\n print(\"\\nAvailable labels:\")\n for key, value in dict_labels_encoded.items():\n print(value)\n\n # recording_folder = \"{}/recordings\".format(head_folder_curr_project)\n\n # === FOR CNNLSTM END ===\n\n # print(\"훈련되어있는 방법을 선택하세요.\")\n # print(\"1. fbank\")\n # print(\"2. stft\")\n # print(\"3. mfcc\")\n # print(\"4. cqt\")\n # print(\"번호 입력\")\n # train_way = int(input())\n train_way = 1\n\n spk_list.remove('103F3021')\n spk_list.remove('207F2088')\n spk_list.remove('213F5100')\n spk_list.remove('217F3038')\n spk_list.remove('225M4062')\n spk_list.remove('229M2031')\n spk_list.remove('230M4087')\n spk_list.remove('233F4013')\n spk_list.remove('236M3043')\n spk_list.remove('240M3063')\n\n identification_try_success = 0\n identification_try_fail = 0\n identification_try_total = 0\n\n verification_try_success = 0\n verification_try_fail = 0\n verification_try_total = 0\n for speech_filename in os.listdir(\"recording_mic\"):\n file_name = speech_filename\n speech_filename = recording_folder + \"/\" + speech_filename\n print(speech_filename)\n\n person_name = speech_filename.split(\"/\")[2].split(\"_\")[0]\n print(person_name)\n\n is_he_on_list = False\n print(\"is he in LIST?\")\n if (person_name in spk_list):\n is_he_on_list = True\n print(\"YES\")\n else:\n is_he_on_list = False\n print(\"NO\")\n y_speech, sr = librosa.load(speech_filename, sr=16000, mono=True)\n\n print(\"sound dB : \" + str(np.mean(np.sqrt(np.square(y_speech)))))\n if (np.mean(np.sqrt(np.square(y_speech)))) < 0.001:\n print(\"Too LOW dB.\")\n print(\"GMM check end with FILTER\")\n # return None\n\n if train_way == 1:\n filter_banks, energies = fbank(y_speech, samplerate=16000, nfilt=40, winlen=0.025)\n filter_banks = 20 * np.log10(np.maximum(filter_banks, 1e-5))\n feature = normalize_frames(filter_banks, Scale=False)\n elif train_way == 2:\n feature = stft = get_stft(y_speech, sr)\n\n elif train_way == 3:\n feature = np.asarray(())\n vector = get_mfcc(y_speech, sr)\n\n if feature.size == 0:\n feature = vector\n else:\n feature = np.vstack((feature, vector))\n\n elif train_way == 4:\n feature = np.asarray(())\n vector = get_cqt(y_speech, sr)\n\n if feature.size == 0:\n feature = vector\n else:\n feature = np.vstack((feature, vector))\n\n infor = {\"feat\": feature, \"label\": \"temp\"}\n if not os.path.exists(test_dir + \"temp\"):\n os.makedirs(test_dir + \"temp\")\n pickle.dump(infor, open(test_dir + \"temp/test.p\", \"wb\"))\n\n # Settings\n use_cuda = True # Use cuda or not\n embedding_size = 128 # Dimension of speaker embeddings\n cp_num = 24 # Which checkpoint to use?\n n_classes = 240 # How many speakers in training data?\n test_frames = 100 # Split the test utterance\n\n # Load model from checkpoint\n model = load_model_dvector(use_cuda, log_dir, cp_num, embedding_size, n_classes)\n\n # Get the dataframe for test DB\n enroll_DB, test_DB = split_enroll_and_test(c.TEST_FEAT_DIR)\n\n # Load enroll embeddings\n embeddings = load_enroll_embeddings(embedding_dir)\n\n \"\"\" Test speaker list\n '103F3021', '207F2088', '213F5100', '217F3038', '225M4062', \n '229M2031', '230M4087', '233F4013', '236M3043', '240M3063'\n \"\"\"\n\n # Set the test speaker\n test_speaker = \"temp\"\n\n test_path = os.path.join(test_dir, test_speaker, 'test.p')\n\n\n # Perform the test\n score_array = perform_identification(use_cuda, model, embeddings, test_path, test_frames, spk_list, file_name)\n\n features = featfun.coll_feats_manage_timestep(timesteps, frame_width, speech_filename, feature_type,\n num_filters,\n num_feature_columns, recording_folder, delta=delta,\n dom_freq=dom_freq,\n noise_wavefile=None, vad=vad)\n\n with open(model_log_path, mode='r') as infile:\n reader = csv.reader(infile)\n dict_model_settings = {rows[0]: rows[1] for rows in reader}\n\n model_type = dict_model_settings[\"model type\"]\n activation_output = dict_model_settings[\"activation output\"]\n\n X = features\n if model_type == \"lstm\":\n X = X.reshape((timesteps, frame_width, X.shape[1]))\n elif model_type == \"cnn\":\n X = X.reshape((X.shape[0], X.shape[1], 1))\n X = X.reshape((1,) + X.shape)\n elif model_type == \"cnnlstm\":\n X = X.reshape((timesteps, frame_width, X.shape[1], 1))\n X = X.reshape((1,) + X.shape)\n\n # load model\n model = load_model_CNNLSTM(model_path)\n\n prediction = model.predict(X)\n\n print(prediction)\n print(max(prediction[0]))\n\n identification_try_total += 1\n print(\"score_array의 표준편차 : \" + str(np.std(score_array)))\n if (max(score_array)<0.987):\n print(\"점수가 너무 낮아 등록되지 않은 사람으로 판정.\\n\\n\")\n if is_he_on_list:\n identification_try_fail += 1\n else:\n identification_try_success+=1\n continue\n if (np.std(score_array) < 0.0225):\n print(\"점수가 서로 비슷하여 등록되지 않은 사람으로 판정.\\n\\n\")\n if is_he_on_list:\n identification_try_fail += 1\n else:\n identification_try_success += 1\n continue\n\n if is_he_on_list:\n identification_try_success += 1\n else:\n identification_try_fail += 1\n\n if (max(prediction[0]) < 0.5):\n print(\"This person is not permitted maxscore 0.5\")\n print(\"end with FILTER\")\n\n if is_he_on_list:\n identification_try_fail += 1\n else:\n identification_try_success += 1\n\n continue\n\n pred = str(np.argmax(prediction[0])) # argmax함수로 가장 큰 값 추출\n print(speech_filename)\n label = dict_labels_encoded[pred]\n\n verification_try_total += 1\n print(\"Label without noise reduction: {}\".format(label))\n if label == person_name:\n verification_try_success += 1\n else:\n verification_try_fail += 1\n\n print(\"identification 성공횟수: {}, 실패횟수: {}, 총 시도 횟수: {}, 성공률: {}%\".format(identification_try_success,\n identification_try_fail,\n identification_try_total, (\n identification_try_success / identification_try_total) * 100))\n print(\"verification 성공횟수: {}, 실패횟수: {}, 총 시도 횟수: {}, 성공률: {}%\".format(verification_try_success,\n verification_try_fail,\n verification_try_total, (\n verification_try_success / verification_try_total) * 100))\n print(\"=================\")\n print(\"=================\")\n print(\"\")\n\n\n if (identification_try_total == 0 or verification_try_total == 0): return None\n\n print(\"총 합계 계산..\")\n print(\"identification 성공횟수: {}, 실패횟수: {}, 총 시도 횟수: {}, 성공률: {}%\".format(identification_try_success,identification_try_fail,identification_try_total,(identification_try_success/identification_try_total)*100))\n print(\"verification 성공횟수: {}, 실패횟수: {}, 총 시도 횟수: {}, 성공률: {}%\".format(verification_try_success,\n verification_try_fail,\n verification_try_total, (\n verification_try_success / verification_try_total) * 100))\n\n return None\n\nif __name__==\"__main__\":\n \n project_head_folder = \"stft201_models_2019y11m8d15h3m46s\"\n model_name = \"CNNLSTM_speech_commands001\"\n \n main(project_head_folder,model_name)\n \n \n \n","sub_path":"implement_model_dvector_CNNLSTM folder iter.py","file_name":"implement_model_dvector_CNNLSTM folder iter.py","file_ext":"py","file_size_in_byte":16796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"127997527","text":"\nimport glob\nimport os\nimport dask.bag as db\n\nfrom SComplexity.utils import html_to_txt, convert_pdf_to_txt\nfrom SComplexity.t_analysis import text_proc\n\nfrom natsort import natsorted, ns\nimport pprint\nimport pickle\nimport numpy as np\nimport os\n\n\ndef print_best_text(f):\n link_tuple = pickle.load(open(f,'rb'))\n se_b, page_rank, link, category, buff_ = link_tuple\n return buff_\n\n\n\nclass Analysis(object):\n def __init__(self,files, min_word_length = 200, urlDats=None):\n self.files = files\n self.urlDats = urlDats\n self.mwl = min_word_length\n\n def convert_and_score(self,f):\n urlDat = {}\n b = os.path.getsize(f)\n link_tuple = pickle.load(open(f,'rb'))\n se_b, page_rank, link, category, buff_ = link_tuple\n if buff_ is not None:\n urlDat = { 'link':link,'page_rank':page_rank,'se':se_b,'query':category,'file':f }\n urlDat = text_proc(buff_,urlDat, WORD_LIM = self.mwl)\n return urlDat\n\n def cas(self):\n # Do in parallel as it is 2018\n \n pgrid = db.from_sequence(self.files,npartitions=8)\n urlDats = list(db.map(self.convert_and_score,pgrid).compute())\n # just kidding need to do a serial debug often times, regardless of parallel speed up.\n #urlDats = list(map(self.convert_and_score,self.files))\n urlDats = [ url for url in urlDats if type(url) is not type(None) ]\n #urlDats = list(filter(lambda url: type(url) != None, urlDats))\n urlDats = list(filter(lambda url: len(list(url))>3, urlDats))\n\n urlDats = list(filter(lambda url: len(list(url.keys()))>3, urlDats))\n # urlDats = list(filter(lambda url: str('penalty') in url.keys(), urlDats))\n if type(self.urlDats) is not type(None):\n urlDats.extend(self.urlDats)\n return urlDats\n\n def get_reference_web(self):\n from SComplexity.scrape import SW\n from SComplexity.get_bmark_corpus import get_bmarks\n return get_bmarks()\n\n #def get_reference_pickle(self):\n # known_corpus = []\n # from SComplexity.get_bmark_corpus import get_bmarks\n # return get_bmarks()\n","sub_path":"science_access/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"420831723","text":"from core.cache import CacheManager\nfrom core.helpers import pad_title, get_pref\nfrom core.plugin import ART, NAME, ICON\nfrom interface.sync_menu import SyncMenu\nfrom plugin.core.constants import PLUGIN_PREFIX, PLUGIN_VERSION\n\n\n@handler(PLUGIN_PREFIX, NAME, thumb=ICON, art=ART)\ndef MainMenu():\n oc = ObjectContainer(no_cache=True)\n\n if not get_pref('valid'):\n oc.add(DirectoryObject(\n key=PLUGIN_PREFIX,\n title=L(\"Error: Authentication failed\"),\n ))\n\n oc.add(DirectoryObject(\n key=Callback(SyncMenu),\n title=L(\"Sync\"),\n summary=L(\"Sync the Plex library with Trakt.tv\"),\n thumb=R(\"icon-sync.png\")\n ))\n\n oc.add(DirectoryObject(\n key=Callback(AboutMenu),\n title=L(\"About\"),\n thumb=R(\"icon-about.png\")\n ))\n\n oc.add(PrefsObject(\n title=\"Preferences\",\n summary=\"Configure how to connect to Trakt.tv\",\n thumb=R(\"icon-preferences.png\")\n ))\n\n return oc\n\n\n@route(PLUGIN_PREFIX + '/about')\ndef AboutMenu():\n oc = ObjectContainer(title2=\"About\")\n\n oc.add(DirectoryObject(\n key=Callback(CacheStatisticsMenu),\n title=pad_title(\"Cache Statistics\")\n ))\n\n oc.add(DirectoryObject(\n key=Callback(AboutMenu),\n title=pad_title(\"Version: %s\" % PLUGIN_VERSION)\n ))\n\n return oc\n\n\n@route(PLUGIN_PREFIX + '/about/cache')\ndef CacheStatisticsMenu():\n oc = ObjectContainer(title2=\"Cache Statistics\")\n\n for item in CacheManager.statistics():\n oc.add(DirectoryObject(\n key='',\n title=pad_title(\"[%s] Cache Size: %s, Store Size: %s\" % item)\n ))\n\n return oc\n","sub_path":"Trakttv.bundle/Contents/Code/interface/main_menu.py","file_name":"main_menu.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"133604646","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: zengphil\n# @Date: 2016-03-20 16:36:35\n# @Last Modified by: fibears\n# @Last Modified time: 2016-03-21 20:23:02\n\n# Load packages\nimport time\nimport urllib\nimport urllib2\nimport cookielib\nimport re\nimport sys\nimport random\n\nfrom agents import AGENTS\nfrom lxml.html import parse\n\nclass GrabLecture(object):\n \"\"\"docstring for GrabLecture\"\"\"\n def __init__(self):\n self.user_agent = random.choice(AGENTS)\n self.headers = {'User-Agent': self.user_agent}\n self.LectureUrl = 'http://event.wisesoe.com/LectureOrder.aspx'\n\n # Define the opener\n def getOpener(self):\n cookie = cookielib.MozillaCookieJar()\n cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)\n opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))\n return opener\n\n # Get the html parsed result\n def getParsed(self):\n opener = self.getOpener()\n parsed = parse(opener.open(self.LectureUrl))\n return parsed\n\n # Construct the PostData from parsed result\n def getPostdata(self):\n parsed = self.getParsed()\n # construct regex to extract JSLink of Reservation\n pattern = re.compile(r\"javascript:__doPostBack\\('(.*?)','(.*?)'\\)\")\n # The link of cancelling reservation.\n # JSLink = parsed.xpath('//td/a[contains(@onclick, \"Cancel\")]/@href')\n\n JSLink = parsed.xpath('//td/a[contains(@id, \"btnreceive\")]/@href')\n # check whether JSLink exists\n if JSLink == []:\n print(\"Sorry!!!=======>No Seminar is active at present!\")\n print(\"Bye-Bye!\")\n # Exit python and print information.\n sys.exit()\n\n PostData = []\n\n for i in range(0, len(JSLink)):\n link = JSLink[i]\n EventTarget = pattern.match(link).groups()[0]\n EventArgument = pattern.match(link).groups()[1]\n\n # Extract the parameters from html\n ViewState = parsed.xpath('//input[@name=\"__VIEWSTATE\"]/@value')[0]\n ViewStateGenerator = parsed.xpath('//input[@name=__VIEWSTATEGENERATOR]/@value')\n ViewStateEncrypted = parsed.xpath('//input[@name=__VIEWSTATEENCRYPTED]/@value')\n EventValidation = parsed.xpath('//input[@name=\"__EVENTVALIDATION\"]/@value')[0]\n\n # Create PostData\n PostData.append(urllib.urlencode({\n '__EVENTTARGET': EventTarget,\n '__EVENTARGUMENT': EventArgument,\n '__VIEWSTATE': ViewState,\n '__VIEWSTATEGENERATOR': ViewStateGenerator,\n '__VIEWSTATEENCRYPTED': ViewStateEncrypted,\n '__EVENTVALIDATION': EventValidation\n }))\n\n return PostData\n\n\n def start(self):\n self.headers.update({\n 'Host': 'event.wisesoe.com',\n 'Referer': 'http://event.wisesoe.com/Authenticate.aspx?returnUrl=/LectureOrder.aspx',\n 'Connection': 'keep-alive'\n })\n print(\"The robot is starting!!!\")\n print(\"Searching active seminar...........\")\n opener = self.getOpener()\n PostData = self.getPostdata()\n for i in range(0, len(PostData)):\n Data = PostData[i]\n QKRequest = urllib2.Request(self.LectureUrl, Data, self.headers)\n response = opener.open(QKRequest)\n print(\"Congratulation!!!You have reserved one seminar!!!\")\n\n\nif __name__ == '__main__':\n robot = GrabLecture()\n robot.start()\n\n\n\n\n\n\n\n","sub_path":"code/GrabLecture.py","file_name":"GrabLecture.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"544377366","text":"from django.http import HttpResponse\nfrom django.template import loader\nfrom xml.dom import minidom\n\n\nfrom datetime import datetime, timedelta\nimport urllib.request, zipfile, numpy, json, scipy.interpolate\n\n\nfrom .models import Data, Transacao\n\n\ndef index(request):\n template = loader.get_template('ditax/index.html')\n return HttpResponse(template.render())\n\n\ndef gera_feriados():\n ####\n # Função que gera a lista de feriados em uma string baseada no arquivo\n # feriados.xml fornecido.\n ####\n xml = minidom.parse('feriados.xml')\n feriados_raw = xml.getElementsByTagName('holiday')\n feriados = []\n for dia in feriados_raw:\n feriados.append(datetime.strptime(str(dia.attributes['date'].value), '%Y-%m-%d'))\n\n return feriados\n\n\ndef e_dia_util(data, lista_feriados):\n ####\n # Checa se determinada data é dia util.\n # A data deve ser um objeto datetime.\n ####\n\n\n\n ## weekday = 5 e weekday = 6 são os sábados e domingos.\n if data.weekday() == 5 or data.weekday() == 6:\n return False\n\n if data in lista_feriados:\n return False\n\n return True\n\ndef e_dia_util_view(request, data):\n lista_feriados = gera_feriados()\n if not(e_dia_util(datetime.strptime(str(data), '%y%m%d'), lista_feriados)):\n return HttpResponse('False')\n return HttpResponse('True')\n\n\ndef dias_uteis(request, data, data2):\n ####\n # Retorna o numero de dias uteis entre data e data2.\n # O formato de entrada deve ser do tipo yymmdd.\n ####\n\n dias = 0\n diasuteis = 0\n lista_feriados = gera_feriados()\n\n try:\n data = datetime.strptime(str(data), '%y%m%d')\n data2 = datetime.strptime(str(data2), '%y%m%d')\n\n\n while data <= data2:\n dias += 1\n if e_dia_util(data, lista_feriados):\n diasuteis += 1\n data += timedelta(days=1)\n\n return HttpResponse(diasuteis)\n\n except ValueError:\n raise \"Data inválida.\"\n\n\ndef adiciona_choque(percent, cotacoes):\n return [float(cotacao) + float(percent) for cotacao in cotacoes]\n\n\n\ndef pega_dados_de_data(data):\n\n ####\n # Funcao que acessa o site da BMF, baixa os dados referentes a uma determinada data\n # e armazena no banco caso ainda não esteja. Requer conexão com a internet\n # caso a data não esteja no banco. Caso esteja, ele vai retornar o valor diretamente\n # do banco.\n ####\n\n\n data_existe = Data.objects.filter(data=data).exists()\n lista_feriados = gera_feriados()\n if (not data_existe) and (e_dia_util(datetime.strptime(str(data), '%y%m%d'), lista_feriados)):\n\n data_obj = Data(data=data)\n data_obj.save()\n\n url = \"http://www.bmf.com.br/ftp/ContratosPregaoFinal/BF\" + data + \".ex_\"\n file_name, headers = urllib.request.urlretrieve(url)\n\n # -> /\\ Precisa checar se o download foi Ok!!!\n\n with zipfile.ZipFile(file_name, \"r\") as zip_ref:\n zip_ref.extractall(\".\")\n\n with open(\"BD_Final.txt\", 'r') as file:\n for line in file:\n # As faixas foram retiradas do doc disponibilizado.\n transacao_id = line[0:6]\n codigo = line[21:24]\n data_vencimento = line[36:44]\n cotacao = line[246:259]\n dias_ate_vencimento = line[388:393]\n if (codigo == 'DI1') and (int(cotacao) != 0) and (int(dias_ate_vencimento) != 0):\n transacao_obj = Transacao(data = data_obj,\n transacao_id = transacao_id,\n data_vencimento = data_vencimento,\n cotacao = cotacao,\n dias_ate_vencimento = dias_ate_vencimento)\n\n transacao_obj.save()\n\n\ndef json_data(request, data, choque = None):\n\n ####\n # API para fornecer os dados em json para gerar o gráfico do c3js e que pode\n # ser reutilizada pra outros fins.\n #\n # O data == 0 serve para fornecer um json vazio, para gerar o gráfico inicial.\n ####\n lista_feriados = gera_feriados()\n if data == \"0\" or (not(e_dia_util(datetime.strptime(str(data), '%y%m%d'), lista_feriados))):\n result = '{ \"x\": [\"00-00-00\"], \"Cotação DI (%)\": [\"0\"] }'\n return HttpResponse(result)\n\n pega_dados_de_data(data)\n data_obj = Data.objects.filter(data=data)\n transacoes = Transacao.objects.filter(data=data_obj)\n\n ## Gera a lista com as datas em formato para o c3js\n datas_x = json.dumps([transacao.data_vencimento_em_datetime() for transacao in transacoes])\n\n ## Transforma as taxas em valor em porcentagem e com 2 digitos.\n cotacoes_y = [transacao.taxa_di() * 100 for transacao in transacoes]\n cotacoes_choque = []\n\n if choque:\n cotacoes_choque = adiciona_choque(float(choque), cotacoes_y)\n cotacoes_choque = json.dumps([\"%.2f\" % member for member in cotacoes_choque])\n\n cotacoes_y = json.dumps([\"%.2f\" % member for member in cotacoes_y])\n\n template = loader.get_template('ditax/rawdata.html')\n context = {\n 'x': datas_x,\n 'y': cotacoes_y,\n 'choque': cotacoes_choque\n }\n\n return HttpResponse(template.render(context, request))\n\n\ndef interpol(request, data, data2, interpol_type = 'slinear', choque = '0'):\n lista_feriados = gera_feriados()\n if (not(e_dia_util(datetime.strptime(str(data), '%y%m%d'), lista_feriados))):\n return HttpResponse('0')\n\n pega_dados_de_data(data)\n data2 = int(datetime.strptime(str(data2), '%y%m%d').strftime('%s'))\n\n data_obj = Data.objects.filter(data=data)\n transacoes = Transacao.objects.filter(data=data_obj)\n\n datas_x = [int(transacao.data_vencimento_em_segundos()) for transacao in transacoes]\n cotacoes_y = [transacao.taxa_di() * 100 for transacao in transacoes]\n\n if int(choque):\n cotacoes_y = adiciona_choque(float(choque), cotacoes_y)\n\n datas_x, cotacoes_y = numpy.array(datas_x), numpy.array(cotacoes_y)\n inds = datas_x.argsort()\n datas_x.sort()\n cotacoes_y = cotacoes_y[inds]\n y_interp = scipy.interpolate.interp1d(datas_x, cotacoes_y, fill_value='extrapolate', kind=interpol_type)\n\n y = y_interp(data2)\n y = \"%.2f\" % y\n\n template = loader.get_template('ditax/interpol.html')\n context = {\n 'y': y,\n 'type': interpol_type,\n }\n\n return HttpResponse(template.render(context, request))","sub_path":"ditax/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"121156529","text":"#!/usr/bin/env python\n# Thomas Nagy, 2005-2018 (ita)\n\"\"\"\nTasks represent atomic operations such as processes.\n\"\"\"\nimport os\nimport re\nimport sys\nimport tempfile\nimport traceback\n\nfrom waflib import Errors\nfrom waflib import Logs\nfrom waflib import Utils\n\n# task states\nNOT_RUN = 0\n\"\"\"The task was not executed yet\"\"\"\n\nMISSING = 1\n\"\"\"The task has been executed but the files have not been created\"\"\"\n\nCRASHED = 2\n\"\"\"The task execution returned a non-zero exit status\"\"\"\n\nEXCEPTION = 3\n\"\"\"An exception occurred in the task execution\"\"\"\n\nCANCELED = 4\n\"\"\"A dependency for the task is missing so it was cancelled\"\"\"\n\nSKIPPED = 8\n\"\"\"The task did not have to be executed\"\"\"\n\nSUCCESS = 9\n\"\"\"The task was successfully executed\"\"\"\n\nASK_LATER = -1\n\"\"\"The task is not ready to be executed\"\"\"\n\nSKIP_ME = -2\n\"\"\"The task does not need to be executed\"\"\"\n\nRUN_ME = -3\n\"\"\"The task must be executed\"\"\"\n\nCANCEL_ME = -4\n\"\"\"The task cannot be executed because of a dependency problem\"\"\"\n\nCOMPILE_TEMPLATE_SHELL = \"\"\"\ndef f(tsk):\n\tenv = tsk.env\n\tgen = tsk.generator\n\tbld = gen.bld\n\tcwdx = tsk.get_cwd()\n\tp = env.get_flat\n\ttsk.last_cmd = cmd = \\'\\'\\' %s \\'\\'\\' % s\n\treturn tsk.exec_command(cmd, cwd=cwdx, env=env.env or None)\n\"\"\"\n\nCOMPILE_TEMPLATE_NOSHELL = \"\"\"\ndef f(tsk):\n\tenv = tsk.env\n\tgen = tsk.generator\n\tbld = gen.bld\n\tcwdx = tsk.get_cwd()\n\tdef to_list(xx):\n\t\tif isinstance(xx, str): return [xx]\n\t\treturn xx\n\tdef merge(lst1, lst2):\n\t\tif lst1 and lst2:\n\t\t\treturn lst1[:-1] + [lst1[-1] + lst2[0]] + lst2[1:]\n\t\treturn lst1 + lst2\n\tlst = []\n\t%s\n\tif '' in lst:\n\t\tlst = [x for x in lst if x]\n\ttsk.last_cmd = lst\n\treturn tsk.exec_command(lst, cwd=cwdx, env=env.env or None)\n\"\"\"\n\nclasses = {}\n\"\"\"\nThe metaclass :py:class:`waflib.Task.store_task_type` stores all class tasks\ncreated by user scripts or Waf tools to this dict. It maps class names to class objects.\n\"\"\"\n\n\nclass store_task_type(type):\n \"\"\"\n Metaclass: store the task classes into the dict pointed by the\n class attribute 'register' which defaults to :py:const:`waflib.Task.classes`,\n\n The attribute 'run_str' is compiled into a method 'run' bound to the task class.\n \"\"\"\n\n def __init__(cls, name, bases, dict):\n super().__init__(name, bases, dict)\n name = cls.__name__\n\n if name != \"evil\" and name != \"Task\":\n if getattr(cls, \"run_str\", None):\n # if a string is provided, convert it to a method\n (f, dvars) = compile_fun(cls.run_str, cls.shell)\n cls.hcode = Utils.h_cmd(cls.run_str)\n cls.orig_run_str = cls.run_str\n # change the name of run_str or it is impossible to subclass with a function\n cls.run_str = None\n cls.run = f\n cls.vars = list(set(cls.vars + dvars))\n cls.vars.sort()\n elif getattr(cls, \"run\", None) and not \"hcode\" in cls.__dict__:\n # getattr(cls, 'hcode') would look in the upper classes\n cls.hcode = Utils.h_cmd(cls.run)\n\n # be creative\n getattr(cls, \"register\", classes)[name] = cls\n\n\nevil = store_task_type(\"evil\", (object,), {})\n\"Base class provided to avoid writing a metaclass, so the code can run in python 2.6 and 3.x unmodified\"\n\n\nclass Task(evil):\n \"\"\"\n This class deals with the filesystem (:py:class:`waflib.Node.Node`). The method :py:class:`waflib.Task.Task.runnable_status`\n uses a hash value (from :py:class:`waflib.Task.Task.signature`) which is persistent from build to build. When the value changes,\n the task has to be executed. The method :py:class:`waflib.Task.Task.post_run` will assign the task signature to the output\n nodes (if present).\n \"\"\"\n\n vars = []\n \"\"\"ConfigSet variables that should trigger a rebuild (class attribute used for :py:meth:`waflib.Task.Task.sig_vars`)\"\"\"\n\n always_run = False\n \"\"\"Specify whether task instances must always be executed or not (class attribute)\"\"\"\n\n shell = False\n \"\"\"Execute the command with the shell (class attribute)\"\"\"\n\n color = \"GREEN\"\n \"\"\"Color for the console display, see :py:const:`waflib.Logs.colors_lst`\"\"\"\n\n ext_in = []\n \"\"\"File extensions that objects of this task class may use\"\"\"\n\n ext_out = []\n \"\"\"File extensions that objects of this task class may create\"\"\"\n\n before = []\n \"\"\"List of task class names to execute before instances of this class\"\"\"\n\n after = []\n \"\"\"List of task class names to execute after instances of this class\"\"\"\n\n hcode = Utils.SIG_NIL\n \"\"\"String representing an additional hash for the class representation\"\"\"\n\n keep_last_cmd = False\n \"\"\"Whether to keep the last command executed on the instance after execution.\n\tThis may be useful for certain extensions but it can a lot of memory.\n\t\"\"\"\n\n weight = 0\n \"\"\"Optional weight to tune the priority for task instances.\n\tThe higher, the earlier. The weight only applies to single task objects.\"\"\"\n\n tree_weight = 0\n \"\"\"Optional weight to tune the priority of task instances and whole subtrees.\n\tThe higher, the earlier.\"\"\"\n\n prio_order = 0\n \"\"\"Priority order set by the scheduler on instances during the build phase.\n\tYou most likely do not need to set it.\n\t\"\"\"\n\n __slots__ = (\n \"hasrun\",\n \"generator\",\n \"env\",\n \"inputs\",\n \"outputs\",\n \"dep_nodes\",\n \"run_after\",\n )\n\n def __init__(self, *k, **kw):\n self.hasrun = NOT_RUN\n try:\n self.generator = kw[\"generator\"]\n except KeyError:\n self.generator = self\n\n self.env = kw[\"env\"]\n \"\"\":py:class:`waflib.ConfigSet.ConfigSet` object (make sure to provide one)\"\"\"\n\n self.inputs = []\n \"\"\"List of input nodes, which represent the files used by the task instance\"\"\"\n\n self.outputs = []\n \"\"\"List of output nodes, which represent the files created by the task instance\"\"\"\n\n self.dep_nodes = []\n \"\"\"List of additional nodes to depend on\"\"\"\n\n self.run_after = set()\n \"\"\"Set of tasks that must be executed before this one\"\"\"\n\n def __lt__(self, other):\n return self.priority() > other.priority()\n\n def __le__(self, other):\n return self.priority() >= other.priority()\n\n def __gt__(self, other):\n return self.priority() < other.priority()\n\n def __ge__(self, other):\n return self.priority() <= other.priority()\n\n def get_cwd(self):\n \"\"\"\n :return: current working directory\n :rtype: :py:class:`waflib.Node.Node`\n \"\"\"\n bld = self.generator.bld\n ret = getattr(self, \"cwd\", None) or getattr(bld, \"cwd\", bld.bldnode)\n if isinstance(ret, str):\n if os.path.isabs(ret):\n ret = bld.root.make_node(ret)\n else:\n ret = self.generator.path.make_node(ret)\n return ret\n\n def quote_flag(self, x):\n \"\"\"\n Surround a process argument by quotes so that a list of arguments can be written to a file\n\n :param x: flag\n :type x: string\n :return: quoted flag\n :rtype: string\n \"\"\"\n old = x\n if \"\\\\\" in x:\n x = x.replace(\"\\\\\", \"\\\\\\\\\")\n if '\"' in x:\n x = x.replace('\"', '\\\\\"')\n if old != x or \" \" in x or \"\\t\" in x or \"'\" in x:\n x = '\"%s\"' % x\n return x\n\n def priority(self):\n \"\"\"\n Priority of execution; the higher, the earlier\n\n :return: the priority value\n :rtype: a tuple of numeric values\n \"\"\"\n return (\n self.weight + self.prio_order,\n -getattr(self.generator, \"tg_idx_count\", 0),\n )\n\n def split_argfile(self, cmd):\n \"\"\"\n Splits a list of process commands into the executable part and its list of arguments\n\n :return: a tuple containing the executable first and then the rest of arguments\n :rtype: tuple\n \"\"\"\n return ([cmd[0]], [self.quote_flag(x) for x in cmd[1:]])\n\n def exec_command(self, cmd, **kw):\n \"\"\"\n Wrapper for :py:meth:`waflib.Context.Context.exec_command`.\n This version set the current working directory (``build.variant_dir``),\n applies PATH settings (if self.env.PATH is provided), and can run long\n commands through a temporary ``@argfile``.\n\n :param cmd: process command to execute\n :type cmd: list of string (best) or string (process will use a shell)\n :return: the return code\n :rtype: int\n\n Optional parameters:\n\n #. cwd: current working directory (Node or string)\n #. stdout: set to None to prevent waf from capturing the process standard output\n #. stderr: set to None to prevent waf from capturing the process standard error\n #. timeout: timeout value (Python 3)\n \"\"\"\n if not \"cwd\" in kw:\n kw[\"cwd\"] = self.get_cwd()\n\n if hasattr(self, \"timeout\"):\n kw[\"timeout\"] = self.timeout\n\n if self.env.PATH:\n env = kw[\"env\"] = dict(kw.get(\"env\") or self.env.env or os.environ)\n env[\"PATH\"] = (\n self.env.PATH\n if isinstance(self.env.PATH, str)\n else os.pathsep.join(self.env.PATH)\n )\n\n if hasattr(self, \"stdout\"):\n kw[\"stdout\"] = self.stdout\n if hasattr(self, \"stderr\"):\n kw[\"stderr\"] = self.stderr\n\n # workaround for command line length limit:\n # http://support.microsoft.com/kb/830473\n if not isinstance(cmd, str) and (\n len(repr(cmd)) >= 8192 if Utils.is_win32 else len(cmd) > 200000\n ):\n cmd, args = self.split_argfile(cmd)\n try:\n (fd, tmp) = tempfile.mkstemp()\n os.write(fd, \"\\r\\n\".join(args).encode())\n os.close(fd)\n if Logs.verbose:\n Logs.debug(\"argfile: @%r -> %r\", tmp, args)\n return self.generator.bld.exec_command(cmd + [\"@\" + tmp], **kw)\n finally:\n try:\n os.remove(tmp)\n except OSError:\n # anti-virus and indexers can keep files open -_-\n pass\n else:\n return self.generator.bld.exec_command(cmd, **kw)\n\n def process(self):\n \"\"\"\n Runs the task and handles errors\n\n :return: 0 or None if everything is fine\n :rtype: integer\n \"\"\"\n # remove the task signature immediately before it is executed\n # so that the task will be executed again in case of failure\n try:\n del self.generator.bld.task_sigs[self.uid()]\n except KeyError:\n pass\n\n try:\n ret = self.run()\n except Exception:\n self.err_msg = traceback.format_exc()\n self.hasrun = EXCEPTION\n else:\n if ret:\n self.err_code = ret\n self.hasrun = CRASHED\n else:\n try:\n self.post_run()\n except Errors.WafError:\n pass\n except Exception:\n self.err_msg = traceback.format_exc()\n self.hasrun = EXCEPTION\n else:\n self.hasrun = SUCCESS\n\n if self.hasrun != SUCCESS and self.scan:\n # rescan dependencies on next run\n try:\n del self.generator.bld.imp_sigs[self.uid()]\n except KeyError:\n pass\n\n def log_display(self, bld):\n \"Writes the execution status on the context logger\"\n if self.generator.bld.progress_bar == 3:\n return\n\n s = self.display()\n if s:\n if bld.logger:\n logger = bld.logger\n else:\n logger = Logs\n\n if self.generator.bld.progress_bar == 1:\n c1 = Logs.colors.cursor_off\n c2 = Logs.colors.cursor_on\n logger.info(\n s,\n extra={\"stream\": sys.stderr, \"terminator\": \"\", \"c1\": c1, \"c2\": c2},\n )\n else:\n logger.info(s, extra={\"terminator\": \"\", \"c1\": \"\", \"c2\": \"\"})\n\n def display(self):\n \"\"\"\n Returns an execution status for the console, the progress bar, or the IDE output.\n\n :rtype: string\n \"\"\"\n col1 = Logs.colors(self.color)\n col2 = Logs.colors.NORMAL\n master = self.generator.bld.producer\n\n def cur():\n # the current task position, computed as late as possible\n return master.processed - master.ready.qsize()\n\n if self.generator.bld.progress_bar == 1:\n return self.generator.bld.progress_line(cur(), master.total, col1, col2)\n\n if self.generator.bld.progress_bar == 2:\n ela = str(self.generator.bld.timer)\n try:\n ins = \",\".join([n.name for n in self.inputs])\n except AttributeError:\n ins = \"\"\n try:\n outs = \",\".join([n.name for n in self.outputs])\n except AttributeError:\n outs = \"\"\n return f\"|Total {master.total}|Current {cur()}|Inputs {ins}|Outputs {outs}|Time {ela}|\\n\"\n\n s = str(self)\n if not s:\n return None\n\n total = master.total\n n = len(str(total))\n fs = \"[%%%dd/%%%dd] %%s%%s%%s%%s\\n\" % (n, n)\n kw = self.keyword()\n if kw:\n kw += \" \"\n return fs % (cur(), total, kw, col1, s, col2)\n\n def hash_constraints(self):\n \"\"\"\n Identifies a task type for all the constraints relevant for the scheduler: precedence, file production\n\n :return: a hash value\n :rtype: string\n \"\"\"\n return (\n tuple(self.before),\n tuple(self.after),\n tuple(self.ext_in),\n tuple(self.ext_out),\n self.__class__.__name__,\n self.hcode,\n )\n\n def format_error(self):\n \"\"\"\n Returns an error message to display the build failure reasons\n\n :rtype: string\n \"\"\"\n if Logs.verbose:\n msg = \": {!r}\\n{!r}\".format(self, getattr(self, \"last_cmd\", \"\"))\n else:\n msg = \" (run with -v to display more information)\"\n name = getattr(self.generator, \"name\", \"\")\n if getattr(self, \"err_msg\", None):\n return self.err_msg\n elif not self.hasrun:\n return f\"task in {name!r} was not executed for some reason: {self!r}\"\n elif self.hasrun == CRASHED:\n try:\n return f\" -> task in {name!r} failed with exit status {self.err_code!r}{msg}\"\n except AttributeError:\n return f\" -> task in {name!r} failed{msg}\"\n elif self.hasrun == MISSING:\n return f\" -> missing files in {name!r}{msg}\"\n elif self.hasrun == CANCELED:\n return \" -> %r canceled because of missing dependencies\" % name\n else:\n return f\"invalid status for task in {name!r}: {self.hasrun!r}\"\n\n def colon(self, var1, var2):\n \"\"\"\n Enable scriptlet expressions of the form ${FOO_ST:FOO}\n If the first variable (FOO_ST) is empty, then an empty list is returned\n\n The results will be slightly different if FOO_ST is a list, for example::\n\n env.FOO = ['p1', 'p2']\n env.FOO_ST = '-I%s'\n # ${FOO_ST:FOO} returns\n ['-Ip1', '-Ip2']\n\n env.FOO_ST = ['-a', '-b']\n # ${FOO_ST:FOO} returns\n ['-a', '-b', 'p1', '-a', '-b', 'p2']\n \"\"\"\n tmp = self.env[var1]\n if not tmp:\n return []\n\n if isinstance(var2, str):\n it = self.env[var2]\n else:\n it = var2\n if isinstance(tmp, str):\n return [tmp % x for x in it]\n else:\n lst = []\n for y in it:\n lst.extend(tmp)\n lst.append(y)\n return lst\n\n def __str__(self):\n \"string to display to the user\"\n name = self.__class__.__name__\n if self.outputs:\n if name.endswith((\"lib\", \"program\")) or not self.inputs:\n node = self.outputs[0]\n return node.path_from(node.ctx.launch_node())\n if not (self.inputs or self.outputs):\n return self.__class__.__name__\n if len(self.inputs) == 1:\n node = self.inputs[0]\n return node.path_from(node.ctx.launch_node())\n\n src_str = \" \".join([a.path_from(a.ctx.launch_node()) for a in self.inputs])\n tgt_str = \" \".join([a.path_from(a.ctx.launch_node()) for a in self.outputs])\n if self.outputs:\n sep = \" -> \"\n else:\n sep = \"\"\n return f\"{self.__class__.__name__}: {src_str}{sep}{tgt_str}\"\n\n def keyword(self):\n \"Display keyword used to prettify the console outputs\"\n name = self.__class__.__name__\n if name.endswith((\"lib\", \"program\")):\n return \"Linking\"\n if len(self.inputs) == 1 and len(self.outputs) == 1:\n return \"Compiling\"\n if not self.inputs:\n if self.outputs:\n return \"Creating\"\n else:\n return \"Running\"\n return \"Processing\"\n\n def __repr__(self):\n \"for debugging purposes\"\n try:\n ins = \",\".join([x.name for x in self.inputs])\n outs = \",\".join([x.name for x in self.outputs])\n except AttributeError:\n ins = \",\".join([str(x) for x in self.inputs])\n outs = \",\".join([str(x) for x in self.outputs])\n return \"\".join(\n [\n \"\\n\\t{task %r: \" % id(self),\n self.__class__.__name__,\n \" \",\n ins,\n \" -> \",\n outs,\n \"}\",\n ]\n )\n\n def uid(self):\n \"\"\"\n Returns an identifier used to determine if tasks are up-to-date. Since the\n identifier will be stored between executions, it must be:\n\n - unique for a task: no two tasks return the same value (for a given build context)\n - the same for a given task instance\n\n By default, the node paths, the class name, and the function are used\n as inputs to compute a hash.\n\n The pointer to the object (python built-in 'id') will change between build executions,\n and must be avoided in such hashes.\n\n :return: hash value\n :rtype: string\n \"\"\"\n try:\n return self.uid_\n except AttributeError:\n m = Utils.md5(self.__class__.__name__)\n up = m.update\n for x in self.inputs + self.outputs:\n up(x.abspath())\n self.uid_ = m.digest()\n return self.uid_\n\n def set_inputs(self, inp):\n \"\"\"\n Appends the nodes to the *inputs* list\n\n :param inp: input nodes\n :type inp: node or list of nodes\n \"\"\"\n if isinstance(inp, list):\n self.inputs += inp\n else:\n self.inputs.append(inp)\n\n def set_outputs(self, out):\n \"\"\"\n Appends the nodes to the *outputs* list\n\n :param out: output nodes\n :type out: node or list of nodes\n \"\"\"\n if isinstance(out, list):\n self.outputs += out\n else:\n self.outputs.append(out)\n\n def set_run_after(self, task):\n \"\"\"\n Run this task only after the given *task*.\n\n :param task: task\n :type task: :py:class:`waflib.Task.Task`\n \"\"\"\n assert isinstance(task, Task)\n self.run_after.add(task)\n\n def signature(self):\n \"\"\"\n Task signatures are stored between build executions, they are use to track the changes\n made to the input nodes (not to the outputs!). The signature hashes data from various sources:\n\n * explicit dependencies: files listed in the inputs (list of node objects) :py:meth:`waflib.Task.Task.sig_explicit_deps`\n * implicit dependencies: list of nodes returned by scanner methods (when present) :py:meth:`waflib.Task.Task.sig_implicit_deps`\n * hashed data: variables/values read from task.vars/task.env :py:meth:`waflib.Task.Task.sig_vars`\n\n If the signature is expected to give a different result, clear the cache kept in ``self.cache_sig``::\n\n from waflib import Task\n class cls(Task.Task):\n def signature(self):\n sig = super(Task.Task, self).signature()\n delattr(self, 'cache_sig')\n return super(Task.Task, self).signature()\n\n :return: the signature value\n :rtype: string or bytes\n \"\"\"\n try:\n return self.cache_sig\n except AttributeError:\n pass\n\n self.m = Utils.md5(self.hcode)\n\n # explicit deps\n self.sig_explicit_deps()\n\n # env vars\n self.sig_vars()\n\n # implicit deps / scanner results\n if self.scan:\n try:\n self.sig_implicit_deps()\n except Errors.TaskRescan:\n return self.signature()\n\n ret = self.cache_sig = self.m.digest()\n return ret\n\n def runnable_status(self):\n \"\"\"\n Returns the Task status\n\n :return: a task state in :py:const:`waflib.Task.RUN_ME`,\n :py:const:`waflib.Task.SKIP_ME`, :py:const:`waflib.Task.CANCEL_ME` or :py:const:`waflib.Task.ASK_LATER`.\n :rtype: int\n \"\"\"\n bld = self.generator.bld\n if bld.is_install < 0:\n return SKIP_ME\n\n for t in self.run_after:\n if not t.hasrun:\n return ASK_LATER\n elif t.hasrun < SKIPPED:\n # a dependency has an error\n return CANCEL_ME\n\n # first compute the signature\n try:\n new_sig = self.signature()\n except Errors.TaskNotReady:\n return ASK_LATER\n\n # compare the signature to a signature computed previously\n key = self.uid()\n try:\n prev_sig = bld.task_sigs[key]\n except KeyError:\n Logs.debug(\n \"task: task %r must run: it was never run before or the task code changed\",\n self,\n )\n return RUN_ME\n\n if new_sig != prev_sig:\n Logs.debug(\"task: task %r must run: the task signature changed\", self)\n return RUN_ME\n\n # compare the signatures of the outputs\n for node in self.outputs:\n sig = bld.node_sigs.get(node)\n if not sig:\n Logs.debug(\n \"task: task %r must run: an output node has no signature\", self\n )\n return RUN_ME\n if sig != key:\n Logs.debug(\n \"task: task %r must run: an output node was produced by another task\",\n self,\n )\n return RUN_ME\n if not node.exists():\n Logs.debug(\n \"task: task %r must run: an output node does not exist\", self\n )\n return RUN_ME\n\n return (self.always_run and RUN_ME) or SKIP_ME\n\n def post_run(self):\n \"\"\"\n Called after successful execution to record that the task has run by\n updating the entry in :py:attr:`waflib.Build.BuildContext.task_sigs`.\n \"\"\"\n bld = self.generator.bld\n for node in self.outputs:\n if not node.exists():\n self.hasrun = MISSING\n self.err_msg = \"-> missing file: %r\" % node.abspath()\n raise Errors.WafError(self.err_msg)\n bld.node_sigs[\n node\n ] = self.uid() # make sure this task produced the files in question\n bld.task_sigs[self.uid()] = self.signature()\n if not self.keep_last_cmd:\n try:\n del self.last_cmd\n except AttributeError:\n pass\n\n def sig_explicit_deps(self):\n \"\"\"\n Used by :py:meth:`waflib.Task.Task.signature`; it hashes :py:attr:`waflib.Task.Task.inputs`\n and :py:attr:`waflib.Task.Task.dep_nodes` signatures.\n \"\"\"\n bld = self.generator.bld\n upd = self.m.update\n\n # the inputs\n for x in self.inputs + self.dep_nodes:\n upd(x.get_bld_sig())\n\n # manual dependencies, they can slow down the builds\n if bld.deps_man:\n additional_deps = bld.deps_man\n for x in self.inputs + self.outputs:\n try:\n d = additional_deps[x]\n except KeyError:\n continue\n\n for v in d:\n try:\n v = v.get_bld_sig()\n except AttributeError:\n if hasattr(v, \"__call__\"):\n v = v() # dependency is a function, call it\n upd(v)\n\n def sig_deep_inputs(self):\n \"\"\"\n Enable rebuilds on input files task signatures. Not used by default.\n\n Example: hashes of output programs can be unchanged after being re-linked,\n despite the libraries being different. This method can thus prevent stale unit test\n results (waf_unit_test.py).\n\n Hashing input file timestamps is another possibility for the implementation.\n This may cause unnecessary rebuilds when input tasks are frequently executed.\n Here is an implementation example::\n\n lst = []\n for node in self.inputs + self.dep_nodes:\n st = os.stat(node.abspath())\n lst.append(st.st_mtime)\n lst.append(st.st_size)\n self.m.update(Utils.h_list(lst))\n\n The downside of the implementation is that it absolutely requires all build directory\n files to be declared within the current build.\n \"\"\"\n bld = self.generator.bld\n lst = [\n bld.task_sigs[bld.node_sigs[node]]\n for node in (self.inputs + self.dep_nodes)\n if node.is_bld()\n ]\n self.m.update(Utils.h_list(lst))\n\n def sig_vars(self):\n \"\"\"\n Used by :py:meth:`waflib.Task.Task.signature`; it hashes :py:attr:`waflib.Task.Task.env` variables/values\n \"\"\"\n sig = self.generator.bld.hash_env_vars(self.env, self.vars)\n self.m.update(sig)\n\n scan = None\n \"\"\"\n\tThis method, when provided, returns a tuple containing:\n\n\t* a list of nodes corresponding to real files\n\t* a list of names for files not found in path_lst\n\n\tFor example::\n\n\t\tfrom waflib.Task import Task\n\t\tclass mytask(Task):\n\t\t\tdef scan(self, node):\n\t\t\t\treturn ([], [])\n\n\tThe first and second lists in the tuple are stored in :py:attr:`waflib.Build.BuildContext.node_deps` and\n\t:py:attr:`waflib.Build.BuildContext.raw_deps` respectively.\n\t\"\"\"\n\n def sig_implicit_deps(self):\n \"\"\"\n Used by :py:meth:`waflib.Task.Task.signature`; it hashes node signatures\n obtained by scanning for dependencies (:py:meth:`waflib.Task.Task.scan`).\n\n The exception :py:class:`waflib.Errors.TaskRescan` is thrown\n when a file has changed. In this case, the method :py:meth:`waflib.Task.Task.signature` is called\n once again, and return here to call :py:meth:`waflib.Task.Task.scan` and searching for dependencies.\n \"\"\"\n bld = self.generator.bld\n\n # get the task signatures from previous runs\n key = self.uid()\n prev = bld.imp_sigs.get(key, [])\n\n # for issue #379\n if prev:\n try:\n if prev == self.compute_sig_implicit_deps():\n return prev\n except Errors.TaskNotReady:\n raise\n except OSError:\n # when a file was renamed, remove the stale nodes (headers in folders without source files)\n # this will break the order calculation for headers created during the build in the source directory (should be uncommon)\n # the behaviour will differ when top != out\n for x in bld.node_deps.get(self.uid(), []):\n if not x.is_bld() and not x.exists():\n try:\n del x.parent.children[x.name]\n except KeyError:\n pass\n del bld.imp_sigs[key]\n raise Errors.TaskRescan(\"rescan\")\n\n # no previous run or the signature of the dependencies has changed, rescan the dependencies\n (bld.node_deps[key], bld.raw_deps[key]) = self.scan()\n if Logs.verbose:\n Logs.debug(\n \"deps: scanner for %s: %r; unresolved: %r\",\n self,\n bld.node_deps[key],\n bld.raw_deps[key],\n )\n\n # recompute the signature and return it\n try:\n bld.imp_sigs[key] = self.compute_sig_implicit_deps()\n except OSError:\n for k in bld.node_deps.get(self.uid(), []):\n if not k.exists():\n Logs.warn(\n \"Dependency %r for %r is missing: check the task declaration and the build order!\",\n k,\n self,\n )\n raise\n\n def compute_sig_implicit_deps(self):\n \"\"\"\n Used by :py:meth:`waflib.Task.Task.sig_implicit_deps` for computing the actual hash of the\n :py:class:`waflib.Node.Node` returned by the scanner.\n\n :return: a hash value for the implicit dependencies\n :rtype: string or bytes\n \"\"\"\n upd = self.m.update\n self.are_implicit_nodes_ready()\n\n # scanner returns a node that does not have a signature\n # just *ignore* the error and let them figure out from the compiler output\n # waf -k behaviour\n for k in self.generator.bld.node_deps.get(self.uid(), []):\n upd(k.get_bld_sig())\n return self.m.digest()\n\n def are_implicit_nodes_ready(self):\n \"\"\"\n For each node returned by the scanner, see if there is a task that creates it,\n and infer the build order\n\n This has a low performance impact on null builds (1.86s->1.66s) thanks to caching (28s->1.86s)\n \"\"\"\n bld = self.generator.bld\n try:\n cache = bld.dct_implicit_nodes\n except AttributeError:\n bld.dct_implicit_nodes = cache = {}\n\n # one cache per build group\n try:\n dct = cache[bld.current_group]\n except KeyError:\n dct = cache[bld.current_group] = {}\n for tsk in bld.cur_tasks:\n for x in tsk.outputs:\n dct[x] = tsk\n\n modified = False\n for x in bld.node_deps.get(self.uid(), []):\n if x in dct:\n self.run_after.add(dct[x])\n modified = True\n\n if modified:\n for tsk in self.run_after:\n if not tsk.hasrun:\n # print \"task is not ready...\"\n raise Errors.TaskNotReady(\"not ready\")\n\n\nif sys.hexversion > 0x3000000:\n\n def uid(self):\n try:\n return self.uid_\n except AttributeError:\n m = Utils.md5(\n self.__class__.__name__.encode(\"latin-1\", \"xmlcharrefreplace\")\n )\n up = m.update\n for x in self.inputs + self.outputs:\n up(x.abspath().encode(\"latin-1\", \"xmlcharrefreplace\"))\n self.uid_ = m.digest()\n return self.uid_\n\n uid.__doc__ = Task.uid.__doc__\n Task.uid = uid\n\n\ndef is_before(t1, t2):\n \"\"\"\n Returns a non-zero value if task t1 is to be executed before task t2::\n\n t1.ext_out = '.h'\n t2.ext_in = '.h'\n t2.after = ['t1']\n t1.before = ['t2']\n waflib.Task.is_before(t1, t2) # True\n\n :param t1: Task object\n :type t1: :py:class:`waflib.Task.Task`\n :param t2: Task object\n :type t2: :py:class:`waflib.Task.Task`\n \"\"\"\n to_list = Utils.to_list\n for k in to_list(t2.ext_in):\n if k in to_list(t1.ext_out):\n return 1\n\n if t1.__class__.__name__ in to_list(t2.after):\n return 1\n\n if t2.__class__.__name__ in to_list(t1.before):\n return 1\n\n return 0\n\n\ndef set_file_constraints(tasks):\n \"\"\"\n Updates the ``run_after`` attribute of all tasks based on the task inputs and outputs\n\n :param tasks: tasks\n :type tasks: list of :py:class:`waflib.Task.Task`\n \"\"\"\n ins = Utils.defaultdict(set)\n outs = Utils.defaultdict(set)\n for x in tasks:\n for a in x.inputs:\n ins[a].add(x)\n for a in x.dep_nodes:\n ins[a].add(x)\n for a in x.outputs:\n outs[a].add(x)\n\n links = set(ins.keys()).intersection(outs.keys())\n for k in links:\n for a in ins[k]:\n a.run_after.update(outs[k])\n\n\nclass TaskGroup:\n \"\"\"\n Wrap nxm task order constraints into a single object\n to prevent the creation of large list/set objects\n\n This is an optimization\n \"\"\"\n\n def __init__(self, prev, next):\n self.prev = prev\n self.next = next\n self.done = False\n\n def get_hasrun(self):\n for k in self.prev:\n if not k.hasrun:\n return NOT_RUN\n return SUCCESS\n\n hasrun = property(get_hasrun, None)\n\n\ndef set_precedence_constraints(tasks):\n \"\"\"\n Updates the ``run_after`` attribute of all tasks based on the after/before/ext_out/ext_in attributes\n\n :param tasks: tasks\n :type tasks: list of :py:class:`waflib.Task.Task`\n \"\"\"\n cstr_groups = Utils.defaultdict(list)\n for x in tasks:\n h = x.hash_constraints()\n cstr_groups[h].append(x)\n\n keys = list(cstr_groups.keys())\n maxi = len(keys)\n\n # this list should be short\n for i in range(maxi):\n t1 = cstr_groups[keys[i]][0]\n for j in range(i + 1, maxi):\n t2 = cstr_groups[keys[j]][0]\n\n # add the constraints based on the comparisons\n if is_before(t1, t2):\n a = i\n b = j\n elif is_before(t2, t1):\n a = j\n b = i\n else:\n continue\n\n a = cstr_groups[keys[a]]\n b = cstr_groups[keys[b]]\n\n if len(a) < 2 or len(b) < 2:\n for x in b:\n x.run_after.update(a)\n else:\n group = TaskGroup(set(a), set(b))\n for x in b:\n x.run_after.add(group)\n\n\ndef funex(c):\n \"\"\"\n Compiles a scriptlet expression into a Python function\n\n :param c: function to compile\n :type c: string\n :return: the function 'f' declared in the input string\n :rtype: function\n \"\"\"\n dc = {}\n exec(c, dc)\n return dc[\"f\"]\n\n\nre_cond = re.compile(r\"(?P\\w+)|(?P\\|)|(?P&)\")\nre_novar = re.compile(r\"^(SRC|TGT)\\W+.*?$\")\nreg_act = re.compile(\n r\"(?P\\\\)|(?P\\$\\$)|(?P\\$\\{(?P\\w+)(?P.*?)\\})\",\n re.M,\n)\n\n\ndef compile_fun_shell(line):\n \"\"\"\n Creates a compiled function to execute a process through a sub-shell\n \"\"\"\n extr = []\n\n def repl(match):\n g = match.group\n if g(\"dollar\"):\n return \"$\"\n elif g(\"backslash\"):\n return \"\\\\\\\\\"\n elif g(\"subst\"):\n extr.append((g(\"var\"), g(\"code\")))\n return \"%s\"\n return None\n\n line = reg_act.sub(repl, line) or line\n dvars = []\n\n def replc(m):\n # performs substitutions and populates dvars\n if m.group(\"and\"):\n return \" and \"\n elif m.group(\"or\"):\n return \" or \"\n else:\n x = m.group(\"var\")\n if x not in dvars:\n dvars.append(x)\n return \"env[%r]\" % x\n\n parm = []\n app = parm.append\n for (var, meth) in extr:\n if var == \"SRC\":\n if meth:\n app(\"tsk.inputs%s\" % meth)\n else:\n app('\" \".join([a.path_from(cwdx) for a in tsk.inputs])')\n elif var == \"TGT\":\n if meth:\n app(\"tsk.outputs%s\" % meth)\n else:\n app('\" \".join([a.path_from(cwdx) for a in tsk.outputs])')\n elif meth:\n if meth.startswith(\":\"):\n if var not in dvars:\n dvars.append(var)\n m = meth[1:]\n if m == \"SRC\":\n m = \"[a.path_from(cwdx) for a in tsk.inputs]\"\n elif m == \"TGT\":\n m = \"[a.path_from(cwdx) for a in tsk.outputs]\"\n elif re_novar.match(m):\n m = \"[tsk.inputs%s]\" % m[3:]\n elif re_novar.match(m):\n m = \"[tsk.outputs%s]\" % m[3:]\n elif m[:3] not in (\"tsk\", \"gen\", \"bld\"):\n dvars.append(meth[1:])\n m = \"%r\" % m\n app(f'\" \".join(tsk.colon({var!r}, {m}))')\n elif meth.startswith(\"?\"):\n # In A?B|C output env.A if one of env.B or env.C is non-empty\n expr = re_cond.sub(replc, meth[1:])\n app(f'p({var!r}) if ({expr}) else \"\"')\n else:\n app(f\"{var}{meth}\")\n else:\n if var not in dvars:\n dvars.append(var)\n app(\"p('%s')\" % var)\n if parm:\n parm = \"%% (%s) \" % (\",\\n\\t\\t\".join(parm))\n else:\n parm = \"\"\n\n c = COMPILE_TEMPLATE_SHELL % (line, parm)\n Logs.debug(\"action: %s\", c.strip().splitlines())\n return (funex(c), dvars)\n\n\nreg_act_noshell = re.compile(\n r\"(?P\\s+)|(?P\\$\\{(?P\\w+)(?P.*?)\\})|(?P([^$ \\t\\n\\r\\f\\v]|\\$\\$)+)\",\n re.M,\n)\n\n\ndef compile_fun_noshell(line):\n \"\"\"\n Creates a compiled function to execute a process without a sub-shell\n \"\"\"\n buf = []\n dvars = []\n merge = False\n app = buf.append\n\n def replc(m):\n # performs substitutions and populates dvars\n if m.group(\"and\"):\n return \" and \"\n elif m.group(\"or\"):\n return \" or \"\n else:\n x = m.group(\"var\")\n if x not in dvars:\n dvars.append(x)\n return \"env[%r]\" % x\n\n for m in reg_act_noshell.finditer(line):\n if m.group(\"space\"):\n merge = False\n continue\n elif m.group(\"text\"):\n app(\"[%r]\" % m.group(\"text\").replace(\"$$\", \"$\"))\n elif m.group(\"subst\"):\n var = m.group(\"var\")\n code = m.group(\"code\")\n if var == \"SRC\":\n if code:\n app(\"[tsk.inputs%s]\" % code)\n else:\n app(\"[a.path_from(cwdx) for a in tsk.inputs]\")\n elif var == \"TGT\":\n if code:\n app(\"[tsk.outputs%s]\" % code)\n else:\n app(\"[a.path_from(cwdx) for a in tsk.outputs]\")\n elif code:\n if code.startswith(\":\"):\n # a composed variable ${FOO:OUT}\n if not var in dvars:\n dvars.append(var)\n m = code[1:]\n if m == \"SRC\":\n m = \"[a.path_from(cwdx) for a in tsk.inputs]\"\n elif m == \"TGT\":\n m = \"[a.path_from(cwdx) for a in tsk.outputs]\"\n elif re_novar.match(m):\n m = \"[tsk.inputs%s]\" % m[3:]\n elif re_novar.match(m):\n m = \"[tsk.outputs%s]\" % m[3:]\n elif m[:3] not in (\"tsk\", \"gen\", \"bld\"):\n dvars.append(m)\n m = \"%r\" % m\n app(f\"tsk.colon({var!r}, {m})\")\n elif code.startswith(\"?\"):\n # In A?B|C output env.A if one of env.B or env.C is non-empty\n expr = re_cond.sub(replc, code[1:])\n app(f\"to_list(env[{var!r}] if ({expr}) else [])\")\n else:\n # plain code such as ${tsk.inputs[0].abspath()}\n app(f\"gen.to_list({var}{code})\")\n else:\n # a plain variable such as # a plain variable like ${AR}\n app(\"to_list(env[%r])\" % var)\n if not var in dvars:\n dvars.append(var)\n if merge:\n tmp = \"merge({}, {})\".format(buf[-2], buf[-1])\n del buf[-1]\n buf[-1] = tmp\n merge = True # next turn\n\n buf = [\"lst.extend(%s)\" % x for x in buf]\n fun = COMPILE_TEMPLATE_NOSHELL % \"\\n\\t\".join(buf)\n Logs.debug(\"action: %s\", fun.strip().splitlines())\n return (funex(fun), dvars)\n\n\ndef compile_fun(line, shell=False):\n \"\"\"\n Parses a string expression such as '${CC} ${SRC} -o ${TGT}' and returns a pair containing:\n\n * The function created (compiled) for use as :py:meth:`waflib.Task.Task.run`\n * The list of variables that must cause rebuilds when *env* data is modified\n\n for example::\n\n from waflib.Task import compile_fun\n compile_fun('cxx', '${CXX} -o ${TGT[0]} ${SRC} -I ${SRC[0].parent.bldpath()}')\n\n def build(bld):\n bld(source='wscript', rule='echo \"foo\\\\${SRC[0].name}\\\\bar\"')\n\n The env variables (CXX, ..) on the task must not hold dicts so as to preserve a consistent order.\n The reserved keywords ``TGT`` and ``SRC`` represent the task input and output nodes\n\n \"\"\"\n if isinstance(line, str):\n if line.find(\"<\") > 0 or line.find(\">\") > 0 or line.find(\"&&\") > 0:\n shell = True\n else:\n dvars_lst = []\n funs_lst = []\n for x in line:\n if isinstance(x, str):\n fun, dvars = compile_fun(x, shell)\n dvars_lst += dvars\n funs_lst.append(fun)\n else:\n # assume a function to let through\n funs_lst.append(x)\n\n def composed_fun(task):\n for x in funs_lst:\n ret = x(task)\n if ret:\n return ret\n return None\n\n return composed_fun, dvars_lst\n if shell:\n return compile_fun_shell(line)\n else:\n return compile_fun_noshell(line)\n\n\ndef task_factory(\n name,\n func=None,\n vars=None,\n color=\"GREEN\",\n ext_in=[],\n ext_out=[],\n before=[],\n after=[],\n shell=False,\n scan=None,\n):\n \"\"\"\n Returns a new task subclass with the function ``run`` compiled from the line given.\n\n :param func: method run\n :type func: string or function\n :param vars: list of variables to hash\n :type vars: list of string\n :param color: color to use\n :type color: string\n :param shell: when *func* is a string, enable/disable the use of the shell\n :type shell: bool\n :param scan: method scan\n :type scan: function\n :rtype: :py:class:`waflib.Task.Task`\n \"\"\"\n\n params = {\n \"vars\": vars\n or [], # function arguments are static, and this one may be modified by the class\n \"color\": color,\n \"name\": name,\n \"shell\": shell,\n \"scan\": scan,\n }\n\n if isinstance(func, str) or isinstance(func, tuple):\n params[\"run_str\"] = func\n else:\n params[\"run\"] = func\n\n cls = type(Task)(name, (Task,), params)\n classes[name] = cls\n\n if ext_in:\n cls.ext_in = Utils.to_list(ext_in)\n if ext_out:\n cls.ext_out = Utils.to_list(ext_out)\n if before:\n cls.before = Utils.to_list(before)\n if after:\n cls.after = Utils.to_list(after)\n\n return cls\n\n\ndef deep_inputs(cls):\n \"\"\"\n Task class decorator to enable rebuilds on input files task signatures\n \"\"\"\n\n def sig_explicit_deps(self):\n Task.sig_explicit_deps(self)\n Task.sig_deep_inputs(self)\n\n cls.sig_explicit_deps = sig_explicit_deps\n return cls\n\n\nTaskBase = Task\n\"Provided for compatibility reasons, TaskBase should not be used\"\n","sub_path":"docs/.mywaflib/waflib/Task.py","file_name":"Task.py","file_ext":"py","file_size_in_byte":44305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"300230983","text":"#!/usr/bin/env python3\n\nimport os\nimport glob\n\n## == Constant Definitions ==##\nTAB = \" \" * 4\n\ntop_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\"))\n\ndef guess_solib_dir():\n dirs = glob.glob(os.path.join(top_dir, \"bazel-bin/_solib_*\"))\n assert len(dirs) == 1, \"Only one _solib_* directory under bazel-bin is expected\"\n return dirs[0]\n\nsolib_dir = guess_solib_dir()\n\ndef install_local_solibs():\n relative_dir = solib_dir[len(top_dir)+1:]\n for lib in os.listdir(solib_dir):\n if os.path.isfile(os.path.join(solib_dir, lib)):\n print(\"{}install(\\\"{}/{}\\\", \\\"lib/{}\\\")\".format(TAB, relative_dir, lib, lib))\n\ndef install_data(src, dst):\n print(\"{}install(\\\"{}\\\", \\\"{}\\\")\".format(TAB, src, dst))\n \ndef install_cyber():\n cyber_conf = \"cyber/conf/cyber.pb.conf\"\n install_data(cyber_conf, cyber_conf)\n dreamview_conf = \"cyber/conf/dreamview_sched.conf\"\n install_data(dreamview_conf, dreamview_conf)\n install_data(\"bazel-bin/cyber/mainboard/mainboard\", \"bin/mainboard\")\n\ndef install_cyber_examples():\n # Common Component Example\n install_data(\"bazel-bin/cyber/examples/common_component_example/libcommon_component_example.so\",\n \"cyber/examples/common_component_example/libcommon_component_example.so\")\n install_data(\"cyber/examples/common_component_example/common.dag\", \"cyber/examples/common_component_example/common.dag\")\n install_data(\"cyber/examples/common_component_example/common.launch\", \"cyber/examples/common_component_example/common.launch\")\n\n # Timer Component Example\n install_data(\"bazel-bin/cyber/examples/timer_component_example/libtimer_component_example.so\", \"cyber/examples/timer_component_example/libtimer_component_example.so\")\n install_data(\"cyber/examples/timer_component_example/timer.dag\", \"cyber/examples/timer_component_example/timer.dag\")\n install_data(\"cyber/examples/timer_component_example/timer.launch\", \"cyber/examples/timer_component_example/timer.launch\")\n\ndef main():\n install_local_solibs()\n install_cyber()\n install_cyber_examples()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/install/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"437297294","text":"import csv\nimport os\n\ndef WriteDictToCSV(csv_file,csv_columns,dict_data):\n with open(csv_file, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=csv_columns)\n writer.writeheader()\n for data in dict_data:\n writer.writerow(data)\n return\n\n","sub_path":"elev/toCsv.py","file_name":"toCsv.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"426899757","text":"import logging\n\n\n# included commands\nCOMMANDS = ['backup']\n\n\n# Log file destination, absolute or relative to execution\nLOG_FILE = 'capnflint.log'\n# Writes log to file if True\nLOG_TO_FILE = True\n# Writes log to error console if True\nLOG_TO_STDERR = True\n# Ignore log levels below this. Available: DEBUG, INFO, WARNING, ERROR, CRITICAL\nLOG_LEVEL = logging.INFO\n# Prefix for log lines. See `logging` module documentation for details.\nLOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'\n","sub_path":"default_config.py","file_name":"default_config.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"181019807","text":"#!/usr/bin/env python3\nimport json\nimport os\nimport re\nfrom random import randint\n\nimport gspread\nfrom discord import Embed\nfrom gspread.utils import fill_gaps\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n# https://gspread.readthedocs.io\n# https://towardsdatascience.com/accessing-google-spreadsheet-data-using-python-90a5bc214fd2\n# https://medium.com/datadriveninvestor/use-google-sheets-as-your-database-using-python-77d40009860f\n\nBASE_DIR = os.path.dirname(os.path.realpath(__file__))\nDATA_PATH = os.path.join(BASE_DIR, 'data')\n\nGG_DOCS = {\n 'en': {\n 'url': 'https://docs.google.com/spreadsheets/d/1QjRrz_i6MRHQNPQfI_1kyg4flyKw67Hj9lUIFyUbE64',\n 'target': 'Skill & Unique Equipment',\n },\n 'vi': {\n 'url': 'https://docs.google.com/spreadsheets/d/183GENxcV-LWzwZvnkOMBWiAfU__RJpLH1pp-sD7PZR8',\n 'target': 'Đây là một danh sách',\n },\n}\n\nscopes = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n\nSERVICE_ACCOUNT_CREDENTIALS = os.environ.get('SERVICE_ACCOUNT_CREDENTIALS', None)\n\n\ndef _get_client():\n if SERVICE_ACCOUNT_CREDENTIALS and isinstance(SERVICE_ACCOUNT_CREDENTIALS, str):\n json_credential = json.loads(SERVICE_ACCOUNT_CREDENTIALS)\n credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_credential, scopes=scopes)\n else:\n credentials = ServiceAccountCredentials.from_json_keyfile_name('pricone-bot-d3f8d759f493.json', scopes=scopes)\n return gspread.authorize(credentials)\n\n\nclass Skill:\n _name = 'Unknown'\n _description = None\n\n def __init__(self, name, description=None):\n self.name = name\n self.description = description\n\n @property\n def name(self):\n name = self._name if self._name else 'Unknown'\n return '{}'.format(name)\n\n @name.setter\n def name(self, name):\n self._name = re.sub(r'\\n', '. ', '{}'.format(name))\n\n @property\n def description(self):\n description = self._description if self._description else 'Unknown'\n return '{}.'.format(description.rstrip('.'))\n\n @description.setter\n def description(self, description):\n self._description = re.sub(r'\\n', '. ', '{}'.format(description))\n\n @property\n def json(self):\n return {\n 'name': self.name,\n 'description': self.description,\n }\n\n def __str__(self):\n return self.name\n\n\nclass Character:\n name = 'Unknown'\n katakana = None\n image_url = None\n note = None\n gamewith_url = None\n\n def __init__(self):\n self.ub = Skill('Unknown')\n self.skill_1 = Skill('Unknown')\n self.skill_2 = Skill('Unknown')\n self.skill_ex = Skill('Unknown')\n self.skill_enc = Skill('Unknown')\n\n @property\n def colour(self):\n return randint(0, 0xffffff)\n\n def __str__(self):\n return self.name\n\n\nclass Character_EN(Character):\n unique_equipment = ''\n base_rarity = '1*'\n position = 'Front'\n attack_type = 'Physical'\n\n @property\n def star(self):\n total_star = ''\n for _star in range(int(self.base_rarity.replace('*', ''))):\n total_star += ':star2:'\n return total_star\n\n @property\n def discord_msg(self):\n msg = ''\n msg += '**{}** ({}) {}\\n'.format(self.name, self.katakana, self.star)\n msg += '> **Position:** {}.\\n'.format(self.position)\n msg += '> **Attack Type:** {}.\\n'.format(self.attack_type)\n msg += '> **UB ({}):** {}\\n'.format(self.ub.name, self.ub.description)\n msg += '> **Skill 1 ({}):** {}\\n'.format(self.skill_1.name, self.skill_1.description)\n msg += '> **Skill 2 ({}):** {}\\n'.format(self.skill_2.name, self.skill_2.description)\n msg += '> **Ex Skill ({}):** {}\\n'.format(self.skill_ex.name, self.skill_ex.description)\n if self.skill_enc.name != '' and self.skill_enc.name != 'Unknown':\n msg += '> **Enhanced Skill ({}):** {}\\n'.format(self.skill_enc.name, self.skill_enc.description)\n if self.note and self.gamewith_url not in self.note:\n msg += '> **Notes:**\\n'\n for note in self.note.split('\\n'):\n msg += '>\\t{}\\n'.format(note)\n msg = '{}'.format(msg.strip())\n if self.gamewith_url:\n msg = '{}\\n{}'.format(msg, self.gamewith_url)\n return [msg]\n\n @property\n def discord_embed(self):\n embed = Embed(title='{} ({}) {}'.format(self.name, self.katakana, self.star), colour=self.colour)\n if self.gamewith_url:\n embed.url = self.gamewith_url\n if self.image_url:\n embed.set_thumbnail(url=self.image_url)\n embed.add_field(name='Position', value=self.position)\n embed.add_field(name='Attack Type', value=self.attack_type)\n embed.add_field(name='> UB ({})'.format(self.ub.name), value=self.ub.description)\n embed.add_field(name='> Skill 1 ({})'.format(self.skill_1.name), value=self.skill_1.description)\n embed.add_field(name='> Skill 2 ({})'.format(self.skill_2.name), value=self.skill_2.description)\n embed.add_field(name='> Ex Skill ({})'.format(self.skill_ex.name), value=self.skill_ex.description)\n if self.skill_enc.name != '' and self.skill_enc.name != 'Unknown':\n embed.add_field(name='> Enhanced Skill ({})'.format(self.skill_enc.name), value=self.skill_enc.description)\n if self.unique_equipment:\n embed.add_field(name='Unique Equipment', value='True')\n embed.set_image(url=self.unique_equipment)\n if self.note and self.gamewith_url not in self.note:\n embed.add_field(name='Notes', value='{}'.format(self.note))\n return embed\n\n\nclass Character_VI(Character):\n @property\n def json(self):\n return {\n 'Tên': self.name,\n 'gamewith.jp URL': self.gamewith_url,\n 'UB': self.ub.json,\n 'Skill 1': self.skill_1.json,\n 'Skill 2': self.skill_2.json,\n 'Ex skill (+)': self.skill_ex.json,\n 'Enhanced Skill 1 (+)': self.skill_enc.json,\n 'Note': self.note,\n }\n\n @property\n def discord_msg(self):\n msg = ''\n msg += '**{}**\\n'.format(self.name)\n msg += '> **UB ({}):** {}\\n'.format(self.ub.name, self.ub.description)\n msg += '> **Skill 1 ({}):** {}\\n'.format(self.skill_1.name, self.skill_1.description)\n msg += '> **Skill 2 ({}):** {}\\n'.format(self.skill_2.name, self.skill_2.description)\n msg += '> **Ex Skill ({}):** {}\\n'.format(self.skill_ex.name, self.skill_ex.description)\n if self.skill_enc.name != '' and self.skill_enc.name != 'Unknown':\n msg += '> **Enhanced Skill ({}):** {}\\n'.format(self.skill_enc.name, self.skill_enc.description)\n if self.note and self.gamewith_url not in self.note:\n msg += '> **Notes:**\\n'\n for note in self.note.split('\\n'):\n msg += '>\\t{}\\n'.format(note)\n msg = '{}'.format(msg.strip())\n if self.gamewith_url:\n msg = '{}\\n{}'.format(msg, self.gamewith_url)\n return [msg]\n\n @property\n def discord_embed(self):\n embed = Embed(title=self.name, colour=self.colour)\n if self.gamewith_url:\n embed.url = self.gamewith_url\n if self.image_url:\n embed.set_thumbnail(url=self.image_url)\n embed.add_field(name='> UB ({})'.format(self.ub.name), value=self.ub.description)\n embed.add_field(name='> Skill 1 ({})'.format(self.skill_1.name), value=self.skill_1.description)\n embed.add_field(name='> Skill 2 ({})'.format(self.skill_2.name), value=self.skill_2.description)\n embed.add_field(name='> Ex Skill ({})'.format(self.skill_ex.name), value=self.skill_ex.description)\n if self.skill_enc.name != '' and self.skill_enc.name != 'Unknown':\n embed.add_field(name='> Enhanced Skill ({})'.format(self.skill_enc.name), value=self.skill_enc.description)\n if self.note and self.gamewith_url not in self.note:\n embed.add_field(name='Notes', value='{}'.format(self.note))\n return embed\n\n\ndef write_data(overwrite=True):\n print('overwrite {}'.format(overwrite))\n if not os.path.isdir(DATA_PATH):\n os.mkdir(DATA_PATH)\n gc = _get_client()\n for GG_DOC in list(GG_DOCS):\n folder_path = os.path.join(DATA_PATH, GG_DOC)\n print(folder_path)\n if not os.path.isdir(folder_path):\n os.mkdir(folder_path)\n sheets = gc.open_by_url(GG_DOCS[GG_DOC]['url'])\n worksheets = sheets.worksheets()\n for worksheet in worksheets:\n worksheet_title = worksheet.title\n if '{}'.format(worksheet_title).lower() == '{}'.format(GG_DOCS[GG_DOC]['target']).lower():\n # list_of_lists = worksheet.get_all_values()\n value_render_option = 'FORMULA'\n data = worksheet.spreadsheet.values_get(\n worksheet_title,\n params={'valueRenderOption': value_render_option}\n )\n try:\n list_of_lists = fill_gaps(data['values'])\n except KeyError:\n list_of_lists = []\n path = os.path.join(folder_path, '{}.json'.format(GG_DOCS[GG_DOC]['target']))\n if overwrite or not os.path.isfile(path):\n print('\\t' + path)\n txt = json.dumps(list_of_lists, indent=4, ensure_ascii=False)\n open(path, 'w').write(txt)\n\n\ndef get_json(lang='en'):\n for GG_DOC in list(GG_DOCS):\n folder_path = os.path.join(DATA_PATH, GG_DOC)\n path = os.path.join(folder_path, '{}.json'.format(GG_DOCS[GG_DOC]['target']))\n if GG_DOC.lower() != lang.lower():\n continue\n # no data file, try to generate first\n if not os.path.isfile(path):\n write_data()\n # check again and return the data if has\n if os.path.isfile(path):\n return json.loads(open(path, 'r', encoding='utf-8').read())\n return None\n\n\ndef _get_en_skill(skill_str):\n skill = Skill('Unknown', None)\n if skill_str and ']\\n' in skill_str:\n index = skill_str.index(']\\n')\n name = skill_str[:index].replace('\\n', ' ').lstrip('[')\n description = skill_str[index+1:].replace('\\n', ' ').strip()\n return Skill(name, description)\n return skill\n\n\ndef format_data(json_data, lang='en'):\n if not isinstance(json_data, list):\n return []\n col_num = 0\n rows_num = len(json_data)\n index = 0\n data = []\n if lang == 'en':\n while index < rows_num:\n row = json_data[index]\n if index == 0:\n col_num = len(row)\n index += 1\n elif len(row) == col_num and row[2] != '':\n # character info\n char = Character_EN()\n char.unique_equipment = row[1].lstrip('=image(\"').rstrip('\")').replace('@w200', '@w50')\n _name = re.sub(r'\\n', ' ', row[2])\n char.name = _name.strip()\n _katakana = re.sub(r'\\n', ' ', row[3])\n char.katakana = _katakana.strip()\n char.base_rarity = row[4]\n p_a = row[5].split('\\n\\n')\n char.position = p_a[0] if len(p_a) == 2 else '1*'\n char.attack_type = p_a[1] if len(p_a) == 2 else 'Physical'\n # skills\n char.ub = _get_en_skill(str(row[6]))\n char.skill_1 = _get_en_skill(str(row[7]))\n char.skill_2 = _get_en_skill(str(row[8]))\n char.skill_ex = _get_en_skill(str(row[9]))\n char.skill_enc = _get_en_skill(str(row[10]))\n # append\n data.append(char)\n index += 1\n else:\n index += 1\n return data\n elif lang == 'vi':\n while index < rows_num:\n row = json_data[index]\n if index == 0:\n col_num = len(row)\n index += 1\n elif len(row) == col_num and row[0] != '':\n # character info\n char = Character_VI()\n # _id = row[0]\n _image_url = row[1].lstrip('=IMAGE(\"').replace('\"; 1)', '')\n char.image_url = _image_url\n _url_name = row[2].lstrip('=HYPERLINK(\"').rstrip(')').split(';')\n _url = _url_name[0].rstrip('\"')\n char.gamewith_url = _url\n _name = _url_name[1].strip('\"') if '\"' in _url_name[1] else _url_name[1]\n _name = re.sub(r'\\n', ' ', _name)\n _name = re.sub(r' ', ' ', _name)\n char.name = _name.strip()\n char.ub.name = str(row[3])\n char.skill_1.name = str(row[4])\n char.skill_2.name = str(row[5])\n char.skill_ex.name = str(row[6])\n char.skill_enc.name = str(row[7])\n # skill description\n index += 1\n row = json_data[index]\n char.ub.description = str(row[3])\n char.skill_1.description = str(row[4])\n char.skill_2.description = str(row[5])\n char.skill_ex.description = str(row[6])\n char.skill_enc.description = str(row[7])\n # note\n char.note = ''\n while index + 1 < rows_num and isinstance(json_data[index][0], str):\n index += 1\n row = json_data[index]\n row_str = '\\n'.join(map(lambda r: str(r), row))\n row_str = re.sub(r'\\n\\n', '', row_str)\n if row_str.strip() != '':\n char.note += (row_str + '\\n')\n else:\n break\n char.note = char.note.strip()\n # append\n data.append(char)\n index += 1\n else:\n index += 1\n return data\n return []\n\n\ndef get_character_info(name, lang='en'):\n if not isinstance(name, str):\n return None\n _name = name\n name = name.lower()\n if 'kukka' in name and lang == 'vi':\n name = name.replace('kukka', 'kuuka')\n names = name.strip().split(' ')\n name = '{}'.format(names[0])\n if not name:\n return None\n special_name = names[1] if len(names) >= 2 else None\n print(_name, lang)\n lang = lang.lower()\n if lang not in GG_DOCS:\n return None\n json_data = get_json(lang)\n if json_data is None:\n return None\n # print(len(json_data))\n characters = format_data(json_data, lang)\n # print(len(characters))\n # txt = json.dumps(characters, indent=4, ensure_ascii=False, default=lambda c: c.json)\n # open('characters.json', 'w').write(txt)\n _character = None\n for character in characters:\n character_name = character.name.lower()\n if name in character_name:\n if special_name is not None:\n if special_name in character_name:\n _character = character\n break\n else:\n _character = character\n break\n if _character is not None and lang != 'vi':\n _character_vi = get_character_info(_name, 'vi')\n if _character_vi:\n _character.gamewith_url = _character_vi.gamewith_url\n _character.image_url = _character_vi.image_url\n return _character\n\n\ndef get_character_list(lang, to_str=False):\n if lang != 'en' and lang != 'vi':\n return None\n json_data = get_json(lang)\n if json_data is None:\n return None\n characters = format_data(json_data, lang)\n if to_str:\n msg = '**Character list**'\n for index, char in enumerate(characters, 1):\n msg += '\\n{}. {}'.format(index, char.name)\n return msg\n return characters\n\n\ndef update_data(overwrite=True):\n write_data(overwrite=overwrite)\n\n\nif __name__ == '__main__':\n write_data(False)\n # vi = get_json('vi')\n # char = get_character_info('mui', 'en')\n # print(json.dumps(char.json, indent=4, ensure_ascii=False))\n char = get_character_info('kukka edo', 'en')\n print(char)\n # print(char.gamewith_url)\n # print(char.image_url)\n # print(json.dumps(char.discord_msg, indent=4, ensure_ascii=False))\n char = get_character_info('', 'en')\n print(char)\n\n chars = get_character_list('en', True)\n print(chars)\n","sub_path":"generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":16518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"27624263","text":"import matplotlib.pyplot as plt\nfrom matplotlib import animation, cm\n\nimport numpy as np\n\n# тестовые функции\nfrom test_func import test_function\nfrom test_func import test_function_range\n\n\ndef get_data(delta, low, up, f_index, dimension):\n if (type(up) == int) or (type(up) == float):\n x = np.arange(low, up, delta)\n y = np.arange(low, up, delta)\n else:\n x = np.arange(low[0], up[0], delta)\n y = np.arange(low[1], up[1], delta)\n\n X, Y = np.meshgrid(x, y)\n\n Z = test_function.test_function(np.array([X, Y]), f_index, dimension)\n\n return X, Y, Z\n\n\ndef draw_isolines(low, up, dimension, f_index, delta=0.15):\n\n # delta = 0.15\n # для 4 функции 0.05\n\n if (type(up) == int) or (type(up) == float):\n x = np.arange(low, up, delta)\n y = np.arange(low, up, delta)\n else:\n x = np.arange(low[0], up[0], delta)\n y = np.arange(low[1], up[1], delta)\n\n X, Y = np.meshgrid(x, y)\n\n Z = test_function.test_function(np.array([X, Y]), f_index, dimension)\n\n levels = np.arange(np.min(Z), np.max(Z), delta) # * 65\n\n # CS = plt.contour(X, Y, Z, levels=levels)\n # CS = plt.contour(X, Y, Z)\n # plt.clabel(CS, fmt=\"%1.1f\", inline=1, fontsize=3)\n # plt.title(\"График изолиний функции F\" + str(f_index))\n # plt.show()\n\n return X, Y, Z, levels\n\n\ndef data_gen(max_iter, coord, num=0):\n # i = num\n while num < max_iter:\n xlist = np.zeros((len(coord[num]), 1))\n ylist = np.zeros((len(coord[num]), 1))\n for j in range(len(coord[num])):\n xlist[j] = coord[num][j][0]\n ylist[j] = coord[num][j][1]\n num = num + 1\n yield xlist, ylist\n\n\ndef make_init(low, up, xdata, ydata, line, ax):\n\n def init():\n del xdata[:]\n del ydata[:]\n line.set_data(xdata, ydata)\n if (type(up) == int) or (type(up) == float):\n ax.set_ylim(low, up)\n ax.set_xlim(low, up)\n else:\n ax.set_ylim(low[0], up[0])\n ax.set_xlim(low[0], up[0])\n return line,\n\n return init\n\n\ndef run(data, line):\n # обновление данных\n xlist, ylist = data\n # для автоматического масштабирования точечного графика раскоментировать следующие строки\n # xmin = np.min(xlist)\n # xmax = np.max(xlist)\n # ymin = np.min(ylist)\n # ymax = np.max(ylist)\n # xmin, xmax = ax.get_xlim()\n # ymin, ymax = ax.get_ylim()\n # ax.set_xlim(xmin, xmax)\n # ax.set_ylim(ymin, ymax)\n # ax.figure.canvas.draw()\n\n line.set_data(xlist, ylist)\n\n return line,\n\n\n# Функция построения анимированного графика поиска агентами оптимума.\n# В виде фона используется график изолиний, значения для которого получаеются через функцию draw_isolines.\n# Для анимирования используются вспомогательные функции: data_gen, make_init, run.\n# data_gen - генерирует данные для одного кадра анимации (координаты N агентов за 1 итерацию).\n# make_init - функция выполняется один раз перед первым кадром, для инициализации начальных значений.\n# run - функция задает значения каждого кадра.\n# @param f_index - индекс функции в файле test_function\n# @param rate_change_graph - скорость изменения графика в милисекундах\n# @param coord - трехмерный массив координат агентов по итерациям.\n# Вид: coord[индекс итерации 0 - max_iter-1][индекс агента 0 - N-1][индекс измерения 0 - dim-1]\n# @param max_iter - общее количество итераций\ndef print_graph(f_index, rate_change_graph, coord, max_iter):\n low, up, dim = test_function_range.get_range(f_index)\n\n # точечный анимированный график для трехмерных функций\n if dim == 2:\n fig, ax = plt.subplots()\n xdata, ydata = [], []\n line, = ax.plot([], [], lw=2, color='b', linestyle=' ', marker='o', label='Агенты')\n plt.legend(loc='upper left')\n X, Y, Z, levels = draw_isolines(low, up, dim, f_index)\n # рисование графика изолиний исходной функции\n CS = plt.contour(X, Y, Z, levels=levels)\n ax.grid()\n # создание анимированного точечного графика\n # blit контролирует используется ли blitting. Если True не будет работать масштабирование и перемещение графика\n ani = animation.FuncAnimation(fig, run, frames=data_gen(max_iter, coord), blit=False,\n interval=rate_change_graph, repeat=False,\n init_func=make_init(low, up, xdata, ydata, line, ax), fargs=(line,))\n\n plt.show()\n\n\n# Функция рисования графика динамики лучших решений по итерациям.\n# Если в решениях примутствуют отрицательные значения используется линейная шкала, иначе логарифмическая.\n# @param best_chart - массив значений лучших решений (значений оптимизируемой функции) по итерациям\ndef graph_best_chart(best_chart):\n fig, ax = plt.subplots()\n ax.plot(best_chart, \"g\", label='Лучшие решения')\n plt.grid(True, color=\"k\")\n if np.min(best_chart) >= 0:\n ax.set_yscale('log', basey=10)\n else:\n ax.set_yscale('linear')\n plt.legend(loc='upper right')\n plt.xlabel(\"Итерации\")\n plt.ylabel(\"Лучшие значения\")\n plt.title(\"Изменение лучших значений минимизируемой функции\", loc='center')\n plt.show()\n\n\ndef get_data_func_3d(f_index, delta=0.2):\n low, up, dim = test_function_range.get_range(f_index)\n\n X, Y, Z = get_data(delta, low, up, f_index, dim)\n\n return X, Y, Z\n\n\ndef graph_motion_points_3d(f_index, rate_change_graph, coord, max_iter):\n low, up, dim = test_function_range.get_range(f_index)\n\n fig = plt.figure()\n # ax = Axes3D(fig)\n ax = fig.add_subplot(111, projection='3d')\n # ax = fig.gca(projection='3d')\n xdata, ydata, zdata = [], [], []\n # line, = ax.scatter([], [], [], lw=2, color='b', marker='o', label='Агенты') # linestyle='-'\n # line, = ax.scatter([], [], [], marker='o')\n # line, = ax.plot([], [], [], linestyle=\"\", marker=\"o\", color='b')\n line = ax.scatter([], [], [], marker='o', color='r', label='Агенты')\n\n plt.legend(loc='upper left')\n\n # получение данных для рисования фона\n X, Y, Z = get_data_func_3d(f_index, delta=0.1)\n\n # рисование 3D графика исходной функции как фон\n # plot_surface - сплошная поверхность с подсветкой высот, contour3D - сетка с подсветкой высот (изолинии)\n # plot_wireframe - сетка одного цвета\n ax.plot_surface(X, Y, Z, rstride=4, cstride=4, cmap=cm.jet, alpha=0.5)\n ax.grid()\n\n # создание анимированного точечного графика\n # blit контролирует используется ли blitting. Если True не будет работать масштабирование и перемещение графика\n ani = animation.FuncAnimation(fig, run_3d, frames=data_gen_for_3d_func(max_iter, coord, f_index, dim), blit=False,\n interval=rate_change_graph, repeat=False,\n init_func=make_init_3d(low, up, xdata, ydata, zdata, ax, line), fargs=(line, ax))\n\n plt.show()\n\n\ndef data_gen_for_3d_func(max_iter, coord, f_index, dimension, num=0):\n while num < max_iter:\n # не работает если написать так np.zeros((len(coord[num]), 1))\n xlist = np.zeros((len(coord[num]),))\n ylist = np.zeros((len(coord[num]),))\n zlist = np.zeros((len(coord[num]),))\n for j in range(len(coord[num])):\n xlist[j] = coord[num][j][0]\n ylist[j] = coord[num][j][1]\n zlist[j] = test_function.test_function(coord[num][j], f_index, dimension)\n num = num + 1\n yield xlist, ylist, zlist\n\n\ndef make_init_3d(low, up, xdata, ydata, zdata, ax, line):\n\n def init():\n del xdata[:]\n del ydata[:]\n del zdata[:]\n # line.set_data(xdata, ydata)\n # line.set_3d_properties(zdata)\n line._offsets3d = (xdata, ydata, zdata)\n if (type(up) == int) or (type(up) == float):\n ax.set_ylim(low, up)\n ax.set_xlim(low, up)\n else:\n ax.set_ylim(low[1], up[1])\n ax.set_xlim(low[0], up[0])\n return line\n\n return init\n\n\ndef run_3d(data, line, ax):\n # обновление данных\n xlist, ylist, zlist = data\n # для автоматического масштабирования точечного графика раскоментировать следующие строки\n # xmin = np.min(xlist)\n # xmax = np.max(xlist)\n # ymin = np.min(ylist)\n # ymax = np.max(ylist)\n # xmin, xmax = ax.get_xlim()\n # ymin, ymax = ax.get_ylim()\n # ax.set_xlim(xmin, xmax)\n # ax.set_ylim(ymin, ymax)\n\n # ax.set_zlim(np.min(zlist), np.max(zlist))\n # ax.figure.canvas.draw()\n\n # line.set_data(xlist, ylist)\n # line.set_3d_properties(zlist)\n\n line._offsets3d = (xlist, ylist, zlist)\n\n return line\n\n\n# def graph_with_arrow(f_index, rate_change_graph, coord, max_iter):\n# low, up, dim = test_function_range.get_range(f_index)\n#\n# # точечный анимированный график для трехмерных функций\n# if dim == 2:\n# fig, ax = plt.subplots()\n# xdata, ydata = [], []\n# line, = ax.plot([], [], lw=2, color='b', linestyle=' ', marker='o', label='Агенты')\n# plt.legend(loc='upper left')\n# X, Y, Z, levels = draw_isolines(low, up, dim, f_index)\n# # рисование графика изолиний исходной функции\n# CS = plt.contour(X, Y, Z, levels=levels)\n# ax.grid()\n# # создание анимированного точечного графика\n# # blit контролирует используется ли blitting. Если True не будет работать масштабирование и перемещение графика\n# ani = animation.FuncAnimation(fig, run_arrow, frames=data_gen(max_iter, coord), blit=False,\n# interval=rate_change_graph, repeat=False,\n# init_func=make_init(low, up, xdata, ydata, line, ax), fargs=(line, plt))\n#\n# plt.show()\n#\n# xlist = []\n# ylist = []\n#\n#\n# def run_arrow(data, line, plt):\n# x, y = data\n#\n# xlist.append(x[0][0])\n# ylist.append(y[0][0])\n#\n# line.set_data(x, y)\n# if len(xlist) >= 2:\n# for i in range(0, len(xlist), 2):\n# plt.arrow(xlist[-2], ylist[-2], xlist[-1], ylist[-1], shape='full', lw=3, length_includes_head=True, head_width=.01)\n#\n# return line, plt\n\n\ndef comparative_graph_convergence(f_index, **best_chart_alg):\n \"\"\"Функция построения сравнительного графика сходимости алгоритмов.\"\"\"\n colors = ['b', 'g', 'r', 'm', 'k', 'y', 'c']\n lisestyles = ['-', '--', '-.']\n markers = ['o', 's', '^', 'x', 'p', 'v']\n fig, ax = plt.subplots()\n plt.grid(True, color=\"k\")\n # plt.tick_params(labelsize=16)\n # plt.rcParams.update({'font.size': 14})\n params = {'legend.fontsize': 'x-large',\n 'figure.figsize': (15, 5),\n 'axes.labelsize': 'medium',\n 'axes.titlesize': 'medium',\n 'xtick.labelsize': 'large',\n 'ytick.labelsize': 'large'}\n plt.rcParams.update(params)\n min_char = []\n # chart = np.array(best_chart_alg.values())\n for b in best_chart_alg:\n min_char.append(np.min(best_chart_alg.get(b)))\n\n if np.min(min_char) >= 0:\n ax.set_yscale('log', basey=10)\n else:\n ax.set_yscale('linear')\n plt.xlabel(\"Итерации\", fontsize=14)\n plt.ylabel(\"Лучшие значения\", fontsize=14)\n plt.title(\"Изменение лучших значений минимизируемой функции\", loc='center')\n\n # ax.set_yscale('log', basey=10)\n ind = 0\n for alg in best_chart_alg:\n plt.plot(best_chart_alg.get(alg), color=colors[ind], lw=1, linestyle=lisestyles[ind]) # marker=markers[ind],\n\n if ind <= len(lisestyles):\n ind = ind + 1\n else:\n ind = 0\n\n plt.legend(best_chart_alg.keys(), loc='upper right')\n file_name = 'convergence_F_' + str(f_index) + '.png'\n plt.savefig(file_name)\n # plt.setp()\n\n plt.show()\n\n\ndef grahp_isolines(f_index):\n low, up, dim = test_function_range.get_range(f_index)\n\n # точечный анимированный график для трехмерных функций\n if dim == 2:\n fig, ax = plt.subplots()\n # xdata, ydata = [], []\n # line, = ax.plot([], [], lw=2, color='b', linestyle=' ', marker='o', label='Агенты')\n plt.legend(loc='upper left')\n params = {'legend.fontsize': 'x-large',\n 'figure.figsize': (15, 5),\n 'axes.labelsize': 'large',\n 'axes.titlesize': 'large',\n 'xtick.labelsize': 'large',\n 'ytick.labelsize': 'large'}\n plt.rcParams.update(params)\n X, Y, Z, levels = draw_isolines(low, up, dim, f_index, delta=0.1)\n # рисование графика изолиний исходной функции\n CS = plt.contour(X, Y, Z, levels=levels)\n name = \"Функция F\" + str(f_index)\n plt.title(name, loc='center', fontsize=18)\n ax.grid()\n # создание анимированного точечного графика\n # blit контролирует используется ли blitting. Если True не будет работать масштабирование и перемещение графика\n # ani = animation.FuncAnimation(fig, run, frames=data_gen(max_iter, coord), blit=False,\n # interval=rate_change_graph, repeat=False,\n # init_func=make_init(low, up, xdata, ydata, line, ax), fargs=(line,))\n\n plt.show()\n\n","sub_path":"graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":15226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"325759508","text":"import random\nfrom response_text.best_rate import (\n BEST_RATE_RESPONSE_ONLY_BANK,\n BEST_RATE_RESPONSE_ONLY_REPAYMENT,\n BEST_RATE_RESPONSE_ONLY_FIXEDYEAR,\n BEST_RATE_RESPONSE_ONLY_VARIABLE,\n BEST_RATE_RESPONSE_NO_INPUT,\n BEST_RATE_RESPONSE_ALL_INPUT,\n BEST_RATE_RESPONSE_BANK_MORTGAGE,\n BEST_RATE_RESPONSE_BANK_FIXEDYEAR,\n BEST_RATE_RESPONSE_BANK_VARIABLE,\n BEST_RATE_RESPONSE_MORTGAGE_FIXEDYEAR,\n BEST_RATE_RESPONSE_MORTGAGE_VARIABLE,\n BEST_RATE_RESPONSE_ONLY_OWNERSHIPSTATUS,\n BEST_RATE_RESPONSE_ALL_INPUT_VARIABLE\n)\n\nfrom response_text.compare_rate import (\n COMPARE_RATE_RESPONSE_ALL_INPUT\n)\n\nfrom response_text.show_time import (\n SHOW_TIME_TEXT\n)\n\nfrom response_text.description import (\n DESC_IO,\n DESC_LVR,\n DESC_PI,\n DESC_OO,\n DESC_I,\n NOT_UNDERSTAND\n)\n\nfrom response_text.best_compare_rate_followup import (\n BEST_COMPARE_FOLLOWUP_BETTER,\n BEST_COMPARE_FOLLOWUP_WORST\n)\n\nfrom response_text.welcome import (\n WELCOME_TEXT\n)\n\n\nclass Random:\n @staticmethod\n def get_resp_best_bank(params):\n\n if all(param == \"\" for param in params.values()):\n response_text = BEST_RATE_RESPONSE_NO_INPUT\n elif all(param != \"\" for param in params.values()):\n if params['fixed_year'] == \"-\":\n response_text = BEST_RATE_RESPONSE_ALL_INPUT_VARIABLE\n else:\n response_text = BEST_RATE_RESPONSE_ALL_INPUT\n elif params['bank'] != \"\" and params['mortgage'] != \"\":\n response_text = BEST_RATE_RESPONSE_BANK_MORTGAGE\n elif params['bank'] != \"\" and params['fixed_year'] != \"\":\n if params['fixed_year'] == \"-\":\n response_text = BEST_RATE_RESPONSE_BANK_VARIABLE\n else:\n response_text = BEST_RATE_RESPONSE_BANK_FIXEDYEAR\n elif params['mortgage'] != \"\" and params['fixed_year'] != \"\":\n if params['fixed_year'] == \"-\":\n response_text = BEST_RATE_RESPONSE_MORTGAGE_VARIABLE\n else:\n response_text = BEST_RATE_RESPONSE_MORTGAGE_FIXEDYEAR\n elif params['bank'] != \"\":\n response_text = BEST_RATE_RESPONSE_ONLY_BANK\n elif params['mortgage'] != \"\":\n response_text = BEST_RATE_RESPONSE_ONLY_REPAYMENT\n elif params['fixed_year'] == \"\":\n if params['fixed_year'] == \"-\":\n response_text = BEST_RATE_RESPONSE_ONLY_VARIABLE\n else:\n response_text = BEST_RATE_RESPONSE_ONLY_FIXEDYEAR\n elif params['ownership_status'] != \"\":\n response_text = BEST_RATE_RESPONSE_ONLY_OWNERSHIPSTATUS\n else:\n response_text = BEST_RATE_RESPONSE_NO_INPUT\n\n return response_text\n\n @staticmethod\n def best_bank(params, details):\n response_text = Random.get_resp_best_bank(params)\n\n output_string = random.choice(response_text)\n response = output_string.format(\n bank_name=details['bank_name'],\n interest_rate=details['interest_rate'],\n repayment_type=details['repayment_type'],\n ownership_status=details['ownership_type'],\n year_fixed=details['year_fixed'],\n )\n\n return response\n\n @staticmethod\n def get_resp_description(abv_description):\n if abv_description is None:\n return NOT_UNDERSTAND\n\n response_type = \"DESC_\"\n response_type += abv_description\n response_text = eval(response_type)\n print(response_text)\n\n return response_text\n\n @staticmethod\n def description(abv_description=None):\n response_type = Random.get_resp_description(abv_description)\n output_string = random.choice(response_type)\n response = output_string.format(\n abv_description=abv_description\n )\n\n return response\n\n # TODO: Compare Bank more response.\n @staticmethod\n def compare_bank(bank_1_details, bank_2_details):\n output_string = random.choice(COMPARE_RATE_RESPONSE_ALL_INPUT)\n # If interest_rate from bank 1 is higher\n if bank_1_details['interest_rate'] < bank_2_details['interest_rate']:\n response = output_string.format(\n bank_1=bank_1_details['bank_name'],\n bank_2=bank_2_details['bank_name'],\n repayment_type=bank_1_details['repayment_type'],\n year_fixed=bank_1_details['year_fixed'],\n rate_1=bank_1_details['interest_rate'],\n rate_2=bank_2_details['interest_rate'],\n diff_rate=abs(round(bank_1_details['interest_rate'] - bank_2_details['interest_rate'], 2))\n )\n else:\n response = output_string.format(\n bank_1=bank_2_details['bank_name'],\n bank_2=bank_1_details['bank_name'],\n repayment_type=bank_2_details['repayment_type'],\n year_fixed=bank_2_details['year_fixed'],\n rate_1=bank_2_details['interest_rate'],\n rate_2=bank_1_details['interest_rate'],\n diff_rate=abs(round(bank_2_details['interest_rate'] - bank_1_details['interest_rate'], 2))\n )\n return response\n\n @staticmethod\n def get_best_rate_compare_followup_resp(old_rate, best_rate):\n if old_rate > best_rate['interest_rate']:\n response_text = BEST_COMPARE_FOLLOWUP_BETTER\n else:\n response_text = BEST_COMPARE_FOLLOWUP_WORST\n return response_text\n\n @staticmethod\n def best_rate_compare_followup(old_rate, best_rate):\n response_text = Random.get_best_rate_compare_followup_resp(old_rate, best_rate)\n output_string = random.choice(response_text)\n if old_rate > best_rate['interest_rate']:\n response = output_string.format(\n bank_name=best_rate['bank_name'],\n old_rate=old_rate,\n new_rate=best_rate['interest_rate'],\n diff_rate=abs(round(old_rate - best_rate['interest_rate'], 2))\n )\n else:\n response = output_string.format(\n bank_name=best_rate['bank_name'],\n old_rate=old_rate,\n new_rate=best_rate['interest_rate'],\n diff_rate=abs(round(best_rate['interest_rate'] - old_rate, 2))\n )\n\n return response\n\n @staticmethod\n def welcome_response(timestamp):\n output_string = random.choice(WELCOME_TEXT)\n\n response = output_string.format(\n timestamp=timestamp\n )\n\n return response\n\n @staticmethod\n def show_time(timestamp):\n output_string = random.choice(SHOW_TIME_TEXT)\n\n response = output_string.format(\n timestamp=timestamp\n )\n\n return response","sub_path":"Random.py","file_name":"Random.py","file_ext":"py","file_size_in_byte":6785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"368822747","text":"from melonhub import db\nfrom melonhub.models import Customer, Affiliate, Employee, Stock, Product, Order\n\ndef get(product_name):\n\treturn Product.query.filter_by(name=product_name).first()\n\ndef get_all_unique():\n\tproducts = Product.query.all()\n\tunique_products = []\n\n\tfor unsorted_product in products:\n\t\tunique = True\n\t\tfor unique_product in unique_products:\n\t\t\tif unique_product.name == unsorted_product.name:\n\t\t\t\tunique = False\n\t\t\t\tbreak\n\n\t\tif unique:\n\t\t\tunique_products.append(unsorted_product)\n\n\treturn unique_products\n\ndef search(query):\n\tdb_search = Product.query.filter(Product.name.contains(query)).all()\n\n\tunique_products = []\n\n\tfor unsorted_product in db_search:\n\t\tunique = True\n\t\tfor unique_product in unique_products:\n\t\t\tif unique_product.name == unsorted_product.name:\n\t\t\t\tunique = False\n\t\t\t\tbreak\n\n\t\tif unique:\n\t\t\tunique_products.append(unsorted_product)\n\n\treturn unique_products\n\ndef get_from_id_array(id_array):\n\titems = []\n\tfor i in id_array:\n\t\titems.append(Product.query.get(i))\n\n\treturn items\n","sub_path":"melonhub/products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"183168182","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'valerio cosentino'\n\nfrom importers.vcs.git.git_dao import GitDao\nfrom importers.issue_tracker.github.querier_github import GitHubQuerier\nfrom util.logging_util import LoggingUtil\nfrom util.db_util import DbUtil\nfrom datetime import datetime\n\n\nclass GitHubUtil():\n \"\"\"\n This class helps mapping the identities of the users in the vcs and GitHub\n \"\"\"\n def __init__(self, db_name, project_name,\n repo_name, github_repo_full_name, tokens,\n config, log_root_path):\n \"\"\"\n :type db_name: str\n :param db_name: the name of an existing DB\n\n :type project_name: str\n :param project_name: the name of an existing project in the DB\n\n :type repo_name: str\n :param repo_name: the name of an existing repository in the DB\n\n :type url: str\n :param url: full name of the GitHub repository\n\n :type tokens: list str\n :param token: list of GitHub tokens\n\n :type config: dict\n :param config: the DB configuration file\n\n :type log_root_path: str\n :param log_root_path: the log path\n \"\"\"\n self._log_path = log_root_path + \"map-vcs-github-users-\" + db_name + \"-\" + project_name + \"-\" + repo_name\n self._project_name = project_name\n self._db_name = db_name\n self._repo_name = repo_name\n self._tokens = tokens\n self._active_token = 0\n self._url = github_repo_full_name\n\n config.update({'database': db_name})\n self._config = config\n\n self._logging_util = LoggingUtil()\n self._logger = self._logging_util.get_logger(self._log_path)\n self._db_util = DbUtil()\n self._cnx = self._db_util.get_connection(self._config)\n self._git_dao = GitDao(self._config, self._logger)\n self._github_querier = GitHubQuerier(self._url, self._tokens[self._active_token], self._logger)\n\n def _change_token(self):\n if len(self._tokens) > 1:\n if not self._github_querier._token_util._is_usuable(self._tokens[self._active_token]):\n self._active_token = (self._active_token + 1) % len(self._tokens)\n self._github_querier = GitHubQuerier(self._url, self._tokens[self._active_token], self._logger)\n\n def _analyse_user(self, user, unmatched_user, sha):\n if user:\n user_name = self._github_querier.get_user_name(user)\n user_ids = self._db_util.select_all_user_ids_by_name(self._cnx, user_name, self._logger)\n\n for user_id in user_ids:\n try:\n user_id, alias_id = self._db_util._identify_user_and_alias(self._cnx, unmatched_user, user_id, self._logger)\n if user_id != alias_id:\n self._db_util.insert_user_alias(self._cnx, user_id, alias_id, self._logger)\n self._logger.info(\"user ids \" + str(user_id) + \" and \" + str(alias_id) + \" successfully matched\")\n except Exception:\n self._logger.error(\"user ids \" + str(user_id) + \" and \" + str(alias_id) + \" not matched\", exc_info=True)\n continue\n else:\n self._logger.warning(\"GitHub user not found for commit \" + sha)\n\n def match(self):\n \"\"\"\n matches GitHub and Git identities\n \"\"\"\n try:\n\n self._fileHandler = self._logging_util.get_file_handler(self._logger, self._log_path, \"info\")\n\n self._logger.info(\"GitHubUtil started\")\n start_time = datetime.now()\n repo_id = self._git_dao.select_repo_id(self._repo_name)\n user_ids = self._git_dao.select_all_developer_ids(repo_id)\n alias_ids = self._db_util.select_all_aliased_user_ids(self._cnx, self._logger)\n unmatched_users = list(set(user_ids) - set(alias_ids))\n\n for unmatched_user in unmatched_users:\n matched = False\n sha = self._git_dao.select_sha_commit_by_user(unmatched_user, repo_id, match_on=\"author\")\n if sha:\n author = self._github_querier.get_author_by_commit(sha)\n self._analyse_user(author, unmatched_user, sha)\n matched = True\n else:\n sha = self._git_dao.select_sha_commit_by_user(unmatched_user, repo_id, match_on=\"committer\")\n if sha:\n committer = self._github_querier.get_committer_by_commit(sha)\n self._analyse_user(committer, unmatched_user, sha)\n matched = True\n\n if not matched:\n self._logger.warning(\"No commits found for user \" + str(unmatched_user))\n\n end_time = datetime.now()\n minutes_and_seconds = self._logging_util.calculate_execution_time(end_time, start_time)\n self._logger.info(\"GitHubUtil finished after \" + str(minutes_and_seconds[0])\n + \" minutes and \" + str(round(minutes_and_seconds[1], 1)) + \" secs\")\n self._logging_util.remove_file_handler_logger(self._logger, self._fileHandler)\n\n except:\n self._logger.error(\"GitHubUtil failed\", exc_info=True)\n finally:\n if self._git_dao:\n self._git_dao.close_connection()\n\n if self._cnx:\n self._db_util.close_connection(self._cnx)","sub_path":"util/github_util.py","file_name":"github_util.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"229042393","text":"# -*- coding: UTF-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens\n# www.pagebot.io\n#\n# P A G E B O T\n#\n# Licensed under MIT conditions\n#\n# Supporting DrawBot, www.drawbot.com\n# Supporting Flat, xxyxyz.org/flat\n# -----------------------------------------------------------------------------\n#\n# stylelib.py\n#\n# Default CSS reset.\n# Library of predefined named styles.\n#\n# D E P R E C A T E D\n#\n# CSS is now implemented as SCSS files, using PageBot-generated variable.scss.\n#\nfrom pagebot.toolbox.units import *\nfrom pagebot.toolbox.color import whiteColor, blackColor, color\n\nMARGIN = (0, 0, px(10), 0)\n\ndefault = {\n 'body': dict(\n font='Verdana, sans',\n fontStyle='normal', \n fontWeight='normal',\n tracking=0,\n fontSize=px(12),\n leading=em(1.4),\n color=0,\n fill=whiteColor,\n ),\n 'pre, code': dict(\n display='none',\n ),\n 'a': dict(\n color=color('#828487'),\n textDecoration='none',\n transition='all 0.3s ease-in-out',\n ),\n 'a:hover': dict(\n color=blackColor,\n ),\n 'p': dict(\n margin=MARGIN,\n tracking=0,\n ),\n 'em': dict(\n fontWeight='Bold',\n ),\n 'h1, h2, h3, h4, h5': dict(\n fontWeight='Bold',\n fontStyle='Bold',\n ),\n 'h2, h3, h4, h5': dict(\n margin=MARGIN,\n ),\n}\n\n\"\"\"\nol {\n list-style-type: None; }\nli strong {\n font-family: \"Upgrade-SemiboldItalic\", sans;\n}\ntable {\n width: 100%;\n border-collapse: collapse;\n margin: 0px; }\n\ntd, th {\n padding: 1em; }\n\narticle {\n margin-top: 0;\n padding: 0;\n display: block;\n vertical-align: text-top; }\n\na[rel=\"footnote\"] {\n border-bottom: none;\n background-color: white;\n padding: 0.1em;\n line-height: 0; }\n\nsup {\n top: -0.5em;\n font-size: 0.8em;\n line-height: 0;\n position: relative;\n vertical-align: baseline; }\n\na[rel=\"footnote\"]:before {\n content: \"(\"; }\n\na[rel=\"footnote\"]:after {\n content: \")\"; }\n\ninput, textarea, select {\n font-family: \"Upgrade-Regular\", sans;\n padding: 0.1em;\n font-size: 1em;\n line-height: 1em;\n width: 95%;\n padding: 0.4em 0.4em 0.4em 0.4em;\n color: #828487;\n background: #e1e1e1;\n border: none;\n text-align: left;\n -webkit-appearance: none; }\n\ntextarea {\n color: #828487;\n padding: 0.3em 0.3em 0.3em 0.3em;\n height: 55px;\n background: #e1e1e1;\n text-align: left;\n -webkit-appearance: none; }\n\nselect {\n padding: 0.5em 0.5em 0.5em 0.5em;\n background: #e1e1e1;\n -webkit-appearance: none; }\n\ninput[type=text] {\n background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #aaaaaa), color-stop(0.12, white));\n padding: 0.3em 0.3em 0.3em 0.3em;\n background: #e1e1e1;\n text-align: left;\n -webkit-appearance: none; }\n\n.video-container {\n float: none;\n clear: both;\n width: 100%;\n position: relative;\n padding-bottom: 56.25%;\n padding-top: 25px;\n height: 0; }\n\niframe, embed, object {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%; }\n\n\"\"\"\nstyleLib = {\n 'default': default,\n}\n","sub_path":"Lib/pagebot/stylelib.py","file_name":"stylelib.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"113788794","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nPrepare UXSSD/UPX data for decoding with Speaker Labelling model.\n\nDate: 2018\nAuthor: M. Sam Ribeiro\n\"\"\"\n\nimport os\nimport sys\nimport argparse\n\nfrom utils import write_data\nfrom utils import get_duration\n\n\ndef main(corpus_dir, labels_dir, output_dir, sample_rate=16000, use_reference=False):\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n datadir = os.path.join(corpus_dir, 'core')\n wav_base = 'FILEID sox WAVPATH -r {0} -t .wav - |'.format(sample_rate)\n\n if use_reference:\n ref_dir = os.path.join(labels_dir, 'reference_labels', 'speaker_labels', 'lab')\n reference_list = [f.replace('.lab', '') for f in os.listdir(ref_dir)]\n\n # utterances with issues, ignore these\n reject_list = ['02F-Therapy_07-004A', '20M-BL2-009A']\n\n speaker_utts = {}\n text, wav = [], []\n utt2spk, spk2utt = [], []\n utt2dur = []\n\n speakers = os.listdir(datadir)\n\n for speaker in speakers:\n sessions = os.listdir(os.path.join(datadir, speaker))\n\n for session in sessions:\n\n session_dir = os.path.join(datadir, speaker, session)\n flist = [f for f in os.listdir(session_dir) if f.endswith('.wav')]\n\n for f in flist:\n f = f.replace('.wav', '')\n fileid = '-'.join([speaker, session, f])\n\n if fileid in reject_list:\n continue\n\n if use_reference:\n if fileid not in reference_list:\n continue\n\n # use prompt for text, although it will be ignored for decoding\n txt_f = os.path.join(session_dir, f+'.txt')\n with open(txt_f, 'r') as fid:\n txt = fid.readline().rstrip()\n\n words = []\n for w in txt.split():\n w = w.upper()\n words.append(w)\n\n words = ' '.join([fileid] + words)\n text.append(words)\n\n # prepare wav.scp\n wavpath = os.path.join(session_dir, f+'.wav')\n file_wav = wav_base.replace('FILEID', fileid)\n file_wav = file_wav.replace('WAVPATH', wavpath)\n wav.append(file_wav)\n\n # prepare utt2dur\n dur = get_duration(wavpath)\n utt2dur.append('{0} {1}'.format(fileid, dur))\n\n # prepare utt2spk\n utt2spk.append('{0} {1}'.format(fileid, speaker))\n\n if speaker in speaker_utts:\n speaker_utts[speaker].append(fileid)\n else:\n speaker_utts[speaker] = [fileid]\n\n # prepare spk2utt\n for speaker in speaker_utts:\n spk_utts = '{0} {1}'.format(speaker, ' '.join(sorted(speaker_utts[speaker])))\n spk2utt.append(spk_utts)\n\n text_f = os.path.join(output_dir, 'text')\n wav_f = os.path.join(output_dir, 'wav.scp')\n utt2spk_f = os.path.join(output_dir, 'utt2spk')\n spk2utt_f = os.path.join(output_dir, 'spk2utt')\n utt2dur_f = os.path.join(output_dir, 'utt2dur')\n \n write_data(text, text_f)\n write_data(wav, wav_f)\n write_data(utt2spk, utt2spk_f)\n write_data(spk2utt, spk2utt_f)\n write_data(utt2dur, utt2dur_f)\n\n # validate data directory\n validate_cmd = './utils/validate_data_dir.sh --no-feats {0}'.format(output_dir)\n os.system(validate_cmd)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('corpus_dir', type=str, help='path to UXSSD corpus')\n parser.add_argument('labels_dir', type=str, help='path to UXTD label directory')\n parser.add_argument('output_dir', type=str, help='path to output directory')\n parser.add_argument('--sr', dest='sample_rate', type=int, help='sample rate in Hz')\n parser.add_argument('--use_reference', dest='use_reference', action='store_true', help='restrict to reference utterances')\n\n parser.set_defaults(sample_rate=16000)\n parser.set_defaults(use_reference=False)\n args = parser.parse_args()\n\n main(args.corpus_dir, args.labels_dir, args.output_dir, args.sample_rate, args.use_reference)\n","sub_path":"diarization/v1/local/data/decode-uxssd-upx.py","file_name":"decode-uxssd-upx.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"79786904","text":"\"\"\"proyecto1 URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom proyecto1.views import index, formulario, covidno, covidsi, viejosi, viejono, cardiono, cardiosi, inmusi, inmuno, salsi, salno, informacion\r\n\r\nurlpatterns = [\r\n path('', index),\r\n path('admin/', admin.site.urls),\r\n path('formulario/', formulario),\r\n path('formulario/covidno/', covidno),\r\n path('formulario/covidsi/', covidsi),\r\n path('formulario/covidno/viejosi/', viejosi),\r\n path('formulario/covidno/viejono/', viejono),\r\n path('cardiosi/', cardiosi),\r\n path('cardiono/', cardiono),\r\n path('cardiono/inmusi', inmusi),\r\n path('cardiono/inmuno', inmuno),\r\n path('cardiono/salsi', salsi),\r\n path('cardiono/salno', salno),\r\n path('informacion', informacion),\r\n]\r\n","sub_path":"COVIDNETWORKFINAL/proyecto1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"300948552","text":"import sys\nimport test6\nimport keyword\nimport builtins\n\narr = sys.argv[:] # Сохраняет в переменную имя файла\nfor n in arr:\n print(n)\n\n\"\"\" Замисть help используем doc\"\"\"\n\nprint(test6.__doc__) \nprint(test6.fun.__doc__)\n\nprint(dir(test6)) # dir() получаем список всех индентификаторов\n\nkey_word = keyword.kwlist\n\ninput(\"Enter\")\n\nprint(key_word) # Вызывает ключевые слова\n\ninput(\"Enter\")\n\nfck = dir(builtins)\n\nprint(fck) # Вызов встроенных индентификаторов\n\ninput(\"Enter\")\n\n","sub_path":"py/test5.py","file_name":"test5.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"116848320","text":"import os\n\n\ntrain_dict = {}\nfiles = os.listdir('Train-corpus/Cleaned_files_sentences/')\ndirectory = 'Train-corpus/Cleaned_files_sentences/'\n# print(len(files)) = 520\nfor filename in files:\n\tfile = open(directory+filename)\n\tfor line in file:\n\t for words in line.split():\n\t \tif words in train_dict :\n\t \t\ttrain_dict[words]=train_dict[words]+1\n\t \telse :\n\t \t\ttrain_dict[words]=1\n\tfile.close()\n\nlength=len(train_dict) # 255506\nprint(length)\n\nwrite_file = open(\"frequency.txt\", \"w+\")\nwrite_file.write(str(train_dict))\nwrite_file.close() \n","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"400502326","text":"import os\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\ntransf = transforms.Compose([\n transforms.ToTensor(),\n # transforms.Normalize((0.1307,), (0.3081,))\n # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n# dst = '/media/ray/D43E51303E510CBC/MyStuff/Workspace/Python/dataset/original/mnist'\ndst = '/media/ray/SSD/workspace/python/dataset/original/mnist'\nmnist_trainset = datasets.MNIST(\n dst,\n train=True,\n download=True,\n transform=transf\n)\nmnist_testset = datasets.MNIST(\n dst,\n train=False,\n download=True,\n transform=transf\n)\n\n\ntrain_loader = torch.utils.data.DataLoader(\n mnist_trainset,\n batch_size=10000,\n shuffle=True\n)\n\ntest_loader = torch.utils.data.DataLoader(\n mnist_testset,\n # batch_size=10,\n shuffle=False\n)\ngpu = torch.cuda.is_available()\n\nclass AutoEncoder(nn.Module):\n def __init__(self, input_dim, encoding_dim):\n super(AutoEncoder, self).__init__()\n self.encoder = nn.Linear(input_dim, encoding_dim)\n self.decoder = nn.Linear(encoding_dim, input_dim)\n\n def forward(self, x):\n encoded = F.relu(self.encoder(x))\n decoded = self.decoder(encoded)\n return decoded, encoded\n\n\ninput_dim = 784\nencoding_dim = 32\n\nmodel = AutoEncoder(input_dim, encoding_dim)\nmodel.cuda()\noptimizer = optim.Adam(model.parameters())\n\n\ndef l1_penalty(var):\n return torch.abs(var).sum()\n\n\ndef train(epoch, sparsity=False, l1_weight=1e-5):\n for batch_idx, (data, _) in enumerate(train_loader):\n data = Variable(data.view([-1, 784]).cuda())\n optimizer.zero_grad()\n\n # enforcing sparsity with l1 reg\n if sparsity:\n decoder_out, encoder_out = model(data)\n mse_loss = F.mse_loss(decoder_out, data)\n l1_reg = l1_weight * l1_penalty(encoder_out)\n loss = mse_loss + l1_reg\n else:\n output, _ = model(data)\n loss = F.binary_cross_entropy_with_logits(output, data)\n # loss = F.mse_loss(output, data)\n\n loss.backward()\n optimizer.step()\n # print(epoch)\n if batch_idx % 1 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader),\n # loss.data[0]\n loss.item()\n ))\n\n\nnum_epochs = 300\n\nfor epoch in range(1, num_epochs + 1):\n train(epoch)","sub_path":"world-models-pytorch/vae/2_layers_in_GPU.py","file_name":"2_layers_in_GPU.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"489821896","text":"import requests\nimport simplejson as json\nimport ast\nimport requests.packages.urllib3\n\nrequests.packages.urllib3.disable_warnings()\n\n\ndef get(url):\n\tf = open('/Users/jmc856/Desktop/Webpage/FlaskApp/Stockfighter/stockfighter.txt', 'r') # obtain api keys\n\ttext = f.read()\n\tapikey = ast.literal_eval(text)\n\theaders = {'X-Starfighter-Authorization': apikey}\n\tr = requests.get(url, headers=headers)\n\n\tif r.status_code == requests.codes.ok:\n\t\treturn json.loads(r.text)\n\telse:\n\t\treturn False\n\n\ndef post(url, payload):\n\tf = open('/Users/jmc856/Desktop/Webpage/FlaskApp/Stockfighter/stockfighter.txt', 'r')\n\ttext = f.read()\n\tapikey = ast.literal_eval(text)\n\theaders = {'X-Starfighter-Authorization': apikey}\n\n\tr = requests.post(url, data=json.dumps(payload), headers=headers)\n\tif r.status_code == requests.codes.ok:\n\t\treturn json.loads(r.text)\n\telse:\n\t\treturn False\n\n\ndef check_venue(venue):\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{}/heartbeat'.format(venue)\n\tdata = get(url)\n\n\treturn data\n\n\ndef venue_stocks(venue):\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{}/stocks'.format(venue)\n\tdata = get(url)\n\n\treturn data\n\n\ndef stocks_order(stock, venue):\n\tstock = str(stock)\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{0}/stocks/{1}'.format(venue, stock)\n\tdata = get(url)\n\n\treturn data\n\n\ndef stocks_order_post(stock, venue, payload):\n\tstock = str(stock)\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{0}/stocks/{1}/orders'.format(venue, stock)\n\tdata = post(url, payload)\n\n\treturn data\n\n\ndef order_status(stock, venue, id):\n\tstock = str(stock)\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{0}/stocks/{1}/orders/{2}'.format(venue, stock, id)\n\tdata = get(url)\n\n\treturn data\n\n\ndef stock_quote(venue, stock):\n\tstock = str(stock)\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{0}/stocks/{1}/quote'.format(venue, stock)\n\tdata = get(url)\n\n\treturn data\n\n\ndef stock_order_status(venue, stock, account):\n\tstock = str(stock)\n\tvenue = str(venue)\n\taccount = str(account)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{0}/accounts/{1}/stocks/{2}/orders'.format(venue, account, stock)\n\tdata = get(url)\n\n\treturn data\n\n\ndef cancel_order(stock, venue, id):\n\tstock = str(stock)\n\tvenue = str(venue)\n\turl = 'https://api.stockfighter.io/ob/api/venues/{0}/stocks/{1}/orders/{2}/cancel'.format(venue, stock, id)\n\tf = open('/Users/jmc856/Desktop/Webpage/FlaskApp/Stockfighter/stockfighter.txt', 'r')\n\ttext = f.read()\n\tapikey = ast.literal_eval(text)\n\theaders = {'X-Starfighter-Authorization': apikey}\n\tr = requests.post(url, headers=headers)\n\n\tif r.status_code == requests.codes.ok:\n\t\treturn json.loads(r.text)\n\telse:\n\t\treturn False\n\n\ndef payload(account, venue, stock, block, price, direction, ordertype):\n\tpayload = {\n\t\t'account': account,\n\t\t'venue': venue,\n\t\t'stock': stock,\n\t\t'qty': block,\n\t\t'price': price,\n\t\t'direction': direction,\n\t\t'orderType': ordertype\n\t}\n\n\treturn payload\n\n\ndef exposure_stock(venue, stock, account):\n\tinventory = stock_order_status(venue, stock, account)\n\tlong = 0\n\tshort = 0\n\n\tfor i in range(len(inventory['orders'])):\n\t\tif inventory['orders'][i]['direction'] == 'sell':\n\t\t\tshort += inventory['orders'][i]['totalFilled']\n\t\telse:\n\t\t\tlong += inventory['orders'][i]['totalFilled']\n\n\texposure = long - short\n\n\treturn exposure\n\n\ndef avg_purch_price(default_avg, venue, stock, account):\n\tinventory = stock_order_status(venue, stock, account)\n\tprices = 0\n\tfor i in range(len(inventory['orders'])):\n\t\tprices += inventory['orders'][i]['price']\n\n\ttry:\n\t\taverage = prices / len(inventory['orders'])\n\t\treturn average\n\n\texcept ZeroDivisionError:\n\t\treturn default_avg\n\n\ndef earnings(venue, stock, account):\n\tinventory = stock_order_status(venue, stock, account)\n\tlast_trade = stock_quote(venue, stock)['last']\n\texposure = exposure_stock(venue, stock, account)\n\n\tsold = 0\n\tbought = 0\n\n\tfor i in range(len(inventory['orders'])):\n\n\t\tif inventory['orders'][i]['direction'] == 'sell':\n\n\t\t\tfor j in range(len(inventory['orders'][i]['fills'])):\n\t\t\t\tsold += (inventory['orders'][i]['fills'][j]['price'] * inventory['orders'][i]['fills'][j]['qty'])\n\n\t\telif inventory['orders'][i]['direction'] == 'buy':\n\n\t\t\tfor j in range(len(inventory['orders'][i]['fills'])):\n\t\t\t\tbought += (inventory['orders'][i]['fills'][j]['price'] * inventory['orders'][i]['fills'][j]['qty'])\n\n\t\telse:\n\t\t\tpass\n\n\tcash = sold - bought\n\tworth = exposure * last_trade\n\tNAV = cash + worth\n\n\treturn cash, worth, NAV\n\n\ndef findorders(stock, venue):\n\torders = []\n\tfor order in range(1, 10):\n\t\ttry:\n\t\t\tif order_status(stock, venue, order) is None:\n\t\t\t\torders.append(order)\n\t\texcept AttributeError:\n\t\t\tpass\n\n\treturn orders\n\n\ndef submit_account(id):\n\tpayload = {\"account\": \"ABC123456\", \"explanation_link\": \"http://www.example.com\",\n\t\t\t \"executive_summary\": \"Lorem ipsum blah blah blah.\"}\n\turl = 'https://api.stockfighter.io/ob/api//gm/instances/%s/judge' % (id)\n\n\ndef websocket(venue, account):\n\turl = 'wss://api.stockfighter.io/ob/api/ws/%s/venues/%s/executions/' % (account, venue)\n\turl = 'wss://api.stockfighter.io/ob/api/ws/%s/venues/%s/tickertape' % (account, venue)\n","sub_path":"Stockfighter/stock_functions.py","file_name":"stock_functions.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"97274550","text":"from .encoder import Encoder\nfrom .discriminator import Discriminator\nfrom .sampler import SamplerFactory\n\nfrom .estimator import BaseEstimator\nfrom ..utils import get_device, ModelInput, GraphInput, HyperParameter, ModuleParameter\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom typing import Union\nfrom ..datasets import Graph, Graphs\nimport networkx as nx\nfrom ..utils import scipy_coo_to_torch_sparse, preprocess_features\n\n\nclass Framework(nn.Module):\n def __init__(self, dataset, module_params: ModuleParameter, hyper_params: HyperParameter):\n super(Framework, self).__init__()\n self.dataset = dataset\n self.module_params = module_params\n self.hyper_params = hyper_params\n\n # row-normalize feature matrix for graphs\n features = torch.from_numpy(dataset.features()).to(torch.float32)\n features = preprocess_features(features)\n dataset.setfeatures(features)\n self.register_buffer(\"features\", features)\n\n # get dimensions\n input_dim = self.features.shape[1]\n self.enc_dims = [input_dim] + [self.hyper_params.output_dim] * (self.hyper_params.hidden_size + 1)\n self.dec_dims = [self.enc_dims[-1] * 2, 1]\n\n if isinstance(dataset, Graphs):\n graphs_data = dataset.data\n else:\n feats = torch.from_numpy(dataset.features())\n adjmat = scipy_coo_to_torch_sparse(dataset.adjmat(sparse=True).tocoo())\n edgelist = adjmat._indices()\n weights = adjmat._values()\n graphs_data = [GraphInput(feats, None, edgelist, weights)]\n self.graphs_data = graphs_data\n self.num_graphs = len(graphs_data)\n\n self.graph_sampler = False\n if self.module_params.sampler in ['dgi', 'mvgrl', 'graphcl', 'gca']:\n self.graph_sampler = True\n self.mask = False\n if (self.graph_sampler and self.num_graphs > 1) or self.module_params.sampler == 'gca':\n self.mask = True\n self.outer = self.graph_sampler\n\n self.encoder = Encoder(self.module_params.enc, self.enc_dims,\n getattr(dataset, 'nodesize', 1),\n self.hyper_params.dropout,\n self.module_params.readout,\n self.hyper_params.ff)\n self.discriminator = Discriminator(self.module_params.dec, self.enc_dims[-1], self.dec_dims)\n self.estimator = BaseEstimator(self.module_params.est)\n self.sampler = SamplerFactory(self.module_params.sampler, graphs_data,\n self.features, self.hyper_params.batch_size)\n self.normalize = self.module_params.est == 'nce'\n\n def embed(self, x):\n if self.normalize:\n return F.normalize(self.encoder(x), dim=-1)\n return self.encoder(x)\n\n def forward(self, x: ModelInput, pos: ModelInput, neg: ModelInput):\n def get_anchor():\n pos_mask, neg_mask = None, None\n\n # repeat\n def repeat(start_idx):\n old_idx = start_idx[0]\n vectors = []\n for i, idx in enumerate(start_idx[1:]):\n vectors.append(hx[i].repeat(idx - old_idx, 1))\n old_idx = idx\n return torch.cat(vectors)\n\n def get_mask(start_idx):\n pos_mask = torch.zeros(hx.shape[0], hpos.shape[0])\n neg_mask = torch.ones(hx.shape[0], hpos.shape[0])\n old_idx = start_idx[0]\n if self.module_params.sampler == 'graphcl':\n pos_mask = torch.diag(torch.ones(hx.shape[0]))\n neg_mask = 1 - pos_mask\n else:\n for i, idx in enumerate(start_idx[1:]):\n pos_mask[i][old_idx:idx] = 1\n neg_mask[i][old_idx:idx] = 0\n old_idx = idx\n\n return pos_mask.to(get_device()), neg_mask.to(get_device())\n\n if self.mask:\n pos_mask, neg_mask = get_mask(pos.start_idx)\n hxp = hxn = hx\n return hxp, hxn, pos_mask, neg_mask\n\n hx = self.embed(x)\n hpos = self.embed(pos)\n hneg = self.embed(neg)\n hxp, hxn, pos_mask, neg_mask = get_anchor()\n pos_score = self.discriminator(hxp, hpos, self.outer)\n\n if self.mask:\n neg_score = pos_score\n else:\n neg_score = self.discriminator(hxn, hneg, self.outer)\n loss = self.estimator(pos_score, neg_score, pos_mask, neg_mask)\n self.encoder.reset()\n return loss\n","sub_path":"src/opengcl/framework/framework.py","file_name":"framework.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"422194596","text":"import gtk\nimport os\nimport misc\nfrom misc import noneToString, stringToNone, noneToBlankString, stringToBoolean\nimport wpath\nlanguage = misc.get_language_list_gui()\ndaemon = None\nwired = None\nwireless = None\ndef error(parent, message): \n \"\"\" Shows an error dialog \"\"\"\n dialog = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,\n gtk.BUTTONS_OK)\n dialog.set_markup(message)\n dialog.run()\n dialog.destroy()\nclass SmallLabel(gtk.Label):\n def __init__(self, text=''):\n gtk.Label.__init__(self, text)\n self.set_size_request(50, -1)\nclass LabelEntry(gtk.HBox):\n \"\"\" A label on the left with a textbox on the right. \"\"\"\n def __init__(self, text):\n gtk.HBox.__init__(self)\n self.entry = gtk.Entry()\n self.entry.set_size_request(200, -1)\n self.label = SmallLabel()\n self.label.set_text(text)\n self.label.set_size_request(170, -1)\n self.pack_start(self.label, fill=False, expand=False)\n self.pack_start(self.entry, fill=False, expand=False)\n self.label.show()\n self.entry.show()\n self.entry.connect('focus-out-event', self.hide_characters)\n self.entry.connect('focus-in-event', self.show_characters)\n self.auto_hide_text = False\n self.show()\n def set_text(self, text):\n self.entry.set_text(text)\n def get_text(self):\n return self.entry.get_text()\n def set_auto_hidden(self, value):\n self.entry.set_visibility(False)\n self.auto_hide_text = value\n def show_characters(self, widget=None, event=None):\n if self.auto_hide_text and widget:\n self.entry.set_visibility(True)\n def set_sensitive(self, value):\n self.entry.set_sensitive(value)\n self.label.set_sensitive(value)\n def hide_characters(self, widget=None, event=None):\n if self.auto_hide_text and widget:\n self.entry.set_visibility(False)\nclass GreyLabel(gtk.Label):\n \"\"\" Creates a grey gtk.Label. \"\"\"\n def __init__(self):\n gtk.Label.__init__(self)\n def set_label(self, text):\n self.set_markup(\"\" + text + \"\")\n self.set_alignment(0, 0)\nclass AdvancedSettingsDialog(gtk.Dialog):\n def __init__(self):\n \"\"\" Build the base advanced settings dialog.\n This class isn't used by itself, instead it is used as a parent for\n the WiredSettingsDialog and WirelessSettingsDialog.\n \"\"\"\n gtk.Dialog.__init__(self, title=language['advanced_settings'],\n flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CANCEL,\n gtk.RESPONSE_REJECT,\n gtk.STOCK_OK,\n gtk.RESPONSE_ACCEPT))\n self.txt_ip = LabelEntry(language['ip'])\n self.txt_ip.entry.connect('focus-out-event', self.set_defaults)\n self.txt_netmask = LabelEntry(language['netmask'])\n self.txt_gateway = LabelEntry(language['gateway'])\n self.txt_dns_1 = LabelEntry(language['dns'] + ' ' + language['1'])\n self.txt_dns_2 = LabelEntry(language['dns'] + ' ' + language['2'])\n self.txt_dns_3 = LabelEntry(language['dns'] + ' ' + language['3'])\n self.chkbox_static_ip = gtk.CheckButton(language['use_static_ip'])\n self.chkbox_static_dns = gtk.CheckButton(language['use_static_dns'])\n self.chkbox_global_dns = gtk.CheckButton(language['use_global_dns'])\n self.hbox_dns = gtk.HBox(False, 0)\n self.hbox_dns.pack_start(self.chkbox_static_dns)\n self.hbox_dns.pack_start(self.chkbox_global_dns)\n self.vbox.pack_start(self.chkbox_static_ip, fill=False, expand=False)\n self.vbox.pack_start(self.txt_ip, fill=False, expand=False)\n self.vbox.pack_start(self.txt_netmask, fill=False, expand=False)\n self.vbox.pack_start(self.txt_gateway, fill=False, expand=False)\n self.vbox.pack_start(self.hbox_dns, fill=False, expand=False)\n self.vbox.pack_start(self.txt_dns_1, fill=False, expand=False)\n self.vbox.pack_start(self.txt_dns_2, fill=False, expand=False)\n self.vbox.pack_start(self.txt_dns_3, fill=False, expand=False)\n self.chkbox_static_ip.connect(\"toggled\", self.toggle_ip_checkbox)\n self.chkbox_static_dns.connect(\"toggled\", self.toggle_dns_checkbox)\n self.chkbox_global_dns.connect(\"toggled\", self.toggle_global_dns_checkbox)\n self.chkbox_static_ip.set_active(False)\n self.chkbox_static_dns.set_active(False)\n def set_defaults(self, widget=None, event=None):\n \"\"\" Put some default values into entries to help the user out. \"\"\"\n ipAddress = self.txt_ip.get_text() \n netmask = self.txt_netmask\n gateway = self.txt_gateway\n ip_parts = misc.IsValidIP(ipAddress)\n if ip_parts:\n if stringToNone(gateway.get_text()) is None: \n gateway.set_text('.'.join(ip_parts[0:3]) + '.1')\n if stringToNone(netmask.get_text()) is None: \n netmask.set_text('255.255.255.0') \n elif ipAddress != \"\":\n error(None, \"Invalid IP Address Entered.\")\n def reset_static_checkboxes(self):\n if stringToNone(self.txt_ip.get_text()):\n self.chkbox_static_ip.set_active(True)\n self.chkbox_static_dns.set_active(True)\n self.chkbox_static_dns.set_sensitive(False)\n else:\n self.chkbox_static_ip.set_active(False)\n self.chkbox_static_dns.set_active(False)\n self.chkbox_static_dns.set_sensitive(True)\n if stringToNone(self.txt_dns_1.get_text()):\n self.chkbox_static_dns.set_active(True)\n else:\n self.chkbox_static_dns.set_active(False)\n self.toggle_ip_checkbox()\n self.toggle_dns_checkbox()\n self.toggle_global_dns_checkbox()\n def toggle_ip_checkbox(self, widget=None):\n \"\"\"Toggle entries/checkboxes based on the static IP checkbox. \"\"\"\n if self.chkbox_static_ip.get_active():\n self.chkbox_static_dns.set_active(True)\n self.chkbox_static_dns.set_sensitive(False)\n else:\n self.chkbox_static_dns.set_sensitive(True)\n self.txt_ip.set_sensitive(self.chkbox_static_ip.get_active())\n self.txt_netmask.set_sensitive(self.chkbox_static_ip.get_active())\n self.txt_gateway.set_sensitive(self.chkbox_static_ip.get_active())\n def toggle_dns_checkbox(self, widget=None):\n \"\"\" Toggle entries and checkboxes based on the static dns checkbox. \"\"\"\n if self.chkbox_static_ip.get_active():\n self.chkbox_static_dns.set_active(self.chkbox_static_ip.\n get_active())\n self.chkbox_static_dns.set_sensitive(False)\n self.chkbox_global_dns.set_sensitive(self.chkbox_static_dns.\n get_active())\n if self.chkbox_static_dns.get_active():\n self.txt_dns_1.set_sensitive(not self.chkbox_global_dns.get_active())\n self.txt_dns_2.set_sensitive(not self.chkbox_global_dns.get_active())\n self.txt_dns_3.set_sensitive(not self.chkbox_global_dns.get_active())\n else:\n self.txt_dns_1.set_sensitive(False)\n self.txt_dns_2.set_sensitive(False)\n self.txt_dns_3.set_sensitive(False)\n self.chkbox_global_dns.set_active(False)\n def toggle_global_dns_checkbox(self, widget=None):\n \"\"\" Set the DNS entries' sensitivity based on the Global checkbox. \"\"\"\n if daemon.GetUseGlobalDNS() and self.chkbox_static_dns.get_active():\n self.txt_dns_1.set_sensitive(not self.chkbox_global_dns.get_active())\n self.txt_dns_2.set_sensitive(not self.chkbox_global_dns.get_active())\n self.txt_dns_3.set_sensitive(not self.chkbox_global_dns.get_active())\n def destroy_called(self, *args):\n \"\"\" Clean up everything. \n This might look excessive, but it was the only way to prevent\n memory leakage.\n \"\"\"\n for obj in vars(self):\n if hasattr(obj, \"destroy\"):\n obj.destroy()\n if hasattr(obj, \"__del__\"):\n obj.__del__()\n else:\n del obj\n super(AdvancedSettingsDialog, self).destroy()\n self.destroy()\n del self\nclass WiredSettingsDialog(AdvancedSettingsDialog):\n def __init__(self, name):\n \"\"\" Build the wired settings dialog. \"\"\"\n AdvancedSettingsDialog.__init__(self)\n self.des = self.connect(\"destroy\", self.destroy_called)\n self.prof_name = name\n def set_net_prop(self, option, value):\n \"\"\" Sets the given option to the given value for this network. \"\"\"\n wired.SetWiredProperty(option, value)\n def set_values(self):\n \"\"\" Fill in the Gtk.Entry objects with the correct values. \"\"\"\n self.txt_ip.set_text(self.format_entry(\"ip\"))\n self.txt_netmask.set_text(self.format_entry(\"netmask\"))\n self.txt_gateway.set_text(self.format_entry(\"gateway\"))\n self.txt_dns_1.set_text(self.format_entry(\"dns1\"))\n self.txt_dns_2.set_text(self.format_entry(\"dns2\"))\n self.txt_dns_3.set_text(self.format_entry(\"dns3\"))\n self.reset_static_checkboxes()\n def format_entry(self, label):\n \"\"\" Helper method to fetch and format wired properties. \"\"\"\n return noneToBlankString(wired.GetWiredProperty(label))\n def destroy_called(self, *args):\n \"\"\" Clean up everything. \n This might look excessive, but it was the only way to prevent\n memory leakage.\n \"\"\"\n self.disconnect(self.des)\n for obj in vars(self):\n if hasattr(obj, \"destroy\"):\n obj.destroy()\n if hasattr(obj, \"__del__\"):\n obj.__del__()\n else:\n del obj\n super(WiredSettingsDialog, self).destroy_called()\n self.destroy()\n del self\nclass WirelessSettingsDialog(AdvancedSettingsDialog):\n def __init__(self, networkID):\n \"\"\" Build the wireless settings dialog. \"\"\"\n AdvancedSettingsDialog.__init__(self)\n self.networkID = networkID\n self.combo_encryption = gtk.combo_box_new_text()\n self.chkbox_encryption = gtk.CheckButton(language['use_encryption'])\n self.chkbox_global_settings = gtk.CheckButton(language['global_settings'])\n self.vbox_encrypt_info = gtk.VBox(False, 0) \n self.toggle_encryption()\n self.chkbox_encryption.set_active(False)\n self.combo_encryption.set_sensitive(False)\n self.encrypt_types = misc.LoadEncryptionMethods()\n activeID = -1 \n for x, enc_type in enumerate(self.encrypt_types):\n self.combo_encryption.append_text(enc_type[0])\n if enc_type[1] == wireless.GetWirelessProperty(networkID,\n \"enctype\"):\n activeID = x\n self.combo_encryption.set_active(activeID)\n if activeID != -1:\n self.chkbox_encryption.set_active(True)\n self.combo_encryption.set_sensitive(True)\n self.vbox_encrypt_info.set_sensitive(True)\n else:\n self.combo_encryption.set_active(0)\n self.change_encrypt_method()\n self.vbox.pack_start(self.chkbox_global_settings, False, False)\n self.vbox.pack_start(self.chkbox_encryption, False, False)\n self.vbox.pack_start(self.combo_encryption, False, False)\n self.vbox.pack_start(self.vbox_encrypt_info, False, False)\n self.chkbox_encryption.connect(\"toggled\", self.toggle_encryption)\n self.combo_encryption.connect(\"changed\", self.change_encrypt_method)\n self.des = self.connect(\"destroy\", self.destroy_called)\n def destroy_called(self, *args):\n \"\"\" Clean up everything. \n This might look excessive, but it was the only way to prevent\n memory leakage.\n \"\"\"\n self.disconnect(self.des)\n for obj in vars(self):\n if hasattr(obj, \"destroy\"):\n obj.destroy()\n if hasattr(obj, \"__del__\"):\n obj.__del__()\n else:\n del obj\n super(WirelessSettingsDialog, self).destroy_called()\n self.destroy()\n del self\n def set_net_prop(self, option, value):\n \"\"\" Sets the given option to the given value for this network. \"\"\"\n wireless.SetWirelessProperty(self.networkID, option, value)\n def set_values(self):\n \"\"\" Set the various network settings to the right values. \"\"\"\n networkID = self.networkID\n self.txt_ip.set_text(self.format_entry(networkID,\"ip\"))\n self.txt_netmask.set_text(self.format_entry(networkID,\"netmask\"))\n self.txt_gateway.set_text(self.format_entry(networkID,\"gateway\"))\n self.chkbox_global_dns.set_active(bool(wireless.GetWirelessProperty(networkID,\n 'use_global_dns')))\n self.txt_dns_1.set_text(self.format_entry(networkID, \"dns1\"))\n self.txt_dns_2.set_text(self.format_entry(networkID, \"dns2\"))\n self.txt_dns_3.set_text(self.format_entry(networkID, \"dns3\"))\n self.reset_static_checkboxes()\n self.chkbox_encryption.set_active(bool(wireless.GetWirelessProperty(networkID,\n 'encryption')))\n self.chkbox_global_settings.set_active(bool(wireless.GetWirelessProperty(networkID,\n 'use_settings_globally')))\n activeID = -1 \n user_enctype = wireless.GetWirelessProperty(networkID, \"enctype\")\n for x, enc_type in enumerate(self.encrypt_types):\n if enc_type[1] == user_enctype:\n activeID = x\n self.combo_encryption.set_active(activeID)\n if activeID != -1:\n self.chkbox_encryption.set_active(True)\n self.combo_encryption.set_sensitive(True)\n self.vbox_encrypt_info.set_sensitive(True)\n else:\n self.combo_encryption.set_active(0)\n self.change_encrypt_method()\n def format_entry(self, networkid, label):\n \"\"\" Helper method for fetching/formatting wireless properties. \"\"\"\n return noneToBlankString(wireless.GetWirelessProperty(networkid, label))\n def toggle_encryption(self, widget=None):\n \"\"\" Toggle the encryption combobox based on the encryption checkbox. \"\"\"\n active = self.chkbox_encryption.get_active()\n self.vbox_encrypt_info.set_sensitive(active)\n self.combo_encryption.set_sensitive(active)\n def change_encrypt_method(self, widget=None):\n \"\"\" Load all the entries for a given encryption method. \"\"\"\n for z in self.vbox_encrypt_info:\n z.destroy() \n ID = self.combo_encryption.get_active()\n methods = misc.LoadEncryptionMethods()\n self.encryption_info = {}\n if ID == -1:\n self.combo_encryption.set_active(0)\n ID = 0\n opts = methods[ID][2]\n for x in opts:\n box = None\n if language.has_key(opts[x][0]):\n box = LabelEntry(language[opts[x][0].lower().replace(' ','_')])\n else:\n box = LabelEntry(opts[x][0].replace('_',' '))\n box.set_auto_hidden(True)\n self.vbox_encrypt_info.pack_start(box)\n self.encryption_info[opts[x][1]] = box.entry\n box.entry.set_text(noneToBlankString(\n wireless.GetWirelessProperty(self.networkID, opts[x][1])))\n self.vbox_encrypt_info.show_all() \nclass NetworkEntry(gtk.HBox):\n def __init__(self, dbus_ifaces):\n \"\"\" Base network entry class.\n Provides gtk objects used by both the WiredNetworkEntry and\n WirelessNetworkEntry classes.\n \"\"\"\n global daemon, wired, wireless\n daemon = dbus_ifaces[\"daemon\"]\n wired = dbus_ifaces[\"wired\"]\n wireless = dbus_ifaces[\"wireless\"]\n gtk.HBox.__init__(self, False, 2)\n self.expander = gtk.Expander()\n self.image = gtk.Image()\n self.pack_start(self.image, False, False)\n self.connect_button = gtk.Button(stock=gtk.STOCK_CONNECT)\n self.connect_hbox = gtk.HBox(False, 2)\n self.connect_hbox.pack_start(self.connect_button, False, False)\n self.connect_hbox.show()\n self.disconnect_button = gtk.Button(stock=gtk.STOCK_DISCONNECT)\n self.connect_hbox.pack_start(self.disconnect_button, False, False)\n self.expander_vbox = gtk.VBox(False, 1)\n self.expander_vbox.show()\n self.expander_vbox.pack_start(self.expander)\n self.expander_vbox.pack_start(self.connect_hbox, False, False)\n self.pack_end(self.expander_vbox)\n self.advanced_button = gtk.Button()\n self.advanced_image = gtk.Image()\n self.advanced_image.set_from_stock(gtk.STOCK_EDIT, 4)\n self.advanced_image.set_padding(4, 0)\n self.advanced_button.set_alignment(.5, .5)\n self.advanced_button.set_label(language['advanced_settings'])\n self.advanced_button.set_image(self.advanced_image)\n self.script_button = gtk.Button()\n self.script_image = gtk.Image()\n self.script_image.set_from_stock(gtk.STOCK_EXECUTE, 4)\n self.script_image.set_padding(4, 0)\n self.script_button.set_alignment(.5, .5)\n self.script_button.set_image(self.script_image)\n self.script_button.set_label(language['scripts'])\n self.settings_hbox = gtk.HBox(False, 3)\n self.settings_hbox.set_border_width(5)\n self.settings_hbox.pack_start(self.script_button, False, False)\n self.settings_hbox.pack_start(self.advanced_button, False, False)\n self.vbox_top = gtk.VBox(False, 0)\n self.vbox_top.pack_end(self.settings_hbox, False, False)\n aligner = gtk.Alignment(xscale=1.0)\n aligner.add(self.vbox_top)\n aligner.set_padding(0, 0, 15, 0)\n self.expander.add(aligner)\n def destroy_called(self, *args):\n \"\"\" Clean up everything. \n This might look excessive, but it was the only way to prevent\n memory leakage.\n \"\"\"\n for obj in vars(self):\n try: obj.destroy()\n except: pass\n if hasattr(obj, '__del__'):\n obj.__del__()\n else:\n del obj\n for obj in vars(super(NetworkEntry, self)):\n try: obj.destroy()\n except: pass\n if hasattr(obj, '__del__'):\n obj.__del__()\n else:\n del obj\n super(NetworkEntry, self).destroy()\n self.destroy()\nclass WiredNetworkEntry(NetworkEntry):\n def __init__(self, dbus_ifaces):\n \"\"\" Load the wired network entry. \"\"\"\n NetworkEntry.__init__(self, dbus_ifaces)\n self.image.set_alignment(.5, 0)\n self.image.set_size_request(60, -1)\n self.image.set_from_icon_name(\"network-wired\", 6)\n self.image.show()\n self.expander.show()\n self.connect_button.show()\n self.expander.set_label(language['wired_network'])\n self.is_full_gui = True\n self.button_add = gtk.Button(stock=gtk.STOCK_ADD)\n self.button_delete = gtk.Button(stock=gtk.STOCK_DELETE)\n self.profile_help = gtk.Label(language['wired_network_instructions'])\n self.chkbox_default_profile = gtk.CheckButton(language['default_wired'])\n self.combo_profile_names = gtk.combo_box_entry_new_text()\n self.profile_list = wired.GetWiredProfileList()\n if self.profile_list:\n for x in self.profile_list:\n self.combo_profile_names.append_text(x)\n self.profile_help.set_justify(gtk.JUSTIFY_LEFT)\n self.profile_help.set_line_wrap(True)\n self.hbox_temp = gtk.HBox(False, 0)\n self.hbox_def = gtk.HBox(False, 0)\n self.vbox_top.pack_start(self.profile_help, True, True)\n self.vbox_top.pack_start(self.hbox_def)\n self.vbox_top.pack_start(self.hbox_temp)\n self.hbox_temp.pack_start(self.combo_profile_names, True, True)\n self.hbox_temp.pack_start(self.button_add, False, False)\n self.hbox_temp.pack_start(self.button_delete, False, False)\n self.hbox_def.pack_start(self.chkbox_default_profile, False, False)\n self.button_add.connect(\"clicked\", self.add_profile)\n self.button_delete.connect(\"clicked\", self.remove_profile)\n self.chkbox_default_profile.connect(\"toggled\",\n self.toggle_default_profile)\n self.combo_profile_names.connect(\"changed\", self.change_profile)\n self.script_button.connect(\"button-press-event\", self.edit_scripts)\n if stringToBoolean(wired.GetWiredProperty(\"default\")):\n self.chkbox_default_profile.set_active(True)\n else:\n self.chkbox_default_profile.set_active(False)\n self.show_all()\n self.profile_help.hide()\n self.advanced_dialog = WiredSettingsDialog(self.combo_profile_names.get_active_text())\n if self.profile_list is not None:\n prof = wired.GetDefaultWiredNetwork()\n if prof != None: \n i = 0\n while self.combo_profile_names.get_active_text() != prof:\n self.combo_profile_names.set_active(i)\n i += 1\n else:\n self.combo_profile_names.set_active(0)\n self.expander.set_expanded(False)\n else:\n if not wired.GetAlwaysShowWiredInterface():\n self.expander.set_expanded(True)\n self.profile_help.show() \n self.check_enable()\n self.wireddis = self.connect(\"destroy\", self.destroy_called)\n def destroy_called(self, *args):\n \"\"\" Clean up everything. \n This might look excessive, but it was the only way to prevent\n memory leakage.\n \"\"\"\n self.disconnect(self.wireddis)\n self.advanced_dialog.destroy_called()\n del self.advanced_dialog\n for obj in vars(self):\n if hasattr(obj, \"destroy\"):\n obj.destroy()\n if hasattr(obj, '__del__'):\n obj.__del__()\n else:\n del obj\n super(WiredNetworkEntry, self).destroy_called()\n self.destroy()\n del self\n def edit_scripts(self, widget=None, event=None):\n \"\"\" Launch the script editting dialog. \"\"\"\n profile = self.combo_profile_names.get_active_text()\n if os.getuid() != 0:\n try:\n sudo_prog = misc.choose_sudo_prog()\n msg = \"You must enter your password to configure scripts\"\n if sudo_prog.endswith(\"gksu\") or sudo_prog.endswith(\"ktsuss\"):\n msg_flag = \"-m\"\n else:\n msg_flag = \"--caption\"\n misc.LaunchAndWait([sudo_prog, msg_flag, msg, \n wpath.lib + \"configscript.py\", profile,\n \"wired\"])\n except misc.WicdError:\n error(None, \"Could not find a graphical sudo program.\" + \\\n \" Script editor could not be launched.\")\n else:\n misc.LaunchAndWait([wpath.lib + \"configscript.py\", profile, \"wired\"])\n def check_enable(self):\n \"\"\" Disable objects if the profile list is empty. \"\"\"\n profile_list = wired.GetWiredProfileList()\n if profile_list == None:\n self.button_delete.set_sensitive(False)\n self.connect_button.set_sensitive(False)\n self.advanced_button.set_sensitive(False)\n self.script_button.set_sensitive(False)\n def update_connect_button(self, state, apbssid=None):\n \"\"\" Update the connection/disconnect button for this entry. \"\"\"\n if state == misc.WIRED:\n self.disconnect_button.show()\n self.connect_button.hide()\n else:\n self.disconnect_button.hide()\n self.connect_button.show()\n def add_profile(self, widget):\n \"\"\" Add a profile to the profile list. \"\"\"\n profile_name = self.combo_profile_names.get_active_text()\n profile_list = wired.GetWiredProfileList()\n if profile_list:\n if profile_name in profile_list:\n return False\n if profile_name != \"\":\n self.profile_help.hide()\n wired.CreateWiredNetworkProfile(profile_name)\n self.combo_profile_names.prepend_text(profile_name)\n self.combo_profile_names.set_active(0)\n self.advanced_dialog.prof_name = profile_name\n if self.is_full_gui:\n self.button_delete.set_sensitive(True)\n self.connect_button.set_sensitive(True)\n self.advanced_button.set_sensitive(True)\n self.script_button.set_sensitive(True)\n def remove_profile(self, widget):\n \"\"\" Remove a profile from the profile list. \"\"\"\n profile_name = self.combo_profile_names.get_active_text()\n wired.DeleteWiredNetworkProfile(profile_name)\n self.combo_profile_names.remove_text(self.combo_profile_names.\n get_active())\n self.combo_profile_names.set_active(0)\n self.advanced_dialog.prof_name = self.combo_profile_names.get_active_text()\n if not wired.GetWiredProfileList():\n self.profile_help.show()\n entry = self.combo_profile_names.child\n entry.set_text(\"\")\n if self.is_full_gui:\n self.button_delete.set_sensitive(False)\n self.advanced_button.set_sensitive(False)\n self.script_button.set_sensitive(False)\n self.connect_button.set_sensitive(False)\n else:\n self.profile_help.hide()\n def toggle_default_profile(self, widget):\n \"\"\" Change the default profile. \"\"\"\n if self.chkbox_default_profile.get_active():\n wired.UnsetWiredDefault()\n wired.SetWiredProperty(\"default\",\n self.chkbox_default_profile.get_active())\n wired.SaveWiredNetworkProfile(self.combo_profile_names.get_active_text())\n def change_profile(self, widget):\n \"\"\" Called when a new profile is chosen from the list. \"\"\"\n if self.combo_profile_names.get_active() > -1:\n if not self.is_full_gui:\n return\n profile_name = self.combo_profile_names.get_active_text()\n wired.ReadWiredNetworkProfile(profile_name)\n self.advanced_dialog.txt_ip.set_text(self.format_entry(\"ip\"))\n self.advanced_dialog.txt_netmask.set_text(self.format_entry(\"netmask\"))\n self.advanced_dialog.txt_gateway.set_text(self.format_entry(\"gateway\"))\n self.advanced_dialog.txt_dns_1.set_text(self.format_entry(\"dns1\"))\n self.advanced_dialog.txt_dns_2.set_text(self.format_entry(\"dns2\"))\n self.advanced_dialog.txt_dns_3.set_text(self.format_entry(\"dns3\"))\n self.advanced_dialog.prof_name = profile_name\n is_default = wired.GetWiredProperty(\"default\")\n self.chkbox_default_profile.set_active(stringToBoolean(is_default))\n def format_entry(self, label):\n \"\"\" Help method for fetching/formatting wired properties. \"\"\"\n return noneToBlankString(wired.GetWiredProperty(label))\nclass WirelessNetworkEntry(NetworkEntry):\n def __init__(self, networkID, dbus_ifaces):\n \"\"\" Build the wireless network entry. \"\"\"\n NetworkEntry.__init__(self, dbus_ifaces)\n self.networkID = networkID\n self.image.set_padding(0, 0)\n self.image.set_alignment(.5, 0)\n self.image.set_size_request(60, -1)\n self.image.set_from_icon_name(\"network-wired\", 6)\n self.essid = wireless.GetWirelessProperty(networkID, \"essid\")\n self.lbl_strength = GreyLabel()\n self.lbl_encryption = GreyLabel()\n self.lbl_mac = GreyLabel()\n self.lbl_channel = GreyLabel()\n self.lbl_mode = GreyLabel()\n self.hbox_status = gtk.HBox(False, 5)\n self.chkbox_autoconnect = gtk.CheckButton(language['automatic_connect'])\n self.set_signal_strength(wireless.GetWirelessProperty(networkID, \n 'quality'),\n wireless.GetWirelessProperty(networkID, \n 'strength'))\n self.set_mac_address(wireless.GetWirelessProperty(networkID, 'bssid'))\n self.set_mode(wireless.GetWirelessProperty(networkID, 'mode'))\n self.set_channel(wireless.GetWirelessProperty(networkID, 'channel'))\n self.set_encryption(wireless.GetWirelessProperty(networkID,\n 'encryption'),\n wireless.GetWirelessProperty(networkID, \n 'encryption_method'))\n self.expander.set_use_markup(True)\n self.expander.set_label(self._escape(self.essid) + \" \" + \n self.lbl_strength.get_label() + \" \" +\n self.lbl_encryption.get_label() + \" \" +\n self.lbl_mac.get_label())\n self.hbox_status.pack_start(self.lbl_strength, True, True)\n self.hbox_status.pack_start(self.lbl_encryption, True, True)\n self.hbox_status.pack_start(self.lbl_mac, True, True)\n self.hbox_status.pack_start(self.lbl_mode, True, True)\n self.hbox_status.pack_start(self.lbl_channel, True, True)\n self.vbox_top.pack_start(self.chkbox_autoconnect, False, False)\n self.vbox_top.pack_start(self.hbox_status, True, True)\n if stringToBoolean(self.format_entry(networkID, \"automatic\")):\n self.chkbox_autoconnect.set_active(True)\n else:\n self.chkbox_autoconnect.set_active(False)\n self.chkbox_autoconnect.connect(\"toggled\", self.update_autoconnect)\n self.script_button.connect(\"button-press-event\", self.edit_scripts) \n self.show_all()\n self.advanced_dialog = WirelessSettingsDialog(networkID)\n self.wifides = self.connect(\"destroy\", self.destroy_called)\n def _escape(self, val):\n return val.replace(\"&\", \"&\").replace(\"<\", \"<\").\\\n replace(\">\",\">\").replace(\"'\", \"'\").replace('\"', \""\")\n def destroy_called(self, *args):\n \"\"\" Clean up everything. \n This might look excessive, but it was the only way to prevent\n memory leakage.\n \"\"\"\n self.disconnect(self.wifides)\n self.advanced_dialog.destroy_called()\n del self.advanced_dialog\n for obj in vars(self):\n if hasattr(obj, \"destroy\"):\n obj.destroy()\n if hasattr(obj, '__del__'):\n obj.__del__()\n else:\n del obj\n super(WirelessNetworkEntry, self).destroy_called()\n self.destroy()\n del self\n def set_signal_strength(self, strength, dbm_strength):\n \"\"\" Set the signal strength displayed in the WirelessNetworkEntry. \"\"\"\n if strength is not None:\n strength = int(strength)\n else:\n strength = -1\n if dbm_strength is not None:\n dbm_strength = int(dbm_strength)\n else:\n dbm_strength = -100\n display_type = daemon.GetSignalDisplayType()\n if daemon.GetWPADriver() == 'ralink legacy' or display_type == 1:\n if dbm_strength >= -60:\n signal_img = 'signal-100.png'\n elif dbm_strength >= -70:\n signal_img = 'signal-75.png'\n elif dbm_strength >= -80:\n signal_img = 'signal-50.png'\n else:\n signal_img = 'signal-25.png'\n ending = \"dBm\"\n disp_strength = str(dbm_strength)\n else:\n if strength > 75:\n signal_img = 'signal-100.png'\n elif strength > 50:\n signal_img = 'signal-75.png'\n elif strength > 25:\n signal_img = 'signal-50.png'\n else:\n signal_img = 'signal-25.png'\n ending = \"%\"\n disp_strength = str(strength)\n self.image.set_from_file(wpath.images + signal_img)\n self.lbl_strength.set_label(disp_strength + ending)\n def update_connect_button(self, state, apbssid):\n \"\"\" Update the connection/disconnect button for this entry. \"\"\"\n if not apbssid:\n apbssid = wireless.GetApBssid()\n if state == misc.WIRELESS and \\\n apbssid == wireless.GetWirelessProperty(self.networkID, \"bssid\"):\n self.disconnect_button.show()\n self.connect_button.hide()\n else:\n self.disconnect_button.hide()\n self.connect_button.show()\n def set_mac_address(self, address):\n \"\"\" Set the MAC address for the WirelessNetworkEntry. \"\"\"\n self.lbl_mac.set_label(str(address))\n def set_encryption(self, on, ttype):\n \"\"\" Set the encryption value for the WirelessNetworkEntry. \"\"\"\n if on and ttype:\n self.lbl_encryption.set_label(str(ttype))\n if on and not ttype: \n self.lbl_encryption.set_label(language['secured'])\n if not on:\n self.lbl_encryption.set_label(language['unsecured'])\n def set_channel(self, channel):\n \"\"\" Set the channel value for the WirelessNetworkEntry. \"\"\"\n self.lbl_channel.set_label(language['channel'] + ' ' + str(channel))\n def set_mode(self, mode):\n \"\"\" Set the mode value for the WirelessNetworkEntry. \"\"\"\n self.lbl_mode.set_label(str(mode))\n def format_entry(self, networkid, label):\n \"\"\" Helper method for fetching/formatting wireless properties. \"\"\"\n return noneToBlankString(wireless.GetWirelessProperty(networkid, label))\n def edit_scripts(self, widget=None, event=None):\n \"\"\" Launch the script editting dialog. \"\"\"\n if os.getuid() != 0:\n try:\n sudo_prog = misc.choose_sudo_prog()\n msg = \"You must enter your password to configure scripts\"\n if sudo_prog.endswith(\"gksu\") or sudo_prog.endswith(\"ktsuss\"):\n msg_flag = \"-m\"\n else:\n msg_flag = \"--caption\"\n misc.LaunchAndWait([sudo_prog, msg_flag, msg,\n wpath.lib + \"configscript.py\", \n str(self.networkID), \"wireless\"])\n except IOError:\n error(None, \"Could not find a graphical sudo program.\" + \\\n \" Script editor could no be launched.\")\n else:\n misc.LaunchAndWait([\"./configscript.py\", str(self.networkID),\n \"wireless\"])\n def update_autoconnect(self, widget=None):\n \"\"\" Called when the autoconnect checkbox is toggled. \"\"\"\n wireless.SetWirelessProperty(self.networkID, \"automatic\",\n noneToString(self.chkbox_autoconnect.\n get_active()))\n wireless.SaveWirelessNetworkProperty(self.networkID, \"automatic\")\n","sub_path":"wicd/rev519-557/right-branch-557/wicd/netentry.py","file_name":"netentry.py","file_ext":"py","file_size_in_byte":35581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"188544819","text":"import unittest\n\nfrom concrete.util.mem_io import (\n read_communication_from_buffer,\n write_communication_to_buffer,\n communication_deep_copy\n)\nfrom concrete.util.simple_comm import create_comm\nfrom concrete.structure.ttypes import Token\n\n\nclass TestCommunicationDeepCopy(unittest.TestCase):\n\n def assert_simple_comms_equal(self, comm1, comm2):\n self.assertEquals(comm1.id, comm2.id)\n self.assertEquals(comm1.uuid.uuidString, comm2.uuid.uuidString)\n self.assertEquals(comm1.metadata.tool, comm2.metadata.tool)\n self.assertEquals(comm1.metadata.timestamp, comm2.metadata.timestamp)\n self.assertEquals(\n comm1.sectionList[0].uuid.uuidString,\n comm2.sectionList[0].uuid.uuidString,\n )\n self.assertEquals(\n comm1.sectionList[0].kind,\n comm2.sectionList[0].kind,\n )\n self.assertEquals(\n comm1.sectionList[0].sentenceList[0].uuid.uuidString,\n comm2.sectionList[0].sentenceList[0].uuid.uuidString,\n )\n self.assertEquals(\n comm1.sectionList[0].sentenceList[0].tokenization.uuid,\n comm2.sectionList[0].sentenceList[0].tokenization.uuid,\n )\n self.assertEquals(\n comm1.sectionList[0].sentenceList[0].tokenization.kind,\n comm2.sectionList[0].sentenceList[0].tokenization.kind,\n )\n self.assertEquals(\n comm1.sectionList[0].sentenceList[0].tokenization.metadata.tool,\n comm2.sectionList[0].sentenceList[0].tokenization.metadata.tool,\n )\n self.assertEquals(\n comm1.sectionList[0].sentenceList[\n 0].tokenization.metadata.timestamp,\n comm2.sectionList[0].sentenceList[\n 0].tokenization.metadata.timestamp,\n )\n self.assertEquals(\n map(lambda t: t.text, comm1.sectionList[0].sentenceList[\n 0].tokenization.tokenList.tokenList),\n map(lambda t: t.text, comm2.sectionList[0].sentenceList[\n 0].tokenization.tokenList.tokenList),\n )\n self.assertEquals(\n map(lambda t: t.tokenIndex, comm1.sectionList[\n 0].sentenceList[0].tokenization.tokenList.tokenList),\n map(lambda t: t.tokenIndex, comm2.sectionList[\n 0].sentenceList[0].tokenization.tokenList.tokenList),\n )\n\n def test_communication_deep_copy(self):\n comm1 = create_comm('a-b-c', text='foo bar baz .')\n comm2 = communication_deep_copy(comm1)\n comm3 = communication_deep_copy(comm1)\n self.assert_simple_comms_equal(comm1, comm2)\n self.assert_simple_comms_equal(comm2, comm3)\n tkzn1 = comm1.sectionList[0].sentenceList[0].tokenization\n tkzn1.tokenList.tokenList[0] = Token(text='bbq', tokenIndex=0)\n tkzn2 = comm2.sectionList[0].sentenceList[0].tokenization\n self.assertNotEqual(\n map(lambda t: t.text, tkzn1.tokenList.tokenList),\n map(lambda t: t.text, tkzn2.tokenList.tokenList),\n )\n self.assert_simple_comms_equal(comm2, comm3)\n\n\nclass TestReadCommunicationFromBuffer(unittest.TestCase):\n\n def test_read_against_file_contents(self):\n filename = u'tests/testdata/simple_1.concrete'\n with open(filename, 'rb') as f:\n buf = f.read()\n comm = read_communication_from_buffer(buf)\n self.assertTrue(hasattr(comm, 'sentenceForUUID'))\n self.assertEquals('one', comm.id)\n\n def test_read_against_file_contents_no_add_references(self):\n filename = u'tests/testdata/simple_1.concrete'\n with open(filename, 'rb') as f:\n buf = f.read()\n comm = read_communication_from_buffer(buf, add_references=False)\n self.assertFalse(hasattr(comm, 'sentenceForUUID'))\n self.assertEquals('one', comm.id)\n\n\nclass TestWriteCommunicationToBuffer(unittest.TestCase):\n\n def test_write_against_file_contents(self):\n filename = u'tests/testdata/simple_1.concrete'\n with open(filename, 'rb') as f:\n f_buf = f.read()\n comm = read_communication_from_buffer(f_buf)\n buf = write_communication_to_buffer(comm)\n self.assertEquals(f_buf, buf)\n\n def test_read_write_fixed_point(self):\n comm = create_comm('comm-1')\n buf_1 = write_communication_to_buffer(comm)\n buf_2 = write_communication_to_buffer(\n read_communication_from_buffer(buf_1)\n )\n self.assertEquals(buf_1, buf_2)\n","sub_path":"tests/test_mem_io.py","file_name":"test_mem_io.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"425984605","text":"from unittest import TestCase\nfrom filemanager.arxiv import file_type\nfrom filemanager.arxiv.file_type import guess_file_type, get_type_priority, is_tex_type, get_type_name, get_type_priority, \\\n _is_tex_type, name, guess\nimport os.path\n\n# type_tests.append(['', ''])\n\ntype_tests = []\n#type_tests.append(['garbage.txt', 'shit'])\ntype_tests.append(['00README.XXX', 'TYPE_README'])\n# Ignore/Abort\ntype_tests.append(['head.tmp', 'TYPE_ALWAYS_IGNORE']) # new\ntype_tests.append(['body.tmp', 'TYPE_ALWAYS_IGNORE']) # new\ntype_tests.append(['missfont.log', 'TYPE_ABORT']) # new\n# TeX Auxillary Files\ntype_tests.append(['ms.bbl', 'TYPE_TEXAUX']) # new\ntype_tests.append(['ol.sty', 'TYPE_TEXAUX']) # new\n\ntype_tests.append(['SciPost.cls', 'TYPE_TEXAUX']) # new\n# archives\ntype_tests.append(['compressed.Z', 'TYPE_COMPRESSED'])\ntype_tests.append(['gzipped.gz', 'TYPE_GZIPPED'])\n# BZIP\ntype_tests.append(['short-1.txt.bz2', 'TYPE_BZIP2'])\ntype_tests.append(['short-4.txt.bz2', 'TYPE_BZIP2'])\ntype_tests.append(['short-9.txt.bz2', 'TYPE_BZIP2'])\n# Tar\ntype_tests.append(['testtar.tar', 'TYPE_TAR'])\n\ntype_tests.append(['verlinde.dvi', 'TYPE_DVI'])\n\n# type_tests.append(['image.gif', 'TYPE_IMAGE'])\n# Image\ntype_tests.append(['image.tif', 'TYPE_IMAGE'])\ntype_tests.append(['image.jpg', 'TYPE_IMAGE'])\ntype_tests.append(['image.png', 'TYPE_IMAGE'])\ntype_tests.append(['image.gif', 'TYPE_IMAGE']) # new\ntype_tests.append(['centaur_1_first1k.mpg', 'TYPE_ANIM'])\n\ntype_tests.append(['pipnss.jar', 'TYPE_JAR'])\ntype_tests.append(['odf_test.odt', 'TYPE_ODF'])\ntype_tests.append(['Hellotest.docx', 'TYPE_DOCX'])\ntype_tests.append(['Agenda_Elegant_Style_EN.Level1.docx', 'TYPE_DOCX'])\ntype_tests.append(['Helloworld.xlsx', 'TYPE_XLSX'])\ntype_tests.append(['holtxdoc.zip', 'TYPE_ZIP'])\ntype_tests.append(['Hellotest.not_docx_ext', 'TYPE_ZIP'])\ntype_tests.append(['Helloworld.not_xlsx_ext', 'TYPE_ZIP'])\ntype_tests.append(['odf_test.not_odt_ext', 'TYPE_ZIP'])\n\ntype_tests.append(['0604408.pdf', 'TYPE_RAR'])\ntype_tests.append(['minimal.pdf', 'TYPE_PDF']) # new\n\n# TeX\ntype_tests.append(['polch.tex', 'TYPE_LATEX'])\ntype_tests.append(['paper-t4.1_Vienna_preprint.tex', 'TYPE_LATEX2e'])\ntype_tests.append(['minMac.tex', 'TYPE_LATEX2e', '', 'This file was generated on MAC with \\r\\n'])\ntype_tests.append(['pascal_petit.tex', 'TYPE_PDFLATEX'])\n\n# a \\pdfoutput=1 may come in various places, all valid\ntype_tests.append(['pdfoutput_before_documentclass.tex', 'TYPE_PDFLATEX'])\ntype_tests.append(['pdfoutput_sameline_documentclass.tex', 'TYPE_PDFLATEX'])\ntype_tests.append(['pdfoutput_after_documentclass.tex', 'TYPE_PDFLATEX'])\ntype_tests.append(['pdfoutput_after_documentclass_big_comment_before.tex', 'TYPE_PDFLATEX'])\n# but if we put it too late it is ignored\ntype_tests.append(['pdfoutput_too_far_after_documentclass.tex', 'TYPE_LATEX2e'])\ntype_tests.append(['pdfoutput_too_far_after_documentclass_big_comment_before.tex', 'TYPE_LATEX2e'])\n# EPS\ntype_tests.append(['dos_eps_1.eps', 'TYPE_DOS_EPS'])\ntype_tests.append(['dos_eps_2.eps', 'TYPE_DOS_EPS'])\n\n# Need MAC\n\n# font files must not be detected as simple PS\ntype_tests.append(['rtxss.pfb', 'TYPE_PS_FONT'])\ntype_tests.append(['c059036l.pfb', 'TYPE_PS_FONT'])\ntype_tests.append(['hrscs.pfa', 'TYPE_PS_FONT'])\ntype_tests.append(['bchbi.pfa', 'TYPE_PS_FONT'])\ntype_tests.append(['mutau2-sub_first10kB.tar', 'TYPE_PS_PC', '',\n 'Should really be TYPE_TAR but this is old pre-posix tar which we will not support. Doing so would require re-implementation of the c-code used by the unix file command, there are no magic codes for this. http://issues.library.cornell.edu/browse/ARXIVDEV-146'])\n# error cases\ntype_tests.append(['10240_null_chars.tar', 'TYPE_FAILED'])\ntype_tests.append(['file_does_not_exit', 'TYPE_FAILED'])\n\ntype_tests.append(['fmultipart.txt', 'TYPE_FAILED'])\ntype_tests.append(['multipart.txt', 'TYPE_MULTI_PART_MIME'])\ntype_tests.append(['one.ps', 'TYPE_POSTSCRIPT'])\ntype_tests.append(['index.html', 'TYPE_HTML'])\ntype_tests.append(['sample.bib', 'TYPE_BIBTEX']) # new\n\nname_tests = []\n\n\nclass TestGuessFileType(TestCase):\n \"\"\"Test file type identification logic\"\"\"\n\n def test_file_type_guess(self):\n \"\"\"Test file type identification.\"\"\"\n\n cwd = os.getcwd()\n testfiles_dir = os.path.join(cwd, 'tests/type_test_files')\n\n # Reproduce tests from legacy system\n for test in type_tests:\n\n test_file, test_file_type, deep, note, *extras = test + [None] * 2\n new_path = os.path.join(testfiles_dir, test_file)\n\n debug = 0\n if debug:\n print(\"\\nTest:\" + test_file + \":\" + test_file_type + \"\\tDeep: \"\n + str(deep) + \"Note: \" + str(note))\n\n # Make the call - get the file type guess\n guessed_type, tex_type, error_msg = guess_file_type(new_path)\n\n # print(\"****File: \" + test_file + \" Guessed Type: \" + guessed_type\n # + \" TeX type: \" + tex_type + \" Error: \" + error_msg + \"\\n\")\n\n msg = \"Expected file '\" + test_file + \"' of type '\" + test_file_type + \"' but got '\" + guessed_type + \"'\"\n if note:\n msg = msg + \" (\" + note + \")\"\n\n self.assertEqual(guessed_type, test_file_type, msg)\n\n def test_get_type_name(self):\n \"\"\"Test human readable type name lookup.\"\"\"\n self.assertEqual(get_type_name('TYPE_LATEX'), 'LaTeX', 'Lookup type name')\n self.assertEqual(get_type_name('TYPE_TAR'), 'TAR archive', 'Lookup type name')\n self.assertEqual(get_type_name('TYPE_DAVID'), 'unknown', 'Lookup name for non existent type')\n\n\n def test_is_tex_type(self):\n \"\"\"Test that TeX file types are identified correctly.\"\"\"\n self.assertTrue(is_tex_type('TYPE_LATEX'), 'Expected TeX file type')\n self.assertTrue(is_tex_type('TYPE_TEX'), 'Expected TeX file type')\n self.assertTrue(is_tex_type('TYPE_TEX_priority2'), 'Expected TeX file type')\n self.assertFalse(is_tex_type('TYPE_HTML'), 'Expected non-TeX file type')\n\n\n def test_type_priority(self):\n \"\"\"Spot check type priorities.\"\"\"\n self.assertEqual(get_type_priority('TYPE_DOES_NOT_EXIST'), 0,\n 'Unknown type should return lowest priorit=0')\n self.assertLess(get_type_priority('TYPE_BIBTEX'), get_type_priority('TYPE_TEX'),\n 'TeX source higher priority than BibTeX')\n self.assertLess(get_type_priority('TYPE_TEX'), get_type_priority('TYPE_PDFTEX'),\n 'PDFTEX is higher priority then plain TEX source.')\n self.assertLess(get_type_priority('TYPE_LATEX'), get_type_priority('TYPE_LATEX2e'),\n 'PDFTEX is higher priority then plain TEX source.')\n self.assertLess(get_type_priority('TYPE_LATEX2e'), get_type_priority('TYPE_PDFLATEX'),\n 'PDFTEX is higher priority then plain TEX source.')\n\n self.assertLess(get_type_priority('TYPE_LATEX'), get_type_priority('TYPE_README'),\n 'README directives file higher priority than TeX source')\n\n # Add some specific priority tests to catch inadvertant changes to new list\n self.assertEqual(get_type_priority('TYPE_ABORT'), 1,\n 'Expect signal for immediate stop.')\n self.assertEqual(get_type_priority('TYPE_FAILED'), 2,\n 'Expect priority for TYPE_FAILED type guess.')\n self.assertEqual(get_type_priority('TYPE_PDF'), 13,\n 'Expect priority for TYPE_PDF type guess.')\n self.assertEqual(get_type_priority('TYPE_TEX'), 18,\n 'Expect priority for TYPE_TEX type guess.')\n self.assertEqual(get_type_priority('TYPE_LATEX'), 24,\n 'Expect priority for TYPE_LATEX type guess.')\n self.assertEqual(get_type_priority('TYPE_ZIP'), 39,\n 'Expect priority for TYPE_ZIP type guess.')\n self.assertEqual(get_type_priority('TYPE_INCLUDE'), 48,\n 'Expect priority for TYPE_INCLUDE type guess.')\n\n\nclass TestExternalMethods(TestCase):\n \"\"\"Test file type identification logic\"\"\"\n\n def test_abreviated_type_methods(self):\n cwd = os.getcwd()\n testfiles_dir = os.path.join(cwd, 'tests/type_test_files')\n testfile_path = os.path.join(testfiles_dir, 'image.gif')\n self.assertEqual(guess(testfile_path), \"image\", 'Check guess type with normalized/lower cased type')\n self.assertEqual(name('LATEX'), 'LaTeX', 'Lookup type name')\n self.assertTrue(_is_tex_type('LATEX'), 'Expected TeX file type')\n self.assertTrue(_is_tex_type('LATEX2E'), 'Expected TeX file type')\n self.assertTrue(_is_tex_type('TYPE_TEX_PRIORITY'), 'Expected TeX file type')\n self.assertFalse(_is_tex_type('TYPE_TEX_FAKE'), 'Expected non-TeX file type')\n","sub_path":"tests/test_unit_file_type.py","file_name":"test_unit_file_type.py","file_ext":"py","file_size_in_byte":8876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"528068572","text":"# # _*_coding:utf-8_*_\n# # Simple usage\n# from stanfordcorenlp import StanfordCoreNLP\n# # Other human languages support, e.g. Chinese\n# sentence = '朱元璋说我喜欢吃肉'\n# print('kaishi')\n# # with StanfordCoreNLP(r'/mnt/data/dev/model/stanford-chinese-corenlp', lang='zh') as nlp:\n# # print(nlp.word_tokenize(sentence))\n# # print(nlp.pos_tag(sentence))\n# # print(nlp.ner(sentence))\n# # print(nlp.parse(sentence))\n# # print(nlp.dependency_parse(sentence))\n\n\n# # nlp = StanfordCoreNLP(r'/mnt/data/dev/model/stanford-corenlp-full-2018-02-27', lang='zh')\n\n# # print(nlp.word_tokenize(sentence))\n# # nlp.close()\n# nlp = StanfordCoreNLP('http://localhost', port=9000, lang='zh')\n# print(nlp.word_tokenize(sentence))\n# print(nlp.pos_tag(sentence))\n# print(nlp.ner(sentence))\n# print(nlp.parse(sentence))\n# print(nlp.dependency_parse(sentence))\n\n# # with StanfordCoreNLP(r'/mnt/data/dev/model/stanford-corenlp-full-2018-02-27', lang='zh') as nlp:\n# # print(nlp.word_tokenize(sentence))\n# # print(nlp.pos_tag(sentence))\n# # print(nlp.ner(sentence))\n# # print(nlp.parse(sentence))\n# # print(nlp.dependency_parse(sentence))\n\n\n# coding=utf-8\n# java -mx4g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000\n\nimport json\nfrom stanfordcorenlp import StanfordCoreNLP\n\nnlp = StanfordCoreNLP(r'/mnt/data/dev/model/stanford-corenlp-full-2018-02-27', quiet=False, lang='zh')\nprops = {'annotators': 'coref', 'pipelineLanguage': 'zh'}\n\ntext =\"\"\"\n\n流浪猫的生活艰难,尤其是在这样高楼林立的社会,流浪猫的生活更加不容易了。比如说在一些恶劣的天气时,它们就无处可躲,只能深深的受着,能不能挺过去还不一定呢。好在,也有一些好心人会尽自己所能帮助流浪猫,在流浪猫遇到困难的时候伸出援助之手。\n\"\"\"\n\nprint(nlp.annotate(text, properties=props))\nresult = json.loads(nlp.annotate(text, properties=props))\n\nnum, mentions = result['corefs'].items()[0]\nfor mention in mentions:\n print(mention)","sub_path":"test/ltp.py","file_name":"ltp.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"23847792","text":"# David Dalisay\n# Aggregates raw data and stores calculations for metrics into their own collections.\n# Each function below defines a calculated metric.\n# See the list of calculated metrics in the \"Calculated Metrics\" section of the README\n\nimport requests\nimport ConfigParser\n\n# Start MongoDB client\nfrom pymongo import MongoClient\nclient = MongoClient('localhost', 27017)\n\n# Get configs\nconfig_parser = ConfigParser.ConfigParser()\n\ndef getMongoDB(db_name = 'local'):\n db = client[db_name]\n return db\n\ndef aggregateTotals():\n pass\n\ndef aggregateItemBuilds(championId=161):\n pass\n\ndef getKeyFromArray(arr):\n sorted_arr = sorted(arr)\n sorted_arr = [str(i) for i in sorted_arr]\n key = ''.join(sorted_arr)\n return key\n\ndef getChampsPerArr(champIds):\n local_db = getMongoDB()\n champion_col = local_db['champions']\n champNames = [champion_col.find_one({'championId':c_id}) for c_id in champIds]\n return champNames\n\ndef aggregateComps():\n # Get mongo db and collection\n local_db = getMongoDB()\n matches_col = local_db['matches']\n champion_col = local_db['champions']\n aggr_comps_col = local_db['aggr_comps']\n\n comps = {} # comps[comp_key] = {wins,losses,damage,kills,deaths,assists,gold,games}\n for match in matches_col.find():\n match_details = match[\"match_details\"]\n if \"participants\" not in match_details: # TODO - current hack...\n continue\n participants = match_details[\"participants\"]\n champIds = {100:[],200:[]}\n for participant in participants:\n champIds[participant['teamId']].append(participant['championId'])\n\n velkozTeam = 100\n if 161 in champIds[200]:\n velkozTeam = 200\n\n comp_key = getKeyFromArray(champIds[velkozTeam])\n if comp_key not in comps:\n comps[comp_key] = {\"wins\":0,\"losses\":0,\"damage\":0,\"kills\":0,\"deaths\":0,\"assists\":0,\"gold\":0,\"games\":0,\"champIds\":champIds[velkozTeam]}\n\n teamWin = 0\n for team in match[\"match_details\"][\"teams\"]:\n if team[\"winner\"]:\n teamWin = 1\n\n comps[comp_key][\"wins\"] += teamWin\n\n for comp in comps:\n ids = comps[comp]['champIds']\n names = getChampsPerArr(ids)\n print(\"{0} ---- {1}\".format(names,comps[comp]))\n raw_input()\n return comps\n\n# Aggregates matchups against championId with all lane opponents and evaluates wins, losses, cs, wards, and total games.\n# Aggregated numbers are stored in aggr_matchups.\ndef aggregateMatchups(championId=161):\n # Get mongo db and collection\n local_db = getMongoDB()\n matches_col = local_db['matches']\n champion_col = local_db['champions']\n aggr_matchup_col = local_db['aggr_matchups']\n\n total_matches = 0\n\n matchups = {} #'wins':{},'losses':{},'creep':{},'wards':{},'games':{}\n for match_details in matches_col.find():\n all_participants = {\n 100: {\"TOP\":\"N/A\",\"JUNGLE\":\"N/A\",\"MIDDLE\":\"N/A\",\"BOTTOM\":\"N/A\",\"SUPPORT\":\"N/A\"},\n 200: {\"TOP\":\"N/A\",\"JUNGLE\":\"N/A\",\"MIDDLE\":\"N/A\",\"BOTTOM\":\"N/A\",\"SUPPORT\":\"N/A\"}\n }\n\n # Lane that the target champion is in\n champion_lane = \"\"\n\n # Team that the opposing champion is on\n opponent_team = 0\n\n # Int representing whether or not both the target champion and their opponent has been found\n foundBoth = 0\n\n # Get match records\n match = match_details['match_details']\n\n # Look through each summoner in an individual match\n targetchampion_win = 0\n targetchampion_creep = 0\n targetchampion_wards = 0\n targetchampion_id = championId\n targetchampion_name = champion_col.find({'championId':championId})\n opposingchampion_id = 0\n opposingchampion_name = \"\"\n if 'participants' not in match:\n continue\n for participant in match['participants']:\n\n # If foundBoth = 2, it means that I found the target summoner and the opponent.\n if foundBoth >= 2:\n break\n\n # Track all participants so far as a reference for later\n all_participants[participant['teamId']][participant['timeline']['lane']] = participant\n\n # Identify target summoner and opposing summoner\n if participant['championId'] == 161 or champion_lane:\n # if it's the opponent and they are already found - opposing champion\n if champion_lane and all_participants[opponent_team][champion_lane] != \"N/A\":\n opponent = all_participants[opponent_team][champion_lane]\n opposingchampion_id = int(opponent['championId'])\n opposingchampion_name = champion_col.find({'championId:':opposingchampion_id})\n\n # if it's the champion you're looking for - target champion\n else:\n champion_lane = participant['timeline']['lane']\n champion_team = participant['teamId']\n\n # If target champion won\n if participant['stats']['winner']:\n targetchampion_win = 1\n else:\n targetchampion_win = 0\n\n # Get target champion cs\n targetchampion_creep = int(participant['stats']['minionsKilled'])\n\n # Get target champion wards\n targetchampion_wards = int(participant['stats']['wardsPlaced'])\n\n # if the champion is on team 100, then opponent is on team 200 - and vice versa\n if champion_team == 100:\n opponent_team = 200\n else:\n opponent_team = 100\n\n # Append matchup records to total aggregation of matchups\n if opposingchampion_id not in matchups:\n matchups[opposingchampion_id] = {'wins':0,'losses':0,'creep':0,'wards':0,'games':0}\n\n # Append wins/losses\n if targetchampion_win == 1:\n matchups[opposingchampion_id]['wins'] += 1\n else:\n matchups[opposingchampion_id]['losses'] += 1\n\n # Append creep\n matchups[opposingchampion_id]['creep'] += targetchampion_creep\n\n # Append wards\n matchups[opposingchampion_id]['wards'] += targetchampion_wards\n\n # Append games played (which is just 1 more game than before)\n matchups[opposingchampion_id]['games'] += 1\n total_matches += 1\n\n # Load data into aggr_matchups.\n for matchup in matchups:\n if matchup == 0:\n continue\n champName = champion_col.find_one({'championId':matchup})['championName']\n aggr_matchup_col.insert_one({'opposingchampion_id':matchup,'opposingchampion_name':champName,'matchup_details':matchups[matchup]})\n\n\n print(\"total matches: {0}\".format(total_matches))\n # Close mongo client\n client.close()\n\ndef aggregateItemBuildMatchups(championId = 161,allChampions=False):\n # Get mongo db and collection\n local_db = getMongoDB()\n matches_col = local_db['matches']\n champion_col = local_db['champions']\n items_col = local_db['items']\n aggr_itembuild_matchup_col = local_db['aggr_itembuild_matchups']\n\n total_matches = 0\n\n # error_log\n error_log = {}\n matchups = {}\n matches_count = 0\n for match_details in matches_col.find():\n all_participants = {\n 100: {\"TOP\":\"N/A\",\"JUNGLE\":\"N/A\",\"MIDDLE\":\"N/A\",\"BOTTOM\":\"N/A\",\"SUPPORT\":\"N/A\"},\n 200: {\"TOP\":\"N/A\",\"JUNGLE\":\"N/A\",\"MIDDLE\":\"N/A\",\"BOTTOM\":\"N/A\",\"SUPPORT\":\"N/A\"}\n }\n\n # Lane that the target champion is in\n champion_lane = \"\"\n\n # Team that the opposing champion is on\n opponent_team = 0\n\n # Int representing whether or not both the target champion and their opponent has been found\n foundBoth = 0\n\n # Get match records\n match = match_details['match_details']\n\n # Look through each summoner in an individual match\n targetchampion_win = 0\n targetchampion_id = championId\n targetchampion_name = champion_col.find({'championId':championId})\n targetchampion_kills = 0\n targetchampion_deaths = 0\n targetchampion_assists = 0\n targetchampion_damagedealt = 0.0\n targetchampion_goldearned = 0.0\n targetchampion_build = []\n\n opposingchampion_id = 0\n opposingchampion_name = \"\"\n opposingchampion_build = []\n\n wentThrough = False\n runThrough = 0\n\n if 'participants' not in match:\n if \"participants not in match\" not in error_log:\n error_log[\"participants not in match\"] = 0\n error_log[\"participants not in match\"] += 1\n continue\n for participant in match['participants']:\n # If foundBoth = 2, it means that I found the target summoner and the opponent.\n if foundBoth >= 2:\n break\n\n # Track all participants so far as a reference for later\n all_participants[participant['teamId']][participant['timeline']['lane']] = participant\n\n # Identify target summoner and opposing summoner\n if participant['championId'] == 161 or champion_lane:\n # if it's the opponent and they are already found - opposing champion\n if champion_lane and all_participants[opponent_team][champion_lane] != \"N/A\":\n wentThrough = True\n opponent = all_participants[opponent_team][champion_lane]\n opposingchampion_id = int(opponent['championId'])\n opposingchampion_name = champion_col.find_one({'championId':opposingchampion_id})['championName']\n opposingchampion_build = [\n opponent['stats']['item1'],\n opponent['stats']['item2'],\n opponent['stats']['item3'],\n opponent['stats']['item4'],\n opponent['stats']['item5'],\n opponent['stats']['item6']\n ]\n foundBoth += 1\n\n # if it's the champion you're looking for - target champion\n elif participant['championId'] == 161:\n print(\"participant['championId'] = {0}\".format(participant['championId']))\n runThrough += 1\n champion_lane = participant['timeline']['lane']\n print(\"champion_lane = {0}\".format(champion_lane))\n champion_team = participant['teamId']\n\n # If target champion won\n if participant['stats']['winner']:\n targetchampion_win = 1\n else:\n targetchampion_win = 0\n\n # Get target champion item build\n targetchampion_build = [\n participant['stats']['item1'],\n participant['stats']['item2'],\n participant['stats']['item3'],\n participant['stats']['item4'],\n participant['stats']['item5'],\n participant['stats']['item6']\n ]\n\n # Get target champion number of kills, deaths ,assists\n targetchampion_kills += participant['stats']['kills']\n targetchampion_deaths += participant['stats']['deaths']\n targetchampion_assists += participant['stats']['assists']\n\n # Get target champion damage dealt to champions\n targetchampion_damagedealt += participant['stats']['totalDamageDealtToChampions']\n\n # Get target champion gold earned\n targetchampion_goldearned += participant['stats']['goldEarned']\n\n\n # if the champion is on team 100, then opponent is on team 200 - and vice versa\n if champion_team == 100:\n opponent_team = 200\n else:\n opponent_team = 100\n\n foundBoth += 1\n\n # Append matchup records to total aggregation of matchups\n if opposingchampion_id == 0:\n # print(\"runThrough = {0}\".format(runThrough))\n # print(\"wentThrough = {0}\".format(wentThrough))\n print(\"opposing champion id = 0, match_id = {0}\".format(match_details['m_id']))\n # raw_input()\n if opposingchampion_id not in matchups:\n matchups[opposingchampion_id] = {}\n\n # Append item build records\n # Sort item build, append to item build count\n # try:\n item_build = filter(lambda a: a != 0, targetchampion_build)\n item_build = sorted(item_build)\n item_build_names = []\n for item in item_build:\n item_name = \"\"\n try:\n item_name = items_col.find_one({\"id\": int(item)})['name']\n except:\n item_name = \"Name not found.\"\n item_build_names.append(item_name)\n item_build_id = ''.join(str(item) for item in item_build)\n\n if item_build_id not in matchups[opposingchampion_id]:\n matchups[opposingchampion_id][item_build_id] = {'item_build':[],'item_build_names':[],'wins':0, 'losses':0, 'games':0,'kills':0,'deaths':0,'assists':0,'total_damage_dealt_to_champions':0.0,'gold_earned':0.0}\n\n # Append item build by id\n matchups[opposingchampion_id][item_build_id]['item_build'] = item_build\n\n # Append item build by name\n matchups[opposingchampion_id][item_build_id]['item_build_names'] = item_build_names\n\n # Append wins/losses\n if targetchampion_win == 1:\n matchups[opposingchampion_id][item_build_id]['wins'] += 1\n else:\n matchups[opposingchampion_id][item_build_id]['losses'] += 1\n\n # Append games played (which is just 1 more game than before)\n matchups[opposingchampion_id][item_build_id]['games'] += 1\n\n # Append wins, deaths, assists\n matchups[opposingchampion_id][item_build_id]['kills'] += targetchampion_kills\n matchups[opposingchampion_id][item_build_id]['deaths'] += targetchampion_deaths\n matchups[opposingchampion_id][item_build_id]['assists'] += targetchampion_assists\n\n # Append damage dealt to champions\n matchups[opposingchampion_id][item_build_id]['total_damage_dealt_to_champions'] += targetchampion_damagedealt\n\n # Append gold earned\n matchups[opposingchampion_id][item_build_id]['gold_earned'] += targetchampion_goldearned\n\n # Load data into aggr_itembuild_matchups.\n\n badMatches = 0\n for matchup in matchups:\n if matchup == 0:\n for i in matchups[matchup]:\n badMatches += matchups[matchup][i]['games']\n continue\n champName = champion_col.find_one({'championId':matchup})['championName']\n for i in matchups[matchup]:\n total_matches += matchups[matchup][i]['games']\n aggr_itembuild_matchup_col.insert_one({'opposingchampion_id':matchup,'opposingchampion_name': champName,'matchup_details':matchups[matchup]})\n\n print(\"badMatches: {0}\".format(badMatches))\n\n return error_log\n\naggregateComps()","sub_path":"aggregate.py","file_name":"aggregate.py","file_ext":"py","file_size_in_byte":15339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"624671671","text":"from sfcsim.classes import *\nfrom sfcsim.algorithms import common\nimport time\nclass TS_scheduler(dynamic_scheduler):\n def __init__(self,tabu_length=10,iteration=50,stop_condition=5,log=False): #log=means not to print deployment procedure information\n super(TS_scheduler, self).__init__(log=log)\n self.tabu_list=[]\n self.tabu_length=tabu_length \n self.stop_condition=stop_condition\n self.iteraction_count=iteration #最大迭代次数\n\n self.max_deploy_record={} #存储最优解的解量\n self.max_deploy_solution={} #存储最优解的数字量\n self.global_max_deploy_record={} #存储全局最优解记录\n self.grade_list=[] #存储所有迭代的最优分数\n ###############################################\n self.all_sfc_deploy_solutions={} #存储对所有sfc的所有可行方案,以字典格式存储{'sfc1':[{},{},{}],...}\n self.solutions_length={} #存储所有sfc的所有可能部署方案个数\n self.last_num=0 #邻域变化之前的解\n \n #清除网���的所有sfc、vnf部署,同时清空记录\n def clear_network(self,network,sfcs): \n records_list=[]\n for sfc_id in self.get_records(): \n records_list.append(sfc_id) #存储key,防止字典/列表长度随迭代变化\n for i in records_list:\n self.remove_sfc(sfcs.get_sfc(i),network) \n for node in network.get_nodes():\n vnfs=network.get_vnfs(node.get_id())\n vnfs_list=[]\n for j in range(len(vnfs)): \n vnfs_list.append(vnfs[j].get_name()) \n for i in vnfs_list: \n network.delete_vnf(node.get_id(),i)\n\n #检查服务的总流量大小\n def check_score(self,record,sfcs): \n grade=0\n for sfc_id in record:\n if 'node' in record[sfc_id] and 'edge' in record[sfc_id]:\n if len(record[sfc_id]['node'])== sfcs.get_length(sfc_id)-2 and len(record[sfc_id]['edge'])== sfcs.get_length(sfc_id)-1:\n for bandwidth in sfcs.get_bandwidths(sfc_id):\n grade=grade+bandwidth\n return grade\n \n #通过记录执行部署操作并计算返回适应度\n def deploy_sfc_by_records(self,sfcs,network,vnf_types,records):#通过记录部署所有服务功能链\n for sfc_id in records:\n if records[sfc_id] !=-1: #{}表示不部署这条sfc\n log=True\n sfc=sfcs.get_sfc(sfc_id)\n for i in records[sfc_id]['node']:\n if self.deploy_nf_scale_out(sfc,network.get_node(records[sfc_id]['node'][i]),i,vnf_types)!=True: \n if sfc_id in self.get_records(): \n self.remove_sfc(sfc,network) \n log=False\n if log==False:\n break #跳出1层循环\n if log==False: #这条条sfc部署失败,执行下一条sfc的部署 \n continue \n for j in records[sfc_id]['edge']: \n edge_list=records[sfc_id]['edge'][j]\n edge=[]\n for m in range(len(edge_list)):\n edge.append(network.get_node(edge_list[m]))\n if self.deploy_link(sfc,j,network,edge)!=True: #链路部署失败,则将sfc删除\n if sfc.get_id() in self.get_records():\n self.remove_sfc(sfc,network) \n log=False \n if log==False:\n break #跳出1层循环\n fit=0\n record=self.get_records()\n for sfc_id in record: #所有sfc的虚拟链路相加之和\n if 'node' in record[sfc_id] and 'edge' in record[sfc_id]:\n if len(record[sfc_id]['node'])== sfcs.get_length(sfc_id)-2 and len(record[sfc_id]['edge'])== sfcs.get_length(sfc_id)-1:\n for bandwidth in sfcs.get_bandwidths(sfc_id):\n fit=fit+bandwidth\n self.clear_network(network,sfcs) \n return fit \n \n #获得进行邻域操作之后的新部署方案 \n def get_new_deploy_solution(self,neighbour):\n self.last_num=copy.deepcopy(self.max_deploy_solution[neighbour[0]])\n if neighbour[1] !=0:\n self.max_deploy_solution[neighbour[0]]+=neighbour[1]\n self.max_deploy_record[neighbour[0]]=self.all_sfc_deploy_records[neighbour[0]][self.max_deploy_solution[neighbour[0]]]\n else:\n self.max_deploy_solution[neighbour[0]]=-1\n self.max_deploy_record[neighbour[0]]=-1\n\n #回到邻域操作之前的部署方案 \n def get_last_deploy_solution(self,neighbour):\n self.max_deploy_solution[neighbour[0]]=self.last_num\n if self.last_num!=-1:\n self.max_deploy_record[neighbour[0]]=self.all_sfc_deploy_records[neighbour[0]][self.max_deploy_solution[neighbour[0]]]\n else:\n self.max_deploy_record[neighbour[0]]=-1\n \n # 获得一条sfc的部署邻域\n def get_neighbour(self,sfc_id):\n neighbour=[]\n num=self.max_deploy_solution[sfc_id]\n max_num=self.solutions_length[sfc_id] #获得最大id\n if num>0 :\n neighbour.append((sfc_id,-1))\n if num',neighbour)\n return neighbour\n\n # 获得单前解的所有邻域\n def get_neighbours(self):\n neighbours=[]\n for sfc_id in self.max_deploy_record:\n neighbours.extend(self.get_neighbour(sfc_id))\n return neighbours\n\n #判断邻域是否在禁忌表中\n def is_in_tabu_list(self,neighbour): #判断邻域是否在禁忌列表中\n lens=len(self.tabu_list) \n for data in self.tabu_list:\n if data[0]== neighbour[0] and data[1] == -neighbour[1]: #\n return True\n return False\n\n #计算邻域的适应度\n def calculate_fits(self,sfcs,network,vnf_types,neighbours): \n fits=[]\n for neighbour in neighbours: \n self.get_new_deploy_solution(neighbour) #进入新领域\n fits.append(self.deploy_sfc_by_records(sfcs,network,vnf_types,self.max_deploy_record))\n self.get_last_deploy_solution(neighbour) #回退到原始最优解\n return fits\n\n #执行一次搜索\n def single_search(self,network,sfcs,vnf_types): \n neighbours=self.get_neighbours() #获得解集合和对应邻域操作 neighbours=[('sfc1',1),('sfc2',1),...]\n # print('neighbours=>',neighbours)\n fits=self.calculate_fits(sfcs,network,vnf_types,neighbours) #计算所有邻域的适应度\n candidate_grade=max(fits) #获取最大适应度\n neighbour=neighbours[fits.index(candidate_grade)] #获取最大适应度所在邻域\n\n if candidate_grade > self.max_grade: #藐视法则\n print('************ new solution***********')\n self.max_grade = candidate_grade\n if self.is_in_tabu_list(neighbour): \n self.tabu_list.remove(neighbour)\n self.tabu_list.append(neighbour)\n if len(self.tabu_list) > self.tabu_length: #判断该禁忌列表长度是否以达到限制,是的话移除最初始的move\n self.tabu_list.remove(self.tabu_list[0])\n self.get_new_deploy_solution(neighbour) \n self.global_max_deploy_record=copy.deepcopy(self.max_deploy_record)\n return True\n else:\n print('************ old solution***********')\n while(self.is_in_tabu_list(neighbour)):\n fits[fits.index(candidate_grade)]=-1 #把最优解设置为最小值 \n candidate_grade=max(fits) \n neighbour=neighbours[fits.index(candidate_grade)] #获取最大适应度所在邻域\n self.tabu_list.append(neighbour)\n if len(self.tabu_list) > self.tabu_length: #判断该禁忌列表长度是否以达到限制,是的话移除最初始的move\n self.tabu_list.remove(self.tabu_list[0])\n self.get_new_deploy_solution(neighbour) #更新最优解\n return False\n\n #初始化,提前计算一些常用的量\n def init(self,init_record,network,sfcs): \n self._scheduler__records=init_record\n self._dynamic_scheduler__records=init_record\n self.__records=self.get_records() #更新初始解\n self.max_grade=self.check_score(init_record,sfcs) #更新初始目标值\n self.all_sfc_deploy_solutions,self.all_sfc_deploy_records=common.find_sfcs_solutions(network,sfcs,1) #先找到所有可行解的部署方案,第一项是数字记录,第二项为字符串记录\n for sfc_id in self.all_sfc_deploy_solutions: #每一条sfc的部署方案\n self.solutions_length[sfc_id]=len(self.all_sfc_deploy_solutions[sfc_id])\n self.max_deploy_record=common.records_node_to_str(self.get_records()) #存储最优解的字符串量\n for sfc_id in self.all_sfc_deploy_records:\n if sfc_id not in self.max_deploy_record:\n self.max_deploy_record[sfc_id]=-1\n self.max_deploy_solution=common.records_str_to_num(self.max_deploy_record,self.all_sfc_deploy_records) \n self.clear_network(network,sfcs)\n\n #主函数\n def deploy_sfcs(self,network,sfcs,vnf_types,init_record): \n start = time.clock()\n self.init(init_record,network,sfcs)\n for i in range(self.iteraction_count):\n if self.single_search(network,sfcs,vnf_types)==True: #进行一轮搜索\n count=0\n else:\n count=count+1\n self.grade_list.append(self.max_grade)\n end = time.clock()\n print('time=>',end-start,'s','max grade=>',self.max_grade)\n if(count>self.stop_condition):\n print(\"迭代%d次为发现更优解,迭代停止\"%(self.stop_condition))\n break\n end = time.clock()\n print('execution time=>',end-start,'s')\n print('optimal solution=>',self.max_grade,' =>',self.global_max_deploy_record)\n\n\n\n\n\n\n\n","sub_path":"build/lib/sfcsim/algorithms/TS_scheduler.py","file_name":"TS_scheduler.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"199040840","text":"# coding=utf-8\n# ☯ Author: SDLPython\n# ☯ Email : aoguangjin@chsdl.com\n# ☯ Date : 2021/3/17 14:57\n# ☯ File : alarm_3_action.py\n\nimport datetime\nimport numpy as np\nfrom dbPart.MSSql_SqlHelp_copy import MSSQL\n\n\nms2 = MSSQL(server=\"172.16.12.3\", user=\"sa\", pwd=\"@admin123\", db=\"AlarmInfo_test\")\ntime_anomaly = float(0.2)\n\n# 获取关联点位列表\ndef Get_PointRelation_List(point_list, distance):\n\n '''\n :param point_list: 站点列表\n :param distance: 公里数\n :return: 关联站点代码列表(含自身)\n '''\n\n point_list_id = str(point_list).replace('[', '').replace(']', '') if point_list else \"''\"\n sql1 = \"select device_id, association_device_id from T_Grid_PointRelation where distance <= '3000' and device_id in (\" + point_list_id + \") and association_device_id in (SELECT device_id FROM T_Grid_PointInfo WHERE device_type != '国控')\"\n temp_point_list = ms2.ExecQuery(sql1)\n # print('获取完成3000米站点')\n return temp_point_list\n\n\n# 智能报警\ndef SmartAlarm(sTime, DataGatherCode, PollutantCode, MonitorValue, point_diatance, now_stationdata,\n last_stationdata):\n # 时间异常\n time_warning_MoreTime(sTime, DataGatherCode, MonitorValue, PollutantCode, last_stationdata)\n\n # 空间异常\n Spatial_Outlier_MoreTime(sTime, DataGatherCode, MonitorValue, PollutantCode, point_diatance, now_stationdata)\n\n# 时间异常调用的函数\ndef time_warning_MoreTime(sTime, DataGatherCode, MonitorValue, PollutantCode, last_stationdata):\n # print('进入时间异常')\n # 时间异常取上一时刻报警\n value_data = get_value(last_stationdata, DataGatherCode, PollutantCode)\n # print(\"我是value_data\", value_data)\n # print('时间异常取上一时刻报警',value_data)\n\n if value_data:\n # print('开始时间异常')\n time_warning(sTime, DataGatherCode, MonitorValue, value_data['MonitorValue'], PollutantCode)\n\n\n# 时间异常调用的函数\ndef get_value(last_stationdata, DataGatherCode, PollutantCode):\n # print('获取mongo的当前值或者上一个值')\n data_item = {}\n for every_station in last_stationdata:\n try:\n if every_station['DataGatherCode'] == DataGatherCode:\n for data in every_station['RealDataList']:\n if data['PollutantCode'] == PollutantCode:\n if float(data['MonitorValue']) != 0:\n data_item['PollutantCode'] = data['PollutantCode']\n data_item['MonitorValue'] = float(data['MonitorValue'])\n break\n except Exception as e:\n print('循环mongo取值', e)\n # print('已整理好mongo值')\n return data_item\n\n\n# 时间异常调用的的函数\ndef time_warning(sTime, DataGatherCode, MonitorValue, last_MonitorValue, PollutantCode):\n '''\n :param sTime: 时间\n :param DataGatherCode: mn号\n :param MonitorValue: 当前时刻值\n :param last_MonitorValue: 上一时刻值\n :param PollutantCode: 监测因子\n :return: 生成时间异常后存库\n '''\n # try:\n # sql = \"select time_anomaly_all from T_Grid_PointInfo where device_id = '%s' \" % (point_id)\n # print('sql系数',sql)\n # time_anomaly = ms.ExecQuery(sql.encode('utf-8'))\n # 存库时间\n\n sTime_utc = sTime - datetime.timedelta(hours=8)\n # print('获取时间异常时间---',)\n # 系数\n if time_anomaly != None and time_anomaly > 0:\n # print(\"我是up_MonitorValue\",last_MonitorValue)\n if last_MonitorValue < 0:\n temp = MonitorValue * (-time_anomaly)\n else:\n temp = MonitorValue * time_anomaly\n # print(temp)\n print(MonitorValue - last_MonitorValue)\n if MonitorValue - last_MonitorValue > temp:\n print('时间异常咯')\n\n # except_info = \"当前值:\" + str(all_data[0]) + \"-----前一个值:\" + str(all_data[1]) + \"-----系数:\" + str(temp)\n except_info = \"当前值:\" + str(MonitorValue) + \" ,前一个值:\" + str(last_MonitorValue) + \" ,超过上一个浓度值:\" + str(\n round(MonitorValue - last_MonitorValue, 1))\n\n print(\"时间异常存库信息\", DataGatherCode, sTime_utc.strftime('%Y-%m-%d %H:%M:%S'), 'TimeAnomaly', '',\n except_info, '', str(MonitorValue), PollutantCode)\n\n insertDB(DataGatherCode, sTime_utc.strftime('%Y-%m-%d %H:%M:%S'), 'TimeAnomaly', '',\n except_info=except_info, except_factor=PollutantCode,\n except_value=str(MonitorValue))\n\n print('时间异常存库结束...')\n\n\n\n# 空间异常调用的函数\ndef Spatial_Outlier_MoreTime(sTime, DataGatherCode, MonitorValue, PollutantCode, point_diatance, now_stationdata):\n # print('进入空间异常')\n\n # 取监测中心点和周边3公里站点的值\n value = Range_data(PollutantCode, DataGatherCode, point_diatance, now_stationdata)\n # print('空间异常;l获取3公里结束。。。')\n # print('周边站点的数据value', value)\n value.append(MonitorValue)\n # 空间异常计算\n Spatial_Outlier(sTime, DataGatherCode, PollutantCode, value, MonitorValue)\n\n\n# 空间异��调用的函数\ndef Range_data(PollutantCode, DataGatherCode, point_diatance, now_stationdata):\n '''\n :param PollutantCode: 因子\n :param DataGatherCode: 站点mn\n :param point_diatance: 站点距离\n :param all_stationdata: mongo数据\n :return: 关联站点得mongo数据\n '''\n # print('空间异常:获取周边3公里....')\n mongo_data = []\n for every_data in now_stationdata:\n for data in every_data['RealDataList']:\n if data['PollutantCode'] == PollutantCode:\n for p_d in point_diatance:\n # print(\"我是p_d[0]\", p_d[0])\n # print(\"我是p_d[1]\", p_d[1])\n if p_d[0] == DataGatherCode and p_d[1] == every_data['DataGatherCode']:\n if float(data['MonitorValue']) != 0:\n up_MonitorValue = float(data['MonitorValue'])\n # print(\"嘿嘿嘿嘿嘿嘿嘿\", up_MonitorValue)\n mongo_data.append(up_MonitorValue)\n return mongo_data\n\n\n# 空间异常调用的函数\ndef Spatial_Outlier(sTime, DataGatherCode, PollutantCode, value, MonitorValue):\n # print('空间异常:计算开始')\n\n sTime_utc = sTime - datetime.timedelta(hours=8)\n all_data = [all_d for all_d in value if all_d != 0]\n\n # print('周边3公里站点的值', all_data)\n # print(\"哼哼哼哼\", all_data, MonitorValue)\n\n if MonitorValue <= 0:\n # print('比较站点此刻缺少数据')\n return False\n\n elif len(all_data) > 2 and MonitorValue > 0:\n # 在python中计算一个多维数组的任意百分比分位数,此处的百分位是从小到大排列\n quantile_25 = np.percentile(all_data, 25)\n # print(\"我是quantile_25\", quantile_25)\n\n quantile_75 = np.percentile(all_data, 75)\n # print(\"我是quantile_75\", quantile_75)\n\n if MonitorValue >= quantile_75 + 1.5 * (quantile_75 - quantile_25):\n print('判断出空间异常')\n\n insertDB(DataGatherCode, sTime_utc.strftime('%Y-%m-%d %H:%M:%S'), 'SpatialAnomaly', 'max',\n '', PollutantCode, '')\n print('空间异常存库结束。。。')\n print('空间异常存库信息', DataGatherCode, PollutantCode, sTime_utc.strftime('%Y-%m-%d %H:%M:%S'),\n 'SpatialAnomaly', 'max',\n '', PollutantCode, '')\n\n\n# 智能报警(时间异常空间异常存库)\ndef insertDB(point_id, datatime, except_type, except_tag, except_info, except_factor, except_value):\n '''\n :param point_id: 站点mn\n :param datatime: 时间\n :param except_type: 异常类型\n :param except_tag: 异常标签(eg:空间 max)\n :param except_info: 异常详情信息\n :param except_factor: 异常因子\n :param except_value:\n :return:\n '''\n sql = \" select count(ID) from T_Grid_PointDataExcept_test where device_id = '%s' and utc_time = '%s' and except_type = '%s' and except_tag = '%s' and pollutant_name = '%s'\" % (\n point_id, datatime, except_type, except_tag, except_factor)\n print(\"我是智能能报警\", sql)\n isRepeat = ms2.ExecQuery(sql)\n print(\"我是isRepeat\", isRepeat)\n\n if isRepeat[0][0] == 0:\n print(\"isRepeat[0][0]\", isRepeat[0][0])\n sql = \"insert into T_Grid_PointDataExcept_test(device_id,utc_time,except_type,except_tag,except_info ,except_diff,pollutant_name,except_value) values('%s','%s','%s','%s','%s','%s','%s','%s') \" % (\n point_id, datatime, except_type, except_tag, except_info, '', except_factor, except_value)\n print(\"我是智能报警存储sql\",sql)\n ms2.ExecNonQuery(sql)\n print('存库结束')\n\n\n","sub_path":"alarm_3_action.py","file_name":"alarm_3_action.py","file_ext":"py","file_size_in_byte":8980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"9409024","text":"\"\"\"Basic drawing elements for gene track figures\n\"\"\"\nimport drawsvg as draw\n\nclass Figure:\n \"\"\"Genetracks Figure\n \"\"\"\n def __init__(self, padding=None, track_height=10):\n self.track_height = track_height\n\n if padding is None:\n self.padding = track_height/2\n else:\n self.padding = padding\n\n self.elements = []\n self.w = 0\n self.h = self.padding\n\n def add(self, element, gap=10, padding=None):\n \"\"\" Add an element to the figure.\n\n :param element: a new Track or other element to add\n :param gap: the distance to leave below the new track\n :param padding: the distance to leave above the new track\n \"\"\"\n if padding is not None:\n self.h += padding - self.padding\n self.elements.append((self.h + element.h, element))\n self.h += element.h + gap\n self.w = max(self.w, element.w)\n self.padding = gap\n\n def show(self, w=None, h=None):\n xscale=1.0\n if h is None:\n h = self.h\n if w is None:\n w = self.w\n else:\n xscale = w / self.w\n\n if h is None:\n h = self.h\n\n d = draw.Drawing(self.w * xscale, h, origin=(0,0), context=draw.Context(invert_y=True))\n for y, element in self.elements:\n d.append(element.draw(xscale=xscale, y=y-h))\n\n# d.setRenderSize(w, h)\n return d\n\n def to_svg(self, path, w=None, h=None):\n self.show(w=w, h=h).save_svg(path, context=draw.Context(invert_y=True))\n\n def to_png(self, path, w=None, h=None):\n self.show(w=w, h=h).save_png(path, context=draw.Context(invert_y=True))\n\n\nclass Element:\n \"\"\"Baseclass for drawable element\n \"\"\"\n def __init__(self, x, y, h=10, w=0):\n self.x = x\n self.y = y\n self.h = h \n self.w = w\n\n def draw(self, x=0, y=0, xscale=1.0):\n pass\n\n\nclass Track(Element):\n \"\"\"Track representing an interval of a genomic sequence\n \"\"\"\n def __init__(self, a, b, h=10, label=None, color='lightgrey', ticks=[],\n regions=[], direction=\"\"):\n self.color = color\n self.a = a\n self.b = b\n self.w = b\n if 'f' in direction:\n self.w += 5\n self.h = h\n self.ticks = ticks\n self.label = label\n self.direction = direction\n self.regions = regions\n\n def add_tick(self, tick):\n self.ticks.append(tick)\n\n def draw(self, x=0, y=0, xscale=1.0):\n h = self.h\n a = self.a * xscale\n b = self.b * xscale\n x = x * xscale\n \n #assert isinstance(x, float) and isinstance(y, float)\n d = draw.Group(transform=\"translate({} {})\".format(x, y))\n d.append(draw.Rectangle(a, 0, b-a, h,\n fill=self.color, stroke=self.color))\n\n if 'f' in self.direction:\n d.append(draw.Lines(b, 0, b + 5, (h/2), b, h,\n fill=self.color, stroke=self.color))\n if 'r' in self.direction:\n d.append(draw.Lines(a, 0, a - 5, (h/2), a, h,\n fill=self.color, stroke=self.color))\n\n for r_a, r_b, color in self.regions:\n r_a = r_a * xscale\n r_b = r_b * xscale\n d.append(draw.Rectangle(r_a, 0, r_b - r_a, h, fill=color, stroke=color))\n\n for tick in self.ticks:\n tick = tick * xscale\n d.append(draw.Lines(tick, 0, tick, h, stroke='red'))\n\n if self.label:\n label = self.label\n font_size = 10\n offset = h + font_size\n if isinstance(self.label, Label):\n d.append(label.draw(x=(b+a)/2))\n elif isinstance(self.label, str):\n d.append(Label(0, self.label).draw(x=(b+a)/2))\n return d\n\n\nclass Coverage(Element):\n \"\"\"Coverage graph\n \"\"\"\n def __init__(self, a, b, ys, height = 10, color='blue', opacity='1.0'):\n self.color = color\n self.opacity = opacity\n self.a = a\n self.b = b\n self.h = height\n self.ys = ys\n self.w = b\n\n def draw(self, x=0, y=0, xscale=1.0):\n #assert isinstance(x, int) and isinstance(y, int)\n h = self.h\n a = self.a * xscale\n b = self.b * xscale\n x = x * xscale\n d = draw.Group(transform=\"translate({} {})\".format(x, y))\n yscale = self.h / max(self.ys)\n for i, v in enumerate(self.ys):\n d.append(draw.Rectangle(a+(i*xscale), 0, xscale, v*yscale,\n fill=self.color, fill_opacity=self.opacity))#, stroke=self.color))\n return d\n\n\nclass Label(Element):\n \"\"\"Wrap a text label\n \"\"\"\n def __init__(self, x, text, font_size=10, offset=0):\n self.font_size = font_size\n self.offset = offset\n self.text = str(text)\n self.h = font_size\n self.w = x # it would be cool to know how wide the text is\n\n def draw(self, x=None, y=0, xscale=1.0):\n# font_family = self.label.font_family\n if self.offset is not None:\n offset = self.offset\n\n if x is None:\n x = self.w * xscale\n\n d = draw.Group(transform=\"translate({} {})\".format(x, y))\n d.append(draw.Text(self.text, self.font_size, self.w,\n offset, font_family='monospace', text_anchor='middle'))\n return d\n\n\n\nclass Alignment(Element):\n \"\"\"Link two tracks to illustrate similar regions\n \"\"\"\n def __init__(self, track1, track2, connections, text=None, style=None,\n gap=30, color=\"black\"):\n self.t1 = track1\n self.t2 = track2\n self.color = color\n self.connections = connections\n self.gap = gap\n self.h = track1.h + track2.h + gap\n self.b = max(track1.b, track2.b)\n self.a = min(track1.a, track2.a)\n self.w = max(track1.w, track2.w)\n\n def draw(self, x=0, y=0, xscale=1.0):\n d = draw.Group(transform=\"translate({} {})\".format(x, y-self.gap))\n d.append(self.t1.draw(xscale=xscale))\n d.append(self.t2.draw(y=self.t1.h+self.gap, xscale=xscale))\n\n for bottom, top in self.connections:\n bottom = bottom * xscale\n top = top * xscale\n d.append(draw.Lines(bottom, 0, top, -self.gap, stroke=self.color))\n d.append(draw.Lines(bottom, self.t1.h, bottom, 0, stroke=self.color))\n d.append(draw.Lines(top, -self.gap, top,\n -(self.gap+self.t2.h),\n stroke=self.color))\n return d\n\n\nclass Multitrack(Element):\n \"\"\"Pack multiple tracks onto a line\n \"\"\"\n def __init__(self, tracks, join=False):\n self.tracks = tracks\n self.join = join\n self.h = max(map(lambda x: x.h, tracks))\n self.w = max(map(lambda x: x.b, tracks))\n self.b = max(map(lambda x: x.b, tracks))\n\n def draw(self, x=0, y=0, xscale=1.0):\n h = self.h\n #assert isinstance(x, int) and isinstance(y, int)\n g = draw.Group(transform=\"translate({} {})\".format(x, y))\n if self.join:\n start = min([t.a for t in self.tracks]) * xscale\n end = max([t.b for t in self.tracks]) * xscale\n g.append(draw.Lines(start, h / 2, end, h / 2, stroke='lightgrey'))\n for track in self.tracks:\n g.append(track.draw(xscale=xscale))\n\n return g\n\n\nclass Tick:\n \"\"\"Wrapper for tick\n \"\"\"\n def __init__(self, x, color='red'):\n self.x = x\n","sub_path":"genetracks/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":7506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"413219465","text":"#!/usr/bin/env python\nimport os\nimport re\n\nimport sys\n\nfn = sys.argv[1]\nfiles_path = os.path.relpath(fn)\nextension = 'php'\n\nSTATEMENT_CLASS = 'class'\nSTATEMENT_COMMENT_START = '/*'\nSTATEMENT_COMMENT_END = '*/'\nSTATEMENT_VAR = '@var'\nSTATEMENT_PRIVATE = 'private'\nSTATEMENT_PROTECTED = 'protected'\nSTATEMENT_PUBLIC = 'public'\nSTATEMENT_PROPERTY_START = '$'\n\nSTATEMENT_JMS_GROUP = '@JMS\\Groups'\nSTATEMENT_JMS_EXCLUDE = '@JMS\\Exclude'\nSTATEMENT_JMS_GROUP_REGEX = r\"\\s+(|\\*)\\s{0,}@JMS\\\\Groups\\(\\{([\\w:]+)+?([\\s\\,]+([\\w:]+)|)\"\nSTATEMENT_GROUP_MINIMAL = 'EntityGroup::MINIMAL'\nSTATEMENT_GROUP_EXTENDED = 'EntityGroup::EXTENDED'\n\ndef convert(name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n\ndef find_files(path, extension):\n if path.endswith(\".%s\" % extension):\n pathExtract = path.split('\\\\')\n analyze_file(os.path.join('\\\\\\\\'.join(pathExtract[:len(pathExtract) - 1]), pathExtract[-1]))\n return\n\n for dir in os.listdir(path):\n if os.path.isdir(os.path.join(path, dir)) and dir not in ('RepositoryParamsConfiguration', 'RepositoryProvider'):\n for file in os.listdir(os.path.join(path, dir)):\n if file.endswith(\".%s\" % extension):\n # print os.path.join(path, dir, file)\n analyze_file(os.path.join(path, dir, file))\n\n\ndef analyze_file(filepath):\n class_start = False\n class_collection = False\n\n comment_start = False\n comment_line_number = None\n comment_lines = None\n\n groups = []\n\n field_exclude = False\n field_groups = None\n fields_minimal = []\n fields_extended = []\n\n print(\"filepath=%s\" % filepath)\n\n with open(filepath, 'r') as file:\n lines = file.readlines()\n file_lines = lines[:]\n\n for index, line in enumerate(file_lines):\n if class_start is False and line.find(STATEMENT_CLASS) > -1:\n\n if line.find('implements') == -1:\n lines[index] = lines[index].strip(\"\\n\") + ' implements \\JsonSerializable'\n else:\n lines[index] = lines[index].strip(\"\\n\").replace('implements', 'implements \\JsonSerializable, ')\n\n if line.find('extends') == -1:\n lines[index] = lines[index].replace('implements',\n ' extends \\Domain\\EntityGroup implements')\n lines[index] += \"\\n\"\n\n class_start = True\n\n if line.find('Collection') > -1:\n class_collection = True\n\n print(line)\n\n if class_start is True:\n if line.find(STATEMENT_COMMENT_START) > -1:\n comment_start = True\n comment_line_number = index\n field_exclude = False\n field_name = None\n\n if line.find(STATEMENT_COMMENT_END) > -1:\n comment_start = False\n\n if comment_start is True:\n if comment_lines is None:\n comment_lines = []\n comment_lines.append(line)\n\n if line.find(STATEMENT_JMS_EXCLUDE) > -1:\n field_exclude = True\n\n if line.find(STATEMENT_JMS_GROUP) > -1:\n matches = re.search(STATEMENT_JMS_GROUP_REGEX, line)\n\n field_groups = (matches.group(2), matches.group(4))\n\n if comment_start is False:\n if line.find(STATEMENT_PROPERTY_START) > -1 and field_exclude is False:\n regex = r\"\\s+(public|protected|private)\\s+\\$([\\w\\d]+)(.*)\\;\"\n matches = re.search(regex, line)\n\n\n if field_groups is None:\n continue\n if matches is not None:\n if STATEMENT_GROUP_MINIMAL in field_groups:\n fields_minimal.append(matches.group(2))\n\n if STATEMENT_GROUP_EXTENDED in field_groups:\n fields_extended.append(matches.group(2))\n\n if line.startswith(\"}\"):\n template = []\n template.append(\"\\n\")\n template.append(\" function jsonSerialize()\\n\")\n template.append(\" {\\n\")\n\n if class_collection is False:\n template.append(\" if ($this->entityGroup === \\Domain\\EntityGroup::EXTENDED) {\\n\")\n template.append(\" return [\\n\")\n\n if class_collection is False:\n for idx, field in enumerate(fields_extended):\n template.append(\" '{field_name}' => $this->{field},\\n\".format(field=field, field_name=convert(field)))\n\n template.append(\" ];\\n\")\n template.append(\" }\\n\")\n template.append(\"\\n\")\n\n template.append(\" return [\\n\")\n if class_collection is False:\n for idx, field in enumerate(fields_minimal):\n template.append(\" '{field_name}' => $this->{field},\\n\".format(field=field, field_name=convert(field)))\n else:\n template.append(\" 'items' => $this->items,\\n\")\n template.append(\" 'quantity' => $this->quantity\\n\")\n\n template.append(\" ];\\n\")\n template.append(\" }\\n\")\n\n for idx, tpl_line in enumerate(template[::-1]):\n lines.insert(index, tpl_line)\n file.close()\n\n if len(fields_minimal) > 0:\n with open(filepath, 'w') as file:\n file.writelines(\"\".join(lines))\n file.close()\n\n\ndef main():\n # php = PhpClass(\"asd\")\n # php.properties = (PhpClass.Property(\"private\", \"asd\", \"bang\"),)\n #\n # print(files_path)\n # print(vars(php))\n\n find_files(files_path, extension)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"538830014","text":"\n\nfrom xai.brain.wordbase.nouns._tablespoon import _TABLESPOON\n\n#calss header\nclass _TABLESPOONS(_TABLESPOON, ):\n\tdef __init__(self,): \n\t\t_TABLESPOON.__init__(self)\n\t\tself.name = \"TABLESPOONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tablespoon\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tablespoons.py","file_name":"_tablespoons.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"166623404","text":"#!/usr/bin/env python\n\"\"\"mapper.py\"\"\"\n\nimport sys\nimport re\nimport zipimport\nimporter = zipimport.zipimporter('mwparserfromhell.mod')\nparser = importer.load_module('mwparserfromhell')\n\n\ndef getTemplate(text):\n #text = text.lower()\n REGEX_INFOBOX_TEMPLATE = \"(i|I)nfobox(\\s(\\w.)*)?(\\s(\\w)*){1,2}\";\n templateMapping = re.compile(REGEX_INFOBOX_TEMPLATE)\n found = templateMapping.search(text)\n if found:\n return found.group()\n return None\n\n\ndef getInfobox(text):\n REGEX_INFOBOX_MAPPING = \"\\{\\{\\s?(i|I)nfobox.*\\n(|.*\\n)*\\}\\}\";\n infoboxMapping = re.compile(REGEX_INFOBOX_MAPPING)\n\n mapping = infoboxMapping.search(text)\n if mapping:\n\n infobox = mapping.group()\n\n parsedMapping = parser.parse(infobox)\n template = parsedMapping.filter_templates()\n\n if template is not None and len(template) > 0:\n return template[0].params\n else:\n return None\n else:\n return None\n\n\ndef mapper(inf_template):\n article = []\n list = []\n title = \"Unknown\"\n inText = False\n\n for line in sys.stdin:\n line = line.strip()\n\n if line.find(\"\") != -1:\n title = line[len(\"<title>\"): -len(\"\")]\n\n if line.find('') != -1 and \"#REDIRECT\" not in line:\n inText = True\n continue\n\n if line.find(\"\") != -1:\n inText = False\n list.append('\\n'.join(article))\n article = []\n continue\n\n if inText:\n article.append(line)\n\n for article in list:\n\n if len(article) >= 4001:\n article = article[0:4000]\n\n template = getTemplate(article)\n\n if template is not None and (template.rstrip()).lower() == inf_template.lower():\n\n params = getInfobox(article)\n\n if params is not None:\n for param in params:\n if len(param.name.rstrip().strip()) > 0 and len(param.value.rstrip().strip()) > 0:\n try:\n print(\"%s\\t%s\" % (param.name.rstrip().strip(), 1))\n except UnicodeEncodeError:\n continue\n\n print(\"%s\\t%s\" % (\"none\", 1))\n\n\nif len(sys.argv) > 1:\n mapper(sys.argv[1])","sub_path":"hadoop/Mapper2TopProperties.py","file_name":"Mapper2TopProperties.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"405561109","text":"import math\r\n\r\ndef upper(num):\r\n is_prime = [False] * 2 + [True] * (num - 1)\r\n for n in range(int(math.sqrt(num) + 1.5)):\r\n #this stops at root of 2 million\r\n if is_prime[n]:\r\n for i in range(n*n, num+1, n):\r\n is_prime[i] = False\r\n return [i for i, prime in enumerate(is_prime) if prime]\r\n\r\ndef main():\r\n sum_1=0\r\n x=[]\r\n i=2000000\r\n x=upper(i)\r\n finalsum=sum(x)\r\n print (finalsum)\r\n \r\nif __name__ == '__main__':\r\n main()\r\n \r\n","sub_path":"problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"537209857","text":"\r\nimport pulp as plp\r\nimport pandas as pd\r\n\r\n### exercise 5.4\r\n#---------------\r\n\r\n# a)\r\n\r\n# initialize LP-model class\r\nmodel = plp.LpProblem(\"Maximization\", plp.LpMaximize)\r\n\r\n# decision variables\r\nx1 = plp.LpVariable(\"x1\", lowBound=0)\r\nx2 = plp.LpVariable(\"x2\", lowBound=0)\r\n\r\n# objective function\r\nmodel += x1 + 3*x2\r\n\r\n# constraints\r\nmodel += x1 + x2 <= 8, \"resource 1\"\r\nmodel += -x1 + x2 <= 4, \"resource 2\"\r\nmodel += x1 <= 6, \"resource 3\"\r\n\r\n# solve model and display solution\r\nmodel.solve()\r\n\r\nprint(\"x1: \" + str(x1.varValue))\r\nprint(\"x2: \" + str(x2.varValue))\r\n\r\nprint(\"objective function: \" + str(plp.value(model.objective)))\r\n\r\n# b)\r\n\r\n# print the shadow prices\r\n\r\no = [{'name':name, 'shadow price':c.pi}\r\n for name, c in model.constraints.items()]\r\nprint(pd.DataFrame(o))\r\n\r\n# c)\r\n\r\n# generate sensitivity report from the GLPK-engine\r\nmodel.solve(plp.GLPK(options=['--ranges sensitivity.sen']))\r\n\r\n\r\n# Q: how much can c1 and c2 change for the optimal solution to remain the same?\r\n# A: x1 => [-3,3], x2 => [1,infinity)\r\n\r\n# d)\r\n\r\n# Q: how much can the RHS constraint coefficients change without affecting the shadow prices\r\n# A: c1 => [4,16], c2 => [-4,8], c3 => [2,infinity)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"PuLP/LRV - Chapter 5.py","file_name":"LRV - Chapter 5.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"435062740","text":"# collect the latest price of each shoes\n\nimport urllib.request\nimport bs4\nimport ssl\nimport pandas as pd\n\n\n# read html based on url\ndef get_html(url):\n ssl._create_default_https_context = ssl._create_unverified_context\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'}\n url = 'https://stockx.com/sneakers'\n req = urllib.request.Request(url=url, headers=headers)\n response = urllib.request.urlopen(req)\n text = response.read().decode()\n html = bs4.BeautifulSoup(text, 'html.parser')\n return html\n\n\n# 还没有想好怎么写完能够自动读取到页数\ndef get_page_num():\n html = get_html('https://stockx.com/sneakers')\n page_container = html.find(\"div\", attrs={\"class\", \"css-zfbjl9-PaginationContainer\"})\n pages = html.find_all(\"ul\", attrs={\"class\", \"css-tcf6ot-ButtonList\"})\n\n\n# format the list of url based on the number of page\nurls = ['https://stockx.com/sneakers?page={}'.format(i)\n for i in range(1, 26)]\n# for each page read the name of the shoes\nfor url in urls:\n ssl._create_default_https_context = ssl._create_unverified_context\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'}\n req = urllib.request.Request(url=url, headers=headers)\n response = urllib.request.urlopen(req)\n text = response.read().decode()\n html = bs4.BeautifulSoup(text, 'html.parser')\n shoes = html.find_all(\"div\", attrs={\"class\", \"tile browse-tile\"})\n for shoe in shoes:\n name = shoe.find('a').get('href')\n print(name)\n\n","sub_path":"Alldata.py","file_name":"Alldata.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"317358028","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n d = {}\n window_start, maxLen = 0, 0\n for window_end in range(len(s)):\n right_char = s[window_end]\n if right_char in d:\n window_start = max(window_start, d[right_char] + 1)\n d[right_char] = window_end\n maxLen = max(maxLen, window_end - window_start + 1)\n\n return maxLen\n\n\n'''why need maxmize window_start\nabba\n1. d = {a : 0}, start = 0\n2. d = {a: 0, b : 1}, start = 0\n3. d = {a: 0, b : 2}, start = max(0, d[b] + 1) = max(0, 2) = 2\n4. d = {a: 3, b : 2}\nwithout max: start = d[a] + 1 = 1\nwith max: start = max(2, d[a] + 1) = 2\nchoose the right a not the previous a\n'''\n","sub_path":"Python/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"413072325","text":"import unittest\n\nfrom uTesting_server import FlaskTestCase\n\n'''\n This file executes ALL of the test files. \n The test files can still be executed individually,\n if you only wish to execute a single set of tests. \n'''\n\nif __name__ == '__main__':\n # Run specified tests\n test_classes_to_run = [\n FlaskTestCase\n ]\n\n suites_list = []\n for test_class in test_classes_to_run:\n suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\n suites_list.append(suite)\n\n results = unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(suites_list))\n\n print(\"Test success:\", results.wasSuccessful()) # Overall success.\n results.printErrors()\n","sub_path":"uTesting_All.py","file_name":"uTesting_All.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"40336183","text":"import time\n\nfrom getgauge.python import step, data_store\nfrom api.mms.deliver.mallstate import Mallstate\nfrom api.mms.deliver.goods_material import GoodsMaterial\nfrom api.mms.deliver.deliver import Deliver\nimport time\n\n@step(\"校验当前店铺是否参加物流提升计划\")\ndef mallstate():\n mallstate = Mallstate()\n resp = mallstate.request()\n assert resp['code'] == 0\n data_store.suite['mallstate'] = resp['payload']['is_sign_up']\n\n\n@step(\"设置商品包装材质,goods_id=\")\ndef goodsmaterial(goods_id):\n if data_store.suite['mallstate']:\n goodsmaterial = GoodsMaterial()\n\n goods_id = data_store.suite['goods_id'] if not goods_id else goods_id\n goodsmaterial.data['goods_ids'] = [goods_id]\n\n resp = goodsmaterial.request()\n\n assert resp['code'] == 0\n\n\n@step(\"订单发货,order_id=\")\ndef deliver(order_id):\n deliver = Deliver()\n time.sleep(10)\n order_id = data_store.suite['order_id'] if not order_id else order_id\n deliver.data['order_id'] = order_id\n data_store.suite['order_id']=order_id\n resp = deliver.request()\n assert resp['code'] == 0\n data_store.suite['deliver'] = True\n\n","sub_path":"banshee-master/step_impl/mms/deliver.py","file_name":"deliver.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"125716127","text":"import arcade\n\nSCREEN_WIDTH = 1280\nSCREEN_HEIGHT = 720\n\nclass YouWin(arcade.View):\n def __init__(self,coins):\n self.window = None\n\n self.coins = coins\n\n self.hover_color = [0, 0, 0, 100]\n self.click_color = [0, 0, 0, 150]\n\n self.hovering = None\n self.clicking = None\n\n self.draw_restart_button_hover = None\n\n self.restart_bottom = None\n self.restart_left = None\n\n self.game_over_text = None\n self.game_over_text2 = None\n self.restart_button = None\n\n self.old_screen_center_x = None\n self.old_screen_center_y = None\n self.screen_center_x = None\n self.screen_center_y = None\n\n def on_show(self):\n\n self.window = arcade.get_window()\n\n self.draw_restart_button_hover = False\n\n self.hovering = False\n self.clicking = False\n\n self.old_screen_center_x = int(self.window.get_size()[0] / 2)\n self.old_screen_center_y = int(self.window.get_size()[1] / 2)\n self.screen_center_x = int(self.window.get_size()[0] / 2)\n self.screen_center_y = int(self.window.get_size()[1] / 2)\n\n win_text = 'You Won! You Got More Coins Then On The Bar-Round!'\n self.game_over_text = arcade.draw_text(win_text, self.screen_center_x, self.screen_center_y + 150,\n anchor_x='center',\n anchor_y='center', color=arcade.csscolor.WHITE, font_size=32, font_name='fonts/RobotoMono-Regular.ttf')\n win_text = f'You had a stunning {self.coins} coins! Can you beat it?'\n self.game_over_text2 = arcade.draw_text(win_text, self.screen_center_x, self.screen_center_y + 100,\n anchor_x='center',\n anchor_y='center', color=arcade.csscolor.WHITE, font_size=32,\n font_name='fonts/RobotoMono-Regular.ttf')\n\n play_again_text = 'Play Again'\n self.restart_button = arcade.draw_text(play_again_text, self.screen_center_x, self.screen_center_y,\n anchor_x='center', anchor_y='center',\n color=arcade.csscolor.WHITE, font_size=64, font_name='fonts/RobotoMono-Regular.ttf')\n\n arcade.set_background_color([66, 245, 212, 255])\n\n arcade.set_viewport(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT)\n\n def on_mouse_motion(self, x, y, dx, dy):\n if self.play_left + self.restart_button.width + 50 >= x >= self.play_left - 50 and self.play_bottom + self.restart_button.height + 25 >= y >= self.play_bottom - 25:\n self.draw_restart_button_hover = True\n self.hovering = True\n else:\n self.draw_restart_button_hover = False\n self.hovering = False\n\n def on_mouse_press(self, x, y, button, modifiers):\n if self.play_left + self.restart_button.width + 50 >= x >= self.play_left - 50 and self.play_bottom + self.restart_button.height + 25 >= y >= self.play_bottom - 25:\n self.draw_restart_button_hover = True\n self.clicking = True\n else:\n self.draw_restart_button_hover = False\n self.clicking = False\n\n def on_mouse_release(self, x, y, button, modifiers):\n if self.play_left + self.restart_button.width + 50 >= x >= self.play_left - 50 and self.play_bottom + self.restart_button.height + 25 >= y >= self.play_bottom - 25:\n from open_window_views import MyGame\n game = MyGame(1, 0, 0)\n self.window.show_view(game)\n\n def on_draw(self):\n arcade.start_render()\n\n arcade.set_viewport(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT)\n\n screen_width, screen_height = self.window.get_size()\n self.screen_center_x = int(screen_width / 2)\n self.screen_center_y = int(screen_height / 2)\n\n if self.old_screen_center_x != self.screen_center_x or self.old_screen_center_y != self.screen_center_y:\n game_over_text = 'You Won! You Got More Coins Then On The Bar-Round!'\n self.game_over_text = arcade.draw_text(game_over_text, self.screen_center_x, self.screen_center_y + 150,\n anchor_x='center',\n anchor_y='center', color=arcade.csscolor.WHITE, font_size=32,\n font_name='fonts/RobotoMono-Regular.ttf')\n win_text = 'You got a stunning ' + str(self.coins) + '! Can you beat it?'\n self.game_over_text2 = arcade.draw_text(win_text, self.screen_center_x, self.screen_center_y + 100,\n anchor_x='center',\n anchor_y='center', color=arcade.csscolor.WHITE, font_size=32,\n font_name='fonts/RobotoMono-Regular.ttf')\n\n restart_text = 'Restart'\n self.restart_button = arcade.draw_text(restart_text, self.screen_center_x,\n self.screen_center_y,\n anchor_x='center', anchor_y='center',\n color=arcade.csscolor.WHITE, font_size=64,\n font_name='fonts/RobotoMono-Regular.ttf')\n\n self.old_screen_center_x = self.screen_center_x\n self.old_screen_center_y = self.screen_center_y\n\n if self.draw_restart_button_hover:\n if self.clicking:\n arcade.draw_rectangle_filled(self.screen_center_x, self.screen_center_y, self.restart_button.width + 100, self.restart_button.height + 50, self.click_color)\n elif self.hovering:\n arcade.draw_rectangle_filled(self.screen_center_x, self.screen_center_y, self.restart_button.width + 100, self.restart_button.height + 50, self.hover_color)\n\n self.play_bottom = self.restart_button.bottom\n self.play_left = self.restart_button.left\n\n self.game_over_text.draw()\n self.game_over_text2.draw()\n self.restart_button.draw()\n\ndef main(gm=False):\n if not gm:\n window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, 'Help', resizable=True)\n window.show_view(GameOver(1, 0, 0))\n arcade.run()\n\nif __name__ == \"__main__\":\n main()","sub_path":"Finalists/the-friendly-snakes/YouWin.py","file_name":"YouWin.py","file_ext":"py","file_size_in_byte":6541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"455403102","text":"\"\"\"\nTask: write a program which can simulate cake with surprise.\nWhen you run program it should print 1 of 5 surprise which choose random.\n\"\"\"\n\n__author__ = \"Egor Antonovich\"\n__version__ = \"1.0.0\"\n__mainteiner__ = \"Egor Antonovich\"\n__email__ = \"antonovich.egor1@gmail.com\"\n\nimport random\n\nsurprise = random.randrange(2000, 10001, 2000)\nprint(\"\\n\\tYour winnings is:\", surprise, \"$\")\ninput(\"\\n\\nPress Enter for a exit.\")\n","sub_path":"Chapter3/surprise_cake.py","file_name":"surprise_cake.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"333554013","text":"import re\nimport os\n\nfrom flask import render_template, send_from_directory, request, flash, redirect, url_for\nfrom flask.globals import current_app\nfrom flask_login import login_required\n\nfrom yublog.extensions import db\nfrom yublog.forms import AddImagePathForm\nfrom yublog.models import Image, ImagePath\nfrom yublog.views import image_bp\nfrom yublog.views.utils.image_utils import IMAGE_MIMES, asyncio_saver, image_remove, image_rename, mkdir\n\n\n@image_bp.route('/')\n@image_bp.route('/index', methods=['GET', 'POST'])\n@login_required\ndef index():\n _paths = ImagePath.query.all()\n paths = [p.path for p in _paths]\n\n form = AddImagePathForm()\n if form.validate_on_submit():\n new_path = form.path_name.data\n # print(f'new_path: {new_path}')\n if new_path and new_path not in paths:\n _path = ImagePath(path=new_path)\n db.session.add(_path)\n db.session.commit()\n mkdir(os.path.join(current_app.config['IMAGE_UPLOAD_PATH'], new_path))\n flash('Add image path successful.')\n else:\n flash('Add image path fail.')\n return redirect(url_for('image.index'))\n\n return render_template('image/index.html', paths=paths, form=form, title='图片')\n\n\n@image_bp.route('//', methods=['GET', 'POST'])\n@login_required\ndef get_path_images(path):\n images = Image.query.filter_by(path=path).order_by(Image.id).all()\n filenames = {i.filename for i in images}\n if request.method == 'POST':\n img_name = request.form.get('key', None)\n file = request.files['file']\n filename = file.filename if not img_name else re.sub(r'[\\/\\\\\\:\\*\\?\"<>|]', r'_', img_name)\n img_stream = file.stream.read()\n # print(f'file.mimetype : {file.mimetype }')\n if filename not in filenames and file.mimetype in IMAGE_MIMES:\n asyncio_saver(\n os.path.join(current_app.config['IMAGE_UPLOAD_PATH'], path),\n filename, img_stream)\n \n _path = ImagePath.query.filter_by(path=path).first()\n up_img = Image(path=path, filename=filename, image_path=_path)\n db.session.add(up_img)\n db.session.commit()\n flash('Upload image {0} successful'.format(filename))\n else:\n flash('Upload image fail')\n return redirect(url_for('image.get_path_images', path=path))\n\n images = Image.query.filter_by(path=path).order_by(Image.id).all()\n # print(f'images: {images}')\n return render_template('image/path.html', path=path, images=images, title='图片路径')\n\n\n@image_bp.route('//')\ndef get_image(path, filename):\n return send_from_directory('static', 'upload/image/{path}/{filename}'.format(path=path, filename=filename))\n\n\n@image_bp.route('/delete', methods=['GET', 'POST'])\n@login_required\ndef delete_img():\n _id = request.get_json()['id']\n _image = Image.query.get_or_404(_id)\n cur_img_path = _image.path\n filename = _image.filename\n\n db.session.delete(_image)\n db.session.commit()\n\n image_remove(os.path.join(current_app.config['IMAGE_UPLOAD_PATH'], cur_img_path), filename)\n flash('Delete image {0} successful'.format(_id))\n return redirect(url_for('image.get_path_images', path=cur_img_path))\n\n\n@image_bp.route('/rename', methods=['GET', 'POST'])\n@login_required\ndef rename_img():\n _id = request.get_json()['id']\n new_name = request.get_json()['newName']\n new_name = re.sub(r'[\\/\\\\\\:\\*\\?\"<>|]', r'_', new_name)\n _image = Image.query.get_or_404(_id)\n cur_img_path = _image.path\n # 判断图片名称是否存在\n images = Image.query.filter_by(path=cur_img_path).all()\n filenames = {i.filename for i in images}\n if new_name in filenames:\n return redirect(url_for('image.get_path_images', path=cur_img_path))\n\n old_name = _image.filename\n _image.filename = new_name\n db.session.add(_image)\n db.session.commit()\n\n image_rename(os.path.join(current_app.config['IMAGE_UPLOAD_PATH'], cur_img_path), old_name, new_name)\n flash('Rename image {0} successful'.format(new_name))\n return redirect(url_for('image.get_path_images', path=cur_img_path))\n","sub_path":"yublog/views/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"168782350","text":"# Copyright 2014 Scalyr Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------\n#\n# author: Steven Czerwinski \nimport threading\n\n__author__ = 'czerwin@scalyr.com'\n\n\nimport os\nimport tempfile\n\nimport logging\nimport sys\nimport unittest2 as unittest\n\nroot = logging.getLogger()\nroot.setLevel(logging.DEBUG)\n\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nroot.addHandler(ch)\n\nfrom scalyr_agent.configuration import Configuration\nfrom scalyr_agent.copying_manager import CopyingParameters, CopyingManager\nfrom scalyr_agent.platform_controller import DefaultPaths\nfrom scalyr_agent.scalyr_client import AddEventsRequest\nfrom scalyr_agent.test_base import ScalyrTestCase\nfrom scalyr_agent.test_util import ScalyrTestUtils\nfrom scalyr_agent.json_lib import JsonObject, JsonArray\nfrom scalyr_agent import json_lib\n\nONE_MB = 1024 * 1024\n\n\nclass CopyingParamsTest(ScalyrTestCase):\n def setUp(self):\n self.__config_dir = tempfile.mkdtemp()\n self.__config_file = os.path.join(self.__config_dir, 'agentConfig.json')\n self.__config_fragments_dir = os.path.join(self.__config_dir, 'configs.d')\n os.makedirs(self.__config_fragments_dir)\n\n fp = open(self.__config_file, 'w')\n fp.write('{api_key: \"fake\"}')\n fp.close()\n\n config = self.__create_test_configuration_instance()\n config.parse()\n self.test_params = CopyingParameters(config)\n\n def test_initial_settings(self):\n self.assertEquals(self.test_params.current_bytes_allowed_to_send, ONE_MB)\n self.assertEquals(self.test_params.current_sleep_interval, 5.0)\n\n def test_no_events_being_sent(self):\n for i in range(0, 5):\n self.test_params.update_params('success', 0)\n self.assertEquals(self.test_params.current_bytes_allowed_to_send, ONE_MB)\n self.assertEquals(self.test_params.current_sleep_interval, 5.0)\n\n def test_small_events_being_sent(self):\n self.test_params.current_sleep_interval = 1\n self._run('success', 10 * 1024, [1.5, ONE_MB], [2.25, ONE_MB], [3.375, ONE_MB], [5, ONE_MB])\n\n def test_too_many_events_being_sent(self):\n self.test_params.current_sleep_interval = 5\n\n self._run('success', 200 * 1024, [3.0, ONE_MB], [1.8, ONE_MB], [1.08, ONE_MB], [1, ONE_MB])\n\n def test_request_too_big(self):\n self.test_params.current_sleep_interval = 1\n\n self.test_params.update_params('requestTooLarge', 300 * 1024)\n self.assertAlmostEquals(self.test_params.current_bytes_allowed_to_send, 150 * 1024)\n\n self.test_params.update_params('requestTooLarge', 150 * 1024)\n self.assertAlmostEquals(self.test_params.current_bytes_allowed_to_send, 100 * 1024)\n\n def test_error_back_off(self):\n self.test_params.current_sleep_interval = 3\n self._run('error', 200 * 1024, [4.5, ONE_MB], [6.75, ONE_MB], [10.125, ONE_MB], [15.1875, ONE_MB],\n [22.78125, ONE_MB], [30, ONE_MB])\n\n def _run(self, status, bytes_sent, *expected_sleep_interval_allowed_bytes):\n \"\"\"Verifies that when test_params is updated with the specified status and bytes sent the current sleep\n interval and allowed bytes is updated to the given values.\n\n This will call test_params.update_params N times where N is the number of additional arguments supplied.\n After the ith invocation of test_params.update_params, the values for the current_sleep_interval and\n current_bytes_allowed_to_send will be checked against the ith additional parameter.\n\n @param status: The status to use when invoking test_params.update_params.\n @param bytes_sent: The number of bytes sent to use when invoking test_params.update_params.\n @param expected_sleep_interval_allowed_bytes: A variable number of two element arrays where the first element\n is the expected value for current_sleep_interval and the second is the expected value of\n current_bytes_allowed_to_send. Each subsequent array represents what those values should be after invoking\n test_params.update_param again.\n \"\"\"\n for expected_result in expected_sleep_interval_allowed_bytes:\n self.test_params.update_params(status, bytes_sent)\n self.assertAlmostEquals(self.test_params.current_sleep_interval, expected_result[0])\n self.assertAlmostEquals(self.test_params.current_bytes_allowed_to_send, expected_result[1])\n\n class LogObject(object):\n def __init__(self, config):\n self.config = config\n self.log_path = config['path']\n\n class MonitorObject(object):\n def __init__(self, config):\n self.module_name = config['module']\n self.config = config\n self.log_config = {'path': self.module_name.split('.')[-1] + '.log'}\n\n def __create_test_configuration_instance(self):\n\n default_paths = DefaultPaths('/var/log/scalyr-agent-2', '/etc/scalyr-agent-2/agent.json',\n '/var/lib/scalyr-agent-2')\n return Configuration(self.__config_file, default_paths, None)\n\n\nclass CopyingManagerInitializationTest(ScalyrTestCase):\n\n def test_from_config_file(self):\n test_manager = self.__create_test_instance([\n {\n 'path': '/tmp/hi.log'\n }\n ], [])\n self.assertEquals(len(test_manager.log_matchers), 2)\n self.assertEquals(test_manager.log_matchers[0].config['path'], '/tmp/hi.log')\n self.assertEquals(test_manager.log_matchers[1].config['path'], '/var/log/scalyr-agent-2/agent.log')\n\n def test_from_monitors(self):\n test_manager = self.__create_test_instance([\n ], [\n {\n 'path': '/tmp/hi_monitor.log',\n }\n ])\n self.assertEquals(len(test_manager.log_matchers), 2)\n self.assertEquals(test_manager.log_matchers[0].config['path'], '/var/log/scalyr-agent-2/agent.log')\n self.assertEquals(test_manager.log_matchers[1].config['path'], '/tmp/hi_monitor.log')\n self.assertEquals(test_manager.log_matchers[1].config['attributes']['parser'], 'agent-metrics')\n\n def test_multiple_monitors_for_same_file(self):\n test_manager = self.__create_test_instance([\n ], [\n {'path': '/tmp/hi_monitor.log'},\n {'path': '/tmp/hi_monitor.log'},\n {'path': '/tmp/hi_second_monitor.log'}\n ])\n self.assertEquals(len(test_manager.log_matchers), 3)\n self.assertEquals(test_manager.log_matchers[0].config['path'], '/var/log/scalyr-agent-2/agent.log')\n self.assertEquals(test_manager.log_matchers[1].config['path'], '/tmp/hi_monitor.log')\n self.assertEquals(test_manager.log_matchers[1].config['attributes']['parser'], 'agent-metrics')\n self.assertEquals(test_manager.log_matchers[2].config['path'], '/tmp/hi_second_monitor.log')\n self.assertEquals(test_manager.log_matchers[2].config['attributes']['parser'], 'agent-metrics')\n\n def test_monitor_log_config_updated(self):\n test_manager = self.__create_test_instance([\n ], [\n {'path': 'hi_monitor.log'},\n ])\n self.assertEquals(len(test_manager.log_matchers), 2)\n self.assertEquals(test_manager.log_matchers[0].config['path'], '/var/log/scalyr-agent-2/agent.log')\n self.assertEquals(test_manager.log_matchers[1].config['path'], '/var/log/scalyr-agent-2/hi_monitor.log')\n\n # We also verify the monitor instance itself's log config object was updated to have the full path.\n self.assertEquals(self.__monitor_fake_instances[0].log_config['path'], '/var/log/scalyr-agent-2/hi_monitor.log')\n\n def __create_test_instance(self, configuration_logs_entry, monitors_log_configs):\n logs_json_array = JsonArray()\n for entry in configuration_logs_entry:\n logs_json_array.add(JsonObject(content=entry))\n\n config = ScalyrTestUtils.create_configuration(extra_toplevel_config={'logs': logs_json_array})\n\n self.__monitor_fake_instances = []\n for monitor_log_config in monitors_log_configs:\n self.__monitor_fake_instances.append(FakeMonitor(monitor_log_config))\n\n # noinspection PyTypeChecker\n return CopyingManager(config, self.__monitor_fake_instances)\n\n\nclass CopyingManagerEnd2EndTest(ScalyrTestCase):\n\n def setUp(self):\n self._controller = None\n\n def tearDown(self):\n if self._controller is not None:\n self._controller.stop()\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_single_log_file(self):\n controller = self.__create_test_instance()\n self.__append_log_lines('First line', 'Second line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('success')\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_multiple_scans_of_log_file(self):\n controller = self.__create_test_instance()\n self.__append_log_lines('First line', 'Second line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('success')\n\n self.__append_log_lines('Third line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(1, len(lines))\n self.assertEquals('Third line', lines[0])\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_normal_error(self):\n controller = self.__create_test_instance()\n self.__append_log_lines('First line', 'Second line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('error')\n\n self.__append_log_lines('Third line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_drop_request_due_to_error(self):\n controller = self.__create_test_instance()\n self.__append_log_lines('First line', 'Second line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('discardBuffer')\n\n self.__append_log_lines('Third line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(1, len(lines))\n self.assertEquals('Third line', lines[0])\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_request_too_large_error(self):\n controller = self.__create_test_instance()\n self.__append_log_lines('First line', 'Second line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('requestTooLarge')\n\n self.__append_log_lines('Third line')\n (request, responder_callback) = controller.wait_for_rpc()\n\n lines = self.__extract_lines(request)\n self.assertEquals(3, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n self.assertEquals('Third line', lines[2])\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_pipelined_requests(self):\n controller = self.__create_test_instance(use_pipelining=True)\n self.__append_log_lines('First line', 'Second line')\n\n controller.perform_scan()\n self.__append_log_lines('Third line')\n controller.perform_pipeline_scan()\n (request, responder_callback) = controller.wait_for_rpc()\n\n self.assertFalse(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('success')\n\n (request, responder_callback) = controller.wait_for_rpc()\n\n self.assertTrue(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n self.assertEquals(1, len(lines))\n self.assertEquals('Third line', lines[0])\n\n responder_callback('success')\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_pipelined_requests_with_normal_error(self):\n controller = self.__create_test_instance(use_pipelining=True)\n self.__append_log_lines('First line', 'Second line')\n\n controller.perform_scan()\n self.__append_log_lines('Third line')\n controller.perform_pipeline_scan()\n (request, responder_callback) = controller.wait_for_rpc()\n\n self.assertFalse(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('error')\n\n (request, responder_callback) = controller.wait_for_rpc()\n self.assertFalse(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('success')\n\n (request, responder_callback) = controller.wait_for_rpc()\n\n self.assertTrue(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n self.assertEquals(1, len(lines))\n self.assertEquals('Third line', lines[0])\n\n responder_callback('success')\n\n @unittest.skip(\"@czerwin to investigate\")\n def test_pipelined_requests_with_retry_error(self):\n controller = self.__create_test_instance(use_pipelining=True)\n self.__append_log_lines('First line', 'Second line')\n\n controller.perform_scan()\n self.__append_log_lines('Third line')\n controller.perform_pipeline_scan()\n (request, responder_callback) = controller.wait_for_rpc()\n\n self.assertFalse(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n\n self.assertEquals(2, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n\n responder_callback('requestTooLarge')\n\n (request, responder_callback) = controller.wait_for_rpc()\n self.assertFalse(self.__was_pipelined(request))\n\n lines = self.__extract_lines(request)\n\n self.assertEquals(3, len(lines))\n self.assertEquals('First line', lines[0])\n self.assertEquals('Second line', lines[1])\n self.assertEquals('Third line', lines[2])\n\n responder_callback('success')\n\n def __extract_lines(self, request):\n parsed_request = json_lib.parse(request.get_payload())\n\n lines = []\n\n if 'events' in parsed_request:\n for event in parsed_request.get_json_array('events'):\n if 'attrs' in event:\n attrs = event.get_json_object('attrs')\n if 'message' in attrs:\n lines.append(attrs.get_string('message').strip())\n\n return lines\n\n def __was_pipelined(self, request):\n return 'pipelined=1.0' in request.get_timing_data()\n\n def __create_test_instance(self, use_pipelining=False):\n tmp_dir = tempfile.mkdtemp()\n config_dir = os.path.join(tmp_dir, 'config')\n data_dir = os.path.join(tmp_dir, 'data')\n log_dir = os.path.join(tmp_dir, 'log')\n\n os.mkdir(data_dir)\n os.mkdir(config_dir)\n os.mkdir(log_dir)\n\n self.__test_log_file = os.path.join(tmp_dir, 'test.log')\n fp = open(self.__test_log_file, 'w')\n fp.close()\n\n config_file = os.path.join(config_dir, 'agentConfig.json')\n config_fragments_dir = os.path.join(config_dir, 'configs.d')\n os.makedirs(config_fragments_dir)\n\n logs_json_array = JsonArray()\n logs_json_array.add(JsonObject(path=self.__test_log_file))\n\n pipeline_threshold = 1.1\n if use_pipelining:\n pipeline_threshold = 0.0\n\n fp = open(config_file, 'w')\n fp.write(json_lib.serialize(JsonObject(api_key='fake', logs=logs_json_array,\n pipeline_threshold=pipeline_threshold)))\n fp.close()\n\n default_paths = DefaultPaths(log_dir, config_file, data_dir)\n\n config = Configuration(config_file, default_paths, None)\n config.parse()\n\n # noinspection PyTypeChecker\n self._controller = TestableCopyingManager(config, []).controller\n return self._controller\n\n def __append_log_lines(self, *args):\n fp = open(self.__test_log_file, 'a')\n for l in args:\n fp.write(l)\n fp.write('\\n')\n fp.close()\n\n\nclass TestableCopyingManager(CopyingManager):\n \"\"\"An instrumented version of the CopyingManager which allows intercepting of requests sent, control when\n the manager processes new logs, etc.\n\n This allows for end-to-end testing of the core of the CopyingManager.\n\n Doing this right is a bit complicated because the CopyingManager runs in its own thread.\n\n To actually control the copying manager, use the TestController object returned by ``controller``.\n \"\"\"\n def __init__(self, configuration, monitors):\n CopyingManager.__init__(self, configuration, monitors)\n # Approach: We will override key methods of CopyingManager, blocking them from returning until the controller\n # tells it to proceed. This allows us to then do things like write new log lines while the CopyingManager is\n # blocked. Coordinating the communication between the two threads is done using two condition variables.\n # We changed the CopyingManager to block in three places: while it is sleeping before it starts a new loop,\n # when it invokes ``_send_events`` to send a new request, and when it blocks to receive the response.\n # These three states or referred to as \"sleeping\", \"blocked_on_send\", \"blocked_on_receive\".\n #\n # This cv protects all of the variables written by the CopyingManager thread.\n self.__test_state_cv = threading.Condition()\n # Which state the CopyingManager is currently blocked in -- \"sleeping\", \"blocked_on_send\", \"blocked_on_receive\"\n self.__test_state = None\n # The number of times the CopyingManager has blocked.\n self.__test_state_changes = 0\n # Whether or not the CopyingManager should stop.\n self.__test_stopping = False\n # Written by CopyingManager. The last AddEventsRequest request passed into ``_send_events``.\n self.__captured_request = None\n # Protected by __test_state_cv. The status message to return for the next call to ``_send_events``.\n self.__pending_response = None\n\n # This cv protects __advance_requests and is used mainly by the testing thread.\n self.__advance_requests_cv = threading.Condition()\n # This is incremented everytime the controller wants the CopyingManager to advance to the next blocking state,\n # regardless of which state it is in.\n self.__advance_requests = 0\n\n self.__controller = TestableCopyingManager.TestController(self)\n\n @property\n def controller(self):\n return self.__controller\n\n def _sleep_but_awaken_if_stopped(self, seconds):\n \"\"\"Blocks the CopyingManager thread until the controller tells it to proceed.\n \"\"\"\n self.__test_state_cv.acquire()\n self.__wait_until_advance_received('sleeping')\n self.__test_state_cv.release()\n\n def _create_add_events_request(self, session_info=None, max_size=None):\n # Need to override this to return an AddEventsRequest even though we don't have a real scalyr client instance.\n if session_info is None:\n body = JsonObject(server_attributes=session_info, token='fake')\n else:\n body = JsonObject(token='fake')\n\n return AddEventsRequest(body, max_size=max_size)\n\n def _send_events(self, add_events_task):\n \"\"\"Captures ``add_events_task`` and emulates sending an AddEventsTask.\n\n This method will not return until the controller tells it to advance to the next state.\n \"\"\"\n # First, block even returning from this method until the controller advances us.\n self.__test_state_cv.acquire()\n self.__wait_until_advance_received('blocked_on_send')\n self.__captured_request = add_events_task.add_events_request\n self.__test_state_cv.release()\n\n # Create a method that we can return that will (when invoked) return the response\n def emit_response():\n # Block on return the response until the state is advanced.\n self.__test_state_cv.acquire()\n self.__wait_until_advance_received('blocked_on_receive')\n\n # Use the pending response if there is one. Otherwise, we just say \"success\" which means all add event\n # requests will just be processed.\n result = self.__pending_response\n self.__pending_response = None\n self.__test_state_cv.release()\n\n if result is not None:\n return result, 0, 'fake'\n else:\n return 'success', 0, 'fake'\n\n return emit_response\n\n def __wait_until_advance_received(self, new_state):\n \"\"\"Helper method for blocking the thread until the controller thread has indicated this one should advance\n to its next state.\n\n You must be holding the self.__test_state_cv lock to invoke this method.\n\n @param new_state: The name of the blocking state the CopyingManager is in until it is advanced.\n @type new_state: str\n \"\"\"\n if self.__test_stopping:\n return\n # We are about to block, so be sure to increment the count. We make use of this to detect when state changes\n # are made. This is broadcasted to the controller thread.\n self.__test_state_changes += 1\n self.__test_state = new_state\n self.__test_state_cv.notifyAll()\n self.__test_state_cv.release()\n\n # Now we have to wait until we see another advance request. To do that, we just note when the number of\n # advances has increased. Of course, we need to get the __advance_requests_cv lock to look at that var.\n self.__advance_requests_cv.acquire()\n original_advance_requests = self.__advance_requests\n\n while self.__advance_requests == original_advance_requests:\n self.__advance_requests_cv.wait()\n self.__advance_requests_cv.release()\n\n # Get the lock again so that we have it when the method returns.\n self.__test_state_cv.acquire()\n self.__test_state = 'running'\n\n def captured_request(self):\n \"\"\"Returns the last request that was passed into ``_send_events`` by the CopyingManager, or None if there\n wasn't any.\n\n This will also reset the captured request to None so the returned request won't be returned twice.\n\n @return: The last request\n @rtype: AddEventsRequest\n \"\"\"\n self.__test_state_cv.acquire()\n try:\n result = self.__captured_request\n self.__captured_request = None\n return result\n finally:\n self.__test_state_cv.release()\n\n def set_response(self, status_message):\n \"\"\"Sets the status_message to return as the response for the next AddEventsRequest.\n\n @param status_message: The status message\n @type status_message: str\n \"\"\"\n self.__test_state_cv.acquire()\n self.__pending_response = status_message\n self.__test_state_cv.release()\n\n def advance_until(self, final_state):\n \"\"\"Instructs the CopyingManager thread to keep advancing through its blocking states until it reaches the\n named one.\n\n @param final_state: The name of the state to wait for (such as \"sleeping\", \"blocked_on_receive\", etc.\n @type final_state: str\n \"\"\"\n self.__test_state_cv.acquire()\n original_count = self.__test_state_changes\n\n # We have to keep incrementing the __advanced_requests count so that the copying manager thread keeps\n # advancing. We wait on the test_state_cv because everytime the CopyingManager blocks, it notifies that cv.\n while self.__test_state_changes <= original_count or self.__test_state != final_state:\n self.__advance_requests_cv.acquire()\n self.__advance_requests += 1\n self.__advance_requests_cv.notifyAll()\n self.__advance_requests_cv.release()\n self.__test_state_cv.wait()\n\n self.__test_state_cv.release()\n\n def stop_manager(self, wait_on_join=True, join_timeout=5):\n \"\"\"Stops the manager's thread.\n\n @param wait_on_join: Whether or not to wait on thread to finish.\n @param join_timeout: The number of seconds to wait on the join.\n @type wait_on_join: bool\n @type join_timeout: float\n @return:\n @rtype:\n \"\"\"\n # We need to do some extra work here in case the CopyingManager thread is currently in a blocked state.\n # We need to tell it to advance.\n self.__test_state_cv.acquire()\n self.__test_stopping = True\n self.__test_state_cv.release()\n\n self.__advance_requests_cv.acquire()\n self.__advance_requests += 1\n self.__advance_requests_cv.notifyAll()\n self.__advance_requests_cv.release()\n\n CopyingManager.stop_manager(self, wait_on_join=wait_on_join, join_timeout=join_timeout)\n\n @property\n def test_state(self):\n \"\"\"\n @return: Returns the name of the state the CopyingManager thread is currently blocked in, such as\n \"sleeping\", \"blocked_on_send\", \"blocked_on_receive\".\n @rtype: str\n \"\"\"\n self.__test_state_cv.acquire()\n try:\n return self.__test_state\n finally:\n self.__test_state_cv.release()\n\n class TestController(object):\n \"\"\"Used to control the TestableCopyingManager.\n\n Its main role is to tell the manager thread when to unblock and how far to run.\n \"\"\"\n def __init__(self, copying_manager):\n self.__copying_manager = copying_manager\n copying_manager.start_manager(dict(fake_client=True))\n\n # To do a proper initialization where the copying manager has scanned the current log file and is ready\n # for the next loop, we let it go all the way through the loop once and wait in the sleeping state.\n self.__copying_manager.advance_until('sleeping')\n\n def perform_scan(self):\n \"\"\"Tells the CopyingManager thread to go through the process loop until far enough where it has performed\n the scan of the file system looking for new bytes in the log file.\n\n At this point, the CopyingManager should have a request ready to be sent.\n \"\"\"\n self.__copying_manager.captured_request()\n self.__copying_manager.advance_until('blocked_on_send')\n\n def perform_pipeline_scan(self):\n \"\"\"Tells the CopyingManager thread to advance far enough where it has performed the file system scan\n for the pipelined AddEventsRequest, if the manager is configured to send one..\n\n This is only valid to call immediately after a ``perform_scan``\n \"\"\"\n self.__copying_manager.advance_until('blocked_on_receive')\n\n def wait_for_rpc(self):\n \"\"\"Tells the CopyingManager thread to advance to the point where it has emulated sending an RPC.\n\n @return: A tuple containing the AddEventsRequest that was sent by the CopyingManager and a function that\n when invoked will return the passed in status message as the response to the AddEventsRequest.\n @rtype: (AddEventsRequest, func)\n \"\"\"\n if self.__copying_manager.test_state != 'blocked_on_receive':\n self.__copying_manager.advance_until('blocked_on_receive')\n request = self.__copying_manager.captured_request()\n\n def send_response(status_message):\n self.__copying_manager.set_response(status_message)\n self.__copying_manager.advance_until('sleeping')\n\n return request, send_response\n\n def stop(self):\n self.__copying_manager.stop_manager()\n\n\nclass FakeMonitor(object):\n def __init__(self, monitor_log_config):\n self.module_name = 'fake_monitor'\n self.log_config = monitor_log_config\n\n def set_log_watcher(self, log_watcher):\n pass\n","sub_path":"scalyr_agent/tests/copying_manager_test.py","file_name":"copying_manager_test.py","file_ext":"py","file_size_in_byte":30391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"191458351","text":"'''Arsenal API physical_elevations.'''\n# Copyright 2015 CityGrid Media, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport logging\nfrom datetime import datetime\nfrom pyramid.view import view_config\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom arsenalweb.views import (\n get_authenticated_user,\n )\nfrom arsenalweb.views.api.common import (\n api_200,\n api_400,\n api_500,\n api_501,\n collect_params,\n )\nfrom arsenalweb.views.api.physical_racks import (\n find_physical_rack_by_name_loc,\n )\nfrom arsenalweb.views.api.physical_locations import (\n find_physical_location_by_name,\n )\nfrom arsenalweb.models.common import (\n DBSession,\n )\nfrom arsenalweb.models.physical_elevations import (\n PhysicalElevation,\n PhysicalElevationAudit,\n )\n\nLOG = logging.getLogger(__name__)\n\n\n# Functions\ndef find_physical_elevation_by_elevation(elevation, physical_rack_id):\n '''Find a physical_elevation by elevation and physical_rack_id. Returns\n a physical_elevation object if found, raises NoResultFound otherwise.'''\n\n LOG.debug('Searching for physical_elevation by elevation: {0} '\n 'physical_rack_id: {1}'.format(elevation, physical_rack_id))\n physical_elevation = DBSession.query(PhysicalElevation)\n physical_elevation = physical_elevation.filter(PhysicalElevation.elevation == elevation)\n physical_elevation = physical_elevation.filter(PhysicalElevation.physical_rack_id == physical_rack_id)\n\n return physical_elevation.one()\n\ndef find_physical_elevation_by_id(physical_elevation_id):\n '''Find a physical_elevation by id.'''\n\n LOG.debug('Searching for physical_elevation by id: {0}'.format(physical_elevation_id))\n physical_elevation = DBSession.query(PhysicalElevation)\n physical_elevation = physical_elevation.filter(PhysicalElevation.id == physical_elevation_id)\n\n return physical_elevation.one()\n\ndef create_physical_elevation(elevation=None,\n physical_rack_id=None,\n updated_by=None,\n **kwargs):\n '''Create a new physical_elevation.\n\n Required params:\n\n elevation : A string that is the elevation of the rack.\n physical_rack_id: An integer that represents the id of the\n physical_rack the elevation resides in.\n updated_by: A string that is the user making the update.\n\n Optional kwargs:\n\n None yet.\n '''\n\n try:\n LOG.info('Creating new physical_elevation name: {0} physical_rack_id: '\n '{1}'.format(elevation, physical_rack_id))\n\n utcnow = datetime.utcnow()\n\n physical_elevation = PhysicalElevation(elevation=elevation,\n physical_rack_id=physical_rack_id,\n updated_by=updated_by,\n created=utcnow,\n updated=utcnow,\n **kwargs)\n\n DBSession.add(physical_elevation)\n DBSession.flush()\n\n audit = PhysicalElevationAudit(object_id=physical_elevation.id,\n field='elevation',\n old_value='created',\n new_value=physical_elevation.elevation,\n updated_by=updated_by,\n created=utcnow)\n DBSession.add(audit)\n DBSession.flush()\n\n return api_200(results=physical_elevation)\n\n except Exception as ex:\n msg = 'Error creating new physical_elevation elevation: {0} exception: ' \\\n '{1}'.format(elevation, ex)\n LOG.error(msg)\n return api_500(msg=msg)\n\ndef update_physical_elevation(physical_elevation, **kwargs):\n '''Update an existing physical_elevation.\n\n Required params:\n\n physical_elevation : A physical_elevation object.\n updated_by : A string that is the user making the update.\n\n Optional kwargs:\n\n physical_rack_id: An integer that represents the id of the\n physical_rack the elevation resides in.\n '''\n\n try:\n LOG.info('Updating physical_elevation: {0}'.format(physical_elevation.elevation))\n\n utcnow = datetime.utcnow()\n\n for attribute in kwargs:\n if attribute == 'elevation':\n LOG.debug('Skipping update to physical_elevation.elevation')\n continue\n old_value = getattr(physical_elevation, attribute)\n new_value = kwargs[attribute]\n\n if old_value != new_value and new_value:\n if not old_value:\n old_value = 'None'\n\n LOG.debug('Types old_value: {0} new_value: {1}'.format(type(old_value),\n type(new_value)))\n LOG.debug('Updating physical_elevation: {0} attribute: '\n '{1} new_value: {2}'.format(physical_elevation.elevation,\n attribute,\n new_value))\n audit = PhysicalElevationAudit(object_id=physical_elevation.id,\n field=attribute,\n old_value=old_value,\n new_value=new_value,\n updated_by=kwargs['updated_by'],\n created=utcnow)\n DBSession.add(audit)\n setattr(physical_elevation, attribute, new_value)\n\n DBSession.flush()\n\n return api_200(results=physical_elevation)\n\n except Exception as ex:\n msg = 'Error updating physical_elevation name: {0} updated_by: {1} exception: ' \\\n '{2}'.format(physical_elevation.elevation,\n my_attribs['updated_by'],\n repr(ex))\n LOG.error(msg)\n raise\n\n# Routes\n@view_config(route_name='api_physical_elevations', request_method='GET', request_param='schema=true', renderer='json')\ndef api_physical_elevations_schema(request):\n '''Schema document for the physical_elevations API.'''\n\n physical_elevation = {\n }\n\n return physical_elevation\n\n@view_config(route_name='api_physical_elevations', permission='physical_elevation_write', request_method='PUT', renderer='json')\ndef api_physical_elevations_write(request):\n '''Process write requests for /api/physical_elevations route.'''\n\n try:\n req_params = [\n 'elevation',\n 'physical_location',\n 'physical_rack',\n ]\n opt_params = []\n params = collect_params(request, req_params, opt_params)\n\n try:\n physical_location = find_physical_location_by_name(params['physical_location'])\n del params['physical_location']\n\n physical_rack = find_physical_rack_by_name_loc(params['physical_rack'],\n physical_location.id)\n params['physical_rack_id'] = physical_rack.id\n del params['physical_rack']\n\n try:\n physical_el = find_physical_elevation_by_elevation(params['elevation'],\n params['physical_rack_id'])\n resp = update_physical_elevation(physical_el, **params)\n except NoResultFound:\n resp = create_physical_elevation(**params)\n except:\n raise\n\n return resp\n\n except Exception as ex:\n msg = 'Error writing to physical_racks API: {0} exception: {1}'.format(request.url, ex)\n LOG.error(msg)\n return api_500(msg=msg)\n\n@view_config(route_name='api_physical_elevation_r', permission='physical_elevation_delete', request_method='DELETE', renderer='json')\n@view_config(route_name='api_physical_elevation_r', permission='physical_elevation_write', request_method='PUT', renderer='json')\ndef api_physical_elevation_write_attrib(request):\n '''Process write requests for the /api/physical_elevations/{id}/{resource} route.'''\n\n resource = request.matchdict['resource']\n payload = request.json_body\n auth_user = get_authenticated_user(request)\n\n LOG.debug('Updating {0}'.format(request.url))\n\n # First get the physical_elevation, then figure out what to do to it.\n physical_elevation = find_physical_elevation_by_id(request.matchdict['id'])\n LOG.debug('physical_elevation is: {0}'.format(physical_elevation))\n\n # List of resources allowed\n resources = [\n 'nothing_yet',\n ]\n\n # There's nothing to do here yet. Maye add updates to existing physical_elevation?\n if resource in resources:\n try:\n actionable = payload[resource]\n except KeyError:\n msg = 'Missing required parameter: {0}'.format(resource)\n return api_400(msg=msg)\n except Exception as ex:\n LOG.error('Error updating physical_elevations: {0} exception: {1}'.format(request.url, ex))\n return api_500(msg=str(ex))\n else:\n return api_501()\n\n return resp\n","sub_path":"server/arsenalweb/views/api/physical_elevations.py","file_name":"physical_elevations.py","file_ext":"py","file_size_in_byte":9810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"160184432","text":"\"\"\"\nCS224N 2016-17: Homework 3\nutil.py: General utility routines\nArun Chaganty \n\"\"\"\nfrom __future__ import division\nimport tensorflow as tf\nimport sys\nimport time\nimport logging\nimport io\nfrom collections import defaultdict, Counter, OrderedDict\nimport numpy as np\nimport tensorflow as tf\nfrom numpy import array, zeros, allclose\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom os.path import join as pjoin\nimport os\nimport pickle\n\ndef BiLSTM_layer(inputs, masks, state_size, initial_state_fw=None, initial_state_bw=None, reuse = False, keep_prob=1.0):\n ''' Wrapped BiLSTM_layer for reuse'''\n # 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size]\n cell_fw = tf.contrib.rnn.BasicLSTMCell(state_size, reuse = reuse)\n cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, input_keep_prob = keep_prob)\n\n cell_bw = tf.contrib.rnn.BasicLSTMCell(state_size, reuse = reuse)\n cell_bw = tf.contrib.rnn.DropoutWrapper(cell_bw, input_keep_prob = keep_prob)\n\n sequence_length = tf.reduce_sum(tf.cast(masks, 'int32'), axis=1)\n sequence_length = tf.reshape(sequence_length, [-1,])\n\n # Outputs Tensor shaped: [batch_size, max_time, cell.output_size]\n (outputs_fw, outputs_bw), (final_state_fw, final_state_bw) = tf.nn.bidirectional_dynamic_rnn(\n cell_fw = cell_fw,\\\n cell_bw = cell_bw,\\\n inputs = inputs,\\\n sequence_length = sequence_length,\n initial_state_fw = initial_state_fw,\\\n initial_state_bw = initial_state_bw,\n dtype = tf.float32)\n\n outputs = tf.concat([outputs_fw, outputs_bw], 2)\n # final_state_fw and final_state_bw are the final states of the forwards/backwards LSTM\n # final_state = tf.concat([final_state_fw[1], final_state_bw[1]], 1)\n # return (outputs, final_state, (final_state_fw, final_state_bw))\n return outputs, final_state_fw, final_state_bw\n\ndef BiGRU_layer(inputs, masks, state_size, initial_state_fw=None, initial_state_bw=None, reuse = False, keep_prob=1.0):\n ''' Wrapped BiGRU_layer for reuse'''\n # 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size]\n cell_fw = tf.contrib.rnn.GRUCell(state_size, reuse = reuse)\n cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, input_keep_prob = keep_prob)\n\n cell_bw = tf.contrib.rnn.GRUCell(state_size, reuse = reuse)\n cell_bw = tf.contrib.rnn.DropoutWrapper(cell_bw, input_keep_prob = keep_prob)\n\n sequence_length = tf.reduce_sum(tf.cast(masks, 'int32'), axis=1)\n sequence_length = tf.reshape(sequence_length, [-1,])\n\n # Outputs Tensor shaped: [batch_size, max_time, cell.output_size]\n (outputs_fw, outputs_bw), (final_state_fw, final_state_bw) = tf.nn.bidirectional_dynamic_rnn(\n cell_fw = cell_fw,\\\n cell_bw = cell_bw,\\\n inputs = inputs,\\\n sequence_length = sequence_length,\n initial_state_fw = initial_state_fw,\\\n initial_state_bw = initial_state_bw,\n dtype = tf.float32)\n\n outputs = tf.concat([outputs_fw, outputs_bw], 2)\n return outputs, final_state_fw, final_state_bw\n\ndef save_graphs(data, path):\n\n # First plot the losses\n losses = data[\"losses\"]\n\n fig = plt.figure()\n plt.plot([i for i in range(len(losses))], losses)\n plt.title(\"Batch sized used: {}\".format(data[\"batch_size\"]))\n plt.xlabel('batch number', fontsize=18)\n plt.ylabel('average loss', fontsize=16)\n fig.savefig(pjoin(path, 'loss.pdf'))\n plt.close(fig)\n\n batch_indices = data[\"batch_indices\"]\n\n # Now plot the f1, EM for the training and validation sets\n f1_train, f1_val = data[\"f1_train\"], data[\"f1_val\"]\n\n fig = plt.figure()\n plt.plot(batch_indices, f1_train, 'b', batch_indices, f1_val, 'r')\n plt.title(\"Batch sized used: {}\".format(data[\"batch_size\"]))\n plt.xlabel('batch number', fontsize=18)\n plt.ylabel('F1 Score', fontsize = 16)\n fig.savefig(pjoin(path, \"f1_scores.pdf\"))\n plt.close(fig)\n\n EM_train, EM_val = data[\"EM_train\"], data[\"EM_val\"]\n\n fig = plt.figure()\n plt.plot(batch_indices, EM_train, 'b', batch_indices, EM_val, 'r')\n plt.title(\"Batch sized used: {}\".format(data[\"batch_size\"]))\n plt.xlabel('batch number', fontsize=18)\n plt.ylabel('EM Score', fontsize = 16)\n fig.savefig(pjoin(path, \"EM_scores.pdf\"))\n plt.close(fig)\n\ndef variable_summaries(var):\n \"\"\" Attach summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\ndef get_optimizer(opt, loss, max_grad_norm, learning_rate):\n ''' With gradient clipping '''\n if opt == \"adam\":\n optfn = tf.train.AdamOptimizer(learning_rate = learning_rate)\n elif opt == \"sgd\":\n optfn = tf.train.GradientDescentOptimizer(learning_rate = learning_rate)\n else:\n assert (False)\n\n grads_and_vars = optfn.compute_gradients(loss)\n variables = [output[1] for output in grads_and_vars]\n gradients = [output[0] for output in grads_and_vars]\n\n gradients = tf.clip_by_global_norm(gradients, clip_norm = max_grad_norm)[0]\n grads_and_vars = [(gradients[i], variables[i]) for i in range(len(gradients))]\n train_op = optfn.apply_gradients(grads_and_vars)\n\n return train_op\n\ndef softmax_mask_prepro(logits, mask):\n ''' Make the indexes of the mask values of 1 and indexes of non mask 0\n Set huge neg number(-1e9) in padding area\n '''\n assert logits.get_shape().ndims == mask.get_shape().ndims\n # filter out the padding area as 1, the index area becomes 0\n new_mask = tf.subtract(tf.constant(1.0), tf.cast(mask, tf.float32))\n paddings_mask = tf.multiply(new_mask, tf.constant(-1e9))\n masked_logits = tf.where(mask, logits, paddings_mask)\n return masked_logits\n\ndef get_best_span(start_logits, end_logits, context_ids):\n start_sentence_logits = []\n end_sentence_logits = []\n new_start_sentence = []\n new_end_sentence = []\n for i, c_id in enumerate(context_ids):\n new_start_sentence.append(start_logits[i])\n new_end_sentence.append(end_logits[i])\n if c_id == 6: # dot id, represents the end of a sentence\n start_sentence_logits.append(new_start_sentence)\n end_sentence_logits.append(new_end_sentence)\n new_start_sentence = []\n new_end_sentence = []\n if len(new_start_sentence) > 0:\n start_sentence_logits.append(new_start_sentence)\n end_sentence_logits.append(new_end_sentence)\n\n # print start_sentence_logits\n # print [len(a) for a in start_sentence_logits]\n best_word_span = (0, 0)\n best_sent_idx = 0\n argmax_j1 = 0\n max_val = start_logits[0] + end_logits[0]\n for f, (ypif, yp2if) in enumerate(zip(start_sentence_logits, end_sentence_logits)):\n argmax_j1 = 0\n for j in range(len(ypif)):\n val1 = ypif[argmax_j1]\n if val1 < ypif[j]:\n val1 = ypif[j]\n argmax_j1 = j\n\n val2 = yp2if[j]\n if val1 + val2 > max_val:\n best_word_span = (argmax_j1, j)\n best_sent_idx = f\n max_val = val1 + val2\n len_pre = 0\n for i in range(best_sent_idx):\n len_pre += len(start_sentence_logits[i])\n # print best_sent_idx\n best_word_span = (len_pre + best_word_span[0], len_pre + best_word_span[1])\n return best_word_span, max_val\n\nclass Progbar(object):\n \"\"\"\n Progbar class copied from keras (https://github.com/fchollet/keras/)\n Displays a progress bar.\n # Arguments\n target: Total number of steps expected.\n interval: Minimum visual progress update interval (in seconds).\n \"\"\"\n\n def __init__(self, target, width=30, verbose = 1):\n self.width = width\n self.target = target\n self.sum_values = {}\n self.unique_values = []\n self.start = time.time()\n self.total_width = 0\n self.seen_so_far = 0\n self.verbose = verbose\n\n def update(self, current, values=None, exact=None):\n \"\"\"\n Updates the progress bar.\n # Arguments\n current: Index of current step.\n values: List of tuples (name, value_for_last_step).\n The progress bar will display averages for these values.\n exact: List of tuples (name, value_for_last_step).\n The progress bar will display these values directly.\n \"\"\"\n values = values or []\n exact = exact or []\n\n for k, v in values:\n if k not in self.sum_values:\n self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far]\n self.unique_values.append(k)\n else:\n self.sum_values[k][0] += v * (current - self.seen_so_far)\n self.sum_values[k][1] += (current - self.seen_so_far)\n for k, v in exact:\n if k not in self.sum_values:\n self.unique_values.append(k)\n self.sum_values[k] = [v, 1]\n self.seen_so_far = current\n\n now = time.time()\n if self.verbose == 1:\n prev_total_width = self.total_width\n sys.stdout.write(\"\\b\" * prev_total_width)\n sys.stdout.write(\"\\r\")\n\n numdigits = int(np.floor(np.log10(self.target))) + 1\n barstr = '%%%dd/%%%dd [' % (numdigits, numdigits)\n bar = barstr % (current, self.target)\n prog = float(current)/self.target\n prog_width = int(self.width*prog)\n if prog_width > 0:\n bar += ('='*(prog_width-1))\n if current < self.target:\n bar += '>'\n else:\n bar += '='\n bar += ('.'*(self.width-prog_width))\n bar += ']'\n sys.stdout.write(bar)\n self.total_width = len(bar)\n\n if current:\n time_per_unit = (now - self.start) / current\n else:\n time_per_unit = 0\n eta = time_per_unit*(self.target - current)\n info = ''\n if current < self.target:\n info += ' - ETA: %ds' % eta\n else:\n info += ' - %ds' % (now - self.start)\n for k in self.unique_values:\n if isinstance(self.sum_values[k], list):\n info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))\n else:\n info += ' - %s: %s' % (k, self.sum_values[k])\n\n self.total_width += len(info)\n if prev_total_width > self.total_width:\n info += ((prev_total_width-self.total_width) * \" \")\n\n sys.stdout.write(info)\n sys.stdout.flush()\n\n if current >= self.target:\n sys.stdout.write(\"\\n\")\n\n if self.verbose == 2:\n if current >= self.target:\n info = '%ds' % (now - self.start)\n for k in self.unique_values:\n info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))\n sys.stdout.write(info + \"\\n\")\n\n def add(self, n, values=None):\n self.update(self.seen_so_far+n, values)\n\ndef read_conll(fstream):\n \"\"\"\n Reads a input stream @fstream (e.g. output of `open(fname, 'r')`) in CoNLL file format.\n @returns a list of examples [(tokens), (labels)]. @tokens and @labels are lists of string.\n \"\"\"\n ret = []\n\n current_toks, current_lbls = [], []\n for line in fstream:\n line = line.strip()\n if len(line) == 0 or line.startswith(\"-DOCSTART-\"):\n if len(current_toks) > 0:\n assert len(current_toks) == len(current_lbls)\n ret.append((current_toks, current_lbls))\n current_toks, current_lbls = [], []\n else:\n assert \"\\t\" in line, r\"Invalid CONLL format; expected a '\\t' in {}\".format(line)\n tok, lbl = line.split(\"\\t\")\n current_toks.append(tok)\n current_lbls.append(lbl)\n if len(current_toks) > 0:\n assert len(current_toks) == len(current_lbls)\n ret.append((current_toks, current_lbls))\n return ret\n\ndef test_read_conll():\n input_ = [\n \"EU ORG\",\n \"rejects O\",\n \"German MISC\",\n \"call O\",\n \"to O\",\n \"boycott O\",\n \"British MISC\",\n \"lamb O\",\n \". O\",\n \"\",\n \"Peter PER\",\n \"Blackburn PER\",\n \"\",\n ]\n output = [\n (\"EU rejects German call to boycott British lamb .\".split(), \"ORG O MISC O O O MISC O O\".split()),\n (\"Peter Blackburn\".split(), \"PER PER\".split())\n ]\n\n assert read_conll(input_) == output\n\ndef write_conll(fstream, data):\n \"\"\"\n Writes to an output stream @fstream (e.g. output of `open(fname, 'r')`) in CoNLL file format.\n @data a list of examples [(tokens), (labels), (predictions)]. @tokens, @labels, @predictions are lists of string.\n \"\"\"\n for cols in data:\n for row in zip(*cols):\n fstream.write(\"\\t\".join(row))\n fstream.write(\"\\n\")\n fstream.write(\"\\n\")\n\ndef test_write_conll():\n input = [\n (\"EU rejects German call to boycott British lamb .\".split(), \"ORG O MISC O O O MISC O O\".split()),\n (\"Peter Blackburn\".split(), \"PER PER\".split())\n ]\n output = \"\"\"EU ORG\n rejects O\n German MISC\n call O\n to O\n boycott O\n British MISC\n lamb O\n . O\n\n Peter PER\n Blackburn PER\n\n \"\"\"\n output_ = io.StringIO()\n write_conll(output_, input)\n output_ = output_.getvalue()\n assert output == output_\n\ndef load_word_vector_mapping(vocab_fstream, vector_fstream):\n \"\"\"\n Load word vector mapping using @vocab_fstream, @vector_fstream.\n Assumes each line of the vocab file matches with those of the vector\n file.\n \"\"\"\n ret = OrderedDict()\n for vocab, vector in zip(vocab_fstream, vector_fstream):\n vocab = vocab.strip()\n vector = vector.strip()\n ret[vocab] = array(list(map(float, vector.split())))\n\n return ret\n\ndef test_load_word_vector_mapping():\n vocab = \"\"\"UUUNKKK\nthe\n,\n.\nof\nand\nin\"\"\".split(\"\\n\")\n vector = \"\"\"0.172414 -0.091063 0.255125 -0.837163 0.434872 -0.499848 -0.042904 -0.059642 -0.635087 -0.458795 -0.105671 0.506513 -0.105105 -0.405678 0.493365 0.408807 0.401635 -0.817805 0.626340 0.580636 -0.246996 -0.008515 -0.671140 0.301865 -0.439651 0.247694 -0.291402 0.873009 0.216212 0.145576 -0.211101 -0.352360 0.227651 -0.118416 0.371816 0.261296 0.017548 0.596692 -0.485722 -0.369530 -0.048807 0.017960 -0.040483 0.111193 0.398039 0.162765 0.408946 0.005343 -0.107523 -0.079821\n-0.454847 1.002773 -1.406829 -0.016482 0.459856 -0.224457 0.093396 -0.826833 -0.530674 1.211044 -0.165133 0.174454 -1.130952 -0.612020 -0.024578 -0.168508 0.320113 0.774229 -0.360418 1.483124 -0.230922 0.301055 -0.119924 0.601642 0.694616 -0.304431 -0.414284 0.667385 0.171208 -0.334842 -0.459286 -0.534202 0.533660 -0.379468 -0.378721 -0.240499 -0.446272 0.686113 0.662359 -0.865312 0.861331 -0.627698 -0.569544 -1.228366 -0.152052 1.589123 0.081337 0.182695 -0.593022 0.438300\n-0.408797 -0.109333 -0.099279 -0.857098 -0.150319 -0.456398 -0.781524 -0.059621 0.302548 0.202162 -0.319892 -0.502241 -0.014925 0.020889 1.506245 0.247530 0.385598 -0.170776 0.325960 0.267304 0.157673 0.125540 -0.971452 -0.485595 0.487857 0.284369 -0.062811 -1.334082 0.744133 0.572701 1.009871 -0.457229 0.938059 0.654805 -0.430244 -0.697683 -0.220146 0.346002 -0.388637 -0.149513 0.011248 0.818728 0.042615 -0.594237 -0.646138 0.568898 0.700328 0.290316 0.293722 0.828779\n-0.583585 0.413481 -0.708189 0.168942 0.238435 0.789011 -0.566401 0.177570 -0.244441 0.328214 -0.319583 -0.468558 0.520323 0.072727 1.792047 -0.781348 -0.636644 0.070102 -0.247090 0.110990 0.182112 1.609935 -1.081378 0.922773 -0.605783 0.793724 0.476911 -1.279422 0.904010 -0.519837 1.235220 -0.149456 0.138923 0.686835 -0.733707 -0.335434 -1.865440 -0.476014 -0.140478 -0.148011 0.555169 1.356662 0.850737 -0.484898 0.341224 -0.056477 0.024663 1.141509 0.742001 0.478773\n-0.811262 -1.017245 0.311680 -0.437684 0.338728 1.034527 -0.415528 -0.646984 -0.121626 0.589435 -0.977225 0.099942 -1.296171 0.022671 0.946574 0.204963 0.297055 -0.394868 0.028115 -0.021189 -0.448692 0.421286 0.156809 -0.332004 0.177866 0.074233 0.299713 0.148349 1.104055 -0.172720 0.292706 0.727035 0.847151 0.024006 -0.826570 -1.038778 -0.568059 -0.460914 -1.290872 -0.294531 0.663751 -0.646503 0.499024 -0.804777 -0.402926 -0.292201 0.348031 0.215414 0.043492 0.165281\n-0.156019 0.405009 -0.370058 -1.417499 0.120639 -0.191854 -0.251213 -0.883898 -0.025010 0.150738 1.038723 0.038419 0.036411 -0.289871 0.588898 0.618994 0.087019 -0.275657 -0.105293 -0.536067 -0.181410 0.058034 0.552306 -0.389803 -0.384800 -0.470717 0.800593 -0.166609 0.702104 0.876092 0.353401 -0.314156 0.618290 0.804017 -0.925911 -1.002050 -0.231087 0.590011 -0.636952 -0.474758 0.169423 1.293482 0.609088 -0.956202 -0.013831 0.399147 0.436669 0.116759 -0.501962 1.308268\n-0.008573 -0.731185 -1.108792 -0.358545 0.507277 -0.050167 0.751870 0.217678 -0.646852 -0.947062 -1.187739 0.490993 -1.500471 0.463113 1.370237 0.218072 0.213489 -0.362163 -0.758691 -0.670870 0.218470 1.641174 0.293220 0.254524 0.085781 0.464454 0.196361 -0.693989 -0.384305 -0.171888 0.045602 1.476064 0.478454 0.726961 -0.642484 -0.266562 -0.846778 0.125562 -0.787331 -0.438503 0.954193 -0.859042 -0.180915 -0.944969 -0.447460 0.036127 0.654763 0.439739 -0.038052 0.991638\"\"\".split(\"\\n\")\n\n wvs = load_word_vector_mapping(vocab, vector)\n assert \"UUUNKKK\" in wvs\n assert allclose(wvs[\"UUUNKKK\"], array([0.172414, -0.091063, 0.255125, -0.837163, 0.434872, -0.499848, -0.042904, -0.059642, -0.635087, -0.458795, -0.105671, 0.506513, -0.105105, -0.405678, 0.493365, 0.408807, 0.401635, -0.817805, 0.626340, 0.580636, -0.246996, -0.008515, -0.671140, 0.301865, -0.439651, 0.247694, -0.291402, 0.873009, 0.216212, 0.145576, -0.211101, -0.352360, 0.227651, -0.118416, 0.371816, 0.261296, 0.017548, 0.596692, -0.485722, -0.369530, -0.048807, 0.017960, -0.040483, 0.111193, 0.398039, 0.162765, 0.408946, 0.005343, -0.107523, -0.079821]))\n assert \"the\" in wvs\n assert \"of\" in wvs\n assert \"and\" in wvs\n\ndef window_iterator(seq, n=1, beg=\"\", end=\"\"):\n \"\"\"\n Iterates through seq by returning windows of length 2n+1\n \"\"\"\n for i in range(len(seq)):\n l = max(0, i-n)\n r = min(len(seq), i+n+1)\n ret = seq[l:r]\n if i < n:\n ret = [beg,] * (n-i) + ret\n if i+n+1 > len(seq):\n ret = ret + [end,] * (i+n+1 - len(seq))\n yield ret\n\ndef test_window_iterator():\n assert list(window_iterator(list(\"abcd\"), n=0)) == [[\"a\",], [\"b\",], [\"c\",], [\"d\"]]\n assert list(window_iterator(list(\"abcd\"), n=1)) == [[\"\",\"a\",\"b\"], [\"a\",\"b\",\"c\",], [\"b\",\"c\",\"d\",], [\"c\", \"d\", \"\",]]\n\ndef one_hot(n, y):\n \"\"\"\n Create a one-hot @n-dimensional vector with a 1 in position @i\n \"\"\"\n if isinstance(y, int):\n ret = zeros(n)\n ret[y] = 1.0\n return ret\n elif isinstance(y, list):\n ret = zeros((len(y), n))\n ret[np.arange(len(y)),y] = 1.0\n return ret\n else:\n raise ValueError(\"Expected an int or list got: \" + y)\n\n\ndef to_table(data, row_labels, column_labels, precision=2, digits=4):\n \"\"\"Pretty print tables.\n Assumes @data is a 2D array and uses @row_labels and @column_labels\n to display table.\n \"\"\"\n # Convert data to strings\n data = [[\"%04.2f\"%v for v in row] for row in data]\n cell_width = max(\n max(map(len, row_labels)),\n max(map(len, column_labels)),\n max(max(map(len, row)) for row in data))\n def c(s):\n \"\"\"adjust cell output\"\"\"\n return s + \" \" * (cell_width - len(s))\n ret = \"\"\n ret += \"\\t\".join(map(c, column_labels)) + \"\\n\"\n for l, row in zip(row_labels, data):\n ret += \"\\t\".join(map(c, [l] + row)) + \"\\n\"\n return ret\n\nclass ConfusionMatrix(object):\n \"\"\"\n A confusion matrix stores counts of (true, guessed) labels, used to\n compute several evaluation metrics like accuracy, precision, recall\n and F1.\n \"\"\"\n\n def __init__(self, labels, default_label=None):\n self.labels = labels\n self.default_label = default_label if default_label is not None else len(labels) -1\n self.counts = defaultdict(Counter)\n\n def update(self, gold, guess):\n \"\"\"Update counts\"\"\"\n self.counts[gold][guess] += 1\n\n def as_table(self):\n \"\"\"Print tables\"\"\"\n # Header\n data = [[self.counts[l][l_] for l_,_ in enumerate(self.labels)] for l,_ in enumerate(self.labels)]\n return to_table(data, self.labels, [\"go\\\\gu\"] + self.labels)\n\n def summary(self, quiet=False):\n \"\"\"Summarize counts\"\"\"\n keys = range(len(self.labels))\n data = []\n macro = array([0., 0., 0., 0.])\n micro = array([0., 0., 0., 0.])\n default = array([0., 0., 0., 0.])\n for l in keys:\n tp = self.counts[l][l]\n fp = sum(self.counts[l_][l] for l_ in keys if l_ != l)\n tn = sum(self.counts[l_][l__] for l_ in keys if l_ != l for l__ in keys if l__ != l)\n fn = sum(self.counts[l][l_] for l_ in keys if l_ != l)\n\n acc = (tp + tn)/(tp + tn + fp + fn) if tp > 0 else 0\n prec = (tp)/(tp + fp) if tp > 0 else 0\n rec = (tp)/(tp + fn) if tp > 0 else 0\n f1 = 2 * prec * rec / (prec + rec) if tp > 0 else 0\n\n # update micro/macro averages\n micro += array([tp, fp, tn, fn])\n macro += array([acc, prec, rec, f1])\n if l != self.default_label: # Count count for everything that is not the default label!\n default += array([tp, fp, tn, fn])\n\n data.append([acc, prec, rec, f1])\n\n # micro average\n tp, fp, tn, fn = micro\n acc = (tp + tn)/(tp + tn + fp + fn) if tp > 0 else 0\n prec = (tp)/(tp + fp) if tp > 0 else 0\n rec = (tp)/(tp + fn) if tp > 0 else 0\n f1 = 2 * prec * rec / (prec + rec) if tp > 0 else 0\n data.append([acc, prec, rec, f1])\n # Macro average\n data.append(macro / len(keys))\n\n # default average\n tp, fp, tn, fn = default\n acc = (tp + tn)/(tp + tn + fp + fn) if tp > 0 else 0\n prec = (tp)/(tp + fp) if tp > 0 else 0\n rec = (tp)/(tp + fn) if tp > 0 else 0\n f1 = 2 * prec * rec / (prec + rec) if tp > 0 else 0\n data.append([acc, prec, rec, f1])\n\n # Macro and micro average.\n return to_table(data, self.labels + [\"micro\",\"macro\",\"not-O\"], [\"label\", \"acc\", \"prec\", \"rec\", \"f1\"])\n\ndef get_minibatches(data, minibatch_size, shuffle=True):\n \"\"\"\n Iterates through the provided data one minibatch at at time. You can use this function to\n iterate through data in minibatches as follows:\n\n for inputs_minibatch in get_minibatches(inputs, minibatch_size):\n ...\n\n Or with multiple data sources:\n\n for inputs_minibatch, labels_minibatch in get_minibatches([inputs, labels], minibatch_size):\n ...\n\n Args:\n data: there are two possible values:\n - a list or numpy array\n - a list where each element is either a list or numpy array\n minibatch_size: the maximum number of items in a minibatch\n shuffle: whether to randomize the order of returned data\n Returns:\n minibatches: the return value depends on data:\n - If data is a list/array it yields the next minibatch of data.\n - If data a list of lists/arrays it returns the next minibatch of each element in the\n list. This can be used to iterate through multiple data sources\n (e.g., features and labels) at the same time.\n\n \"\"\"\n list_data = type(data) is list and (type(data[0]) is list or type(data[0]) is np.ndarray)\n data_size = len(data[0]) if list_data else len(data)\n indices = np.arange(data_size)\n if shuffle:\n np.random.shuffle(indices)\n for minibatch_start in np.arange(0, data_size, minibatch_size):\n minibatch_indices = indices[minibatch_start:minibatch_start + minibatch_size]\n yield [minibatch(d, minibatch_indices) for d in data] if list_data \\\n else minibatch(data, minibatch_indices)\n\ndef get_minibatches_with_window(data, batch_size, window_batch):\n list_data = type(data) is list and (type(data[0]) is list or type(data[0]) is np.ndarray)\n data_size = len(data[0]) if list_data else len(data)\n batch_num = int(np.ceil(data_size * 1.0 / batch_size))\n window_size = min([batch_size*window_batch, data_size])\n window_start = np.random.randint(data_size-window_size+1, size=(batch_num,))\n # print(window_start)\n for i in range(batch_num):\n window_index = np.arange(window_start[i], window_start[i]+window_size)\n # print(window_index)\n minibatch_indices = np.random.choice(window_index,size = (batch_size,),replace=False)\n # print(minibatch_indices)\n yield [minibatch(d, minibatch_indices) for d in data] if list_data \\\n else minibatch(data, minibatch_indices)\n\n\ndef minibatch(data, minibatch_idx):\n return data[minibatch_idx] if type(data) is np.ndarray else [data[i] for i in minibatch_idx]\n\ndef minibatches(data, batch_size, shuffle=True, window_batch=None):\n batches = [np.array(col) for col in zip(*data)]\n if window_batch is None:\n return get_minibatches(batches, batch_size, shuffle)\n else:\n return get_minibatches_with_window(batches, batch_size, window_batch)\n\n\ndef print_sentence(output, sentence, labels, predictions):\n\n spacings = [max(len(sentence[i]), len(labels[i]), len(predictions[i])) for i in range(len(sentence))]\n # Compute the word spacing\n output.write(\"x : \")\n for token, spacing in zip(sentence, spacings):\n output.write(token)\n output.write(\" \" * (spacing - len(token) + 1))\n output.write(\"\\n\")\n\n output.write(\"y*: \")\n for token, spacing in zip(labels, spacings):\n output.write(token)\n output.write(\" \" * (spacing - len(token) + 1))\n output.write(\"\\n\")\n\n output.write(\"y': \")\n for token, spacing in zip(predictions, spacings):\n output.write(token)\n output.write(\" \" * (spacing - len(token) + 1))\n output.write(\"\\n\")\n","sub_path":"code/utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":27226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"634172493","text":"#!/usr/bin/env python\n# coding:utf8\n\n\"\"\"\n一个实用的策略,根据历史价格做出判断\n- 如果上一个时间点价格高出五天平均价1%,则全仓买入\n- 如果上一个时间点价格低于五天平均价,则空仓卖出\n\"\"\"\n\nfrom JoinQuant import *\n\n\ndef initialize(context):\n # 000001 平安银行\n g.security = \"000001.XSHE\"\n # 设定沪深300作为基准\n set_benchmark(\"000300.XSHG\")\n\n\ndef handle_data(context, data):\n security = g.security\n close_data = attribute_history(security, 5, '1d', ['close'])\n # 取得过去五天的平均价格\n MA5 = close_data['close'].mean()\n # 取得上一时间点价格\n current_price = close_data['close'][-1]\n # 取得当前的现金\n cash = context.portfolio.cash\n\n if current_price > 1.01 * MA5:\n # 全仓买入\n order_value(security, cash)\n log.info(\"Buying %s\" % (security))\n elif current_price < MA5 and context.portfolio.positions[security].sellable_amount > 0:\n # 如果上一时间点价格低于五天平均价,则空仓卖出\n order_target(security, 0)\n log.info(\"Selling %s\" % (security))\n\n # 画出上一时间点价格\n record(stock_price=current_price)\n","sub_path":"demo_2.py","file_name":"demo_2.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"475361890","text":"\r\n\r\ndef get_divisors(n):\r\n\tdivisors = [1]\r\n\tfor i in range(2, int(n/2) + 1):\r\n\t\tif n % i == 0:\r\n\t\t\tdivisors.append(i)\r\n\t\treturn divisors\r\n\r\ndef is_perfect(n):\r\n\tdivisors = get_divisors(n)\r\n\tsum = 0\r\n\tfor i in divisors:\r\n\t\tsum+= i\r\n\treturn n == sum\r\n\r\nprint (is_perfect(6))","sub_path":"perfectnums.py","file_name":"perfectnums.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"332949190","text":"import time\r\nimport json\r\nfrom urllib.request import urlopen\r\n\r\n#clientId='NCCWW3BJFASFFMU0JSFZVYGXZMI5TUGVRGX0POKDW11HOWXU'\r\n#client_secret='4PVBXZXWMECT1E5JF5CRQP3EHEGHU2HLUB3MUJWZFB4YVKL0'\r\n\r\nclientId= 'YKBJMILK4OFZUI34J3ORRE4NHKD55TSDLQOQNKPATRWHFVT5'\r\nclient_secret = '2SSWLCMKMSVJW2NRD1YPNI1HTXX24OARYE03K51RMY2VDSN2'\r\ncategory_id='4d4b7105d754a06374d81259' #Food\r\n\r\nclass fs_buss:\r\n def __init__(self, name, address,checkin_count,herenow):\r\n self.name = name\r\n self.address = address\r\n self.checkin_count = checkin_count\r\n self.herenow= herenow\r\n self.rank = 0\r\n\r\ndef make_request(venuesearch_url):\r\n \"\"\"\r\n Makes a new HTTP request to the given URL\r\n :param url: The URL to request\r\n :returns: JSON response\r\n \"\"\"\r\n\r\n return json.loads(urlopen(venuesearch_url).read().decode(encoding='UTF-8'))\r\n\r\nSEARCH_URL = 'https://api.foursquare.com/v2/venues/search?ll={},{}&intent=browse&radius={}&limit=50&categoryId={}&client_id={}&client_secret={}&v={}'\r\ndef fs_venue_search(lat, lng, distance):\r\n\r\n fs_vs_url = SEARCH_URL.format(lat, lng, distance,category_id, clientId, client_secret,time.strftime(\"%Y%m%d\"))\r\n venue_list = []\r\n\r\n try:\r\n data = make_request(fs_vs_url)\r\n print(data)\r\n\r\n for item in data['response']['venues']:\r\n venue = item\r\n if hasattr(venue, 'herenow'):\r\n venue_list.append(fs_buss(venue['name'],venue['location']['formattedAddress'],venue['stats']['checkinsCount'],venue['herenow']['count']))\r\n else:\r\n venue_list.append(fs_buss(venue['name'], venue['location']['formattedAddress'], venue['stats']['checkinsCount'],'NA'))\r\n except Exception as e:\r\n print(e)\r\n\r\n return venue_list\r\n\r\ndef rated_list_checkin(lat,lng,distance):\r\n venue_list=fs_venue_search(lat,lng,distance)\r\n #venue_list_sorted =sorted(venue_list, key=lambda fs_buss: fs_buss.checkin_count)\r\n venue_list = sorted(venue_list,key=lambda fs_buss: fs_buss.checkin_count, reverse=True)\r\n if venue_list:\r\n venue_list[0].rank = 1\r\n dupcount = 0\r\n prev = venue_list[0]\r\n for venue in venue_list[1:]:\r\n if venue.checkin_count == prev.checkin_count:\r\n venue.rank = prev.rank\r\n dupcount += 1\r\n else:\r\n venue.rank = prev.rank + dupcount + 1\r\n dupcount = 0\r\n prev = venue\r\n\r\n return venue_list\r\n\r\n","sub_path":"xingling/Archive0.3/foursquare_venue.py","file_name":"foursquare_venue.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"430637644","text":"#!/usr/bin/python\n#imports for use of random.randint\nimport random\n#fucntion to create random nums\ndef numGenerator():\n #declar lis as a list\n lis=list()\n #run it 4 time and append an int into the list\n for x in range(0,4):\n lis.append(random.randint(0,1000))\n #this makes our lis which was a list to a tuple!\n tup1=tuple(lis) \n #return the tuple\n return tup1\n\n#nums equals the tup1 since thats what it returned\nnums=numGenerator()\n#print the nums from numGenerator\nprint(nums)\n#print(type(nums))\n","sub_path":"python/tryits/week2/tryit1.py","file_name":"tryit1.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"16014480","text":"\"\"\"\nTakes an image, returns stuff.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nimport os\nimport os.path as osp\nimport numpy as np\nimport scipy.misc\nimport torch\nimport torchvision\nfrom torch.autograd import Variable\nimport scipy.io as sio\n\nfrom nnutils import mesh_net\nfrom nnutils import geom_utils\nfrom nnutils.nmr import NeuralRenderer\nfrom utils import bird_vis\nimport plotly.graph_objects as go\nimport math\n\n# These options are off by default, but used for some ablations reported.\nflags.DEFINE_boolean('ignore_pred_delta_v', False, 'Use only mean shape for prediction')\nflags.DEFINE_boolean('use_sfm_ms', False, 'Uses sfm mean shape for prediction')\nflags.DEFINE_boolean('use_sfm_camera', False, 'Uses sfm mean camera')\n\n\nclass MeshPredictor(object):\n def __init__(self, opts):\n self.opts = opts\n\n self.symmetric = opts.symmetric\n #img_size是(256,256)\n img_size = (opts.img_size, opts.img_size)\n print('Setting up model..')\n #-----------------目前猜測是在這一行的什後從mean mesh變成learned mesh的\n# print(opts.nz_feat)\n# exit()\n #nz_feat目前不確定是哪冒出來的,還要找源頭\n #nz_feat 為200\n self.model = mesh_net.MeshNet(img_size, opts, nz_feat=opts.nz_feat)\n #-----------------------------------經這一個之後就被改變了得到一個337的verts,但原本的verts至少有600個所以它可能是將某些點更動了,\n # 也可能是它會透過對稱的手法來變成完整的mean shape\n self.load_network(self.model, 'pred', self.opts.num_train_epoch)\n #model 從training()模式轉換成評估模式\n self.model.eval()\n\n self.model = self.model.cuda(device=self.opts.gpu_id)\n\n self.renderer = NeuralRenderer(opts.img_size)\n\n if opts.texture:#--------------------這個只是true而已\n self.tex_renderer = NeuralRenderer(opts.img_size)\n # Only use ambient light for tex renderer\n self.tex_renderer.ambient_light_only()\n#--------------------------------這邊將initial mean shape拿進去訓練得到 訓練過後的learned mean shape\n #----------------是否使用use_sfm_ms(它門預設都沒有,這個mesh非常的簡陋,它必須經過學習才會得到一個mean shape\n if opts.use_sfm_ms:\n anno_sfm_path = osp.join(opts.cub_cache_dir, 'sfm', 'anno_testval.mat')\n anno_sfm = sio.loadmat(\n anno_sfm_path, struct_as_record=False, squeeze_me=True)\n sfm_mean_shape = torch.Tensor(np.transpose(anno_sfm['S'])).cuda(\n device=opts.gpu_id)\n self.sfm_mean_shape = Variable(sfm_mean_shape, requires_grad=False)\n self.sfm_mean_shape = self.sfm_mean_shape.unsqueeze(0).repeat(\n opts.batch_size, 1, 1)\n sfm_face = torch.LongTensor(anno_sfm['conv_tri'] - 1).cuda(\n device=opts.gpu_id)\n self.sfm_face = Variable(sfm_face, requires_grad=False)\n faces = self.sfm_face.view(1, -1, 3)\n#-------------------------------------------\n else:\n # For visualization\n faces = self.model.faces.view(1, -1, 3)\n\n self.faces = faces.repeat(opts.batch_size, 1, 1)\n #--------------------------------------這邊會到vis render init()\n self.vis_rend = bird_vis.VisRenderer(opts.img_size,\n faces.data.cpu().numpy())\n self.vis_rend.set_bgcolor([1., 1., 1.])\n self.resnet_transform = torchvision.transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n def load_network(self, network, network_label, epoch_label):\n save_filename = '{}_net_{}.pth'.format(network_label, epoch_label)\n network_dir = os.path.join(self.opts.checkpoint_dir, self.opts.name)\n save_path = os.path.join(network_dir, save_filename)\n print('loading {}..'.format(save_path))\n network.load_state_dict(torch.load(save_path))\n\n return\n\n def set_input(self, batch):\n opts = self.opts\n\n # original image where texture is sampled from.\n img_tensor = batch['img'].clone().type(torch.FloatTensor)\n\n # input_img is the input to resnet\n input_img_tensor = batch['img'].type(torch.FloatTensor)\n for b in range(input_img_tensor.size(0)):\n input_img_tensor[b] = self.resnet_transform(input_img_tensor[b])\n\n self.input_imgs = Variable(\n input_img_tensor.cuda(device=opts.gpu_id), requires_grad=False)\n self.imgs = Variable(\n img_tensor.cuda(device=opts.gpu_id), requires_grad=False)\n if opts.use_sfm_camera:\n cam_tensor = batch['sfm_pose'].type(torch.FloatTensor)\n self.sfm_cams = Variable(\n cam_tensor.cuda(device=opts.gpu_id), requires_grad=False)\n\n def predict(self, batch):\n \"\"\"\n batch has B x C x H x W numpy\n \"\"\"\n self.set_input(batch)\n self.forward()\n return self.collect_outputs()\n\n def forward(self):\n if self.opts.texture:\n pred_codes, self.textures = self.model.forward(self.input_imgs)#這邊得到的textures就是1 1280 6 6 2\n else:\n pred_codes = self.model.forward(self.input_imgs)\n\n self.delta_v, scale, trans, quat = pred_codes\n\n if self.opts.use_sfm_camera:\n self.cam_pred = self.sfm_cams\n else:\n self.cam_pred = torch.cat([scale, trans, quat], 1)\n\n del_v = self.model.symmetrize(self.delta_v)\n # Deform mean shape:\n self.mean_shape = self.model.get_mean_shape()\n#-------------------------edited by parker\n#----------------------------這確實是mean shape----------------\n f=open(\"bird_mean_mesh.off\",\"w\")\n f.write(\"OFF\\n\")\n line=str(len(self.mean_shape))+\" \"+str(len(self.faces[0]))+\" 0\\n\"\n f.write(line)\n mesh_x = np.empty(len(self.mean_shape))\n mesh_y = np.empty(len(self.mean_shape))\n mesh_z = np.empty(len(self.mean_shape))\n # print(\"bird_vis verts:\", self.mean_shape)\n for i in range(len(self.mean_shape)):\n mesh_x_point=float(self.mean_shape[i][0])\n mesh_y_point=float(self.mean_shape[i][1])\n mesh_z_point=float(self.mean_shape[i][2])\n\n line=str(mesh_x_point)+\" \"+str(mesh_y_point)+\" \"+str(mesh_z_point)+\"\\n\"\n f.write(line)\n for j in range(3):\n if (j == 0):\n mesh_x[i] = self.mean_shape[i][j]\n elif (j == 1):\n mesh_y[i] = self.mean_shape[i][j]\n else:\n mesh_z[i] = self.mean_shape[i][j]\n\n tri_i = np.empty(len(self.faces[0]))\n tri_j = np.empty(len(self.faces[0]))\n tri_k = np.empty(len(self.faces[0]))\n\n for i in range(len(self.faces[0])):\n\n #-------------------------\n face_point1 = int(self.faces[0][i][0])\n face_point2 = int(self.faces[0][i][1])\n face_point3 = int(self.faces[0][i][2])\n#--------------------------------------\n\n line = str(3) + \" \" + str(face_point1) + \" \" + str(face_point2) + \" \" + str(face_point3) + \"\\n\"\n f.write(line)\n for j in range(3):\n if (j == 0):\n tri_i[i] = self.faces[0][i][j]\n elif (j == 1):\n tri_j[i] = self.faces[0][i][j]\n else:\n tri_k[i] = self.faces[0][i][j]\n#--------------我暫時不需要顯示這些東西\n# fig = go.Figure(\n# data=[go.Mesh3d(x=mesh_x, y=mesh_y, z=mesh_z, color='lightgreen', opacity=0.5,i=tri_i, j=tri_j, k=tri_k)])\n# fig.show()\n f.close()\n#---------------------------------------------------------\n# exit()\n if self.opts.use_sfm_ms:\n self.pred_v = self.sfm_mean_shape\n elif self.opts.ignore_pred_delta_v:\n self.pred_v = self.mean_shape + del_v*0\n else:\n self.pred_v = self.mean_shape + del_v\n\n # Compute keypoints.\n if self.opts.use_sfm_ms:\n self.kp_verts = self.pred_v\n else:\n self.vert2kp = torch.nn.functional.softmax(\n self.model.vert2kp, dim=1)\n self.kp_verts = torch.matmul(self.vert2kp, self.pred_v)\n\n # Project keypoints\n self.kp_pred = self.renderer.project_points(self.kp_verts,\n self.cam_pred)\n self.mask_pred = self.renderer.forward(self.pred_v, self.faces,\n self.cam_pred)\n\n # Render texture.\n if self.opts.texture and not self.opts.use_sfm_ms:\n if self.textures.size(-1) == 2:\n # Flow texture!\n self.texture_flow = self.textures\n#-----------------------\n # txt_file = open(\"texture_flow.txt\", \"w\")\n # txt_file.write(repr(self.textures.shape))\n # txt_file.write(repr(self.textures))\n # txt_file.close()\n#-----------------------\n self.textures = geom_utils.sample_textures(self.textures,\n self.imgs)\n#-----------------------edited by parker\n # txt_file=open(\"texture_sample_textures.txt\",\"w\")\n # txt_file.write(repr(self.textures.shape))\n # txt_file.write(repr(self.textures))\n # txt_file.close()\n\n if self.textures.dim() == 5: # B x F x T x T x 3\n tex_size = self.textures.size(2)\n self.textures = self.textures.unsqueeze(4).repeat(1, 1, 1, 1,\n tex_size, 1)#這一行部知道在幹麻\n\n # Render texture:\n self.texture_pred = self.tex_renderer.forward(\n self.pred_v, self.faces, self.cam_pred, textures=self.textures)\n\n # B x 2 x H x W\n uv_flows = self.model.texture_predictor.uvimage_pred\n # B x H x W x 2\n self.uv_flows = uv_flows.permute(0, 2, 3, 1)\n self.uv_images = torch.nn.functional.grid_sample(self.imgs,\n self.uv_flows, align_corners=True)\n #edited_by parker\n # uv_flows=open(\"uv_flows.txt\",\"w\")\n # uv_flows.write(repr(self.uv_flows.shape))\n # uv_flows.write(repr(self.uv_flows))\n # uv_flows.close()\n # uv_images=open(\"uv_images.txt\",\"w\")\n # uv_images.write(repr(self.uv_images[0].shape))\n # uv_images_png=np.reshape(self.uv_images[0],(128,256,3))\n # uv_images.write(repr(uv_images_png))\n # uv_images.close()\n #---------------------\n #----------------------------------show uv image------ parker\n uv_image_array = np.zeros([128, 256, 3])\n\n for i in range(len(self.uv_images[0])):\n for j in range(len(self.uv_images[0][i])):\n for k in range(len(self.uv_images[0][i][j])):\n uv_image_array[j][k][i]=self.uv_images[0][i][j][k]\n import matplotlib.pyplot as plt\n plt.imshow(uv_image_array)\n plt.draw()\n plt.show()\n plt.savefig('uv_image_test.png')\n #----------------------------------\n else:\n self.textures = None\n\n def collect_outputs(self):\n outputs = {\n 'kp_pred': self.kp_pred.data,\n 'verts': self.pred_v.data,\n 'kp_verts': self.kp_verts.data,\n 'cam_pred': self.cam_pred.data,\n 'mask_pred': self.mask_pred.data,\n }\n if self.opts.texture and not self.opts.use_sfm_ms:\n outputs['texture'] = self.textures\n outputs['texture_pred'] = self.texture_pred.data\n outputs['uv_image'] = self.uv_images.data\n outputs['uv_flow'] = self.uv_flows.data\n\n return outputs\n","sub_path":"nnutils/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":12180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"176275515","text":"import string\n\ndef processBook(filename):\n hashmap = {}\n file = open(filename, \"r\")\n for line in file:\n breakWords = line.split()\n for word in breakWords:\n cleanup = word.replace(\"'s\", \"\")\n cleanup = cleanup.translate(cleanup.maketrans(\"\", \"\",\\\n string.punctuation))\n cleanup = cleanup.lower()\n hashmap[cleanup] = hashmap.get(cleanup, 0) + 1\n file.close()\n return hashmap\n\ndef numOccurences(hashmap, word):\n return hashmap.get(word, 0)\n","sub_path":"Chapter16/problem_2.py","file_name":"problem_2.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"472983460","text":"#!/usr/bin/env python3.7\n\n# Copyright 2020, Gurobi Optimization, LLC\n\n# Want to cover three different sets but subject to a common budget of\n# elements allowed to be used. However, the sets have different priorities to\n# be covered; and we tackle this by using multi-objective optimization.\n\nimport gurobipy as gp\nfrom gurobipy import GRB\nimport sys\n\ntry:\n # Sample data\n Groundset = range(20)\n Subsets = range(4)\n Budget = 12\n Set = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0],\n [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0]]\n SetObjPriority = [3, 2, 2, 1]\n SetObjWeight = [1.0, 0.25, 1.25, 1.0]\n\n # Create initial model\n model = gp.Model('multiobj')\n\n # Initialize decision variables for ground set:\n # x[e] == 1 if element e is chosen for the covering.\n Elem = model.addVars(Groundset, vtype=GRB.BINARY, name='El')\n\n # Constraint: limit total number of elements to be picked to be at most\n # Budget\n model.addConstr(Elem.sum() <= Budget, name='Budget')\n\n # Set global sense for ALL objectives\n model.ModelSense = GRB.MAXIMIZE\n\n # Limit how many solutions to collect\n model.setParam(GRB.Param.PoolSolutions, 100)\n\n # Set and configure i-th objective\n for i in Subsets:\n objn = sum(Elem[k]*Set[i][k] for k in range(len(Elem)))\n model.setObjectiveN(objn, i, SetObjPriority[i], SetObjWeight[i],\n 1.0 + i, 0.01, 'Set' + str(i))\n\n # Save problem\n model.write('multiobj.lp')\n\n # Optimize\n model.optimize()\n\n model.setParam(GRB.Param.OutputFlag, 0)\n\n # Status checking\n status = model.Status\n if status in (GRB.INF_OR_UNBD, GRB.INFEASIBLE, GRB.UNBOUNDED):\n print(\"The model cannot be solved because it is infeasible or \"\n \"unbounded\")\n sys.exit(1)\n\n if status != GRB.OPTIMAL:\n print('Optimization was stopped with status ' + str(status))\n sys.exit(1)\n\n # Print best selected set\n print('Selected elements in best solution:')\n selected = [e for e in Groundset if Elem[e].X > 0.9]\n print(\" \".join(\"El{}\".format(e) for e in selected))\n\n # Print number of solutions stored\n nSolutions = model.SolCount\n print('Number of solutions found: ' + str(nSolutions))\n\n # Print objective values of solutions\n if nSolutions > 10:\n nSolutions = 10\n print('Objective values for first ' + str(nSolutions) + ' solutions:')\n for i in Subsets:\n model.setParam(GRB.Param.ObjNumber, i)\n objvals = []\n for e in range(nSolutions):\n model.setParam(GRB.Param.SolutionNumber, e)\n objvals.append(model.ObjNVal)\n\n print('\\tSet{} {:6g} {:6g} {:6g}'.format(i, *objvals))\n\nexcept gp.GurobiError as e:\n print('Error code ' + str(e.errno) + \": \" + str(e))\n\nexcept AttributeError as e:\n print('Encountered an attribute error: ' + str(e))\n","sub_path":"gurobi/examples_from_gurobi/multiobj.py","file_name":"multiobj.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"90818330","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Taken from \"Theatrum Chemicum\" at\n# https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/WindowedRangeQuery\n\nfrom sqlalchemy import and_, func, text\n\n\ndef column_windows(session, column, windowsize):\n \"\"\"\n Return a series of WHERE clauses against a given column that break it into\n windows.\n\n Result is an iterable of tuples, consisting of ((start, end), whereclause),\n where (start, end) are the ids.\n\n Requires a database that supports window functions, i.e. Postgresql,\n SQL Server, Oracle.\n\n Enhance this yourself ! Add a \"where\" argument so that windows of just a\n subset of rows can be computed.\n \"\"\"\n\n def int_for_range(start_id, end_id):\n if end_id:\n return and_(column >= start_id, column < end_id)\n else:\n return column >= start_id\n\n q = session.query(\n column,\n func.row_number().over(order_by=column).label('rownum')\n ).from_self(column)\n\n if windowsize > 1:\n q = q.filter(text(\"rownum %% %d=1\" % windowsize))\n\n intervals = [row[0] for row in q]\n\n while intervals:\n start = intervals.pop(0)\n if intervals:\n end = intervals[0]\n else:\n end = None\n\n yield int_for_range(start, end)\n\n\ndef windowed_query(q, column, windowsize):\n \"\"\"\"\n Break a Query into windows on a given column.\n \"\"\"\n\n for whereclause in column_windows(q.session, column, windowsize):\n for row in q.filter(whereclause).order_by(column):\n yield row\n","sub_path":"warehouse/utils/db/windowed_query.py","file_name":"windowed_query.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"133803962","text":"#!/usr/bin/python3\n\nimport sys\r\nfrom cx_Freeze import setup, Executable\r\n\nbase = None\nif sys.platform == \"win32\":\n base = \"Win32GUI\"\n\nexecutables = [\r\n Executable(\"car_numbers_client.pyw\",base=base)\r\n]\n\nincludeFiles = [\n(\"qt_untranslated.qm\", \"qt_untranslated.qm\"),\n]\n\nbuildOptions = {\n 'build_exe':'dist/car_number_client',\r\n 'compressed':True,\r\n 'includes':[\"sip\"],\n 'optimize':2,\n #'copy_dependent_files':True,\n 'create_shared_zip':True,\n 'include_files':includeFiles,\n 'icon':'ui/icons/transportation_car.png'\n }\r\n \nsetup(\n name = \"calculate\",\n version = \"0.1\",\n description = \"test\",\n options = dict(build_exe = buildOptions),\n executables = executables\n)\n","sub_path":"CarNumbersClient/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"505434975","text":"#!/usr/bin/env python3\n\nimport os\nimport argparse\nimport sys\nfrom mfutil.plugins import develop_plugin, \\\n MFUtilPluginAlreadyInstalled, is_dangerous_plugin, \\\n is_plugins_base_initialized\nfrom mfutil.cli import echo_ok, echo_running, echo_nok, echo_bold\n\nDESCRIPTION = \"develop a plugin from a directory\"\nMFMODULE_LOWERCASE = os.environ.get('MFMODULE_LOWERCASE', 'mfext')\n\n\ndef main():\n arg_parser = argparse.ArgumentParser(description=DESCRIPTION)\n arg_parser.add_argument(\"--plugin-path\", default=\".\",\n help=\"plugin directory path\")\n arg_parser.add_argument(\"name\",\n help=\"plugin name\")\n args = arg_parser.parse_args()\n if not is_plugins_base_initialized():\n echo_bold(\"ERROR: the module is not initialized\")\n echo_bold(\" => start it once before installing your plugin\")\n print()\n print(\"hint: you can use %s.start to do that\" % MFMODULE_LOWERCASE)\n print()\n sys.exit(3)\n echo_running(\"- Devlinking plugin %s...\" % args.name)\n try:\n develop_plugin(args.plugin_path, args.name)\n except MFUtilPluginAlreadyInstalled:\n echo_nok(\"already installed\")\n sys.exit(1)\n echo_ok()\n is_dangerous_plugin(args.name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"mfutil/cli_tools/plugins_develop.py","file_name":"plugins_develop.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"574822491","text":"#!/bin/env python\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.python.data import make_one_shot_iterator\nfrom tensorflow.keras.losses import kld\nfrom tensorflow.keras.optimizers import SGD\nimport numpy as np\nimport pandas as pd\nimport scipy.stats.stats as stats\nimport sklearn\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, auc\nimport pickle\n\n\ndef optimizer():\n return None\n\n\ndef loss():\n return None\n\n\nclass ScoreCard(keras.Model):\n\n def __init__(self, feature_columns=None, pf_bin_size=5):\n super(ScoreCard, self).__init__(name='ScoreCard')\n\n self._target_score = 600\n self._factor = 20/np.log(2)\n self._offset = 600 - 20*np.log(20) / np.log(2)\n self._bins = dict()\n self._pf_bin_size = pf_bin_size\n\n def _pf_bin(self, y, x):\n # population frequency bucket\n bad_num = y.sum()\n good_num = y.count() - y.sum()\n d1 = pd.DataFrame({'x': x,'y': y,'bucket': pd.qcut(x, self._pf_bin_size, duplicates='drop')})\n d2 = d1.groupby('bucket',as_index=True)\n d3 = pd.DataFrame(d2.x.min(),columns=['min_bin']) \n\n d3[\"min\"] = d2.min().x\n d3[\"max\"] = d2.max().x\n d3[\"badcostum\"] = d2.sum().y\n d3[\"goodcostum\"] = d2.count().y - d2.sum().y\n d3[\"total\"] = d2.count().y\n d3[\"bad_rate\"] = d2.sum().y/d2.count().y\n d3[\"woe\"] = np.log(d3[\"badcostum\"]/d3[\"goodcostum\"]*good_num/bad_num)\n iv = ((d3[\"badcostum\"]/bad_num-d3[\"goodcostum\"]/good_num)*d3[\"woe\"])\n d3[\"iv\"] = iv\n woe = list(d3[\"woe\"].round(6))\n cut = list(d3[\"max\"].round(6))\n cut.insert(0, float(\"-inf\"))\n cut[-1] = float(\"inf\")\n return d3, cut, woe, iv\n\n def _to_dataframe(self, dataset):\n x_df = pd.DataFrame()\n y_df = pd.DataFrame()\n for _, minibatch in enumerate(dataset):\n data, label = minibatch\n dx = {}\n dy = {}\n for name, value in data.items():\n dx[name] = value.numpy()[0][0]\n x_df = x_df.append(dx, ignore_index=True)\n dy['label'] = label.numpy()[0]\n y_df = y_df.append(dy, ignore_index=True)\n return x_df, y_df\n\n def _replace_woe(self, x, cut, woe):\n return pd.cut(x, cut, labels=pd.Categorical(woe))\n\n def _woe_encoder(self, x, y):\n x_train_dict = {}\n for col in x.columns:\n dfx, cut, woe, iv = self._pf_bin(y, x[col])\n self._bins[col] = (dfx, cut, woe, iv)\n # replacing by the WOE encode\n x_train_dict[col] = self._replace_woe(x[col], cut, woe)\n return pd.DataFrame.from_dict(x_train_dict)\n\n def sqlflow_train_loop(self, dataset, epochs=1, verbose=0):\n x_df, y_df = self._to_dataframe(dataset)\n x = self._woe_encoder(x_df, y_df['label'])\n x.to_csv(\"/tmp/train_woe.csv\")\n lr = LogisticRegression()\n\n x_train, x_test, y_train, y_test = train_test_split(x, y_df['label'])\n lr.fit(x_train, y_train)\n prob = lr.predict_proba(x_test)[:, 1]\n auc_score = roc_auc_score(y_test, prob)\n print(\"AUC: {}\\n\".format(auc_score))\n\n # print the score card\n print(\"TARGET SCORE: %d\" % self._target_score)\n coe = lr.coef_\n for i, col_name in enumerate(x_df.columns):\n bin_cols = self._bins[col_name][0].index.to_list()\n for j, w in enumerate(self._bins[col_name][2]):\n print(col_name, bin_cols[j],\n round(coe[0][i] * w * self._factor +\n self._offset/self._pf_bin_size, 0))\n","sub_path":"sqlflow_models/score_card.py","file_name":"score_card.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"611613556","text":"# coding: utf-8\nimport argparse\n\nimport asyncio\nimport os\nimport sys\n\nPROJECT_DIR = os.path.dirname(os.path.abspath(__file__))\nPARENT_FOLDER = os.path.dirname(PROJECT_DIR)\nsys.path.append(PARENT_FOLDER)\n\nfrom yeoboseyo.models import Trigger\nfrom yeoboseyo.go import go\n\n\nasync def report():\n triggers = await Trigger.objects.all()\n print(\"{:5} {:30} {:30} {:7} {:7} {:22}\".format(\"ID\", \"Name\", \"Notebook\", \"Mastodon\", \"Status\", \"Triggered\",))\n for trigger in triggers:\n date_triggered = trigger.date_triggered if trigger.date_triggered is not None else '***Not triggered yet**'\n joplin_folder = trigger.joplin_folder if trigger.joplin_folder is not None else '***Not used ***'\n print(\"{:5} {:<30} {:<30} {:>8} {:>7} {}\".format(trigger.id,\n trigger.description,\n joplin_folder,\n trigger.mastodon,\n trigger.status,\n date_triggered\n )\n )\n\n\nasync def switch(trigger_id):\n \"\"\"\n\n :param trigger_id: the id of the trigger to switch on/off\n :return:\n \"\"\"\n trigger = await Trigger.objects.get(id=trigger_id)\n status = not trigger.status\n await trigger.update(status=status)\n print(f\"Successfully switched Trigger '{trigger.description}' to {status}\")\n\n\nif __name__ == '__main__':\n print('여보세요 !', end=\"\")\n parser = argparse.ArgumentParser(prog=\"python run.py\", description='Yeoboseyo')\n parser.add_argument('-a',\n action='store',\n choices=['report', 'go', 'switch'],\n required=True,\n help=\"choose -a report or -a go or -a swtch -trigger_id \")\n parser.add_argument('-trigger_id',\n action=\"store\",\n help=\"trigger id to switch of status\",\n type=int,\n required=False,\n default=0)\n args = parser.parse_args()\n if 'a' not in args:\n parser.print_help()\n elif args.a == 'go':\n loop = asyncio.get_event_loop()\n try:\n print(' RUN and GO')\n loop.run_until_complete(go())\n finally:\n loop.close()\n elif args.a == 'report':\n print(' Report')\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(report())\n finally:\n loop.close()\n elif args.a == 'switch':\n print(' Switch')\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(switch(args.trigger_id))\n finally:\n loop.close()\n","sub_path":"yeoboseyo/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"66375096","text":"from bs4 import BeautifulSoup\nimport requests\n\n# import scripts.file_utils\nfrom scripts import file_utils\n\n\ndef main():\n \"\"\"URLをファイルを読み込みスクレイピングを行い、CSVファイルに出力(title,descriptionを取得)\n :return: なし\n \"\"\"\n urls = file_utils.get_urls_from_file(\"inputs_files\", \"urls.txt\")\n # print(urls)\n outinfo = [[]]\n outinfo.clear()\n\n for url in urls:\n outline = []\n outline.append(url)\n # print(url)\n html = requests.get(url)\n soup = BeautifulSoup(html.text, 'lxml')\n # soup = BeautifulSoup(html.text, \"html.parser\")\n\n titles = soup.find_all('title')\n # print(titles[0].text)\n outline.append(titles[0].text)\n\n for meta_tag in soup.find_all('meta', attrs={'name': 'description'}):\n # print(meta_tag.get('content'))\n outline.append(meta_tag.get('content'))\n\n outinfo.append(outline)\n # print(','.join(outline))\n\n file_utils.put_info_to_csv(outinfo, \"outputs_files\", \"out_csv.txt\",\n [\"url\", \"title\", \"description\"])\n # print(outinfo)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"45697419","text":"import cv2\nimport myCV\nimport net\n\n\nface_net = net.face_detection()\nlandmark_net = net.face_lanmark()\nface_reid_net = net.face_reid()\nbody_net = myCV.Net(\"mo_mobilenet-ssd.xml\", \"mo_mobilenet-ssd.bin\", (300, 300))\n\n\nstream = cv2.VideoCapture(0)\ncounter = cv2.TickMeter()\nfaces_data = {}\n\n\nwhile True:\n counter.stop()\n counter.start()\n\n grab, frame = stream.read()\n if not grab:\n raise Exception('Image not found')\n\n img = frame.copy()\n\n # 15 = person id in mobilessd list\n bodies = myCV.detect(body_net, frame, 0.7, 15)\n for bxmin, bymin, bxmax, bymax in bodies:\n cv2.rectangle(img, (bxmin, bymin), (bxmax, bymax), (255, 255, 0), 2)\n\n bchip = frame[bymin:bymax, bxmin:bxmax]\n\n face = myCV.detect(face_net, bchip, 0.7)\n for fxmin, fymin, fxmax, fymax in face:\n fxmin += bxmin\n fymin += bymin\n fxmax += bxmin\n fymax += bymin\n\n cv2.rectangle(img, (fxmin, fymin),\n (fxmax, fymax), (0, 255, 0), 2)\n\n fchip = frame[fymin:fymax, fxmin:fxmax]\n\n dots = myCV.get_landmarks(landmark_net, fchip, (fxmin, fymin))\n for x, y in dots:\n cv2.circle(img, (x, y), 3, (255, 0, 255), -1)\n\n face_info = myCV.get_descriptor(face_reid_net, fchip)\n\n ID = myCV.object_in_data(face_info, faces_data, 0.5)\n if not ID:\n ID = len(faces_data) + 1\n # Rewriting data!!!\n faces_data[ID] = face_info\n\n cv2.putText(img, 'id{}'.format(ID), (bxmin, bymin - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)\n\n runtime = counter.getTimeSec()\n cv2.putText(img, 'Runtime:{:.0f}s'.format(runtime), (5, img.shape[0] - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)\n\n cv2.imshow('Output', img)\n k = cv2.waitKey(1)\n if k == ord('q'):\n break\n stream.release()\n cv2.destroyAllWindows()\n","sub_path":"person_processing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"208409718","text":"from scipy.spatial import ConvexHull\nimport math\nimport numpy as np\nimport get_leave_curvature\n\n\n\n\ndef get_leave_serration(contours):\n '''\n contours: 叶片边界坐标\n return: 叶片锯齿索引, 最深处索引, 锯齿个数,深度,宽度\n '''\n hull = ConvexHull(contours)\n\n # print('ConvexHull选出的凸角索引: ', hull.vertices)\n # print('ConvexHull选出的凸角个数: ', len(hull.vertices))\n\n # hull 中的index\n ser1_idx = sorted(hull.vertices)\n # print('排序后的凸角索引: ', ser1_idx)\n\n\n # hull 中点的坐标\n ser1 = [contours[i] for i in ser1_idx]\n # print('ConvexHull选出的凸角坐标: ', ser1)\n\n\n # 寻找ser2_idx\n ser2_idx = []\n for i in range(len(ser1_idx)-1):\n if abs(ser1_idx[i] - ser1_idx[i+1]) >=10:\n ser2_idx.append(ser1_idx[i])\n # print('去除靠近的点后剩余的凸角索引: ', ser2_idx)\n # print('去除靠近的点后剩余的凸角个数: ', len(ser2_idx))\n\n # 计算每一个ser2_idx 点之间的斜率\n M = []\n K = []\n for j in range(len(ser2_idx)):\n if j== len(ser2_idx)-1:\n break\n for k in range(ser2_idx[j], ser2_idx[j+1]):\n m = (contours[k+1, 1] - contours[ser2_idx[j], 1])/(contours[k+1, 0] - contours[ser2_idx[j], 0])\n M.append(m)\n K.append(M)\n M = []\n # print('ser2_idx 两点之间斜率的变化: ')\n # print(K)\n # print(len(K))\n\n # 寻找中间斜率最大的index\n I = []\n for k in K:\n b = k.index(max(k))\n I.append(b)\n # print('ser2_idx 两点之间斜率最大的点: ', I)\n\n\n # ser2_idx_max, 选择 ser3_idx\n ser2_idx_max = [a+b+1 for a,b in zip(ser2_idx[:-1], I)]\n # print('斜率最大的点的 index: ', ser2_idx_max)\n\n ser3_idx = ser2_idx_max + ser2_idx\n ser3_idx = set(ser3_idx)\n ser3_idx = sorted(list(ser3_idx))\n # print('添加斜率搜寻后的点 ser3_idx: ', ser3_idx)\n # print(len(ser3_idx))\n\n ser3 = [contours[i] for i in ser3_idx]\n # print('ser3_idx 中点的坐标: ', ser3)\n\n\n\n # depth\n N = []\n D = []\n for j in range(len(ser3_idx)):\n if j== len(ser3_idx)-1:\n break\n\n k = (contours[ser3_idx[j+1], 1] - contours[ser3_idx[j], 1])/(contours[ser3_idx[j+1], 0] - contours[ser3_idx[j], 0])\n\n for p in range(ser3_idx[j], ser3_idx[j+1]):\n f = abs(k*contours[p+1, 0]- contours[p+1, 1]-k*contours[ser3_idx[j], 0] + contours[ser3_idx[j], 1])\n d = f/math.sqrt(k**2 + 1)\n N.append(d)\n D.append(N)\n N = []\n # print('ser3_idx 中两点之间的 depth: ', D)\n # print(len(D))\n\n # 寻找中间深度最大的index\n DI = []\n ser3_deepest = []\n for d in D:\n b = d.index(max(d))\n DI.append(b)\n # print(DI)\n ser3_deepest = [max(d) for d in D]\n\n\n # Depth point\n ser3_deepest_idx = [a+b+1 for a,b in zip(ser3_idx[:-1], DI)]\n # print('最大高度点的ser3_deepest_idx: ', ser3_deepest_idx)\n # print('最大高度点对应的ser3_deepest个数为: ', len(ser3_deepest))\n # print('最大高度点对应的ser3_deepest高度是: ', ser3_deepest)\n\n\n ser4_idx = []\n for i in range(len(ser3_deepest)):\n if ser3_deepest[i] > 1:\n ser4_idx.append(ser3_idx[i])\n ser4_idx.append(ser3_idx[i+1])\n\n ser4_deepest_idx = [ser3_deepest_idx[i] for i in range(len(ser3_deepest)) if ser3_deepest[i] > 1]\n ser4_deepest = [ser3_deepest[i] for i in range(len(ser3_deepest)) if ser3_deepest[i] > 1]\n\n ser4_widthes = []\n for i in range(0, len(ser4_idx), 2):\n width = math.sqrt((contours[ser4_idx[i+1], 1] - contours[ser4_idx[i], 1])**2 +\n (contours[ser4_idx[i+1], 0] - contours[ser4_idx[i], 0])**2)\n ser4_widthes.append(width)\n\n ser4_deepest = [i/118.11 for i in ser4_deepest]\n ser4_widthes = [i/118.11 for i in ser4_widthes]\n\n # print('最大高度点的ser4_deepest_idx: ', ser4_deepest_idx)\n # print('最大高度点对应的ser4_deepest个数为: ', len(ser4_deepest))\n # print('最大高度点对应的ser4_deepest高度是: ', ser4_deepest)\n # print('ser4 的宽度: ', ser4_widthes)\n # print('ser4 的个数: ', len(ser4_idx))\n # print('ser4 的索引: ', ser4_idx)\n\n serration_numbers = len(ser4_deepest)\n serration_depths = ser4_deepest\n serration_widthes = ser4_widthes\n\n\n\n curvatures_mean = []\n curvatures_median = []\n curvatures_std = []\n serrations_curvatures = []\n for i in range(0, len(ser4_idx), 2):\n curvature = get_leave_curvature.curvature_splines(\n contours[ser4_idx[i]:ser4_idx[i+1]+1, 0], contours[ser4_idx[i]:ser4_idx[i+1]+1, 1], error=0.1)\n serrations_curvatures.append(curvature)\n curvature_mean = np.mean(curvature)\n curvature_median = np.median(curvature)\n curvature_std = np.std(curvature)\n curvatures_mean.append(curvature_mean)\n curvatures_median.append(curvature_median)\n curvatures_std.append(curvature_std)\n\n\n total_curvature = get_leave_curvature.curvature_splines(contours[:, 0], contours[:, 1], error=0.1)\n total_curvature_mean = [np.mean(total_curvature)]\n total_curvature_median = [np.median(total_curvature)]\n total_curvature_std = [np.std(total_curvature)]\n\n\n return ser4_idx, ser4_deepest_idx, serration_numbers, serration_depths, serration_widthes, \\\n curvatures_mean, curvatures_median, curvatures_std, total_curvature_mean, \\\n total_curvature_median, total_curvature_std, total_curvature, serrations_curvatures\n\n\n\n\ndef show_leave_serration(ax, contours, ser4_idx, ser4_deepest_idx):\n ax.plot(contours[:, 0], contours[:, 1], linewidth=2)\n ax.plot(contours[ser4_idx, 0], contours[ser4_idx, 1], 'r--', lw=2)\n ax.plot([contours[ser4_idx[-1], 0], contours[ser4_idx[0], 0]],\n [contours[ser4_idx[-1], 1], contours[ser4_idx[0], 1]], 'r--', lw=2)\n for i in ser4_deepest_idx:\n ax.scatter(contours[i, 0], contours[i, 1], c='g', marker='x')\n for idx in ser4_idx:\n ax.scatter(contours[idx, 0], contours[idx, 1])\n\n\n\n\n\n\n\n#\n# def save_to_csv(serration_numbers, serration_depths, serration_widthes, curvatures_mean,\n# curvatures_median, curvatures_std, boundary_curvature_mean,\n# boundary_curvature_median, boundary_curvature_std, name_str):\n# # 将深度宽度等结果保存到文件\n# results_list = list()\n# # 写入参数配置\n# results_list.append(['serration_idx', 'serration_depth', 'serration_width', 'curvatures_mean', 'curvatures_median',\n# 'curvatures_std'])\n#\n# serration_idx = 0\n# for i in range(serration_numbers + 1):\n# if serration_idx >= serration_numbers:\n# break\n# if serration_idx < serration_numbers:\n# serration_depth = serration_depths[serration_idx]\n# serration_width = serration_widthes[serration_idx]\n# curvature_mean = curvatures_mean[serration_idx]\n# curvature_median = curvatures_median[serration_idx]\n# curvature_std = curvatures_std[serration_idx]\n# serration_idx += 1\n# results_list.append(\n# [serration_idx, serration_depth, serration_width, curvature_mean, curvature_median, curvature_std])\n# results_list.append(['boundary_curvature_mean', 'boundary_curvature_median', 'boundary_curvature_std'])\n# results_list.append([ boundary_curvature_mean, boundary_curvature_median, boundary_curvature_std])\n#\n# # 将结果保存到文件\n# results_file = open(name_str, 'w', newline='')\n# csv_writer = csv.writer(results_file, dialect='excel')\n# for row in results_list:\n# csv_writer.writerow(row)\n#\n#\n#\n# def save_curvatures_to_csv(serration_numbers, serrations_curvatures, boundary_curvature, name_str):\n# serrations_names = []\n# for i in range(serration_numbers):\n# serrations_names.append('serration_'+str(i+1)+'_curvature')\n# print('serrations_names: ', len(serrations_names))\n#\n# df = pd.DataFrame({'serration_1_curvature': serrations_curvatures[0]})\n# for i in range(1, len(serrations_names)):\n# print(serrations_curvatures[i])\n# df[serrations_names[i]] = serrations_curvatures[i]\n#\n# df['boundary_curvature'] = boundary_curvature\n#\n# df.to_csv(name_str, index=False)","sub_path":"get_leave_serration.py","file_name":"get_leave_serration.py","file_ext":"py","file_size_in_byte":8389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"433394818","text":"import os\nimport json\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom function.baidu_ai import audio2text, text2audio\n\nfrom function.broswer_search import search_kw\nfrom function.mybroswer_search import mysearch_kw\n\nfrom function.tuling import get_roboot_answer\nfrom function.qingyun import get_myroboot_answer\n\nfrom function.gensim_lsi import get_high_sim\nfrom function.database import read_answer\nfrom function.play_song import play_song, play_function\nfrom config.config import *\nfrom function.sc_capture import capture\nimport time\n# Create your views here.\n\n\ndef home(request):\n return render(request, 'robot_app/index.html')\n\n\ndef upload(request):\n # print(request.POST)\n file_name = os.path.join('robot_app', 'static', 'audio_file', request.POST['name'])\n file = request.FILES['file']\n print(request)\n with open(file_name, 'wb') as f:\n f.write(file.read())\n\n text = audio2text(file_name)\n print('识别结果', text)\n index = get_high_sim(text)\n if index is not None:\n answer = read_answer(index)\n if index == 3:\n os.popen('notepad')\n elif index == 4:\n os.popen(qq_exe)\n # os.popen(r'D:\\日常应用\\QQ\\Bin\\QQScLauncher.exe')\n elif index==5:\n os.popen(kill_qq)\n elif index==6:\n os.popen(music_exe)\n # os.popen(r'D:\\音乐\\CloudMusic\\cloudmusic.exe')\n elif index==7:\n os.popen(kill_music)\n elif index == 8:\n keyword = text[text.rfind('音乐') + 2:]\n print('播放音乐keyword:',keyword)\n song_name = play_song(keyword)\n print('songname:',song_name)\n if song_name:\n print('好的', song_name)\n # return '好的', song_name\n else:\n mysearch_kw(keyword)\n print('好不到歌曲,百度搜索中···')\n # return search_kw('杨宗纬 - 越过山丘'),\n elif 9 <= index <= 13:\n play_function(index)\n elif index==14:\n # 等待一秒调整截图屏幕,转到要截图的界面\n time.sleep(1)\n capture()\n elif index==15:\n keyword = text[text.rfind('搜索') + 2:]\n # print('搜索keyword:',keyword)\n # shurl= r'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd={}'.format(keyword)\n # print('搜索的url:',shurl)\n # shcmd='explorer \"'+shurl+'\"'\n # print('搜索cmd:',shcmd)\n # os.popen(shcmd)\n mysearch_kw(keyword)\n\n else:\n answer = get_myroboot_answer(text)\n\n hecheng_name = os.path.join('robot_app', 'static', 'audio_file', 'hecheng' + request.POST['name'])\n\n if text2audio(answer.replace('
',' '), hecheng_name):\n print('合成成功!')\n res_name = hecheng_name.strip('robot_app//')\n else:\n print('合成失败!')\n res_name = ''\n\n res_str = {\n 'play_tpe': 'talk',\n 'res_name': res_name,\n 'content': answer,\n 'history':text\n }\n\n return HttpResponse(json.dumps(res_str), content_type='application/json')\n","sub_path":"robot_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"450478320","text":"n = int(input())\na = [int(x) for x in input().split()]\n\nv = set()\nfor e in a:\n while e % 2 == 0:\n e = e // 2\n while e % 3 == 0:\n e = e // 3\n v.add(e)\nif len(v) == 1:\n print(\"Yes\")\nelse:\n print(\"No\")\n","sub_path":"codeforces/573A.py","file_name":"573A.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"52001142","text":"import math\n\nimport matplotlib\nfrom matplotlib import pyplot, gridspec\nfrom scipy import stats\nfrom scipy.special import gamma, gammaln\n\nimport ternary\n\n## Functions to plot #\n\ndef beta(alphas):\n \"\"\"Multivariate beta function\"\"\"\n #return math.exp(sum(map(gammaln, alphas)) - gammaln(sum(alphas)))\n return sum(map(gammaln, alphas)) - gammaln(sum(alphas))\n\ndef dirichlet(alphas):\n \"\"\"Computes Dirichlet probability distribution assuming all parameters alphas > 1.\"\"\"\n B = beta(alphas)\n def f(x):\n s = 0.\n for i in range(len(alphas)):\n try:\n t = (alphas[i]-1.) * math.log(x[i])\n s += t\n except ValueError:\n return 0.\n return math.exp(s - B)\n return f\n\ndef shannon_entropy(p):\n \"\"\"Computes the Shannon Entropy at a distribution in the simplex.\"\"\"\n s = 0.\n for i in range(len(p)):\n try:\n s += p[i] * math.log(p[i])\n except ValueError:\n continue\n return -1.*s\n\nif __name__ == '__main__':\n ## Boundary and Gridlines\n pyplot.figure()\n steps = 30\n gs = gridspec.GridSpec(1,2)\n ax = pyplot.subplot(gs[0,0])\n ax = ternary.draw_boundary(steps, color='black', ax=ax)\n ternary.draw_gridlines(steps, ax=ax, color='black')\n ax.set_title(\"Simplex Boundary and Gridlines\")\n\n ## Various lines\n ax = pyplot.subplot(gs[0,1])\n ternary.draw_boundary(steps, linewidth=2., color='black', ax=ax)\n ternary.draw_horizontal_line(ax, steps, 16)\n ternary.draw_left_parallel_line(ax, steps, 10, linewidth=2., color='red', linestyle=\"--\")\n ternary.draw_right_parallel_line(ax, steps, 20, linewidth=3., color='blue')\n p1 = ternary.project_point((12,8,10))\n p2 = ternary.project_point((2, 26, 2))\n ternary.draw_line(ax, p1, p2, linewidth=3., marker='s', color='green', linestyle=\":\")\n ax.set_title(\"Various Lines\")\n\n ## Heatmap roundup\n steps = 60\n for function in [shannon_entropy, dirichlet([4, 8, 13])]:\n pyplot.figure()\n gs = gridspec.GridSpec(2,2)\n ax = pyplot.subplot(gs[0,0])\n ternary.function_heatmap(function, steps=steps, boundary_points=True, ax=ax)\n ternary.draw_boundary(steps+1, ax=ax, color='black')\n ax.set_title(\"Triangular with Boundary\")\n\n ax = pyplot.subplot(gs[0,1])\n ternary.function_heatmap(function, steps=steps, boundary_points=False, ax=ax)\n ternary.draw_boundary(steps+1, ax=ax, color='black')\n ax.set_title(\"Triangular without Boundary\")\n\n ax = pyplot.subplot(gs[1,0])\n ternary.function_heatmap(function, steps=steps, boundary_points=True, ax=ax, style=\"hexagonal\")\n ternary.draw_boundary(steps, ax=ax, color='black')\n ax.set_title(\"Hexagonal with Boundary\")\n\n ax = pyplot.subplot(gs[1,1])\n ternary.function_heatmap(function, steps=steps, boundary_points=False, ax=ax, style=\"hexagonal\")\n ternary.draw_boundary(steps, ax=ax, color='black')\n ax.set_title(\"Hexagonal without Boundary\")\n\n ## Sample trajectory plot\n pyplot.figure()\n ax = ternary.draw_boundary(color='black')\n ax.set_title(\"Plotting of sample trajectory data\")\n points = []\n with open(\"curve.txt\") as handle:\n for line in handle:\n points.append(map(float, line.split(' ')))\n ternary.plot(points, linewidth=2.0, ax=ax)\n\n pyplot.show()\n\n","sub_path":"examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"510237860","text":"from rest_framework import serializers\n\nfrom .models import KeyMap, Keyboard\n\n\nclass KeyMapSerializer(serializers.ModelSerializer):\n class Meta:\n model = KeyMap\n fields = ('cellid', 'key')\n\n\nclass KeyboardSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField(required=False)\n user = serializers.CharField(source='user.username', allow_null=True)\n mappings = KeyMapSerializer(many=True)\n\n class Meta:\n model = Keyboard\n fields = ('id', 'user', 'label', 'is_primary', 'created',\n 'last_modified', 'mappings')\n\n def create(self, validated_data):\n mappings_data = validated_data.pop('mappings')\n keyboard = Keyboard.objects.create(**validated_data)\n mapping_objects = [KeyMap.objects.get_or_create(cellid=mapping['cellid'], key=mapping['key'])[0] for\n mapping in mappings_data]\n keyboard.set_keymaps(mapping_objects)\n return keyboard\n\n def update(self, instance, validated_data):\n mappings_data = validated_data.pop('mappings')\n instance.label = validated_data.get('label', instance.label)\n instance.is_primary = validated_data.get('is_primary', instance.is_primary)\n instance.save()\n\n mapping_objects = [KeyMap.objects.get_or_create(cellid=mapping['cellid'], key=mapping['key'])[0] for\n mapping in mappings_data]\n instance.set_keymaps(mapping_objects)\n return instance","sub_path":"cellcounter/cc_kapi/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"197850910","text":"# reference: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport scipy\nfrom functools import partial\nimport PIL\n\nmodel_fn = './inception5h/tensorflow_inception_graph.pb'\nlayer = 'mixed4d_3x3_bottleneck_pre_relu'\nchannel = 139\nimg_noise = np.random.uniform(size=(224, 224, 3)) + 100.0\nsave_dir = './imgs/weights/'\ndeepdream_img_path = 'imgs/chicago.jpg'\n\n\n###=========================================================\n### Some helpful funcs\n###=========================================================\ndef mkdir(path):\n\tif not os.path.exists(path):\n\t\tos.mkdir(path)\n\ndef show_array(arr, img_name='res', visiable=False):\n\tarr = np.uint8(np.clip(arr, 0, 1)*255)\n\t# plt.figure(figsize=(8, 8))\n\tplt.imsave(save_dir+img_name, arr)\n\tif visiable:\n\t\tplt.imshow(arr)\n\t\tplt.show()\n\ndef norm_array(arr, s=0.1):\n\treturn (arr - arr.mean())/max(arr.std(), 1e-4)*s + 0.5\n\ndef get_tensor(layer, graph):\n\treturn graph.get_tensor_by_name(\"import/%s:0\" % layer)\n\ndef resize_img(img, size):\n\timg = np.copy(img)\n\tfactors = (float(size[0]) / img.shape[0],\n\t float(size[1]) / img.shape[1],\n\t 1)\n\treturn scipy.ndimage.zoom(img, factors, order=1)\n\n###=========================================================\n### Reload the model\n###=========================================================\nmkdir(save_dir)\ngraph = tf.get_default_graph()\n# sess = tf.Session()\nsess = tf.InteractiveSession(graph=graph)\n\n\nwith tf.gfile.FastGFile(model_fn, 'rb') as f:\n\tgraph_def = tf.GraphDef()\n\tgraph_def.ParseFromString(f.read())\n\nt_input = tf.placeholder(dtype=np.float32, name='input')\nimagenet_mean = 117.0\nt_preprocessed = tf.expand_dims(t_input - imagenet_mean, 0)\ntf.import_graph_def(graph_def, input_map={'input': t_preprocessed})\nprint('Model load successfully!')\n\n###=========================================================\n### Check for the loaded model and layer names\n###=========================================================\nlayers = [op.name for op in graph.get_operations() if op.type=='Conv2D' and \n\t'import/' in op.name]\nfeature_nums = [graph.get_tensor_by_name(name+':0').get_shape() for name in layers]\nfor i in range(10):\n\tprint(layers[i], ': ', feature_nums[i])\n\n\nprint('='*100)\nprint('Start for Visualizing')\nprint('='*100)\n###=========================================================\n### Visualize the Weights\n###=========================================================\n\ndef visualize_weight(t_obj, img_in, l_name, iter_n=20, step=1.0):\n\tt_score = tf.reduce_mean(t_obj)\n\tt_grad = tf.gradients(t_score, t_input)[0]\n\timg = img_in.copy()\n\tfor i in range(iter_n):\n\t\tgrad, score = sess.run([t_grad, t_score], feed_dict={t_input: img})\n\t\tgrad /= grad.std() + 1e-8\n\t\timg += grad*step\n\t\tprint('Basic \\t step: %d/%d, score: %.2f' % (i+1, iter_n, score))\n\timg = norm_array(img)\n\timg_name = l_name + '_basic.png'\n\tshow_array(img, img_name)\n\n\n\nt_layer = get_tensor(layer, graph)\n# visualize_weight(t_obj=t_layer[:, :, :, channel], img_in=img_noise, l_name='mixed4d_139')\n\n\n###=========================================================\n### Multiscale Visualize the Weights\n###=========================================================\n\ndef weight_multiscale(t_obj, img_in, l_name, iter_n=10, step=1.0, octave_n=3, octave_scale=1.4):\n\tt_score = tf.reduce_mean(t_obj)\n\tt_grad = tf.gradients(t_score, t_input)[0]\n\n\timg = img_in.copy()\n\tfor octave in range(octave_n):\n\t\tif octave>0:\n\t\t\thw = np.float32(img.shape[:2])*octave_scale\n\t\t\timg = resize_img(img, np.int32(hw))\n\t\tfor i in range(iter_n):\n\t\t\t# g = calc_grad_tiled(img, t_grad)\n\t\t\tg = sess.run(t_grad, {t_input:img})\n\t\t\tg /= g.std()+1e-8\n\t\t\timg += g*step\n\t\t\tprint('Multiscale \\t step: %d/%d, octave: %d/%d' % (i+1, iter_n, octave+1, octave_n))\n# img = norm_array(img)\n\t\timg_name = l_name + '_multi_scale_'+str(octave)+'.png'\n\t\tshow_array(norm_array(img), img_name)\n\n# t_layer = get_tensor(layer, graph)\n# weight_multiscale(t_obj=t_layer[:, :, :, channel], img_in=img_noise, l_name='mixed4d_139')\n\n\n\n###===================================================================================\n### More details about the weights visualize with laplacian pyramid\n###===================================================================================\nk = np.float32([1,4,6,4,1])\nk = np.outer(k, k)\nk5x5 = k[:,:,None,None]/k.sum()*np.eye(3, dtype=np.float32)\n\n\n###Not very import, but for better performance, can be added...\ndef calc_grad_tiled(img, t_grad, tile_size=512):\n\t'''Compute the value of tensor t_grad over the image in a tiled way.\n Random shifts are applied to the image to blur tile boundaries over \n multiple iterations.'''\n\tsz = tile_size\n\th, w = img.shape[:2]\n\tsx, sy = np.random.randint(sz, size=2)\n\timg_shift = np.roll(np.roll(img, sx, 1), sy, 0)\n\tgrad = np.zeros_like(img)\n\tfor y in range(0, max(h-sz//2, sz),sz):\n\t\tfor x in range(0, max(w-sz//2, sz),sz):\n\t\t\tsub = img_shift[y:y+sz,x:x+sz]\n\t\t\tg = sess.run(t_grad, {t_input:sub})\n\t\t\tgrad[y:y+sz,x:x+sz] = g\n\treturn np.roll(np.roll(grad, -sx, 1), -sy, 0)\n\n\n\ndef lap_split(img):\n\t'''Split the image into lo and hi frequency components'''\n\twith tf.name_scope('split'):\n\t\tlo = tf.nn.conv2d(img, k5x5, [1,2,2,1], 'SAME')\n\t\tlo2 = tf.nn.conv2d_transpose(lo, k5x5*4, tf.shape(img), [1,2,2,1])\n\t\thi = img-lo2\n\treturn lo, hi\n\ndef lap_split_n(img, n):\n\t'''Build Laplacian pyramid with n splits'''\n\tlevels = []\n\tfor i in range(n):\n\t\timg, hi = lap_split(img)\n\t\tlevels.append(hi)\n\tlevels.append(img)\n\treturn levels[::-1]\n\ndef lap_merge(levels):\n\t'''Merge Laplacian pyramid'''\n\timg = levels[0]\n\tfor hi in levels[1:]:\n\t\twith tf.name_scope('merge'):\n\t\t\timg = tf.nn.conv2d_transpose(img, k5x5*4, tf.shape(hi), [1,2,2,1]) + hi\n\treturn img\n\ndef normalize_std(img, eps=1e-10):\n '''Normalize image by making its standard deviation = 1.0'''\n with tf.name_scope('normalize'):\n std = tf.sqrt(tf.reduce_mean(tf.square(img)))\n return img/tf.maximum(std, eps)\n\ndef lap_normalize(img, scale_n=4):\n\t'''Perform the Laplacian pyramid normalization.'''\n\timg = tf.expand_dims(img,0)\n\ttlevels = lap_split_n(img, scale_n)\n\ttlevels = list(map(normalize_std, tlevels))\n\tout = lap_merge(tlevels)\n\treturn out[0,:,:,:]\n\n# Showing the lap_normalize graph with TensorBoard\nlap_graph = tf.Graph()\nwith lap_graph.as_default():\n\tlap_in = tf.placeholder(np.float32, name='lap_in')\n\tlap_out = lap_normalize(lap_in)\n\ndef tffunc(*argtypes):\n '''Helper that transforms TF-graph generating function into a regular one.\n '''\n placeholders = list(map(tf.placeholder, argtypes))\n def wrap(f):\n out = f(*placeholders)\n def wrapper(*args, **kw):\n return out.eval(dict(zip(placeholders, args)), session=kw.get('session'))\n return wrapper\n return wrap\n\ndef weight_lapnorm(t_obj, img_in, l_name, visfunc=norm_array, iter_n=10, step=1.0, octave_n=3, octave_scale=1.4, lap_n=4):\n\tt_score = tf.reduce_mean(t_obj) # defining the optimization objective\n\tt_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!\n\t# build the laplacian normalization graph\n\n\tlap_norm_func = tffunc(np.float32)(partial(lap_normalize, scale_n=lap_n))\n\n\n\timg = img_in.copy()\n\tfor octave in range(octave_n):\n\t\tif octave>0:\n\t\t\thw = np.float32(img.shape[:2])*octave_scale\n\t\t\timg = resize_img(img, np.int32(hw))\n\t\tfor i in range(iter_n):\n\t\t\tg = calc_grad_tiled(img, t_grad)\n\t\t\t# g = sess.run(t_grad, {t_input:img})\n\t\t\tg = lap_norm_func(g)\n\t\t\timg += g*step\n\t\t\tprint('Lap \\t iteration: %d/%d, \\t octave: %d/%d' % (i+1, iter_n, octave+1, octave_n))\n\t\t# img = norm_array(img)\n\t\t# show_array(img, 'lap2_weights'+str(octave)+'.png')\n\t\timg_name = l_name+'_lap_weight_'+str(octave)+'.png'\n\t\tshow_array(visfunc(img), img_name)\n\nt_layer = get_tensor(layer, graph)\n# weight_lapnorm(t_obj=t_layer[:, :, :, channel], img_in=img_noise, l_name='mixed4d_139')\n# weight_lapnorm(t_obj=t_layer[:, :, :, 65]+t_layer[:, :, :, 139], img_in=img_noise, l_name='mixed4d_139_65')\n\n\n\n###===================================================================================\n### Deep Dream\n###===================================================================================\ndef deepdream(t_obj, img_in, l_name, iter_n=10, step=1.5, octave_n=4, octave_scale=1.4):\n\tt_score = tf.reduce_mean(t_obj) \n\tt_grad = tf.gradients(t_score, t_input)[0] \n\n\t# split the image into a number of octaves\n\timg = img_in\n\toctaves = []\n\tfor i in range(octave_n-1):\n\t\thw = img.shape[:2]\n\t\tlo = resize_img(img, np.int32(np.float32(hw)/octave_scale))\n\t\thi = img-resize_img(lo, hw)\n\t\timg = lo\n\t\toctaves.append(hi)\n\n\t# generate details octave by octave\n\tfor octave in range(octave_n):\n\t\tif octave>0:\n\t\t\thi = octaves[-octave]\n\t\t\timg = resize_img(img, hi.shape[:2])+hi\n\t\tfor i in range(iter_n):\n\t\t\tg = calc_grad_tiled(img, t_grad)\n\t\t\timg += g*(step / (np.abs(g).mean()+1e-7))\n\t\t\tprint('Deep Dream \\t iteration: %d/%d, \\t octave: %d/%d' % (i+1, iter_n, octave+1, octave_n))\n\t\timg_name = l_name + '_DeepDream_'+str(octave)+'.png'\n\t\t# img_save = norm_array(img/255.0) ### No Need !!!!!!!!!!!!!\n\t\tshow_array(img/255.0, img_name)\n\nimg0 = PIL.Image.open(deepdream_img_path)\nimg0 = np.float32(img0)\n\n\nt_layer = get_tensor(layer, graph)\ndeepdream(t_layer[:, :, :, channel], img0, l_name='mixed4d_139')\n# t_layer = get_tensor('mixed4c', graph)\n# deepdream(t_layer, img0, l_name='mixed4c_all')\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tensorflow/neural-style-transfer/tf_weights_visualize_and_deepdream.py","file_name":"tf_weights_visualize_and_deepdream.py","file_ext":"py","file_size_in_byte":9415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"356420812","text":"from rest_framework import status\nfrom rest_framework.generics import RetrieveAPIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom customprofile.models import Profile\nfrom .serializers import ProfileSerializer\nfrom rest_framework.mixins import DestroyModelMixin, UpdateModelMixin\n\nclass ProfileChangeAPIView(RetrieveAPIView,\n DestroyModelMixin,\n UpdateModelMixin):\n permission_classes = (\n IsAuthenticated,\n )\n serializer_class = ProfileSerializer\n \n\n def get_object(self):\n if not Profile.objects.filter(user__id=self.request.user.pk).exists():\n return Profile.objects.create(user=self.request.user)\n return self.request.user.profile\n\n def put(self, request, *args, **kwargs):\n serializer = ProfileSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)","sub_path":"customprofile/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"542266732","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n\nclass EncoderNet:\n\n def __init__(self):\n self.in_w = tf.Variable(tf.truncated_normal(shape=[784,100],stddev=0.1))\n self.in_b = tf.Variable(tf.zeros([100]))\n\n self.logvar_w = tf.Variable(tf.truncated_normal(shape=[100,128],stddev=0.1))\n self.mean_w = tf.Variable(tf.truncated_normal(shape=[100,128],stddev=0.1))\n\n def forward(self,x):\n y = tf.nn.relu(tf.matmul(x,self.in_w) + self.in_b)\n\n #两个输出 没加激活函数是因为不求概率\n mean = tf.matmul(y,self.mean_w)\n logvar = tf.matmul(y,self.logvar_w)\n return mean,logvar\n\nclass DecoderNet:\n def __init__(self):\n self.in_w = tf.Variable(tf.truncated_normal(shape=[128,100],stddev=0.1))\n self.in_b = tf.Variable(tf.zeros([100]))\n\n self.out_w = tf.Variable(tf.truncated_normal(shape=[100,784],stddev=0.1))\n def forward(self,x):\n y = tf.nn.relu(tf.matmul(x,self.in_w) + self.in_b)\n return tf.matmul(y,self.out_w)\n\nclass Net:\n\n def __init__(self):\n self.x = tf.placeholder(dtype=tf.float32,shape=[None,784])\n\n self.encoderNet = EncoderNet()\n self.decoderNet = DecoderNet()\n\n self.forward()\n self.backward()\n\n def forward(self):\n #编码器返回两个值 均值和log方差 方差不能为负,用log方差\n self.mean,self.logVar = self.encoderNet.forward(self.x)\n I = tf.random_normal([128]) #I表示标准正态分布\n self.var = tf.exp(self.logVar) #把log方差变成方差\n std = tf.sqrt(self.var) #标准差\n _x = std * I + self.mean #解码器输入\n self.output = self.decoderNet.forward(_x)\n #这个过程叫做重整化\n\n #创建一个decode函数专门用来生成\n def decode(self):\n I = tf.random_normal(shape=[1,128]) #传入批次和特征\n return self.decoderNet.forward(I)\n\n def backward(self):\n loss_1 = tf.reduce_mean((self.output - self.x) ** 2 )\n loss_2 = tf.reduce_mean(0.5 * (-self.logVar + self.mean **2 +self.var - 1))\n self.loss = loss_1 + loss_2\n self.opt = tf.train.AdamOptimizer().minimize(self.loss)\n\nif __name__ == '__main__':\n\n net = Net()\n test_output = net.decode() #测试输出\n init = tf.global_variables_initializer()\n\n with tf.Session() as sess:\n sess.run(init)\n\n plt.ion()\n for epoch in range(1000000):\n xs,_ = mnist.train.next_batch(100)\n\n loss,_ = sess.run([net.loss,net.opt],feed_dict={net.x:xs})\n\n if epoch % 100 == 0:\n test_img_data = sess.run(test_output)\n test_img = np.reshape(test_img_data,[28,28])\n plt.imshow(test_img)\n plt.pause(0.1)\n print(\"loss:\",loss)\n\n","sub_path":"NeuralNetworkModel/VAE.py","file_name":"VAE.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"514040473","text":"'''\nScrapeStoresDiscount task function\n\n[Call this function from a celery task function]\n\n[This function consumes the StoresDiscountScraper to perform a [TODO: full] site scrape]\n\n\n\n\n'''\nfrom pymongo import MongoClient\nfrom pymongo import ReturnDocument # allows getting the updated document after an update\nfrom scrapers import StoresDiscountScraper\nimport constants\nimport logging\nfrom datetime import datetime, timezone\nimport time\nimport sys\nimport random\nfrom bson import ObjectId\nfrom collections import defaultdict\n\ndef nested_dict(n, type):\n if n == 1:\n return defaultdict(type)\n else:\n return defaultdict(lambda: nested_dict(n-1, type))\n\n\ndef ScrapeStoresDiscount(task, **kwargs):\n\n def baseLog(msg):\n logging.info(\"Log: {}\".format(msg))\n log.append(msg)\n task.update_state(state='PROGRESS', meta = {'currentAction': msg, 'log': log})\n db.tasks.update_one({'taskId':task.request.id}, {'$set': {'state':'PROGRESS','currentAction':msg,'log':log}})\n\n def actionLog(msg):\n logging.info(\"Action: {}\".format(msg))\n task.update_state(state='PROGRESS', meta = {'currentAction': msg})\n db.tasks.update_one({'taskId':task.request.id}, {'$set': {'state':'PROGRESS','currentAction':msg}})\n\n def _generateProductNameFromUrl(url):\n '''\n Extract last past of URL to generate short name (https://www.stores-discount.com/p/store-enrouleur-tamisant/ becomes store-enrouleur-tamisant\n '''\n if type(url) != str: return False\n if url.endswith(\"/\"): url = url[:-1] # trim trailing slash\n if url.endswith(\"/\"): return False # but make sure we're not left with a a string with only a slash\n iLastSlash = url.rfind(\"/\")\n if iLastSlash == -1: return False\n return url[iLastSlash+1:]\n\n def _returnError(reason):\n resultStatus = {\n 'state': 'FAILURE',\n 'status': 'Task failed',\n 'log': log if log else '',\n 'current': 1,\n 'currentAction': 'Error: ' + reason,\n 'total': 1,\n 'endTime' : datetime.now(timezone.utc),\n }\n result = db.tasks.update_one( { 'taskId': task.request.id },\n {'$set' : resultStatus\n }, False)\n\n return resultStatus\n\n\n def _returnSuccess(reason):\n #result = db.tasks.update_one( { 'taskId': task.request.id },\n # {'$set' : resultStatus\n # }, False)\n #print(result)\n\n #return resultStatus\n\n resultStatus = {\n 'state': 'SUCCESS',\n 'status': 'Task completed!',\n 'log': log,\n 'current': 1,\n 'currentAction': 'Done',\n 'total': 1,\n 'endTime' : datetime.now(timezone.utc),\n }\n\n result = db.tasks.update_one( { 'taskId': task.request.id },\n {'$set' : resultStatus\n }, False)\n\n return resultStatus\n\n\n\n def _roundup100(x):\n return x if x % 100 == 0 else x + 100 - x % 100\n\n try:\n db = constants.dbConnect()\n #mongo = MongoClient(constants.MONGO_AUTH_URL)\n #db = getattr(mongo, constants.MONGO_DBNAME) # using getattr will not raise an exception\n\n log = []\n baseLog(\"Started task to scrape Stores Discount.\")\n\n url = kwargs[\"url\"] if 'url' in kwargs else \"\"\n width = kwargs['width'] if 'width' in kwargs else ''\n height = kwargs['height'] if 'height' in kwargs else ''\n maxGroups = kwargs['maxGroups'] if 'maxGroups' in kwargs else ''\n\n baseLog(\"URL: {}\".format(url))\n baseLog(\"Requested width: [{}], height [{}], maxGroups [{}]\".format(width, height, maxGroups))\n\n\n sdisc = StoresDiscountScraper.StoresDiscountScraper(**kwargs)\n sdisc.setLogging(baseLog, actionLog)\n\n if not sdisc.isUrlSupported(url):\n logging.error(\"URL is not supported by scraper: {}\".format(url))\n return _returnError(\"URL is not supported by scraper\")\n logging.info(\"URL is supported by scraper\")\n\n productName = _generateProductNameFromUrl(url)\n if productName == False: return _returnError(\"Couldn't recognize product name in URL. URL is probably incorrect or not supported.\")\n\n # store new task in database\n db.tasks.update_one( { 'taskId': task.request.id }, { '$set': {\n \"taskName\":\"Stores-Discount.com\",\n \"taskDescription\": productName,\n \"startTime\": datetime.now(timezone.utc),\n \"taskId\": task.request.id,\n \"status\": 'Task started.',\n \"state\": 'STARTED',\n \"log\": log\n }}, True ) # upsert is true\n\n\n baseLog(\"Fetching and analyzing product info and price groups for {}\".format(productName))\n\n productInfo = sdisc.getProductInfo(maxGroups = maxGroups, task = task)\n if not productInfo:\n baseLog(\"Error getting product info and price groups\")\n return _returnError(\"Couldn't get product info and price groups\")\n\n baseLog(\"Done retrieving product info and price groups.\")\n\n # create/update Platform for the webshop of Stores-Discount\n if not('Platforms' in db.list_collection_names()):\n db.create_collection('Platforms') # create collection if necessary otherwise find_one_and_update will fail\n result = db.Platforms.find_one_and_update(\n {'name': constants.STORES_DISCOUNT_SHORT },\n {\n '$set': {\n 'prettyShortName' : \"Stores-Discount.com\",\n 'prettyLongName' : \"Stores-Discount.com Webshop\",\n 'dateLastObserved': datetime.now(timezone.utc)\n },\n '$addToSet': {\n 'datesObserved': datetime.now(timezone.utc)\n }\n\n },\n upsert = True,\n return_document = ReturnDocument.AFTER\n )\n if result is None:\n baseLog(\"Could not update Platform document. Quitting.\")\n return False\n platformId = result[\"_id\"] # remember the platform Id\n\n # create/update Seller for Stores-Discount as seller on the platform Stores-Discount.com\n if not('Sellers' in db.list_collection_names()):\n db.create_collection('Sellers') # create collection if necessary otherwise find_one_and_update will fail\n result = db.Sellers.find_one_and_update(\n {'name': constants.STORES_DISCOUNT_SHORT },\n {\n '$set': {\n 'prettyShortName': \"Stores-Discount\",\n 'prettyLongName': \"Stores-Discount Seller\",\n 'dateLastObserved': datetime.now(timezone.utc)\n },\n '$addToSet': {\n 'datesObserved': datetime.now(timezone.utc)\n }\n },\n upsert = True,\n return_document = ReturnDocument.AFTER\n )\n if result is None:\n baseLog(\"Could not update Seller document. Quitting.\")\n return False\n sellerId = result[\"_id\"]\n\n\n # create/update a ProductGroup for each price group found (e.g. all roller blind colors in price group 2 are in one ProductGroup)\n # and scrape all prices\n priceGroups = [] # empty array of pricegroups\n for priceGroup in productInfo[\"priceGroups\"]:\n baseLog(\"Iterating through price group {}-{}-{}\".format(constants.STORES_DISCOUNT_SHORT, productName, priceGroup[0]))\n baseLog(\"Price group has {} colors\".format(len(priceGroup[1]['colorNames'])))\n\n # create/update a Product for each color\n colors = priceGroup[1]['colorNames']\n colorIds = []\n for color in colors:\n result = db.Products.find_one_and_update(\n {'name' : constants.STORES_DISCOUNT_SHORT + \"-\" + productName + \"-\" + str(color)},\n {\n '$set' : {\n 'description' : \"Stores-Discount \" + productName + \" \" + str(color),\n 'dateLastObserved': datetime.now(timezone.utc)\n },\n '$addToSet' : {\n 'datesObserved' : datetime.now(timezone.utc)\n }\n },\n upsert = True,\n return_document = ReturnDocument.AFTER # return the document after it was updated\n )\n # remember the Product ID of each color\n productId = result[\"_id\"]\n colorIds.append(productId)\n\n #print(colorIds) # colorIds has all the productIds of all the colors found to be in this price group\n\n # scrape the first color in this pricegroup\n minWidth = int(productInfo[\"minWidth\"])\n maxWidth = int(productInfo[\"maxWidth\"])\n minHeight = int(productInfo[\"minHeight\"])\n maxHeight = int(productInfo[\"maxHeight\"])\n baseLog(\"Scraping first color of price group {}. Widths: {}-{}. Heights: {}-{}\".format(priceGroup[0], minWidth, maxWidth, minHeight, maxHeight))\n\n # check if most recent price observation is still valid\n #baseLog(\"Finding most recent price observation matching any of these productIds: {}\".format(colorIds))\n cursor = db.PriceObservations.find({'productIds': {'$in': colorIds}}).limit(1).sort('dateLastObserved', -1)\n changeFound = False\n if cursor.count() > 0:\n # found most recent price observation for this product, now we'll check a number of prices to see if they changed\n for doc in cursor:\n vptab = nested_dict(2, float)\n for vp in doc[\"varPrices\"]: # get varPrices in a two-dimensional dict\n vptab[vp['width']][vp['height']] = vp['price']\n\n # check from price\n w = _roundup100(minWidth)\n h = _roundup100(minHeight)\n pOld = vptab[w][h]\n logging.info(\"scraping color {}, w{}, h{}\".format(colors[0],w,h))\n pNew = sdisc.scrapeProductColor(colors[0],w,h)\n logging.info(\"{}x{}: old price: {}, new price: {}\".format(w,h,pOld,pNew))\n if pNew != pOld: changeFound = True\n\n # check 60x60 price\n pOld = vptab[600][600]\n pNew = sdisc.scrapeProductColor(colors[0],600, 600)\n logging.info(\"{}x{}: old price: {}, new price: {}\".format(600,600, pOld,pNew))\n if pNew != pOld: changeFound = True\n\n # do a number of random spot checks if no change was found yet\n if not changeFound:\n checks = -(-len(vptab) // 4) # will round up to next integer, use 2, or a higher number for testing\n baseLog(\"Will do {} checks\".format(checks))\n for x in range(1,checks+1):\n w = _roundup100(random.randint(minWidth,maxWidth-100))\n h = _roundup100(random.randint(minHeight,maxHeight-100))\n pOld = vptab[w][h]\n pNew = sdisc.scrapeProductColor(colors[0],w,h)\n actionLog(\"check {}: {}x{}: old price: {}, new price: {}\".format(x,w,h,pOld,pNew))\n if pNew != pOld: changeFound = True\n\n # if prices are unchanged, then don't scrape everything but just add a date to the price observation document\n if not changeFound:\n baseLog(\"Prices are unchanged. No need to scrape the whole thing. Updating previous price observation with today's date.\")\n result = db.PriceObservations.find_one_and_update(\n {'_id' : doc[\"_id\"]},\n {\n '$set': {\n 'dateLastObserved': datetime.now(timezone.utc)\n },\n '$addToSet' : {\n 'datesObserved' : datetime.now(timezone.utc)\n }\n },\n upsert = True,\n return_document = ReturnDocument.AFTER # return the document after it was updated\n )\n\n if (cursor.count() == 0) or (changeFound):\n # a change was found, or no previous observation was found, so scrape the whole thing\n baseLog(\"A price change was found, or this product has not previously been observed. Sraping all sizes.\")\n varPrices = []\n for width in range(_roundup100(minWidth), maxWidth+1, 100):\n for height in range(_roundup100(minHeight), maxHeight+1, 100):\n price = sdisc.scrapeProductColor(colors[0], width, height)\n actionLog(\"Found price for width {}, height {} : {}\".format(width,height,price))\n varPrices.append({'width': width, 'height': height, 'price': price})\n\n db.PriceObservations.insert_one({\n 'price': priceGroup[0],\n 'productIds': colorIds,\n 'sellerId': sellerId,\n 'platformId': platformId,\n 'datesObserved': [datetime.now(timezone.utc)],\n 'dateLastObserved': datetime.now(timezone.utc),\n 'varPrices': varPrices\n })\n\n # create/update a ProductGroup document for this price group...\n result = db.ProductGroups.find_one_and_update(\n {'name' : constants.STORES_DISCOUNT_SHORT + \"-\" + productName + \"-\" + str(priceGroup[0])},\n {\n '$set' : {\n 'memberProducts' : colorIds,\n 'minWidth' : productInfo[\"minWidth\"],\n 'maxWidth' : productInfo[\"maxWidth\"],\n 'minHeight' : productInfo[\"minHeight\"],\n 'maxHeight' : productInfo[\"maxHeight\"],\n 'dateLastObserved' : datetime.now(timezone.utc)\n },\n '$addToSet' : {\n 'datesObserved' : datetime.now(timezone.utc)\n }\n },\n upsert = True,\n return_document = ReturnDocument.AFTER # return the document after it was updated\n )\n # ... and remember all price groups document IDs for this product group\n if result is None:\n baseLog(\"ERROR: Could not update ProductGroup document for price group {}-{}-{}\".format(constants.STORES_DISCOUNT_SHORT, productName, str(priceGroup[0])))\n else:\n priceGroups.append(result[\"_id\"])\n\n # baseLog(\"IDs of all price groups: {}\".format(priceGroups))\n\n # Create/update a ProductGroup for the product group (e.g. roller blinds), containing all its price groups\n result = db.ProductGroups.find_one_and_update(\n {'name': constants.STORES_DISCOUNT_SHORT + \"-\" + productName },\n {\n '$set': {\n 'minWidth' : productInfo[\"minWidth\"],\n 'maxWidth' : productInfo[\"maxWidth\"],\n 'minHeight' : productInfo[\"minHeight\"],\n 'maxHeight' : productInfo[\"maxHeight\"],\n 'dateLastObserved': datetime.now(timezone.utc)\n },\n '$addToSet': {\n 'memberProductGroups' : { '$each': priceGroups },\n 'datesObserved': datetime.now(timezone.utc)\n }\n },\n upsert = True,\n return_document = ReturnDocument.AFTER\n )\n if result is None:\n baseLog(\"ERROR: Could not update ProductGroup document for product group {}-{}\".format(constants.STORES_DISCOUNT_SHORT, productName))\n\n topLevelProductGroupId = result[\"_id\"]\n\n # add the ProductGroup to the Platform's top-level product groups\n result = db.Platforms.find_one_and_update(\n {'name': constants.STORES_DISCOUNT_SHORT },\n {\n '$set': {\n 'prettyShortName' : \"Stores-Discount\",\n 'prettyLongName' : \"Stores-Discount.com Webshop\",\n },\n '$addToSet': {\n 'topLevelProductGroups' : topLevelProductGroupId\n }\n },\n upsert = True,\n return_document = ReturnDocument.AFTER\n )\n\n if result is None:\n baseLog(\"ERROR: Could not update Platform document {}\".format(constants.STORES_DISCOUNT_SHORT))\n\n\n baseLog(\"Done!\")\n return _returnSuccess(\"\")\n\n\n except Exception as e:\n logging.error(\"Exception in scrapeStoresDiscount: \"+ str(e))\n logging.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno))\n return None\n","sub_path":"tasks/ScrapeStoresDiscount.py","file_name":"ScrapeStoresDiscount.py","file_ext":"py","file_size_in_byte":17232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"594813843","text":"import glob\nfrom csv import DictReader, DictWriter\nfrom pathlib import Path\n\nimport vcfpy\nfrom Bio import SeqIO\n\nfrom cupcake import cupcake_logger as logger\n\nFIELDS = [\"locus\", \"size\", \"num_snp\", \"num_hap_nopartial\", \"num_hap_withpartial\"]\n\ndirs = [Path(_) for _ in glob.glob(\"by_loci/*size*\")]\n\nwith open(\"summarized.isophase_results.txt\", \"w\") as f:\n writer = DictWriter(f, FIELDS, delimiter=\"\\t\")\n writer.writeheader()\n\n for d in dirs:\n size = 0\n for r in SeqIO.parse(d.joinpath(\"ccs.fasta\").open(), \"fasta\"):\n size += 1\n\n rec = {\"locus\": d, \"size\": size}\n\n if d.joinpath(d, \"phased.nopartial.NO_SNPS_FOUND\").exists():\n rec[\"num_snp\"] = 0\n rec[\"num_hap_nopartial\"] = 0\n rec[\"num_hap_withpartial\"] = 0\n else:\n rec[\"num_snp\"] = len(\n [x for x in vcfpy.Reader(d.joinpath(\"phased.partial.vcf\"))]\n )\n if d.joinpath(\"phased.nopartial.NO_HAPS_FOUND\").exists():\n rec[\"num_hap_nopartial\"] = 0\n rec[\"num_hap_withpartial\"] = 0\n else:\n file1 = d.joinpath(\"phased.nopartial.cleaned.human_readable.txt\")\n file2 = d.joinpath(\"phased.partial.cleaned.human_readable.txt\")\n with open(file1, \"r\") as h1, open(file2, \"r\") as h2:\n h1.readline() # skip header\n h2.readline() # skip header\n rec[\"num_hap_nopartial\"] = len(\n [r for r in DictReader(h1, delimiter=\"\\t\")]\n )\n rec[\"num_hap_withpartial\"] = len(\n [r for r in DictReader(h2, delimiter=\"\\t\")]\n )\n writer.writerow(rec)\n\nlogger.info(f\"Summarized results of by_loci/ to {f.name}.\")\n","sub_path":"src/cupcake/phasing/utils/summarize_byloci_results.py","file_name":"summarize_byloci_results.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"352015314","text":"from typing import List\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n # 颜色标记法的变形,对于当前节点不需要标记,直接存到结果列表中即可\n res, stack = [], [root] if root else []\n while stack:\n i = stack.pop()\n res.append(i.val)\n stack.extend([j for j in [i.right, i.left] if j is not None])\n return res\n\n def preorderTraversal_02(self, root: TreeNode) -> List[int]:\n # 手动实现递归栈\n node, stack, res = root, [], []\n while node or stack:\n if node:\n res.append(node.val)\n stack.append(node)\n node = node.left\n else:\n node = stack.pop().right\n return res\n\n def preorderTraversal_03(self, root: TreeNode) -> List[int]:\n # 递归法\n return [] if not root else [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)","sub_path":"Week02/preorder_traversal.py","file_name":"preorder_traversal.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"619146206","text":"def leap_year(year):\n if not isinstance(year,int):\n raise TypeError(\"Year entered must be an integer!\")\n if year%4==0:\n if year%100==0:\n if year%400==0:\n return True\n else:\n return False\n else:\n return True\n\nyear = input(\"Please choose the year:\")\ntry:\n year = int(year)\nexcept TypeError:\n print(\"Please input an integer!\")\n\nprint(leap_year(year))","sub_path":"leap/leap.py","file_name":"leap.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"365126086","text":"from __future__ import print_function\n\nimport SimpleITK as sitk\nfrom PIL import Image\nimport sys\nimport os\n\n\ndef command_iteration(filter) :\n print(\"{0:3} = {1:10.5f}\".format(\n filter.GetElapsedIterations(),\n filter.GetMetric())\n )\n\n\nfixed_file = '../images/fixedImage.png'\nmoving_file = '../images/movingImage.png'\n\nfixed = sitk.ReadImage(fixed_file)\n\nmoving = sitk.ReadImage(moving_file)\n\nmatcher = sitk.HistogramMatchingImageFilter()\nif fixed.GetPixelID() in (sitk.sitkUInt8, sitk.sitkInt8):\n matcher.SetNumberOfHistogramLevels(128)\nelse:\n matcher.SetNumberOfHistogramLevels(1024)\nmatcher.SetNumberOfMatchPoints(7)\nmatcher.ThresholdAtMeanIntensityOn()\nmoving = matcher.Execute(moving, fixed)\n\n# The fast symmetric forces Demons Registration Filter\n# Note there is a whole family of Demons Registration algorithms included in SimpleITK\ndemons = sitk.FastSymmetricForcesDemonsRegistrationFilter()\ndemons.SetNumberOfIterations(200)\n# Standard deviation for Gaussian smoothing of displacement field\ndemons.SetStandardDeviations(1.0)\n\ndemons.AddCommand(sitk.sitkIterationEvent, lambda: command_iteration(demons))\n\ndisplacementField = demons.Execute(fixed, moving)\n\n\nprint(\"-------\")\nprint(\"Number Of Iterations: {0}\".format(demons.GetElapsedIterations()))\nprint(\" RMS: {0}\".format(demons.GetRMSChange()))\n\noutTx = sitk.DisplacementFieldTransform(displacementField)\n\n# sitk.WriteTransform(outTx, sys.argv[3])\n\nif not \"SITK_NOSHOW\" in os.environ:\n\n resampler = sitk.ResampleImageFilter()\n resampler.SetReferenceImage(fixed)\n resampler.SetInterpolator(sitk.sitkLinear)\n resampler.SetDefaultPixelValue(100)\n resampler.SetTransform(outTx)\n\n out = resampler.Execute(moving)\n simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)\n simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)\n cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)\n\n nda = sitk.GetArrayViewFromImage(cimg)\n my_pil = Image.fromarray(nda)\n my_pil.show()\n\n # sitk.Show(cimg, \"DeformableRegistration1 Composition\")\n\n","sub_path":"Learning_projects/SimpleITK_pruebas/pruebas/Demons_registration2.py","file_name":"Demons_registration2.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"33483887","text":"from .errors import InvalidOption\r\nimport aiohttp\r\n\r\nasync def fetch(option:str):\r\n async with aiohttp.ClientSession() as session:\r\n async with session.post(f\"https://discordemoji.com/api/?request=stats\") as response:\r\n r = await response.json()\r\n\r\n if option.upper() == 'EMOJI':\r\n return r['emoji']\r\n elif option.upper() == 'USERS':\r\n return r['users']\r\n elif option.upper() == 'FAVES' or option.upper() == 'FAVOURITES' or option.upper() == 'FAVORITES':\r\n return r['faves']\r\n elif option.upper() == 'PENDING' or option.upper() == 'PENDINGAPPROVALS':\r\n return r['pending_approvals']\r\n else:\r\n raise InvalidOption(\"You have provided an invalid option. Options: Emoji, Users, Faves, Pending\")\r\n","sub_path":"pydemoji/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"172572292","text":"import numpy as np\nfrom SparseContext import SparseContext\n\ntitanic_projected = open('../input/titanic-5-proj.csv')\n\nattributes = list(titanic_projected.readline().strip().split(','))[1:]\n# objects = set(range(1, titanic_train.shape[0] + 1))\n\ndef parse_ohe(line):\n values = np.array([int(i) for i in line.strip().split(',')])\n return (values[0], set(np.where(values[1:-1] == 1)[0]), values[-1])\n\ntitanic_table = map(parse_ohe, titanic_projected)\n\n# print(titanic_table)\n\ntitanic_train_context = SparseContext(titanic_table, attr_names=attributes)\n\nintents = titanic_train_context.closed_intents_with_metrics()\n\nprint(titanic_train_context.rules(intents))\nprint(titanic_train_context.predict())\n\n","sub_path":"src/lazy_lattice_titanic.py","file_name":"lazy_lattice_titanic.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"279323033","text":"#GUIPRACTICEAGAIN\n\nimport tkinter as tk\nfrom tkinter import *\n\n\nSimulator = tk.Tk()\n\n\nSimulator.title(\"Fury Simulator\")\nSimulator.geometry(\"900x300\")\n\ninstructions = tk.Label(Simulator , text = \"This is intended to be a ghetto simulation.\\n\"\n\"Most buffs are held constant.\")\ninstructions.place(relx = 0.5, rely = .1)\n\n#Create an entry box\nweapon_label = tk.Label(Simulator , text = 'Enter weapon here: ')\nweapon_label.place(relx = .4 , rely = .3)\nweapon_input = tk.Entry(Simulator)\nweapon_input.place(relx = .75 , rely = .3 )\n\n#create listbox\nweapons_list = Listbox(Simulator , width = 50 , height = 20)\nweapons_list.place(relx = .75 , rely = .5)\n\n\nduration_label = tk.Label(Simulator , text = 'Number of iterations:')\nduration_label.place(relx = .4 , rely = .4)\nduration_label1 = Spinbox(Simulator , from_ = 60 , to_= 600)\nduration_label1.place(relx = .75 , rely = .4)\n\nbutton = tk.Button(Simulator , text = \"Enter\" )\nbutton.place(relx = .9 , rely = .3)\n\nSimulator.mainloop()","sub_path":"Weapon/#GUIPRACTICEAGAIN.py","file_name":"#GUIPRACTICEAGAIN.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"176075742","text":"# import wx\nimport wx.html\n#import os, re \n#from string import atoi\nfrom libpy.conf import ModanConf\n#from libpy.model_mdobject import MdObject\n\nLabelSize = (100, 15)\n\n\nclass MdObjectContent(wx.html.HtmlWindow):\n def __init__(self, parent, wid, frame):\n window_style = wx.html.HW_SCROLLBAR_AUTO\n super(MdObjectContent, self).__init__(parent, wid,\n style=window_style)\n self.frame = frame\n self.app = wx.GetApp()\n mdconf = ModanConf()\n self.conf = mdconf.item\n if 'gtk2' in wx.PlatformInfo:\n self.SetStandardFonts()\n\n def SetObjectContent(self, mdobject):\n self.mdobject = mdobject\n #colspan = mdobject\n lmcount = len(mdobject.landmark_list)\n csize = mdobject.get_centroid_size()\n\n rv = \"\"\n rv += \"\"\n\n rv += \"\"\n for lm in mdobject.landmark_list:\n coords = lm.coords[:]\n if len(mdobject.image_list) > 0 and mdobject.image_list[0].ppmm > 0:\n coords = [c / mdobject.image_list[0].ppmm for c in coords]\n rv += \"\"\n rv += \"\"\n #mdobject.bookstein_registration( 1, 2, 3 )\n #mdobject.print_landmarks(\"bookstein\")\n #mdobject.sliding_baseline_registration( 1, 2, 3 )\n #mdobject.print_landmarks(\"SBR\")\n #for lm in mdobject.landmarks:\n # rv+= \"\"\n ## if( lm.zcoord > -99999 ):\n # rv+= \"\"\n # rv+= \"\"\n rv += \"
\"\n rv += \"Object Name
\" + mdobject.objname + \"
Landmarks\"\n rv += \"
\"\n rv += \"Landmark count: \" + str(lmcount)\n if ( csize > 0 ):\n rv += \", Centroid size: \" + str(int(csize * 100) / 100.0)\n rv += \"
\" + \"\".join([str(int(n* 100) / 100.0) for n in coords]) + \"
 
\"+str(lm.lmseq)+\"\"+str(lm.xcoord)+\"\"+str(lm.ycoord)+\"\" + str( lm.zcoord ) + \"
\"\n\n self.SetPage(rv)\n\n def SetBlank(self):\n self.SetPage('')\n","sub_path":"gui/main_content.py","file_name":"main_content.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"77443478","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\n翻转一棵二叉树。\n\n示例:\n\n输入:\n\n 4\n / \\\n 2 7\n / \\ / \\\n1 3 6 9\n输出:\n\n 4\n / \\\n 7 2\n / \\ / \\\n9 6 3 1\n备注:\n这个问题是受到 Max Howell 的 原问题 启发的 :\n\n谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/invert-binary-tree\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\n\nimport doctest\nfrom collections import deque\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n \"\"\"\n >>> s = Solution()\n >>> t1 = TreeNode(4)\n >>> t2 = TreeNode(2)\n >>> t3 = TreeNode(7)\n >>> t4 = TreeNode(1)\n >>> t5 = TreeNode(3)\n >>> t6 = TreeNode(6)\n >>> t7 = TreeNode(9)\n\n >>> t1.left, t1.right = t2, t3\n >>> t2.left, t2.right = t4, t5\n >>> t3.left, t3.right = t6, t7\n\n >>> root = s.invertTree(t1)\n >>> root.val == 4\n True\n >>> root.left.val == 7\n True\n >>> root.right.val == 2\n True\n >>> root.left.left.val == 9\n True\n >>> root.left.right.val == 6\n True\n >>> root.right.left.val == 3\n True\n >>> root.right.right.val == 1\n True\n \"\"\"\n\n def invertTree(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 递归做法\n 具有明显的递归特征\n\n 1.将根节点的左右子树对调\n 2.递归对调左子树和右子树\n \"\"\"\n if not root:\n return None\n\n root.left, root.right = root.right, root.left\n self.invertTree(root.left)\n self.invertTree(root.right)\n\n return root\n\n def invertTree2(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 遍历解法\n \"\"\"\n if not root:\n return root\n\n queue = [root]\n while queue:\n node = queue.pop(0)\n node.left, node.right = node.right, node.left # 取出节点追后交换节点\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return root\n\n def invertTree3(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 遍历解法\n 使用双端队列,加速pop\n \"\"\"\n if not root:\n return root\n\n queue = deque()\n queue.append(root)\n while queue:\n node = queue.popleft()\n node.left, node.right = node.right, node.left\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return root\n\n\nif __name__ == '__main__':\n doctest.testmod()\n","sub_path":"algorithms/leetcode/easy/0226_翻转二叉树.py","file_name":"0226_翻转二叉树.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"151929321","text":"import time\nimport colorsys\nimport json\nimport urllib\nimport RPi.GPIO as GPIO\n\nfrom neopixel import *\n\nLED_COUNT = 30 # Number of LED pixels.\nLED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).\nLED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)\nLED_DMA = 5 # DMA channel to use for generating signal (try 5)\nLED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest\nLED_INVERT = False # True to invert the signal (when using NPN transistor level shift\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(4, GPIO.OUT) ## Setup GPIO Pin 4 to OUT\nGPIO.setup(17, GPIO.OUT) \nGPIO.setup(27, GPIO.OUT) \n# Create NeoPixel object with appropriate configuration.\nstrip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)\n# Intialize the library (must be called once before other functions).\nstrip.begin()\n\ndef AllOFF():\n\tfor i in range(LED_COUNT+1):\n\t\tstrip.setPixelColor(i, 0)\n\tstrip.show()\n\ndef showValue(strip, barLength, startpoint, value, reversed=False):\n\tmaxRGB = 255\n\tcolors = []\n\tfor i in range(barLength):\n\t\tif ((float(i))/float(barLength)) <= (float(value)/100):\n\t\t\ttemp = colorsys.hsv_to_rgb( (float(120) - 1.2*float(value) ) /360, 1, 1)\n\t\t\t# print temp\n\t\t\tcolors.append(Color(int(temp[0]*maxRGB), int(temp[1]*maxRGB), int(temp[2]*maxRGB) ))\n\t\telse:\n\t\t\tcolors.append(Color(0,0,0))\n\n\n\tfor i in range(barLength):\n\t\tprint(colors[i])\n\t\tif(reversed):\n\t\t\tstrip.setPixelColor(startpoint+i, colors[barLength-i-1])\n\t\telse:\n\t\t\tstrip.setPixelColor(startpoint+i, colors[i])\n\n\tstrip.show()\ndef showStrip(stripnum, value):\n\tif (stripnum==1):\n\t\treversed=False\n\telse:\n\t\treversed=False\n\n\tshowValue(strip,8,stripnum*11,value,reversed)\n\ndef pinSet(number, value):\n\tGPIO.output(number,value)\n\ndef blink(number, count=10):\n\tfor i in range(1,count):\n\t\tGPIO.output(number,True)\n\t\ttime.sleep(1)\n\t\tGPIO.output(number,False)\n\t\ttime.sleep(1)\n\t\t\n\n#When you have no more money its alarmed by blinking 5 times at GPIO 4\ndef lightsControl():\n\talarmed=False\n\twhile True:\n\t\turl = 'http://194.42.111.90:8000/api/categories'\n\t\tr = urllib.urlopen(url)\n\t\tdata = json.loads(r.read())\n\t\tshowStrip(0, 100-data[\"Entertainment\"][\"percentage\"])\n\t\tshowStrip(1, 100-data[\"Car\"][\"percentage\"])\n\t\tshowStrip(2, 100-data[\"Healthcare\"][\"percentage\"])\n\t\ttime.sleep(1)\n\t\tif (data[\"Entertainment\"][\"percentage\"]+data[\"Car\"][\"percentage\"]+data[\"Healthcare\"][\"percentage\"])>280 and not alarmed:\n\t\t\tblink(4,6)\n\t\t\talarmed=True\n","sub_path":"abhackathon_rpi/bars.py","file_name":"bars.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"583147703","text":"def open_file(filename):\n try:\n f=open(filename)\n return f\n except :\n print('文件打开失败')\ndef save_file(file_content,file_format,file_number,file_name):\n file_name=file_name+'_'+str(file_number)+file_format\n f=open(file_name,'w')\n f.writelines(file_content)\n f.close()\n\nif __name__=='__main__':\n '''\n num3=set([1,2,5,9,0,7,5])\n print(num3)\n num2={1,7,4}\n print(type(num2))\n print(num2)\n num1={}\n print(type(num1))\n '''\n filename='E:\\\\seleniumstdy\\\\testcode\\\\pythontest\\\\record.txt'\n f=open_file(filename)\n boy=[] \n count=1 \n for each_line in f:\n if each_line[:6]!='======':\n \n try:\n (role,speak)=each_line.split(':',1)\n boy.append(speak)\n except:\n print('failure')\n else:\n save_file(boy,'.txt',count,'boy')\n boy=[]\n count+=1\n save_file(boy,'.txt',count,'boy')\n f.close()","sub_path":"pythontest/02test.py","file_name":"02test.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"87554440","text":"'''\nThis is alert sample for selenium python\nName: Arun Mannepula\n'''\nfrom selenium import webdriver\nfrom selenium.webdriver.common.alert import Alert\nfrom time import sleep\n\ndriver = webdriver.Chrome()\ndriver.get(\"file:///C:/Users/ARUNM/Desktop/Alert1.html\")\ndriver.maximize_window()\n# This is simple alert popup\nelem1 = driver.find_element_by_xpath(\"//*[@id='content']/p[4]/button\")\nelem1.click()\nalt_elem1 = Alert(driver)\nassert \"A simple Alert\" in alt_elem1.text\nalt_elem1.accept()\n\n\n# This alert discmiss ction\nelem2 = driver.find_element_by_xpath(\"//*[@id='content']/p[8]/button\")\nelem2.click()\nalt_elem2=Alert(driver)\nassert \"Confirm pop up with OK and Cancel button\" in alt_elem2.text\nalt_elem2.dismiss()\n\n\nelem3 = driver.find_element_by_xpath(\"//*[@id='content']/p[11]/button\")\nelem3.click()\n\nalt_elem3=Alert(driver)\n# print(alt_elem3.text)\nassert \"Do you like toolsqa?\" in alt_elem3.text\nsleep(4)\nalt_elem3.dismiss()\n\n\ndriver.quit()\n\n# assert \"Google\" in driver.page_source\n# print(\"Assert pass\")\n# driver.close()\n\n","sub_path":"AlertExamples.py","file_name":"AlertExamples.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"25107967","text":"test_files = (\n 'tests/resources/mmcs65',\n 'tests/resources/corsika74100'\n)\n\n\ndef test_fortran_raw():\n from corsikaio.io import read_buffer_size\n\n with open('tests/resources/mmcs65', 'rb') as f:\n assert read_buffer_size(f) is None\n\n with open('tests/resources/corsika74100', 'rb') as f:\n assert read_buffer_size(f) == 22932 # standard CORSIKA buffer size\n\n\ndef test_fortran_raw_file():\n from corsikaio import CorsikaFile\n\n events = [e for e in CorsikaFile('tests/resources/corsika75700')]\n\n assert len(events) == 10\n\n\ndef test_read_block():\n from corsikaio.io import read_buffer_size, read_block\n\n for path in test_files:\n with open(path, 'rb') as f:\n buffer_size = read_buffer_size(f)\n block = read_block(f, buffer_size)\n assert block[:4] == b'RUNH'\n\n\ndef test_versions():\n from corsikaio.io import read_buffer_size, read_block\n from corsikaio.subblocks import get_version\n from corsikaio.constants import RUNH_VERSION_POSITION\n from corsikaio.constants import EVTH_VERSION_POSITION\n\n for path, version in zip(test_files, (6.5, 7.41)):\n\n with open(path, 'rb') as f:\n buffer_size = read_buffer_size(f)\n block = read_block(f, buffer_size)\n\n assert get_version(block, RUNH_VERSION_POSITION) == version\n\n block = read_block(f, buffer_size)\n\n assert get_version(block, EVTH_VERSION_POSITION) == version\n","sub_path":"tests/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"599087345","text":"from collections import defaultdict\n\ndef prime_factorize(N): #素因数分解\n exponent = 0\n while N%2 == 0:\n exponent += 1\n N //= 2\n if exponent: factorization = [[2,exponent]]\n else: factorization = []\n i=1\n while i*i <=N:\n i += 2\n if N%i: continue\n exponent = 0\n while N%i == 0:\n exponent += 1\n N //= i\n factorization.append([i,exponent])\n if N!= 1: factorization.append([N,1])\n assert N != 0, \"zero\"\n return factorization\n\nN = int(input())\n\nif N <= 2:\n print(N)\n exit()\nelse:\n num = defaultdict(int)\n for i in range(2,N+1):\n for n,m in prime_factorize(i):\n num[n] += m\n\n\nans = 1\nmod = int(1e9+7)\nfor i in num.values():\n ans = ((i+1)*ans)%mod\n\nprint(ans) ","sub_path":"Python_codes/p03828/s835960918.py","file_name":"s835960918.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"505472568","text":"import numpy as np\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nimport utils\n\n\ndevice = ('cuda' if torch.cuda.is_available() else 'cpu')\n(corpus_indices, char_to_idx, idx_to_char, vocab_size) = utils.load_data_jay_lyrics()\nnum_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size\nnum_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e2, 1e-2\npred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']\n\n\ndef get_params():\n def _one(shape):\n ts = torch.tensor(np.random.normal(0, 0.01, size=shape), \n device=device,\n dtype=torch.float32)\n return torch.nn.Parameter(ts, requires_grad=True)\n def _three():\n return (_one((num_inputs, num_hiddens)),\n _one((num_hiddens, num_hiddens)),\n torch.nn.Parameter(torch.zeros(num_hiddens, \n device=device, dtype=torch.float32), requires_grad=True))\n \n W_xz, W_hz, b_z = _three() # update gate params\n W_xr, W_hr, b_r = _three() # reset gate params\n W_xh, W_hh, b_h = _three() # hidden state params\n W_hq = _one((num_hiddens, num_outputs))\n b_q = torch.nn.Parameter(torch.zeros(num_outputs, device=device, \n dtype=torch.float32), requires_grad=True)\n return nn.ParameterList([W_xz, W_hz, b_z, W_xr, W_hr, b_r, \n W_xh, W_hh, b_h, W_hq, b_q])\n\n\ndef init_gru_state(batch_size, num_hiddens, device):\n return (torch.zeros((batch_size, num_hiddens), device=device), ) \n\n\ndef gru(inputs, state, params):\n W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q = params\n H, = state\n outputs = []\n for X in inputs:\n Z = torch.sigmoid(torch.matmul(X, W_xz) + torch.matmul(H, W_hz) + b_z)\n R = torch.sigmoid(torch.matmul(X, W_xr) + torch.matmul(H, W_hr) + b_r)\n H_tilda = torch.tanh(torch.matmul(X, W_xh) + R * torch.matmul(H, W_hh) + b_h)\n H = Z * H + (1 - Z) * H_tilda\n Y = torch.matmul(H, W_hq) + b_q\n outputs.append(Y) \n return outputs, (H,)\n\n\ndef train():\n print('will use:', device)\n utils.train_and_predict_rnn(gru, get_params, init_gru_state, num_hiddens, \n vocab_size, device, corpus_indices, idx_to_char, char_to_idx, False,\n num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, \n pred_len, prefixes)\n\n\ndef train_pytorch():\n lr = 1e-2\n num_epochs = 320\n gru_layer = nn.GRU(input_size=vocab_size, hidden_size=num_hiddens)\n model = utils.RNNModel(gru_layer, vocab_size).to(device)\n utils.train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device, \n corpus_indices, idx_to_char, char_to_idx, num_epochs, num_steps, lr, \n clipping_theta, batch_size, pred_period, pred_len, prefixes) \n\n\nif __name__ == '__main__':\n #train()\n train_pytorch()\n\n","sub_path":"ai/pytorch/dive_into_dl/models/language_model_gru.py","file_name":"language_model_gru.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"342284807","text":"import sys\nsys.path.append('../')\n\nfrom numpy import *\nfrom nlab import *\nimport matplotlib.pyplot as plt\n\nNStrip = 2**4\ndt = 0.005\n\nalpha = 5.0\nl = 3\nW0 = -7.0\nI = 1.0\n\nHead = array([Neuron_IF() for _ in range(0,2)])\t\t\t# The Head cells\nStrip = array([Neuron_HH() for _ in range(0,2*NStrip)])\t\t# The Strip cells\nRight = Strip[0:NStrip]\t\nLeft = Strip[NStrip:2*NStrip]\n\nfor i in range(0,2*NStrip):\n\tStrip[i].I = I\ncvar.Neuron_HH_VT = -40\ncvar.Neuron_HH_beta = 1\n\nconnect_one_to_many(Head[0], Right, alpha)\t# Connecting the Right neurons to the first Head cell\nconnect_one_to_many(Head[1], Left, alpha) # Connecting the Left neurons to the second Head cell\n\nM = strip_matrix_OneBump2(NStrip, l, W0) \t# Create connection matrix for the Strip cell network\nconnect_with_matrix2(Strip, Strip, M) \t# Apply the connection matrix to the Stripcell network\n\n\n# INITIAL CONDITIONS\nfor i in range(NStrip/2, NStrip/2+1):\n\tRight[i].Vp = -0.0\n\tLeft[i].Vp = -0.0\n#\tRight[i].sp = 0.0\n#\tLeft[i].sp = 0.0\nHead[0].sp = 1.0\nHead[1].sp = 0.0\n\n\nt= 0\nm = 0\nd = 0\nplt.figure()\nplt.ion()\nplotVarName = \"Vp\"; yaxis = (-100, 70)\n#plotVarName = \"mp\"; yaxis = (-0.1, 1.1)\n#plotVarName = \"sp\"; yaxis = (-0.1, 1.1)\n# MAIN TIMELOOP\nwhile(t < 200):\n\tt= t+dt\n\tstepNetwork(Strip, t, dt) # Perform time-step in Strip cells\n\tupdateNetwork(Strip)\t# Update Neuron.sp = Neuron.s\n\tll = get_neuron_entry(Left, plotVarName)\n\trr = get_neuron_entry(Right, plotVarName)\n\t\n\tif(m%40 == 0):\n\t\tplt.clf()\n\t\tplt.plot(ll)\n\t\tplt.plot(rr)\n\t\tplt.title('t=%f'%t)\n\t\tplt.ylim(yaxis)\n\t\tplt.draw()\n\t\t#plt.savefig('./fig/%d.png'%d)\n\t\td= d+1\n\t\t\n\t# if(m==80):\n\t# \tHead[0].sp = 1.0\n\tif(abs(t-50) < dt):\n\t\tHead[0].sp = 0.0\n\t\tHead[1].sp = 1.0\n\t\n\tm= m+1\n","sub_path":"examples/onebump_ML.py","file_name":"onebump_ML.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"288828719","text":"import psutil, datetime, time, cProfile, re\nfrom ProgramClass import LogisticRegML, \\\n LinearRegML\nfrom time import sleep\n\n\nclass ResourceMonitor:\n def __init__(self, proc_id):\n self.start_monitor = True\n self.process = proc_id\n self.program_thread = psutil.Process(pid=self.process)\n self.cpu_cores = psutil.cpu_count()\n\n def cpuUsage(self):\n time_stamp = time.time()\n print(datetime.datetime.fromtimestamp(time_stamp).strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n cpu_usage = self.program_thread.cpu_times()\n # current_cpu = self.program_thread.cpu_num()\n available_core = len(self.program_thread.cpu_affinity())\n print(f\"\\n# CPU cores: \\n \\t{self.cpu_cores}\\n\")\n # print(f\"\\n Using CPU: \\n \\t{current_cpu}\\n\")\n print(f\"\\nCPU available for Process: \\n \\t{available_core}\\n\")\n print(f\"\\n CPU use: User, System, Interrupt = \\n \\t {cpu_usage}\\n\")\n\n def cpuUtilization(self):\n cpu_utilization = self.program_thread.cpu_percent(interval=0.1)\n cpu_thread = self.program_thread.num_threads()\n context_switch = self.program_thread.num_ctx_switches()\n sleep(0.1)\n\n print(f\"\\n CPU utilization % : \\n \\t {cpu_utilization / self.cpu_cores}\\n\")\n print(f\"\\n CPU thread for Process: \\n \\t {cpu_thread}\\n\")\n print(f\"\\n Context Switching on Process: \\n \\t {context_switch}\\n\")\n\n def memoryUsage(self):\n max_memory = self.program_thread.memory_info()\n mem_map = self.program_thread.memory_maps()\n mem_percent = self.program_thread.memory_percent()\n\n print(f\"\\n Memory Analysis: \\n \\t {max_memory}\\n\")\n print(f\"\\n Memory Map: \\n \\t {mem_map}\\n\")\n print(f\"\\n Memory Percentage(RSS): \\n \\t {mem_percent}\\n\")\n\n def diskMemoryIO(self):\n disk_usage = self.program_thread.io_counters()\n\n print(f\"\\n Disk I/O use: \\n \\t {disk_usage}\\n\")\n\n\n# def main():\n# process_1 = LogisticRegML.LogRegression_P1()\n# #process_2 = LinearRegML.LinRegression()\n# pid_1 = process_1.get_pid()\n# #pid_2 = process_2.get_pid()\n# monitor = ResourceMonitor(pid_1)\n# monitor.cpuUsage()\n# monitor.cpuUtilization()\n# monitor.memoryUsage()\n# monitor.diskMemoryIO()\n# monitor.start_monitor = False\n# print(cProfile.run('re.compile(\"process\")'))\n#\n#\n# if __name__ == '__main__':\n# run_time = time.time()\n# main()\n# print(\"%.2f sec\" % (time.time() - run_time))\n","sub_path":"p1.OLU/ProgramClass/ProcessResource.py","file_name":"ProcessResource.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"309343668","text":"from urlparse import urljoin\n\nfrom event_indexing.scrapers.base_json_scraper import IncidentJsonScraper\nfrom event_indexing.util.time_utils import now_milliseconds\n\nMINIMUM_CUSTOMERS_AFFECTED = 10\n\n\nclass LUPowerOutages(IncidentJsonScraper):\n name = 'LUPowerOutages'\n tz_name = 'US/Eastern'\n method = 'GET'\n\n def get_provider(self, **kwargs):\n return {\n 'id': 'lu_power_outages',\n 'name': 'LaFollette Utilities',\n 'api_host': 'www.outageentry.com',\n 'api_route': '/CustomerFacingAppJQM/ajaxShellOut.php',\n 'url': 'https://www.outageentry.com/CustomerFacingAppJQM/outage.php?clientid=LAFOLLETTE'\n }\n\n def get_params(self, **kwargs):\n now = now_milliseconds()\n\n return {\n 'target': 'device_markers',\n 'action': 'get',\n 'serviceIndex': 1,\n 'url': '10.58.27.9',\n '': '3A80',\n '_': now\n }\n\n def get_url(self, **kwargs):\n '''\n url is different from api_host + api_route, format and use\n '''\n provider = self.get_provider()\n host = 'http://{}'.format(provider['api_host'])\n\n return urljoin(host, provider['api_route'])\n\n def is_valid_incident(self, incident):\n affected = int(incident['consumers_affected'])\n\n return affected >= MINIMUM_CUSTOMERS_AFFECTED\n\n def get_incidents(self, content, **kwargs):\n incidents = content.get('markers', [])\n\n return [self.get_incident(incident) for incident in incidents if self.is_valid_incident(incident)]\n\n def get_incident(self, raw_incident, **kwargs):\n incident = 'Power Outage'\n start_date = raw_incident['start_date']\n longitude = raw_incident['lon']\n latitude = raw_incident['lat']\n consumers_affected = raw_incident['consumers_affected']\n\n created_at = self.get_created_at(start_date)\n\n incident_id = self.get_incident_id([created_at, incident, latitude, longitude])\n\n return {\n 'id': incident_id,\n 'incident': incident,\n 'created_at': created_at,\n 'start_date': start_date,\n 'longitude': longitude,\n 'latitude': latitude,\n 'consumers_affected': consumers_affected\n }\n","sub_path":"event_indexing/scrapers/power_outages/lu_power_outages.py","file_name":"lu_power_outages.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"562903043","text":"# needs to be made into callable functions using extract_brain and spm for segs as death match\n# done on mrs.tissue_fractions.py\nfrom __future__ import division\nfrom pathlib import *\nimport numpy as np\nimport os\nimport nibabel\nimport nibabel.nifti1 as nifti1\nfrom mmimproc.utils.provenance import ProvenanceWrapper\nfrom nipype.interfaces import fsl\nfrom os.path import join\nfrom scipy.ndimage.measurements import center_of_mass as com\nfrom mmimproc.utils.paths import getmmimprocpath\nfrom mmimproc.utils import InDir\nfrom mmimproc.io.spar import load as readspar\nfrom mmimproc.utils.paths import getnetworkdataroot\nfs = getnetworkdataroot(target='jaba')\nprov = ProvenanceWrapper()\nflt = fsl.FLIRT(bins=640, interp='nearestneighbour', cost_func='mutualinfo', output_type='NIFTI_GZ')\napplyxfm = fsl.ApplyXfm(interp='nearestneighbour', output_type='NIFTI_GZ')\nbet = fsl.BET(output_type='NIFTI_GZ')\nfast = fsl.FAST(output_type='NIFTI_GZ')\n\n\nproject = 'nbwr'\nsubject = 'sub-nbwr144'\nsession = 'ses-1'\nside = '_left'\n\ntry:\n os.makedirs(join(fs, project, subject, session, 'mrs'))\nexcept OSError:\n if not os.path.isdir(join(fs, project, subject, session, 'mrs')):\n raise\ntempmrs = InDir(join(fs, project, subject, session, 'mrs'))\n\nsparf = 'NBWR144_WIP_LTPRESS_TE80_GLU_48MEAS_6_2_raw_act.SPAR'\nsparfname = join(fs, project, subject, session, 'source_sparsdat', sparf)\nmatching_fname = 'sub-nbwr144_ses-1'+side+'_match_mrs_ti1100_1.nii'\nmatch_file = join(fs, project, subject, session, 'mrs', matching_fname)\n\n# start function here using working directory\n# def make_voi_mask(spar_file, matching_mpr, f_factor=0.3\n\nparoutfname = join(fs, project, subject, session, 'mrs', subject+'_'+session + side + '_match_mrs_ti1100_1')\nmaskfname = join(fs, project, subject, session, 'mrs', subject +'_'+session + side + '_glu_sv_voi_mask.nii.gz')\nspar = readspar(sparfname)\nmatch_img = nibabel.load(match_file)\nmatch_hdr = match_img.header\nmatch_img_data = match_img.get_data()\naffine = match_img.get_affine()\nmask_img = np.zeros(match_img_data.shape)\nlr_diff = round((spar['lr_size'] / 2.) / match_hdr.get_zooms()[0])\nap_diff = round((spar['ap_size'] / 2.) / match_hdr.get_zooms()[1])\ncc_diff = round((spar['cc_size'] / 2.) / match_hdr.get_zooms()[2])\nstartx = int((match_img_data.shape[0] / 2.0) - lr_diff)\nendx = int((match_img_data.shape[0] / 2.0) + lr_diff)\nstarty = int((match_img_data.shape[1] / 2.0) - ap_diff)\nendy = int((match_img_data.shape[1] / 2.0) + ap_diff)\nstartz = int((match_img_data.shape[2] / 2.0) - cc_diff)\nendz = int((match_img_data.shape[2] / 2.0) + cc_diff)\nmask_img[startx:endx, starty:endy, startz:endz] = 1\n\nnmask_img = nifti1.Nifti1Image(mask_img, affine, match_hdr)\nnmask_hdr = nmask_img.header\nnmask_hdr.set_qform(affine, code=2)\nnibabel.save(nmask_img, maskfname)\nprov.log(maskfname, 'sv mrs voi mask file created for csf fraction', sparfname, script=__file__)\n\n# use extract_brain function in struc\n\nflt.inputs.in_file = join(getmmimprocpath(), 'data', 'atlases', 'MNI152_T1_1mm_bet_zcut.nii.gz')\nflt.inputs.reference = match_file\nflt.inputs.out_matrix_file = join(fs, project, subject, session, 'mrs', subject + side + '_mpr_match_sv.mat')\nflt.inputs.out_file = join(fs, project, subject, session, 'mrs', subject + side + '_match_bet_zcut_MNIroi.nii')\nres = flt.run()\napplyxfm.inputs.in_matrix_file = join(fs, project, subject, session, 'mrs', subject + side + '_mpr_match_sv.mat')\napplyxfm.inputs.in_file = join(getmmimprocpath(), 'data', 'atlases', 'MNI152_T1_1mm-com-mask8k.nii.gz')\napplyxfm.inputs.out_file = join(fs, project, subject, session, 'mrs', subject + side + '_match_bet_com_roi.nii')\napplyxfm.inputs.reference = paroutfname + '.nii'\napplyxfm.inputs.apply_xfm = True\nresult = applyxfm.run()\n\n#chop off neck with MNI zcut\nzcut_data = nibabel.load(join(fs, project, subject, session, 'mrs', subject + side + '_match_bet_zcut_MNIroi.nii')).get_data()\nzcut_data_maskb = zcut_data > 4000\nzcut_data_mask = np.zeros(zcut_data.shape)\nzcut_data_mask[zcut_data_maskb] = 1\nzcut = int(np.round(com(zcut_data_mask))[2])\nmatch_img_data[:,:,0:zcut] = 0\nnzcut_img = nibabel.nifti1.Nifti1Image(match_img_data, affine, match_hdr)\nnzcut_img.set_qform(affine, code=2)\nnibabel.save(nzcut_img, join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_zcut.nii'))\n\n#get com for fsl bet\ncom_data = nibabel.load(join(fs, project, subject, session, 'mrs', subject + side + '_match_bet_com_roi.nii')).get_data()\ncom_data_maskb = com_data > 4000\ncom_data_mask = np.zeros(com_data.shape)\ncom_data_mask[com_data_maskb] = 1\nmatch_com = np.round(com(com_data_mask)).astype(int)\n\n#extract brain before segmenting\nbrain_outfname = join(fs, project, subject, session, 'mrs', subject + side + '_mpr_match_sv_brain.nii')\nbet.inputs.in_file = join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_zcut.nii')\nbet.inputs.center = list(match_com)\nbet.inputs.frac = 0.3\nbet.inputs.mask = True\nbet.inputs.skull = True\nbet.inputs.out_file = brain_outfname\nbetres = bet.run()\nprov.log(brain_outfname, 'bet brain for segmentation', paroutfname + '.nii', script=__file__)\n\n#segmentation using fsl fast - should be superseded by\ntempmrs.__enter__()\nfast.inputs.in_files = join(fs, project, subject, session, 'mrs', subject + side + '_mpr_match_sv_brain.nii')\nfast.inputs.img_type = 1\nfast.inputs.number_classes = 3\nfast.inputs.hyper = 0.1\nfast.inputs.bias_iters = 4\nfast.inputs.bias_lowpass = 20\nfast.inputs.output_biascorrected = True\nfast.inputs.output_biasfield = True\nfast.inputs.segments = True\nfast.inputs.probability_maps = True\nfast.inputs.out_basename = join(fs, project, subject, session, 'mrs', subject + side + '_match_sv')\nfastres = fast.run()\n\nGM_seg_data = nibabel.load(join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_seg_1.nii')).get_data()\nGM_voi = GM_seg_data * mask_img\nGM_num_vox = np.count_nonzero(GM_voi)\nWM_seg_data = nibabel.load(join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_seg_2.nii')).get_data()\nWM_voi = WM_seg_data * mask_img\nWM_num_vox = np.count_nonzero(WM_voi)\nCSF_seg_data = nibabel.load(join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_seg_0.nii')).get_data()\nCSF_voi = CSF_seg_data * mask_img\nCSF_num_vox = np.count_nonzero(CSF_voi)\nmask_num_vox = np.count_nonzero(mask_img)\n\nwith open(join(fs, project, subject, session, 'mrs', subject + side + '_sv_voi_tissue_proportions.txt'), \"w\") as f:\n f.write('CSF: {0}\\nGM: {1}\\nWM: {2}\\n'.format('{:.3%}'.format(CSF_num_vox / mask_num_vox),\n '{:.3%}'.format(GM_num_vox / mask_num_vox),\n '{:.3%}'.format(WM_num_vox / mask_num_vox)))\n\nos.chdir(tempmrs._orig_dir)\nprov.log(join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_seg_0.nii'), 'CSF segmentation', brain_outfname, script=__file__)\nprov.log(join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_seg_1.nii'), 'GM segmentation', brain_outfname, script=__file__)\nprov.log(join(fs, project, subject, session, 'mrs', subject + side + '_match_sv_seg_2.nii'), 'WM segmentation', brain_outfname, script=__file__)\nprov.log(join(fs, project, subject, session, 'mrs', subject + side + '_sv_voi_tissue_proportions.txt'), 'results file containing %tissue values', brain_outfname, script=__file__)\n","sub_path":"mmimproc/mrs/csf_fraction.py","file_name":"csf_fraction.py","file_ext":"py","file_size_in_byte":7348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"545154815","text":"# -*- coding: utf-8 -*-\r\n\r\nimport requests\r\nimport numpy as np\r\nimport math\r\nimport pandas as pd\r\nimport os\r\nimport zipfile\r\nimport datetime\r\nimport time\r\n#import simple_salesforce + sf instance + response with access token (could be func)\r\nimport shutil\r\n\r\ndef get_photo(sf, body_url, name, folder, account_id):\r\n region = get_region(sf, account_id).replace(' ', '_')\r\n if region == None:\r\n region = 'Undefined'\r\n if folder == None:\r\n folder = 'Undefined'\r\n directory = 'photos2/' + folder + '/' + region\r\n fname = directory + '/' + name + '.jpg'\r\n if os.path.exists(fname):\r\n print('{0} file has been already downloaded'.format(name))\r\n return\r\n # ToDo: reference to global object reposponse. Name appropriately or pass as argument\r\n req = None\r\n while req == None:\r\n try:\r\n req = requests.get(response['instance_url']+body_url, headers = {'Authorization': 'Bearer ' + response['access_token']})\r\n except:\r\n print('Connection refused. Waiting for 5 seconds.')\r\n time.sleep(5)\r\n if not os.path.isdir(directory):\r\n os.makedirs(directory)\r\n s = 'Сергиенко Василия _ Героев 93-й бригады'\r\n if s in name:\r\n name_n = name.replace(s, 'Сергиенко Василия_Героев')\r\n f = open(directory + '/' + name_n + '.jpg', 'wb') \r\n else:\r\n f = open(directory + '/' + name + '.jpg', 'wb')\r\n f.write(req.content)\r\n f.close()\r\n\r\ndef get_region(sf, account_id):\r\n records = sf.query(\"SELECT Address_line_2_vod__c FROM Address_vod__c WHERE Account_vod__c = '\" + account_id + \"'\")\r\n return records['records'][0]['Address_line_2_vod__c'].partition(',')[0]\r\n\r\ndef get_parent_name(df, id_value):\r\n try:\r\n item = df.loc[id_value]\r\n except KeyError:\r\n return None\r\n if item['ParentId'] == None:\r\n return item['Name']\r\n else:\r\n return get_parent_name(df, item['ParentId'])\r\n\r\ndef get_title(sf, account_id):\r\n records = sf.query(\"SELECT Name, Account_Identifier_vod__c, ParentId, External_ID_vod__c FROM Account WHERE Id = '\" + account_id + \"'\")\r\n records = records['records'][0]\r\n if records['Name'] == None:\r\n acc_name = ''\r\n else:\r\n acc_name = records['Name'][:50]\r\n if records['Account_Identifier_vod__c'] == None:\r\n acc_address = ''\r\n else:\r\n acc_address = records['Account_Identifier_vod__c']\r\n if records['External_ID_vod__c'] == None:\r\n acc_name = ''\r\n else:\r\n external_id = records['External_ID_vod__c']\r\n \r\n acc_parent = records['ParentId']\r\n acc_parent_title = None\r\n while acc_parent != None:\r\n records = sf.query(\"SELECT Name, Account_Identifier_vod__c, ParentId FROM Account WHERE Id = '\" + acc_parent + \"'\")\r\n records = records['records'][0]\r\n acc_parent = records['ParentId']\r\n if acc_parent_title == None:\r\n acc_parent_title = records['Name']\r\n\r\n print('Got parent name for {0}'.format(acc_name))\r\n return (external_id + '_' + acc_name + '_' + acc_address, acc_parent_title)\r\n\r\n\r\nsf = teva_salesforce.sf_instance()\r\n\r\nresponse = sf[1]\r\n\r\nsf = sf[0]\r\nq = sf.query_all\r\n\r\nperiod_start = datetime.date(2019, 4, 19)\r\nperiod_end = datetime.date(2019, 4, 25)\r\ndays = (period_end - period_start).days + 1\r\n\r\ndate_format = '%Y-%m-%d'\r\n\r\n\r\n\r\nprint('Getting account list...', end='')\r\naccounts = q('SELECT Id, Name, Account_Identifier_vod__c, ParentId, External_ID_vod__c, xR1_Account_Type__c FROM Account WHERE xR1_Account_Type__c IN (\\'Pharmacy\\', \\'Distributor\\', \\'Pharmacy chain\\') AND xR1_Account_Status__c=\\'Active\\'')\r\nprint('done')\r\naccounts = accounts['records']\r\nacc = pd.DataFrame(accounts).set_index('Id')\r\n# Add parent name column, keep corporation name existing\r\nprint('Getting main parent name...', end='')\r\nacc['MainParentName'] = [get_parent_name(acc, x) for x in acc.index.values]\r\nprint('done')\r\nacc.loc[:,['Name','Account_Identifier_vod__c','External_ID_vod__c']].fillna(value='', inplace=True)\r\nacc['ApplicableName'] = acc['External_ID_vod__c'] + '_' + acc['Name'].str[:50] + '_' + acc['Account_Identifier_vod__c']\r\n\r\nprint('{0} days to fetch images.'.format(days))\r\n\r\nfor d in range(days):\r\n start_date = period_start + datetime.timedelta(days=d)\r\n end_date = start_date + datetime.timedelta(days=1)\r\n print('\\nProcessing {0}'.format(start_date.strftime(date_format)))\r\n # Gets all inventory monitoring for chosen date\r\n records = q(\"SELECT Account_vod__c, Call2_vod__c, CreatedDate,Id FROM Inventory_Monitoring_vod__c WHERE CreatedDate >= \" + start_date.strftime(date_format) + \"T00:00:00Z AND CreatedDate < \" + end_date.strftime(date_format) + \"T00:00:00Z\")\r\n records = records['records']\r\n \r\n if len(records) == 0:\r\n print('Nothing to download.')\r\n continue\r\n\r\n im = pd.DataFrame(records).set_index('Id')[['Account_vod__c', 'CreatedDate']].drop_duplicates()\r\n\r\n if im.shape[0] == 0:\r\n print('No inventory monitorings to download in chosen period')\r\n continue\r\n print('{0} IM recond(s) fetched.'.format(im.shape[0]))\r\n \r\n \r\n \r\n im = im.merge(acc, how='left', left_on='Account_vod__c', right_index=True)\r\n imgs = pd.DataFrame()\r\n im_tmp = '\\'' + im.index.values + '\\''\r\n \r\n print('Getting IM Ids...')\r\n for i in range(1, im.shape[0] // 100 + 2):\r\n start = 100*(i-1)\r\n end = 100 * i\r\n if end > im.shape[0]:\r\n end = im.shape[0]\r\n if start == end:\r\n break\r\n records = q('SELECT Id, Body, Name, ParentId FROM Attachment where ContentType=\\'image/jpeg\\' AND ParentId IN (' + ','.join(im_tmp[start:end]) + ')')\r\n records = records['records']\r\n \r\n if len(records) > 0:\r\n imgs = imgs.append(records)\r\n print('Fetched {0} of {1} inventory monitoring attachement(s) data.'.format(end, im.shape[0]))\r\n \r\n \r\n if imgs.shape[0] == 0:\r\n print('No images to download in chosen period')\r\n continue\r\n \r\n imgs = imgs[['Id', 'Name', 'ParentId', 'Body']].set_index('Id').drop_duplicates()\r\n \r\n print('{0} image recond(s) fetched.'.format(imgs.shape[0]))\r\n \r\n \r\n \r\n counter = 0\r\n total = imgs.shape[0]\r\n for i, r in im.iterrows():\r\n for ii, ir in imgs[imgs['ParentId'] == i].iterrows():\r\n counter += 1\r\n if not isinstance(r['ApplicableName'], str):\r\n r['ApplicableName'], r['MainParentName'] = get_title(sf, r['Account_vod__c'])\r\n print('Got non-active pharmancy name.')\r\n get_photo(sf, ir['Body'], (r['ApplicableName'] + '_' + ir['Name'][0:19]).replace(':','-').replace('/', '_'), r['MainParentName'], r['Account_vod__c'])\r\n print('{1} of {2}: Got {0} image'.format(ir['Name'], counter, total))\r\n\r\n print('Zipping...', end='') \r\n zipf = zipfile.ZipFile('inventory_monitoring_{0}.zip'.format(start_date.strftime('%Y%m%d')), 'w', zipfile.ZIP_STORED)\r\n path = 'photos2/'\r\n for root, dirs, files in os.walk(path):\r\n for file in files:\r\n zipf.write(os.path.join(root, file))\r\n zipf.close()\r\n print('done')\r\n \r\n print('Removing photos directory...', end='')\r\n shutil.rmtree(path)\r\n print('done')\r\n \r\n\r\nprint('Done!')\r\n","sub_path":"SalesForce_photo_download.py","file_name":"SalesForce_photo_download.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"37998765","text":"import sys,os\nimport pandas as pd\nfrom pyspark.sql.types import StructField,StructType,StringType,IntegerType\nfrom pyspark.sql.types import StructField,StructType,StringType,IntegerType\nfrom pyspark.sql.types import ArrayType,LongType,BooleanType,MapType\nfrom jinja2 import Template,Environment, FileSystemLoader, select_autoescape\nfrom pyspark.sql.functions import explode,get_json_object,json_tuple,size,col,from_json,to_json,create_map\n\n\ntemplate_path = ''\nfile_list = ''\noutput_report = ''\n\ndef get_json_schema():\n schema = \\\n StructType([\n StructField(\"Flowcell\",StringType(),True),\n StructField(\"RunNumber\",IntegerType(),True),\n StructField(\"RunId\",StringType(),True),\n StructField(\"ReadInfosForLanes\",\n ArrayType(StructType([\n StructField(\"LaneNumber\",IntegerType(),True),\n StructField(\"ReadInfos\",\n ArrayType(StructType([\n StructField(\"Number\",IntegerType(),True),\n StructField(\"NumCycles\",IntegerType(),True),\n StructField(\"IsIndexedRead\",BooleanType(),True)])),\n True)])),\n True),\n StructField(\"ConversionResults\",\n ArrayType(StructType([\n StructField(\"LaneNumber\",IntegerType(),True),\n StructField(\"TotalClustersRaw\",LongType(),True),\n StructField(\"TotalClustersPF\",LongType(),True),\n StructField(\"Yield\",LongType(),True),\n StructField(\"DemuxResults\",\n ArrayType(StructType([\n StructField(\"SampleId\",StringType(),True),\n StructField(\"SampleName\",StringType(),True),\n StructField(\"IndexMetrics\",\n ArrayType(StructType([\n StructField(\"IndexSequence\",StringType(),True),\n StructField(\"MismatchCounts\",\n MapType(StringType(),IntegerType(),True),\n True)\n ])),\n True),\n StructField(\"NumberReads\",IntegerType(),True),\n StructField(\"Yield\",LongType(),True),\n StructField(\"ReadMetrics\",\n ArrayType(StructType([\n StructField(\"ReadNumber\",IntegerType(),True),\n StructField(\"Yield\",LongType(),True),\n StructField(\"YieldQ30\",LongType(),True),\n StructField(\"QualityScoreSum\",LongType(),True),\n StructField(\"TrimmedBases\",IntegerType(),True)\n ])),\n True)\n ])),\n True),\n StructField(\"Undetermined\",\n StructType([\n StructField(\"NumberReads\",IntegerType(),True),\n StructField(\"Yield\",LongType(),True),\n StructField(\"ReadMetrics\",\n ArrayType(StructType([\n StructField(\"ReadNumber\",IntegerType(),True),\n StructField(\"Yield\",LongType(),True),\n StructField(\"YieldQ30\",LongType(),True),\n StructField(\"QualityScoreSum\",LongType(),True),\n StructField(\"TrimmedBases\",IntegerType(),True)\n ])),\n True)\n ]),\n True),\n ])),\n True),\n StructField(\"UnknownBarcodes\",\n ArrayType(MapType(StringType(),StringType(),True)),\n True)\n ])\n return schema\n\ndef generateFormattedReport(template_path,output_report,title,barcode_stats,\n undetermined_barcode_stats):\n try:\n env = \\\n Environment(\\\n loader=FileSystemLoader(\\\n searchpath=os.path.dirname(template_path)),\n autoescape=select_autoescape(['xml']))\n template = \\\n env.get_template(\\\n os.path.basename(template_path))\n template.\\\n stream(\\\n title=title,\n barcode_stats=barcode_stats,\n undetermined_barcode_stats=undetermined_barcode_stats).\\\n dump(output_report)\n except:\n raise\n\ndef get_file_list(file_list):\n try:\n data_list = \\\n pd.read_csv(\\\n file_list,\n header=None,\n names=['file'])\n files = list(data_list['file'].values)\n return files\n except:\n raise\n\ndef get_demultiplexing_stats_from_json(spark,file_list):\n try:\n schema = get_json_schema()\n schema2 = MapType(StringType(),StringType())\n files = get_file_list(file_list=file_list)\n df1 = \\\n spark.\\\n read.\\\n format(\"json\").\\\n option(\"mode\",\"failfast\").\\\n option('inferSchema','false').\\\n option('multiLine','true').\\\n schema(schema).\\\n load(files)\n df1\\\n .withColumn('ReadInfosForLanesExploded',\n explode('ReadInfosForLanes'))\\\n .withColumn('ReadInfosForLanesReadInfosExploded',\n explode('ReadInfosForLanesExploded.ReadInfos'))\\\n .selectExpr(\\\n 'Flowcell',\n 'RunNumber',\n 'RunId',\n 'ReadInfosForLanesExploded.LaneNumber as ReadInfosForLanesLaneNumber',\n 'ReadInfosForLanesReadInfosExploded.Number as ReadInfosNumber',\n 'ReadInfosForLanesReadInfosExploded.NumCycles as ReadInfosNumCycles',\n 'ReadInfosForLanesReadInfosExploded.IsIndexedRead as ReadInfosIsIndexedRead')\\\n .createOrReplaceTempView('ReadsInfosForLanes')\n df1\\\n .withColumn('ConversionResultsExploded',\n explode('ConversionResults'))\\\n .withColumn('ConversionResultsDemuxResultsExploded',\n explode('ConversionResults.DemuxResults'))\\\n .withColumn('ConversionResultsDemuxResultsExplodedRe',\n explode('ConversionResultsDemuxResultsExploded'))\\\n .withColumn('ConversionResultsDemuxResultsIndexMetricsExploded',\n explode('ConversionResultsDemuxResultsExplodedRe.IndexMetrics'))\\\n .withColumn('ReadMetricsExploded',\n explode('ConversionResultsDemuxResultsExplodedRe.ReadMetrics'))\\\n .selectExpr(\\\n 'Flowcell',\n 'RunNumber',\n 'RunId',\n 'ConversionResultsExploded.LaneNumber as LaneNumber',\n 'ConversionResultsExploded.TotalClustersRaw as TotalClustersRaw',\n 'ConversionResultsExploded.TotalClustersPF as TotalClustersPF',\n 'ConversionResultsExploded.Yield as Yield',\n 'ConversionResultsDemuxResultsIndexMetricsExploded.IndexSequence as IndexSequence',\n 'ConversionResultsDemuxResultsIndexMetricsExploded.MismatchCounts[0] as PerfectBarcode',\n 'ConversionResultsDemuxResultsIndexMetricsExploded.MismatchCounts[1] as OneMismatchBarcode',\n 'ConversionResultsDemuxResultsExplodedRe.SampleId as SampleId',\n 'ConversionResultsDemuxResultsExplodedRe.SampleName as SampleName',\n 'ConversionResultsDemuxResultsExplodedRe.NumberReads as PFClusters',\n 'ReadMetricsExploded.ReadNumber as ReadMetricsReadNumber',\n 'ReadMetricsExploded.Yield as ReadMetricsYield',\n 'ReadMetricsExploded.YieldQ30 as ReadMetricsYieldQ30',\n 'ReadMetricsExploded.QualityScoreSum as ReadMetricsQualityScoreSum',\n 'ReadMetricsExploded.TrimmedBases as ReadMetricsTrimmedBases')\\\n .createOrReplaceTempView('ConversionResults')\n df1\\\n .withColumn('ConversionResultsExploded',\n explode('ConversionResults'))\\\n .withColumn('ConversionResultsExplodedUndeterminedReadMetricsExploded',\n explode('ConversionResultsExploded.Undetermined.ReadMetrics'))\\\n .selectExpr(\\\n 'Flowcell',\n 'RunNumber',\n 'RunId',\n 'ConversionResultsExploded.LaneNumber as LaneNumber',\n 'ConversionResultsExploded.TotalClustersPF as TotalClustersPF',\n 'ConversionResultsExploded.Undetermined.NumberReads as UndeterminedNumberReads',\n 'ConversionResultsExploded.Undetermined.Yield as UndeterminedTotalYield',\n 'ConversionResultsExplodedUndeterminedReadMetricsExploded.Yield as UndeterminedReadYield',\n 'ConversionResultsExplodedUndeterminedReadMetricsExploded.YieldQ30 as UndeterminedReadYieldQ30',\n 'ConversionResultsExplodedUndeterminedReadMetricsExploded.QualityScoreSum as UndeterminedReadQualityScoreSum'\n )\\\n .createOrReplaceTempView('ConversionResultsUndetermined')\n barcode_stats = \\\n spark.sql('''\n select \n LaneNumber,\n SampleId,\n first(SampleName) as SampleName,\n first(IndexSequence) as IndexSequence,\n CAST(sum(PFClusters) / 2 as INTEGER) as PFClusters,\n CAST(sum(PFClusters) /sum(TotalClustersPF) * 100 as DECIMAL(15,2)) as PCT_PFClusters,\n CAST(sum(PerfectBarcode) / (sum(PerfectBarcode) + sum(OneMismatchBarcode)) * 100 as DECIMAL(15,2)) as PCT_PerfectBarcode,\n CAST(sum(OneMismatchBarcode) / (sum(PerfectBarcode) + sum(OneMismatchBarcode)) * 100 as DECIMAL(15,2)) as PCT_OneMismatchBarcode,\n CAST(sum(ReadMetricsYield) / 1000000 as INTEGER) as Yield,\n CAST(sum(ReadMetricsYieldQ30) / sum(ReadMetricsYield) * 100 as INTEGER) as PCT_YieldQ30,\n CAST(sum(ReadMetricsQualityScoreSum)/sum(ReadMetricsYield) as DECIMAL(20,2)) as MeanQualityScoreSum\n from \n ConversionResults\n group by SampleId, LaneNumber\n order by PFClusters DESC\n ''')\n undetermined_barcode_stats = \\\n spark.sql('''\n select \n LaneNumber,\n CAST(sum(UndeterminedNumberReads) /2 as INTEGER) as PFCluster,\n CAST(mean(UndeterminedNumberReads) / first(TotalClustersPF) * 100 as DECIMAL(20,2)) as PCT_of_lane,\n CAST(sum(UndeterminedTotalYield) /2 /1000000 as INTEGER) as Yield,\n CAST(sum(UndeterminedReadYieldQ30) / sum(UndeterminedReadYield) * 100 as DECIMAL(20,2)) as PCT_Q30_yield,\n CAST(sum(UndeterminedReadQualityScoreSum)/ sum(UndeterminedReadYield) as DECIMAL(20,2)) as MeanQualityScore\n from\n ConversionResultsUndetermined\n group by LaneNumber\n ''')\n return barcode_stats, undetermined_barcode_stats\n except:\n raise\n\nif __name__=='__main__':\n try:\n from pyspark.sql import SparkSession\n spark = \\\n SparkSession.\\\n builder.\\\n appName('GenerateDemultiplexingReport').\\\n getOrCreate()\n barcode_stats, undetermined_barcode_stats = \\\n get_demultiplexing_stats_from_json(\\\n spark=spark,\n file_list=file_list)\n barcode_stats = \\\n barcode_stats\\\n .toPandas()\\\n .to_html(index=False)\n undetermined_barcode_stats = \\\n undetermined_barcode_stats\\\n .toPandas()\\\n .to_html(index=False)\n generateFormattedReport(\\\n template_path=template_path,\n output_report=output_report,\n title='Merged Report',\n barcode_stats=barcode_stats,\n undetermined_barcode_stats=undetermined_barcode_stats)\n spark.stop()\n\n except Exception as e:\n print('Got exception {0}'.format(e))","sub_path":"script/generateReport.py","file_name":"generateReport.py","file_ext":"py","file_size_in_byte":11121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"219500060","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport rospy\n\nfrom tf2_ros import TransformBroadcaster\nfrom geometry_msgs.msg import TransformStamped, Twist\nfrom ackermann_msgs.msg import AckermannDrive\n\n# Because of transformations\nfrom tf_conversions import transformations\n\nclass RCSim(object):\n def __init__(self, initial_pose=(0, 0, 0), wheel_base=0.2):\n self.pos = np.matrix([float(initial_pose[0]), float(initial_pose[1]), 1.0]).T\n self.dir = float(initial_pose[2])\n\n self.wheel_base = wheel_base\n self.speed = 0.0\n self.steer = 0.0\n\n def ackmn_callback(self, msg):\n self.speed = msg.speed\n self.steer = msg.steering_angle\n\n def gen_rot(self, theta):\n c = np.cos(theta)\n s = np.sin(theta)\n rot = np.matrix([[c, -s, 0], [s, c, 0], [0, 0, 1]])\n return rot\n\n def sim(self):\n t = rospy.get_rostime()\n dt = (t - self.t0).to_sec()\n self.t0 = t\n\n self.twist = Twist()\n self.twist.linear.x = self.speed\n self.twist.angular.z = self.speed * np.tan(self.steer) / self.wheel_base\n\n dx = self.twist.linear.x * dt\n dy = 0.0\n\n trans = np.matrix([dx, dy, 1]).T\n\n hdtheta = 0\n if self.steer != 0.0:\n hdtheta = self.twist.angular.z * dt / 2.0\n\n half_rot = self.gen_rot(hdtheta)\n pose_rot = self.gen_rot(self.dir)\n\n self.pos += pose_rot * half_rot * trans\n self.dir += hdtheta * 2.0\n\n def publish_msgs(self):\n t = rospy.Time.now()\n\n tf = TransformStamped()\n tf.header.stamp = t\n tf.header.frame_id = \"world\"\n tf.child_frame_id = \"base_footprint\"\n tf.transform.translation.x = self.pos[0][0]\n tf.transform.translation.y = self.pos[1][0]\n tf.transform.translation.z = 0.0\n q = transformations.quaternion_from_euler(0, 0, self.dir)\n tf.transform.rotation.x = q[0]\n tf.transform.rotation.y = q[1]\n tf.transform.rotation.z = q[2]\n tf.transform.rotation.w = q[3]\n self.br.sendTransform(tf)\n\n tf.header.frame_id = \"base_footprint\"\n tf.child_frame_id = \"steer\"\n tf.transform.translation.x = self.wheel_base\n tf.transform.translation.y = 0.0\n tf.transform.translation.z = 0.0\n q = transformations.quaternion_from_euler(0, 0, self.steer)\n tf.transform.rotation.x = q[0]\n tf.transform.rotation.y = q[1]\n tf.transform.rotation.z = q[2]\n tf.transform.rotation.w = q[3]\n self.br.sendTransform(tf)\n\n self.pub_twist.publish(self.twist)\n\n def run(self):\n rospy.init_node('ackmn_simulator', anonymous=True)\n rospy.Subscriber(\"/ackmn_drive\", AckermannDrive, self.ackmn_callback)\n self.pub_twist = rospy.Publisher(\"/twist_sim\", Twist, queue_size=1)\n self.br = TransformBroadcaster()\n\n r = rospy.Rate(50)\n self.t0 = rospy.get_rostime()\n while not rospy.is_shutdown():\n self.sim()\n self.publish_msgs()\n r.sleep()\n\n\nif __name__ == '__main__':\n sim = RCSim()\n sim.run()\n","sub_path":"scripts/rc_car_sim.py","file_name":"rc_car_sim.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"109170395","text":"from typing import (\n Generic,\n Generator,\n List,\n TypeVar,\n Union\n)\n\n\nT = TypeVar('T')\n\n\nclass Node(Generic[T]):\n def __init__(self, initdata: T, next: \"Node[T]\" = None, previous: \"Node[T]\" = None):\n self.next = next\n self.previous = previous\n self.data = initdata\n\n def get_data(self) -> T:\n return self.data\n\n def get_next(self):\n return self.next\n\n def get_previous(self):\n return self.previous\n\n def set_data(self, newdata: T):\n self.data = newdata\n\n def set_next(self, newnext: \"Node[T]\" = None):\n self.next = newnext\n\n def set_previous(self, newnprev: \"Node[T]\" = None):\n self.previous = newnprev\n\n def __str__(self):\n if self.next is None:\n return \"{}\".format(self.data)\n else:\n return \"{data}-->{node}\".format(data=self.data, node=str(self.next))\n\n\nclass DoublyLinkedList(Generic[T]):\n def __init__(self, array: List[T] = []):\n self._head: Union[Node[T], None] = None\n self._tail: Union[Node[T], None] = None\n self._size: int = 0\n\n for element in array:\n self.append(element)\n\n def peek(self):\n return self.first().get_data() if self.first() else None\n\n def prepend(self, item: T):\n temp: Node = Node(item)\n temp.set_next(self._head)\n self._head = temp\n self._size += 1\n\n def append(self, item: T):\n temp: Node = Node(item)\n temp.set_next(None)\n if self._head is None:\n self._head = temp\n elif self._tail is not None:\n temp.set_previous(self._tail)\n self._tail.set_next(temp)\n\n self._tail = temp\n self._size += 1\n\n def __len__(self) -> int:\n return self._size\n\n def _first(self) -> Union[Node[T], None]:\n return self._head\n\n def _last(self) -> Union[Node[T], None]:\n return self._tail\n\n def __iter__(self) -> Generator:\n current = self._head\n\n while current is not None:\n yield current.get_data()\n current = current.get_next()\n\n def search(self, item: T) -> int:\n current = self._head\n index = 0\n while current is not None:\n if current.get_data() == item:\n return index\n else:\n current = current.get_next()\n index += 1\n\n # Not found\n return -1\n\n def reverse(self):\n self._tail = self._head\n current_n = self._head\n prev_n = None\n\n while current_n is not None:\n next_n = current_n.get_next()\n current_n.set_next(prev_n)\n current_n.set_previous(next_n)\n prev_n = current_n\n current_n = next_n\n\n self._head = prev_n\n\n def merge_parse(self, list2: \"DoublyLinkedList[T]\"):\n p1 = self._head\n p2 = list2._first()\n\n while p2 is not None and p1 is not None:\n temp1 = p1.get_next()\n temp2 = p2.get_next()\n\n p1.set_next(p2)\n p2.set_next(temp1)\n\n p1 = temp1\n p2 = temp2\n\n def _remove_first(self) -> T:\n current = self._head\n\n if current is None:\n raise IndexError(\"Removing from an empty list.\")\n\n if current.get_next() is not None:\n current.get_next().set_previous(None)\n else:\n self._tail = None\n\n self._head = current.get_next()\n\n self._size -= 1\n\n return current.get_data()\n\n def _remove_last(self) -> T:\n current = self._tail\n\n if current is None:\n raise IndexError(\"Removing from an empty list.\")\n\n if current.get_previous() is not None:\n current.get_previous().set_next(None)\n else:\n self._head = None\n\n self._tail = current.get_previous()\n\n self._size -= 1\n\n return current.get_data()\n\n def has_next(self) -> bool:\n return self._head is not None\n\n def remove(self, item: T):\n current = self._head\n previous = None\n found = False\n\n while not found and current is not None:\n if current.get_data() == item:\n found = True\n else:\n previous = current\n current = current.get_next()\n\n if not found:\n raise LookupError(\"No such element in the list.\")\n\n if current is None:\n return\n\n if current.get_next() is not None:\n current.get_next().set_previous(previous)\n\n if previous is None:\n self._head = current.get_next()\n else:\n previous.set_next(current.get_next())\n\n if previous is not None and previous.get_next() is None:\n self._tail = previous\n\n self._size -= 1\n\n def __str__(self):\n return str(self._head)\n\n\ndef merge_two_sorted_ll(l1: Node, l2: Node) -> Node:\n # Keeps a dummy node to hold the new list\n dummy: Node = Node(-1)\n # Keeps track of the dummy list\n tail = dummy\n\n temp1 = l1\n temp2 = l2\n while (temp1 is not None and temp2 is not None):\n # if temp1 is smaller, put it next to dummy node\n # advance temp1\n # else\n # put temp2 next to dummy node\n # advance temp2\n if (temp1.get_data() <= temp2.get_data()):\n tail.set_next(temp1)\n temp1 = temp1.get_next()\n else:\n tail.set_next(temp2)\n temp2 = temp2.get_next()\n\n tail = tail.get_next()\n\n if temp1 is not None:\n tail.set_next(temp1)\n else:\n tail.set_next(temp2)\n\n return dummy.get_next()\n\n\nclass Stack(DoublyLinkedList):\n def pop(self):\n return self._remove_last()\n\n def push(self, item: T):\n self.append(item)\n\n\nclass Queue(DoublyLinkedList):\n def dequeue(self) -> T:\n return self._remove_first()\n\n def enqueue(self, item: T):\n self.append(item)\n\n\ndef interesection_between_two_ll(l1: Node, l2: Node) -> int:\n length1 = _get_length(l1)\n length2 = _get_length(l2)\n\n # Catchup the longer list to the shorter\n catchup_point = abs(length1 - length2)\n catcher = l1 if length1 > length2 else l2\n to_catch = l1 if length1 < length2 else l2\n\n i = 0\n while (i < catchup_point):\n catcher = catcher.get_next()\n i += 1\n\n # Then start together from here until we find an intersection\n while (catcher is not None):\n if catcher.get_data() == to_catch.get_data():\n return catcher.get_data()\n\n catcher = catcher.get_next()\n to_catch = to_catch.get_next()\n\n return -1\n\n\ndef _get_length(l: Node) -> int:\n current = l\n length = 0\n while (current is not None):\n length += 1\n current = current.get_next()\n\n return length\n\n\ndef get_middle(node: Node) -> Node:\n if not node:\n return node\n\n fast_ptr = node.get_next()\n slow_ptr = node\n\n while(fast_ptr):\n fast_ptr = fast_ptr.get_next()\n\n if fast_ptr is not None:\n slow_ptr = slow_ptr.get_next()\n fast_ptr = fast_ptr.get_next()\n\n return slow_ptr\n\n\ndef main():\n sll2 = Queue([1, 2, 3, 4])\n sll2.reverse()\n sll2.dequeue()\n print(list(sll2))\n\n\nmain()\n","sub_path":"Python/src/pkg/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":7244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"202780719","text":"#!/usr/bin/env python\nimport nmap\nimport os\n#\n# scaning all services from list\n#\ndef scaningAll(url):\n file = open('result.csv', 'a')\n nm = nmap.PortScanner()\n nm.scan(url, arguments='-sV --script vuln')\n nm.command_line()\n for host in nm.all_hosts():\n dns = nm[host].hostname()\n print(host)\n for protocol in nm[host].all_protocols():\n portList = nm[host][protocol].keys()\n for port in portList:\n result = ('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,' % (host, dns, protocol, port, nm[host][protocol][port]['state'], nm[host][protocol][port]['name'], nm[host][protocol][port]['version'], nm[host][protocol][port]['product'], nm[host][protocol][port]['cpe'], nm[host][protocol][port]['conf']))\n try:\n vuln = ('\"%s\"' % nm[host][protocol][port]['script']['vulners'])\n file.write(result + vuln + '\\n')\n pass\n except Exception as e:\n file.write(result + '\"vuln not found\"\\n')\n print('Scann ended.')\n file.close()\n#\n# reading ip list\n#\nfs = open('ip_list.txt', 'r')\nprint('Starting scann...')\nprint('IP,DNS,Protocolo,Porta,Status,Servico,Versao,Produto,Cpe,Conf,Vuln')\nfor url in fs:\n url = url.replace('\\n', '')\n scaningAll(url)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"497763725","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport csv\nimport math\nimport numpy as np\nimport pandas as pd\nimport string\n\n# Classification utils\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn import grid_search\nfrom sklearn.metrics import f1_score\n\n# Classifiers\nfrom sklearn.ensemble import RandomForestClassifier\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.style.use('ggplot')\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\ntask = pd.read_csv('data.csv')\nquiz = pd.read_csv('quiz.csv')\n\n\n# In[2]:\n\n# Name Columns (53 total)\nalphabet = list(string.ascii_lowercase)\nalphabet2 = alphabet + [l+l for l in alphabet] + ['aaa']\n\ntask.columns = alphabet2\n# Leave out label column for test data\nquiz.columns = alphabet2[:-1]\n\ncontinuous_cols = [\n 'vv', 'ww'\n]\n\n# Designate Boolean Columns (15 total)\nboolean_cols = [\n 'g', 'p', 'q', 's',\n 'v', 'w', 'y', 'z',\n 'oo', 'pp', 'qq', 'rr',\n 'xx', 'yy', 'zz'\n]\n\nzero_one_two_cols = ['aa','bb','cc','dd','ee','ff','gg','hh','ii','jj','kk','ll','mm','nn']\n\n# Designate Categorical Columns (16 total)\ncols = task.columns\nnum_cols = task._get_numeric_data().columns\nlist(set(cols) - set(num_cols))\n\ncategorical_cols = ['a', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'k',\n 'l', 'm', 'n', 'o', \n 'ss', 'tt', 'uu'\n ]\n\nfor col in categorical_cols:\n task[col] = task[col].astype('category')\n quiz[col] = quiz[col].astype('category')\n\n# Designate Numeric Columns (37 total)\nnumeric_cols = ['b', 'g', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',\n 'z', 'aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii',\n 'jj', 'kk', 'll', 'mm', 'nn', 'oo', 'pp', 'qq', 'rr', 'vv',\n 'ww', 'xx', 'yy', 'zz']\n\nnumeric_indices = []\nfor i, letter in enumerate(alphabet2):\n if letter in numeric_cols:\n numeric_indices.append(i)\n\ntrain_labels = np.array(task['aaa']).astype(int)\n\n\n# In[3]:\n\n# One-hot encoded features for categorical vars\n\nX_dummies = pd.get_dummies(task[categorical_cols + zero_one_two_cols + boolean_cols])\nX_quiz_dummies = pd.get_dummies(quiz[categorical_cols + zero_one_two_cols + boolean_cols])\n\nX_train_dummies = X_dummies[[col for col in X_dummies.columns if col in X_quiz_dummies.columns]]\nX_quiz_dummies = X_quiz_dummies[[col for col in X_quiz_dummies.columns if col in X_train_dummies.columns]]\n\n\n# In[5]:\n\n# Select K best\nk_best = SelectKBest(chi2, k=1000)\nX_train_k_best_cols = k_best.fit_transform(X_train_dummies, task.ix[:,-1])\na = X_train_k_best_cols.get_support()\n\n# Add the continuous features back in\nX_train_k_best_cols = pd.DataFrame(X_train_k_best_cols)\nX_train_k_best_cols = pd.concat([X_train_k_best_cols, task[continuous_cols]], axis=1)\n\n\n# In[23]:\n\nX_quiz_k_best_cols = X_quiz_dummies.iloc[:,a]\n\nX_quiz_k_best = pd.DataFrame(X_quiz_k_best_cols)\nX_quiz_k_best = pd.concat([X_quiz_k_best, quiz[continuous_cols]], axis=1)\n\n\n# In[24]:\n\nrf = RandomForestClassifier(n_jobs=3, n_estimators=100, max_features=50, max_depth=200)\nclf_full_trained = rf.fit(X_train_k_best_cols, task.ix[:,-1])\n\n\n# In[22]:\n\nprint(X_quiz_k_best)\n\n\n# In[21]:\n\npreds = clf_full_trained.predict(X_quiz_k_best)\nwrite_results(preds)\n\n\n# In[4]:\n\n# Exploring different parameter settings with grid_search\n# Features reduced with select k best\n# Training size reduced with train_test_split\n\nparam_grid = [{\n 'n_estimators': [100],\n 'max_features': [50],\n 'max_depth': [200]\n}]\n\nrf = RandomForestClassifier(n_jobs=2)\nclf = grid_search.GridSearchCV(rf, param_grid)\n\nx_train, x_test, y_train, y_test = train_test_split(X_train_k_best, task.ix[:,-1], train_size=0.05, test_size=0.05)\nclf_trained = clf.fit(x_train, y_train)\n\nscores = cross_val_score(clf_trained, x_test, y_test, cv=2)\n\nprint(scores)\nprint('best params: ', clf_trained.best_params_)\n\n\n# In[ ]:\n\n# n_estimators accuracy plot\nparam_results = clf_trained.grid_scores_\n\n# Features were reduced using select K best (1000)\n# train_size=0.05, test_size=0.05 (train_test_split)\nn_estimators_values = [1, 10, 100, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000]\nn_estimators_results = [0.65084, 0.81438, 0.85980, 0.86027, 0.86217, 0.86169, 0.86106, 0.86343,\n 0.86154, 0.86138, 0.86264, 0.86359, 0.86185]\n\nts = pd.Series(n_estimators_results, index=n_estimators_values)\n\nax = ts.plot()\nax.set_title('Number of RF estimators vs RF prediction accuracy', fontsize=14, fontweight='bold')\nax.set_xlabel('n_estimators')\nax.set_ylabel('accuracy')\n\nplt.figure(); ts.plot();\nplt.show()\n\n\n# In[ ]:\n\n# max_features accuracy plot\nparam_results = clf_trained.grid_scores_\n# pp.pprint(param_results)\n\nmax_features_values = [1, 10, 50, 100, 200, 500, 1000]\nmax_features_results = [0.57562, 0.84608, 0.87352, 0.87053, 0.87478, 0.87305, 0.86942]\n\nts = pd.Series(max_features_results, index=max_features_values)\n\nax = ts.plot()\nax.set_title('Number of RF features vs RF prediction accuracy', fontsize=14, fontweight='bold')\nax.set_xlabel('max_features')\nax.set_ylabel('accuracy')\n\nplt.figure(); ts.plot();\nplt.show()\n\n\n# In[ ]:\n\n# max_depth accuracy plot\nparam_results = clf_trained.grid_scores_\npp.pprint(param_results)\n\nmax_depth_values = [1, 10, 50, 100, 200, 500, 1000, 2000, 5000]\nmax_depth_results = [0.64517, 0.86501, 0.88850, 0.88771, 0.89182, 0.88992, 0.88945, 0.88693, 0.88992]\n\nts = pd.Series(max_depth_results, index=max_depth_values)\n\nax = ts.plot()\nax.set_title('RF max depth vs RF prediction accuracy', fontsize=14, fontweight='bold')\nax.set_xlabel('max_depth')\nax.set_ylabel('accuracy')\n\nplt.figure(); ts.plot();\nplt.show()\n\n\n# In[1]:\n\ndef write_results(preds):\n with open('test_predictions.csv', 'wb') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['id', 'Prediction'])\n for i, pred in enumerate(preds):\n writer.writerow([i+1, pred])\n\n\n# In[ ]:\n\n\n\n","sub_path":"ian_4.py","file_name":"ian_4.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"68654231","text":"import xml.etree.ElementTree as etree # from lxml import etree #for parser\nfrom io import BytesIO\nimport logging\nimport tempfile\nfrom six.moves import urllib\nfrom xml.sax.saxutils import quoteattr\n\n# Serialization\n\n\ndef __get_ontology_string(onto, name):\n onto_string = \"\"\n if onto is None:\n return onto_string\n if len(onto) > 0:\n onto_string += \" <\" + name + \">\\n\"\n onto_string += ' \\n'\n if len(onto) > 1:\n onto_string += \" \" + onto[1] + \"\\n\"\n if len(onto) > 3:\n onto_string += \" \\n\"\n onto_string += (\n ' \\n'\n )\n onto_string += \" \\n\"\n onto_string += \" \\n\"\n onto_string += \" \\n\"\n return onto_string\n\n\ndef __get_extension_string(extension):\n ext_string = \"\"\n if extension is None:\n return ext_string\n for key, value in extension:\n ext_string += \" <\" + key + \">\" + value + \"\\n\"\n return ext_string\n\n\ndef __get_xml_intro(onto_one=None, onto_two=None, extension=None):\n return (\n \"\"\"\n \n\n yes\n 0\n ??\"\"\"\n + __get_extension_string(extension)\n + __get_ontology_string(onto_one, \"onto1\")\n + __get_ontology_string(onto_two, \"onto2\")\n )\n\n\ndef __get_mapping_string(source, target, relation, confidence):\n return \"\"\"\n \n \n \n \n %s\n %s\n \n \"\"\" % (\n quoteattr(source),\n quoteattr(target),\n relation,\n confidence,\n )\n\n\ndef __get_xml_outro():\n return \"\"\"\n \n\n\"\"\"\n\n\ndef serialize_mapping_to_file(\n file_path, alignment, onto_one=None, onto_two=None, extension=None\n):\n \"\"\"\n Serialize a alignment (iterable of (source, target, relation, confidence)) to a given file.\n :param file_path: represent the path of the file as a string\n :param alignment: iterable of (source, target, relation, confidence)\n :param onto_one: description of ontology one as (id, url, formalismName, formalismURI)\n :param onto_two: description of ontology two as (id, url, formalismName, formalismURI)\n :param extension: iterable of (key, value) describing the alignment\n \"\"\"\n with open(file_path, \"w\", encoding=\"utf-8\") as out_file:\n out_file.write(__get_xml_intro(onto_one, onto_two, extension))\n for source, target, relation, confidence in alignment:\n out_file.write(__get_mapping_string(source, target, relation, confidence))\n out_file.write(__get_xml_outro())\n\n\ndef serialize_mapping_to_tmp_file(\n alignment, onto_one=None, onto_two=None, extension=None\n):\n \"\"\"\n Serialize a alignment (iterable of (source, target, relation, confidence)) to a file in the systems temp folder\n (which is not deleted) and return a file url of that file.\n :param alignment: iterable of (source, target, relation, confidence)\n :param onto_one: description of ontology one as (id, url, formalismName, formalismURI)\n :param onto_two: description of ontology two as (id, url, formalismName, formalismURI)\n :param extension: iterable of (key, value) describing the alignment\n :return: file url of the generated alignment file like file://tmp/alignment_123.rdf\n \"\"\"\n with tempfile.NamedTemporaryFile(\n \"w\", prefix=\"alignment_\", suffix=\".rdf\", delete=False\n ) as out_file:\n out_file.write(__get_xml_intro(onto_one, onto_two, extension))\n for source, target, relation, confidence in alignment:\n out_file.write(__get_mapping_string(source, target, relation, confidence))\n out_file.write(__get_xml_outro())\n return urllib.parse.urljoin(\"file:\", urllib.request.pathname2url(out_file.name))\n\n\n# Parser\n\n\nclass AlignmentHandler(object):\n def __init__(self):\n self.base = \"{http://knowledgeweb.semanticweb.org/heterogeneity/alignment}\"\n self.rdf = \"{http://www.w3.org/1999/02/22-rdf-syntax-ns#}\"\n self.text = \"\"\n self.alignment = []\n self.one_cell = [\"\", \"\", \"\", \"\"]\n self.extension = {}\n self.onto1 = \"\"\n self.onto2 = \"\"\n self.onto_temp = [\"\", \"\"]\n self.used_tags = set(\n [\n self.base + name\n for name in [\n \"entity1\",\n \"entity2\",\n \"relation\",\n \"measure\",\n \"Cell\",\n \"map\",\n \"Alignment\",\n \"xml\",\n \"level\",\n \"type\",\n \"onto1\",\n \"onto2\",\n \"Ontology\",\n \"location\",\n \"formalism\",\n \"Formalism\",\n ]\n ]\n )\n self.used_tags.add(self.rdf + \"RDF\")\n\n def start(self, name, attrs):\n if name == self.base + \"entity1\":\n self.one_cell[0] = attrs[self.rdf + \"resource\"] # .encode('utf-8')\n elif name == self.base + \"entity2\":\n self.one_cell[1] = attrs[self.rdf + \"resource\"] # .encode('utf-8')\n elif name == self.base + \"Ontology\":\n self.onto_temp[0] = attrs[self.rdf + \"about\"] # .encode('utf-8')\n self.text = \"\"\n\n def end(self, name):\n if name == self.base + \"relation\":\n self.one_cell[2] = self.text.strip()\n elif name == self.base + \"measure\":\n self.one_cell[3] = self.text.strip()\n elif name == self.base + \"Cell\":\n self.alignment.append(self.one_cell)\n self.one_cell = [\"\", \"\", \"\", \"\"]\n elif name == self.base + \"location\":\n self.onto_temp[1] = self.text.strip()\n elif name == self.base + \"onto1\":\n if self.onto_temp[0] == \"\" and self.onto_temp[1] == \"\":\n self.onto_temp[0] = self.text.strip()\n self.onto1 = list(self.onto_temp)\n elif name == self.base + \"onto2\":\n if self.onto_temp[0] == \"\" and self.onto_temp[1] == \"\":\n self.onto_temp[0] = self.text.strip()\n self.onto2 = list(self.onto_temp)\n elif name == self.base + \"measure\":\n self.one_cell[3] = self.text.strip()\n elif name not in self.used_tags:\n key = name[name.index(\"}\") + 1 :]\n self.extension[key] = self.text\n\n def data(self, chars):\n self.text += chars\n\n def close(self):\n pass\n\n\ndef parse_mapping_from_string(s):\n \"\"\"\n Parses a alignment from a given string.\n :param s: a string representing a alignment in alignment format\n :return: (alignment: list of (source, target, relation, confidence), onto1 as ((id, url, formalismName, formalismURI),\n onto2 similar to onto1, extension (iterable of key, values) )\n \"\"\"\n handler = AlignmentHandler()\n etree.parse(BytesIO(s.encode(\"utf-8\")), etree.XMLParser(target=handler))\n return handler.alignment, handler.onto1, handler.onto2, handler.extension\n\n\ndef parse_mapping_from_file(source):\n \"\"\"\n Parses a alignment from a filename or file object.\n :param source: is a filename or file object containing a alignment in alignment format\n :return: (alignment: list of (source, target, relation, confidence), onto1 as ((id, url, formalismName, formalismURI),\n onto2 similar to onto1, extension (iterable of key, values) )\n \"\"\"\n handler = AlignmentHandler()\n etree.parse(source, etree.XMLParser(target=handler))\n return handler.alignment, handler.onto1, handler.onto2, handler.extension\n\n\n# if __name__ == \"__main__\":\n# logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.INFO)\n# logging.info(\"Generate\")\n# t = [('http://test.dwfwegwegwegtrh/12&34_' + str(i), 'http://test2.dwfwegwegwegtrh/' + str(i), '=', 1.0)\n# for i in range(200)]\n# logging.info(\"write\")\n# serialize_mapping_to_file('test.txt', t)\n# # bla = serialize_mapping_to_tmp_file(t)\n# # logging.info(bla)\n","sub_path":"examples/externalPythonMatcherSeals/oaei-resources/AlignmentFormat.py","file_name":"AlignmentFormat.py","file_ext":"py","file_size_in_byte":8635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"411229924","text":"'''\n654. Maximum Binary Tree\n\nGiven an integer array with no duplicates. A maximum tree building on this array is defined as follow:\n\nThe root is the maximum number in the array.\nThe left subtree is the maximum tree constructed from left part subarray divided by the maximum number.\nThe right subtree is the maximum tree constructed from right part subarray divided by the maximum number.\nConstruct the maximum tree by the given array and output the root node of this tree.\n\nExample 1:\nInput: [3,2,1,6,0,5]\nOutput: return the tree root node representing the following tree:\n\n 6\n / \\\n 3 5\n \\ / \n 2 0 \n \\\n 1\nNote:\nThe size of the given array will be in the range [1,1000].\n\n'''\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def constructMaximumBinaryTree(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"# non-recursive\n ''' \n # construct trees and update currentRoot\n end = len(nums)\n \n if len(nums) == 0 :\n return None\n \n root = TreeNode(nums[0])\n \n for i in range(1, len(nums)):\n \n current = TreeNode(nums[i])\n \n # update root\n if nums[i] > root.val:\n current.left = root\n root = current\n \n # insert it to right side\n else:\n node = root\n while node.right!=None:\n if nums[i] > node.right.val: \n current.left = node.right \n break\n node = node.right\n \n node.right = current\n \n return root'''\n \n # recursive\n '''\n # construct trees and update currentRoot\n end = len(nums)\n \n if len(nums) == 0 :\n return None\n \n root = TreeNode(nums[0])\n \n def constructTree(i, root):\n #print(root.val)\n if i == end:\n return root\n \n current = TreeNode(nums[i])\n \n # update root\n if nums[i] > root.val:\n current.left = root\n root = current\n \n # insert it to right side\n else:\n node = root\n while node.right!=None:\n if nums[i] > node.right.val: \n current.left = node.right \n break\n node = node.right\n \n node.right = current\n \n return constructTree(i+1, root)\n \n \n \n root = constructTree(1, root)\n \n return root\n '''\n \n # use a stack to maintain right path, smallest one is at index 0 \n \n '''stack = []\n for n in nums:\n current = TreeNode(n)\n while len(stack) >0 and stack[0].val < n:\n current.left = stack.pop(0)\n if len(stack) > 0:\n stack[0].right = current\n stack.insert(0, current)\n \n return stack[-1]'''\n # use a stack to maintain right path, smallest one is at index -1 \n '''stack = []\n for n in nums:\n current = TreeNode(n)\n while len(stack) >0 and stack[-1].val < n:\n current.left = stack.pop()\n if len(stack) > 0:\n stack[-1].right = current\n stack.append(current)\n \n return stack[0]\n '''\n \n l = len(nums)\n if l == 0:\n return None\n \n index = 0\n maximum = nums[index]\n for i in range(l):\n if nums[i] > maximum:\n maximum = nums[i]\n index = i\n \n root = TreeNode(maximum)\n root.left = self.constructMaximumBinaryTree(nums[:index])\n root.right = self.constructMaximumBinaryTree(nums[index+1:])\n \n return root\n","sub_path":"654_MaximumBinaryTree.py","file_name":"654_MaximumBinaryTree.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"243888110","text":"'''\r\nCreated on 2020年5月14日\r\n\r\n@author: likecan\r\n'''\r\n#coding = utf-8\r\nimport xlrd\r\n\r\nclass case_doucument_handle(object):\r\n '''\r\n classdocs\r\n '''\r\n\r\n\r\n def __init__(self, case_file_path = './Data/Interface_Case.xlsx'):\r\n '''\r\n Constructor\r\n '''\r\n open_excel = xlrd.open_workbook(filename=case_file_path)\r\n self.get_sheet_content = open_excel.sheet_by_index(0)\r\n self.total_row = self.get_sheet_content.nrows\r\n\r\n def get_row_num(self,case_id):\r\n total_rows = self.get_sheet_content.nrows\r\n print(total_rows)\r\n for row in range(1,total_rows):\r\n if case_id == self.get_sheet_content.cell_value(row,0):\r\n return row\r\n \r\n \r\n \r\n def get_cell_content(self,row,colum):\r\n '''\r\n 根据列数获取单元格内容\r\n '''\r\n cell_content = self.get_sheet_content.cell_value(row,colum)\r\n if cell_content == '' or cell_content == 'None':\r\n return None\r\n return cell_content\r\n \r\n\r\n \r\n \r\n \r\nclass data_handle(object):\r\n \r\n \r\n def data_to_dict(self,data):\r\n '''\r\n 将传入的数据转换成字典,主要针对header,cookie,请求数据等\r\n '''\r\n data_dict = {}\r\n if not isinstance(data,str) or not data:\r\n return data\r\n data_list = data.split('\\n')\r\n # print(data_list)\r\n for d in data_list:\r\n if d != '':\r\n data_dict[d.split(' ',1)[0]] = d.split(' ',1)[1][1:]\r\n return data_dict\r\n\r\n# import sys\r\n# sys.path.append('./')\r\n# from Json_File_Handle.Json_File_Read import json_file_read\r\n# jf_read = json_file_read()\r\n# case_d = case_doucument_handle()\r\n# data_h = data_handle()\r\n# data = []\r\n# for r in range(1,case_d.total_row):\r\n# data.append({case_d.get_cell_content(r,0):case_d.get_cell_content(r,4)})\r\n# jf_read.send_request_result_data_to_json('Request_Data',data,'Request_Data.json')\r\n# jf_read.read_content_from_json('','Request_Data')","sub_path":"Interface_Test_Frame/Data/Case_Document_Handle.py","file_name":"Case_Document_Handle.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"474390085","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nhttp://www.cnblogs.com/kaituorensheng/p/4445418.html\n当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。\n\"\"\"\n\nimport os\nimport sys\nimport requests\nimport time\nfrom pprint import pprint as pp\nimport multiprocessing\n\ndef worker_1(f):\n fs = open(f, 'a+')\n for i in range(3):\n fs.write(\"eric write without lock %s\\n\" % i)\n time.sleep(0.5)\n fs.close()\n print ( \"workder_1 done\" )\n \ndef worker_2(f):\n fs = open(f, 'a+')\n for i in range(3):\n fs.write(\"nolan write without lock %s\\n\" % i)\n time.sleep(0.5)\n fs.close()\n print ( \"workder_2 done\" )\n \n'''\n不加锁,只有一个进程能写一个文件\n''' \nif __name__ == \"__main__\":\n f = \"0file.txt\"\n os.path.exists(f) and os.remove(f)\n w1 = multiprocessing.Process(target = worker_1, args=[f])\n w2 = multiprocessing.Process(target = worker_2, args=[f])\n w1.start()\n w2.start()\n\n# worker_1(f)\n# worker_2(f)\n print (\"end\")\n\n","sub_path":"process/file-write-lock-no.py","file_name":"file-write-lock-no.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"564933548","text":"l=list(\"WELCOMETOGUVICORPORATIONS\") \nn=list(input())\nll,lll=[],[]\nfor j in range(0,len(l),5):\n ll.append(l[j:j+5])\nk=0\nfor i in range(len(ll)):\n for j in range(len(ll[i])):\n if k==len(n):\n break \n if ll[i][j]==n[k]: \n lll.append([i,j])\n k+=1 \nif k==len(n): \n print(*lll[0])\n print(*lll[-1])\nelse:print(0)","sub_path":"hunter/set5/42.py","file_name":"42.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"254496603","text":"### <--- ALL I WANT --->\nfrom flask import Flask, render_template, request, session, send_file\nimport cx_Oracle\nfrom cx_Oracle import DatabaseError\nimport os\nimport csv\n\n\n### <--- CONFIGURE FLASK --->\napp = Flask(__name__)\napp.secret_key = os.urandom(1235)\n\n\n### <--- BUILDING WEB-APP TEMPLATES --->\n@app.route('/')\ndef homePage():\n return render_template('home.html')\n\n@app.route('/database_connection')\ndef connectionFormPage():\n return render_template('database_connection.html')\n\n@app.route('/source_data')\ndef showSourceDataPage():\n return render_template('source_data.html')\n\n@app.route('/select_columns')\ndef selectColumnsPage():\n return render_template('select_columns.html')\n\n@app.route('/config_columns')\ndef configureColumnsPage():\n return render_template('config_columns.html')\n\n@app.route('/target_data')\ndef showTargetDataPage():\n return render_template('target_data.html')\n\n@app.route('/export_files')\ndef exportFilesPage():\n return render_template('export.files.html')\n\n\n### <--- DEFINING FUNCTION --->\n@app.route('/connection_form', methods=['GET', 'POST'])\ndef databaseConnectionForm():\n if request.method == \"POST\":\n ### <--- Store Source & Target Connection Form --->\n session['SOU_USER'] = request.form['sou_username']\n session['SOU_PASS'] = request.form['sou_password']\n session['SOU_HOST'] = request.form['sou_hostname']\n session['SOU_PORT'] = request.form['sou_port']\n session['SOU_SID'] = request.form['sou_sid']\n\n session['TAR_USER'] = request.form['tar_username']\n session['TAR_PASS'] = request.form['tar_password']\n session['TAR_HOST'] = request.form['tar_hostname']\n session['TAR_PORT'] = request.form['tar_port']\n session['TAR_SID'] = request.form['tar_sid']\n ### <--------------------------------------------->\n\n SOU_USER = request.form['sou_username']\n SOU_PASS = request.form['sou_password']\n SOU_DBURL = (request.form['sou_hostname'] + ':' + request.form['sou_port'] + '/' + request.form['sou_sid'])\n TAR_USER = request.form['tar_username']\n TAR_PASS = request.form['tar_password']\n TAR_DBURL = (request.form['tar_hostname'] + ':' + request.form['tar_port'] + '/' + request.form['tar_sid'])\n\n try:\n SOURCE_CONN = cx_Oracle.connect(SOU_USER, SOU_PASS, SOU_DBURL)\n SOURCE_CUR = SOURCE_CONN.cursor()\n TARGET_CONN = cx_Oracle.connect(TAR_USER, TAR_PASS, TAR_DBURL)\n TARGET_CUR = SOURCE_CONN.cursor()\n\n GET_TABLE_NAME = \" SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = UPPER('\"+ SOU_USER.upper() +\"') \"\n SOURCE_CUR.execute(GET_TABLE_NAME)\n TABLES = SOURCE_CUR.fetchall()\n SOU_TABLE_CUT = []\n for i in range(len(TABLES)):\n TABLE = TABLES[i]\n SOU_TABLE_CUT.append(TABLE[0])\n\n except cx_Oracle.DatabaseError as e:\n error, = e.args\n #print('Error.code =', error.code)\n #print('Error.message =', error.message)\n #print('Error.offset =', error.offset)\n return render_template('database_connection.html', errors=error.message)\n\n session['SOU_TABLE_CUT'] = SOU_TABLE_CUT\n\n return render_template('source_data.html', tables=SOU_TABLE_CUT)\n\n@app.route('/get_data_source', methods=['GET', 'POST'])\ndef showDataSource():\n if request.method == \"POST\":\n SOU_USER = session['SOU_USER']\n SOU_PASS = session['SOU_PASS']\n SOU_DBURL = (session['SOU_HOST'] + ':' + session['SOU_PORT'] + '/' + session['SOU_SID'])\n\n SOU_TABLE_NAME = request.form.get('table_selected')\n session['SOU_TABLE_NAME'] = request.form.get('table_selected')\n\n SOURCE_CONN = cx_Oracle.connect(SOU_USER, SOU_PASS, SOU_DBURL)\n SOURCE_CUR = SOURCE_CONN.cursor()\n\n GET_DATA = \" SELECT * FROM \"+ SOU_TABLE_NAME +\" \"\n SOURCE_CUR.execute(GET_DATA)\n DATA = SOURCE_CUR.fetchall()\n DATA_CUT = []\n for i in DATA:\n DATA_CUT.append(i)\n\n GET_COLUMN_NAME = \" SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '\"+ SOU_TABLE_NAME +\"' ORDER BY COLUMN_ID \"\n SOURCE_CUR.execute(GET_COLUMN_NAME)\n COLUMNS = SOURCE_CUR.fetchall()\n COL_CUT = []\n for i in range(len(COLUMNS)):\n COL = COLUMNS[i]\n COL_CUT.append(COL[0])\n session['COL_CUT'] = COL_CUT\n SOU_TABLE_CUT = session['SOU_TABLE_CUT']\n\n return render_template('source_data.html', columns=COL_CUT, data=DATA_CUT, tables=SOU_TABLE_CUT, tbn=SOU_TABLE_NAME)\n\n@app.route('/select_cols', methods=['GET', 'POST'])\ndef selectColumns():\n COL_CUT = session['COL_CUT']\n return render_template('select_columns.html', columns=COL_CUT)\n\n@app.route('/get_column_details', methods=['GET', 'POST'])\ndef selectColumnDetails():\n SOU_USER = session['SOU_USER']\n SOU_PASS = session['SOU_PASS']\n SOU_DBURL = (session['SOU_HOST'] +':'+ session['SOU_PORT'] +'/'+ session['SOU_SID'])\n SOU_TABLE_NAME = session['SOU_TABLE_NAME']\n\n if request.method == \"POST\":\n COLUMNS = request.form.getlist('col_selected')\n session['COLUMNS'] = request.form.getlist('col_selected')\n COLUMN_NAME = \"\"\n for i in range(len(COLUMNS)):\n COLUMN_NAME = COLUMN_NAME + \"'\" + COLUMNS[i] + \"'\"\n if i < len(COLUMNS) - 1:\n COLUMN_NAME += \",\"\n\n SOURCE_CONN = cx_Oracle.connect(SOU_USER, SOU_PASS, SOU_DBURL)\n SOURCE_CUR = SOURCE_CONN.cursor()\n\n GET_COLUMN_DETAILS = \" SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH,\" \\\n \" CASE WHEN DATA_TYPE = 'DATE' THEN 'DATE' \" \\\n \" ELSE DATA_TYPE||'('||DATA_LENGTH||')' END AS TYPE_LENGTH \" \\\n \" FROM USER_TAB_COLUMNS \" \\\n \" WHERE COLUMN_NAME in (\"+ COLUMN_NAME +\") AND TABLE_NAME = '\"+ SOU_TABLE_NAME +\"' \" \\\n \" ORDER BY COLUMN_ID \"\n SOURCE_CUR.execute(GET_COLUMN_DETAILS)\n ROWS = SOURCE_CUR.fetchall()\n COLUMN_DETAILS = []\n for i in ROWS:\n COLUMN_DETAILS.append(i)\n session['COLUMN_DETAILS'] = COLUMN_DETAILS\n\n return render_template('config_columns.html', details=COLUMN_DETAILS)\n\n@app.route('/config_columns', methods=['GET', 'POST'])\ndef configureColumnsForm():\n SOU_USER = session['SOU_USER']\n SOU_PASS = session['SOU_PASS']\n SOU_DBURL = (session['SOU_HOST'] + ':' + session['SOU_PORT'] + '/' + session['SOU_SID'])\n TAR_USER = session['TAR_USER']\n TAR_PASS = session['TAR_PASS']\n TAR_DBURL = (session['TAR_HOST'] + ':' + session['TAR_PORT'] + '/' + session['TAR_SID'])\n SOU_TABLE_NAME = session['SOU_TABLE_NAME']\n COLUMN_DETAILS = session['COLUMN_DETAILS']\n PICK_COLUMNS = session['COLUMNS']\n\n if request.method == \"POST\":\n CHECK_TABLE = request.form.get('check_table')\n TAR_TABLE_NAME = request.form['new_table_name']\n NEW_COLUMN_NAME = request.form.getlist('new_col_name')\n NEW_DATA_TYPE = request.form.getlist('new_data_type')\n NEW_DATA_LENGTH = request.form.getlist('new_data_length')\n\n SOURCE_CONN = cx_Oracle.connect(SOU_USER, SOU_PASS, SOU_DBURL)\n SOURCE_CUR = SOURCE_CONN.cursor()\n TARGET_CONN = cx_Oracle.connect(TAR_USER, TAR_PASS, TAR_DBURL)\n TARGET_CUR = TARGET_CONN.cursor()\n\n # <----------------------------------->\n # <--- check if it's a fact table. --->\n # <----------------------------------->\n if CHECK_TABLE == 'Fact':\n # <---------------------------------------------------------------------->\n # <--- check in target database that's already have sequences or not. --->\n # <---------------------------------------------------------------------->\n CHECK_FACT_SEQ = \" SELECT COUNT(*) \" \\\n \" FROM USER_SEQUENCES \" \\\n \" WHERE SEQUENCE_NAME = 'SEQ_\" + TAR_TABLE_NAME.upper() + \"' \"\n TARGET_CUR.execute(CHECK_FACT_SEQ)\n ROWS = TARGET_CUR.fetchall()\n CHECK_FAS = []\n for i in range(len(ROWS)):\n ROW = ROWS[i]\n CHECK_FAS.append(ROW[0])\n\n CHECK_DATE_SEQ = \" SELECT COUNT(*) \" \\\n \" FROM USER_SEQUENCES \" \\\n \" WHERE SEQUENCE_NAME = 'SEQ_DATE_DIMENSION' \"\n TARGET_CUR.execute(CHECK_DATE_SEQ)\n ROWS = TARGET_CUR.fetchall()\n CHECK_DAS = []\n for i in range(len(ROWS)):\n ROW = ROWS[i]\n CHECK_DAS.append(ROW[0])\n\n CHECK_FACT_TABLE = \" SELECT COUNT(*) \" \\\n \" FROM USER_TABLES \" \\\n \" WHERE TABLE_NAME = '\" + TAR_TABLE_NAME.upper() + \"' \"\n TARGET_CUR.execute(CHECK_FACT_TABLE)\n ROWS = TARGET_CUR.fetchall()\n CHECK_FAT = []\n for i in range(len(ROWS)):\n ROW = ROWS[i]\n CHECK_FAT.append(ROW[0])\n\n CHECK_DATE_DIM = \" SELECT COUNT(*) \" \\\n \" FROM USER_TABLES \" \\\n \" WHERE TABLE_NAME = 'DATE_DIMENSION' \"\n TARGET_CUR.execute(CHECK_DATE_DIM)\n ROWS = TARGET_CUR.fetchall()\n CHECK_DAD = []\n for i in range(len(ROWS)):\n ROW = ROWS[i]\n CHECK_DAD.append(ROW[0])\n # <---------------------------------------------------------------------->\n\n if ((CHECK_FAS == [0]) & (CHECK_DAS == [0])) & ((CHECK_FAT == [0]) & (CHECK_DAD == [0])):\n # <------------------------------------------------------------>\n # <--- if in target database not have sequences, create it. --->\n # <------------------------------------------------------------>\n CREATE_FACT_SEQ = \" CREATE SEQUENCE \"+ TAR_USER.upper() +\".SEQ_\"+ TAR_TABLE_NAME +\" \" \\\n \" MINVALUE 1 \" \\\n \" START WITH 1 \" \\\n \" INCREMENT BY 1 \" \\\n \" CACHE 20 \"\n SOURCE_CUR.execute(CREATE_FACT_SEQ)\n\n CREATE_DATE_SEQ = \" CREATE SEQUENCE \" + TAR_USER.upper() + \".SEQ_DATE_DIMENSION \" \\\n \" MINVALUE 1 \" \\\n \" START WITH 1 \" \\\n \" INCREMENT BY 1 \" \\\n \" CACHE 20 \"\n SOURCE_CUR.execute(CREATE_DATE_SEQ)\n # <------------------------------------------------------------>\n\n # <-------------------------->\n # <--- create fact table. --->\n # <-------------------------->\n CFT_CREATE = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n if NEW_DATA_TYPE[i] == 'DATE':\n CFT_CREATE = CFT_CREATE + \" \" + NEW_COLUMN_NAME[i] + \" \" + NEW_DATA_TYPE[i]\n\n else:\n CFT_CREATE = CFT_CREATE + \" \" + NEW_COLUMN_NAME[i] + \" \" + NEW_DATA_TYPE[i] + \"(\" + \\\n NEW_DATA_LENGTH[i] + \") \"\n\n if i < len(NEW_COLUMN_NAME) - 1:\n CFT_CREATE += \",\"\n\n CREATE_FACT_TABLE = \" CREATE TABLE \"+ TAR_USER.upper() +\".\"+ TAR_TABLE_NAME +\" \" \\\n \" (SRG_KEY INT, \" \\\n \" \" + CFT_CREATE + \" )\"\n SOURCE_CUR.execute(CREATE_FACT_TABLE)\n # <-------------------------->\n\n # <----------------------------------------------------------->\n # <--- create date dimension from date data in fact table. --->\n # <----------------------------------------------------------->\n for i in COLUMN_DETAILS:\n if i[1] == 'DATE':\n CREATE_DATE_DIM = \" CREATE TABLE \"+ TAR_USER.upper() +\".DATE_DIMENSION\" \\\n \" AS( SELECT \"+ TAR_USER.upper() +\".SEQ_DATE_DIMENSION.nextval as \\\"SRG_KEY\\\", \" \\\n \" TO_CHAR(\"+ i[0] +\", 'DD/MM/YYYY') as FULL_DATE_ARABIC, \" \\\n \" TO_CHAR(\"+ i[0] +\", 'DY') as DAY_SHORT, \" \\\n \" TO_CHAR(\"+ i[0] +\", 'MM') as MONTH_NUM, \" \\\n \" TO_CHAR(\"+ i[0] +\", 'MONTH') as MONTH_NAME, \" \\\n \" TO_CHAR(\"+ i[0] +\", 'MON') as MONTH_SHORT, \" \\\n \" TO_CHAR(\"+ i[0] +\", 'YYYY') as YEAR, \" \\\n \" TO_CHAR(TO_DATE(\"+ i[0] +\", 'DD/MM/RRRR'), 'D') as DAY_OF_WEEK \" \\\n \" FROM \"+ SOU_USER.upper() +\".\"+ SOU_TABLE_NAME +\") \"\n SOURCE_CUR.execute(CREATE_DATE_DIM)\n\n IFT_INSERT_TAR = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n IFT_INSERT_TAR = IFT_INSERT_TAR + \" \" + NEW_COLUMN_NAME[i] + \" \"\n\n if i < len(NEW_COLUMN_NAME) - 1:\n IFT_INSERT_TAR += \",\"\n\n IFT_SELECT_SOU = \"\"\n for i in range(len(PICK_COLUMNS)):\n IFT_SELECT_SOU = IFT_SELECT_SOU + \" \" + PICK_COLUMNS[i] + \" \"\n\n if i < len(PICK_COLUMNS) - 1:\n IFT_SELECT_SOU += \",\"\n\n INSERT_FACT_TABLE = \" INSERT INTO \" + TAR_USER.upper() + \".\" + TAR_TABLE_NAME + \"( SRG_KEY, \" + IFT_INSERT_TAR + \" ) \" \\\n \" ( SELECT \" + TAR_USER.upper() + \".SEQ_\" + TAR_TABLE_NAME + \".nextval as \\\"SRG_KEY\\\",\" \\\n \" \" + IFT_SELECT_SOU + \" \" \\\n \" FROM \" + SOU_USER.upper() + \".\" + SOU_TABLE_NAME + \" ) \"\n SOURCE_CUR.execute(INSERT_FACT_TABLE)\n SOURCE_CONN.commit()\n # <----------------------------------------------------------->\n\n # <-------------------------------------------------------------->\n # <--- merge it, if it's already have table that be the same. --->\n # <-------------------------------------------------------------->\n else:\n MFT_INSERT_TAR = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n MFT_INSERT_TAR = MFT_INSERT_TAR + \" TAR.\" + NEW_COLUMN_NAME[i] + \" \"\n\n if i < len(NEW_COLUMN_NAME) - 1:\n MFT_INSERT_TAR += \",\"\n\n MFT_SELECT_SOU = \"\"\n MFT_VALUES_SOU = \"\"\n for i in range(len(PICK_COLUMNS)):\n MFT_SELECT_SOU = MFT_SELECT_SOU + \" \" + PICK_COLUMNS[i] + \" \"\n MFT_VALUES_SOU = MFT_VALUES_SOU + \" SOU.\" + PICK_COLUMNS[i] + \" \"\n\n if i < len(PICK_COLUMNS) - 1:\n MFT_SELECT_SOU += \",\"\n MFT_VALUES_SOU += \",\"\n\n MFT_JOIN = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n for j in range(len(PICK_COLUMNS)):\n if i == j:\n MFT_JOIN = MFT_JOIN + \" TAR.\" + NEW_COLUMN_NAME[j] + \" = SOU.\" + PICK_COLUMNS[j] + \" \"\n\n if i < len(NEW_COLUMN_NAME) -1:\n MFT_JOIN += \"AND\"\n\n MERGE_FACT_TABLE = \" MERGE INTO \" + TAR_USER.upper() + \".\" + TAR_TABLE_NAME + \" TAR \" \\\n \" USING (SELECT \" + MFT_SELECT_SOU + \" FROM \" + SOU_USER.upper() + \".\" + SOU_TABLE_NAME + \") SOU \" \\\n \" ON (\" + MFT_JOIN + \") \" \\\n \" WHEN NOT MATCHED THEN INSERT \" \\\n \" (TAR.SRG_KEY, \" + MFT_INSERT_TAR + \") \" \\\n \" VALUES \" \\\n \" (\" + TAR_USER.upper() + \".SEQ_\" + TAR_TABLE_NAME + \".nextval, \" \\\n \" \" + MFT_VALUES_SOU + \") \"\n SOURCE_CUR.execute(MERGE_FACT_TABLE)\n\n for i in COLUMN_DETAILS:\n if i[1] == 'DATE':\n MERGE_DATE_DIM = \" MERGE INTO \" + TAR_USER.upper() + \".DATE_DIMENSION TAR \" \\\n \" USING (SELECT DISTINCT \" + i[0] + \" FROM \" + SOU_USER.upper() + \".\" + SOU_TABLE_NAME + \") SOU \" \\\n \" ON (TAR.FULL_DATE_ARABIC = TO_CHAR(SOU.\" + i[0] + \", 'DD/MM/YYYY')) \" \\\n \" WHEN NOT MATCHED THEN INSERT \" \\\n \" (TAR.SRG_KEY, TAR.FULL_DATE_ARABIC, TAR.DAY_SHORT, TAR.MONTH_NUM, TAR.MONTH_NAME, TAR.MONTH_SHORT, TAR.YEAR, TAR.DAY_OF_WEEK) \" \\\n \" VALUES \" \\\n \" (\" + TAR_USER.upper() + \".SEQ_DATE_DIMENSION.nextval, \" \\\n \" TO_CHAR(SOU.\" + i[0] + \", 'DD/MM/YYYY'), \" \\\n \" TO_CHAR(SOU.\" + i[0] + \", 'DY'), \" \\\n \" TO_CHAR(SOU.\" + i[0] + \", 'MM'), \" \\\n \" TO_CHAR(SOU.\" + i[0] + \", 'MONTH'), \" \\\n \" TO_CHAR(SOU.\" + i[0] + \", 'MON'), \" \\\n \" TO_CHAR(SOU.\" + i[0] + \", 'YYYY'), \" \\\n \" TO_CHAR(TO_DATE(SOU.\" + i[0] + \", 'DD/MM/RRRR'), 'DD')) \"\n SOURCE_CUR.execute(MERGE_DATE_DIM)\n SOURCE_CONN.commit()\n # <-------------------------------------------------------------->\n\n # <---------------------------------------->\n # <--- check if it's a dimension table. --->\n # <---------------------------------------->\n else:\n # <---------------------------------------------------------------------->\n # <--- check in target database that's already have sequences or not. --->\n # <---------------------------------------------------------------------->\n CHECK_DIM_SEQ = \" SELECT COUNT(*) \" \\\n \" FROM USER_SEQUENCES \" \\\n \" WHERE SEQUENCE_NAME = 'SEQ_\" + TAR_TABLE_NAME.upper() + \"' \"\n TARGET_CUR.execute(CHECK_DIM_SEQ)\n ROWS = TARGET_CUR.fetchall()\n CHECK_DIS = []\n for i in range(len(ROWS)):\n ROW = ROWS[i]\n CHECK_DIS.append(ROW[0])\n\n CHECK_DIM_TABLE = \" SELECT COUNT(*) \" \\\n \" FROM USER_TABLES \" \\\n \" WHERE TABLE_NAME = '\" + TAR_TABLE_NAME.upper() + \"' \"\n TARGET_CUR.execute(CHECK_DIM_TABLE)\n ROWS = TARGET_CUR.fetchall()\n CHECK_DIT = []\n for i in range(len(ROWS)):\n ROW = ROWS[i]\n CHECK_DIT.append(ROW[0])\n # <---------------------------------------------------------------------->\n\n if (CHECK_DIS == [0]) & (CHECK_DIT == [0]):\n # <------------------------------------------------------------>\n # <--- if in target database not have sequences, create it. --->\n # <------------------------------------------------------------>\n CREATE_DIM_SEQ = \" CREATE SEQUENCE \" + TAR_USER.upper() + \".SEQ_\" + TAR_TABLE_NAME + \" \" \\\n \" MINVALUE 1 \" \\\n \" START WITH 1 \" \\\n \" INCREMENT BY 1 \" \\\n \" CACHE 20 \"\n SOURCE_CUR.execute(CREATE_DIM_SEQ)\n # <------------------------------------------------------------>\n\n # <------------------------------->\n # <--- create dimension table. --->\n # <------------------------------->\n CDT_CREATE = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n if NEW_DATA_TYPE[i] == 'DATE':\n CDT_CREATE = CDT_CREATE + \" START_DATE \" + NEW_DATA_TYPE[i] + \" , END_DATE \" + NEW_DATA_TYPE[i]\n\n else:\n CDT_CREATE = CDT_CREATE + \" \" + NEW_COLUMN_NAME[i] + \" \" + NEW_DATA_TYPE[i] + \"(\" + NEW_DATA_LENGTH[\n i] + \") \"\n\n if i < len(NEW_COLUMN_NAME) - 1:\n CDT_CREATE += \",\"\n\n CREATE_DIM_TABLE = \" CREATE TABLE \" + TAR_USER.upper() + \".\" + TAR_TABLE_NAME + \" \" \\\n \" (SRG_KEY INT, \" \\\n \" \" + CDT_CREATE + \" )\"\n SOURCE_CUR.execute(CREATE_DIM_TABLE)\n # <------------------------------->\n\n # <------------------------------->\n # <--- if not, then insert it. --->\n # <------------------------------->\n IDT_INSERT_TAR = \"\"\n\n for i in range(len(NEW_COLUMN_NAME)):\n if NEW_DATA_TYPE[i] != 'DATE':\n IDT_INSERT_TAR = IDT_INSERT_TAR + \" TAR.\" + NEW_COLUMN_NAME[i]\n\n if ((i < len(NEW_COLUMN_NAME) - 1) & (NEW_DATA_TYPE[i] != 'DATE')) & \\\n ~((i == len(NEW_COLUMN_NAME) - 2) & (NEW_DATA_TYPE[len(NEW_COLUMN_NAME) - 1] == 'DATE')):\n IDT_INSERT_TAR += \",\"\n\n IDT_SELECT_SOU = \"\"\n IDT_GROUPBY_SOU = \"\"\n IDT_VALUES_SOU = \"\"\n\n for i in range(len(PICK_COLUMNS)):\n if NEW_DATA_TYPE[i] == 'DATE':\n IDT_SELECT_SOU = IDT_SELECT_SOU + \" MIN(\" + PICK_COLUMNS[i] + \") as START_DATE, MAX(\" + \\\n PICK_COLUMNS[i] + \") as END_DATE \"\n\n else:\n IDT_GROUPBY_SOU = IDT_GROUPBY_SOU + \" \" + PICK_COLUMNS[i]\n IDT_SELECT_SOU = IDT_SELECT_SOU + \" \" + PICK_COLUMNS[i]\n IDT_VALUES_SOU = IDT_VALUES_SOU + \" SOU.\" + PICK_COLUMNS[i]\n\n if i < len(PICK_COLUMNS) - 1:\n IDT_SELECT_SOU += \",\"\n if ((i < len(PICK_COLUMNS) - 1) & (PICK_COLUMNS[i] != 'DATE')) & \\\n ~((i == len(PICK_COLUMNS) - 2) & (NEW_DATA_TYPE[len(PICK_COLUMNS) - 1] == 'DATE')):\n IDT_GROUPBY_SOU += \",\"\n IDT_VALUES_SOU += \",\"\n\n IDT_JOIN = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n for j in range(len(PICK_COLUMNS)):\n if (i == j) & (NEW_DATA_TYPE[i] != 'DATE'):\n IDT_JOIN = IDT_JOIN + \" TAR.\" + NEW_COLUMN_NAME[j] + \" = SOU.\" + PICK_COLUMNS[j] + \" \"\n\n if ((i < len(PICK_COLUMNS) - 1) & (PICK_COLUMNS[i] != 'DATE')) & \\\n ~((i == len(PICK_COLUMNS) - 2) & (NEW_DATA_TYPE[len(PICK_COLUMNS) - 1] == 'DATE')):\n IDT_JOIN += \"AND\"\n\n INSERT_DIM_TABLE = \" MERGE INTO \" + TAR_USER.upper() + \".\" + TAR_TABLE_NAME + \" TAR \" \\\n \" USING (SELECT \" + IDT_SELECT_SOU + \" FROM \" + SOU_USER.upper() + \".\" + SOU_TABLE_NAME + \" GROUP BY \" + IDT_GROUPBY_SOU + \") SOU \" \\\n \" ON (\" + IDT_JOIN + \") \" \\\n \" WHEN NOT MATCHED THEN INSERT (TAR.SRG_KEY,\" + IDT_INSERT_TAR + \", TAR.START_DATE, TAR.END_DATE) \" \\\n \" VALUES \" \\\n \" (\" + TAR_USER.upper() + \".SEQ_\" + TAR_TABLE_NAME + \".nextval, \" \\\n \" \" + IDT_VALUES_SOU + \", SOU.START_DATE, SOU.END_DATE) \"\n SOURCE_CUR.execute(INSERT_DIM_TABLE)\n SOURCE_CONN.commit()\n # <------------------------------->\n\n # <------------------------------------------>\n # <--- if already have it, then merge it. --->\n # <------------------------------------------>\n else:\n MDT_INSERT_TAR = \"\"\n\n for i in range(len(NEW_COLUMN_NAME)):\n if NEW_DATA_TYPE[i] != 'DATE':\n MDT_INSERT_TAR = MDT_INSERT_TAR + \" TAR.\" + NEW_COLUMN_NAME[i]\n\n if ((i < len(NEW_COLUMN_NAME) - 1) & (NEW_DATA_TYPE[i] != 'DATE')) & \\\n ~((i == len(NEW_COLUMN_NAME) - 2) & (NEW_DATA_TYPE[len(NEW_COLUMN_NAME) - 1] == 'DATE')):\n MDT_INSERT_TAR += \",\"\n\n MDT_SELECT_SOU = \"\"\n MDT_GROUPBY_SOU = \"\"\n MDT_VALUES_SOU = \"\"\n\n for i in range(len(PICK_COLUMNS)):\n if NEW_DATA_TYPE[i] == 'DATE':\n MDT_SELECT_SOU = MDT_SELECT_SOU + \" MIN(\" + PICK_COLUMNS[i] + \") as START_DATE, MAX(\" + PICK_COLUMNS[i] + \") as END_DATE \"\n\n else:\n MDT_GROUPBY_SOU = MDT_GROUPBY_SOU + \" \" + PICK_COLUMNS[i]\n MDT_SELECT_SOU = MDT_SELECT_SOU + \" \" + PICK_COLUMNS[i]\n MDT_VALUES_SOU = MDT_VALUES_SOU + \" SOU.\" + PICK_COLUMNS[i]\n\n if i < len(PICK_COLUMNS) - 1:\n MDT_SELECT_SOU += \",\"\n if ((i < len(PICK_COLUMNS) - 1) & (PICK_COLUMNS[i] != 'DATE')) & \\\n ~((i == len(PICK_COLUMNS) - 2) & (NEW_DATA_TYPE[len(PICK_COLUMNS) - 1] == 'DATE')):\n MDT_GROUPBY_SOU += \",\"\n MDT_VALUES_SOU += \",\"\n\n MDT_JOIN = \"\"\n for i in range(len(NEW_COLUMN_NAME)):\n for j in range(len(PICK_COLUMNS)):\n if (i == j) & (NEW_DATA_TYPE[i] == 'DATE'):\n MDT_JOIN = MDT_JOIN + \" TAR.START_DATE = SOU.START_DATE AND TAR.END_DATE = SOU.END_DATE\"\n elif (i == j) & (NEW_DATA_TYPE[i] != 'DATE'):\n MDT_JOIN = MDT_JOIN + \" TAR.\" + NEW_COLUMN_NAME[j] + \" = SOU.\" + PICK_COLUMNS[j] + \" \"\n\n if i < len(NEW_COLUMN_NAME) - 1:\n MDT_JOIN += \"AND\"\n\n MERGE_DIM_TABLE = \" MERGE INTO \" + TAR_USER.upper() + \".\" + TAR_TABLE_NAME + \" TAR \" \\\n \" USING (SELECT \" + MDT_SELECT_SOU + \" FROM \" + SOU_USER.upper() + \".\" + SOU_TABLE_NAME + \" GROUP BY \" + MDT_GROUPBY_SOU + \") SOU \" \\\n \" ON (\" + MDT_JOIN + \") \" \\\n \" WHEN NOT MATCHED THEN INSERT (TAR.SRG_KEY,\" + MDT_INSERT_TAR + \", TAR.START_DATE, TAR.END_DATE) \" \\\n \" VALUES \" \\\n \" (\" + TAR_USER.upper() + \".SEQ_\" + TAR_TABLE_NAME + \".nextval, \" \\\n \" \" + MDT_VALUES_SOU + \", SOU.START_DATE, SOU.END_DATE) \"\n SOURCE_CUR.execute(MERGE_DIM_TABLE)\n SOURCE_CONN.commit()\n # <------------------------------------------>\n\n GET_TABLE_NAME = \" SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = UPPER('\" + TAR_USER.upper() + \"') \"\n TARGET_CUR.execute(GET_TABLE_NAME)\n TABLES = TARGET_CUR.fetchall()\n TAR_TABLE_CUT = []\n for i in range(len(TABLES)):\n TABLE = TABLES[i]\n TAR_TABLE_CUT.append(TABLE[0])\n session['TAR_TABLE_CUT'] = TAR_TABLE_CUT\n\n return render_template('target_data.html', tables=TAR_TABLE_CUT)#, stats=STAT_DICT)\n\n# @app.route('/get_target_table')\n# def getTargetTableName():\n# TAR_USER = session['TAR_USER']\n# TAR_PASS = session['TAR_PASS']\n# TAR_DBURL = (session['TAR_HOST'] + ':' + session['TAR_PORT'] + '/' + session['TAR_SID'])\n#\n# TARGET_CONN = cx_Oracle.connect(TAR_USER, TAR_PASS, TAR_DBURL)\n# TARGET_CUR = TARGET_CONN.cursor()\n#\n# GET_TABLE_NAME = \" SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = UPPER('\" + TAR_USER.upper() + \"') \"\n# TARGET_CUR.execute(GET_TABLE_NAME)\n# TABLES = TARGET_CUR.fetchall()\n# TAR_TABLE_CUT = []\n# for i in range(len(TABLES)):\n# TABLE = TABLES[i]\n# TAR_TABLE_CUT.append(TABLE[0])\n# session['TAR_TABLE_CUT'] = TAR_TABLE_CUT\n#\n# return render_template('target_data.html', tables=TAR_TABLE_CUT)\n\n@app.route('/get_data_target', methods=['GET', 'POST'])\ndef showDataTarget():\n TAR_USER = session['TAR_USER']\n TAR_PASS = session['TAR_PASS']\n TAR_DBURL = (session['TAR_HOST'] + ':' + session['TAR_PORT'] + '/' + session['TAR_SID'])\n\n if request.method == \"POST\":\n TAR_TABLE_NAME = request.form.get('table_selected')\n session['TTN'] = TAR_TABLE_NAME\n\n TARGET_CONN = cx_Oracle.connect(TAR_USER, TAR_PASS, TAR_DBURL)\n TARGET_CUR = TARGET_CONN.cursor()\n\n GET_DATA = \" SELECT * FROM \" + TAR_TABLE_NAME + \" \"\n TARGET_CUR.execute(GET_DATA)\n DATA = TARGET_CUR.fetchall()\n DATA_CUT = []\n for i in DATA:\n DATA_CUT.append(i)\n\n GET_COLUMN_NAME = \" SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '\" + TAR_TABLE_NAME + \"' ORDER BY COLUMN_ID \"\n TARGET_CUR.execute(GET_COLUMN_NAME)\n COLUMNS = TARGET_CUR.fetchall()\n COL_CUT = []\n for i in range(len(COLUMNS)):\n COL = COLUMNS[i]\n COL_CUT.append(COL[0])\n\n TAR_TABLE_CUT = session['TAR_TABLE_CUT']\n\n return render_template('target_data.html', columns=COL_CUT, data=DATA_CUT, tables=TAR_TABLE_CUT, tbn=TAR_TABLE_NAME)\n\n@app.route('/export_csv_file')\ndef exportCSVfile():\n TAR_USER = session['TAR_USER']\n TAR_PASS = session['TAR_PASS']\n TAR_DBURL = (session['TAR_HOST'] + ':' + session['TAR_PORT'] + '/' + session['TAR_SID'])\n TTN = session['TTN']\n\n TARGET_CONN = cx_Oracle.connect(TAR_USER, TAR_PASS, TAR_DBURL)\n TARGET_CUR = TARGET_CONN.cursor()\n\n SELECT_COLUMN_EXPORT = \" SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '\" + TTN + \"' ORDER BY COLUMN_ID \"\n TARGET_CUR.execute(SELECT_COLUMN_EXPORT)\n COLUMNS = TARGET_CUR.fetchall()\n COL_CUT = []\n for i in range(len(COLUMNS)):\n COL = COLUMNS[i]\n COL_CUT.append(COL[0])\n\n SELECT_TABLE_EXPORT = \" SELECT * FROM \"+ TTN.upper() +\" \"\n TARGET_CUR.execute(SELECT_TABLE_EXPORT)\n DATA = TARGET_CUR.fetchall()\n\n FILENAME = \"\" + TTN + \".csv\"\n CSV_FILE = open(FILENAME, 'w', newline='')\n if DATA:\n WRITER = csv.writer(CSV_FILE)\n WRITER.writerow(COL_CUT)\n WRITER.writerows(DATA)\n session['FILENAME'] = FILENAME\n\n return render_template('export_files.html', filename=FILENAME)\n\n@app.route('/download_file', methods=['GET', 'POST'])\ndef downloadFile():\n if request.method == 'POST':\n FILENAME = session['FILENAME']\n testfile = '../PROJECT-HTWRDS/'+ FILENAME\n return send_file(testfile, as_attachment=True, mimetype='text/csv')\n\n\n# <--- RUN WEB-APP --->\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":31328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"191332090","text":"vijiammu=input()\nfish=0\nfor i in range(0,len(vijiammu)-1):\n for j in range(i+1,len(vijiammu)):\n if vijiammu[i]=0 and r=0 and r right: self.res.append(values)\n for j in range(left, right+1):\n if self.isPal[left][j] == 1: self.dfs(values+[self.s[left:j+1]], j+1, right)\n \n \n def dfs(self, s, e):\n res = []\n for j in range(s, e+1):\n if self.isPal[s][j] == 1: \n if j == e: \n res.append([self.s[s:]])\n else:\n temp = self.dfs(j+1, e)\n for t in temp:\n res.append([self.s[s:j+1]]+t)\n return res\n \n \n# Solution 2\nclass Solution(object):\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n self.s = s\n # self.isPal = self.isPalindrome()\n self.memo = {}\n return self.dfs(0, len(self.s)-1)\n return self.res\n \n def isPal(self, s, e):\n while s < e:\n if self.s[s]!=self.s[e]: return False\n s+=1\n e-=1\n return True\n \n \n def dfs(self, s, e):\n if tuple([s,e]) in self.memo: return self.memo[tuple([s,e])]\n res = []\n for j in range(s, e+1):\n if self.isPal(s,j): \n if j == e: \n res.append([self.s[s:e+1]])\n else:\n temp = self.dfs(j+1, e)\n for t in temp:\n res.append([self.s[s:j+1]]+t)\n self.memo[tuple([s,e])] = res\n return res\n","sub_path":"LEETCODE/0131. Palindrome Partitioning.py","file_name":"0131. Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"401177031","text":"import hashlib\nimport string\n\nfrom lokp.config.files import valid_mime_extensions\n\n\ndef get_valid_file_extension(request, mimetype):\n \"\"\"\n Helper function to return the predefined file extension for a mimetype.\n Also used to check valid file types (return None if not supported)\n \"\"\"\n vme = valid_mime_extensions(request)\n try:\n return vme[mimetype]\n except KeyError:\n return None\n\n\ndef get_file_size(file):\n \"\"\"\n Return the size of a file.\n \"\"\"\n file.seek(0, 2) # Seek to the end of the file\n size = file.tell() # Get the position of EOF\n file.seek(0) # Reset the file position to the beginning\n return size\n\n\ndef clean_filename(filename):\n \"\"\"\n Return a clean filename by removing all invalid characters from the input.\n \"\"\"\n # Then make sure the filename is valid by removing all invalid characters\n valid_chars = frozenset(\"-_.() %s%s\" % (\n string.ascii_letters, string.digits))\n filename = ''.join(\n c for c in filename if c in valid_chars)\n if filename == '':\n # If all the characters were removed, use a default filename\n filename = 'defaultfilename'\n return filename\n\n\ndef file_buffer(f, chunk_size=10000):\n \"\"\"\n Helper function to process a file chunkwise\n \"\"\"\n while True:\n chunk = f.read(chunk_size)\n if not chunk:\n break\n yield chunk\n\n\ndef get_file_hash(filepath):\n \"\"\"\n Calculate the hash digest of a file.\n \"\"\"\n hasher = hashlib.md5()\n with open(filepath, 'rb') as afile:\n buf = afile.read()\n hasher.update(buf)\n return hasher.hexdigest()\n\n\ndef get_folders_from_identifier(identifier):\n \"\"\"\n Return the folder structure based on an identifier.\n Folder 1: the first two digits of the identifier\n Folder 2: the third digit of the identifier\n \"\"\"\n return identifier[:2], identifier[2:3]\n","sub_path":"lokp/utils/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"442126162","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QListView, QTreeView, QStyledItemDelegate\nfrom PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt\nfrom PyQt5.QtQml import QQmlApplicationEngine, QQmlContext\n\nclass CustomModel(QAbstractItemModel):\n\tNodeRole = Qt.UserRole + 1\n\tdef __init__(self, in_nodes):\n\t\tsuper().__init__()\n\t\tself._root = CustomNode(None)\n\t\tfor node in in_nodes:\n\t\t\tself._root.addChild(node)\n\n\tdef addChild(self, in_node, in_parent):\n\t\tif not in_parent or not in_parent.isValid():\n\t\t\tparent = self._root\n\t\telse:\n\t\t\tparent = in_parent.internalPointer()\n\t\tparent.addChild(in_node)\n\n\tdef index(self, in_row, in_column, in_parent=None):\n\t\tif not in_parent or not in_parent.isValid():\n\t\t\tparent = self._root\n\t\telse:\n\t\t\tparent = in_parent.internalPointer()\n\n\t\tif not QAbstractItemModel.hasIndex(self, in_row, in_column, in_parent):\n\t\t\treturn QModelIndex()\n\n\t\tchild = parent.child(in_row)\n\t\tif child:\n\t\t\treturn QAbstractItemModel.createIndex(self, in_row, in_column, child)\n\t\telse:\n\t\t\treturn QModelIndex()\n\n\tdef parent(self, in_index):\n\t\tif in_index.isValid():\n\t\t\tp = in_index.internalPointer().parent()\n\t\t\tif p:\n\t\t\t\treturn QAbstractItemModel.createIndex(self, p.row(), 0, p)\n\t\treturn QModelIndex()\n\n\tdef columnCount(self, in_index):\n\t\tif in_index.isValid():\n\t\t\treturn in_index.internalPointer().columnCount()\n\t\treturn self._root.columnCount()\n\n\tdef data(self, in_index, role=None):\n\t\tif not in_index.isValid():\n\t\t\treturn None\n\t\tnode = in_index.internalPointer()\n\t\tif role == CustomModel.NodeRole:\n\t\t\t#print(node.data(in_index.column()))\n\t\t\treturn node.data(in_index.column())\n\t\treturn None\n\n\tdef rowCount(self, in_index):\n\t\tif in_index.isValid():\n\t\t\treturn in_index.internalPointer().childCount()\n\t\treturn self._root.childCount()\n\n\tdef roleNames(self):\n\t\treturn { CustomModel.NodeRole: b'node' }\n\n\nclass CustomNode():\n\tdef __init__(self, in_data):\n\t\tself._data = in_data\n\t\tif type(in_data) == tuple:\n\t\t\tself._data = list(in_data)\n\t\tif type(in_data) == str or not hasattr(in_data, '__getitem__'):\n\t\t\tself._data = [ in_data ]\n\t\t\n\t\tself._columncount = len(self._data)\n\t\tself._children = []\n\t\tself._parent = None\n\t\tself._row = 0\n\n\tdef childCount(self):\n\t\treturn len(self._children)\n\n\tdef data(self, in_column):\n\t\tif in_column >= 0 and in_column < len(self._data):\n\t\t\treturn self._data[in_column]\n\n\tdef columnCount(self):\n\t\treturn self._columncount\n\n\tdef child(self, in_row):\n\t\tif in_row >=0 and in_row < self.childCount():\n\t\t\treturn self._children[in_row]\n\n\tdef parent(self):\n\t\treturn self._parent\n\n\tdef row(self):\n\t\treturn self._row\n\n\tdef addChild(self, in_child):\n\t\tin_child._parent = self\n\t\tin_child._row = len(self._children)\n\t\tself._children.append(in_child)\n\t\tself._columncount = max(in_child.columnCount(), self._columncount)\n\nclass CustomDelgate(QStyledItemDelegate):\n\t\"\"\"docstring for sampleItemDelgate\"\"\"\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\t\n\tdef paint(self, painter, option, index):\n\t\tdata = index.data()\n\t\tmodel = index.model()\n\t\tpainter.save()\n\t\t\n\t\tpainter.drawText(option.rect, 0, data)\n\t\tpainter.restore()\n\t\t\n\n\nif __name__ == '__main__':\n\tapp = QApplication(sys.argv)\n\titems = []\n\tfor i in 'abc':\n\t\titems.append( CustomNode(i))\n\t\titems[-1].addChild( CustomNode(['d', 'e', 'f']))\n\t\titems[-1].addChild( CustomNode(['g', 'h', 'i']))\n\t\n\tmodel = CustomModel(items)\n\t#delegate = CustomDelgate()\n\t\n\t'''\n\tview = QListView()\n\tview = QTreeView()\n\tview.setModel(model)\n\tview.setItemDelegate(delegate)\n\tview.show()\n\t'''\n\tengine = QQmlApplicationEngine()\n\tctx = engine.rootContext()\n\t\n\tctx.setContextProperty(\"myModel\", model)\n\tengine.load(\"custom_model2.qml\")\n\tengine.quit.connect(app.quit)\n\t\n\tsys.exit(app.exec_())\n","sub_path":"custom_model2.py","file_name":"custom_model2.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"493149417","text":"\"\"\"\nExercise B03\nWritten By: Jan Balk\n\"\"\"\n\n# Write a function that calculates the factorial of n and makes use of recursion\n# hint think about the recursion exit condition (the last number you multiply by is 1)\n# hint think about the relationship of n to the next number you multiply it by in a factorial chain (n and n-1)\n\ndef factorial(n):\n if(n <= 1):\n return 1\n else:\n return n * factorial(n-1)\n\nprint(factorial(6))\n","sub_path":"prog_sessions/PR2_Files/Exercises B/B03.py","file_name":"B03.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"137613158","text":"# pylint: disable=invalid-name,no-self-use\nimport argparse\nimport json\n\nfrom flaky import flaky\n\nfrom allennlp.commands.evaluate import evaluate_from_args, Evaluate\nfrom allennlp.common.testing import AllenNlpTestCase\n\n\nclass TestEvaluate(AllenNlpTestCase):\n def setUp(self):\n super().setUp()\n\n self.parser = argparse.ArgumentParser(description=\"Testing\")\n subparsers = self.parser.add_subparsers(title='Commands', metavar='')\n Evaluate().add_subparser('evaluate', subparsers)\n\n @flaky\n def test_evaluate_from_args(self):\n kebab_args = [\"evaluate\", str(self.FIXTURES_ROOT / \"bidaf\" / \"serialization\" / \"model.tar.gz\"),\n str(self.FIXTURES_ROOT / \"data\" / \"squad.json\"),\n \"--cuda-device\", \"-1\"]\n\n args = self.parser.parse_args(kebab_args)\n metrics = evaluate_from_args(args)\n assert metrics.keys() == {'span_acc', 'end_acc', 'start_acc', 'em', 'f1'}\n\n def test_output_file_evaluate_from_args(self):\n output_file = str(self.TEST_DIR / \"metrics.json\")\n kebab_args = [\"evaluate\", str(self.FIXTURES_ROOT / \"bidaf\" / \"serialization\" / \"model.tar.gz\"),\n str(self.FIXTURES_ROOT / \"data\" / \"squad.json\"),\n \"--cuda-device\", \"-1\",\n \"--output-file\", output_file]\n args = self.parser.parse_args(kebab_args)\n computed_metrics = evaluate_from_args(args)\n with open(output_file, 'r') as file:\n saved_metrics = json.load(file)\n assert computed_metrics == saved_metrics\n","sub_path":"code/AllenNLP_Modifications/allennlp_selmo30k/build/lib/allennlp/tests/commands/evaluate_test.py","file_name":"evaluate_test.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"392218363","text":"from classes.Product import Product\nimport pandas as pd\n\n\n# An inventory of products created from an Excel spreadsheet\nclass Inventory:\n def __init__(self, inventory_file):\n # Excel file with inventory data\n self.inventory_file = inventory_file\n # List of all product objects in the inventory\n self.product_list = []\n # Products that are at or below reorder quantity\n self.reorder_products = []\n\n # Read the current status of all products in the inventory and update their objects\n def update(self):\n # Read the excel file, dropping any rows that are missing all data\n inventory_df = pd.read_excel(self.inventory_file).dropna(how='all')\n\n # Replace spaces with underscores in column names for attribute access\n inventory_df.columns = [c.replace(' ', '_') for c in inventory_df.columns]\n\n # Iterate through products in spreadsheet\n for index, product in inventory_df.iterrows():\n # Bool to keep track of whether each item has already been inventoried\n new_item = True\n\n for existing_product in self.product_list:\n # If product in the spreadsheet has already been inventoried\n if product.Product == existing_product.name:\n # Update the stock quantity for that item\n existing_product.in_stock = product.In_Stock\n # This item has already been inventoried, so don't add it to inventory\n new_item = False\n if new_item:\n try:\n # If the item wasn't already inventoried, create a new product object\n self.product_list.append(Product(product.Product, int(product.In_Stock), int(product.Reorder_At)))\n # If the stock values can't be converted to int, they are invalid or missing and the row should be ignored\n except ValueError:\n continue\n\n # If a product quantity is at or below the warning threshold and a warning email has not been sent yet, send one\n def notification_needed(self):\n # Clear old reorder product list\n self.reorder_products.clear()\n\n for product in self.product_list:\n if product.in_stock <= product.reorder_at:\n # Repopulate the reorder products list\n self.reorder_products.append(product)\n else:\n # Reset notification because it is above restock quantity\n product.notified = False\n\n # If there are any items that need reordering that have not been notified yet, send email\n for product in self.reorder_products:\n if not product.notified:\n return True\n return False\n","sub_path":"classes/Inventory.py","file_name":"Inventory.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"421933351","text":"from py_read_serial import *\n'''\nPut all the sensor names in this list here, and plug them in accordingly.\nMake sure they are plugged in correctly, otherwise your data will be wrong.\n'''\nsensors = ['CO2 Sensor']\n\nwhile 1:\n sensor = readPins()\n ''' This for loop, loops though all the sensors in the \"sensors\" list,\n ensuring all sensors print out values. '''\n for x in range(len(sensors)):\n ''' The if statement checks if the serial signals ID,\n the first letter of the string sent over,\n corresponds with the number the sensor is in the list. '''\n if int(sensor['num']) == x:\n if(sensor[num] == 0):\n print('The CO2 Content of the surrounding environment is',sensor['value'],'ppm (parts per million)')\n if(sensor[num] == 1):\n print('The current temperature is',temp,'*C')\n ''' A print statement to display the values, according to the sensor. '''\n print('The',str(sensors[x]),'signal is',sensor['value'])\n","sub_path":"sensors.py","file_name":"sensors.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"504358273","text":"'''\nRegex Version of strip()\nWrite a function that takes a string and does the same thing as the strip() string method.\nIf no other arguments are passed other than the string to strip,\nthen whitespace characters will be removed from the beginning and end of the string.\nOtherwise, the characters specified in the second argument to the function will be removed from the string.\n'''\n\nimport re\n\ndef regex_strip(string: str, chars = '') -> str :\n \n stripped = ''\n if chars == '':\n # whitespace chars removed from beginning and end of string\n whitespace_begin_regex = re.compile(r'^\\s+')\n whitespace_end_regex = re.compile(r'\\s+$')\n \n whitespace_begin_stripped = whitespace_begin_regex.sub('',string)\n stripped = whitespace_end_regex.sub('',whitespace_begin_stripped)\n else:\n # match any characters not between brackets\n remove_chars_regex = re.compile('[^' + chars + ']')\n\n stripped = ''\n for c in remove_chars_regex.findall(string):\n stripped += c\n\n return stripped\n\ninput_string = ' 123412asdfawleirj 1231 asdfasd '\nchars_to_strip = ' 14adijf'\n\nprint(regex_strip(input_string))\nprint(regex_strip(input_string, chars_to_strip))\n\n","sub_path":"regex_strip.py","file_name":"regex_strip.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"328668536","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\"\"\"\nFlatten Binary Tree to Linked List\nTime - O(N)\nSpace - O(1)\n\"\"\"\nclass Solution:\n def flatten(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n def dfs(root):\n if not root:\n return\n if not root.left and not root.right:\n return root\n l=dfs(root.left)\n r=dfs(root.right)\n if l:\n l.right=root.right\n root.right=root.left\n root.left=None\n return r if r else l\n return dfs(root)","sub_path":"Flatten Binary Tree to Linked List.py","file_name":"Flatten Binary Tree to Linked List.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"444813042","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 9 14:29:06 2016\n@author: soma0sd\n\ncolor map을 만드는 방법\n@ 이전 주차의 모듈을 그대로 적용\n\"\"\"\nimport tkinter as tk\nimport numpy as np\n\n\n\"\"\"\n다른 문서에서도 이용할 수 있도록 클레스를 제작한다\n\"\"\"\nclass cmap:\n def __init__(self, points, grid):\n d = len(grid)\n data = {}\n for i, x in enumerate(grid):\n pos = i/d\n for j in range(len(points)-1):\n if points[j][0] <= pos <= points[j+1][0]:\n ratio = (pos-points[j][0])/(points[j+1][0]-points[j][0])\n rgbi = np.array(points[j][1])\n rgbf = np.array(points[j+1][1])\n rgbd = ratio*(rgbf-rgbi)\n rgb = rgbi+rgbd\n c = \"#{:02X}{:02X}{:02X}\".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))\n data[x] = c\n self.map = data\n\n def get_colorcode(self, x):\n return self.map[x]\n\n\nif __name__ == '__main__':\n \"\"\"\n 초기조건\n 웹 색상을 기준으로 다중 포인트 그래디언트 생성\n\n @ point\n 각 컬러세트는 해당 포인트가 위치하는 [0, 1]의 부동소수점,\n 해당하는 [0, 255]의 정수형 RGB 색상값으로 이루어져 있다.\n\n @ grid\n 나열 가능한 숫자형 변수\n \"\"\"\n point = [[0, (0, 0, 0)], [0.25, (255, 0, 0)],\n [0.75, (0, 0, 255)], [1,(255, 255, 0)]]\n grid = np.arange(50, 255, 1)\n\n \"\"\"\n tkinter의 Canvas에 적용한 예\n \"\"\"\n root = tk.Tk()\n root.title('Color mapping')\n canvas = tk.Canvas(root, width=300, height=150, bg='#FFF')\n canvas.pack()\n _ = cmap(point, grid)\n for x in grid:\n canvas.create_rectangle(x, 50, x+5, 100,fill=_.get_colorcode(x), width=0)\n root.mainloop()\n","sub_path":"W11/lib_ColorMap.py","file_name":"lib_ColorMap.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"473448815","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport numpy as np\n\n#DIAGONAL PRINCIPAL\ndef somaDiagonal1(a):\n soma=0\n for i in range (0, a.shape[0],1):\n soma=soma+a[i,i]\n return soma\n \n#DIAGONAL SECUNDÁRIA\ndef somaDiagonal2(a):\n soma=0\n i=0\n j=a.shape[0]-1\n while j>=0:\n soma=soma+a[i,j]\n i=i+1\n j=j-1\n return soma \n \n#SOMA DAS LINHAS (PIOR PARTE)\ndef somaLinhas(a):\n l=[]\n for i in range(0,a.shape[0],1):\n soma=0\n for j in range (0,a.shape[1],1):\n soma=soma+a[i,j]\n l.append (soma)\n return l\n\n#SOMA DAS COLUNAS (PIOR PARTE 2)\ndef somaColunas(a):\n c=[]\n for j in range (0,a.shape[1],1):\n soma=0\n for i in range (0,a.shape[0],1):\n soma=soma+a[i,j]\n c.append (soma)\n return c\n\n#QUADRADO MÁGICO, SIM OU NÃO? EIS A QUESTÃO\ndef quadradoMagico(a):\n sdp=somaDiagonal1(a)\n sds=somaDiagonal2(a)\n sl=somaLinhas(a)\n sc=somaColunas(a)\n cont=0\n for i in range (0, len(sl),1):\n if sdp==sds==sl[i]==sc[i]:\n cont=cont+1\n if cont==len(sl):\n return True\n else:\n return False\n \n#PROGRAMA PRINCIPAL \nn=input('Digite o tamanho da matriz:')\na=np.zeros((n,n))\nfor i in range (0,a.shape[0],1):\n for j in range (0,a.shape[1],1):\n a[i,j]=input('Digite um elemento da matriz a:')\n\nif quadradoMagico (a):\n print ('S')\nelse:\n print ('N')\n ","sub_path":"moodledata/vpl_data/53/usersdata/68/21355/submittedfiles/matriz2.py","file_name":"matriz2.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"223801126","text":"from getopt import *\nfrom time import *\nfrom numpy import *\nimport sys\nfrom random import *\nfrom copy import *\nimport random\nfrom collections import defaultdict\nimport numpy\n\nSEEDS = set() # the seed set\nVERTEX_NUM = 0 # number of vertex\nEDGE_NUM = 0 # number of edge\n\n\n# Read the network file\ndef network_reader(file_path):\n global VERTEX_NUM\n global EDGE_NUM\n data = str.split(open(file_path).readline())\n VERTEX_NUM, EDGE_NUM = int(data[0]), int(data[1])\n graph_edge = loadtxt(file_path, skiprows=1)\n return graph_edge\n\n\n# Read the seed file\ndef seed_reader(file_path):\n lines = open(file_path).readlines()\n for line in lines:\n SEEDS.add(int(line.split()[0]))\n\n\n# Read the sys arguments\ndef sys_reader():\n options, args = getopt(sys.argv[1:], \"i:s:m:t:\", [])\n network_path, seed_path, diffusion_model = \"\", \"\", \"\"\n termination = 0\n for syntax, value in options:\n # absolute path of the social network file\n if syntax in \"-i\":\n network_path = value\n # absolute path of the seed set file\n if syntax in \"-s\":\n seed_path = value\n # IC / LT\n if syntax in \"-m\":\n diffusion_model = value\n # time limitation\n if syntax in \"-t\":\n termination = int(value)\n return network_path, seed_path, diffusion_model, termination\n\n\n# IC model\ndef ic_model(target_graph, seed_set):\n active_set = deepcopy(seed_set)\n actived_set = deepcopy(seed_set)\n count = len(active_set)\n length = count\n new_active_set = set()\n while length != 0:\n new_active_set.clear()\n for item in active_set:\n for neighbor in target_graph.edges[int(item) - 1]:\n if random.random() < target_graph.weight[(item - 1, neighbor)]:\n if neighbor + 1 not in actived_set:\n actived_set.add(neighbor + 1)\n new_active_set.add(neighbor + 1)\n else:\n pass\n count += len(new_active_set)\n active_set = deepcopy(new_active_set)\n length = len(active_set)\n return count\n\n\n# LT model\ndef lt_model(target_graph, seed_set):\n active_set = deepcopy(seed_set)\n actived_set = deepcopy(seed_set)\n count = len(active_set)\n threshold = defaultdict(int)\n for i in range(len(target_graph.nodes)):\n threshold[i] = random.random()\n if threshold[i] == 0:\n active_set.add(i)\n actived_set.add(i)\n new_active_set = set()\n while len(active_set) != 0:\n new_active_set.clear()\n for item in active_set:\n for neighbor in target_graph.edges[item - 1]:\n weight_counted_list = [target_graph.weight[(neighbour, neighbor)] for neighbour in\n target_graph.in_edges[neighbor] if neighbour + 1 in actived_set]\n tol_weight = numpy.sum(weight_counted_list, dtype=float64)\n if tol_weight > threshold[neighbor]:\n if neighbor + 1 not in actived_set:\n new_active_set.add(neighbor + 1)\n actived_set.add(neighbor + 1)\n count += len(new_active_set)\n active_set = deepcopy(new_active_set)\n return count\n\n\nclass Graph:\n nodes = set()\n edges = []\n in_edges = []\n weight = {}\n\n def __init__(self, numpy_array, num_vertex):\n array_length = len(numpy_array)\n for i in range(num_vertex):\n self.add_node(i)\n for i in range(array_length):\n self.add_edge(numpy_array[i][0], numpy_array[i][1], numpy_array[i][2])\n\n def add_edge(self, from_node, to_node, weight):\n from_node = int(from_node)\n to_node = int(to_node)\n self.weight[from_node - 1, to_node - 1] = weight\n self.edges[from_node - 1].append(to_node - 1)\n self.in_edges[to_node - 1].append(from_node - 1)\n\n def add_node(self, value):\n self.nodes.add(value)\n self.edges.append([])\n self.in_edges.append([])\n\n\nif __name__ == '__main__':\n START_TIME = time()\n network_path, seed_path, diffusion_model, time_budget = sys_reader()\n graph_numpy = network_reader(network_path)\n seed_reader(seed_path)\n graph_class = Graph(graph_numpy, VERTEX_NUM)\n sum, iter = 0, 0\n while True:\n if diffusion_model == \"IC\":\n count = ic_model(graph_class, SEEDS)\n elif diffusion_model == \"LT\":\n count = lt_model(graph_class, SEEDS)\n sum = count + sum\n iter += 1\n if time_budget - 3 < time() - START_TIME:\n break\n print(sum / iter)\n","sub_path":"IMP/ISE.py","file_name":"ISE.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"601670877","text":"from django.conf.urls import url\nfrom basic_app import views\n\n#This name space is for Template Tagging\napp_name = 'basic_app'\n\nurlpatterns = [\n url('relative/',views.relative,name = 'relative'),\n url('other/',views.other,name='other'),\n]\n","sub_path":"learning_templates/basic_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"390780001","text":"# --------------\n# --------------\r\n# Import the required Libraries\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport calendar\r\nimport seaborn as sns\r\nimport warnings\r\nfrom math import ceil\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n# https://seaborn.pydata.org/tutorial/categorical.html\r\n# https://www.drawingfromdata.com/setting-figure-size-using-seaborn-and-matplotlib\r\n\r\n# Generate a line chart that visualizes the readings in the months\r\n\r\ndef line_chart(df,period,col):\r\n \"\"\" A line chart that visualizes the readings in the months\r\n \r\n This function accepts the dataframe df ,period(day/month/year) and col(feature), which plots the aggregated value of the feature based on the periods. Ensure the period labels are properly named.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n period - Period of time over which you want to aggregate the data\r\n col - Feature of the dataframe\r\n \r\n \"\"\"\r\n if period=='day':\r\n df['period'] = df['Date/Time']\r\n plt.xticks(rotation=90)\r\n elif period=='month':\r\n df['period'] = df['Date/Time'].apply(lambda x:pd.to_datetime(x).month)\r\n plt.xticks(np.arange(1,13), calendar.month_name[1:13], rotation=90)\r\n elif period == 'year':\r\n df['period'] = df['Date/Time'].apply(lambda x:pd.to_datetime(x).year)\r\n plt.xticks(rotation=90)\r\n \r\n plt.plot(df.groupby(['period'])[col].mean())\r\n \r\n plt.title('Temperature Trend, 2012')\r\n plt.xlabel(period)\r\n plt.ylabel(col)\r\n plt.show()\r\n \r\n\r\n\r\n\r\n\r\n\r\n# Function to perform univariate analysis of categorical columns\r\ndef plot_categorical_columns(df):\r\n \"\"\" Univariate analysis of categorical columns\r\n \r\n This function accepts the dataframe df which analyzes all the variable in the data and performs the univariate analysis using bar \r\n plot.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n \r\n \"\"\"\r\n categorical_columns = df.select_dtypes(include='object')\r\n\r\n for column in categorical_columns:\r\n df[column].value_counts(ascending=False).plot(kind='bar',figsize=(10,8),rot=90)\r\n\r\n \"\"\"\r\n print(df.shape)\r\n \r\n sub_plot_total = len(categorical_columns)\r\n sub_plot_columns = 2\r\n sub_plot_rows = round(sub_plot_total / 2)\r\n #fig, ax = plt.subplots(sub_plot_rows,sub_plot_columns, figsize=(20,10))\r\n print(sub_plot_total)\r\n #print(ax)\r\n \r\n #print(type(categorical_columns))\r\n #print(categorical_columns.shape)\r\n #print(categorical_columns.columns)\r\n \"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Function to plot continous plots\r\ndef plot_cont(df,plt_typ):\r\n \"\"\" Univariate analysis of Numerical columns\r\n \r\n This function accepts the dataframe df, plt_type(boxplot/distplot) which analyzes all the variable in the data and performs the univariate analysis using boxplot or distplot plot.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n plt_type - type of plot through which you want to visualize the data\r\n \r\n \"\"\"\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Function to plot grouped values based on the feature\r\ndef group_values(df,col1,agg1,col2):\r\n \"\"\" Agrregate values by grouping\r\n \r\n This function accepts a dataframe, 2 column(feature) and aggregated function(agg1) which groupby the dataframe based on the column and plots the bar plot.\r\n \r\n Keyword arguments:\r\n df - Pandas dataframe which has the data.\r\n col1 - Feature of the dataframe on which values will be aggregated.\r\n agg1 - Dictionary of aggregate functions with feature as the key and func as the value\r\n col2 - Feature of the dataframe to be plot against grouped data.\r\n \r\n Returns:\r\n grouping - Dataframe with all columns on which it is grouped on.\r\n \"\"\"\r\n df.groupby(col1).agg(agg1)[col2].plot(kind='bar')\r\n \r\n\r\n\r\n\r\n\r\n# Read the Data and pass the parameter as parse_dates=True, index_col='Date/Time'\r\nweather_df = pd.read_csv(path,sep=',',index_col='Date/Time',parse_dates=True)\r\n#print(weather_df.select_dtypes(include='object'))\r\n#print(weather_df.select_dtypes(include='number'))\r\n\r\n\r\n# Lets try to generate a line chart that visualizes the temperature readings in the months.\r\n# Call the function line_chart() with the appropriate parameters.\r\nweather_df.reset_index(inplace=True)\r\n#line_chart(weather_df,'month','Temp (C)')\r\n\r\n# Now let's perform the univariate analysis of categorical features.\r\n# Call the \"function plot_categorical_columns()\" with appropriate parameters.\r\nweather_df.set_index('Date/Time',inplace=True)\r\n#plot_categorical_columns(weather_df)\r\n\r\n\r\n# Let's plot the Univariate analysis of Numerical columns.\r\n# Call the function \"plot_cont()\" with the appropriate parameters to plot distplot\r\n\r\n\r\n\r\n# Call the function \"plot_cont()\" with the appropriate parameters to plot boxplot\r\n\r\n\r\n# Groupby the data by Weather and plot the graph of the mean visibility during different weathers. Call the function group_values to plot the graph.\r\n# Feel free to try on diffrent features and aggregated functions like max, min.\r\nweather_df.groupby('Weather').agg({'Temp (C)':'mean','Wind Spd (km/h)':'mean','Dew Point Temp (C)':'mean','Rel Hum (%)':'mean','Wind Spd (km/h)':'mean','Visibility (km)':'mean','Stn Press (kPa)':'mean'})['Visibility (km)'].plot(kind='bar',figsize=(10,8),rot=90)\r\n\n\n\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"575218170","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom discuzx_tools.conf.config import config\n\n# 默认100分钟\nUNIX_TIME_TTL = 6000\n\nACCESS_KEY = config.access_key\nSECRET_KEY = config.secret_key\n\n# 默认私有空间\nBUCKET_NAME = config.bucket_name\n\n# \"7xo804.com1.z0.glb.clouddn.com\"\nBUCKET_DOMAIN = config.bucket_domain or \"source.ikuanyu.com\"\n\n# 默认公共空间\nPUBLIC_BUCKET_NAME = \"\"\nPUBLIC_BUCKET_DOMAIN = \"\"\n","sub_path":"discuzx_tools/conf/store_config.py","file_name":"store_config.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"140377092","text":"from datetime import datetime, timedelta\nimport csv\nimport pandas as pd\nimport random as r\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import f1_score, make_scorer, balanced_accuracy_score\nimport pickle\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\n'''\nThis first large code segment is used to build the compiled_data.csv file\nthat is used to build the complete model\n\nThe next four segments read in the csv data from each relabeled file\n'''\n\n# Open file m_dis.csv as f. with statement is used to not have to close the file later\nwith open('m_dis.csv', newline='') as f:\n # csv.reader(csvfile) will return a reader object \n #which will iterate over lines in the given csvfile\n reader = csv.reader(f)\n \n # Creates a list of lists [[10,1],[9,2],[8,3]]\n m_dis_data = list(reader)\n\nwith open('b_imp.csv', newline='') as f:\n reader = csv.reader(f)\n b_imp_data = list(reader)\n\nwith open('l_valve.csv', newline='') as f:\n reader = csv.reader(f)\n l_valve_data = list(reader)\n\nwith open('b_valve.csv', newline='') as f:\n reader = csv.reader(f)\n b_valve_data = list(reader)\n\n\n# The next four segments change the datetime from each csv data from \n# strings into datetime objeccts so that they can be organized when compiled\n\n\nfor i in range(len(m_dis_data)):\n\n # Iterates through each line in the csv or list in this case\n # [i] in this case is the list within a list, [0] is the date stap im guessing\n # it would be the first column in the csv [0:4] they are slicing the string or whatever is \n # in the column\n year = int(m_dis_data[i][0][0:4])\n month = int(m_dis_data[i][0][5:7])\n day = int(m_dis_data[i][0][8:10])\n hour = int(m_dis_data[i][0][11:13])\n minute = int(m_dis_data[i][0][14:16])\n seconds = int(m_dis_data[i][0][17:19])\n # they reformat the [row][first column]\n m_dis_data[i][0] = datetime(year,month,day,hour,minute,seconds)\n\nfor i in range(len(b_imp_data)):\n\n year = int(b_imp_data[i][0][0:4])\n month = int(b_imp_data[i][0][5:7])\n day = int(b_imp_data[i][0][8:10])\n hour = int(b_imp_data[i][0][11:13])\n minute = int(b_imp_data[i][0][14:16])\n seconds = int(b_imp_data[i][0][17:19])\n b_imp_data[i][0] = datetime(year,month,day,hour,minute,seconds)\n\nfor i in range(len(l_valve_data)):\n\n year = int(l_valve_data[i][0][0:4])\n month = int(l_valve_data[i][0][5:7])\n day = int(l_valve_data[i][0][8:10])\n hour = int(l_valve_data[i][0][11:13])\n minute = int(l_valve_data[i][0][14:16])\n seconds = int(l_valve_data[i][0][17:19])\n l_valve_data[i][0] = datetime(year,month,day,hour,minute,seconds)\n\nfor i in range(len(b_valve_data)):\n\n year = int(b_valve_data[i][0][0:4])\n month = int(b_valve_data[i][0][5:7])\n day = int(b_valve_data[i][0][8:10])\n hour = int(b_valve_data[i][0][11:13])\n minute = int(b_valve_data[i][0][14:16])\n seconds = int(b_valve_data[i][0][17:19])\n b_valve_data[i][0] = datetime(year,month,day,hour,minute,seconds)\n\n'''\nThis segment initializes a matrix that is organized by time bins of 2 minutes\nso that the data can be compiled in an organized fashion\n'''\n#datetime is a timestamp function I imagine, block below would be their time range\nstart_time = datetime(2018,2,20,15,0,0)\nend_time = datetime(2020,2,20,15,0,0)\ntime_bins = []\n\n\nwhile start_time < end_time:\n temp_time = start_time\n # They add 2 minutes to the start time\n start_time += timedelta(minutes = 2, seconds=0)\n # append the temp_time to the time_bins\n time_bins.append([temp_time])\n \n# I think these are sets \nwarning_labels = {'Motor_Distorted_Warning','Broken_Impeller_Warning','Leaking_Valve_Warning','Broken_Valve_Warning'}\nbroken_labels = {'Motor_Distorted','Broken_Impeller','Leaking_Valve','Broken_Valve','Cracked_Seal','Valve_Alignment'}\n\nj = 0\n\nfor i in range(len(time_bins)):\n # If the time is the same\n if time_bins[i][0] == m_dis_data[j][0]:\n # Fill up the time bins \n time_bins[i] = m_dis_data[j]\n \n j += 1\n\nj = 0\n\nfor i in range(len(time_bins)):\n # if the time is the same\n if time_bins[i][0] == b_imp_data[j][0]:\n if len(time_bins[i]) == 1:\n time_bins[i] = b_imp_data[j]\n \n else:\n if time_bins[i][7] in warning_labels and b_imp_data[j][7] in broken_labels:\n time_bins[i][7] = b_imp_data[j][7]\n elif time_bins[i][7] == \"Normal\":\n time_bins[i][7] = b_imp_data[j][7] \n \n j += 1\n \n\nj = 0\n\nfor i in range(len(time_bins)):\n \n if time_bins[i][0] == b_valve_data[j][0]:\n if len(time_bins[i]) == 1:\n time_bins[i] = b_valve_data[j]\n else:\n if time_bins[i][7] in warning_labels and b_valve_data[j][7] in broken_labels:\n time_bins[i][7] = b_valve_data[j][7]\n elif time_bins[i][7] == \"Normal\":\n time_bins[i][7] = b_valve_data[j][7]\n \n j += 1\n \nj = 0\n\nfor i in range(len(time_bins)):\n \n if time_bins[i][0] == l_valve_data[j][0]:\n if len(time_bins[i]) == 1:\n time_bins[i] = l_valve_data[j]\n else:\n if time_bins[i][7] in warning_labels and l_valve_data[j][7] in broken_labels:\n time_bins[i][7] = l_valve_data[j][7]\n \n elif time_bins[i][7] == \"Normal\":\n time_bins[i][7] = l_valve_data[j][7]\n \n j += 1\n \n\nfor i in range(len(time_bins)):\n \n if len(time_bins[i]) == 1:\n time_bins[i] = [time_bins[i][0],'Off','Off','Off','Off','Off','Off','Off']\n\n\nwith open('compiled_data.csv', 'w', newline='', encoding=\"utf-8\") as csvfile:\n fieldnames = ['datetime','x vib', 's pressure', 'd pressure', 'flowrate', 'y vibration','motor stat','label']\n writer = csv.DictWriter(csvfile, fieldnames = fieldnames)\n\n for i in range(len(time_bins)):\n writer.writerow({'datetime':time_bins[i][0],'x vib':time_bins[i][1],'s pressure':time_bins[i][2],'d pressure':time_bins[i][3],'flowrate':time_bins[i][4],'y vibration':time_bins[i][5],'motor stat':time_bins[i][6],'label':time_bins[i][7]})\n\n'''\nThis second large segment creates the final model and saves it in the file\ncomplete_model.sav which can be called later on without having to rebuild it\n'''\ncol_names = []\nfor i in range(8):\n if i ==0:\n col_names.append('datetime')\n if i == 1:\n col_names.append('x_vibration')\n if i == 2:\n col_names.append('suction_pressure')\n if i == 3:\n col_names.append('discharge_pressure')\n if i == 4:\n col_names.append('discharge_flow')\n if i == 5:\n col_names.append('y_vibration')\n if i == 6:\n col_names.append('motor_stat')\n if i == 7:\n col_names.append('label')\n\ndata = pd.read_csv(\"compiled_data.csv\", names = col_names)\ndata = data[data.motor_stat != 'Off']\n\ndata_Y = data['label']\ndata_X = data.drop(['datetime','label','motor_stat'],axis=1)\n\n\n### Best Parameters found so far, this segment prints the confusion matrix and \n# classification report for this model.\n\nscaler = StandardScaler()\nclf = SVC(C=1, class_weight={'Normal':1,'Broken_Impeller':25 ,'Broken_Valve':25 ,'Leaking_Valve':25 , 'Motor_Distorted':25,'Broken_Impeller_Warning':25, 'Motor_Distorted_Warning':25,'Leaking_Valve_Warning':25,'Broken_Valve_Warning':25 },kernel=\"rbf\")\npipe = Pipeline(steps=[('scaler', scaler), ('svc', clf)])\n\npredicts = cross_val_predict(pipe, data_X, data_Y, cv=10)\nprint(confusion_matrix(data_Y, predicts))\nprint(classification_report(data_Y,predicts))\n\n# This code segment builds the final model. The best parameters were already found\n\n\nscaler = StandardScaler()\nclf = SVC()\n\npipe = Pipeline(steps=[('scaler', scaler), ('svc', clf)])\n\nparam_grid = {'svc__kernel': ['rbf'],\n 'svc__class_weight': [{'Normal':1,'Broken_Impeller':25 ,'Broken_Valve':25 ,'Leaking_Valve':25 , 'Motor_Distorted':25,'Broken_Impeller_Warning':25, 'Motor_Distorted_Warning':25,'Leaking_Valve_Warning':25,'Broken_Valve_Warning':25 }],\n 'svc__C': [1]\n }\n\ngrid_search = GridSearchCV(pipe, param_grid, cv=5,scoring='f1_macro')\nmodel = grid_search.fit(data_X, data_Y)\n\nfilename = 'Final_Model.sav'\npickle.dump(model, open(filename, 'wb'))\n\n\n# This last code segment is used to have the model predict new data.\n# Data is read from a csv file names new_data.csv but this name can be changed.\n# It is important that there aren't headers in this file and the columns\n# are in the order: x_vibration, suction_pressure, discharge_pressure, \n# discharge_flow, and y_vibration otherwise it will not work.\n\n\nwith open('new_data.csv', newline='') as f:\n reader = csv.reader(f)\n new_data = list(reader)\n\nloaded_model = pickle.load(open('Final_Model.sav', 'rb'))\n\nresults = {}\n\npred = loaded_model.predict(new_data)\n\nfor i in range(len(pred)):\n \n if pred[i] in results:\n results[pred[i]] += 1\n \n else:\n results[pred[i]] = 1\n \nprint(results)\n\n","sub_path":"Spring_2020_Final_Model.py","file_name":"Spring_2020_Final_Model.py","file_ext":"py","file_size_in_byte":9275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"282393714","text":"import os\nimport sys\nimport json\n\n\nclass BuildAutomationTool():\n\n\tdef execute_command(self, current_working_directory, previous_working_directory, process_command, current_script):\n\n\t\tif process_command != \"build\":\n\t\t\traise Exception(process_command + ' is not a recognized process command')\n\t\t\treturn\n\n\n\t\tabsolute_path = os.path.abspath(current_working_directory)\n\t\tos.chdir(absolute_path)\n\t\tscript_found = False\n\n\n\t\twith open(os.path.join(\"build.json\")) as json_file:\n\t\t\tscripts = json.load(json_file)\n\n\t\t\tfor script in scripts:\n\t\t\t\tif script['name'] == current_script:\n\t\t\t\t\tscript_found = True\n\t\t\t\t\tif 'deps' in script:\n\t\t\t\t\t\tfor dependecy in script['deps']:\n\t\t\t\t\t\t\tpath = str(dependecy).split('/')\n\t\t\t\t\t\t\tnew_script = path.pop()\n\t\t\t\t\t\t\tnew_path = \"\"\n\t\t\t\t\t\t\tfor path_segment in path:\n\t\t\t\t\t\t\t\tnew_path += path_segment\n\t\t\t\t\t\t\tself.execute_command(new_path, current_working_directory, process_command, new_script)\n\t\t\t\t\tcurrent_command = script['command']\n\t\t\t\t\tos.system(current_command)\n\t\t\t\t\tprevious_absolute_path = os.path.abspath(previous_working_directory)\n\t\t\t\t\tos.chdir(previous_absolute_path)\n\n\n\t\tif script_found is False:\n\t\t\traise Exception('build ' + current_script + ' is not a recognized command')\n\t\t\treturn\n\n\t\treturn\n\n","sub_path":"solutions/Pranjal Rai/src/Assignment 2/BuildAutomationTool.py","file_name":"BuildAutomationTool.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"285678471","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\ndef cloud_creator(D,N,L):\r\n p1 = np.zeros([N,3])\r\n p2 = np.zeros([N**2,3])\r\n p3 = np.zeros([N**3,3])\r\n p4 = np.zeros([N**4,3])\r\n delta = np.exp(np.log(N)/D)\r\n print(\"Delta: \" + str(delta))\r\n \r\n for i in range(N):\r\n r1 = np.random.uniform(-1,1,3)\r\n p1[i,:] = (L/2)*r1\r\n \r\n for n in range(N):\r\n origin = np.copy(p1[n,:])\r\n #print(origin)\r\n for m in range(N):\r\n r2 = np.random.uniform(-1,1,3)\r\n p2[m+n*N, :] = (L/(2*delta))*r2 + origin\r\n \r\n for k in range(N**2):\r\n origin = np.copy(p2[k,:])\r\n #print(origin)\r\n for q in range(N):\r\n r3 = np.random.uniform(-1,1,3)\r\n p3[q+k*N, :] = (L/(2*delta))*r3 + origin\r\n \r\n for l in range(N**3):\r\n origin = np.copy(p3[l,:])\r\n #print(origin)\r\n for h in range(N):\r\n r4 = np.random.uniform(-1,1,3)\r\n p4[h+l*N, :] = (L/(2*delta))*r4 + origin\r\n \r\n \r\n print(\"The cluster lentgh: \" + str(L/(2*delta)))\r\n return (p1,p2,p3,p4)\r\n\r\n#cloud_creater(2.6,5,1)\r\n\r\ndef main():\r\n D = 2.6\r\n N = 2\r\n L = 100\r\n data = cloud_creator(D,N,L)\r\n p1 = data[0]\r\n p2 = data[1]\r\n p3 = data[2]\r\n p4 = data[3]\r\n \r\n #print(p1)\r\n #print(p2)\r\n \r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n\r\n x1 = p1[:,0]\r\n y1 = p1[:,1]\r\n z1 = p1[:,2]\r\n \r\n #print(x1)\r\n \r\n x2 = p2[:,0]\r\n y2 = p2[:,1]\r\n z2 = p2[:,2]\r\n \r\n x3 = p3[:,0]\r\n y3 = p3[:,1]\r\n z3 = p3[:,2]\r\n \r\n x4 = p4[:,0]\r\n y4 = p4[:,1]\r\n z4 = p4[:,2]\r\n \r\n ax.scatter(x1, y1, z1, c='r', marker='o')\r\n ax.scatter(x2, y2, z2, c='b', marker='o')\r\n ax.scatter(x3, y3, z3, c='m', marker='o')\r\n ax.scatter(x4, y4, z4, c='g', marker='o')\r\n\r\n\r\n plt.show()\r\n \r\nmain()","sub_path":"cloud_creater.py","file_name":"cloud_creater.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"467797125","text":"import os\nfrom app import create_application\nfrom flask_script import Manager, Shell\nfrom app.models import User, data, MealOption\n\napp = create_application(os.getenv('MEAL_APP_CONFIG') or 'default')\n\nmanager = Manager(app)\n\n\ndef make_shell_context():\n return dict(app=app, User=User, data=data)\n\n\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\n\n\n@manager.command\ndef test():\n \"Function to run unit tests\"\n import unittest\n tests = unittest.TestLoader().discover('tests', pattern='test*.py')\n result = unittest.TextTestRunner(verbosity=2).run(tests)\n\n return not result.wasSuccessful()\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"277377593","text":"from OpenGL.GL import *\n\ndef load_shader(shader_file):\n shader_source = \"\"\n with open(shader_file) as f:\n shader_source = f.read()\n f.close()\n return str.encode(shader_source)\n\ndef compile_shader(vs_file, fs_file):\n vert_shader = load_shader(vs_file)\n frag_shader = load_shader(fs_file)\n\n shader = glCreateProgram()\n vs = glCreateShader(GL_VERTEX_SHADER)\n glShaderSource(vs, [vert_shader])\n glCompileShader(vs)\n if not glGetShaderiv(vs, GL_COMPILE_STATUS):\n raise Exception('failed to compile shader \"%s\":\\n%s' % (vs, glGetShaderInfoLog(vs).decode()))\n \n glAttachShader(shader, vs)\n\n fs = glCreateShader(GL_FRAGMENT_SHADER)\n glShaderSource(fs, [frag_shader])\n glCompileShader(fs)\n if not glGetShaderiv(fs, GL_COMPILE_STATUS):\n raise Exception('failed to compile shader \"%s\":\\n%s' % (fs, glGetShaderInfoLog(fs).decode()))\n glAttachShader(shader, fs)\n\n glLinkProgram(shader)\n glValidateProgram(shader)\n glDeleteShader(vs)\n glDeleteShader(fs)\n \n return shader","sub_path":"Tugas 3/ShaderLoader.py","file_name":"ShaderLoader.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"325133674","text":"\"\"\"\n>>> convert(\"PAYPALISHIRING\", 3)\n'PAHNAPLSIIGYIR'\n\"\"\"\n\ndef convert(s, nRows):\n if nRows == 1:\n return s\n\n n = nRows * 2 - 2\n s += ' ' * (n - len(s) % n)\n l = [s[i::n] for i in range(n)]\n r = l[0]\n\n for i in range(1, nRows-1):\n r += \"\".join(a+b for a,b in zip(l[i], l[n-i]))\n\n r += l[nRows-1]\n return \"\".join(r.split(\" \"))\n","sub_path":"solutions/6-zigzag-conversion.py","file_name":"6-zigzag-conversion.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"14248244","text":"import pyexcel as pe\n\n# We have used this script to map the Kaggle dataset with our own dataset\n\ngenre_list = [\n 'Art', 'Biography', 'Business', 'Children', 'Christian', 'Classics', 'Comics', 'Cookbooks', 'Ebooks', 'Fantasy',\n 'Fiction', 'Graphic Novels', 'Historical Fiction', 'History', 'Horror', 'Memoir', 'Music', 'Mystery', 'Nonfiction',\n 'Poetry', 'Psychology', 'Romance', 'Science', 'Science Fiction', 'Self Help', 'Sports', 'Thriller', 'Travel',\n 'Young Adult'\n]\n\n\ndef main():\n sheet = pe.get_sheet(file_name=\"./classifier/dataset.csv\", row_limit=20)\n sheet.name_columns_by_row(0)\n print(sheet.row[1][3])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"classifier/merger.py","file_name":"merger.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"149411401","text":"# import pandas as pd\nimport argparse\nimport os\nimport sys\nimport time\n\nfrom ansys_file_reader import AnsysFileReader\nfrom constants import *\nfrom merge_nodes import MergeNodes\nfrom mesh_data import MeshData\nfrom mesh_file_writer import MeshFileWriter\nfrom mesh_file_writer_for_lst_debug import MeshFileWriterForLstDebug\nfrom neighbor_element_checker import NeighborElementChecker\nfrom reorder_element_connectivity import ReorderElementConnectivity\n\n\ndef main(input_file, output_folder):\n \"\"\"[summary]\n Args:\n input_file ([str]): 入力ファイル\n output_folder ([str]): 出力ディレクトリ\n \"\"\"\n\n logging.basicConfig(level=LOGGER_LEVEL, format=LOGGER_FORMAT)\n\n time_start = time.time()\n\n path = input_file\n\n # 出力先ディレクトリを作成する\n os.makedirs(output_folder, exist_ok=True)\n\n # メッシュデータを格納するオブジェクト\n mesh_data = MeshData()\n\n # Ansysファイルを読み込む\n reader = AnsysFileReader()\n reader.read(path, mesh_data)\n logging.info(f'node={mesh_data.get_nodes_df()}')\n logging.info(f'elements={mesh_data.get_elements_df()}')\n\n # 節点をマージする\n merge_nodes = MergeNodes()\n merge_nodes.merge(mesh_data)\n\n # 要素の隣接関係を計算する\n neighbor_element_checker = NeighborElementChecker()\n neighbor_element_checker.check(mesh_data)\n\n # 要素内の節点順序並び替えと、要素へのフラグ設定を行う\n reorder_element_connectivity = ReorderElementConnectivity()\n reorder_element_connectivity.reorder(mesh_data)\n\n # メッシュファイルなどを出力する\n mesh_file_writer = MeshFileWriter()\n mesh_file_writer.write_clp_mesh_file(mesh_data, output_folder, \"output_mesh.ms\")\n mesh_file_writer.write_merge_node_info_file(mesh_data, output_folder, \"output_merge_node_info.dat\")\n mesh_file_writer.write_domain_id_file(mesh_data, output_folder, \"output_domain_id.dat\")\n mesh_file_writer.write_msh_file(mesh_data, output_folder, \"output.msh\")\n\n mesh_file_writer_lst = MeshFileWriterForLstDebug()\n mesh_file_writer_lst.write_lst_file(mesh_data, output_folder, \"output.lst\")\n\n time_end = time.time()\n logging.info(f'elapse time {time_end - time_start}[sec]')\n\n\nif __name__ == '__main__':\n if len(sys.argv) >= 2:\n parser = argparse.ArgumentParser(description='1 file and 1 directory needed')\n parser.add_argument('files', metavar='files', type=str, nargs=2,\n help='input_file, output_directory')\n args = parser.parse_args()\n input_file_name, output_folder_name = args.files[0], args.files[1]\n main(input_file_name, output_folder_name)\n else:\n sys.exit(\"usage : python main.py input.dat output_dir\")\n","sub_path":"meshconverter/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"589072529","text":"outDir = '/SNS/users/rwp/corelli/ZrO2/'\n\nConvertMultipleRunsToSingleCrystalMD(Filename='CORELLI_2274:2318',\n SetGoniometer=True,\n Axis0='BL9:Mot:Sample:Rot1,0,1,0,1', # Something more is happening with the goniometers #######\n OutputWorkspace='md',\n MinValues=[-15,-15,-15],\n MaxValues=[15,15,15])\nFindPeaksMD(InputWorkspace='md', PeakDistanceThreshold=0.25, DensityThresholdFactor=10000, OutputWorkspace='peaks')\nFindUBUsingFFT(PeaksWorkspace='peaks', MinD=4, MaxD=6)\nShowPossibleCells(PeaksWorkspace='peaks')\nSelectCellOfType(PeaksWorkspace='peaks', CellType='Cubic', Centering='F', Apply=True)\nIndexPeaks(PeaksWorkspace='peaks')\nOptimizeLatticeForCellType(PeaksWorkspace='peaks', Apply=True)\n\nSaveIsawUB('peaks', outDir+'CaZrO2_300K.mat')\n\nSingleCrystalDiffuseReduction(Filename='CORELLI_2274:2318',\n SolidAngle=outDir+'IPTS-12310/SA.nxs',\n Flux=outDir+'IPTS-12310/Flux.nxs',\n OutputWorkspace='output',\n SetGoniometer=True,\n Axis0=\"BL9:Mot:Sample:Axis1,0,1,0,1\",\n UBMatrix=outDir+'CaZrO2_300K.mat',\n BinningDim0='-10.02,10.02,501',\n BinningDim1='-10.02,10.02,501',\n BinningDim2='-10.02,10.02,501')\n\nSingleCrystalDiffuseReduction(Filename='CORELLI_2274:2318',\n SolidAngle=outDir+'IPTS-12310/SA.nxs',\n Flux=outDir+'IPTS-12310/Flux.nxs',\n OutputWorkspace='sym',\n SetGoniometer=True,\n Axis0=\"BL9:Mot:Sample:Axis1,0,1,0,1\",\n UBMatrix=outDir+'CaZrO2_300K.mat',\n BinningDim0='-10.02,10.02,501',\n BinningDim1='-10.02,10.02,501',\n BinningDim2='-10.02,10.02,501',\n SymmetryOps='221') # Really 225\n\nSaveMD('sym', outDir+'CaZrO2_300K_sym.nxs')\n","sub_path":"ZrO2/Ca-300K-PDF.py","file_name":"Ca-300K-PDF.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"536326445","text":"from __future__ import print_function, division\nimport xml.etree.cElementTree as ET\nimport time as time\nimport os\nfrom copy import deepcopy\nfrom subprocess import Popen, PIPE\n\n''' amount of time to wait between location changes'''\nSECONDS_PAUSE_BETWEEN_MOVES = 2.2\n\n''' number of steps to move vertical when on box edges '''\nNUM_STEPS_UP_PER_PASS = 2\n\n''' number of steps to move between horizontal pass'''\nNUM_STEPS_ACCROSS_PER_PASS = 20\n\n''' number of moves going vertical '''\nNUM_INCREMENTS_UP = 50\n\n''' number of pixels down for xcode button '''\nNUM_PIXELS_DOWN_FOR_CLICK = 50\n\n''' click or perform apple script '''\nUSE_APPLE_SCRIPT = True\n\n''' x and y coordinate of xcode location button '''\nXCODE_LOCATION_BUTTON_COORDINATES = {\n 'x': 650,\n 'y': 900\n}\n\n''' file name of location file '''\nLOCATION_FILE_NAME = 'pokemonLocation'\n\nclass Coordinate:\n\n def __init__(self, lat, lon):\n self.lat = lat\n self.lon = lon\n\n def get(self):\n return [self.lat, self.lon]\n\n def __str__(self):\n return 'lat: %f, lon: %f' % (self.lat, self.lon)\n\n def __eq__(self, other):\n\n return (self.lat == other.lat) and (self.lon == other.lon)\n def __mul__(self, other):\n if isinstance(other, Coordinate):\n return Coordinate(self.lat * other.lat, self.lon * other.long)\n elif type(other) is int:\n return Coordinate(self.lat * other, self.lon * other)\n else:\n raise ValueError('Unknown type')\n\n def __add__(self, other):\n if isinstance(other, Coordinate):\n return Coordinate(self.lat + other.lat, self.lon + other.lon)\n elif type(other) is int:\n return Coordinate(self.lat + other, self.lon + other)\n else:\n raise ValueError('Unknown type')\n\n def __sub__(self, other):\n if isinstance(other, Coordinate):\n return Coordinate(self.lat - other.lat, self.lon - other.lon)\n elif type(other) is int:\n return Coordinate(self.lat - other, self.lon - other)\n else:\n raise ValueError('Unknown type')\n\n def __truediv__(self, other):\n if isinstance(other, Coordinate):\n return Coordinate(self.lat / other.lat, self.lon / other.lon)\n elif type(other) is int:\n return Coordinate(self.lat / other, self.lon / other)\n else:\n raise ValueError('Unknown type')\n\n def __div__(self, other):\n\n return self.__truediv__(other)\n\n\ncoordinates = [\n Coordinate(40.7680578657186, -73.981887864142), # Bottom Left\n Coordinate(40.7643841763404, -73.972945530681), # Bottom Right\n Coordinate(40.7969415563396, -73.949272376481), # Top Right\n Coordinate(40.8006549898320, -73.958185987147), # Top Left\n]\n\ndef continueWalking(change, current, end):\n # print(change, current, end)\n\n if change > 0:\n return current < end\n elif change < 0:\n return current > end\n return False\n\n# continueWalking(0.000073, coordinates[0].lat, coordinates[1].lat)\n# continueWalking(-0.000179, coordinates[0].lon, coordinates[1].lon)\n\ndef moveInApp():\n\n if USE_APPLE_SCRIPT is True:\n move_script = '''\n property locationName : \"%s\" # name of gpx filex\n\n tell application \"System Events\"\n tell process \"Xcode\"\n click menu item locationName of menu 1 of menu item \"Simulate Location\" of menu 1 of menu bar item \"Debug\" of menu bar 1\n end tell\n end tell\n ''' % (LOCATION_FILE_NAME)\n\n args = []\n process = Popen(\n ['osascript', '-'] + args,\n stdin=PIPE,\n stdout=PIPE,\n stderr=PIPE\n )\n\n stdout, stderr = process.communicate(move_script)\n\n if len(stderr) != 0:\n print('Error', stderr)\n exit()\n\n else:\n os.system(\"./autoClicker -x %d -y %d\" % (XCODE_LOCATION_BUTTON_COORDINATES ['x'], XCODE_LOCATION_BUTTON_COORDINATES ['y']))\n os.system(\"./autoClicker -x %d -y %d\" % (XCODE_LOCATION_BUTTON_COORDINATES ['x'], XCODE_LOCATION_BUTTON_COORDINATES ['y'] + NUM_PIXELS_DOWN_FOR_CLICK))\n\n ''' delay '''\n time.sleep(SECONDS_PAUSE_BETWEEN_MOVES)\n\ndef writeFile(coordinate):\n gpx = ET.Element(\"gpx\", version=\"1.1\", creator=\"Xcode\")\n wpt = ET.SubElement(gpx, \"wpt\", lat=str(coordinate.lat), lon=str(coordinate.lon))\n ET.SubElement(wpt, \"name\").text = LOCATION_FILE_NAME\n ET.ElementTree(gpx).write(\"%s.gpx\" % (LOCATION_FILE_NAME))\n\n print(\"Location Updated to:\", coordinate)\n\ndef moveToCoordinate(start, end, pace=NUM_STEPS_ACCROSS_PER_PASS):\n current = start\n\n change = end - start\n change /= pace\n\n i_moves = 0\n while (\n continueWalking(change.lat, current.lat, end.lat) \\\n or continueWalking(change.lon, current.lon, end.lon)\n ):\n\n if i_moves > 500:\n print('TERMINATED')\n break\n\n current += change\n\n writeFile(current)\n moveInApp()\n\n i_moves += 1\n # print('moved', i_moves)\n return end\n\n\n\ndef main():\n start = coordinates[0]\n end = coordinates[3]\n\n current = deepcopy(start)\n\n change_left = coordinates[3] - coordinates[0]\n change_left /= NUM_INCREMENTS_UP\n\n change_right = coordinates[2] - coordinates[1]\n change_right /= NUM_INCREMENTS_UP\n\n num_times_left = 0\n num_times_right = 0\n\n i_loops = 0\n while True:\n\n if i_loops > 99999:\n print('ENDED GAME')\n break\n\n # move right\n current = moveToCoordinate(current, coordinates[1] + change_right * num_times_right)\n num_times_right += 1\n\n # move up\n current = moveToCoordinate(current, coordinates[1] + change_right * num_times_right, pace=NUM_STEPS_UP_PER_PASS)\n\n # move left\n current = moveToCoordinate(current, coordinates[0] + change_left * num_times_left)\n num_times_left += 1\n\n # move up\n current = moveToCoordinate(current, coordinates[0] + change_left * num_times_left, pace=NUM_STEPS_UP_PER_PASS)\n\n near_end = current - end\n if abs(near_end.lat) <= 0.0001 or abs(near_end.lon) <= 0.0001:\n print('END')\n break\n\n i_loops += 1\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"moveInRange.py","file_name":"moveInRange.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"136987352","text":"#!/usr/bin/python\nfrom .IndivScores import IndivScores\nimport json\nimport sys\n\ndef handle(req):\n \"\"\"Handles DriverScore Function\"\"\"\n try:\n json_req = json.loads(req)\n sensor_ID = json_req[\"sensor_ID\"]\n scoretype = json_req[\"scoretype\"]\n except:\n print(\"Bad formatted input %s\", req, file=sys.stderr)\n return Exception(400, 'Bad Request', 'Example Input:', '{\"sensor_ID\": \"666\",\"scoretype\": \"driverscore\"}')\n\n temp = IndivScores(sensor_ID, scoretype)\n output = temp.main()\n\n return output\n\n# Example Input:\n# {\"sensor_ID\": \"666\",\"scoretype\": \"driverscore\"}\n","sub_path":"indiv-driverscores/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"106373102","text":"from PyQt5.QtCore import QDate, QRect, pyqtSlot, pyqtSignal\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import (QAbstractItemView, QDateEdit, QDateTimeEdit,\n QLabel, QPushButton, QTableWidget,\n QTableWidgetItem, QWidget)\n\nfrom dialogWindow import QDialogUI\n\n\nclass QWidgetUI(QWidget):\n\n params = pyqtSignal(str, str, str, int, str, str)\n\n def __init__(self):\n\n tbl_headers = [\"날짜\", \"지출/수입 여부\", \"자산\", \"금액\", \"분류\", \"내용\"]\n # return values when input table\n\n super().__init__()\n\n self.setWindowTitle(\"Money PLANet\")\n self.resize(800, 590)\n\n font = QFont()\n font.setFamily(\"카카오OTF Regular\")\n font.setPointSize(15)\n\n self.exportButton = QPushButton(\"지출 입력\", self)\n self.exportButton.setGeometry(QRect(20, 240, 110, 40))\n self.exportButton.setFont(font)\n\n self.importButton = QPushButton(\"수입 입력\", self)\n self.importButton.setGeometry(QRect(20, 290, 110, 40))\n self.importButton.setFont(font)\n\n self.modifyButton = QPushButton(\"내용 수정\", self)\n self.modifyButton.setGeometry(QRect(140, 240, 110, 40))\n self.modifyButton.setFont(font)\n\n self.accountTable = QTableWidget(self)\n self.accountTable.setEditTriggers(QAbstractItemView. NoEditTriggers)\n self.accountTable.setColumnCount(len(tbl_headers))\n self.accountTable.setRowCount(0)\n self.accountTable.setHorizontalHeaderLabels(tbl_headers)\n self.accountTable.setGeometry(QRect(0, 0, 800, 221))\n\n self.totalLabel = QLabel(\"총 수입: \\n\\n총 지출: \\n\\n남은 금액: \", self)\n self.totalLabel.setGeometry(QRect(20, 390, 210, 140))\n self.totalLabel.setFont(font)\n\n self.startdate = QDateEdit(self)\n self.startdate.setGeometry(QRect(20, 350, 110, 22))\n self.startdate.setCurrentSection(QDateTimeEdit.DaySection)\n\n self.fromLabel = QLabel(\"부터\", self)\n self.fromLabel.setGeometry(QRect(140, 345, 40, 30))\n self.fromLabel.setFont(font)\n\n self.finishDate = QDateEdit(self)\n self.finishDate.setGeometry(QRect(190, 350, 110, 22))\n self.finishDate.setCurrentSection(QDateTimeEdit.DaySection)\n self.finishDate.setDate(QDate.currentDate())\n\n self.goButton = QPushButton(\"조회하기\", self)\n self.goButton.setGeometry(QRect(320, 340, 110, 40))\n self.goButton.setFont(font)\n\n @pyqtSlot()\n def openDialog(self, type):\n self.dlg = QDialogUI(type)\n self.dlg.exec_()\n if self.dlg.status is not None:\n iD = list(self.dlg.status)\n self.params.emit(iD[0], iD[1], iD[2], iD[3], iD[4], iD[5])\n\n @pyqtSlot(str, str, str, int, str, str)\n def editTblData(self, date, type, asset, sort, money, text):\n\n self.Row = self.accountTable.rowCount()\n self.accountTable.insertRow(self.Row)\n\n if type == \"export\":\n type = \"지출\"\n else:\n type = \"수입\"\n\n self.accountTable.setItem(self.Row, 0,\n QTableWidgetItem('{}'.format(date)))\n self.accountTable.setItem(self.Row, 1,\n QTableWidgetItem('{}'.format(type)))\n self.accountTable.setItem(self.Row, 2,\n QTableWidgetItem('{}'.format(asset)))\n self.accountTable.setItem(self.Row, 3,\n QTableWidgetItem('{}'.format(sort)))\n self.accountTable.setItem(self.Row, 4,\n QTableWidgetItem('{}'.format(money)))\n self.accountTable.setItem(self.Row, 5,\n QTableWidgetItem('{}'.format(text)))\n\n self.accountTable.resizeColumnsToContents()\n self.accountTable.resizeRowsToContents()\n","sub_path":"widgetWindow.py","file_name":"widgetWindow.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"236145089","text":"#!/usr/bin/python\n\n# Copyright (c) 2009 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n# usage: action_jsconfig.py JS_ENGINE OUTPUT_DIR CONFIG_H_IN FILES_TO_COPY\n# JS_ENGINE may be v8 at present. jsc will be added in the future.\n# OUTPUT_DIR is the directory to put files in.\n# CONFIG_H_IN is the path to config.h.in upon which config.h will be based.\n# FILES_TO_COPY is a list of additional headers to be copied. It may be empty.\n\nimport errno\nimport os\nimport os.path\nimport shutil\nimport sys\n\nassert len(sys.argv) >= 4\njs_engine = sys.argv[1]\noutput_dir = sys.argv[2]\nconfig_h_in_path = sys.argv[3]\nfiles_to_copy = sys.argv[4:]\n\nconfig_h_path = os.path.join(output_dir, 'config.h')\n\nassert js_engine == 'v8'\n\nconfig_h_in_file = open(config_h_in_path)\nconfig_h_in_contents = config_h_in_file.read()\nconfig_h_in_file.close()\n\nconfig_h_file = open(config_h_path, 'w')\nprint >>config_h_file, config_h_in_contents\nif js_engine == 'v8':\n print >>config_h_file, '#define WTF_USE_V8_BINDING 1'\n print >>config_h_file, '#define WTF_USE_NPOBJECT 1'\nconfig_h_file.close()\n\nfor file in files_to_copy:\n # This is not strictly right for jsc headers, which will want to be in one\n # more subdirectory named JavaScriptCore.\n basename = os.path.basename(file)\n destination = os.path.join(output_dir, basename)\n shutil.copy(file, destination)\n","sub_path":"webkit/build/action_jsconfig.py","file_name":"action_jsconfig.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"161707646","text":"def fibonacci_iter(n):\r\n try:\r\n assert n > 0, \"Fibonacci numbers are indexed from 1\"\r\n if n == 1 or n == 2:\r\n return 1\r\n f_1 = 1\r\n f_2 = 1\r\n for i in range(2, n):\r\n f_n = f_1 + f_2\r\n f_1 = f_2\r\n f_2 = f_n\r\n return f_n\r\n except TypeError:\r\n print(\"Given argument is the wrong type!\")\r\n","sub_path":"fibonacci_iter.py","file_name":"fibonacci_iter.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"38476511","text":"\"\"\"\nCopyright 2018 Novartis Institutes for BioMedical Research Inc.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\"\"\"Neural net Models\"\"\"\n\nfrom keras.layers import (\n AveragePooling1D,\n Input,\n Dense,\n Dropout,\n Conv1D,\n Conv2D,\n Conv2DTranspose,\n MaxPooling1D,\n UpSampling1D,\n LSTM,\n RepeatVector,\n Flatten,\n Reshape,\n)\nfrom keras.models import Model\nfrom keras.regularizers import l1\nfrom keras.utils import plot_model\n\n\ndef cnn3(\n input_dim,\n channels=1,\n optimizer=\"adam\",\n loss=\"mse\",\n cfilters=[120],\n ckernel_sizes=[9],\n dunits=[256, 64, 16],\n embedding=10,\n dropouts=[0.0, 0.0, 0.0],\n metrics=[],\n reg_lambda=0.0,\n summary=False,\n plot=False,\n):\n inputs = Input(shape=(input_dim, 1), name=\"decoded_input\")\n\n num_cfilter = len(cfilters)\n num_dunits = len(dunits)\n\n encoded = inputs\n for i, f in enumerate(cfilters):\n encoded = Conv1D(\n f,\n ckernel_sizes[i],\n strides=2,\n activation=\"relu\",\n padding=\"same\",\n name=\"conv{}\".format(i),\n )(encoded)\n encoded = Dropout(dropouts[i], name=\"drop{}\".format(i))(encoded)\n\n encoded = Flatten(name=\"flatten\")(encoded)\n\n for i, u in enumerate(dunits):\n k = num_cfilter + i\n encoded = Dense(u, activation=\"relu\", name=\"fc{}\".format(k))(encoded)\n encoded = Dropout(dropouts[i], name=\"drop{}\".format(k))(encoded)\n\n encoded = Dense(\n embedding,\n activation=\"relu\",\n name=\"embed\",\n kernel_regularizer=l1(reg_lambda),\n )(encoded)\n\n decoded = encoded\n for i, u in enumerate(reversed(dunits)):\n k = num_cfilter + num_dunits + i\n decoded = Dense(u, activation=\"relu\", name=\"fc{}\".format(k))(decoded)\n decoded = Dropout(dropouts[i], name=\"dropout{}\".format(k))(decoded)\n\n decoded = Dense(\n int(input_dim / (2 ** len(cfilters))) * cfilters[-1],\n activation=\"relu\",\n name=\"blowup\",\n )(decoded)\n decoded = Reshape(\n (int(input_dim / (2 ** len(cfilters))), cfilters[-1]), name=\"unflatten\"\n )(decoded)\n\n for i, f in enumerate(reversed(cfilters[:-1])):\n k = num_cfilter + (num_dunits * 2) + i\n j = num_cfilter - i - 2\n decoded = UpSampling1D(2, name=\"upsample{}\".format(i))(decoded)\n decoded = Conv1D(\n f,\n ckernel_sizes[:-1][j],\n activation=\"relu\",\n padding=\"same\",\n name=\"deconv{}\".format(i),\n )(decoded)\n decoded = Dropout(dropouts[i], name=\"drop{}\".format(k))(decoded)\n\n decoded = UpSampling1D(2, name=\"upsample{}\".format(len(cfilters) - 1))(\n decoded\n )\n decoded = Conv1D(\n channels,\n ckernel_sizes[0],\n activation=\"sigmoid\",\n padding=\"same\",\n name=\"out\",\n )(decoded)\n\n autoencoder = Model(inputs, decoded)\n autoencoder.compile(optimizer=optimizer, loss=loss, metrics=metrics)\n\n encoder = Model(inputs, encoded)\n\n encoded_input = Input(shape=(embedding,), name=\"encoded_input\")\n decoded_input = encoded_input\n k = num_dunits * 2 + num_cfilter * 2 + 3\n for i in range(k, len(autoencoder.layers)):\n decoded_input = autoencoder.layers[i](decoded_input)\n decoder = Model(encoded_input, decoded_input)\n\n if summary:\n print(autoencoder.summary())\n print(encoder.summary())\n print(decoder.summary())\n\n if plot:\n plot_model(\n autoencoder,\n to_file=\"cnn3_ae.png\",\n show_shapes=True,\n show_layer_names=True,\n )\n plot_model(\n encoder,\n to_file=\"cnn3_de.png\",\n show_shapes=True,\n show_layer_names=True,\n )\n plot_model(\n encoder,\n to_file=\"cnn3_en.png\",\n show_shapes=True,\n show_layer_names=True,\n )\n\n return (encoder, decoder, autoencoder)\n\n\ndef cnn(\n input_shape=(120, 1),\n optimizer=\"adadelta\",\n loss=\"binary_crossentropy\",\n avg_pooling=False,\n filters=[64, 32, 16, 32],\n kernel_sizes=[5, 5, 3],\n metrics=[],\n summary=False,\n sample_weight_mode=None,\n):\n # `% 8` because we have 3 pooling steps of 2, hence, 2^3 = 8\n if input_shape[0] % 8 == 0:\n pad3 = \"same\"\n else:\n pad3 = \"valid\"\n\n inputs = Input(shape=input_shape, name=\"decoded_input\")\n\n pooling = MaxPooling1D if not avg_pooling else AveragePooling1D\n\n x = Conv1D(\n filters[0],\n kernel_sizes[0],\n activation=\"relu\",\n padding=\"same\",\n name=\"conv1\",\n )(inputs)\n x = pooling(2, padding=\"same\", name=\"pool1\")(x)\n x = Conv1D(\n filters[1],\n kernel_sizes[1],\n activation=\"relu\",\n padding=\"same\",\n name=\"conv2\",\n )(x)\n x = pooling(2, padding=\"same\", name=\"pool2\")(x)\n x = Conv1D(\n filters[2],\n kernel_sizes[2],\n activation=\"relu\",\n padding=pad3,\n name=\"conv3\",\n )(x)\n x = pooling(2, padding=pad3, name=\"pool3\")(x)\n x = Flatten(name=\"flatten\")(x)\n encoded = Dense(filters[3], activation=\"relu\", name=\"embed\")(x)\n\n x = Dense(\n filters[2] * int(input_shape[0] / 8), activation=\"relu\", name=\"deembed\"\n )(encoded)\n x = Reshape((int(input_shape[0] / 8), filters[2]), name=\"unflatten\")(x)\n # x = Conv1D(\n # filters[2],\n # kernel_sizes[2],\n # activation='relu',\n # padding='same',\n # name='deconv0'\n # )(x)\n x = UpSampling1D(2, name=\"up1\")(x)\n x = Conv1D(\n filters[1],\n kernel_sizes[2],\n activation=\"relu\",\n padding=\"same\",\n name=\"deconv1\",\n )(x)\n x = UpSampling1D(2, name=\"up2\")(x)\n x = Conv1D(\n filters[0],\n kernel_sizes[1],\n activation=\"relu\",\n padding=\"same\",\n name=\"deconv2\",\n )(x)\n x = UpSampling1D(2, name=\"up3\")(x)\n decoded = Conv1D(\n input_shape[1],\n kernel_sizes[0],\n activation=\"sigmoid\",\n padding=\"same\",\n name=\"deconv3\",\n )(x)\n\n autoencoder = Model(inputs, decoded)\n autoencoder.compile(\n optimizer=optimizer,\n loss=loss,\n metrics=metrics,\n sample_weight_mode=sample_weight_mode,\n )\n\n encoder = Model(inputs, encoded)\n\n encoded_input = Input(shape=(filters[3],), name=\"encoded_input\")\n decoded_input = encoded_input\n for i in range(9, len(autoencoder.layers)):\n decoded_input = autoencoder.layers[i](decoded_input)\n decoder = Model(encoded_input, decoded_input)\n\n if summary:\n print(autoencoder.summary(), encoder.summary(), decoder.summary())\n\n return (encoder, decoder, autoencoder)\n\n\ndef cnn2(\n input_shape=(120, 1),\n optimizer=\"adadelta\",\n loss=\"binary_crossentropy\",\n filters=[64, 32, 16, 32],\n kernel_sizes=[5, 5, 3],\n metrics=[],\n summary=False,\n dr=False,\n):\n # `% 8` because we have 3 pooling steps of 2, hence, 2^3 = 8\n if input_shape[0] % 8 == 0:\n pad3 = \"same\"\n else:\n pad3 = \"valid\"\n\n inputs = Input(shape=input_shape, name=\"decoded_input\")\n\n x = Conv1D(\n filters[0],\n kernel_sizes[0],\n strides=2,\n activation=\"relu\",\n padding=\"same\",\n name=\"conv1\",\n )(inputs)\n x = Conv1D(\n filters[1],\n kernel_sizes[1],\n strides=2,\n activation=\"relu\",\n padding=\"same\",\n name=\"conv2\",\n )(x)\n x = Conv1D(\n filters[2],\n kernel_sizes[2],\n strides=2,\n activation=\"relu\",\n padding=pad3,\n name=\"conv3\",\n )(x)\n if dr:\n x = Flatten(name=\"flatten\")(x)\n encoded = Dense(filters[3], activation=\"relu\", name=\"embed\")(x)\n else:\n encoded = Flatten(name=\"flatten\")(x)\n\n if dr:\n x = Dense(\n filters[2] * int(input_shape[0] / 8),\n activation=\"relu\",\n name=\"deembed\",\n )(encoded)\n\n x = Reshape((int(input_shape[0] / 8), filters[2]), name=\"unflatten\")(x)\n else:\n x = Reshape((int(input_shape[0] / 8), filters[2]), name=\"unflatten\")(\n encoded\n )\n\n x = UpSampling1D(2, name=\"up1\")(x)\n x = Conv1D(\n filters[1],\n kernel_sizes[2],\n activation=\"relu\",\n padding=\"same\",\n name=\"deconv1\",\n )(x)\n x = UpSampling1D(2, name=\"up2\")(x)\n x = Conv1D(\n filters[0],\n kernel_sizes[1],\n activation=\"relu\",\n padding=\"same\",\n name=\"deconv2\",\n )(x)\n x = UpSampling1D(2, name=\"up3\")(x)\n decoded = Conv1D(\n input_shape[1],\n kernel_sizes[0],\n activation=\"sigmoid\",\n padding=\"same\",\n name=\"deconv3\",\n )(x)\n\n autoencoder = Model(inputs, decoded)\n autoencoder.compile(optimizer=optimizer, loss=loss, metrics=metrics)\n\n encoder = Model(inputs, encoded)\n\n if dr:\n encoded_input = Input(shape=(filters[3],), name=\"encoded_input\")\n else:\n encoded_input = Input(\n shape=(filters[2] * int(input_shape[0] / 8),), name=\"encoded_input\"\n )\n decoded_input = encoded_input\n mid = 6 if dr else 5\n for i in range(mid, len(autoencoder.layers)):\n decoded_input = autoencoder.layers[i](decoded_input)\n decoder = Model(encoded_input, decoded_input)\n\n if summary:\n print(autoencoder.summary(), encoder.summary(), decoder.summary())\n\n return (encoder, decoder, autoencoder)\n\n\ndef cae2d(\n input_shape=(120, 50, 1),\n optimizer=\"adam\",\n loss=\"mse\",\n filters=[32, 64, 128],\n kernel_sizes=[5, 5, 3],\n dunits=[512, 256, 128],\n embedding=10,\n metrics=[],\n summary=False,\n dr=False,\n):\n # `% 8` because we have 3 pooling steps of 2, hence, 2^3 = 8\n if input_shape[0] % 8 == 0:\n pad3 = \"same\"\n else:\n pad3 = \"valid\"\n\n inputs = Input(shape=input_shape, name=\"decoded_input\")\n\n x = Conv2D(\n filters[0],\n kernel_sizes[0],\n strides=2,\n activation=\"relu\",\n padding=\"same\",\n name=\"conv1\",\n )(inputs)\n x = Conv2D(\n filters[1],\n kernel_sizes[1],\n strides=2,\n activation=\"relu\",\n padding=\"same\",\n name=\"conv2\",\n )(x)\n x = Conv2D(\n filters[2],\n kernel_sizes[2],\n strides=2,\n activation=\"relu\",\n padding=pad3,\n name=\"conv3\",\n )(x)\n x = Flatten(name=\"flatten\")(x)\n x = Dense(dunits[0], activation=\"relu\", name=\"fc1\")(x)\n x = Dense(dunits[1], activation=\"relu\", name=\"fc2\")(x)\n x = Dense(dunits[2], activation=\"relu\", name=\"fc3\")(x)\n\n encoded = Dense(embedding, activation=\"relu\", name=\"embed\")(x)\n\n x = Dense(dunits[2], activation=\"relu\", name=\"dfc1\")(encoded)\n x = Dense(dunits[1], activation=\"relu\", name=\"dfc2\")(x)\n x = Dense(dunits[0], activation=\"relu\", name=\"dfc3\")(x)\n x = Dense(\n int(input_shape[0] / 8) * int(input_shape[1] / 8) * filters[2],\n activation=\"relu\",\n name=\"blowup\",\n )(x)\n x = Reshape(\n (int(input_shape[0] / 8), int(input_shape[1] / 8), filters[2]),\n name=\"unflatten\",\n )(x)\n x = Conv2DTranspose(\n filters[1],\n kernel_sizes[2],\n strides=2,\n activation=\"relu\",\n padding=pad3,\n name=\"deconv1\",\n )(x)\n x = Conv2DTranspose(\n filters[0],\n kernel_sizes[1],\n strides=2,\n activation=\"relu\",\n padding=\"same\",\n name=\"deconv2\",\n )(x)\n decoded = Conv2DTranspose(\n input_shape[2],\n kernel_sizes[0],\n strides=2,\n activation=\"sigmoid\",\n padding=\"same\",\n name=\"deconv3\",\n )(x)\n\n autoencoder = Model(inputs, decoded)\n autoencoder.compile(optimizer=optimizer, loss=loss, metrics=metrics)\n\n encoder = Model(inputs, encoded)\n\n encoded_input = Input(shape=(embedding,), name=\"encoded_input\")\n decoded_input = encoded_input\n\n for i in range(9, len(autoencoder.layers)):\n decoded_input = autoencoder.layers[i](decoded_input)\n decoder = Model(encoded_input, decoded_input)\n\n if summary:\n print(autoencoder.summary(), encoder.summary(), decoder.summary())\n\n return (encoder, decoder, autoencoder)\n\n\ndef lstm(latent_dim):\n inputs = Input(shape=train.shape)\n encoded = LSTM(128)(inputs)\n\n decoded = RepeatVector(train.shape[0])(encoded)\n decoded = LSTM(train.shape[1], return_sequences=True)(decoded)\n\n autoencoder = Model(inputs, decoded)\n encoder = Model(inputs, encoded)\n\n autoencoder.compile(optimizer=\"rmsprop\", loss=\"binary_crossentropy\")\n\n return (encoder, decoder, autoencoder)\n","sub_path":"ae/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":13092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"127777283","text":"import scrapy\nimport time\nimport json\nimport logging\nimport pandas as pd\nfrom scrapy.crawler import CrawlerProcess\nfrom bs4 import BeautifulSoup\n\n#activity_list = ['3673761', '3662467', '3669435', '3662636', '3659777', '3664756', '3663135', '3662547']\nactivity_data = pd.read_excel('../data/misle/MISLE Incident Investigations DT.xlsx')\nactivity_list = activity_data['Activity ID'].tolist()\n\ndef getData(cssID, soup):\n data = soup.find(id=cssID)\n if(data is not None):\n return data.text #to extract the text without html tags\n else:\n return ''\n \nbriefs = []\n\nclass MISLEViewStateSpider(scrapy.Spider):\n name = 'misle-viewstate'\n start_urls = ['https://cgmix.uscg.mil/IIR/IIRSearch.aspx']\n download_delay = 1.5\n \n def __init__(self, activity_id=None):\n self.activity_id = activity_id\n \n def parse(self, response):\n yield scrapy.FormRequest('https://cgmix.uscg.mil/IIR/IIRSearch.aspx',\n formdata={'__EVENTVALIDATION': response.css('input#__EVENTVALIDATION::attr(value)'\n ).extract_first(),\n 'TextBoxActivityNumber': self.activity_id,\n 'DropDownListVesselService':'ALL',\n 'TextBoxFromDate':'01/01/2010',\n 'TextBoxToDate':'10/16/2019',\n 'ButtonSearch':'Search',\n '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)'\n ).extract_first()\n },\n callback=self.parse_activity)\n\n def parse_activity(self, response):\n yield scrapy.FormRequest('https://cgmix.uscg.mil/IIR/IIRSearch.aspx',\n formdata={'__EVENTVALIDATION': response.css('input#__EVENTVALIDATION::attr(value)'\n ).extract_first(),\n '__VIEWSTATEGENERATOR': response.css('input#__VIEWSTATEGENERATOR::attr(value)'\n ).extract_first(),\n '__EVENTTARGET':'GridViewIIR$ctl02$ReportButton',\n '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)'\n ).extract_first()\n },\n callback=self.parse_results)\n\n def parse_results(self, response):\n soup = BeautifulSoup(response.body, 'html.parser')\n brief_result = {\n 'activity_id': soup.find(id='LabelActivityNumber').text,\n 'incident_brief': soup.find(id='LabelIncidentBrief').text\n }\n \n yield brief_result\n \nprocess = CrawlerProcess(settings={\n 'FEED_FORMAT':'csv',\n 'FEED_URI': '../data/misle/scrape/misle-scraped-brief.csv',\n 'LOG_LEVEL': logging.WARNING,\n})\n\nfor i in range(len(activity_list)):\n if i >= 3400 and i < 3500:\n time.sleep(5)\n process.crawl(MISLEViewStateSpider, str(activity_list[i]))\n \nprocess.start() # the script will block here until the crawling is finished","sub_path":"code/scrap-misle.py","file_name":"scrap-misle.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"42044226","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom gaebusiness.business import CommandExecutionException\nfrom tekton.gae.middleware.json_middleware import JsonResponse\nfrom solucao_app import solucao_facade\n\n\ndef index():\n cmd = solucao_facade.list_solucaos_cmd()\n solucao_list = cmd()\n solucao_form = solucao_facade.solucao_form()\n solucao_dcts = [solucao_form.fill_with_model(m) for m in solucao_list]\n return JsonResponse(solucao_dcts)\n\n\ndef new(_resp, **solucao_properties):\n cmd = solucao_facade.save_solucao_cmd(**solucao_properties)\n return _save_or_update_json_response(cmd, _resp)\n\n\ndef edit(_resp, id, **solucao_properties):\n cmd = solucao_facade.update_solucao_cmd(id, **solucao_properties)\n return _save_or_update_json_response(cmd, _resp)\n\n\ndef delete(_resp, id):\n cmd = solucao_facade.delete_solucao_cmd(id)\n try:\n cmd()\n except CommandExecutionException:\n _resp.status_code = 500\n return JsonResponse(cmd.errors)\n\n\ndef _save_or_update_json_response(cmd, _resp):\n try:\n solucao = cmd()\n except CommandExecutionException:\n _resp.status_code = 500\n return JsonResponse(cmd.errors)\n solucao_form = solucao_facade.solucao_form()\n return JsonResponse(solucao_form.fill_with_model(solucao))\n\n","sub_path":"projeto/backend/appengine/routes/solucao/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"301690956","text":"class Person ( object ) :\n\tdef __init__ ( self , age ) :\n\t\t# 属性直接对外暴露,不安全,没有数据的过滤\n\t\t\n\t\tself.__age = age\n\t\n\t'''\n\t@Property\n\t'''\n\t\n\t@property\n\tdef age ( self ) :\n\t\treturn self.__age\n\t\n\t@age.setter # 去掉下划线.setter\n\tdef age ( self , age ) :\n\t\tif age <= 0 :\n\t\t\tage = 0\n\t\telse :\n\t\t\tself.__age = age\n\n\nper = Person ( 1 )\nper.age = -100 # 相当与调用 setAge\nprint ( per.age ) # 想当于调用getAge\n\n#\n# \tdef setAge ( self , age ) :\n# \t\tif age <= 0 :\n# \t\t\tage = 0\n# \t\telse :\n# \t\t\tself.__age = age\n#\n# \tdef getAge ( self ) :\n# \t\treturn self.__age\n#\n#\n# per = Person ( 0 )\n# print ( per.getAge ( ) )\n","sub_path":"OPP/@property/property.py","file_name":"property.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"262055763","text":"# coding=utf-8\nimport json\nimport subprocess\nimport nltk\nimport functools\nimport matplotlib.font_manager as fm\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import linalg\nfrom scipy import sparse\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import NuSVC\nfrom sklearn.metrics import roc_curve\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom scipy import io\nimport time\nimport jieba\nimport pickle\nfrom random import random\nfrom scipy.stats import mode\ndef dump_title():\n solr_dump = json.load(open('solr_dump.txt', encoding='utf-8'))\n docs = solr_dump['response']['docs']\n with open('know_title.txt', 'w', encoding='utf-8') as f:\n f.writelines([doc['know_title'] + '\\n' for doc in docs])\n\n\ndef segment_title():\n segment = subprocess.check_output(\n ['stanford-segmenter-2015-12-09\\segment.bat', 'ctb', 'know_title.txt', 'UTF-8', '0'])\n with open('segment_title.txt', 'wb') as f:\n f.write(segment)\n\n\ndef title_avg_len():\n with open('segment_title.txt', 'r', encoding='utf-8') as f:\n segment = f.read().splitlines()\n avg = 0.0\n for i in segment:\n avg += len(i)\n print(avg / len(segment))\n\n\ndef title_tf_plot():\n segment = None\n with open('segment_title.txt', 'r', encoding='utf-8') as f:\n segment = f.read()\n segment_list = functools.reduce(lambda x, y: x + y, (i.split() for i in segment.splitlines()))\n fd = nltk.FreqDist(segment_list)\n with open('title_tf.txt', 'w', encoding='utf-8') as f:\n f.writelines([i + ' ' + str(j) + '\\n' for i, j in fd.most_common()])\n # word = [i for i, j in fd.most_common()]\n # freq = [j for i, j in fd.most_common()]\n # indexes = np.arange(len(freq))\n # msyh = fm.FontProperties(fname='msyh.ttf') # I am on OSX.\n # width = 1\n # plt.bar(indexes, freq, width)\n # plt.xticks(indexes + width * 0.5, word, fontproperties=msyh, rotation=90)\n # plt.show()\n\n\ndef title_idf_plot():\n segment = None\n with open('segment_title.txt', 'r', encoding='utf-8') as f:\n segment = f.read()\n\n vectorizer = CountVectorizer()\n x = vectorizer.fit_transform(segment.splitlines())\n # for i in vectorizer.get_feature_names():\n # print i\n transformer = TfidfTransformer()\n tfidf = transformer.fit(x)\n with open('title_idf.txt', 'w', encoding='utf-8') as f:\n for i, j in sorted(zip(vectorizer.get_feature_names(), list(tfidf.idf_)), key=lambda z: z[1]):\n f.write((i + ' ' + str(j) + '\\n'))\n\n\ndef dump_content():\n solr_dump = json.load(open('solr_dump.txt', encoding='utf-8'))\n docs = solr_dump['response']['docs']\n with open('know_content.txt', 'w', encoding='utf-8') as f:\n f.writelines([doc['know_content'].replace('\\n', ' ') + '\\n' for doc in docs])\n\n\ndef segment_content():\n segment = subprocess.check_output(\n ['stanford-segmenter-2015-12-09\\segment.bat', 'ctb', 'know_content.txt', 'UTF-8', '0'])\n with open('segment_content.txt', 'wb') as f:\n f.write(segment)\n\n\ndef content_avg_len():\n with open('segment_content.txt', 'r', encoding='utf-8') as f:\n segment = f.read().splitlines()\n avg = 0.0\n for i in segment:\n avg += len(i)\n print(avg / len(segment))\n\n\ndef content_tf_plot():\n segment = None\n with open('segment_content.txt', 'r', encoding='utf-8') as f:\n segment = f.read()\n segment_list = functools.reduce(lambda x, y: x + y, (i.split() for i in segment.splitlines()))\n fd = nltk.FreqDist(segment_list)\n with open('content_tf.txt', 'w', encoding='utf-8') as f:\n f.writelines([i + ' ' + str(j) + '\\n' for i, j in fd.most_common()])\n # word = [i for i, j in fd.most_common()]\n # freq = [j for i, j in fd.most_common()]\n # indexes = np.arange(len(freq))\n # msyh = fm.FontProperties(fname='msyh.ttf') # I am on OSX.\n # width = 1\n # plt.bar(indexes, freq, width)\n # plt.xticks(indexes + width * 0.5, word, fontproperties=msyh, rotation=90)\n # plt.show()\n\n\ndef content_idf_plot():\n segment = None\n with open('segment_content.txt', 'r', encoding='utf-8') as f:\n segment = f.read()\n\n vectorizer = CountVectorizer()\n x = vectorizer.fit_transform(segment.splitlines())\n # for i in vectorizer.get_feature_names():\n # print i\n transformer = TfidfTransformer()\n tfidf = transformer.fit(x)\n with open('content_idf.txt', 'w', encoding='utf-8') as f:\n for i, j in sorted(zip(vectorizer.get_feature_names(), list(tfidf.idf_)), key=lambda z: z[1]):\n f.write(i + ' ' + str(j) + '\\n')\n\n\nclass question(object):\n def __init__(self, docs):\n self.standardquestion = None\n self.transformquestion = None\n self.standvec = None\n self.transvec = None\n for d in docs:\n if d['know_type'] == 0:\n self.standardquestion = d['title_tag']\n elif self.transformquestion is None and 'title_tag' in d:\n self.transformquestion = [d['title_tag']]\n elif 'title_tag' in d:\n self.transformquestion.append(d['title_tag'])\n\n def combine_tag(self):\n if self.transformquestion is not None and self.standardquestion is not None:\n sstr = ' '.join(self.standardquestion)\n tstr_list = []\n for s in self.transformquestion:\n tstr = ' '.join(s)\n if len(tstr) > 0:\n tstr_list.append(tstr)\n if len(sstr) > 0 and len(tstr_list) > 0:\n self.standardquestion = sstr\n self.transformquestion = tstr_list\n return sstr, tstr_list, True\n self.standardquestion = None\n self.transformquestion = None\n return None, None, False\n\n def bag_of_word(self, vectorizer):\n # 传list\n self.standvec = vectorizer.transform([self.standardquestion])\n self.transvec = vectorizer.transform(self.transformquestion)\n return self.standvec, self.transvec\n\nclass aligndata(object):\n def __init__(self,docs):\n self.standardquestion = None\n self.transformquestion = None\n for d in docs:\n if d['know_type'] == 0:\n self.standardquestion = d['know_title']\n elif self.transformquestion is None and 'know_title' in d:\n self.transformquestion = [d['know_title']]\n elif 'know_title' in d:\n self.transformquestion.append(d['know_title'])\n if self.standardquestion!=None:\n self.standardquestion=' '.join(jieba.cut(self.standardquestion,cut_all=False))\n if self.transformquestion!=None:\n newtransformquestion=[]\n for q in self.transformquestion:\n newtransformquestion.append(' '.join((jieba.cut(q,cut_all=False))))\n self.transformquestion=newtransformquestion\n\n def output(self):\n if self.transformquestion is not None and self.standardquestion is not None:\n self.standardquestion=[self.standardquestion for i in range(len(self.transformquestion))]\n return self.standardquestion, self.transformquestion, True\n return None, None, False\ndef get_question(filename):\n # r模式读入会对json转义字符做奇怪的事\n solr_dump = json.load(open(filename, 'r', encoding='utf-8'))\n docs = solr_dump['response']['docs']\n question = {}\n for d in docs:\n if d['know_content'] in question:\n question[d['know_content']].append(d)\n else:\n question[d['know_content']] = [d]\n return question.values()\n\n\ndef vfit(result):\n total_list = []\n sstr = None\n tstr_list = None\n pos = 0\n while pos < len(result):\n sstr, tstr_list, flag = result[pos].combine_tag()\n if flag:\n total_list.append(sstr)\n total_list.extend(tstr_list)\n pos += 1\n else:\n result.pop(pos)\n vectorizer = CountVectorizer()\n vectorizer.fit(total_list)\n return vectorizer\n\n\ndef savelrdata(filename):\n result = [question(q) for q in get_question(filename)]\n vectorizer = vfit(result)\n veclen = len(vectorizer.vocabulary_)\n print(veclen)\n truevec = None\n falsevec = None\n print(len(result))\n belong={}\n no=0\n for ii,i in enumerate(result):\n if i.standardquestion != None and i.transformquestion != None:\n svec, tvecs = i.bag_of_word(vectorizer)\n svecs = sparse.csr_matrix(np.ones((tvecs.shape[0], 1))).dot(svec)\n add = svecs.multiply(tvecs)\n if truevec is None:\n truevec = add\n else:\n truevec = sparse.vstack([truevec, add])\n for j in range(len(i.transformquestion)):\n belong[(ii, j)] = [(no,True)]\n no+=1\n\n else:\n raise Exception('unexpected')\n print(len(result))\n for i in range(len(result)):\n for j in range(len(result)):\n if i == j:\n continue\n svec = result[i].standvec\n tvecs = result[j].transvec\n svecs = sparse.csr_matrix(np.ones((tvecs.shape[0], 1))).dot(svec)\n add = svecs.multiply(tvecs)\n # allzero = add.sum(axis=1)\n # newadd=None\n # for k in range(add.shape[0]):\n # if allzero[k]!=0:\n # if newadd is None:\n # newadd = add[k,:]\n # else:\n # newadd = sparse.vstack([newadd, add[k,:]])\n # belong[(j,k)].append((no,False))\n # no+=1\n # if newadd is not None:\n # if falsevec is None:\n # falsevec = newadd\n # else:\n # falsevec = sparse.vstack([falsevec, newadd])\n for k in range(add.shape[0]):\n belong[(j,k)].append((no,False))\n if falsevec is None:\n falsevec = add\n else:\n falsevec = sparse.vstack([falsevec, add])\n print(truevec.shape, falsevec.shape)\n io.savemat('truefalsevec.mat', {'truevec': truevec, 'falsevec': falsevec})\n with open('belong.pickle','wb') as f:\n pickle.dump(belong,f)\n\n\ndef lr():\n belong=None\n with open('belong.pickle', 'rb') as f:\n belong=pickle.load(f)\n mat = io.loadmat('truefalsevec.mat')\n truevec = mat['truevec']\n falsevec = mat['falsevec']\n truelabel = np.ones((truevec.shape[0]))\n trueweight = 110 * np.ones((truevec.shape[0]))\n falselabel = np.zeros((falsevec.shape[0]))\n falseweight = np.ones((falsevec.shape[0]))\n data = sparse.vstack([truevec, falsevec])\n label = np.concatenate([truelabel, falselabel])\n weight = np.concatenate([trueweight, falseweight])\n lrc = LogisticRegression(penalty='l2', solver='newton-cg')\n lrc.fit(data, label, sample_weight=weight)\n predict = lrc.decision_function(data)\n distribution=[]\n for k,v in belong.items():\n truescore=None\n rank=1\n if len(v) !=110:\n print('wrong',len(v))\n for num,s in enumerate(v):\n if s[1]:\n if num!=0:\n print('wrong')\n truescore=predict[s[0]]\n else:\n if predict[s[0]]>truescore:\n rank+=1\n distribution.append(rank)\n plt.figure()\n plt.hist(distribution,bins=100)\n fpr, tpr, thresholds = roc_curve(label, predict, sample_weight=weight)\n plt.figure()\n plt.plot(fpr, tpr)\n return lrc\n\n\ndef rf():\n mat = io.loadmat('truefalsevec.mat')\n truevec = mat['truevec']\n falsevec = mat['falsevec']\n truelabel = np.ones((truevec.shape[0]))\n trueweight = 110 * np.ones((truevec.shape[0]))\n falselabel = np.zeros((falsevec.shape[0]))\n falseweight = np.ones((falsevec.shape[0]))\n data = sparse.vstack([truevec, falsevec])\n label = np.concatenate([truelabel, falselabel])\n weight = np.concatenate([trueweight, falseweight])\n rfc = RandomForestClassifier(n_estimators=100,n_jobs=4)\n rfc.fit(data, label, sample_weight=weight)\n predict = rfc.predict_proba(data)\n fpr, tpr, thresholds = roc_curve(label, predict[:,1], sample_weight=weight)\n plt.plot(fpr, tpr)\n print(fpr)\n print(tpr)\n\ndef svm():\n mat = io.loadmat('truefalsevec.mat')\n truevec = mat['truevec']\n falsevec = mat['falsevec']\n truelabel = np.ones((truevec.shape[0]))\n trueweight = 110 * np.ones((truevec.shape[0]))\n falselabel = np.zeros((falsevec.shape[0]))\n falseweight = np.ones((falsevec.shape[0]))\n data = sparse.vstack([truevec, falsevec])\n label = np.concatenate([truelabel, falselabel])\n weight = np.concatenate([trueweight, falseweight])\n lr = NuSVC()\n lr.fit(data, label, sample_weight=weight)\n predict = lr.decision_function(data)\n fpr, tpr, thresholds = roc_curve(label, predict, sample_weight=weight)\n plt.plot(fpr, tpr)\ndef cos():\n result = [question(q) for q in get_question('solr_lr2.txt')]\n vectorizer = vfit(result)\n veclen = len(vectorizer.vocabulary_)\n print(veclen)\n truescore = None\n falsescore = None\n for i in result:\n if i.standardquestion != None and i.transformquestion != None:\n svec, tvecs = i.bag_of_word(vectorizer)\n svec = np.sqrt(svec / svec.multiply(svec).sum())\n svecs = sparse.csr_matrix(np.ones((tvecs.shape[0], 1))).dot(svec)\n add = svecs.multiply(tvecs).sum(axis=1)\n tsum = np.sqrt(tvecs.multiply(tvecs).sum(axis=1))\n add /= tsum\n if truescore is None:\n truescore = add\n else:\n truescore = np.concatenate([truescore, add])\n else:\n raise Exception('unexpected')\n for i in range(len(result)):\n for j in range(len(result)):\n svec = result[i].standvec\n tvecs = result[j].transvec\n svec = np.sqrt(svec / svec.multiply(svec).sum())\n svecs = sparse.csr_matrix(np.ones((tvecs.shape[0], 1))).dot(svec)\n add = svecs.multiply(tvecs).sum(axis=1)\n tsum = np.sqrt(tvecs.multiply(tvecs).sum(axis=1))\n add /= tsum\n if falsescore is None:\n falsescore = add\n else:\n falsescore = np.concatenate([falsescore, add])\n print(truescore.shape, falsescore.shape)\n predict = np.concatenate([truescore, falsescore])\n truelabel = np.ones((truescore.shape[0]))\n trueweight = 110 * np.ones((truescore.shape[0]))\n falselabel = np.zeros((falsescore.shape[0]))\n falseweight = np.ones((falsescore.shape[0]))\n label = np.concatenate([truelabel, falselabel])\n weight = np.concatenate([trueweight, falseweight])\n fpr, tpr, thresholds = roc_curve(label, predict, sample_weight=weight)\n plt.plot(fpr, tpr)\n\ndef savealigndata():\n result = [aligndata(q) for q in get_question('solr_lr2.txt')]\n # ss=[]\n # tt=[]\n # sss=[]\n # ttt=[]\n slen=[]\n tlen=[]\n tnum=[]\n total=0\n for d in result:\n s,t,flag=d.output()\n if(flag):\n total+=1\n trues=s[0].replace(' ','')\n slen.append(len(trues))\n for i in range(len(t)):\n truet = t[i].replace(' ', '')\n tlen.append(len(truet))\n tnum.append(len(t))\n # for i in range(len(s)):\n # if random() > 1 / 100:\n # ss.append(s[i])\n # tt.append(t[i])\n # else:\n # sss.append(s[i])\n # ttt.append(t[i])\n # for i in range(len(t)):\n # for j in range(len(t)):\n # if i != j:\n # if random()>1/3264:\n # ss.append(t[i])\n # tt.append(t[j])\n # else:\n # sss.append(t[i])\n # ttt.append(t[j])\n print(total)\n # with open('align.s1','w',encoding='utf-8') as f:\n # f.write('\\n'.join(ss))\n # with open('align.t1','w',encoding='utf-8') as f:\n # f.write('\\n'.join(tt))\n # with open('align.s1v','w',encoding='utf-8') as f:\n # f.write('\\n'.join(sss))\n # with open('align.t1v','w',encoding='utf-8') as f:\n # f.write('\\n'.join(ttt))\n plotfreq(slen)\n plotfreq(tlen)\n plotfreq(tnum)\ndef smtout():\n l=None\n with open('h:\\\\test1','r',encoding='utf-8') as f:\n l=f.read().splitlines()\n result=[]\n for i in range(1000):\n j=l[i].find('||| ')\n k=l[i].find(' ||| LexicalReordering0')\n if i%100<20:\n result.append(l[i][j+4:k])\n with open('h:\\\\test1out','w',encoding='utf-8') as f:\n f.write('\\n'.join(result))\n\ndef plotfreq(freq):\n print('均值', np.mean(freq), '中位数', np.median(freq), '众数', mode(freq))\n plt.figure()\n plt.hist(freq, bins=100)\n plt.show()\nif __name__ == '__main__':\n # dump_title()\n # segment_title()\n # title_avg_len()\n # title_tf_plot()\n # title_idf_plot()\n # dump_content()\n # segment_content()\n # content_avg_len()\n # content_tf_plot()\n # content_idf_plot()\n # start=time.time()\n # savelrdata('solr_lr.txt')\n # svm()\n # savelrdata('solr_lr2.txt')\n # lr()\n # rf()\n # # cos()\n # plt.xlabel('False Positive Rate')\n # plt.ylabel('True Positive Rate')\n # plt.title('Receiver operating characteristic example')\n # plt.show()\n savealigndata()\n # smtout()\n\n","sub_path":"solr_statistics.py","file_name":"solr_statistics.py","file_ext":"py","file_size_in_byte":17745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"277036110","text":"import utils\nimport os\nimport wikiparser\nimport time\nfrom argparse import ArgumentParser\n\ndef build_parser():\n\tparser = ArgumentParser()\n\tparser.add_argument('--dir',type=str,\n\t\t\t\tdest='dir',\n\t\t\t\thelp='directory to save the files',\n\t\t\t\trequired=True)\n\tparser.add_argument('--namespace',type=int,\n\t\t\t\tdest='namespace',\n\t\t\t\thelp='namespace to parser',\n\t\t\t\trequired=True)\n\tparser.add_argument('--titlesdir',type=str,\n\t\t\t\tdest='titlesdir',\n\t\t\t\thelp='directories to required titles')\n\tparser.add_argument('--download',action='store_true',\n\t\t\t\tdest='download',\n\t\t\t\thelp='download or not')\n\tparser.add_argument('--f',type=str,\n\t\t\t\tdest='file_dir',\n\t\t\t\thelp='directory to the file if dont download')\n\tparser.add_argument('--idx',type=int,\n\t\t\t\tdest='idx',\n\t\t\t\thelp='index of files to parser',\n\t\t\t\trequired=True)\n\treturn parser\n\ndef main():\n\tparser = build_parser()\n\targs = parser.parse_args()\n\n\tif(args.titlesdir != None):\n\t\twith open(args.titlesdir) as f:\n\t\t\ttitles_ = f.readlines()\n\t\t\ttitles = set(titles_)\n\n\telse: titles = None\n\tif(args.download == True):\n\t\tLINKS = utils.parse_links()\n\t\tlink = LINKS[args.idx]\n\t\t[logfile_dir, file_dir] = utils.download(link,args.idx,args.dir,args.dir,bg=False)\n\t\tunzipped_dir = utils.unzip(args.idx,file_dir,args.dir)\n\telse:\n\t\tassert os.path.exists(args.file_dir)\n\t\tunzipped_dir = args.file_dir\n\n\twikiparser.parser(unzipped_dir,args.dir,args.idx,args.namespace,titles)\n\n\t\t\n\t\nif __name__ == '__main__':\n\tmain()\n","sub_path":"wikipedia_v2.py","file_name":"wikipedia_v2.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"150248918","text":"#from scipy import misc\r\n#import numpy as np\r\nfrom collections import deque\r\n'''Pypy test (faster Python). Numpy is available, but in my settings there were issues with the numpy installation and I skip it for now.\r\n Pypy however doesn't support scipy, which is used as a data source in the original file. \r\n So in order to get the data, modify the original code to produce a binary copy of the image:\r\n \r\nimport pickle \r\n\r\nf = misc.face(gray=True)\r\nf = f.astype(int)\r\nflist = f.tolist();\r\n\r\npickle.dump(obj=flist, file=open(\"flistpy.bin\", \"wb\"), protocol=2); #protocol=3 if Pypy 3 is installed\r\n\r\nAnd run it in your normal Python environment.\r\n\r\nThen run this file in the Pypy environment with adjusting the correct path to load the input.\r\n\r\nIn this version dimensions are set manually (Y, X) in the main function and the access to the lines does not\r\nuses the numpy syntax.\r\n\r\n for y in range(Y):\r\n if (y%20 == 0) : print( str(y) + \"/\"+ str(Y))\r\n # p_ = Fp_[y, :] # y is index of new line p_ : Numpy syntax \r\n p_ = Fp_[y] #lists\r\n\r\nAthor: Todor Arnaudov, 27.1.2018\r\nhttp://research.twenkid.com \r\n'''\r\n\r\n''' Level 1:\r\nlevel_1_working.py\r\n\r\nCross-comparison between consecutive pixels within horizontal scan line (row).\r\nResulting difference patterns dPs (spans of pixels forming same-sign differences)\r\nand relative match patterns vPs (spans of pixels forming same-sign predictive value)\r\nare redundant representations of each line of pixels.\r\nThis code is optimized for variable visibility rather than speed \r\npostfix '_' distinguishes array name from identical element name \r\n\r\nAuthor: Boris Kazachenko, http://www.cognitivealgorithm.info \r\n\r\n'''\r\n\r\n\r\ndef pre_comp(typ, e_, A, r): # pre-processing for comp recursion within pattern\r\n\r\n A += a # filter accumulation compensates for redundancy of fv overlap\r\n X = len(e_)\r\n\r\n olp, vP_, dP_ = 0, [], [] # olp is common for both:\r\n vP = 0, 0, 0, 0, 0, [], [] # pri_s, I, D, V, rv, t_, olp_\r\n dP = 0, 0, 0, 0, 0, [], [] # pri_sd, Id, Dd, Vd, rd, d_, dolp_\r\n\r\n if typ: # comparison range increment within e_ = t_ of vP\r\n\r\n r += 1 # comp range counter, recorded within Ps formed by re_comp\r\n for x in range(r+1, X):\r\n\r\n p, ifd, ifv = e_[x] # ifd, ifv not used, directional pri_p accum only\r\n pri_p, fd, fv = e_[x-r] # for comparison of r-pixel-distant pixels:\r\n\r\n fd, fv, vP, dP, vP_, dP_, olp = \\\r\n re_comp(x, p, pri_p, fd, fv, vP, dP, vP_, dP_, olp, X, A, r)\r\n\r\n else: # comparison derivation incr within e_ = d_ of dP (not tuples per range incr?)\r\n\r\n pri_d = e_[0] # no deriv_incr while r < min_r, only more fuzzy\r\n fd, fv = 0, 0\r\n\r\n for x in range(1, X):\r\n d = e_[x]\r\n\r\n fd, fv, vP, dP, vP_, dP_, olp = \\\r\n re_comp(x, d, pri_d, fd, fv, vP, dP, vP_, dP_, olp, X, A, r)\r\n\r\n pri_d = d\r\n\r\n return vP_, dP_ # local vP_ + dP_ replaces t_ or d_\r\n\r\n\r\ndef form_P(typ, P, alt_P, P_, alt_P_, olp, pri_p, fd, fv, x, X, A, r):\r\n\r\n # accumulation, termination, recursion within patterns (vPs and dPs)\r\n\r\n if typ: s = 1 if fv >= 0 else 0 # sign of fd, 0 is positive?\r\n else: s = 1 if fd >= 0 else 0 # sign of fv, 0 is positive?\r\n\r\n pri_s, I, D, V, rf, e_, olp_ = P # debug: 0 values in P?\r\n\r\n if x > r + 2 and (s != pri_s or x == X - 1): # P is terminated and evaluated\r\n\r\n if typ:\r\n if len(e_) > r + 3 and pri_s == 1 and V > A + aV: # minimum of 3 tuples\r\n rf = 1 # incr range flag\r\n e_.append(pre_comp(1, e_, A, r)) # comparison range incr within e_ = t_\r\n\r\n else:\r\n if len(e_) > 3 and abs(D) > A + aD: # minimum of 3 ds\r\n rf = 1 # incr deriv flag\r\n r = 1 # consecutive-d comp\r\n e_.append(pre_comp(0, e_, A, r)) # comp derivation incr within e_ = d_\r\n\r\n P = type, pri_s, I, D, V, rf, e_, olp_\r\n P_.append(P) # output to level_2\r\n # print (\"type:\", type, \"pri_s:\", pri_s, \"I:\", I, \"D:\", D, \"V:\", V, \"rf:\", rf, \"e_:\", e_, \"olp_:\", olp_)\r\n\r\n o = len(P_), olp # index of current P and terminated olp are buffered in alt_olp_\r\n alt_P[6].append(o)\r\n o = len(alt_P_), olp # index of current alt_P and terminated olp buffered in olp_\r\n olp_.append(o)\r\n\r\n olp, I, D, V, rf, e_, olp_ = 0, 0, 0, 0, 0, [], [] # initialized P and olp\r\n\r\n pri_s = s # vP (span of pixels forming same-sign v) is incremented:\r\n I += pri_p # ps summed within vP\r\n D += fd # fuzzy ds summed within vP\r\n V += fv # fuzzy vs summed within vP\r\n\r\n if typ:\r\n t = pri_p, fd, fv # inputs for inc_rng comp are tuples, vs. pixels for initial comp\r\n e_.append(t)\r\n else:\r\n e_.append(fd) # prior fds of the same sign are buffered within dP\r\n\r\n P = pri_s, I, D, V, rf, e_, olp_\r\n\r\n return P, alt_P, P_, alt_P_, olp # alt_ and _alt_ are accumulated per line\r\n\r\n\r\ndef re_comp(x, p, pri_p, fd, fv, vP, dP, vP_, dP_, olp, X, A, r):\r\n\r\n # recursive comp within vPs | dPs, called from pre_comp(), which is called from form_P\r\n\r\n d = p - pri_p # difference between consecutive pixels\r\n m = min(p, pri_p) # match between consecutive pixels\r\n v = m - A # relative match (predictive value) between consecutive pixels\r\n\r\n fd += d # fuzzy d accumulates ds between p and all prior ps in r via range_incr()\r\n fv += v # fuzzy v; lower-r fv and fd are in lower Ps, different for p and pri_p\r\n\r\n # formation of value pattern vP: span of pixels forming same-sign fv s:\r\n\r\n vP, dP, vP_, dP_, olp = \\\r\n form_P(1, vP, dP, vP_, dP_, olp, pri_p, fd, fv, x, X, A, r)\r\n\r\n # formation of difference pattern dP: span of pixels forming same-sign fd s:\r\n\r\n dP, vP, dP_, vP_, olp = \\\r\n form_P(0, dP, vP, dP_, vP_, olp, pri_p, fd, fv, x, X, A, r)\r\n\r\n olp += 1 # overlap between concurrent vP and dP, to be buffered in olp_s\r\n\r\n return fd, fv, vP, dP, vP_, dP_, olp # for next-p comp, vP and dP increment, output\r\n\r\n\r\ndef comp(x, p, it_, vP, dP, vP_, dP_, olp, X, A, r): # pixel is compared to r prior pixels\r\n\r\n index = 0 # alternative: for index in range(0, len(it_)-1): doesn't work quite right\r\n\r\n for it in it_: # incomplete tuples with fd, fm summation range from 0 to r\r\n pri_p, fd, fm = it\r\n\r\n d = p - pri_p # difference between pixels\r\n m = min(p, pri_p) # match between pixels\r\n\r\n fd += d # fuzzy d: sum of ds between p and all prior ps within it_\r\n fm += m # fuzzy m: sum of ms between p and all prior ps within it_\r\n\r\n it = pri_p, fd, fm\r\n it_[index] = it\r\n index += 1\r\n\r\n if len(it_) == r: # current tuple fd and fm are accumulated over range = r\r\n fv = fm - A\r\n\r\n # formation of value pattern vP: span of pixels forming same-sign fv s:\r\n\r\n vP, dP, vP_, dP_, olp = \\\r\n form_P(1, vP, dP, vP_, dP_, olp, pri_p, fd, fv, x, X, A, r)\r\n\r\n # formation of difference pattern dP: span of pixels forming same-sign fd s:\r\n\r\n dP, vP, dP_, vP_, olp = \\\r\n form_P(0, dP, vP, dP_, vP_, olp, pri_p, fd, fv, x, X, A, r)\r\n\r\n olp += 1 # overlap between vP and dP, stored in both and terminated with either\r\n\r\n it = p, 0, 0 # or left_fd and left_fm, for bilateral accumulation?\r\n it_.appendleft(it) # new tuple is added, displacing completed tuple\r\n\r\n return it_, vP, dP, vP_, dP_, olp # for next-p comparison, vP and dP increment, output\r\n\r\n\r\ndef root_1D(Fp_): # last '_' distinguishes array name from element name\r\n\r\n FP_ = [] # output frame of vPs: relative-match patterns, and dPs: difference patterns\r\n # Y, X = Fp_.shape # Y: frame height, X: frame width\r\n Y = 768; X = 1024;\r\n min_r = 3 # fuzzy comp range\r\n\r\n global a; a = 63\r\n global aV; aV = 63 * min_r # min V for initial incremental-range comp(t_)\r\n global aD; aD = 63 * min_r # min |D| for initial incremental-derivation comp(d_)\r\n\r\n A = a * min_r # initial min match for positive vP inclusion, += a per recursion\r\n\r\n for y in range(Y):\r\n if (y%20 == 0) : print( str(y) + \"/\"+ str(Y)) # + str(time.time()));\r\n #if (y>77): return FP_\r\n #p_ = Fp_[y, :] # y is index of new line p_ : Numpy syntax\r\n\r\n p_ = Fp_[y] #lists\r\n\r\n r, x, olp, vP_, dP_ = min_r, 0, 0, [], [] # initialized at each level\r\n vP = 0, 0, 0, 0, 0, [], [] # pri_s, I, D, V, rv, t_, olp_\r\n dP = 0, 0, 0, 0, 0, [], [] # pri_sd, Id, Dd, Vd, rd, d_, dolp_\r\n\r\n it_ = deque(maxlen=r) # incomplete fuzzy tuples: summation range < r\r\n pri_t = p_[0], 0, 0 # no d, m at x = 0\r\n it_.append(pri_t)\r\n\r\n for x in range(1, X): # cross-compares consecutive pixels\r\n p = p_[x] # new pixel, fuzzy comp to it_:\r\n\r\n it_, vP, dP, vP_, dP_, olp = \\\r\n comp(x, p, it_, vP, dP, vP_, dP_, olp, X, A, r)\r\n\r\n LP_ = vP_, dP_ # line of patterns formed from a line of pixels\r\n FP_.append(LP_) # line of patterns is added to frame of patterns, y = len(FP_)\r\n\r\n return FP_ # output to level 2\r\n\r\nimport pickle\r\n\r\n#f = misc.face(gray=True) # input frame of pixels\r\n#f = f.astype(int)\r\npath = \"flistpy.bin\" #local directory or set the path\r\nf = pickle.load(file=open(path, \"rb\")); #, protocol=2);\r\nfp_ = root_1D(f)\r\n\r\n#DUMP frames for analysis:\r\npickle.dump(obj=fp_, file=open(\"fp_pypy.bin\", \"wb\"))\r\n\r\n#print(fp_) #use only with > fp_output.txt - huge output\r\n","sub_path":"le1pypy.py","file_name":"le1pypy.py","file_ext":"py","file_size_in_byte":9540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"377822475","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 8 21:54:06 2018\n\n@author: smalldave\n\"\"\"\n\n'''\n Deep Spatio-temporal Residual Networks\n'''\n\nfrom keras.layers import (\n Input,\n Activation,\n add,\n Dense,\n Reshape,\n Flatten,\n merge\n)\nimport pandas as pd\nimport numpy as np\nimport os\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Model\nfrom netCDF4 import Dataset\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n#from keras.utils.visualize_util import plot\n\ndef get_streamflow(dayN,day0):\n ganges = pd.read_csv('/media/smalldave/Storage/GBM/Ganges.csv')\n dates = (ganges.Year > 1984) & (ganges.Year<2018)\n ganges2 = ganges[dates]\n dates = (ganges2.Month>5) & (ganges2.Month<10)\n ganges2 = ganges2.loc[dates]\n ganges2 = ganges2.reset_index()\n frame = pd.DataFrame(ganges2['Q (m3/s)'])\n frame.columns = ['Q']\n for lag in np.arange(dayN,day0+1):\n x = ganges.loc[ganges2['index'] - lag, 'Q (m3/s)' ]\n x = pd.DataFrame(x)\n x.columns = [''.join(['Q_',str(lag)])] \n x.index = frame.index\n frame = pd.concat([frame,x],axis=1)\n return frame,ganges2\n\ndef _shortcut(input, residual):\n print (input.shape)\n print (residual.shape)\n return add([input, residual])\n\n\ndef _bn_relu_conv(nb_filter, nb_row, nb_col, subsample=(1, 1), bn=False):\n def f(input):\n if bn:\n input = BatchNormalization(mode=0, axis=1)(input)\n activation = Activation('relu')(input)\n return Conv2D(padding=\"same\", strides=subsample, filters=nb_filter, kernel_size=(nb_row,nb_col))(activation)\n return f\n\n\ndef _residual_unit(nb_filter, init_subsample=(1, 1)):\n def f(input):\n residual = _bn_relu_conv(nb_filter, 3, 3)(input)\n residual = _bn_relu_conv(nb_filter, 3, 3)(residual)\n return _shortcut(input, residual)\n return f\n\n\ndef ResUnits(residual_unit, nb_filter, repetations=1):\n def f(input):\n for i in range(repetations):\n init_subsample = (1, 1)\n input = residual_unit(nb_filter=nb_filter,\n init_subsample=init_subsample)(input)\n return input\n return f\n\n\ndef stresnet(c_conf=(3, 2, 32, 32), p_conf=(3, 2, 32, 32), t_conf=(3, 2, 32, 32), external_dim=8, nb_residual_unit=3):\n '''\n C - Temporal Closeness\n P - Period\n T - Trend\n conf = (len_seq, nb_flow, map_height, map_width)\n external_dim\n '''\n\n # main input\n main_inputs = []\n outputs = []\n for conf in [c_conf, p_conf, t_conf]:\n if conf is not None:\n len_seq, nb_flow, map_height, map_width = conf\n input = Input(shape=(nb_flow * len_seq, map_height, map_width))\n main_inputs.append(input)\n # Conv1\n conv1 = Conv2D (padding=\"same\", filters=64, kernel_size=(3, 3))(input)\n # [nb_residual_unit] Residual Units\n residual_output = ResUnits(_residual_unit, nb_filter=64,\n repetations=nb_residual_unit)(conv1)\n # Conv2\n activation = Activation('relu')(residual_output)\n conv2 = Conv2D(padding=\"same\", filters=nb_flow, kernel_size=(3, 3))(activation)\n outputs.append(conv2)\n\n # parameter-matrix-based fusion\n if len(outputs) == 1:\n main_output = outputs[0]\n else:\n from .iLayer import iLayer\n new_outputs = []\n for output in outputs:\n new_outputs.append(iLayer()(output))\n main_output = add(new_outputs)\n\n # fusing with external component\n if external_dim != None and external_dim > 0:\n # external input\n external_input = Input(shape=(external_dim,))\n main_inputs.append(external_input)\n embedding = Dense(output_dim=10)(external_input)\n embedding = Activation('relu')(embedding)\n h1 = Dense(output_dim=nb_flow * map_height * map_width)(embedding)\n print(h1)\n activation = Activation('relu')(h1)\n external_output = Reshape((nb_flow, map_height, map_width))(activation)\n main_output = add([main_output, external_output])\n \n print('external_dim:', external_dim)\n\n #main_output = Activation('tanh')(main_output)\n flat = Flatten()(main_output) \n flow = Dense(units=1)(flat)\n flow = Activation('relu')(flow)\n model = Model(inputs=main_inputs, outputs=flow)\n\n return model\n\nlat0 = 17\nlat1 = 32+8\nlon0 = 70-8\nlon1 = 101+8\n\nfilename='/media/smalldave/Storage/GBM/persiann_gfs_15day.nc'\ninfile=Dataset(filename,'r')\nlat=list(infile.variables['lat'][:])\nlon=list(infile.variables['lon'][:])\n\nprecip=infile.variables['precipitation'][:,:,lat.index(lat0):lat.index(lat1)+1,lon.index(lon0):lon.index(lon1)+1]\n\n\nprint(precip.shape)\nframe,ganges2 = get_streamflow(15,20)\n\ntraining = ganges2.Year < 2005\ntraining_index = ganges2.loc[training].index\n\ntest = (ganges2.Year >2004) & (ganges2.Year<2017)\ntest_index = ganges2.loc[test].index\n\ntrainingFRAME = frame.loc[training_index]\ntestFRAME = frame.loc[test_index]\ntrainingPRECIP = precip[training_index,:,:,:]\ntestPRECIP = precip[test_index,:,:,:]\ntrainingQ = np.array(trainingFRAME['Q'])\ntestQ = np.array(testFRAME['Q'])\ntrainingFRAME.drop('Q',axis=1,inplace=True)\ntestFRAME.drop('Q',axis=1,inplace=True)\n\ntrainingFRAME = np.array(trainingFRAME)\ntestFRAME = np.array(testFRAME)\n\ntime,fhour,lat_,lon_ = np.shape(trainingPRECIP)\nnb_residual_unit = 16\nnb_epoch = 500\nbatch_size = 32\n\nc_conf = (fhour,1,lat_,lon_)\n_,external_dim = np.shape(trainingFRAME) \n#external_dim = 0\nlr = 0.0002\nhyperparams_name = 'c{}.resunit{}.lr{}'.format(21, nb_residual_unit, lr)\nfname_param = \"/media/smalldave/Storage/GBM/best_parameters.hdf5\"\n\nearly_stopping = EarlyStopping(monitor='mean_squared_error', patience=10, mode='min')\nmodel_checkpoint = ModelCheckpoint(fname_param, verbose=0, save_best_only=True, mode='min')\n\nmodel = stresnet(c_conf=c_conf, p_conf=None, t_conf=None,\n external_dim=external_dim, nb_residual_unit=nb_residual_unit)\n# \n \nmodel.compile(loss='mse', optimizer='adam', metrics=['mse'])\n\nprint(model.summary())\n#\nXtrain = [trainingPRECIP,trainingFRAME]\n#Xtrain = trainingPRECIP\n\nXtest = [testPRECIP,testFRAME]\n#Xtest = testPRECIP\nhistory = model.fit(Xtrain, trainingQ,\n epochs=nb_epoch,\n batch_size=batch_size,\n validation_split=0.1,\n callbacks=[early_stopping,model_checkpoint],\n verbose=1)\n# \n#model.save_weights(os.path.join('MODEL', '{}.h5'.format(hyperparams_name)), overwrite=True)\n#pickle.dump((history.history), open(os.path.join(path_result, '{}.history.pkl'.format(hyperparams_name)), 'wb'))\n#\n#model.load_weights(fname_param)\nscore = model.evaluate(Xtrain, trainingQ, batch_size=trainingQ.shape[0] // 48, verbose=0)\nprint('Train score: %.6f rmse (norm): %.6f' %\n (score[0], score[1]))\n\nscore = model.evaluate(Xtest, testQ, batch_size=testQ.shape[0], verbose=0)\nprint('Test score: %.6f rmse (norm): %.6f' %\n (score[0], score[1]))\n\nQhat = model.predict(Xtest, batch_size=testQ.shape[0], verbose=0)\nQ=pd.concat([pd.DataFrame(Qhat),pd.DataFrame(testQ)],axis=1)\nQ.columns = ['Predicted','Observed']\n","sub_path":"David/resnet_model_precip.py","file_name":"resnet_model_precip.py","file_ext":"py","file_size_in_byte":7251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"538157181","text":"from typing import Callable, List, Optional, Set, Tuple, Union\n\nimport numpy as np\n\nfrom .dataset import JetDataset\nfrom .normalisations import NormaliseABC\nfrom .utils import (\n checkConvertElements,\n checkDownloadZenodoDataset,\n checkListNotEmpty,\n checkStrToList,\n getOrderedFeatures,\n getSplitting,\n)\n\n\nclass QuarkGluon(JetDataset):\n \"\"\"\n PyTorch ``torch.unit.data.Dataset`` class for the Quark Gluon Jets dataset. Either jets with\n or without bottom and charm quark jets can be selected (``with_bc`` flag).\n\n If npz files are not found in the ``data_dir`` directory then dataset will be automatically\n downloaded from Zenodo (https://zenodo.org/record/3164691).\n\n Args:\n jet_type (Union[str, Set[str]], optional): individual type or set of types out of\n 'g' (gluon) and 'q' (light quarks). Defaults to \"all\".\n data_dir (str, optional): directory in which data is (to be) stored. Defaults to \"./\".\n with_bc (bool, optional): with or without bottom and charm quark jets. Defaults to True.\n particle_features (List[str], optional): list of particle features to retrieve. If empty\n or None, gets no particle features. Defaults to\n ``[\"pt\", \"eta\", \"phi\", \"pdgid\"]``.\n jet_features (List[str], optional): list of jet features to retrieve. If empty or None,\n gets no jet features. Defaults to\n ``[\"type\"]``.\n particle_normalisation (NormaliseABC, optional): optional normalisation to apply to\n particle data. Defaults to None.\n jet_normalisation (NormaliseABC, optional): optional normalisation to apply to jet data.\n Defaults to None.\n particle_transform (callable, optional): A function/transform that takes in the particle\n data tensor and transforms it. Defaults to None.\n jet_transform (callable, optional): A function/transform that takes in the jet\n data tensor and transforms it. Defaults to None.\n num_particles (int, optional): number of particles to retain per jet, max of 153.\n Defaults to 153.\n split (str, optional): dataset split, out of {\"train\", \"valid\", \"test\", \"all\"}. Defaults\n to \"train\".\n split_fraction (List[float], optional): splitting fraction of training, validation,\n testing data respectively. Defaults to [0.7, 0.15, 0.15].\n seed (int, optional): PyTorch manual seed - important to use the same seed for all\n dataset splittings. Defaults to 42.\n file_list (List[str], optional): list of files to load, if full dataset is not required.\n Defaults to None (will load all files).\n \"\"\"\n\n _zenodo_record_id = 3164691\n\n # False - without bc, True - with bc\n _file_list = {\n False: [\n \"QG_jets.npz\",\n \"QG_jets_1.npz\",\n \"QG_jets_2.npz\",\n \"QG_jets_3.npz\",\n \"QG_jets_4.npz\",\n \"QG_jets_5.npz\",\n \"QG_jets_6.npz\",\n \"QG_jets_7.npz\",\n \"QG_jets_8.npz\",\n \"QG_jets_9.npz\",\n \"QG_jets_10.npz\",\n \"QG_jets_11.npz\",\n \"QG_jets_12.npz\",\n \"QG_jets_13.npz\",\n \"QG_jets_14.npz\",\n \"QG_jets_15.npz\",\n \"QG_jets_16.npz\",\n \"QG_jets_17.npz\",\n \"QG_jets_18.npz\",\n \"QG_jets_19.npz\",\n ],\n True: [\n \"QG_jets_withbc_0.npz\",\n \"QG_jets_withbc_1.npz\",\n \"QG_jets_withbc_2.npz\",\n \"QG_jets_withbc_3.npz\",\n \"QG_jets_withbc_3.npz\",\n \"QG_jets_withbc_4.npz\",\n \"QG_jets_withbc_5.npz\",\n \"QG_jets_withbc_6.npz\",\n \"QG_jets_withbc_7.npz\",\n \"QG_jets_withbc_8.npz\",\n \"QG_jets_withbc_9.npz\",\n \"QG_jets_withbc_10.npz\",\n \"QG_jets_withbc_11.npz\",\n \"QG_jets_withbc_12.npz\",\n \"QG_jets_withbc_13.npz\",\n \"QG_jets_withbc_14.npz\",\n \"QG_jets_withbc_15.npz\",\n \"QG_jets_withbc_16.npz\",\n \"QG_jets_withbc_17.npz\",\n \"QG_jets_withbc_18.npz\",\n \"QG_jets_withbc_19.npz\",\n ],\n }\n\n max_num_particles = 153\n\n jet_types = [\"g\", \"q\"]\n all_particle_features = [\"pt\", \"eta\", \"phi\", \"pdgid\"]\n all_jet_features = [\"type\"]\n splits = [\"train\", \"valid\", \"test\", \"all\"]\n\n def __init__(\n self,\n jet_type: Union[str, Set[str]] = \"all\",\n data_dir: str = \"./\",\n with_bc: bool = True,\n particle_features: List[str] = all_particle_features,\n jet_features: List[str] = all_jet_features,\n particle_normalisation: Optional[NormaliseABC] = None,\n jet_normalisation: Optional[NormaliseABC] = None,\n particle_transform: Optional[Callable] = None,\n jet_transform: Optional[Callable] = None,\n num_particles: int = max_num_particles,\n split: str = \"train\",\n split_fraction: List[float] = [0.7, 0.15, 0.15],\n seed: int = 42,\n file_list: List[str] = None,\n ):\n self.particle_data, self.jet_data = self.getData(\n jet_type,\n data_dir,\n with_bc,\n particle_features,\n jet_features,\n num_particles,\n split,\n split_fraction,\n seed,\n file_list,\n )\n\n super().__init__(\n data_dir=data_dir,\n particle_features=particle_features,\n jet_features=jet_features,\n particle_normalisation=particle_normalisation,\n jet_normalisation=jet_normalisation,\n particle_transform=particle_transform,\n jet_transform=jet_transform,\n num_particles=num_particles,\n )\n\n self.jet_type = jet_type\n self.split = split\n self.split_fraction = split_fraction\n\n @classmethod\n def getData(\n cls: JetDataset,\n jet_type: Union[str, Set[str]] = \"all\",\n data_dir: str = \"./\",\n with_bc: bool = True,\n particle_features: List[str] = all_particle_features,\n jet_features: List[str] = all_jet_features,\n num_particles: int = max_num_particles,\n split: str = \"all\",\n split_fraction: List[float] = [0.7, 0.15, 0.15],\n seed: int = 42,\n file_list: List[str] = None,\n ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:\n \"\"\"\n Downloads, if needed, and loads and returns Quark Gluon data.\n\n Args:\n jet_type (Union[str, Set[str]], optional): individual type or set of types out of\n 'g' (gluon) and 'q' (light quarks). Defaults to \"all\".\n data_dir (str, optional): directory in which data is (to be) stored. Defaults to \"./\".\n with_bc (bool, optional): with or without bottom and charm quark jets. Defaults to True.\n particle_features (List[str], optional): list of particle features to retrieve. If empty\n or None, gets no particle features. Defaults to\n ``[\"pt\", \"eta\", \"phi\", \"pdgid\"]``.\n jet_features (List[str], optional): list of jet features to retrieve. If empty or None,\n gets no jet features. Defaults to\n ``[\"type\"]``.\n num_particles (int, optional): number of particles to retain per jet, max of 153.\n Defaults to 153.\n split (str, optional): dataset split, out of {\"train\", \"valid\", \"test\", \"all\"}. Defaults\n to \"train\".\n split_fraction (List[float], optional): splitting fraction of training, validation,\n testing data respectively. Defaults to [0.7, 0.15, 0.15].\n seed (int, optional): PyTorch manual seed - important to use the same seed for all\n dataset splittings. Defaults to 42.\n file_list (List[str], optional): list of files to load, if full dataset is not required.\n Defaults to None (will load all files).\n\n Returns:\n Tuple[Optional[np.ndarray], Optional[np.ndarray]]: particle data, jet data\n \"\"\"\n\n assert num_particles <= cls.max_num_particles, (\n f\"num_particles {num_particles} exceeds max number of \"\n + f\"particles in the dataset {cls.max_num_particles}\"\n )\n\n jet_type = checkConvertElements(jet_type, cls.jet_types, ntype=\"jet type\")\n type_indices = [cls.jet_types.index(t) for t in jet_type]\n\n particle_features, jet_features = checkStrToList(particle_features, jet_features)\n use_particle_features, use_jet_features = checkListNotEmpty(particle_features, jet_features)\n\n particle_data = []\n jet_data = []\n\n file_list = cls._file_list[with_bc] if file_list is None else file_list\n\n for file_name in file_list:\n npz_file = checkDownloadZenodoDataset(\n data_dir,\n dataset_name=file_name,\n record_id=cls._zenodo_record_id,\n key=file_name,\n )\n\n print(f\"Loading {file_name}\")\n data = np.load(npz_file)\n\n # select only specified types of jets (qcd or top or both)\n jet_selector = np.sum([data[\"y\"] == i for i in type_indices], axis=0).astype(bool)\n\n if use_particle_features:\n pf = data[\"X\"][jet_selector][:, :num_particles]\n\n # zero-pad if needed (datasets have different numbers of max particles)\n pf_np = pf.shape[1]\n if pf_np < num_particles:\n pf = np.pad(pf, ((0, 0), (0, num_particles - pf_np), (0, 0)), constant_values=0)\n\n # reorder if needed\n pf = getOrderedFeatures(pf, particle_features, cls.all_particle_features)\n\n if use_jet_features:\n jf = data[\"y\"][jet_selector].reshape(-1, 1)\n jf = getOrderedFeatures(jf, jet_features, cls.all_jet_features)\n\n length = np.sum(jet_selector)\n\n # shuffling and splitting into training and test\n lcut, rcut = getSplitting(length, split, cls.splits, split_fraction)\n\n np.random.seed(seed)\n randperm = np.random.permutation(length)\n\n if use_particle_features:\n pf = pf[randperm][lcut:rcut]\n particle_data.append(pf)\n\n if use_jet_features:\n jf = jf[randperm][lcut:rcut]\n jet_data.append(jf)\n\n particle_data = np.concatenate(particle_data, axis=0) if use_particle_features else None\n jet_data = np.concatenate(jet_data, axis=0) if use_jet_features else None\n\n return particle_data, jet_data\n\n def extra_repr(self) -> str:\n ret = f\"Including {self.jet_type} jets\"\n\n if self.split == \"all\":\n ret += \"\\nUsing all data (no split)\"\n else:\n ret += (\n f\"\\nSplit into {self.split} data out of {self.splits} possible splits, \"\n f\"with splitting fractions {self.split_fraction}\"\n )\n\n return ret\n","sub_path":"jetnet/datasets/qgjets.py","file_name":"qgjets.py","file_ext":"py","file_size_in_byte":11101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"584648917","text":"\"\"\"\nCopyright (c) 2014, Christine Dodrill\nAll rights reserved.\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\n 3. This notice may not be removed or altered from any source\n distribution.\n\"\"\"\n\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\n\nNAME=\"The Pirate Bay scraper\"\nDESC=\"TPB torrent lookups\"\n\nTPB_REGEX = re.compile('(thepiratebay\\..*)/torrent/([\\w-]+)')\n\ndef initModule(cod):\n cod.s2scommands[\"PRIVMSG\"].append(thepiratebayLookup)\n\ndef destroyModule(cod):\n cod.s2scommands[\"PRIVMSG\"].remove(thepiratebayLookup)\n\ndef rehash():\n pass\n\ndef thepiratebayLookup(cod, line):\n global TPB_REGEX\n\n if line.args[0] not in cod.channels:\n return\n\n chatline = line.args[-1]\n\n torrentid = None\n\n try:\n torrentid = TPB_REGEX.split(chatline)[2]\n except:\n return\n\n try:\n info = requests.get(\"https://thepiratebay.se/torrent/%s\" % torrentid).text\n soup = BeautifulSoup(info)\n\n link = filter((lambda x: x[\"href\"].startswith(\"magnet\")),\n soup.find_all('a', href=True))[0][\"href\"][:60]\n\n title = soup.find_all(\"title\")[0].text.split(\"(download\")[0].strip()\n\n string = \"^ The Pirate Bay: %s - %s\" % (title, link)\n\n cod.privmsg(line.args[0], string)\n except Exception as e:\n cod.privmsg(line.args[0], \"There was some error looking up that torrent: %s\" % e.message)\n\n","sub_path":"modules/scrapers/thepiratebay.py","file_name":"thepiratebay.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"505506950","text":"import argparse\r\nimport oauth2 as oauth\r\nimport urllib.request as urllib\r\nimport json\r\nimport sys\r\nimport csv\r\nimport codecs\r\n# See Assignment 1 instructions for how to get these credentials\r\naccess_token_key = \"635142863-lvrE1s8c84YK3Wu5yXR6G6a6LrcgWiB4XBc90tL8\"\r\naccess_token_secret = \"ssNUVcWfkSexLFlHw5S7yEvRoUQGzHqOPwNlamuxIsIlw\"\r\n\r\nconsumer_key = \"1rGsmsAe6rT3pIaZ5e5lRAGIe\"\r\nconsumer_secret = \"P9CyHo0MZvf3E2Ims1Mb6e0bl9763BWFN7HCRpHeH6OaZnuYzA\"\r\n\r\n_debug = 0\r\n\r\noauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)\r\noauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)\r\n\r\nsignature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()\r\n\r\nhttp_method = \"GET\"\r\n\r\n\r\nhttp_handler = urllib.HTTPHandler(debuglevel=_debug)\r\nhttps_handler = urllib.HTTPSHandler(debuglevel=_debug)\r\n\r\n'''\r\nConstruct, sign, and open a twitter request\r\nusing the hard-coded credentials above.\r\n'''\r\ndef twitterreq(url, method, parameters):\r\n req = oauth.Request.from_consumer_and_token(oauth_consumer,\r\n token=oauth_token,\r\n http_method=http_method,\r\n http_url=url,\r\n parameters=parameters)\r\n\r\n req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)\r\n\r\n headers = req.to_header()\r\n\r\n if http_method == \"POST\":\r\n encoded_post_data = req.to_postdata()\r\n else:\r\n encoded_post_data = None\r\n url = req.to_url()\r\n\r\n opener = urllib.OpenerDirector()\r\n opener.add_handler(http_handler)\r\n opener.add_handler(https_handler)\r\n\r\n response = opener.open(url, encoded_post_data)\r\n\r\n return response\r\n\r\ndef fetch_samples():\r\n url = \"https://stream.twitter.com/1.1/statuses/sample.json?language=en\"\r\n parameters = []\r\n response = twitterreq(url, \"GET\", parameters)\r\n for line in response:\r\n print (line.strip().decode('utf-8'))\r\n\r\ndef fetch_by_terms(term):\r\n url = \"https://api.twitter.com/1.1/search/tweets.json?count=100\"\r\n parameters = [(\"q\", term)]\r\n response = twitterreq(url, \"GET\", parameters)\r\n print (response.readline())\r\n\r\ndef fetch_by_user_names(user_name_file):\r\n #TODO: Fetch the tweets by the list of usernames and write them to stdout in the CSV format\r\n sn_file = open(user_name_file)\r\n url =\"https://api.twitter.com/1.1/statuses/user_timeline.json\"\r\n with open('result.csv','w') as csvfile:\r\n n =['User','Tweet']\r\n print (\"User , Tweet\")\r\n w = csv.writer(csvfile)\r\n w.writerow(n)\r\n for line in sn_file:\r\n user = line.strip()\r\n parameters = [(\"screen_name\", user),(\"count\",100)]\r\n response = twitterreq(url, \"GET\" ,parameters)\r\n # resp =response.read()\r\n # reader = codecs.getreader(\"utf-8\")\r\n #obj =json.load(reader(response))\r\n str_response =response.read().decode('utf-8')\r\n #obj = json.loads(str_response)\r\n json_load=json.loads(str_response)\r\n for p in json_load :\r\n w.writerow((user,p['text']))\r\n print(user,\",\",p['text'])\r\n #w.writerow((p['text']))\r\n #texts =json_load['text']\r\n #coded =texts.encode('utf-8')\r\n #s =str(coded)\r\n #print(s[2:-1])\r\n\t #for tweet in response\r\n #print(tweet['text'].encode('utf-8'))\r\n #print(user)\r\n # writer = csv.writer(sys.stdout)\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-c', required=True, help='Enter the command')\r\n parser.add_argument('-term', help='Enter the search term')\r\n parser.add_argument('-file', help='Enter the user name file')\r\n opts = parser.parse_args()\r\n if opts.c == \"fetch_samples\":\r\n fetch_samples()\r\n elif opts.c == \"fetch_by_terms\":\r\n term = opts.term\r\n print (term)\r\n fetch_by_terms(term)\r\n elif opts.c == \"fetch_by_user_names\":\r\n user_name_file = opts.file\r\n fetch_by_user_names(user_name_file)\r\n else:\r\n raise Exception(\"Unrecognized command\")\r\n\r\n","sub_path":"fetch_tweets_umenon3.py","file_name":"fetch_tweets_umenon3.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"11315722","text":"# -*- coding: utf-8 -*-\nfront_cam = 0\nside_cam = 1\nfull_speed = 20\nturn_speed = full_speed * 0.8\nEMLARGE_RATIO = 1.2\nmodel_prefix=\"/home/root/workspace/autostart/src/\"\n# mession config\n# one more for background\nMISSION_NUM = 9\nmission_low = 0.3\nmission_high = 0.75\nMISS_DURATION = 200\nmission_label_list = {\n\t0: \"background\",\n\t1: \"daijun\",\n\t2: \"dingxiang\",\n\t3: \"dunhuang\",\n\t4: \"liangcao\",\n\t5: \"rab\",\n\t6: \"red_target\",\n\t#7: \"zhangpeng\",\n\t7: \"campsite\"\n}\n\n# sign config\nMAX_SIGN_PER_FRAME = 2\nsign_list = {\n\t0: \"background\",\n\t1: \"campsite\",\n\t2: \"cereal\",\n\t3: \"lump\",\n\t4: \"target\",\n\t5: \"tower\",\n\t6: \"enjoy\"\n}\n# cruise model\ncruise = {\n\t\"model\":model_prefix + \"models/black_img720\"\n}\n# sign models\nsign = {\n\t\"model\": model_prefix + \"models/sign707\",\n\t\"threshold\": 0.4,\n\t\"label_list\": sign_list,\n\t# label = 0 is background\n\t\"class_num\": 7\n}\n# task model\ntask = {\n\t\"model\":model_prefix + \"models/task715\",\n\t\"threshold\":0.6,\n\t\"label_list\":mission_label_list,\n\t#\"class_num\": 6\n}\n\n\n\n# sign_threshold = 0.3;\n# task_threshold = 0.4;\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"369460419","text":"from itertools import permutations\nfrom math import factorial as f\n'''\nQ: What is the millionth lexicographic permutation\nof the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?\n'''\ndef main():\n\tp = permutations([0,1,2,3,4,5,6,7,8,9])\n\t# lists them in lexicographic order by default\n\tl = list(p)\n\tans = l[1000000-1] #Why the '-1'? l[0] is the first permutation\n\treturn join_ints(ans)\n\n# input: array of ints\n# e.g.: [1,2,3,4]\n# output: a single int\n# e.g.: 1234\ndef join_ints(l):\n\tl = [str(i) for i in l] # to array of chars\n\tas_str = ''.join(l)\n\treturn int(as_str)\n\nif __name__ == '__main__':\n\timport boilerplate, time, resource\n\tt = time.time()\n\tr = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n\tboilerplate.all(main(), t, r)\n\t# ha! So originally I started with the math\n\t# approach, thinking that the factorials would\n\t# slow us down - but then I went back and tested\n\t# the naive approach and it still takes less than\n\t# 5 seconds... so that's what I have down here,\n\t# for simplicity sake","sub_path":"p024.py","file_name":"p024.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"516995524","text":"def eratosthenes(n):\n # Populate a list with True\n primes = [True for i in range(n+1)]\n # We start at 2 because a number must be greater than 1 to be prime.\n p = 2\n # Prevents us from going past the sqrt of n.\n while (p * p <= n):\n # Only check an integer if it hasn't been marked as composite.\n if (primes[p] == True):\n # From the square of p to n+1, step by p.\n for i in range(p*p, n+1, p):\n # Mark each as composite.\n primes[i] = False\n # Increment p by 1 to check the next.\n p += 1\n # Iterate over each integer in range 2 to n\n for p in range(2, n):\n # Check if it has not been marked composite.\n if primes[p]:\n # print it out =D\n print(p)\n\n\neratosthenes(30)\n","sub_path":"src/17_sieve.py","file_name":"17_sieve.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"333468931","text":"import argparse\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom train_helper import validate_data, split_data, train_model\nfrom azureml.core import Run, Dataset\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser() \n parser.add_argument(\n '--solver',\n type=str,\n default=\"liblinear\",\n help='Solver para la regresión logistica'\n )\n parser.add_argument(\n '--random_state',\n type=int,\n default=42,\n help='Entero aleatorio'\n )\n args = parser.parse_args()\n\n run = Run.get_context()\n ws = run.experiment.workspace\n\n datastore = ws.get_default_datastore()\n input_ds = Dataset.get_by_name(ws, 'cardio_ds')\n data = input_ds.to_pandas_dataframe()\n\n dataframe = validate_data(data)\n X_train, X_test, y_train, y_test = split_data(dataframe)\n model = train_model(X_train, y_train, save=True, solver=args.solver,random_state=args.random_state)\n y_pred = model.predict(X_test)\n print(f\"Accurancy: {accuracy_score(y_test, y_pred)}\")\n run.log('accurancy', accuracy_score(y_test, y_pred))","sub_path":"src/remote-train.py","file_name":"remote-train.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"555224730","text":"#!/usr/bin/python3\n\"\"\"Lists States from a database\"\"\"\nfrom sys import argv\nfrom model_state import Base, State\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\nif __name__ == '__main__':\n ngine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], argv[2], argv[3]))\n Sess = sessionmaker(bind=ngine)\n sess = Sess()\n state = sess.query(State).filter(State.name == argv[4]).first()\n if state:\n print('{}'.format(state.id))\n else:\n print('Not found')\n sess.close()\n","sub_path":"0x0F-python-object_relational_mapping/10-model_state_my_get.py","file_name":"10-model_state_my_get.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"341876789","text":"import pytest\nfrom sqlalchemy import (\n select,\n insert,\n delete,\n update,\n func,\n)\n\n@pytest.fixture(scope='function')\ndef author_model():\n from books.modelsa import Author\n return Author\n\n\n@pytest.fixture(scope='function')\ndef author_table(author_model):\n return author_model.__table__\n\n\n@pytest.fixture(scope='function')\ndef author_a():\n from books.models import Author\n return Author.objects.get_or_create(name='a', age=20)[0]\n\n\n@pytest.fixture(scope='function')\ndef author_b():\n from books.models import Author\n return Author.objects.get_or_create(name='b', age=15)[0]\n\n\n@pytest.fixture()\ndef authors():\n from books.models import Author\n return Author.objects.all().order_by('id')\n\n\n@pytest.mark.django_db\nclass Test_query_expression:\n def _callFUT(self, stmt):\n from d2a.db import query_expression\n return query_expression(stmt)\n\n def test_query_expression(self, author_table, author_a, author_b):\n stmt = select([\n author_table.c.id,\n author_table.c.name,\n ]).select_from(author_table).order_by(author_table.c.age)\n actual = self._callFUT(stmt)\n expected = [\n {'id': author_b.id, 'name': author_b.name},\n {'id': author_a.id, 'name': author_a.name},\n ]\n assert actual == expected\n\n\n@pytest.mark.django_db\nclass Test_execute_expression:\n def _callFUT(self, stmt):\n from d2a.db import execute_expression\n return execute_expression(stmt)\n\n def test_insert_expression(self, author_table, authors):\n expected = [\n {'name': 'a', 'age': 10},\n {'name': 'b', 'age': 20},\n {'name': 'c', 'age': 30},\n ]\n stmt = insert(author_table).values(expected)\n assert self._callFUT(stmt) == 3\n actual = list(authors.values('name', 'age'))\n assert actual == expected\n\n def test_update_expression(self, author_table, author_a, author_b, authors):\n stmt = update(author_table).where(author_table.c.id == author_a.id).values(\n name=func.UPPER(author_table.c.name),\n age=author_table.c.age + 1,\n )\n assert self._callFUT(stmt) == 1\n actual = list(authors.values('name', 'age'))\n expected = [\n {'name': 'A', 'age': 21},\n {'name': 'b', 'age': 15},\n ]\n assert actual == expected\n\n def test_delete_expression(self, author_table, author_a, author_b, authors):\n stmt = delete(author_table).where(author_table.c.id == author_a.id)\n assert self._callFUT(stmt) == 1\n actual = list(authors.values('name', 'age'))\n expected = [\n {'name': 'b', 'age': 15},\n ]\n assert actual == expected\n\n\n\nclass Test_make_session:\n def _callFUT(self, **kwargs):\n from d2a.db import make_session\n return make_session(**kwargs)\n\n def test_make_session(self, author_model):\n with self._callFUT(autocommit=True, autoflush=True) as session:\n author = author_model()\n author.name = 'c'\n author.age = 30\n session.add(author)\n actual = [\n {'name': a.name, 'age': a.age}\n for a in session.query(author_model).all()\n ]\n expected = [\n {'name': 'c', 'age': 30},\n ]\n assert actual == expected\n\n","sub_path":"project_mysql/tests/test_db_with_autoload.py","file_name":"test_db_with_autoload.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"494519486","text":"#!/usr/bin/env python\n\"\"\"Test breakpoint manipulation.\"\"\"\n\nimport os\nimport unittest\nimport engine\nimport config\n\n\neng = engine.Engine()\n\nsubtests = {}\nif \"gdb\" in config.debuggers:\n subtests['gdb'] = {'launch': ' dd\\n',\n 'break_main': 'break main\\n'}\nif \"lldb\" in config.debuggers:\n subtests['lldb'] = {'launch': ' dl\\n',\n 'break_main': 'breakpoint set --fullname main\\n'}\n\n\nclass TestBreakpoint(unittest.TestCase):\n \"\"\"Test class.\"\"\"\n\n def test_10_detect(self):\n \"\"\"=> Verify manual breakpoint is detected.\"\"\"\n for backend, spec in subtests.items():\n with self.subTest(backend=backend):\n eng.KeyStroke(spec[\"launch\"])\n eng.KeyStroke(spec[\"break_main\"])\n eng.KeyStroke('run\\n', delay=1)\n\n cur, breaks = eng.GetSigns()\n self.assertEqual(17, cur)\n self.assertEqual([17], breaks)\n\n eng.KeyStrokeL('')\n eng.KeyStrokeL('ZZ')\n\n def test_20_cd(self):\n \"\"\"=> Verify manual breakpoint is detected from a random directory.\"\"\"\n exe_path = os.path.abspath('a.out')\n old_cwd = os.getcwd()\n\n subs = {'gdb': \":GdbStart gdb -q %s\\n\" % exe_path,\n 'lldb': \":GdbStartLLDB lldb %s\\n\" % exe_path}\n\n for backend, spec in subtests.items():\n with self.subTest(backend=backend):\n try:\n eng.KeyStroke(':cd /tmp\\n')\n eng.KeyStroke(subs[backend])\n eng.KeyStroke(subtests[backend][\"break_main\"])\n eng.KeyStroke('run\\n', delay=1)\n\n cur, breaks = eng.GetSigns()\n self.assertEqual(17, cur)\n self.assertEqual([17], breaks)\n\n eng.KeyStrokeL('')\n eng.KeyStrokeL('ZZ')\n finally:\n eng.KeyStroke(':cd %s\\n' % old_cwd)\n\n def test_30_navigate(self):\n \"\"\"=> Verify that breakpoints stay when source code is navigated.\"\"\"\n break_bar = {\"gdb\": \"break Bar\\n\", \"lldb\": \"breakpoint set --fullname Bar\\n\"}\n for backend, spec in subtests.items():\n with self.subTest(backend=backend):\n eng.KeyStroke(spec['launch'])\n eng.KeyStroke(break_bar[backend])\n eng.KeyStrokeL(\":wincmd k\")\n eng.KeyStrokeL(\":e src/test.cpp\\n\")\n eng.KeyStrokeL(\":10\")\n eng.KeyStrokeL(\"\")\n\n cur, breaks = eng.GetSigns()\n self.assertEqual(-1, cur)\n self.assertEqual([5, 10], breaks)\n\n # Go to another file\n eng.KeyStroke(\":e src/lib.hpp\\n\")\n cur, breaks = eng.GetSigns()\n self.assertEqual(-1, cur)\n self.assertEqual([], breaks)\n eng.KeyStroke(\":8\\n\")\n eng.KeyStrokeL(\"\")\n cur, breaks = eng.GetSigns()\n self.assertEqual(-1, cur)\n self.assertEqual([8], breaks)\n\n # Return to the first file\n eng.KeyStroke(\":e src/test.cpp\\n\")\n cur, breaks = eng.GetSigns()\n self.assertEqual(-1, cur)\n self.assertEqual([5, 10], breaks)\n\n eng.KeyStrokeL('ZZ')\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_20_breakpoint.py","file_name":"test_20_breakpoint.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"512686774","text":"from pyb import Pin,Timer\ntm2=Timer(2,freq=100)#初始化时钟\ntm3=Timer(3,freq=100)\nintensity4=0#初始化亮度\nintensity3=0\nled4=tm3.channel(1,Timer.PWM,pin=Pin.cpu.B4)#启用时钟3的1通道,设置为pwm模式\nled3=tm2.channel(1,Timer.PWM,pin=Pin.cpu.A15)\nwhile True:\n\twhile intensity3<99:#逐渐变亮\n\t\tled3.pulse_width_percent(intensity3)\n\t\tintensity3=(intensity3+1)%100\n\t\tpyb.delay(50)\n\twhile intensity4<99:\n\t\tled4.pulse_width_percent(intensity4)\n\t\tintensity4=(intensity4+1)%100\n\t\tpyb.delay(50)\n\twhile intensity3>0:#达到最亮时逐渐变暗\n\t\tled3.pulse_width_percent(intensity3)\n\t\tintensity3=(intensity3-1)%100\n\t\tpyb.delay(50)\n\twhile intensity4>0:\n\t\tled4.pulse_width_percent(intensity4)\n\t\tintensity4=(intensity4-1)%100\n\t\tpyb.delay(50)\n\t\n","sub_path":"trailbreaker/source/python/呼吸灯/LED.py","file_name":"LED.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"72744060","text":"from communities.models import Community, SendToOption\nfrom django.utils.translation import ugettext_lazy as _\nfrom ocd.formfields import HTMLArea, OCSplitDateTime\nimport floppyforms as forms\nfrom django.utils import timezone\nfrom datetime import datetime, date, time\n\nclass EditUpcomingMeetingForm(forms.ModelForm):\n\n class Meta:\n model = Community\n\n fields = (\n 'upcoming_meeting_title',\n 'upcoming_meeting_location',\n 'upcoming_meeting_scheduled_at',\n # 'voting_ends_at',\n 'upcoming_meeting_comments',\n )\n\n widgets = {\n 'upcoming_meeting_title': forms.TextInput,\n 'upcoming_meeting_scheduled_at': OCSplitDateTime,\n 'upcoming_meeting_location': forms.TextInput,\n # 'voting_ends_at': OCSplitDateTime,\n 'upcoming_meeting_comments': HTMLArea,\n }\n \n def __init__(self, *args, **kwargs):\n super(EditUpcomingMeetingForm, self).__init__(*args, **kwargs)\n self.fields['upcoming_meeting_title'].label = _('Title')\n self.fields['upcoming_meeting_scheduled_at'].label = _('Scheduled at')\n self.fields['upcoming_meeting_location'].label = _('Location')\n self.fields['upcoming_meeting_comments'].label = _('Background')\n\n \"\"\"\n removed this function as we don't include voting_end_time in the form any more.\n # ----------------------------------------------------------------------------\n def clean(self):\n #prevent voting end time from illegal values (past time,\n #time after meeting schedule)\n \n try:\n voting_ends_at = self.cleaned_data['voting_ends_at']\n except KeyError:\n voting_ends_at = None\n try:\n meeting_time = self.cleaned_data['upcoming_meeting_scheduled_at']\n except KeyError:\n meeting_time = None\n\n if voting_ends_at:\n if voting_ends_at <= timezone.now():\n raise forms.ValidationError(_(\"End voting time cannot be set to the past\"))\n if meeting_time and voting_ends_at > meeting_time:\n raise forms.ValidationError(_(\"End voting time cannot be set to after the meeting time\"))\n return self.cleaned_data\n \"\"\"\n \n def save(self):\n c = super(EditUpcomingMeetingForm, self).save()\n c.voting_ends_at = datetime.combine(date(2025, 1, 1), time(12, 0, 0))\n c.save()\n return c\n\n\n\nclass PublishUpcomingMeetingForm(forms.ModelForm):\n\n send_to = forms.TypedChoiceField(label=_(\"Send to\"), coerce=int,\n choices=SendToOption.choices,\n widget=forms.RadioSelect)\n\n class Meta:\n model = Community\n\n fields = ()\n\n\nclass EditUpcomingMeetingSummaryForm(forms.ModelForm):\n\n class Meta:\n model = Community\n\n fields = (\n 'upcoming_meeting_summary',\n )\n\n widgets = {\n 'upcoming_meeting_summary': HTMLArea,\n }\n\n\nclass UpcomingMeetingParticipantsForm(forms.ModelForm):\n\n class Meta:\n model = Community\n\n fields = (\n 'upcoming_meeting_participants',\n 'upcoming_meeting_guests',\n )\n\n widgets = {\n 'upcoming_meeting_participants': forms.CheckboxSelectMultiple,\n 'upcoming_meeting_guests': forms.Textarea,\n }\n\n def __init__(self, *args, **kwargs):\n super(UpcomingMeetingParticipantsForm, self).__init__(*args, **kwargs)\n self.fields['upcoming_meeting_participants'].queryset = self.instance.get_members()\n self.fields['upcoming_meeting_guests'].widget.attrs['rows'] = 4\n","sub_path":"src/communities/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"371834169","text":"import speech_recognition as sr\ndef speech2text(wavfile,lang='mr-IN'): \n r = sr.Recognizer()\n with sr.AudioFile(wavfile) as source:\n audio = r.record(source)\n\n try:\n s = r.recognize_google(audio,language = lang)\n print(\"Text: \"+s)\n filename=wavfile.replace('.wav','.txt')\n f = open(filename, \"a\")\n f.write(s)\n f.close()\n \n except Exception as e:\n print(\"Exception: \"+str(e))\nif __name__ == \"__main__\":\n speech2text(\"marathi.wav\")","sub_path":"marathi_speech2text.py","file_name":"marathi_speech2text.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"559071172","text":"# -*- coding: utf-8 - *-\nfrom __future__ import absolute_import, unicode_literals\nfrom datetime import timedelta\nfrom django.contrib.sites.models import Site\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom phonenumber_field.modelfields import PhoneNumberField\n\nfrom project import utils\nfrom project.rolodex.models import Email, Phone\nfrom . import querysets, settings\n\n\ndef get_current_site():\n try:\n return Site.objects.get_current().pk\n except Site.DoesNotExist:\n pass\n\n\ndef get_duration(n, per_booking=30):\n PER_BOOKING = timedelta(minutes=per_booking)\n duration = PER_BOOKING + (PER_BOOKING*n)\n if duration > settings.DEFAULT_DURATION:\n return settings.DEFAULT_DURATION\n else:\n return duration\n\n\nclass Table(models.Model):\n\n number = models.CharField(max_length=8)\n\n is_active = models.BooleanField(default=True)\n\n\nclass Booking(models.Model):\n\n code = models.CharField(max_length=8, blank=True, default='')\n\n name = models.CharField(max_length=200)\n\n party_size = models.PositiveIntegerField(\n validators=[MaxValueValidator(settings.CAPACITY),\n MinValueValidator(1)],\n verbose_name=\"Number of people\",\n )\n\n status = models.CharField(max_length=50, choices=settings.STATUS_CHOICE,\n default=settings.STATUS_CHOICE[0][0])\n\n is_cancelled = models.BooleanField(default=False)\n\n service = models.CharField(max_length=50, choices=settings.SERVICE_CHOICE,\n blank=True, default='')\n\n area = models.CharField(max_length=50, choices=settings.AREA_CHOICE,\n default=settings.AREA_CHOICE[0][0])\n\n notes = models.TextField(blank=True, default='')\n\n private_notes = models.TextField(blank=True, default='')\n\n email = models.EmailField(max_length=150, blank=True, default='')\n\n phone = PhoneNumberField(\n help_text=\"One phone number only. Put additional numbers in 'notes' if necessary. We may need to confirm details so be sure to provide a good number.\" # noqa\n )\n\n postcode = models.CharField(max_length=16, blank=True, default='')\n\n booking_method = models.CharField(\n max_length=50, choices=settings.METHOD_CHOICE,\n default=settings.METHOD_CHOICE[0][0],\n help_text=\"Only logged in people can see booking method.\"\n )\n\n reserved_date = models.DateField(db_index=True)\n reserved_time = models.TimeField(db_index=True, default=timezone.now)\n\n booking_duration = models.DurationField(\n blank=True, null=True,\n default=timedelta(hours=4)\n )\n\n busy_night = models.BooleanField(default=False)\n\n # Usage fields\n\n deposit_amount_paid = models.DecimalField(\n max_digits=7, decimal_places=2,\n null=True, blank=True)\n\n is_arrived = models.BooleanField(default=False)\n\n table = models.ForeignKey(\n Table,\n models.PROTECT,\n null=True, blank=True)\n\n # Internal Fields\n\n created_at = models.DateTimeField(auto_now_add=True, editable=True)\n\n updated_at = models.DateTimeField(auto_now=True, editable=False)\n\n updated_by = models.ForeignKey(\n 'auth.User', blank=True, null=True,\n related_name=\"booking_updated_by\"\n )\n\n hear_choices = models.CharField(\n max_length=56, blank=True, default='',\n choices=settings.HEAR_CHOICE,\n verbose_name=\"Choices\",\n help_text=\"How did you hear about us?\"\n )\n\n hear_other = models.TextField(\n blank=True, default='',\n verbose_name=\"Other\",\n help_text=\"Tell us a story about how you heard about us ...\" # noqa\n )\n\n legacy_code = models.CharField(max_length=256, blank=True, null=True)\n\n site = models.ForeignKey('sites.Site', default=get_current_site,\n related_name='bookings_booking',\n on_delete=models.PROTECT)\n\n objects = querysets.QuerySet.as_manager()\n\n class Meta(object):\n ordering = ['reserved_date', 'reserved_time', 'name']\n verbose_name_plural = 'bookings'\n\n def __str__(self):\n desc = \"{date} {start} {pax}pax {name}\".format(\n name=self.name,\n pax=self.party_size,\n date=self.reserved_date.strftime(\"%d-%b-%Y\"),\n start=self.reserved_time.strftime(\"%H:%M\")\n )\n\n if self.booking_duration:\n desc = \"{date} {start} {pax}pax {name}\".format(\n name=self.name,\n pax=self.party_size,\n date=self.reserved_date.strftime(\"%d-%b-%Y\"),\n start=self.reserved_time.strftime(\"%H:%M\")\n )\n return desc\n\n def get_absolute_url(self):\n return reverse('bookings:booking_update', kwargs={'code': self.code})\n\n def get_next(self):\n queryset = self.__class__.objects.exclude(pk=self.pk).filter(\n site=self.site, reserved_date__gte=self.reserved_date\n ).active().order_by('reserved_date', 'reserved_time')\n return queryset.first()\n\n def get_previous(self):\n queryset = self.__class__.objects.exclude(pk=self.pk).filter(\n site=self.site, reserved_date__lte=self.reserved_date\n ).active().order_by('-reserved_date', 'reserved_time')\n return queryset.first()\n\n def is_active(self):\n return self in self.__class__.objects.filter(pk=self.pk).active()\n is_active.boolean = True\n is_active.short_description = 'active'\n\n def save(self, *args, **kwargs):\n\n # Automatically make code if doesn't already have one.\n if not self.code:\n self.code = utils.generate_unique_hex(\n hex_field='code',\n queryset=Booking.objects.all())\n\n # adding on first creation. Messy, but works.\n # @@TODO make this less crap\n if \"full\" in self.private_notes:\n self.busy_night = True\n for booking in Booking.objects.filter(\n reserved_date=self.reserved_date):\n booking.busy_night = True\n booking.save()\n\n # Automatically set `service` (eg. lunch) based upon `reserved_time`.\n for service_time, service in reversed(settings.SERVICE_TIMES):\n if self.reserved_time >= service_time:\n this_service = service\n break\n self.service = this_service\n\n if self.email:\n Email.objects.get_or_create(email=self.email)\n\n if self.phone:\n Phone.objects.get_or_create(phone=self.phone)\n\n if (self.status == 'no_show' and not self.is_cancelled) \\\n or (self.status == 'cancelled' and not self.is_cancelled):\n self.is_cancelled = True\n\n if not (self.status == 'cancelled'\n or self.status == 'no_show') and self.is_cancelled:\n self.is_cancelled = False\n\n self.booking_duration = get_duration(self.party_size)\n\n super(Booking, self).save(*args, **kwargs)\n","sub_path":"project/bookings/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"531607043","text":"# imports - standard imports\nfrom subprocess import call, list2cmdline\n\n# imports - module imports\nfrom pipupgrade.commands.parser import get_parser\nfrom pipupgrade.util import list_filter\nfrom pipupgrade import _pip\nfrom pipupgrade import cli\n\ndef command():\n parser = get_parser()\n args = parser.parse_args()\n\n packages = _pip.get_installed_distributions()\n npackages = len(packages)\n\n query = \"Do you wish to update {} packages?\".format(npackages)\n \n if args.yes or cli.confirm(query):\n for i, package in enumerate(packages):\n name = package.project_name\n\n info = cli.format(\"Updating {} of {} packages: {}\".format(\n i + 1,\n npackages,\n name if args.no_color else cli.format(name, cli.GREEN)\n ), cli.BOLD)\n\n cli.echo(info)\n\n params = list_filter([\n \"pip\",\n \"install\",\n \"--quiet\" if not args.verbose else None,\n \"--no-cache\",\n \"--upgrade\",\n name\n ], filter_ = bool)\n command = list2cmdline(params)\n \n call(command, shell = True)\n\n cli.echo(cli.format(\"UPGRADED ALL THE PACKAGES!\", cli.BOLD))\n \n return 0","sub_path":"pipupgrade/commands/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"146823391","text":"import json\nimport sys\nimport random\nimport nltk\n\nfin = open(sys.argv[1])\ncodes_vocab_f = open(sys.argv[2])\nfout = open(sys.argv[3], 'w')\n\ncodes_vocab = {}\nfor line in codes_vocab_f:\n c, t = line.strip().split('\\t')\n codes_vocab[c] = t\n\nfor line in fin:\n json_dict = json.loads(line)\n \n if random.random() < 0.5:\n title = json_dict.get('title', \"\")\n body = json_dict.get('body', \"\")\n if not title: title = \"\"\n if not body: body = \"\"\n doc = title + '\\n' + body\n sentences = nltk.sent_tokenize(doc)\n for sent in sentences:\n fout.write(sent)\n fout.write(\"\\n\")\n fout.write(\"\\n\")\n continue\n codes = json_dict[\"codes\"]\n\n country_codes = codes.get(\"bip:countries:1.0\", [])\n topic_codes = codes.get(\"bip:topics:1.0\", [])\n industry_codes = codes.get(\"bip:industries:1.0\", [])\n\n random.shuffle(country_codes)\n random.shuffle(topic_codes)\n random.shuffle(industry_codes)\n \n if country_codes:\n country_code_text = \"CODECOUNTRY \" + ' , '.join([codes_vocab.get(t, \"\") for t in country_codes])\n if topic_codes:\n topic_code_text = \"CODETOPIC \" + ' , '.join([ codes_vocab.get(t, \"\") for t in topic_codes])\n if industry_codes:\n industry_code_text = \"CODEINDUSTRY \" + ' , '.join([codes_vocab.get(t, \"\") for t in industry_codes])\n\n title = json_dict.get('headline', \"\")\n if not title:\n title = \"\"\n body = json_dict.get('body', \"\")\n doc = title + body\n doc = doc.replace('\\n', ' ')\n doc = ' '.join(doc.split(' ')[0:100])\n\n sents = []\n\n if industry_codes and not topic_codes:\n sents.append(industry_code_text)\n if topic_codes and not industry_codes:\n sents.append(topic_code_text)\n if topic_codes and industry_codes:\n r = random.random()\n if r < 0.4:\n sents.append(topic_code_text)\n elif 0.4 <= r < 0.8:\n sents.append(industry_code_text)\n elif 0.8 <= r:\n sents.append(topic_code_text)\n sents.append(industry_code_text)\n\n if random.random() < 0.01 and country_codes:\n sents.append(country_code_text)\n\n sents.append(doc)\n\n random.shuffle(sents)\n for sent in sents:\n fout.write(sent.strip())\n fout.write(\"\\n\")\n fout.write(\"\\n\")\n","sub_path":"to_rcvtextcodes_mix_pretrain.py","file_name":"to_rcvtextcodes_mix_pretrain.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"454815724","text":"from flask import Blueprint\nfrom flask import render_template\nfrom flask import request\nfrom flask import jsonify\n\nfrom ..services import ArticlesService\n\nblog_views = Blueprint('blog_views', __name__)\narticles_service = ArticlesService()\n\n@blog_views.route('/blog')\ndef home_page():\n articles = articles_service.listArticles()\n return render_template('blog.html',\n articles=articles,\n current_page=\"blog\",\n )\n\n@blog_views.route('/api/articles', methods=[\"GET\", \"POST\"])\ndef display_articles_list():\n if request.method == 'GET':\n articles = articles_service.listArticles()\n return jsonify(articles)\n elif request.method == 'POST':\n article_title = request.json['title']\n article_content = request.json['content']\n articles_service.addArticle(article_title, article_content)\n return \"ok\", 200","sub_path":"web/views/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"132586794","text":"\nfrom model import PopulationModel\nfrom model import PopulationPlotter\n\n## vector of population nodes\n# nodes[0]: susceptible\n# nodes[1]: infected\n# nodes[2]: recovered\n# nodes[3]: dead\n# nodes[4]: total infections\nnodes = [1, 0, 0, 0, 0]\n\n## transition matrix\ntmat = [\n [0.95, 0.00, 0.00, 0.00, 0.00],\n [0.05, 0.84, 0.00, 0.00, 0.00],\n [0.00, 0.15, 1.00, 0.00, 0.00],\n [0.00, 0.01, 0.00, 1.00, 0.00],\n [0.05, 0.00, 0.00, 0.00, 1.00]\n]\n\ndef main():\n\n ## define our population model\n model = PopulationModel(nodes, tmat)\n\n ## iterate over time\n model.iterate(50)\n\n ## print the population history\n print(str(model.history))\n\n ## show plot of population nodes over time\n plotter = PopulationPlotter(model.history)\n plotter.labels = [\"susceptable\", \"infected\", \"recovered\", \"dead\", \"total infected\"]\n plotter.plot()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"173413503","text":"from Scraper import Scraper\nimport json\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\n\nimport time\nfrom Company import Company\nfrom utils import AnyEC\n\n\nclass CompanyScraper(Scraper):\n def scrape(self, url='', company='facebook', overview_only=True):\n print('in main')\n # Get Overview\n self.load_initial(url, company)\n overview_html = self.driver.find_element_by_css_selector(\n '.organization-outlet').get_attribute('outerHTML')\n jobs_html = ''\n life_html = ''\n\n # Get job Info\n if not overview_only:\n try:\n self.load_jobs()\n jobs_html = self.driver.find_element_by_css_selector(\n '.org-jobs-container').get_attribute('outerHTML')\n except:\n print(\"UNABLE TO GET JOB INFO\")\n\n # Get Life Info\n try:\n self.load_life()\n life_html = self.driver.find_element_by_css_selector(\n '.org-life').get_attribute('outerHTML')\n except:\n print(\"UNABLE TO GET LIFE INFO\")\n return Company(overview_html, jobs_html, life_html)\n\n def load_initial(self, url, company=None):\n if company:\n url = 'https://www.linkedin.com/company/{}/'.format(company)\n if 'com/company/' not in url:\n raise ValueError(\"Url must look like ...linkedin.com/company/NAME\")\n\n self.driver.get(url)\n try:\n myElem = WebDriverWait(self.driver, self.timeout).until(AnyEC(\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, '.organization-outlet')),\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, '.error-container'))\n ))\n except TimeoutException as e:\n raise ValueError(\n \"\"\"Took too long to load company. Common problems/solutions:\n 1. Invalid LI_AT value: ensure that yours is correct (they\n update frequently)\n 2. Slow Internet: increase the timeout parameter in the Scraper constructor\"\"\")\n try:\n self.driver.find_element_by_css_selector('.organization-outlet')\n except:\n raise ValueError(\n 'Company Unavailable: Company link does not match any companies on LinkedIn')\n\n def load_jobs(self):\n jobs_tab = self.driver.find_element_by_css_selector('.nav-jobs-tab')\n jobs_link = jobs_tab.find_element_by_xpath('..')\n jobs_link.click()\n el = WebDriverWait(self.driver, self.timeout).until(EC.presence_of_element_located(\n (By.CSS_SELECTOR, '.org-jobs-container')\n ))\n\n def load_life(self):\n life_tab = self.driver.find_element_by_css_selector('.nav-lifeat-tab')\n life_link = life_tab.find_element_by_xpath('..')\n life_link.click()\n el = WebDriverWait(self.driver, self.timeout).until(EC.presence_of_element_located(\n (By.CSS_SELECTOR, '.org-life')\n ))\n","sub_path":"LinkedinScrapper-master/CompanyScraper.py","file_name":"CompanyScraper.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"468839882","text":"import os, SocketServer \nfrom SimpleHTTPServer import SimpleHTTPRequestHandler\n\nclass RemoteScanHandler(SimpleHTTPRequestHandler):\n\tdef do_GET(self):\n\t\tif self.path == '/':\n\t\t\tos.system(\"scanimage >scan.pnm --resolution 200\")\n\t\t\tos.system(\"pnmtojpeg scan.pnm > scan.jpeg\")\n\t\t\tself.path = \"/index.html\"\n\t\treturn SimpleHTTPRequestHandler.do_GET(self)\t\t\t\n\nhttpd = SocketServer.TCPServer((\"\", 8000), RemoteScanHandler)\nhttpd.serve_forever()\n","sub_path":"rem_scan_handler.py","file_name":"rem_scan_handler.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"229517737","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom drf_yasg.views import get_schema_view\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.routers import SimpleRouter\nfrom drf_yasg import openapi\n\nfrom main.views import ProductViewSet, ReviewViewSet, LikeViewSet, Favorites, CartProducts\n\nrouter = SimpleRouter()\n\nrouter.register('products', ProductViewSet)\nrouter.register('reviews', ReviewViewSet)\n# router.register('orders', OrderViewSet)\nrouter.register('likes', LikeViewSet)\n\n# документация\nschema_view = get_schema_view(\n openapi.Info(\n title='My Api',\n default_version='v1',\n description='My ecommerce API'\n ),\n public=True,\n permission_classes=[AllowAny],\n)\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/v1/', include(router.urls)),\n path('api/v1/', include('account.urls')),\n path('docs/', schema_view.with_ui('swagger')),\n path('favorite/', Favorites.as_view()),\n path('cart/', CartProducts.as_view()),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"boards/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"452072093","text":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\ndef make_parent(parent: str) -> str:\n parent = parent\n\n return parent\n\ndef make_model(\n display_name: str, \n container_spec_image_uri: str, \n artifact_uri: str,\n input_tensor_name: str,\n output_tensor_name: str,\n feature_names: list\n) -> google.cloud.aiplatform_v1beta1.types.model.Model:\n\n # Container specification for deploying the model\n container_spec = {\"image_uri\": container_spec_image_uri, \"command\": [], \"args\": []}\n\n # The explainabilty method and corresponding parameters\n parameters = aiplatform_v1beta1.ExplanationParameters({\"xrai_attribution\": { \"step_count\": 1}})\n\n # The input tensor for feature attribution to the output\n # For single input model, y = f(x), this will be the serving input layer.\n input_metadata = aiplatform_v1beta1.ExplanationMetadata.InputMetadata({\n \"input_tensor_name\": input_tensor_name,\n # Input is tabular data\n \"modality\": \"numeric\",\n # Assign feature names to the inputs for explanation\n \"encoding\": \"BAG_OF_FEATURES\",\n \"index_feature_mapping\": feature_names\n })\n\n # The output tensor to explain\n # For single output model, y = f(x), this will be the serving output layer.\n output_metadata = aiplatform_v1beta1.ExplanationMetadata.OutputMetadata({\n\t\"output_tensor_name\": output_tensor_name\n })\n\n # Assemble the explanation metadata\n metadata = aiplatform_v1beta1.ExplanationMetadata(\n inputs={'features': input_metadata},\n outputs={'prediction' : output_metadata}\n )\n\n # Assemble the explanation specification\n explanation_spec = aiplatform_v1beta1.ExplanationSpec(\n parameters=parameters,\n metadata=metadata\n )\n\n model = aiplatform_v1beta1.Model(display_name=display_name,\n # The Cloud Storage location of the custom model\n artifact_uri=artifact_uri,\n explanation_spec=explanation_spec,\n container_spec=container_spec\n )\n\n return model\n\n","sub_path":".sample_configs/param_handlers/upload_model_explain_tabular_managed_container_sample.py","file_name":"upload_model_explain_tabular_managed_container_sample.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"262408938","text":"# print(\"Hello World\")\n# Python Strings\n\n# To comment out and uncomment\n# multiple lines of code in Pycharm,\n# highlight or place cursor anywhere\n# on the lines of the text and hit ctrl + /\n\n\"\"\"Python\n\n Strings\"\"\"\n\"\"\"\nx = \"Hello, World\"\ny = \" hello world\"\n\nprint(x[0:3])\nprint((y.strip()))\nprint(x.split(','))\nprint(\"Hello\".upper())\nprint(\"shit\"*100)\n\n########################\n\nx = -100\n\nif x != 100 and x > 0:\n print(\"x is = \")\n print(x)\n\nif x > 0:\n print(\"x is positive\")\nelse:\n print(\"x is negative\")\n\nprint(\"end\")\n\nname = input(\"Enter a name: \")\n\nif name == \"Max\":\n print(\"Name entered is : \", name)\nelif name == \"Leo\":\n print(\"Name entered is : \", name)\nelif name == \"Roy\":\n print(\"Name entered is : \", name)\nelse:\n print(\"Name entered is invalid\")\n \n##########################################\n\nx = 10\nif x < 0:\n print(\"negative\")\nelse:\n print(\"positive\")\n if (x % 2) == 0:\n print(\"even\")\n else:\n print(\"odd\")\n\n##########################\n# Lists\n\nx = [3, 5, 4, 9, 7, 10]\nprint(x)\nprint(x[0])\ny = ['Max', 1, 15.5, [3, 2]]\nprint(y[3])\nx.insert(2, 'tommy')\nprint(x)\nx.remove('tommy')\nprint(x)\nx.insert(2, 'tommy')\nx.insert(2, 'tommy')\nprint(x)\nx.remove('tommy')\nprint(x)\n# remove will only remove one item starting with the one from the left\nx.pop()\nprint(x)\nz = [1,2,5,4]\nz.sort()\nprint(z)\n# reverse, append, copy, count\nprint(x)\nx.reverse()\nprint(x)\nx.append(3)\nx.append(3)\nx.remove('tommy')\nprint(x)\nx.sort()\nprint(x.count(3))\n\n# Tuples\n# Tuples are like lists, but they are immutable - cannot be changed\n\nx = (1, 5, 3, 4, 8)\nprint(x)\ny = (1, 'max', 1.6)\n# can concatenate tuples\nz = x + y\nprint(z)\n# can fill tuple with multiplication\na = ('hi',) * 5\nprint(a)\nprint(max(x))\n\n#####################\n# Set - unordered collection with no duplicate elements and no indexing\n\nA = {1, 2, 5, 4, 7, 9, 2}\nprint(A)\nprint(len(A))\nA.add(10)\nprint(A)\nA.update([15, 18, 17, 14])\nprint(A)\nA.discard(17)\nprint(A)\n# discard and remove are similar but discard won't throw error with out of range value\nA.pop()\n# pop removes random element\nprint(A)\nA.pop()\nprint(A)\nname = {'max', 'tom', 'dan'}\nname.clear()\nprint(name)\n# set constructor\nname = set(('alice', 'bob', 'eve'))\nprint(name)\nprint(name)\n# convert list to set\nZ = set([5, 3, 1, 2, 2, 3])\nprint(Z)\nprint(A)\nB = {10, 11, 12, 13, 14, 16, 18}\nprint(B)\nprint(A | B)\nprint(A & B)\nprint(A.intersection(B))\nprint(A - B)\nprint(B - A)\nprint(A.difference(B))\n# Symmetric difference - either in A but not B or vice versa\nprint(A ^ B)\n\n##############\n# Dictionary\n\n# Dictionary - list of pairs\n\nD = {'name': 'max', 'age': 14, 'year': 2004}\n\nprint(D)\nprint(D['name'])\nprint(D['age'])\n\nE = {'name': 'Tom', 15: 15, 15.1: 15.1, True: True, (2,3): 5}\nprint(E[(2,3)])\nprint(E[True])\n# print(E[100]) # error\nprint(len(E))\n''' print(D.get('name').upper())\nD['name'] = D.get('name').upper()\nprint((D['name']))\nD['name'] = 'max'\nprint(D['name']) '''\nD['Surname'] = 'Smith'\nprint(D)\nD.pop('Surname')\nprint(D)\nprint(E)\nE.clear()\nprint(E)\ndel E\n# print(E)\nD['name'] = 'Mark'\nprint(D)\nD.update({'name': 'Christian'})\nprint(D)\nprint(D.keys())\nprint(D.values())\n# popitem removes last item inserted\n# D.popitem()\nD.update({'name': 'max'})\nD.popitem()\nprint(D)\n\n#############################\n# Slice and negative index\n\na = [0,1,2,3,4,5,6,7,8,9]\nb = (0,1,2,3,4,5,6,7,8,9)\nc = '0123456789'\n\nx = a[0:5]\nprint(x)\n\nprint(a[:5])\nprint(a[3:])\nprint(c[0:5])\nprint(a[0:10:3])\nprint(c[-1])\nprint(a[::-1])\nprint(c[::-1])\nprint(a[3:1:-1])\nprint(a[-1:-4:-1])\nprint(a[-3::-1])\n\n\"\"\"\n\n##############################\n# Loops\n\n\"\"\" \n\nnum = 1\nsum = 0\nprint(\"Enter a number. Please enter zero(0) to exit.\")\nwhile num != 0:\n num = float(input())\n sum += num\n print(\"sum = \", sum)\nelse:\n print(\"Finished sum\")\n\ni = 1\nwhile i <= 5:\n print(\"The value of i is: \", i)\n i += 1\n\nA = [0,1,2,3,4,5] # list\nB = (0,1,2,3,4,5) # tuple\nC = {0,1,2,3,4,5} # set\nD = '012345' # string\nE = {\n \"name\": 'max',\n \"age\": 20\n}\n\nfor x, y in E.items(): # keys(), values(), items()\n print(x, ' ', y)\n\nfor z in range(2,30,3):\n print(z)\nelse:\n print(\"Finished\")\n\na = [0,1,2,3,4,5]\nfor x in a:\n if x == 3:\n break\n print(x)\n\ni = 0\nwhile i < 5:\n if i == 3:\n break\n print(i)\n i += 1\n\n\"\"\"\n\n##############################\n# Functions\n\n\"\"\"\ndef student(name='unknown', age='unknown', **grades):\n # * for tuple, ** for dictionary\n print(\"Name: \", name)\n print(\"Age: \", age)\n # print(\"Grades: \", grades)\n for x,y in grades.items():\n print(x,y)\n # print(\"Grades: \",grades)\n\n\nstudent()\nstudent('Mark',28, English=90, Math=85,History=99,Science=100)\n\n\"\"\"\n\n##############################\n# Classes\n##############################\n\n# if you pyt multiple init methods in class, it only recognizes last one\n\n# to make data private, use __ in front\n\n# encapsulation\n# single _ makes data partially private, and it's only a convention\n\nclass Hello:\n def __init__(self, name):\n self.a = 10\n self._b = 20\n self.__c = 30\n def public_method(self):\n print(self.a)\n print(self.__c);\n print('public')\n self.__private_method()\n\n def __private_method(self):\n print('private')\n\nhello = Hello('Name')\nprint(hello.a)\nprint(hello._b)\nhello.public_method()\n# print(hello.__c)\n\n\n\n######################### Inheritance\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Reverse and add integer problem. Given integer input, check first and last digits.\n# If they are not equal, take reverse of integer and add together e.g. 123 + 321.\n# Repeat until you come to a number in which the first and last digits are equal.\n# Output the final integer, and the amount of additions needed to get the result.\n#\n# Examples:\n#\n# Input: 123\n# Output: 444 1\n#\n# Input: 945\n# Output: 11781 3\n#\n#\n#\n# def reverse(num):\n# return int(str(num)[::-1])\n#\n#\n# def checkFirstLast(num):\n# return str(num)[0] == str(num)[-1]\n#\n#\n# def reverseAdd(num, count=0 xz):\n# if checkFirstLast(num):\n# print(num, \" \", count)\n# else:\n# num += reverse(num)\n# count += 1\n# reverseAdd(num, count)\n#\n#\n# a = int(input(\"Enter number: \"))\n#\n# reverseAdd(a)\n\n\n\n\"\"\"\n\nnum = input(\"Enter number: \")\ncount = 0\ndef checkFirstLast\ndef reverseandadd(num):\n if num[0] == num[-1]:\n print(num)\n # print(count)\n elif num[0] != num[-1]:\n print(\"Not palindrome\")\n rev = int(num[::-1])\n num = int(num)\n print(rev)\n print(num)\n sumOf = num + rev\n # count += 1\n print(sumOf)\n print(count)\n num = sumOf\n reverseandadd(num)\n\"\"\"","sub_path":"python-sandbox.py","file_name":"python-sandbox.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"300871844","text":"from lxml import objectify,etree\nimport lxml\nfrom pathlib import Path\nimport uuid\nfrom itertools import product\n\nfrom mako.template import Template\nfrom mako import exceptions\n\nimport networkx as nx\n\ndef xml_pars(node):\n '''xml格式解析转化'''\n sd = []\n for n in node:\n if n.countchildren():\n sor = {}\n for x in n.getchildren():\n sor[x.tag] = x if x.countchildren() else x.text\n sd.append(sor)\n return sd\n \nclass ktr_parse(object):\n def __init__(self,file):\n '''解析ktr文件'''\n with open(file,'r') as f:\n xml = objectify.parse(f)\n self.root = xml.getroot()\n self.ktr_name = Path(file).stem\n self.kuid = str(uuid.uuid1())\n self.__file = file\n \n def get_info(self):\n '''获取ktr的基本信息'''\n \n data = xml_pars(self.root.iterdescendants(tag= 'info'))\n for n in data:\n n['ktr'] = n.pop(\"name\")\n n['kuid'] = self.kuid\n return data\n\n def get_parameters(self):\n '''ket的参数信息'''\n parameter = xml_pars(self.root.iterdescendants(tag= 'parameter'))\n for n in parameter:\n n['ktr'] = self.ktr_name\n n['kuid'] = self.kuid\n return parameter\n\n def get_hops(self,graph = False,directed = False):\n '''步骤顺序关联\n \n Args:\n -----\n grap: bool\n 是否返回图的格式\n directed:bool\n 返回的图是否为有向图 默认为无向图\n '''\n hop = xml_pars(self.root.iterdescendants(tag= 'hop'))\n if graph:\n G = nx.DiGraph() if directed else nx.Graph()\n for n in hop:\n G.add_edge(n['from'], n['to'])\n hop = G\n \n return hop \n \n def get_steps(self,mark_x= None,mark_y = None,valid= True):\n '''步骤节点'''\n step = xml_pars(self.root.iterdescendants(tag= 'step'))\n stepclas = {}\n for n in step:\n n['ktr'] = self.ktr_name\n n['kuid'] = self.kuid\n \n # 节点类型归类\n if n.get('type',None) in stepclas:\n stepclas[n.get('type',None)].append(n['name'])\n else:\n stepclas[n.get('type',None)] = [n['name']]\n \n # 对表输出的子内容处理 \n if n.get('type',None) == 'TableOutput':\n if isinstance(n['fields'],lxml.objectify.ObjectifiedElement):\n \n fields = xml_pars(n['fields'].getchildren())\n for x in fields:\n x['table'] = n['table']\n n['fields_content'] = fields\n \n # 标记节点关系\n if mark_x and mark_y:\n hop = xml_pars(self.root.iterdescendants(tag= 'hop'))\n G = nx.Graph()\n for n in hop:\n G.add_edge(n['from'], n['to'])\n \n # 取连接有效的节点\n if valid:\n valid_step = set()\n for n in hop:\n if n['enabled'] =='Y':\n valid_step.add(n['from'])\n valid_step.add(n['to'])\n \n step_valid = []\n for n in step:\n if n['name'] in valid_step:\n step_valid.append(n)\n step = step_valid\n \n if mark_x in stepclas and mark_y in stepclas:\n nexus = product(stepclas[mark_x],stepclas[mark_y])\n for n in nexus:\n if nx.has_path(G,n[0],n[1]):\n step_uuid = str(uuid.uuid1())\n for sp in step:\n if sp.get('name',None) in [n[0],n[1]]:\n sp['suid'] = step_uuid\n \n return step\n\n def get_conn(self):\n '''数据源连接信息'''\n conn = xml_pars(self.root.iterdescendants(tag= 'connection'))\n for n in conn:\n n['ktr'] = self.ktr_name\n n['kuid'] = self.kuid\n return conn\n \n def set_step(self,name='TableInput',value= {},inplace =False):\n '''修改ktr文件step步骤中的标签值\n \n Parameters\n ----------\n name: str\n 标签\n value: \n 值\n '''\n step = self.root.xpath(f\"/transformation/step[type='{name}']\")\n if step:\n for x,y in value.items():\n setattr(step[0],'sql',y)\n if inplace:\n self.save(self.__file)\n return True\n else:\n return False\n \n def to_string(self,obj=None):\n '''root根对象xml文档输出为字符串\n '''\n data = obj if obj else self.root \n objectify.deannotate(data, cleanup_namespaces=True)\n xml_str = str(etree.tostring(data, encoding=\"utf-8\", pretty_print=True),encoding='UTF-8')\n return xml_str\n \n def save(self,path):\n '''root输出保存到指定路径文件\n '''\n xml_str = self.to_string()\n Path(path).write_bytes(bytes(xml_str,encoding = \"utf8\") ) \n return True\n \nclass ktr(object):\n def __init__(self):\n '''生成ktr文件\n '''\n self.data = {'connection':[],'step':[]}\n \n def create_info(self,name,directory = '',trans_type='Normal',trans_status=0,created_date= None,modified_date =None,\n created_user='-',modified_user='-'):\n '''ktr主体信息\n \n name:str\n ktr转换名称\n directory:str\n 路径\n '''\n data = {\"name\":name,'trans_type':trans_type,'directory':directory,\n 'created_user':created_user,'trans_status':trans_status,\n 'created_date':created_date,'modified_user':modified_user,'modified_date':modified_date}\n self.data.update(data)\n return data\n \n def create_parameters(self,data=[]):\n '''参数\n data:list\n 列表元素为字典\n name: str\n 变量名称\n default_value: str\n 默认值\n description:str\n 变量说明\n '''\n self.data['parameters'] = data\n return data\n \n def create_order(self,data):\n '''步骤顺序连接\n \n data: dict\n {from:step1,to:stpe2,enabled:'Y'}\n '''\n self.data['order'] = data\n return data\n \n def create_conn(self,name,server='',type='',access='',database='',port='',username='',password='',attributes=''):\n '''数据库连接\n \n server:str\n ip\n types:str\n 数据库类型 ORACLE\n access:str\n Native\n database:str\n 数据库名\n port:str\n 端口\n username: str\n 用户名\n password:str\n 密码\n attributes: dict\n 相关属性 \n '''\n data = locals()\n data.pop('self')\n data['name'] = name\n if not data['attributes']:\n data['attributes'] = [{'code':'FORCE_IDENTIFIERS_TO_LOWERCASE','attribute':'N'},\n {'code':'FORCE_IDENTIFIERS_TO_UPPERCASE','attribute':'N'},\n {'code':'IS_CLUSTERED','attribute':'N'},\n {'code':'PORT_NUMBER','attribute':port},\n {'code':'PRESERVE_RESERVED_WORD_CASE','attribute':'Y'},\n {'code':'QUOTE_ALL_FIELDS','attribute':'N'},\n {'code':'SUPPORTS_BOOLEAN_DATA_TYPE','attribute':'Y'},\n {'code':'SUPPORTS_TIMESTAMP_DATA_TYPE','attribute':'Y'},\n {'code':'USE_POOLING','attribute':'N'}]\n else:\n data['attributes'] = attributes\n self.data['connection'].append(data)\n return data\n \n def create_step_execsql(self,name,conn,sql,execute_each_row='N',single_statement='N',replace_variables='N',\n quoteString='N',set_params ='N',\n xloc = 120,yloc = 80,draw='Y'):\n '''表输入\n '''\n data = locals()\n data.pop('self')\n data['name'] = name\n data ['connection'] = conn\n data ['sql'] = sql\n data ['type'] = 'ExecSQL'\n self.data['step'].append(data)\n return data\n \n \n def create_step_tableinput(self,name,conn,sql,limit = 0,distribute = 'Y',copies=1,execute_each_row='N',variables_active='Y',lazy_conversion_active='N',\n xloc = 320,yloc = 80,draw='y'):\n data = locals()\n data.pop('self')\n data ['name'] = name\n data['connection'] = conn\n data['sql'] = sql\n data ['type'] = 'TableInput'\n self.data['step'].append(data)\n return data\n \n def create_step_tableoutput(self,name,conn,table,fields,commit =100,tablename_in_table='Y',truncate='N',ignore_errors='N',\n use_batch='Y',specify_fields='Y',partitioning_enabled='N',partitioning_daily = 'N',\n partitioning_monthly='Y',tablename_in_field = 'N',return_keys ='',xloc = 520,yloc = 80,draw='y'):\n '''表输出\n name: str\n 表输出名字\n conn: \n 数据库连接\n table: str\n 表名\n '''\n data = locals()\n data.pop('self')\n data['name'] = name\n data['connection'] = conn\n data['table'] = table\n data['tablename_in_table'] = tablename_in_table\n \n data ['type'] = 'TableOutput'\n self.data['step'].append(data)\n return data\n \n def render(self):\n '''生成ktr xml文件'''\n mytemplate = Template(filename=str(Path(__file__).parent/'template'/'ktr.xml'))\n try:\n res = mytemplate.render(**self.data)\n return res\n except:\n raise Exception(exceptions.text_error_template().render())\n \n def save(self,path):\n '''保存ktr xml文件对象\n '''\n ktr_string = self.render()\n Path(path).write_text(ktr_string)\n \nclass ktr_parses():\n def __init__(self,files):\n '''同时解析多个ktr文件'''\n self.__files = files\n \n def get_info(self):\n '''获取ktr的基本信息\n '''\n data = []\n for n in self.__files:\n kr = ktr_parse(n)\n data.extend(kr.get_info())\n return data \n \n def get_parameters(self):\n '''ket的参数信息\n '''\n data = []\n for n in self.__files:\n kr = ktr_parse(n)\n data.extend(kr.get_parameters())\n return data\n \n def get_hops(self,graph = False,directed = False):\n '''步骤顺序关联\n '''\n data = {}\n for n in self.__files:\n kr = ktr_parse(n)\n data.update({self.kuid:kr.get_hops(graph = graph,directed = directed)})\n return data\n \n def get_steps(self,mark_x= None,mark_y = None):\n '''步骤节点\n '''\n data = []\n for n in self.__files:\n kr = ktr_parse(n)\n data.extend(kr.get_steps(mark_x = mark_x,mark_y = mark_y))\n return data\n \n def get_conn(self):\n '''数据源连接信息\n '''\n data = []\n for n in self.__files:\n kr = ktr_parse(n)\n data.extend(kr.get_conn())\n return data\n","sub_path":"build/lib/datamation/etl/kettle.py","file_name":"kettle.py","file_ext":"py","file_size_in_byte":11789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"402563424","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, TextField, SubmitField\nfrom wtforms.validators import DataRequired, Length\n\n\nclass BmiForm(FlaskForm):\n \"\"\"Contact form.\"\"\"\n height = NumberField(\n 'height',\n [DataRequired()]\n )\n weight = NumberField(\n 'weight',\n [\n Email(message=('Not a valid email address.')),\n DataRequired()\n ]\n )\n \n submit = SubmitField('Submit')","sub_path":"03-template/BMI-APP/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"149941048","text":"import numpy as np\nfrom mmdet.core.bbox.iou_calculators import build_iou_calculator\nfrom mmdet.models.builder import HEADS\nfrom mmdet.models.roi_heads.bbox_heads.convfc_bbox_head import Shared2FCBBoxHead\nfrom mmcv.runner import force_fp32\nimport torch\nfrom mmdet.models.losses import accuracy\nfrom mmdet.core import multi_apply\n\n\n@HEADS.register_module()\nclass Shared2FCBBoxHeadWeightV4(Shared2FCBBoxHead):\n\n def __init__(self, **kwargs):\n super(Shared2FCBBoxHeadWeightV4, self).__init__(**kwargs)\n\n @force_fp32(apply_to=('cls_score', 'bbox_pred'))\n def loss(self,\n custom_weight,\n gt_labels,\n cls_score,\n bbox_pred,\n rois,\n labels,\n label_weights,\n bbox_targets,\n bbox_weights,\n bbox_gt_inds,\n reduction_override=None):\n torch.set_printoptions(threshold=np.inf)\n # 获取有效预测结果的mask,非有效预测的结果弄成零方便取权重,最后通过mask筛选取出的值\n bbox_gt_inds_mask = bbox_gt_inds != -1\n bbox_gt_inds[bbox_gt_inds == -1] = 0\n # 通过bbox的weight和每个bbox属于的类别计算出类别的权重,\n # [1,0.5,0.8] 对应的类别为[0,0,1] 那么类别权重和背景权重为[0.75,0.8,0.76]\n custom_label_weight = []\n for i in range(len(custom_weight)):\n custom_label_weight.append([0 for _ in range(self.num_classes + 1)])\n for i in range(len(custom_label_weight)):\n for j in range(self.num_classes + 1):\n # num_classes代表背景\n if j == self.num_classes:\n mask = np.asarray(custom_label_weight[i]) > 0\n background_weight = np.average(np.asarray(custom_label_weight[i])[mask])\n custom_label_weight[i][j] = background_weight\n else:\n img_i_gt_labels_wrt_class_j = (gt_labels[i] == j).cpu().numpy()\n img_i_class_j_weight = custom_weight[i][img_i_gt_labels_wrt_class_j]\n if len(img_i_class_j_weight) > 0:\n custom_label_weight[i][j] = np.average(img_i_class_j_weight)\n else:\n custom_label_weight[i][j] = 0\n start_index = 0\n lengths = []\n bbox_weight_list = []\n label_weight_list=[]\n predict_img_index = rois[:, 0]\n num_imgs = len(custom_weight)\n # 得出每个img有多少个预测结果,一个img一个img的处理\n for i in range(num_imgs):\n lengths.append(torch.count_nonzero(predict_img_index == i).item())\n for index, length in enumerate(lengths):\n cur_custom_bbox_weight = torch.from_numpy(custom_weight[index]).type_as(bbox_pred)\n cur_custom_label_weight = torch.from_numpy(np.asarray(custom_label_weight[index])).type_as(labels)\n cur_custom_bbox_weight = cur_custom_bbox_weight[bbox_gt_inds[start_index:length + start_index]]\n cur_custom_label_weight = cur_custom_label_weight[labels[start_index:length + start_index]]\n cur_custom_bbox_weight[~bbox_gt_inds_mask[start_index:length + start_index]] = 0\n bbox_weight_list.append(cur_custom_bbox_weight)\n label_weight_list.append(cur_custom_label_weight)\n start_index += length\n final_custom_bbox_weight = torch.concatenate(bbox_weight_list, dim=0)\n final_custom_label_weight = torch.concatenate(label_weight_list, dim=0)\n bbox_weights = final_custom_bbox_weight.unsqueeze(-1) * bbox_weights\n label_weights = final_custom_label_weight * label_weights\n losses = dict()\n if cls_score is not None:\n avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.)\n if cls_score.numel() > 0:\n loss_cls_ = self.loss_cls(\n cls_score,\n labels,\n label_weights,\n avg_factor=avg_factor,\n reduction_override=reduction_override)\n if isinstance(loss_cls_, dict):\n losses.update(loss_cls_)\n else:\n losses['loss_cls'] = loss_cls_\n if self.custom_activation:\n acc_ = self.loss_cls.get_accuracy(cls_score, labels)\n losses.update(acc_)\n else:\n losses['acc'] = accuracy(cls_score, labels)\n if bbox_pred is not None:\n bg_class_ind = self.num_classes\n # 0~self.num_classes-1 are FG, self.num_classes is BG\n pos_inds = (labels >= 0) & (labels < bg_class_ind)\n # do not perform bounding box regression for BG anymore.\n if pos_inds.any():\n if self.reg_decoded_bbox:\n # When the regression loss (e.g. `IouLoss`,\n # `GIouLoss`, `DIouLoss`) is applied directly on\n # the decoded bounding boxes, it decodes the\n # already encoded coordinates to absolute format.\n bbox_pred = self.bbox_coder.decode(rois[:, 1:], bbox_pred)\n if self.reg_class_agnostic:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), 4)[pos_inds.type(torch.bool)]\n else:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), -1,\n 4)[pos_inds.type(torch.bool),\n labels[pos_inds.type(torch.bool)]]\n losses['loss_bbox'] = self.loss_bbox(\n pos_bbox_pred,\n bbox_targets[pos_inds.type(torch.bool)],\n bbox_weights[pos_inds.type(torch.bool)],\n avg_factor=bbox_targets.size(0),\n reduction_override=reduction_override)\n else:\n losses['loss_bbox'] = bbox_pred[pos_inds].sum()\n return losses\n\n def get_targets(self,\n sampling_results,\n gt_bboxes,\n gt_labels,\n rcnn_train_cfg,\n concat=True):\n # 重写这个方法是为了加入pos_assigned_gt_inds,方便判断pos的pred_box是预测的哪个gt_box,在tradboost中每个标签框的权重不一样\n pos_bboxes_list = [res.pos_bboxes for res in sampling_results]\n neg_bboxes_list = [res.neg_bboxes for res in sampling_results]\n pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]\n pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]\n pos_assigned_gt_inds_list = [res.pos_assigned_gt_inds for res in sampling_results]\n labels, label_weights, bbox_targets, bbox_weights, bbox_gt_inds = multi_apply(\n self._get_target_single,\n pos_bboxes_list,\n neg_bboxes_list,\n pos_gt_bboxes_list,\n pos_gt_labels_list,\n pos_assigned_gt_inds_list,\n cfg=rcnn_train_cfg)\n if concat:\n labels = torch.cat(labels, 0)\n label_weights = torch.cat(label_weights, 0)\n bbox_targets = torch.cat(bbox_targets, 0)\n bbox_weights = torch.cat(bbox_weights, 0)\n bbox_gt_inds = torch.cat(bbox_gt_inds, 0)\n return labels, label_weights, bbox_targets, bbox_weights, bbox_gt_inds\n\n def _get_target_single(self, pos_bboxes, neg_bboxes, pos_gt_bboxes,\n pos_gt_labels, pos_assigned_gt_inds_list, cfg):\n num_pos = pos_bboxes.size(0)\n num_neg = neg_bboxes.size(0)\n num_samples = num_pos + num_neg\n # original implementation uses new_zeros since BG are set to be 0\n # now use empty & fill because BG cat_id = num_classes,\n # FG cat_id = [0, num_classes-1]\n labels = pos_bboxes.new_full((num_samples,),\n self.num_classes,\n dtype=torch.long)\n label_weights = pos_bboxes.new_zeros(num_samples)\n bbox_targets = pos_bboxes.new_zeros(num_samples, 4)\n bbox_weights = pos_bboxes.new_zeros(num_samples, 4)\n bbox_gt_inds = pos_bboxes.new_full((num_samples,),\n -1,\n dtype=torch.long)\n if num_pos > 0:\n labels[:num_pos] = pos_gt_labels\n pos_weight = 1.0 if cfg.pos_weight <= 0 else cfg.pos_weight\n label_weights[:num_pos] = pos_weight\n if not self.reg_decoded_bbox:\n pos_bbox_targets = self.bbox_coder.encode(\n pos_bboxes, pos_gt_bboxes)\n else:\n # When the regression loss (e.g. `IouLoss`, `GIouLoss`)\n # is applied directly on the decoded bounding boxes, both\n # the predicted boxes and regression targets should be with\n # absolute coordinate format.\n pos_bbox_targets = pos_gt_bboxes\n bbox_targets[:num_pos, :] = pos_bbox_targets\n bbox_gt_inds[:num_pos] = pos_assigned_gt_inds_list\n bbox_weights[:num_pos, :] = 1\n if num_neg > 0:\n label_weights[-num_neg:] = 1.0\n\n return labels, label_weights, bbox_targets, bbox_weights, bbox_gt_inds\n","sub_path":"transfer_folder/convfc_bbox_head_weightv4.py","file_name":"convfc_bbox_head_weightv4.py","file_ext":"py","file_size_in_byte":9397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"466049542","text":"#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom engine import *\nfrom bs4 import BeautifulSoup as bs\nimport os\nimport re\nimport sys\nsys.path.append(\"../\")\n\ntry:\n import urllib2 as urllib\nexcept:\n from urllib.parse import urljoin\n\ncount = 0\n\n\nclass X8List(KolaParser):\n def __init__(self, url=None):\n super().__init__()\n if url:\n self.cmd['source'] = url\n # self.cmd['cache'] = False\n\n def cmd_parser(self, text):\n data = {}\n if 'private' in text:\n data = text['private']\n\n soup = bs(text['data'], \"html.parser\", exclude_encodings='UTF8')\n # print(text['data'])\n\n i = 0\n for tc_nr in soup.findAll('div', {\"class\": \"tc_nr l_b\"}):\n for li in tc_nr.findAll('li'):\n for videoinfo in li.findAll('div', {\"class\": \"w_z\"}):\n href = videoinfo.findAll('a')\n if href and href[0]['href'] != '/':\n data = {}\n data['href'] = urljoin(text['source'], href[0]['href'])\n data['text'] = href[0].text\n\n img = li.findAll('img', {\"class\": \"lazy\"})\n data['img'] = img[0]['data-original']\n data['id'] = os.path.basename(data['img'][:-4])\n\n span = li.findAll('span')\n data['time'] = span[0].text\n data['date'] = span[1].text\n\n # if len(data['id']) != 32:\n X8Detailed(data['href'], data).AddCommand()\n i += 1\n\n # self.Finish()\n # return\n # 下一页\n for page in soup.findAll('a', {'class': 'pagenum extend'}):\n if page.text == '下一页' and page['href'] != 'page_20000.html':\n next_url = urljoin(text['source'], page['href'])\n print(next_url)\n X8List(next_url).AddCommand()\n else:\n self.Finish()\n\n\nclass X8Detailed(KolaParser):\n def __init__(self, url=None, data=None):\n super().__init__()\n if url:\n self.cmd['source'] = url\n self.cmd['cache'] = True\n self.cmd['private'] = data\n\n def cmd_parser(self, text):\n global count\n\n data = {}\n if 'private' in text:\n data = text['private']\n\n soup = bs(text['data'], \"html.parser\", exclude_encodings='UTF8')\n\n for v in soup.findAll('span', {\"id\": \"vpath\"}):\n vservers = [\"https://aikantp.com/v/\", \"https://jiuktp.com/v/\"]\n url_0 = urljoin(vservers[0], v.text)\n url_1 = urljoin(vservers[1], v.text)\n data['m3u8'] = [url_0, url_1]\n data['id2'] = os.path.basename(v.text[:-11])\n break\n\n for v in soup.findAll('div', {\"class\": \"x_z\"}):\n x = v.findAll(\n 'a', {'rel': \"noopener noreferrer\", 'target': \"_self\"})\n if x:\n if x[0]['href'] != '#':\n data['url'] = x[0]['href']\n break\n\n if 'url' in data and data['url']:\n count += 1\n # print(\"%4d %s %10s %s %s\" % (count, data['date'], data['time'], data['url'], data['text']))\n print(\"%4d %s %10s %s %s\" % (count, data['date'], data['time'], data['url'], ''))\n\n return data\n\n\nclass X8Engine(EngineBase):\n def __init__(self):\n self.parserList = [\n X8Detailed(),\n X8List(),\n ]\n\n def Start(self):\n url = 'https://8atw.com/html/category/video/'\n\n # text, ret = get_url('https://8x8x.com')\n # print(text)\n # if ret:\n # soup = bs(text, \"html.parser\", exclude_encodings='UTF8')\n # for v in soup.findAll('span', {\"class\": \"abc\"}):\n # urls = v.findAll('a')\n # if urls:\n # url = urljoin(urls[0]['href'], 'html/category/video/')\n\n url = 'https://8bwj.com/html/category/video/page_724.html'\n # url = 'https://8aam.com/html/category/video/page_1.html'\n # # url = 'https://8aam.com/html/category/video/page_1220.html'\n X8List(url).AddCommand()\n","sub_path":"books/x8x8.py","file_name":"x8x8.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"132483082","text":"import sys\nimport numpy as np\nimport matplotlib\nif sys.platform in ['linux', 'linux2']:\n matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport six\nimport os\nimport math, argparse, random\nimport chainer\nfrom chainer import cuda\nfrom chainer import optimizers\nfrom chainer import serializers\nimport itertools\nfrom pathlib import Path\nimport modules.stargan_net as net\nfrom util.utility import separate_speaker, get_separated_values\nfrom tqdm import trange\n\n# make ramdom indexes sequence (N kinds, length of list = Nmax)\ndef myperm(N, Nmax):\n rep = math.ceil(Nmax/N)\n indexes = np.concatenate([np.random.permutation(N) for _ in range(rep)])\n\n return indexes[:Nmax]\n\ndef packing(np_objs):\n lengths = [data.shape[0] for data in np_objs]\n return np.concatenate(np_objs, axis=0), lengths\n\ndef unpacking(np_obj, lengths):\n cumsum_lens = np.concatenate(([0], np.cumsum(lengths)))\n N = len(lengths)\n return [np_obj[cumsum_lens[i]:cumsum_lens[i+1]] for i in range(N)]\n\n# input: list of bach datas [(mcep_dim, T1), (mcep_dim, T2), ... ]\n# return: np.array which shape is (batch_size, mcep_dim, max(T1, T2, ... ))\n# if mcep_dim is difference, I think return error.\ndef batchlist2array(batchlist):\n # batchlist[b]\n # b: utterance index\n batchsize = len(batchlist)\n widths = [batchdata.shape[1] for batchdata in batchlist]\n maxheight = batchlist[0].shape[0]\n maxwidth = max(widths)\n\n X = np.zeros((batchsize, maxheight, maxwidth))\n for b in range(batchsize):\n tmp = batchlist[b]\n tmp = np.tile(tmp, (1, math.ceil(maxwidth/tmp.shape[1])))\n X[b,:,:] = tmp[:, 0:maxwidth] # error if mcep_dim is different\n #X[b,0:tmp.shape[0],0:tmp.shape[1]] = tmp\n #mask[b,:,0:tmp.shape[1]] = 1.0\n return X\n\ndef snapshot(output_dir, epoch, generator, classifier, adverserial_discriminator):\n # print('save the generator at {} epoch'.format(epoch))\n serializers.save_npz(output_dir / f'{epoch}.gen', generator)\n # print('save the classifier at {} epoch'.format(epoch))\n serializers.save_npz(output_dir / f'{epoch}.cls', classifier)\n # print('save the real/fake discriminator at {} epoch'.format(epoch))\n serializers.save_npz(output_dir / f'{epoch}.advdis', adverserial_discriminator)\n\n# print('AdvLoss_d={}, AdvLoss_g={}, ClsLoss_r={}, ClsLoss_f={}'\n# .format(AdvLoss_d.data, AdvLoss_g.data, ClsLoss_r.data, ClsLoss_f.data))\n# print('CycLoss={}, RecLoss={}'\n# .format(CycLoss.data, RecLoss.data))\ndef save_loss(output_dir, advloss_d, advloss_g, clsloss_r, clsloss_f, cycloss, recloss):\n logdir = output_dir / \"sgvc_log\"\n logdir.mkdir(exist_ok=True)\n fnames = [\"advloss_d\", \"advloss_g\", \"clsloss_r\", \"clsloss_f\", \"cycloss\", \"recloss\"]\n values = chainer.cuda.to_cpu([advloss_d, advloss_g, clsloss_r, clsloss_f, cycloss, recloss])\n for fname, value in zip(fnames, values):\n with (logdir / f\"{fname}.txt\").open(mode=\"a\") as f:\n np.savetxt(f, np.array([value, ]))\n\ndef main():\n parser = argparse.ArgumentParser(description='Train stargan voice convertor')\n parser.add_argument(\n '--gpu', type=int, default=-1, help='GPU ID (negative value indicates CPU)')\n parser.add_argument(\"--train_data\", type=Path, required=True, help=\"training data\")\n parser.add_argument(\"--speaker_id\", type=Path, required=True, help=\"speaker_id file\")\n parser.add_argument(\"--output_file\", type=Path, required=True)\n parser.add_argument(\n '--epoch', default=6000, type=int, help='number of epochs to learn')\n parser.add_argument(\"--epoch_start\", type=int, default=0)\n\n parser.add_argument(\n '--snapshot', default=100, type=int, help='interval of snapshot')\n parser.add_argument(\n '--batchsize', type=int, default=4, help='Batch size')\n parser.add_argument(\n '--optimizer', default='Adam', choices=[\"Adam\", \"MomentumSGD\", \"RMSprop\"], type=str, help='optimizer to use: Adam, MomentumSGD, RMSprop')\n parser.add_argument(\n '--lrate', default='0.00001', type=float, help='learning rate for Adam, MomentumSGD or RMSprop')\n parser.add_argument(\n '--genpath', type=str, help='path for a pretrained generator')\n parser.add_argument(\n '--clspath', type=str, help='path for a pretrained classifier')\n parser.add_argument(\n '--advdispath', type=str, help='path for a pretrained real/fake discriminator')\n\n args = parser.parse_args()\n epsi = sys.float_info.epsilon\n\n output_file = args.output_file\n output_dir = output_file.with_suffix(\"\")\n output_dir.mkdir(exist_ok=True, parents=True)\n\n all_source = np.load(args.train_data)\n Speakers, SpeakerIndividualKeys = separate_speaker(np.load(args.speaker_id))\n NormalizedAllData = get_separated_values(all_source, SpeakerIndividualKeys)\n SpeakerNum = len(Speakers)\n\n # Set input directories\n EpochNum = args.epoch\n BatchSize = args.batchsize\n\n SentenceNum = [len(SpeakerIndividualKeys[s]) for s in range(SpeakerNum)]\n MaxSentenceNum = max(SentenceNum)\n\n print('#GPU: {}'.format(args.gpu))\n print('#epoch: {}'.format(EpochNum))\n print('Optimizer: {}'.format(args.optimizer))\n print('Learning rate: {}'.format(args.lrate))\n print('Snapshot: {}'.format(args.snapshot))\n\n # Set up model\n num_mels = 36\n zdim = 5\n hdim = 32\n cdim = 8\n adim = 32\n\n # num_mels = data.shape[0] (36dim)\n # zdim = 8\n # hdim = 32\n generator_class = net.Generator1\n classifier_class = net.Classifier1\n discriminator_class = net.AdvDiscriminator1\n loss_class = net.Loss1\n\n generator = generator_class(SpeakerNum)\n # paranum = sum(p.data.size for p in generator.params())\n # print('Parameter #: {}'.format(paranum))\n\n # cdim = 8\n classifier = classifier_class(num_mels, SpeakerNum, cdim)\n # paranum = sum(p.data.size for p in classifier.params())\n # print('Parameter #: {}'.format(paranum))\n\n # adim = 32\n adverserial_discriminator = discriminator_class(num_mels, SpeakerNum, adim)\n # adverserial_discriminator = net.AdvDiscriminator_noactive(num_mels, SpeakerNum, adim)\n # paranum = sum(p.data.size for p in adverserial_discriminator.params())\n # print('Parameter #: {}'.format(paranum))\n\n if args.genpath is not None:\n try:\n serializers.load_npz(args.genpath, generator)\n except:\n print('Could not load generator.')\n if args.clspath is not None:\n try:\n serializers.load_npz(args.clspath, classifier)\n except:\n print('Could not load domain classifier.')\n if args.advdispath is not None:\n try:\n serializers.load_npz(args.advdispath, adverserial_discriminator)\n except:\n print('Could not load real/fake discriminator.')\n\n if args.gpu >= 0:\n chainer.cuda.get_device(args.gpu).use()\n generator.to_gpu()\n classifier.to_gpu()\n adverserial_discriminator.to_gpu()\n xp = np if args.gpu < 0 else cuda.cupy\n\n # Set up optimziers\n # loss = net.Loss1(generator, classifier, adverserial_discriminator)\n loss = loss_class(generator, classifier, adverserial_discriminator)\n w_adv = 1.0\n w_cls = 1.0\n w_cyc = 1.0\n w_rec = 1.0\n if args.optimizer == 'MomentumSGD':\n opt_gen = optimizers.MomentumSGD(lr=args.lrate, momentum=0.9)\n opt_cls = optimizers.MomentumSGD(lr=args.lrate, momentum=0.9)\n opt_advdis = optimizers.MomentumSGD(lr=args.lrate, momentum=0.9)\n elif args.optimizer == 'Adam':\n opt_gen = optimizers.Adam(alpha=0.001, beta1=0.9)\n opt_cls = optimizers.Adam(alpha=0.00005, beta1=0.5)\n opt_advdis = optimizers.Adam(alpha=0.00001, beta1=0.5)\n elif args.optimizer == 'RMSprop':\n opt_gen = optimizers.RMSprop(lr=args.lrate)\n opt_cls = optimizers.RMSprop(lr=args.lrate)\n opt_advdis = optimizers.RMSprop(lr=args.lrate)\n opt_gen.setup(generator)\n opt_cls.setup(classifier)\n opt_advdis.setup(adverserial_discriminator)\n\n\n AllCombinationPairs = list(itertools.combinations(range(SpeakerNum), 2))\n # train\n for epoch in trange(args.epoch_start, EpochNum+1):\n\n # shuffled_indexes[speaker_idx][idx]: value is index of NormalizedAllData[speaker_idx][**here**]\n shuffled_indexes = [myperm(SentenceNum[s], MaxSentenceNum) for s in range(SpeakerNum)]\n\n for n in range(MaxSentenceNum//BatchSize):\n # batchlist_mcep[speaker_idx][sentence_idx_in_batch]\n batchlist_mcep = []\n begin_idx = n * BatchSize\n end_idx = begin_idx + BatchSize # not include @ end_idx\n for s in range(SpeakerNum):\n batch_tmp = []\n for idx in shuffled_indexes[s][begin_idx:end_idx]:\n batch_tmp.append( NormalizedAllData[s][idx].T ) # Transpose here!!\n batchlist_mcep.append(batch_tmp)\n # Convert batchlist into a list of arrays\n X = [batchlist2array(batchlist) for batchlist in batchlist_mcep]\n\n xin = [chainer.Variable(xp.asarray(Xs, dtype=np.float32)) for Xs in X]\n\n # Iterate through all speaker pairs\n random.shuffle(AllCombinationPairs)\n for s0, s1 in AllCombinationPairs:\n AdvLoss_d, AdvLoss_g, ClsLoss_r, ClsLoss_f, CycLoss, RecLoss \\\n = loss.calc_loss(xin[s0], xin[s1], s0, s1, SpeakerNum)\n gen_loss = (w_adv * AdvLoss_g + w_cls * ClsLoss_f\n + w_cyc * CycLoss + w_rec * RecLoss)\n cls_loss = ClsLoss_r\n advdis_loss = AdvLoss_d\n generator.cleargrads()\n gen_loss.backward()\n opt_gen.update()\n classifier.cleargrads()\n cls_loss.backward()\n opt_cls.update()\n adverserial_discriminator.cleargrads()\n advdis_loss.backward()\n opt_advdis.update()\n\n print('epoch {}, mini-batch {}:'.format(epoch, n+1))\n print('AdvLoss_d={}, AdvLoss_g={}, ClsLoss_r={}, ClsLoss_f={}'\n .format(AdvLoss_d.data, AdvLoss_g.data, ClsLoss_r.data, ClsLoss_f.data))\n print('CycLoss={}, RecLoss={}'\n .format(CycLoss.data, RecLoss.data))\n save_loss(output_dir, AdvLoss_d.data, AdvLoss_g.data, ClsLoss_r.data, ClsLoss_f.data, CycLoss.data, RecLoss.data)\n\n if epoch % args.snapshot == 0:\n snapshot_dir = output_dir / \"snapshot\"\n snapshot_dir.mkdir(exist_ok=True)\n snapshot(snapshot_dir, epoch, generator, classifier, adverserial_discriminator)\n snapshot_feature_dir = output_dir / \"snapshot_feature\"\n snapshot_feature_dir.mkdir(exist_ok=True)\n output = {}\n with chainer.no_backprop_mode():\n for s in range(SpeakerNum):\n for key, mcep in zip(SpeakerIndividualKeys[s], NormalizedAllData[s]):\n mcep_T = mcep.T\n out = generator.hidden_layer(chainer.Variable(xp.asarray(mcep_T[np.newaxis,:,:], dtype=np.float32)))\n out = np.squeeze(cuda.to_cpu(out.data))\n output[key] = out.T\n np.savez(snapshot_feature_dir / f\"{output_file.stem}_epoch_{epoch:05}.npz\", **output)\n\n # output final result\n output = {}\n with chainer.no_backprop_mode():\n for s in range(SpeakerNum):\n for key, mcep in zip(SpeakerIndividualKeys[s], NormalizedAllData[s]):\n mcep_T = mcep.T\n out = generator.hidden_layer(chainer.Variable(xp.asarray(mcep_T[np.newaxis,:,:], dtype=np.float32)))\n out = np.squeeze(cuda.to_cpu(out.data))\n output[key] = out.T\n np.savez(output_file, **output)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Experiment_1/src/StarGAN-VC/train_stargan-vc.py","file_name":"train_stargan-vc.py","file_ext":"py","file_size_in_byte":11823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"504359668","text":"#https://datascience.stackexchange.com/questions/36049/how-to-adjust-the-hyperparameters-of-mlp-classifier-to-get-more-perfect-performa\n#http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf\n#https://towardsdatascience.com/simple-guide-to-hyperparameter-tuning-in-neural-networks-3fe03dad8594\nfrom __future__ import print_function\nimport pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import ExtraTreesClassifier\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nimport random as rn\n\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Dropout, Input\nfrom keras.callbacks import Callback, ModelCheckpoint\nfrom keras.regularizers import l2\nimport csv\nimport p1b2\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import preprocessing\nimport seaborn as sns\n# Printing complete marix / full numpy array\nimport sys\nnp.set_printoptions(threshold=sys.maxsize)\n\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\n\n#Writing in Excel\nimport xlwt\nfrom xlwt import Workbook\nBATCH_SIZE = 1024#64#1806111\nNB_EPOCH = 20 # number of training epochs\nPENALTY = 0.0001 # L2 regularization penalty\nACTIVATION = 'relu'\nFEATURE_SUBSAMPLE = None\nDROP = None\n\nL1 = 16\n#L2 = 8\n#L3 = 4\n#L4 = 8\nLAYERS = [L1] #[L1,L2,L3]\n\nclass BestLossHistory(Callback):\n def on_train_begin(self, logs={}):\n self.best_val_loss = np.Inf\n self.best_val_acc = -np.Inf\n self.best_model = None\n\n def on_epoch_end(self, batch, logs={}):\n if float(logs.get('val_loss', 0)) < self.best_val_loss:\n self.best_model = self.model\n self.best_val_loss = min(float(logs.get('val_loss', 0)), self.best_val_loss)\n self.best_val_acc = max(float(logs.get('val_acc', 0)), self.best_val_acc)\n\n\ndef extension_from_parameters():\n \"\"\"Construct string for saving model with annotation of parameters\"\"\"\n ext = ''\n ext += '.A={}'.format(ACTIVATION)\n ext += '.B={}'.format(BATCH_SIZE)\n ext += '.D={}'.format(DROP)\n ext += '.E={}'.format(NB_EPOCH)\n if FEATURE_SUBSAMPLE:\n ext += '.F={}'.format(FEATURE_SUBSAMPLE)\n for i, n in enumerate(LAYERS):\n if n:\n ext += '.L{}={}'.format(i+1, n)\n ext += '.P={}'.format(PENALTY)\n return ext\n\ndef test():\n (X_train, y_train), (X_test, y_test) = p1b2.load_data(n_cols=FEATURE_SUBSAMPLE)\n #dist = pd.DataFrame(X_train)\n print(y_test.shape)\n\ndef recordSoftmaxProbabilities(X_train = None, y_train = None, X_test = None, y_test = None, DeterministicResults = False,fileName=None):\n if(DeterministicResults):\n __setSession()\n if(X_train is None):\n (X_train, y_train), (X_test, y_test) = p1b2.load_data()\n wb = Workbook()\n\n # =====create sheet1 and add headers====\n sheetToRecordTrainValidTestLossAndAccuracy = wb.add_sheet('Sheet 1')\n sheetToRecordTrainValidTestLossAndAccuracy.write(0, 0, 'ValidationLoss')\n sheetToRecordTrainValidTestLossAndAccuracy.write(0, 1, 'TestLoss')\n sheetToRecordTrainValidTestLossAndAccuracy.write(0, 2, 'Accuracy')\n\n for x in range(1, 26):\n if X_train is None:\n (X_train, y_train), (X_test, y_test) = p1b2.load_data(n_cols=FEATURE_SUBSAMPLE)\n\n input_dim = X_train.shape[1]\n output_dim = y_train.shape[1]\n\n\n\n model = Sequential()\n model.add(Dense(LAYERS[0], input_dim=input_dim,\n activation=\"sigmoid\",\n kernel_regularizer=l2(PENALTY),\n activity_regularizer=l2(PENALTY)))\n\n for layer in LAYERS[1:]:\n if layer:\n if DROP:\n model.add(Dropout(DROP))\n model.add(Dense(layer, activation=ACTIVATION,\n kernel_regularizer=l2(PENALTY),\n activity_regularizer=l2(PENALTY)))\n\n model.add(Dense(output_dim, activation='softmax'))\n\n #Next the model would be compiled. Compiling the model takes two parameters: optimizer and loss\n #https: // towardsdatascience.com / building - a - deep - learning - model - using - keras - 1548ca149d37\n #https://towardsdatascience.com/sequence-models-by-andrew-ng-11-lessons-learned-c62fb1d3485b\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\n\n print(\"Model Summary:\", model.summary())\n\n ext = extension_from_parameters()\n checkpointer = ModelCheckpoint(filepath='model'+ext+'.h5', save_best_only=True)\n history = BestLossHistory()\n\n trainingResults = model.fit(X_train, y_train,\n batch_size=BATCH_SIZE,\n epochs=NB_EPOCH,\n validation_split=0.2,\n callbacks=[history, checkpointer])\n\n y_pred = history.best_model.predict(X_test)\n predictedOutputs = model.predict_classes(X_test)\n\n scores = p1b2.evaluate(y_pred, y_test)\n\n #Confusion Matrix\n #cnf_matrix = confusion_matrix(y_test_SingleColumn, predictedOutputs)\n #print(\"Confusion Matrix = \", cnf_matrix)\n\n #ROC curve\n # keep probabilities for the positive outcome only\n #ns_probs = [0 for _ in range(len(y_test_SingleColumn))]\n #lr_probs = y_pred[:, 0]\n #print(\"Faqeer = \", lr_probs)\n # calculate scores\n #ns_auc = roc_auc_score(y_test_SingleColumn, ns_probs)\n #lr_auc = roc_auc_score(y_test_SingleColumn, lr_probs)\n #print('No Skill: ROC AUC=%.3f' % (ns_auc))\n #print('Logistic: ROC AUC=%.3f' % (lr_auc))\n\n #Print Other Results\n testResults = model.evaluate(X_test,y_test,batch_size=BATCH_SIZE)\n print('Evaluation on test data:', scores)\n #print('Test Scores [Test Loss, Test Accuracy] = ', testResults[0])\n #print('Loss: ', np.amin(trainingResults.history['loss']),'Accuracy: ',np.amin(trainingResults.history['accuracy']),'Val_Loss: ',np.amin(trainingResults.history['val_loss']),'Val_Accuracy :',np.amin(trainingResults.history['val_accuracy']))\n #print('best_val_loss={:.5f} best_val_acc={:.5f}'.format(history.best_val_loss, history.best_val_acc))\n #print('Best model saved to: {}'.format('model'+ext+'.h5'))\n\n # ======Save Training loss,Validation(Best model) loss, test loss and Accuracy\n #sheetToRecordTrainValidTestLossAndAccuracy.write(x, 0, str(round(np.amin(trainingResults.history['loss']), 3)))\n sheetToRecordTrainValidTestLossAndAccuracy.write(x, 0, str(round(history.best_val_loss, 3)))\n sheetToRecordTrainValidTestLossAndAccuracy.write(x, 1, str(round(testResults[0], 3)))\n sheetToRecordTrainValidTestLossAndAccuracy.write(x, 2, str(scores))\n # ===========================================================================\n # =====Save Instance level outputs against each experiment/iteration over for Each Class=====\n # =====create sheet2 and add headers====\n sheetToRecordInstanceLevelOutput = wb.add_sheet('IterationNo' + str(x))\n sheetToRecordInstanceLevelOutput.write(1, 0, 'InputFeatures')\n sheetToRecordInstanceLevelOutput.write(1, 1, 'Expected_OR_ActualOutput')\n sheetToRecordInstanceLevelOutput.write(1, 2, 'PredictedOutput')\n sheetToRecordInstanceLevelOutput.write(1, 3, 'Probabilities')\n sheetToRecordInstanceLevelOutput.write(1, 4, 'MaxProbability')\n startRowToBeInserted = 2\n for x in range(X_test.shape[0]):\n # print(\"ddd = \", X_test[x])\n sheetToRecordInstanceLevelOutput.write(startRowToBeInserted, 0, 'Test Data Input Features') # str(X_test[x]))\n sheetToRecordInstanceLevelOutput.write(startRowToBeInserted, 1, str(y_test[x]))\n sheetToRecordInstanceLevelOutput.write(startRowToBeInserted, 2, str(predictedOutputs[x]))\n sheetToRecordInstanceLevelOutput.write(startRowToBeInserted, 3, str(y_pred[x]))\n sheetToRecordInstanceLevelOutput.write(startRowToBeInserted, 4, str(np.amax(y_pred[x])))\n startRowToBeInserted = startRowToBeInserted + 1\n # ==============================================================================\n\n submission = {'scores': scores,\n 'model': model.summary(),\n 'submitter': 'Developer Name' }\n\n if fileName != None:\n wb.save(fileName) # .xls\n else:\n wb.save(\"Default.xls\") # .xls\n # print('Submitting to leaderboard...')\n # leaderboard.submit(submission)\n __resetSeed()\n # return history.best_model\n return scores\n\n\n#https://towardsdatascience.com/feature-selection-techniques-in-machine-learning-with-python-f24e7da3f36e\n#https://towardsdatascience.com/chi-square-test-for-feature-selection-in-machine-learning-206b1f0b8223\ndef UnivariateSelection():\n data = pd.read_csv(\"C:/Users/faqeerrehman/MSU/Research/CancerPrediction/ScientificSWTesting/Data/Pilot1/P1B2.train.csv\")\n #data = pd.read_csv(\"C:/Users/faqeerrehman/MSU/Research/CancerPrediction/ScientificSWTesting/Data/Pilot1/Train.csv\")\n X = data.iloc[:, 2:] # independent columns\n y = data.iloc[:, 1] # target column i.e price range\n #print(\"X = \", X)\n #print(\"Y = \", y)\n # apply SelectKBest class to extract top 10 best features\n bestfeatures = SelectKBest(score_func=chi2, k=3000)\n\n fit = bestfeatures.fit(X, y)\n dfscores = pd.DataFrame(fit.scores_)\n dfcolumns = pd.DataFrame(X.columns)\n # concat two dataframes for better visualization\n featureScores = pd.concat([dfcolumns, dfscores], axis=1)\n featureScores.columns = ['Specs', 'Score'] # naming the dataframe columns\n #print(dfcolumns.to_string())\n bestFeaturesWithScores = featureScores.nlargest(3000, 'Score')\n print(bestFeaturesWithScores.to_string()) # print 10 best features\n #print(bestFeaturesWithScores)\n #print(extractFeaturesIndexFromFile())\n\ndef extractFeaturesIndexFromFile():\n concatenatedColumnValues = ''\n data = pd.read_csv(\"C:/Users/faqeerrehman/MSU/Research/CancerPrediction/ScientificSWTesting/Data/Pilot1/BestFeaturesResult.csv\")\n for index, row in data.iterrows():\n firstIndexColumnValues = row[0].split(' ')\n concatenatedColumnValues = concatenatedColumnValues + ',' + str(int(firstIndexColumnValues[0])+2)\n print(concatenatedColumnValues[1:])\n #return concatenatedColumnValues[1:]\n #for i in range(length):\n #print(i)\n\n\ndef featureImportance():\n data = pd.read_csv(\"C:/Users/faqeerrehman/MSU/Research/CancerPrediction/ScientificSWTesting/Data/Pilot1/P1B2.train.csv\")\n X = data.iloc[:, 2:] # independent columns\n y = data.iloc[:, 1] # target column i.e price range\n #print(\"X = \", X)\n #print(\"Y = \", y)\n model = ExtraTreesClassifier()\n model.fit(X, y)\n print(model.feature_importances_) # use inbuilt class feature_importances of tree based classifiers\n # plot graph of feature importances for better visualization\n feat_importances = pd.Series(model.feature_importances_, index=X.columns)\n feat_importances.nlargest(10).plot(kind='barh')\n plt.show()\n\ndef correlationMatrixwithHeatmap():\n data = pd.read_csv(\"C:/Users/faqeerrehman/MSU/Research/CancerPrediction/ScientificSWTesting/Data/Pilot1/P1B2.train.csv\")\n X = data.iloc[:, 2:] # independent columns\n y = data.iloc[:, 1] # target column i.e price range\n # get correlations of each features in dataset\n corrmat = data.corr()\n top_corr_features = corrmat.index\n plt.figure(figsize=(20, 20))\n # plot heat map\n g = sns.heatmap(data[top_corr_features].corr(), annot=True, cmap=\"RdYlGn\")\n\ndef mainFeatureSelection(X_train = None, y_train = None, X_test = None, y_test = None, DeterministicResults = False):\n if(DeterministicResults):\n __setSession()\n\n\n\n if X_train is None:\n (X_train, y_train), (X_test, y_test) = p1b2.load_data(n_cols=FEATURE_SUBSAMPLE)\n\n input_dim = X_train.shape[1]\n output_dim = y_train.shape[1]\n print(\"X Train: \", X_train)\n print(\"Y Train: \", y_train)\n model = Sequential()\n model.add(Dense(LAYERS[0], input_dim=input_dim,\n activation=ACTIVATION,\n kernel_regularizer=l2(PENALTY),\n activity_regularizer=l2(PENALTY)))\n\n for layer in LAYERS[1:]:\n if layer:\n if DROP:\n model.add(Dropout(DROP))\n model.add(Dense(layer, activation=ACTIVATION,\n kernel_regularizer=l2(PENALTY),\n activity_regularizer=l2(PENALTY)))\n\n model.add(Dense(output_dim, activation=ACTIVATION))\n\n\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n print(model.summary())\n\n ext = extension_from_parameters()\n checkpointer = ModelCheckpoint(filepath='model'+ext+'.h5', save_best_only=True)\n history = BestLossHistory()\n\n model.fit(X_train, y_train,\n batch_size=BATCH_SIZE,\n epochs=NB_EPOCH,\n validation_split=0.2,\n callbacks=[history, checkpointer])\n\n y_pred = history.best_model.predict(X_test)\n predictedOutputs = model.predict_classes(X_test)\n #print(\"TestDataX = \", X_test)\n #print(\"TestDataY = \", y_test)\n #i=0\n #j=1\n\n #for x in np.nditer(X_test, flags = ['external_loop'], order = 'C'):\n # print(\"Instance = \", X_test[i:j], \" --> Prediciton = \", history.best_model.predict(np.array(X_test[i:j])))\n # i = i + 1\n # j = j + 1\n #print(\"Loop Iterations : \", x)\n\n #print(\"Y_Pred = \" , y_pred)\n #print(\"PredictedOutputs = \", predictedOutputs)\n scores = p1b2.evaluate(y_pred, y_test)\n print('Evaluation on test data:', scores)\n\n print('best_val_loss={:.5f} best_val_acc={:.5f}'.format(history.best_val_loss, history.best_val_acc))\n print('Best model saved to: {}'.format('model'+ext+'.h5'))\n\n\n\n submission = {'scores': scores,\n 'model': model.summary(),\n 'submitter': 'Developer Name' }\n\n # print('Submitting to leaderboard...')\n # leaderboard.submit(submission)\n __resetSeed()\n #return history.best_model\n return scores\n\ndef mainFaqeer(X_train = None, y_train = None, X_test = None, y_test = None, DeterministicResults = False,fileName = \"\"):\n if(DeterministicResults):\n __setSession()\n\n # Workbook is created\n wb = Workbook()\n\n # add_sheet is used to create sheet.\n sheet1 = wb.add_sheet('Sheet 1')\n\n for x in range(1,3):\n print(\"Run-----> \", x)\n if X_train is None:\n (X_train, y_train), (X_test, y_test) = p1b2.load_data(n_cols=FEATURE_SUBSAMPLE)\n\n input_dim = X_train.shape[1]\n output_dim = y_train.shape[1]\n\n model = Sequential()\n\n model.add(Dense(LAYERS[0], input_dim=input_dim,\n activation=ACTIVATION,\n kernel_regularizer=l2(PENALTY),\n activity_regularizer=l2(PENALTY)))\n\n for layer in LAYERS[1:]:\n if layer:\n if DROP:\n model.add(Dropout(DROP))\n model.add(Dense(layer, activation=ACTIVATION,\n kernel_regularizer=l2(PENALTY),\n activity_regularizer=l2(PENALTY)))\n\n model.add(Dense(output_dim, activation=ACTIVATION))\n\n\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n print(model.summary())\n\n ext = extension_from_parameters()\n checkpointer = ModelCheckpoint(filepath='model'+ext+'.h5', save_best_only=True)\n history = BestLossHistory()\n\n model.fit(X_train, y_train,\n batch_size=BATCH_SIZE,\n epochs=NB_EPOCH,\n validation_split=0.2,\n callbacks=[history, checkpointer])\n\n y_pred = history.best_model.predict(X_test)\n\n print('best_val_loss={:.5f} best_val_acc={:.5f}'.format(history.best_val_loss, history.best_val_acc))\n print('Best model saved to: {}'.format('model'+ext+'.h5'))\n\n scores = p1b2.evaluate(y_pred, y_test)\n print('Evaluation on test data:', scores)\n #sheet1.write(x, 0, str(scores))\n sheet1.write(x, 0, str(np.amax(y_pred)))\n sheet1.write(x, 1, str(scores))\n submission = {'scores': scores,\n 'model': model.summary(),\n 'submitter': 'Developer Name' }\n\n # print('Submitting to leaderboard...')\n # leaderboard.submit(submission)\n wb.save(fileName)\n __resetSeed()\n return history.best_model\n\ndef __resetSeed():\n np.random.seed()\n rn.seed()\n\ndef __setSession():\n # Sets session for deterministic results\n # https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development\n\n\n # The below is necessary in Python 3.2.3 onwards to\n # have reproducible behavior for certain hash-based operations.\n # See these references for further details:\n # https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED\n # https://github.com/keras-team/keras/issues/2280#issuecomment-306959926\n import os\n os.environ['PYTHONHASHSEED'] = '0'\n\n # The below is necessary for starting Numpy generated random numbers\n # in a well-defined initial state.\n np.random.seed(42)\n # The below is necessary for starting core Python generated random numbers\n # in a well-defined state.\n rn.seed(12345)\n # Force TensorFlow to use single thread.\n # Multiple threads are a potential source of\n # non-reproducible results.\n # For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res\n session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n from keras import backend as K\n # The below tf.set_random_seed() will make random number generation\n # in the TensorFlow backend have a well-defined initial state.\n # For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n # tf.global_variables_initializer()\n tf.compat.v1.set_random_seed(1234)\n sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)\n\n # Fixed by Faqeer ur Rehman on 24 Nov 2019\n #K.set_session(sess)\n tf.compat.v1.keras.backend.set_session(sess)\n\n\nif __name__ == '__main__':\n #mainToRecordTrainValidateTestLosses()\n recordSoftmaxProbabilities(None,None,None,None,DeterministicResults = False, fileName= \"SourceOrg.xls\")\n","sub_path":"IDS_ANN_App1/OnlyHighAccuracyMutantsStudy/ANNUnderTest/IDS_OpenStack.py","file_name":"IDS_OpenStack.py","file_ext":"py","file_size_in_byte":18844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"372164876","text":"import codecs\nimport json\nfrom collections import defaultdict\n\naejson = codecs.open('../rhetorical_analysis/anaphora_epistrophe.json' , 'r', encoding='utf-8')\najson = codecs.open('../rhetorical_analysis/applause_count.json' , 'r', encoding='utf-8')\nljson = codecs.open('../rhetorical_analysis/laughter_count.json' , 'r', encoding='utf-8')\ntfjson = codecs.open('../predictive_modeling/tfidf_vectors.json' , 'r', encoding='utf-8')\nae = json.load(aejson)\na = json.load(ajson)\nl = json.load(ljson)\ntf = json.load(tfjson)\n\ndef assemble_vectors():\n\tresultsdict = defaultdict(lambda: [])\n\tfor candidate, applause in a.iteritems():\n\t\tlaughter = l[candidate]\n\t\tanaphora = ae[candidate][0]\n\t\tepistrophe = ae[candidate][1]\n\t\ttfidf = tf[candidate]\n\t\tresultsdict[candidate] += tfidf\n\t\tresultsdict[candidate].append(applause)\n\t\tresultsdict[candidate].append(laughter)\n\t\tresultsdict[candidate].append(anaphora)\n\t\tresultsdict[candidate].append(epistrophe)\n\tnewf = codecs.open('assembled_vectors.json' , 'w', encoding='utf-8')\n\tnewf.write(json.dumps(resultsdict))\n\tnewf.close()\n\nif __name__ == '__main__':\n\tassemble_vectors()","sub_path":"clustering/assemble_vectors.py","file_name":"assemble_vectors.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"524768376","text":"#!/usr/bin/env python3\r\n# coding: utf-8\r\n\r\nimport re, sys, collections, threadpool, os\r\n\r\nclass FrequencyCount:\r\n def __init__(self):\r\n self.counts = collections.Counter()\r\n\r\n def count(self):\r\n stopwords = set(open('stop_words').read().split(','))\r\n\r\n def countFile(file):\r\n words = re.findall('\\w{3,}', open(file).read().lower())\r\n self.counts += collections.Counter(w for w in words if w not in stopwords)\r\n\r\n file_list = [i for i in os.listdir('.') if i.endswith('txt')]\r\n# print(file_list)\r\n# file_list = [('crossbow.txt', None), ('gems.txt', None), ('anonymit.txt', None), ('cDc-0200.txt', None)]\r\n pool = threadpool.ThreadPool(10)\r\n requests = threadpool.makeRequests(countFile, file_list)\r\n [pool.putRequest(req) for req in requests]\r\n pool.wait()\r\n\r\n for (w, c) in self.counts.most_common(25):\r\n print(w, '-', c)\r\n\r\n\r\nif __name__ == '__main__':\r\n fc = FrequencyCount()\r\n fc.count()\r\n\r\n","sub_path":"2019Fall/SWE244P/ex5/tf.py","file_name":"tf.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"384641789","text":"from collections import defaultdict, deque\r\nimport sys\r\n\r\n\r\ndef solution(n, s, a, b, fares):\r\n result = []\r\n graph = defaultdict(list)\r\n\r\n for f in fares:\r\n graph[f[0]].append((f[1], f[2]))\r\n graph[f[1]].append((f[0], f[2]))\r\n\r\n path = []\r\n\r\n def dfs(node, cost, total_cost, cg):\r\n if node in path:\r\n return\r\n path.append(node)\r\n total_cost += cost\r\n cg[node] = min(cg[node], total_cost)\r\n\r\n for i, c in graph[node]:\r\n dfs(i, c, total_cost, cg)\r\n path.pop()\r\n return\r\n\r\n\r\n #dfs(4, 0, 0)\r\n #\r\n a_cost = defaultdict(lambda: sys.maxsize)\r\n dfs(a, 0, 0, a_cost)\r\n b_cost = defaultdict(lambda: sys.maxsize)\r\n dfs(b, 0, 0, b_cost)\r\n cost1 = a_cost[b]\r\n\r\n for n in a_cost:\r\n if n != a:\r\n if a_cost[n] + b_cost[n] == cost1:\r\n ex = n\r\n break\r\n\r\n s_cost = defaultdict(lambda: sys.maxsize)\r\n dfs(s, 0, 0, s_cost)\r\n\r\n cost1 += s_cost[n]\r\n cost2 = s_cost[a] + s_cost[b]\r\n\r\n return min(cost1, cost2)\r\n\r\n\r\nf = [[2, 6, 6], [6, 3, 7], [4, 6, 7], [6, 5, 11], [2, 5, 12], [5, 3, 20], [2, 4, 8], [4, 3, 9]]\r\nprint(solution(6, 4, 5, 6, f))\r\n","sub_path":"프로그래머스/2021 블라인드/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"395025062","text":"from ethereumetl.jobs.composite_item_exporter import CompositeItemExporter\n\nFIELDS_TO_EXPORT = [\n 'erc20_token',\n 'erc20_from',\n 'erc20_to',\n 'erc20_value',\n 'erc20_tx_hash',\n 'erc20_log_index',\n 'erc20_block_number'\n]\n\n\ndef export_erc20_transfers_job_item_exporter(erc20_transfer_output):\n return CompositeItemExporter(\n filename_mapping={\n 'erc20_transfer': erc20_transfer_output\n },\n field_mapping={\n 'erc20_transfer': FIELDS_TO_EXPORT\n }\n )\n","sub_path":"ethereumetl/jobs/export_erc20_transfers_job_item_exporter.py","file_name":"export_erc20_transfers_job_item_exporter.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"267438672","text":"#!/usr/bin/python\n# -*- eval: (progn (make-local-variable 'before-save-hook) (remove-hook 'before-save-hook 'delete-trailing-whitespace-in-some-modes t)) -*-\n#\n# (the above line is an Emacs file local variable that says *not* to delete\n# trailing whitespace, since some of it in test data is meaningful.)\n\"\"\"Unit tests for twitter.py.\n\"\"\"\n\n__author__ = ['Ryan Barrett ']\n\nimport copy\ntry:\n import json\nexcept ImportError:\n import simplejson as json\nimport mox\n\nimport source\nimport twitter\nfrom webutil import testutil\nfrom webutil import util\n\n\n# test data\ndef tag_uri(name):\n return util.tag_uri('twitter.com', name)\n\nUSER = {\n 'created_at': 'Sat May 01 21:42:43 +0000 2010',\n 'description': 'my description',\n 'location': 'San Francisco',\n 'name': 'Ryan Barrett',\n 'profile_image_url': 'http://a0.twimg.com/profile_images/866165047/ryan_normal.jpg',\n 'screen_name': 'snarfed_org',\n }\nACTOR = {\n 'displayName': 'Ryan Barrett',\n 'image': {\n 'url': 'http://a0.twimg.com/profile_images/866165047/ryan_normal.jpg',\n },\n 'id': tag_uri('snarfed_org'),\n 'published': '2010-05-01T21:42:43',\n 'url': 'http://twitter.com/snarfed_org',\n 'location': {'displayName': 'San Francisco'},\n 'username': 'snarfed_org',\n 'description': 'my description',\n }\nTWEET = {\n 'created_at': 'Wed Feb 22 20:26:41 +0000 2012',\n 'id': 172417043893731329,\n 'place': {\n 'full_name': 'Carcassonne, Aude',\n 'id': '31cb9e7ed29dbe52',\n 'name': 'Carcassonne',\n 'url': 'http://api.twitter.com/1.1/geo/id/31cb9e7ed29dbe52.json',\n },\n 'geo': {\n 'type': 'Point',\n 'coordinates': [32.4004416, -98.9852672],\n },\n 'user': USER,\n 'entities': {\n 'media': [{'media_url': 'http://p.twimg.com/AnJ54akCAAAHnfd.jpg'}],\n 'urls': [{\n 'expanded_url': 'http://instagr.am/p/MuW67/',\n 'url': 'http://t.co/6J2EgYM',\n 'indices': [43, 62],\n 'display_url': 'instagr.am/p/MuW67/'\n }],\n 'hashtags': [{\n 'text': 'tcdisrupt',\n 'indices': [32, 42]\n }],\n 'user_mentions': [{\n 'name': 'Twitter',\n 'id_str': '783214',\n 'id': 783214,\n 'indices': [0, 8],\n 'screen_name': 'foo'\n },\n {\n 'name': 'Picture.ly',\n 'id_str': '334715534',\n 'id': 334715534,\n 'indices': [15, 28],\n 'screen_name': 'foo'\n }],\n },\n 'text': '@twitter meets @seepicturely at #tcdisrupt <3 http://t.co/6J2EgYM',\n 'source': 'Choqok',\n 'in_reply_to_screen_name': 'other_user',\n 'in_reply_to_status_id': 789,\n }\nOBJECT = {\n 'objectType': 'note',\n 'author': ACTOR,\n 'content': '@twitter meets @seepicturely at #tcdisrupt <3 http://t.co/6J2EgYM',\n 'id': tag_uri('172417043893731329'),\n 'published': '2012-02-22T20:26:41',\n 'url': 'http://twitter.com/snarfed_org/status/172417043893731329',\n 'image': {'url': 'http://p.twimg.com/AnJ54akCAAAHnfd.jpg'},\n 'location': {\n 'displayName': 'Carcassonne, Aude',\n 'id': '31cb9e7ed29dbe52',\n 'url': 'https://maps.google.com/maps?q=32.4004416,-98.9852672',\n },\n 'tags': [{\n 'objectType': 'person',\n 'id': tag_uri('foo'),\n 'url': 'http://twitter.com/foo',\n 'displayName': 'Twitter',\n 'startIndex': 0,\n 'length': 8,\n }, {\n 'objectType': 'person',\n 'id': tag_uri('foo'), # same id as above, shouldn't de-dupe\n 'url': 'http://twitter.com/foo',\n 'displayName': 'Picture.ly',\n 'startIndex': 15,\n 'length': 13,\n }, {\n 'objectType': 'hashtag',\n 'url': 'https://twitter.com/search?q=%23tcdisrupt',\n 'startIndex': 32,\n 'length': 10,\n }, {\n 'objectType': 'article',\n 'url': 'http://instagr.am/p/MuW67/',\n 'startIndex': 43,\n 'length': 19,\n }],\n 'attachments': [{\n 'objectType': 'image',\n 'image': {'url': u'http://p.twimg.com/AnJ54akCAAAHnfd.jpg'},\n }],\n }\nACTIVITY = {\n 'verb': 'post',\n 'published': '2012-02-22T20:26:41',\n 'id': tag_uri('172417043893731329'),\n 'url': 'http://twitter.com/snarfed_org/status/172417043893731329',\n 'actor': ACTOR,\n 'object': OBJECT,\n 'title': 'Ryan Barrett: @twitter meets @seepicturely at #tcdisrupt <3 http://t.co/6J2EgYM',\n 'generator': {'displayName': 'Choqok', 'url': 'http://choqok.gnufolks.org/'},\n 'context': {\n 'inReplyTo' : {\n 'objectType' : 'note',\n 'url' : 'http://twitter.com/other_user/status/789',\n 'id' : tag_uri('789'),\n }\n },\n }\n\nATOM = \"\"\"\\\n\n\n\n activitystreams-unofficial\nhttp://localhost/\nUser feed for Ryan Barrett\n\nmy description\n\nhttp://a0.twimg.com/profile_images/866165047/ryan_normal.jpg\n2012-02-22T20:26:41\n\n http://activitystrea.ms/schema/1.0/person\n http://twitter.com/snarfed_org\n Ryan Barrett\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n http://activitystrea.ms/schema/1.0/person\n http://twitter.com/snarfed_org\n Ryan Barrett\n\n\n\n \n http://activitystrea.ms/schema/1.0/note\n \n \"\"\" + tag_uri('172417043893731329') + \"\"\"\n Ryan Barrett: @twitter meets @seepicturely at #tcdisrupt <3 http://t.co/6J2EgYM\n\n \n
\n\n@twitter meets @seepicturely at #tcdisrupt <3 http://t.co/6J2EgYM\n\n

\n
\n

\n\n

\n

\n\n
\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n http://activitystrea.ms/schema/1.0/post\n 2012-02-22T20:26:41\n \n \n \n \n \n \n \n \n \n Carcassonne, Aude\n \n \n \n
\n\n
\n\"\"\"\n\n\nclass TwitterTest(testutil.HandlerTest):\n\n def setUp(self):\n super(TwitterTest, self).setUp()\n self.twitter = twitter.Twitter('key', 'secret')\n\n def test_get_actor(self):\n self.expect_urlopen(\n 'https://api.twitter.com/1.1/users/lookup.json?screen_name=foo',\n json.dumps(USER))\n self.mox.ReplayAll()\n self.assert_equals(ACTOR, self.twitter.get_actor('foo'))\n\n def test_get_actor_default(self):\n self.expect_urlopen(\n 'https://api.twitter.com/1.1/account/verify_credentials.json',\n json.dumps(USER))\n self.mox.ReplayAll()\n self.assert_equals(ACTOR, self.twitter.get_actor())\n\n def test_get_activities(self):\n self.expect_urlopen(\n 'https://api.twitter.com/1.1/statuses/home_timeline.json?'\n 'include_entities=true&count=0',\n json.dumps([TWEET, TWEET]))\n self.mox.ReplayAll()\n self.assert_equals((None, [ACTIVITY, ACTIVITY]),\n self.twitter.get_activities())\n\n def test_get_activities_start_index_count(self):\n tweet2 = copy.deepcopy(TWEET)\n tweet2['user']['name'] = 'foo'\n activity2 = copy.deepcopy(ACTIVITY)\n activity2['actor']['displayName'] = 'foo'\n activity2['title'] = activity2['title'].replace('Ryan Barrett: ', 'foo: ')\n\n self.expect_urlopen(\n 'https://api.twitter.com/1.1/statuses/home_timeline.json?'\n 'include_entities=true&count=2',\n json.dumps([TWEET, tweet2]))\n self.mox.ReplayAll()\n\n got = self.twitter.get_activities(start_index=1, count=1)\n self.assert_equals((None, [activity2]), got)\n\n def test_get_activities_activity_id(self):\n self.expect_urlopen(\n 'https://api.twitter.com/1.1/statuses/show.json?id=000&include_entities=true',\n json.dumps(TWEET))\n self.mox.ReplayAll()\n\n # activity id overrides user, group, app id and ignores startIndex and count\n self.assert_equals(\n (1, [ACTIVITY]),\n self.twitter.get_activities(\n user_id='123', group_id='456', app_id='789', activity_id='000',\n start_index=3, count=6))\n\n def test_get_activities_self(self):\n self.expect_urlopen('https://api.twitter.com/1.1/statuses/user_timeline.json?'\n 'include_entities=true&count=0',\n '[]')\n self.mox.ReplayAll()\n\n self.assert_equals((None, []),\n self.twitter.get_activities(group_id=source.SELF))\n\n def test_tweet_to_activity_full(self):\n self.assert_equals(ACTIVITY, self.twitter.tweet_to_activity(TWEET))\n\n def test_tweet_to_activity_minimal(self):\n # just test that we don't crash\n self.twitter.tweet_to_activity({'id': 123, 'text': 'asdf'})\n\n def test_tweet_to_activity_empty(self):\n # just test that we don't crash\n self.twitter.tweet_to_activity({})\n\n def test_tweet_to_object_full(self):\n self.assert_equals(OBJECT, self.twitter.tweet_to_object(TWEET))\n\n def test_tweet_to_object_minimal(self):\n # just test that we don't crash\n self.twitter.tweet_to_object({'id': 123, 'text': 'asdf'})\n\n def test_tweet_to_object_empty(self):\n self.assert_equals({}, self.twitter.tweet_to_object({}))\n\n def test_user_to_actor_full(self):\n self.assert_equals(ACTOR, self.twitter.user_to_actor(USER))\n\n def test_user_to_actor_minimal(self):\n # just test that we don't crash\n self.twitter.user_to_actor({'screen_name': 'snarfed_org'})\n\n def test_user_to_actor_empty(self):\n self.assert_equals({}, self.twitter.user_to_actor({}))\n\n def test_oauth(self):\n def check_headers(headers):\n sig = dict(headers)['Authorization']\n return (sig.startswith('OAuth ') and\n 'oauth_token=\"key\"' in sig and\n 'oauth_signature=' in sig)\n\n self.expect_urlopen(\n 'https://api.twitter.com/1.1/users/lookup.json?screen_name=foo',\n json.dumps(USER),\n headers=mox.Func(check_headers))\n self.mox.ReplayAll()\n\n self.twitter.get_actor('foo')\n","sub_path":"twitter_test.py","file_name":"twitter_test.py","file_ext":"py","file_size_in_byte":11839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"158057041","text":"import numpy as np\nimport pandas as pd\nfrom Bio import SeqIO\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.SeqIO.FastaIO import FastaWriter\n\ntabel_path = 'C:/Users/user/Desktop/max_quant_test/combined/txt/'\nsimulation_path = 'C:/Users/user/Google_Drive/RNA_Editing/proteomics_simulator/'\n\n\n\"\"\"\nfrom maxquant column of protein groups, creat a list of all protein groups of child peptide\n\"\"\"\ndef comps_string_to_list(row, substr_to_del):\n return [x.replace(substr_to_del,\"\") for x in row.split(\";\")]\n\n\n\"\"\"\nread a table in txt file to dataframe\n\"\"\"\ndef read_peptides_tabel(tabel_path, tabel_name = 'peptides.txt', fasta_file_name = 'squ'):\n \n data = []\n with open(tabel_path + tabel_name, \"r\") as f:\n content = f.readlines()\n columns = content[0].split('\\t')\n for i,line in enumerate(content[1:]):\n line_arr = line.split('\\t')\n data.append(line_arr)\n \n df = pd.DataFrame(data = data, columns = columns)\n df = df.apply(pd.to_numeric, errors='ignore')\n df = df.replace(np.nan, '', regex=True)\n df['proteins_list'] = df.apply(lambda row: comps_string_to_list(row['Proteins'], fasta_file_name + '|'), axis = 1)\n df['protein_sources'] = df.apply(lambda row: len(row.proteins_list), axis = 1)\n return df\n\n\ndef get_detected_sources(row, maxquant_df):\n if row['peptide'] in maxquant_df.index:\n return maxquant_df.loc[row['peptide'],'proteins_list']\n else:\n return '-'\n \ndef check_detected_peptides(row, maxquant_df):\n if row['peptides'] in maxquant_df.index:\n return True\n else:\n return False\n \n\ndef compare_maxquant_and_simulation_results(simulation_df, maxquant_df):\n \n simulation_df['detected'] = simulation_df.apply(lambda row: check_detected_peptides(row, maxquant_df), axis = 1)\n# simulation_df['max_quant_sources'] = simulation_df.apply(lambda row: get_detected_sources(row, maxquant_df), axis = 1)\n# simulation_df['detected_proteins'] = simulation_df.apply(lambda row: len(row.max_quant_sources), axis = 1)\n \n #printing all sites to file\n return simulation_df\n\n\ndef remove_fasta_descriptions(input_path, input_fasta):\n from Bio import SeqIO\n writer = FastaWriter(open(input_path + 'no_description_' + input_fasta , 'w'), wrap=None)\n writer.write_header()\n for record in SeqIO.parse(input_path + input_fasta, \"fasta\"):\n writer.write_record(SeqRecord(record.seq, id = record.id,description = ''))\n writer.write_footer()\n\n \n \n \n \n \n \n \n","sub_path":"scripts/proteomics_simulator/OLD/20181014/backup/read_maxquant_tables.py","file_name":"read_maxquant_tables.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"309977280","text":"from secrets import Oauth_Secrets\nimport tweepy\nfrom textblob import TextBlob\n\n\ndef getdata(input_hashtag):\n\n # input_hashtag = 'obama'\n secrets = Oauth_Secrets()\n auth = tweepy.OAuthHandler(secrets.consumer_key, secrets.consumer_secret)\n auth.set_access_token(secrets.access_token, secrets.access_token_secret)\n\n api = tweepy.API(auth)\n\n N = 100 # number of tweets\n # Tweets = api.user_timeline(id=input_hashtag, count=N)\n Tweets = tweepy.Cursor(api.search, q=input_hashtag,\n lang=\"en\").items(N)\n # Tweets = api.geo_search(query='Kenya', granularity=\"country\")\n # print(Tweets.text[0])\n negative = 0.0\n positive = 0.0\n negative_count = 0\n neutral_count = 0\n postive_count = 0\n tweets_pos = []\n tweets_neg = []\n tweets_nut = []\n general_location = []\n time_negative = {}\n time_neutral = {}\n time_positive = {}\n # if len(Tweets) < 1:\n # print(\"no tweets for now\")\n # else:\n # print(Tweets)\n for tweet in Tweets:\n # print(tweet.created_at)\n # print(tweet.user.location)\n # print(\"placeid:%s\" % tweet)\n # print(tweet.id_str, tweet.coordinates, tweet.geo, tweet.geocode)\n # print(tweet.place.country)\n general_location.append(tweet.user.location)\n blob = TextBlob(tweet.text)\n if blob.sentiment.polarity < 0:\n negative += blob.sentiment.polarity\n negative_count += 1\n tweets_neg.append(tweet.text)\n time_negative[tweet.created_at] = tweet.text\n elif blob.sentiment.polarity == 0:\n neutral_count += 1\n tweets_nut.append(tweet.text)\n time_neutral[tweet.created_at] = tweet.text\n else:\n positive += blob.sentiment.polarity\n postive_count += 1\n tweets_pos.append(tweet.text)\n time_positive[tweet.created_at] = tweet.text\n\n # post = (\"Positive \", float(postive_count/N)*100, \"%\")\n\n data = {\n 'Sample': N,\n 'Topic': input_hashtag,\n 'Positive': postive_count,\n 'Neutral': neutral_count,\n 'Negative': negative_count,\n 'Nagative_tweets': tweets_neg,\n 'Neutral_tweets': tweets_nut,\n 'Postive_tweets': tweets_pos,\n 'general_location': general_location,\n 'time_negative': time_negative,\n 'time_neutral': time_neutral,\n 'time_positive': time_positive\n\n }\n # print(post)\n # print(data)\n\n return data\n # return [['Sentiment', 'number of tweets'], ['Positive', postive_count],\n # ['Neutral', neutral_count], ['Negative', negative_count]]\n","sub_path":"twitter/apicall.py","file_name":"apicall.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"96689196","text":"from tests.base import BaseTestCase\nfrom nose.plugins.attrib import attr\n\nfrom shiftcontent.item import Item\nfrom shiftcontent import exceptions as x\nfrom datetime import datetime\nfrom uuid import uuid1\nimport json\nfrom pprint import pprint as pp\n\n\n@attr('item')\nclass ItemTest(BaseTestCase):\n\n def test_instantiating_item(self):\n \"\"\" Instantiating item \"\"\"\n item = Item()\n self.assertIsInstance(item, Item)\n\n def test_can_access_field_types(self):\n \"\"\" Content item has access to field types \"\"\"\n item = Item()\n types = item.field_types\n self.assertTrue(type(types) is dict)\n\n def test_getting_printable_representation_of_item(self):\n \"\"\" Getting printable representation of an item \"\"\"\n item = Item()\n repr = item.__repr__()\n self.assertIn(' pivot:\n bigger.append(n)\n elif n == pivot:\n equal.append(n)\n else:\n smaller.append(n)\n # Check if Equal sequence contains mth element of list\n if len(smaller) < m and len(smaller)+len(equal)>=m:\n return equal[0] # Since all elements in equal list are the same, we can return any element\n\n# Generate random list of numbers from 1 to 20 of n size\nnumbers = []\nfor i in range(n):\n numbers.append(randint(1, 20))\n\nprint()\nprint('Generated numbers: ', numbers)\nprint(m,'th smallest number: ',QuickSort(numbers, m))","sub_path":"Advanced/A08.py","file_name":"A08.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"231102734","text":"from os import getenv\n\nfrom web3 import Web3\n\nfrom compile_functions import compile_with_output_file, get_abi_and_bytecode\n\n\ndef deploy():\n compiled_sol = compile_with_output_file(\"SimpleStorage\", \"0.6.0\")\n abi, bytecode = get_abi_and_bytecode(compiled_sol)\n\n # Connection info\n w3 = Web3(Web3.HTTPProvider(getenv(\"HTTP_PROVIDER\")))\n chain_id = getenv(\"CHAIN_ID\")\n my_address = getenv(\"MY_ADDRESS\")\n private_key = getenv(\"PRIVATE_KEY\")\n\n # Create contract\n SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)\n # Get nonce from latest transaction count\n nonce = w3.eth.getTransactionCount(my_address)\n # Build -> Sign -> Send transaction\n transaction = SimpleStorage.constructor().buildTransaction(\n {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce}\n )\n signed_transaction = w3.eth.account.sign_transaction(\n transaction, private_key=private_key\n )\n\n print(\"Depoying Contract...\")\n transaction_hash = w3.eth.send_raw_transaction(signed_transaction.rawTransaction)\n transaction_receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)\n print(\"Deployed!\")\n\n # Working with the contract -> Contract Address / Contract ABI\n simple_storage = w3.eth.contract(\n address=transaction_receipt.contractAddress, abi=abi\n )\n\n # Interaction -> Call / Transaction\n\n print(f\"Value of favouriteNumber: {simple_storage.functions.retrieve().call()}\")\n print(\"Contract Transaction Initiating...\")\n store_transaction = simple_storage.functions.store(15).buildTransaction(\n {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce + 1}\n )\n signed_store_transaction = w3.eth.account.sign_transaction(\n store_transaction, private_key=private_key\n )\n store_transaction_hash = w3.eth.send_raw_transaction(\n signed_store_transaction.rawTransaction\n )\n store_transaction_receipt = w3.eth.wait_for_transaction_receipt(\n store_transaction_hash\n )\n print(\"Contract Transaction Complete!\")\n\n print(f\"Value of favouriteNumber: {simple_storage.functions.retrieve().call()}\")\n","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"435316789","text":"\"\"\"\nPlot gaussian distributions of the upper and lower relative standard deviation around 1.0\n\"\"\"\nfrom make_latex_table import get_sigma_from_table\nimport numpy as np\nimport matplotlib.pyplot as pl\n\ndef plot_gaussians(fig_object, loa_means, loa_sigmas, loa_labels, x_array):\n ax = fig_object.gca()\n ax.grid(True)\n gauss = lambda x, x0, sigma: np.exp(-((x-x0)/sigma)**2)\n for mean, sigma, label in zip(loa_means, loa_sigmas, loa_labels):\n y_array = gauss(x_array, mean, sigma)\n ax.plot(x_array, y_array, label=label)\n return fig_object\n\nif __name__ == '__main__':\n #get all sigma values\n doa_sigmas = get_sigma_from_table(\"arnould_table_modified.dat\")\n x_array = np.linspace(0,2,1001)\n #repeat for each isotope\n for isotope_tuple in doa_sigmas[\"tuple-list\"]:\n iso, sigma_lower, sigma_upper = isotope_tuple\n sigma_lower = abs(sigma_lower)\n sigma_mean = 0.5*(sigma_lower + sigma_upper)\n loa_sigmas = [sigma_lower, sigma_mean, sigma_upper]\n loa_labels = [r\"$\\sigma_{lower}$\", r\"$\\bar{\\sigma}$\", r\"$\\sigma_{upper}$\"]\n loa_means = [1.0 for i in range(len(loa_sigmas))]\n fig_object = plot_gaussians(fig_object=pl.figure(), loa_means=loa_means,\n loa_sigmas=loa_sigmas, loa_labels=loa_labels,\n x_array=x_array)\n fig_object.suptitle(iso.capitalize())\n fig_object.legend(numpoints=1,bbox_to_anchor=(0.9,0.9), loc='upper right')\n fig_object.savefig(\"arnould_plots/isotope_gaussian_%s.png\"%iso)\n fig_object.show()\n #print(iso)\n","sub_path":"latex/thesis/other_data/plot_uncertainty_arnould.py","file_name":"plot_uncertainty_arnould.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"278202642","text":"import csv\nfrom subprocess import call\nfrom datetime import datetime\nimport os\n\n\nclass Cell:\n def __init__(self, enb_name, cell_number):\n self.enb_name = enb_name\n self.number = cell_number\n self.normal = None\n self.semi = None\n self.abnormal = None\n self.total = None\n self.rate = None\n\n def __repr__(self):\n return 'enb:{},cell_num:{},normal:{},semi:{},abnormal:{},toal:{}'.format(\n self.enb_name, self.number, self.normal, self.semi, self.abnormal, self.total)\n\n\nclass EnbNode:\n def __init__(self, enb_name, start_index):\n self.name = enb_name\n self.start_index = start_index\n self.end_index = None\n self.cell_numbers = []\n self.cells = []\n\n def __repr__(self):\n return '{} ({}, {})'.format(self.name, self.start_index, self.end_index)\n\n def get_cell_numbers(self, cell_data):\n for index in range(self.start_index, self.end_index + 1):\n self.cell_numbers.append(cell_data[index])\n\n def get_cell_data(self, normal_data, semi_data, abnormal_data, total_data):\n index_list = list(range(self.start_index, self.end_index + 1))\n for cell_num, index in zip(self.cell_numbers, index_list):\n cell = Cell(self.name, cell_num)\n cell.normal = int(normal_data[index])\n cell.semi = int(semi_data[index])\n cell.abnormal = int(abnormal_data[index])\n cell.total = int(total_data[index])\n if cell.total != 0:\n cell.rate = round(cell.normal / cell.total * 100)\n else:\n cell.rate = 0\n self.cells.append(cell)\n\n\ndef clear_and_print(text):\n call('cls', shell=True)\n print(text)\n\n\ndef make_enb_list(crr_file):\n global index\n enb_name_data = []\n enb_cell_data = []\n enb_normal_data = []\n enb_semi_data = []\n enb_abnormal_data = []\n enb_total_data = []\n\n with open(crr_file, encoding='utf8') as crr_fh:\n csv_reader = csv.reader(crr_fh)\n\n for index, line in enumerate(csv_reader):\n if line:\n if index == 7:\n enb_name_data = line\n elif index == 8:\n enb_cell_data = line\n elif line[0] == 'Normal Count':\n enb_normal_data = line\n elif line[0] == 'Abnormal Count':\n enb_abnormal_data = line\n elif line[0] == 'Semi Count':\n enb_semi_data = line\n elif line[0] == 'Total':\n enb_total_data = line\n\n enb = None\n enb_list = []\n\n for index, item in enumerate(enb_name_data):\n if item:\n if enb:\n enb.end_index = index - 1\n enb_list.append(enb)\n enb = EnbNode(item, index)\n else:\n enb = EnbNode(item, index)\n\n enb.end_index = index\n enb_list.append(enb)\n\n for enb in enb_list:\n enb.get_cell_numbers(enb_cell_data)\n enb.get_cell_data(enb_normal_data, enb_semi_data, enb_abnormal_data, enb_total_data)\n\n return enb_list\n\n\ninner_div = '-' * 100\ninner_div_short = '-' * 100\nconsole_div = '=' * 50\nthreshold = 2\n\nwhile True:\n current_time = datetime.now()\n result_file = 'Compare_CRR_Result_{}.txt'.format(current_time.strftime('%Y%m%d_%H%M%S'))\n zero_result_file = 'Zero_Call_Result_{}.csv'.format(current_time.strftime('%Y%m%d_%H%M%S'))\n log_dir = os.path.abspath('logs')\n\n call('cls', shell=True)\n while True:\n # before_file = input('Enter the file path for the CRR file before work:\\n')\n before_file = r\"D:\\Dev\\Projects\\rakuten_cro\\logs\\test_20191004\\E03_CallReleaseReason_191003_0915.csv\"\n\n if os.path.isfile(before_file):\n break\n else:\n text = '[ERROR] {} is not a valid file path.'.format(before_file)\n clear_and_print(text)\n\n while True:\n # after_file = input('\\nEnter the file path for the CRR file after work:\\n')\n after_file = r\"D:\\Dev\\Projects\\rakuten_cro\\logs\\test_20191004\\E03_CallReleaseReason_191004_0915.csv\"\n\n if os.path.isfile(after_file):\n break\n else:\n text = '[ERROR] {} is not a valid file path.'.format(after_file)\n clear_and_print(text)\n\n while True:\n # zero_call_file = input('\\nEnter the file path for the zero call file:\\n')\n zero_call_file = r\"D:\\Dev\\Projects\\rakuten_cro\\logs\\test_20191004\\result_count_K01_.csv\"\n\n if os.path.isfile(after_file):\n break\n else:\n text = '[ERROR] {} is not a valid file path.'.format(zero_call_file)\n clear_and_print(text)\n\n while True:\n user_threshold = input('\\nEnter call threshold: [default: 2]\\n')\n\n if not user_threshold:\n break\n elif not user_threshold.isdigit():\n text = '[ERROR] {} is a number.'.format(zero_call_file)\n clear_and_print(text)\n else:\n threshold = int(user_threshold)\n break\n\n # Create log directory if not exists\n try:\n if not os.path.exists('logs'):\n os.makedirs('logs')\n except Exception as e:\n print('Failed to create log directory.')\n\n if os.path.exists(log_dir):\n result_file = os.path.join(log_dir, result_file)\n zero_result_file = os.path.join(log_dir, zero_result_file)\n else:\n result_file = os.path.abspath(result_file)\n zero_result_file = os.path.abspath(zero_result_file)\n\n text = \"\"\"Before File: {before}\nAfter File: {after}\nResult File: {result}\nZero Result File: {zero_result}\nCall Threshold: {threshold}\"\"\".format(\n before=before_file,\n after=after_file,\n result=result_file,\n zero_result=zero_result_file,\n threshold=threshold\n )\n\n clear_and_print(text)\n\n before_enb_list = make_enb_list(before_file)\n after_enb_list = make_enb_list(after_file)\n\n description_text = \"\"\"{inner_div}\nDESCRIPTIONS\n{inner_div}\nTIMESTAMP: {timestamp}\nCRR BEFORE: {before_file}\nCRR AFTER: {after_file}\nCALL THRESHOLD: {threshold}\\n\"\"\".format(\n inner_div=inner_div,\n timestamp=current_time.strftime('%Y-%m-%d %H:%M:%S'),\n before_file=before_file,\n after_file=after_file,\n threshold=threshold\n )\n\n result_header_text = \"\"\"\\n\\n{inner_div}\nRESULTS\n{inner_div}\\n\"\"\".format(\n inner_div=inner_div\n )\n\n header_line = 'cNum Rate_Before / Rate_After Call_Before / Call_After\\n'\n result_line = '{cell_num:<4} {rate:24} ' \\\n 'N:{b_n} A:{b_a} S:{b_s} T:{b_t} / N:{a_n} A:{a_a} S:{a_s} T:{a_t}\\n'\n\n zero_call_cell_list = []\n\n with open(result_file, 'w', encoding='utf8') as result_fh:\n result_text = ''\n result_fh.write(description_text)\n result_fh.write(result_header_text)\n\n for before, after in zip(before_enb_list, after_enb_list):\n has_zero = False\n for cell in after.cells:\n if cell.total <= threshold:\n has_zero = True\n\n if has_zero:\n result_fh.write('- {}\\n'.format(before.name))\n result_fh.write(header_line)\n for before_cell, after_cell in zip(before.cells, after.cells):\n if after_cell.total <= threshold:\n result_fh.write(result_line.format(\n cell_num=before_cell.number,\n rate='{} / {}'.format(before_cell.rate, after_cell.rate),\n b_n=before_cell.normal,\n b_a=before_cell.abnormal,\n b_s=before_cell.semi,\n b_t=before_cell.total,\n a_n=after_cell.normal,\n a_a=after_cell.abnormal,\n a_s=after_cell.semi,\n a_t=after_cell.total,\n ))\n zero_call_cell_list.append(after_cell)\n\n result_fh.write('\\n')\n\n with open(zero_result_file, 'w', encoding='utf8', newline='') as result_fh:\n csv_writer = csv.writer(result_fh)\n with open(zero_call_file, encoding='utf8') as zero_fh:\n csv_reader = csv.reader(zero_fh)\n\n for index, line in enumerate(csv_reader):\n if index in [0, 1]:\n csv_writer.writerow(line)\n continue\n enb_name = line[2]\n cell_num = line[3]\n\n for cell in zero_call_cell_list:\n if enb_name == cell.enb_name and cell_num == cell.number:\n csv_writer.writerow(line)\n\n os.startfile(result_file)\n os.startfile(zero_result_file)\n\n run_again = False\n\n while True:\n answer = input('\\nDo you want to run again for diffrent files? (Y/N): ')\n\n if answer in ['Y', 'y', 'yes', 'Yes', 'YES']:\n run_again = True\n break\n elif answer in ['N', 'n', 'no', 'No', 'NO']:\n run_again = False\n break\n else:\n print('{} is not a valid answer...'.format(answer))\n\n if not run_again:\n break\n","sub_path":"zero_calls/zero_calls.py","file_name":"zero_calls.py","file_ext":"py","file_size_in_byte":9259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"351495746","text":"#!/usr/bin/env python3\nfrom ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D\nfrom ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor\nfrom ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4\nimport xml.etree.ElementTree as ET\nimport threading\nimport time\nfrom sys import stderr\n\ngyro = GyroSensor(INPUT_1)\nsteering_drive = MoveSteering(OUTPUT_B, OUTPUT_C)\nlargeMotor_Left= LargeMotor(OUTPUT_B)\nlargeMotor_Right= LargeMotor(OUTPUT_C)\ncolourLeft = ColorSensor(INPUT_3)\ncolourRight = ColorSensor(INPUT_2)\n\ntank_block = MoveTank(OUTPUT_B, OUTPUT_C)\n#_________________________________________________________________________________________________________________________________\ndef StraightGyro_target_toLine(stop, speed, rotations, target, whiteOrBlack):\n\n print(\"In StraightGyro_target_toLine\", file=stderr)\n current_degrees = largeMotor_Left.position \n rotations = rotations * 360\n target_rotations= current_degrees + rotations\n current_gyro_reading = gyro.angle\n # print(\"Current Gyro Reading: {}\"(current_gyro_reading))\n\n while float(current_degrees) < target_rotations:\n if stop(): \n break\n current_gyro_reading = gyro.angle\n current_degrees = largeMotor_Left.position\n\n if current_gyro_reading < target: # If gyro reading is smaller than target reaading turn Right\n correction = target - current_gyro_reading # calculate the correction by the target - current\n correction = correction * .25 #turns by the corrrection\n steering_drive.on(steering = -correction , speed = speed)\n\n\n if current_gyro_reading > target: # If gyro reading is larger than target reAading turn Left\n correction = target - current_gyro_reading # calculate the correction by the target - current\n correction = correction * .25 #turns by the corrrection\n steering_drive.on(steering = -correction , speed = speed)\n\n # if the gyro is = to target just continue straight\n if current_gyro_reading == target:\n steering_drive.on(steering = 0 , speed = speed)\n\n #if the current rotations is larger than target quit out of code\n if float(current_degrees) >= target_rotations:\n break\n\n if stop():\n break\n \n\n # Now find the line\n \n if not stop(): # if the key has not been taken out of the slot\n while True:\n if stop(): \n break\n # reading in the colour values (RLI)\n currentRight_RLI = colourRight.reflected_light_intensity\n currentLeft_RLI = colourLeft.reflected_light_intensity\n\n # if the whiteOrBlack paramater is white then:\n if whiteOrBlack == \"WHITE\":\n if currentRight_RLI > 90 or currentLeft_RLI > 90: #if the left or right sensor read over 90 then stop the robot (done by breaking out of the loop)\n break\n\n if whiteOrBlack == \"BLACK\":\n if currentRight_RLI < 10 or currentLeft_RLI < 10:#if the left or right sensor read under 10 then stop the robot (done by breaking out of the loop)\n break\n \n #otherwise continue straight BUT go slower so the colours are easier to detect\n steering_drive.on(steering = 0 , speed = speed / 2) \n\n\n tank_block.off()\n print('Leaving StraightGyro_target_toLine', file=stderr)\n\n#stopProcessing=False\n#StraightGyro_target_toLine(lambda:stopProcessing, speed=30, rotations=3, target=45, whiteOrBlack=\"WHITE\")","sub_path":"functions/StraightGyro_target_toLine.py","file_name":"StraightGyro_target_toLine.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"623908596","text":"import sys\r\n\r\nif len(sys.argv) > 1:\r\n from PIL import Image\r\n import imgreco\r\n obj = imgreco\r\n objname = '.'.join(sys.argv[1:-1])\r\n for k in sys.argv[1:-1]:\r\n obj = getattr(obj, k)\r\n print('> imgreco.%s(Image.open(%s))' % (objname, repr(sys.argv[-1])))\r\n print(obj(Image.open(sys.argv[-1])))\r\nelse:\r\n print('usage: python -m imgreco module_name function_name image_file')\r\n","sub_path":"imgreco/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"252278916","text":"#!/usr/bin/env python3\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nimport multipart\nfrom io import BytesIO\nimport threading\n\nimport prompt_toolkit\nfrom prompt_toolkit import PromptSession\nfrom prompt_toolkit.patch_stdout import patch_stdout\n\nport = 80\naddress = \"0.0.0.0\"\ntasks = []\nsep = \"\\n\"\n\nclass C2(BaseHTTPRequestHandler):\n # Helper function to send data back to client\n def reply(self, data):\n self.send_response(200)\n self.send_header('Content-Length', len(data))\n self.end_headers()\n self.wfile.write(data)\n\n # Handle HTTP GET requests\n def do_GET(self):\n global tasks\n client = self.client_address[0]\n num_cmds = len(tasks)\n cmd_str = sep.join(tasks).encode()\n self.reply(cmd_str)\n if num_cmds > 0:\n print(\"{} Commands sent to {}\".format(num_cmds, client))\n tasks = []\n\n # Handle HTTP POST requests\n def do_POST(self):\n try:\n content_length = int(self.headers['Content-Length'])\n body = self.rfile.read(content_length)\n stream = BytesIO(body)\n boundary = stream.readline()\n boundary = boundary.strip(b\"\\r\\n\")[2:]\n stream.seek(0)\n parser = multipart.MultipartParser(stream, boundary)\n \n for part in parser:\n res = part.file.read().decode()\n if res:\n print(res)\n except Exception as e:\n print(e)\n\n # Stop log messages from printing to the screen\n def log_message(self, format, *args):\n return\n\nhttpd = HTTPServer((address, port), C2)\nsrv_thread = threading.Thread(target=httpd.serve_forever, args=())\nsrv_thread.daemon = True\nsrv_thread.start()\nprint(\"HTTP Server running on port {}\".format(port))\n\nsession = PromptSession()\nwhile True:\n try:\n with patch_stdout():\n cmd = session.prompt(\">\")\n if cmd:\n tasks.append(cmd)\n print(\"Command queued\")\n except Exception as e:\n print(e)\n","sub_path":"handle_http_min.py","file_name":"handle_http_min.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"248021967","text":"\"\"\"\nphone data into elastic for supported file extensions.\nnote: we truncate outbound documents to DOC_SIZE_LIMIT characters\n(to bound memory pressure and request size to elastic)\n\"\"\"\n\nfrom datetime import datetime\nfrom math import floor\nimport json\nimport os\nfrom urllib.parse import unquote, unquote_plus\n\nfrom aws_requests_auth.aws_auth import AWSRequestsAuth\nimport boto3\nimport botocore\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\nfrom elasticsearch.helpers import bulk\nimport nbformat\nfrom tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential\n\nCONTENT_INDEX_EXTS = [\n \".csv\",\n \".html\",\n \".htm\",\n \".ipynb\",\n \".json\",\n \".md\",\n \".rmd\",\n \".tsv\",\n \".txt\",\n \".xml\"\n]\n# 10 MB, see https://amzn.to/2xJpngN\nCHUNK_LIMIT_BYTES = 20_000_000\nDOC_LIMIT_BYTES = 2_000\nELASTIC_TIMEOUT = 30\nMAX_RETRY = 4 # prevent long-running lambdas due to malformed calls\nNB_VERSION = 4 # default notebook version for nbformat\n# signifies that the object is truly deleted, not to be confused with\n# s3:ObjectRemoved:DeleteMarkerCreated, which we may see in versioned buckets\n# see https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html\nOBJECT_DELETE = \"ObjectRemoved:Delete\"\nQUEUE_LIMIT_BYTES = 100_000_000# 100MB\nRETRY_429 = 5\nTEST_EVENT = \"s3:TestEvent\"\n# we need to filter out GetObject and HeadObject calls generated by the present\n# lambda in order to display accurate analytics in the Quilt catalog\n# a custom user agent enables said filtration\nUSER_AGENT_EXTRA = \" quilt3-lambdas-es-indexer\"\n\ndef bulk_send(elastic, list_):\n \"\"\"make a bulk() call to elastic\"\"\"\n return bulk(\n elastic,\n list_,\n # Some magic numbers to reduce memory pressure\n # e.g. see https://github.com/wagtail/wagtail/issues/4554\n chunk_size=100,# max number of documents sent in one chunk\n # The stated default is max_chunk_bytes=10485760, but with default\n # ES will still return an exception stating that the very\n # same request size limit has been exceeded\n max_chunk_bytes=CHUNK_LIMIT_BYTES,\n # number of retries for 429 (too many requests only)\n # all other errors handled by our code\n max_retries=RETRY_429,\n # we'll process errors on our own\n raise_on_error=False,\n raise_on_exception=False\n )\n\nclass DocumentQueue:\n \"\"\"transient in-memory queue for documents to be indexed\"\"\"\n def __init__(self, context):\n \"\"\"constructor\"\"\"\n self.queue = []\n self.size = 0\n self.context = context\n\n def append(\n self,\n event_type,\n size=0,\n meta=None,\n *,\n last_modified,\n bucket,\n ext,\n key,\n text,\n etag,\n version_id\n ):\n \"\"\"format event as a document and then queue the document\"\"\"\n derived_meta = transform_meta(meta or {})\n # On types and fields, see\n # https://www.elastic.co/guide/en/elasticsearch/reference/master/mapping.html\n body = {\n # Elastic native keys\n \"_id\": f\"{key}:{version_id}\",\n \"_index\": bucket,\n # index will upsert (and clobber existing equivalent _ids)\n \"_op_type\": \"delete\" if event_type == OBJECT_DELETE else \"index\",\n \"_type\": \"_doc\",\n # Quilt keys\n # Be VERY CAREFUL changing these values, as a type change can cause a\n # mapper_parsing_exception that below code won't handle\n \"comment\": derived_meta[\"comment\"],\n \"content\": text,# field for full-text search\n \"etag\": etag,\n \"event\": event_type,\n \"ext\": ext,\n \"key\": key,\n #\"key_text\": created by mappings copy_to\n \"last_modified\": last_modified.isoformat(),\n \"meta_text\": derived_meta[\"meta_text\"],\n \"size\": size,\n \"system_meta\": derived_meta[\"system_meta\"],\n \"target\": derived_meta[\"target\"],\n \"updated\": datetime.utcnow().isoformat(),\n \"user_meta\": derived_meta[\"user_meta\"],\n \"version_id\": version_id\n }\n\n self.append_document(body)\n\n if self.size >= QUEUE_LIMIT_BYTES:\n self.send_all()\n\n def append_document(self, doc):\n \"\"\"append well-formed documents (used for retry or by append())\"\"\"\n if doc[\"content\"]:\n # document text dominates memory footprint; OK to neglect the\n # small fixed size for the JSON metadata\n self.size += min(doc[\"size\"], DOC_LIMIT_BYTES)\n self.queue.append(doc)\n\n def send_all(self):\n \"\"\"flush self.queue in 1-2 bulk calls\"\"\"\n if not self.queue:\n return\n elastic_host = os.environ[\"ES_HOST\"]\n session = boto3.session.Session()\n credentials = session.get_credentials().get_frozen_credentials()\n awsauth = AWSRequestsAuth(\n # These environment variables are automatically set by Lambda\n aws_access_key=credentials.access_key,\n aws_secret_access_key=credentials.secret_key,\n aws_token=credentials.token,\n aws_host=elastic_host,\n aws_region=session.region_name,\n aws_service=\"es\"\n )\n\n elastic = Elasticsearch(\n hosts=[{\"host\": elastic_host, \"port\": 443}],\n http_auth=awsauth,\n max_backoff=get_time_remaining(self.context),\n # Give ES time to respond when under load\n timeout=ELASTIC_TIMEOUT,\n use_ssl=True,\n verify_certs=True,\n connection_class=RequestsHttpConnection\n )\n\n _, errors = bulk_send(elastic, self.queue)\n if errors:\n id_to_doc = {d[\"_id\"]: d for d in self.queue}\n send_again = []\n for error in errors:\n # only retry index call errors, not delete errors\n if \"index\" in error:\n inner = error[\"index\"]\n info = inner.get(\"error\")\n doc = id_to_doc[inner[\"_id\"]]\n # because error.error might be a string *sigh*\n if isinstance(info, dict):\n if \"mapper_parsing_exception\" in info.get(\"type\", \"\"):\n print(\"mapper_parsing_exception\", error, inner)\n # clear out structured metadata and try again\n doc[\"user_meta\"] = doc[\"system\"] = {}\n else:\n print(\"unhandled indexer error:\", error)\n # Always retry, regardless of whether we know to handle and clean the request\n # or not. This can catch temporary 403 on index write blocks and other\n # transcient issues.\n send_again.append(doc)\n else:\n # If index not in error, then retry the whole batch. Unclear what would cause\n # that, but if there's an error without an id we need to assume it applies to\n # the batch.\n send_again = self.queue\n print(\"unhandled indexer error (missing index field):\", error)\n\n # we won't retry after this (elasticsearch might retry 429s tho)\n if send_again:\n _, errors = bulk_send(elastic, send_again)\n if errors:\n raise Exception(\"Failed to load messages into Elastic on second retry.\")\n # empty the queue\n self.size = 0\n self.queue = []\n\ndef get_contents(bucket, key, ext, *, etag, version_id, s3_client, size):\n \"\"\"get the byte contents of a file\"\"\"\n content = \"\"\n if ext in CONTENT_INDEX_EXTS:\n if ext == \".ipynb\":\n content = trim_to_bytes(\n # we have no choice but to fetch the entire notebook, because we\n # are going to parse it\n # warning: huge notebooks could spike memory here\n get_notebook_cells(\n bucket,\n key,\n size,\n etag=etag,\n s3_client=s3_client,\n version_id=version_id\n )\n )\n content = trim_to_bytes(content)\n else:\n content = get_plain_text(\n bucket,\n key,\n size,\n etag=etag,\n s3_client=s3_client,\n version_id=version_id\n )\n\n return content\n\ndef extract_text(notebook_str):\n \"\"\" Extract code and markdown\n Args:\n * nb - notebook as a string\n Returns:\n * str - select code and markdown source (and outputs)\n Pre:\n * notebook is well-formed per notebook version 4\n * \"cell_type\" is defined for all cells\n * \"source\" defined for all \"code\" and \"markdown\" cells\n Throws:\n * Anything nbformat.reads() can throw :( which is diverse and poorly\n documented, hence the `except Exception` in handler()\n Notes:\n * Deliberately decided not to index output streams and display strings\n because they were noisy and low value\n * Tested this code against ~6400 Jupyter notebooks in\n s3://alpha-quilt-storage/tree/notebook-search/\n * Might be useful to index \"cell_type\" : \"raw\" in the future\n See also:\n * Format reference https://nbformat.readthedocs.io/en/latest/format_description.html\n \"\"\"\n formatted = nbformat.reads(notebook_str, as_version=NB_VERSION)\n text = []\n for cell in formatted.get(\"cells\", []):\n if \"source\" in cell and cell.get(\"cell_type\") in (\"code\", \"markdown\"):\n text.append(cell[\"source\"])\n\n return \"\\n\".join(text)\n\ndef get_notebook_cells(bucket, key, size, *, etag, s3_client, version_id):\n \"\"\"extract cells for ipynb notebooks for indexing\"\"\"\n text = \"\"\n try:\n obj = retry_s3(\n \"get\",\n bucket,\n key,\n size,\n etag=etag,\n s3_client=s3_client,\n version_id=version_id\n )\n notebook = obj[\"Body\"].read().decode(\"utf-8\")\n text = extract_text(notebook)\n except UnicodeDecodeError as uni:\n print(f\"Unicode decode error in {key}: {uni}\")\n except (json.JSONDecodeError, nbformat.reader.NotJSONError):\n print(f\"Invalid JSON in {key}.\")\n except (KeyError, AttributeError) as err:\n print(f\"Missing key in {key}: {err}\")\n # there might be more errors than covered by test_read_notebook\n # better not to fail altogether\n except Exception as exc:#pylint: disable=broad-except\n print(f\"Exception in file {key}: {exc}\")\n\n return text\n\ndef get_plain_text(bucket, key, size, *, etag, s3_client, version_id):\n \"\"\"get plain text object contents\"\"\"\n text = \"\"\n try:\n obj = retry_s3(\n \"get\",\n bucket,\n key,\n size,\n etag=etag,\n s3_client=s3_client,\n limit=DOC_LIMIT_BYTES,\n version_id=version_id\n )\n # ignore because limit might break a long character midstream\n text = obj[\"Body\"].read().decode(\"utf-8\", \"ignore\")\n except UnicodeDecodeError as ex:\n print(f\"Unicode decode error in {key}\", ex)\n\n return text\n\ndef get_time_remaining(context):\n \"\"\"returns time remaining in seconds before lambda context is shut down\"\"\"\n time_remaining = floor(context.get_remaining_time_in_millis()/1000)\n if time_remaining < 30:\n print(\n f\"Warning: Lambda function has less than {time_remaining} seconds.\"\n \" Consider reducing bulk batch size.\"\n )\n\n return time_remaining\n\ndef make_s3_client():\n \"\"\"make a client with a custom user agent string so that we can\n filter the present lambda's requests to S3 from object analytics\"\"\"\n configuration = botocore.config.Config(user_agent_extra=USER_AGENT_EXTRA)\n return boto3.client(\"s3\", config=configuration)\n\ndef transform_meta(meta):\n \"\"\" Reshapes metadata for indexing in ES \"\"\"\n helium = meta.get(\"helium\", {})\n user_meta = helium.pop(\"user_meta\", {}) or {}\n comment = helium.pop(\"comment\", \"\") or \"\"\n target = helium.pop(\"target\", \"\") or \"\"\n\n meta_text_parts = [comment, target]\n\n if helium:\n meta_text_parts.append(json.dumps(helium))\n if user_meta:\n meta_text_parts.append(json.dumps(user_meta))\n\n return {\n \"system_meta\": helium,\n \"user_meta\": user_meta,\n \"comment\": comment,\n \"target\": target,\n \"meta_text\": \" \".join(meta_text_parts)\n }\n\ndef handler(event, context):\n \"\"\"enumerate S3 keys in event, extract relevant data and metadata,\n queue events, send to elastic via bulk() API\n \"\"\"\n # message is a proper SQS message, which either contains a single event\n # (from the bucket notification system) or batch-many events as determined\n # by enterprise/**/bulk_loader.py\n for message in event[\"Records\"]:\n body = json.loads(message[\"body\"])\n body_message = json.loads(body[\"Message\"])\n if \"Records\" not in body_message:\n if body_message.get(\"Event\") == TEST_EVENT:\n # Consume and ignore this event, which is an initial message from\n # SQS; see https://forums.aws.amazon.com/thread.jspa?threadID=84331\n continue\n else:\n print(\"Unexpected message['body']. No 'Records' key.\", message)\n raise Exception(\"Unexpected message['body']. No 'Records' key.\")\n batch_processor = DocumentQueue(context)\n events = body_message.get(\"Records\", [])\n s3_client = make_s3_client()\n # event is a single S3 event\n for event_ in events:\n try:\n event_name = event_[\"eventName\"]\n bucket = unquote(event_[\"s3\"][\"bucket\"][\"name\"])\n # In the grand tradition of IE6, S3 events turn spaces into '+'\n key = unquote_plus(event_[\"s3\"][\"object\"][\"key\"])\n version_id = event_[\"s3\"][\"object\"].get(\"versionId\")\n version_id = unquote(version_id) if version_id else None\n etag = unquote(event_[\"s3\"][\"object\"][\"eTag\"])\n _, ext = os.path.splitext(key)\n ext = ext.lower()\n\n head = retry_s3(\n \"head\",\n bucket,\n key,\n s3_client=s3_client,\n version_id=version_id,\n etag=etag\n )\n\n size = head[\"ContentLength\"]\n last_modified = head[\"LastModified\"]\n meta = head[\"Metadata\"]\n text = \"\"\n\n if event_name == OBJECT_DELETE:\n batch_processor.append(\n event_name,\n bucket=bucket,\n ext=ext,\n etag=etag,\n key=key,\n last_modified=last_modified,\n text=text,\n version_id=version_id\n )\n continue\n\n _, ext = os.path.splitext(key)\n ext = ext.lower()\n text = get_contents(\n bucket,\n key,\n ext,\n etag=etag,\n version_id=version_id,\n s3_client=s3_client,\n size=size\n )\n # decode Quilt-specific metadata\n if meta and \"helium\" in meta:\n try:\n decoded_helium = json.loads(meta[\"helium\"])\n meta[\"helium\"] = decoded_helium or {}\n except (KeyError, json.JSONDecodeError):\n print(\"Unable to parse Quilt 'helium' metadata\", meta)\n\n batch_processor.append(\n event_name,\n bucket=bucket,\n key=key,\n ext=ext,\n meta=meta,\n etag=etag,\n version_id=version_id,\n last_modified=last_modified,\n size=size,\n text=text\n )\n except Exception as exc:# pylint: disable=broad-except\n print(\"Fatal exception for record\", event_, exc)\n import traceback\n traceback.print_tb(exc.__traceback__)\n raise exc\n # flush the queue\n batch_processor.send_all()\n\ndef retry_s3(\n operation,\n bucket,\n key,\n size=None,\n limit=None,\n *,\n etag,\n version_id,\n s3_client\n):\n \"\"\"retry head or get operation to S3 with; stop before we run out of time.\n retry is necessary since, due to eventual consistency, we may not\n always get the required version of the object.\n \"\"\"\n if operation == \"head\":\n function_ = s3_client.head_object\n elif operation == \"get\":\n function_ = s3_client.get_object\n else:\n raise ValueError(f\"unexpected operation: {operation}\")\n # Keyword arguments to function_\n arguments = {\n \"Bucket\": bucket,\n \"Key\": key\n }\n if operation == 'get' and size:\n # can only request range if file is not empty\n arguments['Range'] = f\"bytes=0-{limit}\"\n if version_id:\n arguments['VersionId'] = version_id\n else:\n arguments['IfMatch'] = etag\n\n def not_known_exception(exception):\n error_code = exception.response.get('Error', {}).get('HTTPStatusCode', 218)\n return error_code not in [\"402\", \"403\", \"404\"]\n\n @retry(\n # debug\n reraise=True,\n stop=stop_after_attempt(MAX_RETRY),\n wait=wait_exponential(multiplier=2, min=4, max=30),\n retry=(retry_if_exception(not_known_exception))\n )\n def call():\n \"\"\"local function so we can set stop_after_delay dynamically\"\"\"\n # TODO: remove all this, stop_after_delay is not dynamically loaded anymore\n return function_(**arguments)\n\n return call()\n\ndef trim_to_bytes(string, limit=DOC_LIMIT_BYTES):\n \"\"\"trim string to specified number of bytes\"\"\"\n encoded = string.encode(\"utf-8\")\n size = len(encoded)\n if size <= limit:\n return string\n return encoded[:limit].decode(\"utf-8\", \"ignore\")\n","sub_path":"lambdas/es/indexer/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":18628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"570420099","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 3 20:19:58 2017\n\n@author: Ashlyn_Zhao\n\nutils for training set and test set\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\ndef get_unscaled_full_data(df_result, X_col_name, y_col_name):\n X = df_result[X_col_name]\n y = df_result[y_col_name]\n return X, y\n\ndef get_scaled_data(X,y):\n X_scaled = preprocessing.scale(X) # zero mean and unit variance\n X_scaled = pd.DataFrame(X_scaled)\n return X_scaled, y\n\ndef get_last_index_for_consecutive_sequence(sequence):\n tmp = np.where(sequence[:-1] != sequence[1:])[0]\n return np.append(tmp,len(sequence)-1)\n\ndef get_task_data(ticker, df_result, X_scaled, y):\n ind = np.where(df_result['ticker']==ticker)\n return X_scaled[ind], y[ind]\n\ndef get_train_test_data(df_result,X_scaled, y): \n final_year_index = get_last_index_for_consecutive_sequence(df_result['ticker'].values)\n final_year_index_bool = df_result.index.isin(final_year_index)\n X_train = X_scaled[~final_year_index_bool]\n y_train = y[~final_year_index_bool]\n X_test = X_scaled[final_year_index_bool]\n y_test = y[final_year_index_bool]\n return final_year_index, final_year_index_bool, X_train, y_train, X_test, y_test\n\ndef get_train_test_cv_data(X_train, y_train, splitter):\n train_iloc, test_iloc = next(splitter)\n xx_train = X_train.iloc[train_iloc]\n yy_train = y_train.iloc[train_iloc]\n xx_test = X_train.iloc[test_iloc]\n yy_test = y_train.iloc[test_iloc]\n return xx_train, yy_train, xx_test, yy_test\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"169120013","text":"import requests\nimport sqlite3\nimport simplejson as json\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport pandas as pd\nimport calendar\n\ncon = sqlite3.connect('C:/Users/telechips/database/tcs.db')\nuser = pd.read_sql(\"SELECT * FROM id_pw\", con)\nuser_info = user.values.tolist()\ncon.close()\n\nuserData = {'os_username': user_info[0][0], 'os_password': user_info[0][1]}\n\n'''\n#team code 참고\nRND Innovation Team : 2\nWireless Team : 3\nSOC Advanced Team : 4\nSOC Design Team : 5\nSOC Verification Team : 6\nSOC Implementation Team : 8\nSecurity Solution Team : 9\nSystem BSP Team : 10\nApplication BSP Team : 11\nSW Architecture Team : 14\nAutomotive Platform Team : 15\nDriver Assistance Platform Team : 18\nBluetooth Team : 19\nAutomotive MCU Team : 22\nHW Platform Team : 87\nHW Verification Team : 88\nMedia Android Team : 89\nMedia Linux Team : 90\nMedia HAL Team : 91\nProject Management Team : 92\nSTB Platform Team : 93\nTechnical Writing Team : 94\n'''\n#현재 년도, 월을 출력\nday = datetime.now()\nyear = day.year \nmonth = day.month\n\n#전 월을 출력\nday_before = datetime.now() - relativedelta(months=1)\nyear_1 = day_before.year #전 월의 년도\nmonth_1 = day_before.month\nday_last = calendar.monthrange(year_1,month_1)[1]\n\n\nurl1 = 'https://tcs.telechips.com:8443/rest/com.deniz.jira.worklog/1.0/timesheet/team?startDate='\nurl2 = '&endDate='\nurl3 = '&targetKey=89&extraIssueFilter=issuetype%20not%20in%20(Schedule%2C%22Meeting%20Minutes%22)'\n\ndata_resource = []\n\n# 전 월의 워크로그 data를 data_resource에 저장\nfor i in range(1, day_last+1):\n url = url1 + str(year_1) + '-' + str(month_1) + '-' + str(i) + url2 + str(year_1) + '-' + str(month_1) + '-' + str(i) + url3\n #월간 팀별 프로젝트 리소스\n data1 = requests.get(url, userData)\n data2 = json.loads(data1.text)\n for j in range(0, len(data2['projects'])):\n issue_resource = 0\n for k in range(0, len(data2['projects'][j]['issues'])):\n for l in range(0, len(data2['projects'][j]['issues'][k]['workLogs'])):\n issue_resource = issue_resource + data2['projects'][j]['issues'][k]['workLogs'][l]['timeSpent']\n a = [str(year_1) + '-' + str(month_1) + '-' + str(i),data2['projects'][j]['name']+'(' + data2['projects'][j]['key'] + ')',round(issue_resource/60/60,1)]\n data_resource.append(a)\n\n# 현재 월의 워크로그 data를 data_resource에 저장\nfor i in range(1, day.day):\n url = url1 + str(year) + '-' + str(month) + '-' + str(i) + url2 + str(year) + '-' + str(month) + '-' + str(i) + url3\n #월간 팀별 프로젝트 리소스\n data1 = requests.get(url, userData)\n data2 = json.loads(data1.text)\n for j in range(0, len(data2['projects'])):\n issue_resource = 0\n for k in range(0, len(data2['projects'][j]['issues'])):\n for l in range(0, len(data2['projects'][j]['issues'][k]['workLogs'])):\n issue_resource = issue_resource + data2['projects'][j]['issues'][k]['workLogs'][l]['timeSpent']\n a = [str(year) + '-' + str(month) + '-' + str(i),data2['projects'][j]['name']+'(' + data2['projects'][j]['key'] + ')',round(issue_resource/60/60,1)]\n data_resource.append(a)\n\ndata = pd.DataFrame(data_resource, columns = ['date','project','time'])\n\ncon = sqlite3.connect('C:/Users/telechips/database/tcs.db')\ndata.to_sql('Media Android Team', con, if_exists='replace', index = False)\ncon.close()\n","sub_path":"old_script/Media_Android_Team.py","file_name":"Media_Android_Team.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"615126939","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Functions common to test suites.\n\"\"\"\n\n\"\"\"License:\n Copyright 2020 The Cytoscape Consortium\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all copies or substantial portions\n of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom py4cytoscape import *\nimport os\nimport requests\n\n\ndef __init__(self):\n pass\n\n\ndef load_test_session(session_filename=None):\n open_session(session_filename)\n\n\ndef load_test_network(network_name, make_current=True):\n if make_current:\n imported = import_network_from_file(network_name)\n set_current_network(imported['networks'][0])\n else:\n try:\n cur_suid = get_network_suid()\n except:\n cur_suid = None\n imported = import_network_from_file(network_name)\n if cur_suid: set_current_network(cur_suid)\n return imported['networks'][0], imported['views'][0]\n\n\ndef test_select_nodes(node_list):\n if len(node_list) == 0:\n clear_selection(type='nodes')\n else:\n select_nodes(node_list, by_col='COMMON')\n\n\ndef clean_session_file(session_filename):\n if os.path.isfile(session_filename): os.remove(session_filename)\n","sub_path":"test_utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"501174577","text":"from django.conf.urls import *\nfrom gsd.student.views import view_student_listing, view_student_profile, view_student_profile_from_id, view_redirect_to_add_publication\nfrom gsd.student.views_ajax_updates import view_update_committee_members, view_update_profile_attribute\n\nurlpatterns = [\n url(r'^profile/(?P\\w{32,40})/$', view_student_profile, name='view_student_profile'),\n url(r'^profile-from-id/(?P\\d{1,10})/$', view_student_profile_from_id, name='view_student_profile_from_id'),\n url(r'^listing/$', view_student_listing, name='view_student_listing'),\n url(\n r'^add-publication/(?P\\d{1,10})$',\n view_redirect_to_add_publication,\n name='view_redirect_to_add_publication'\n )\n]\n\nurlpatterns += [\n url(r'^profile-attribute-update/(?P\\w{32,40})/$', view_update_profile_attribute, name='view_update_profile_attribute'),\n url(r'^update-committee-members/(?P\\w{32,40})/$', view_update_committee_members, name='view_update_committee_members'),\n]\n","sub_path":"gsd/student/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"284706481","text":"import requests\n\nfrom src.mercadolibre.OAuth import OAuth\nfrom src.mercadolibre.enums import paths\nfrom src.mercadolibre.enums.HttpMethods import HttpMethods\n\n\nclass Client:\n def __init__(self, access_token=None, refresh_token=None):\n self.access_token = access_token\n self.refresh_token = refresh_token\n self.method = HttpMethods.GET\n self.url = ''\n self.headers = None\n self.query_params = None\n self.request_params = None\n self.is_search = False\n self.object_name = None\n self.response_data_list = []\n\n def request(self, method=HttpMethods.GET, path=None, query_params=None, data=None):\n self.method = method\n self.url = f'{paths.BASE_URL}{path}'\n self.query_params = query_params\n self.data = data\n response = self.__submit_request()\n error = None\n tokens = None\n\n if not isinstance(response.json(), list):\n error = response.json().get('error')\n\n if (error == 'invalid_grant' or error == 'not_found') and self.access_token:\n tokens = self.__refresh_token()\n response = self.__submit_request()\n\n return response, tokens\n\n def __submit_request(self):\n self.__set_headers()\n response = requests.request(method=self.method, url=self.url, headers=self.headers, params=self.query_params,\n json=self.data)\n return response\n\n def __set_headers(self):\n if self.access_token:\n self.headers = {'Authorization': f'Bearer {self.access_token}'}\n\n def __refresh_token(self):\n response = OAuth().refresh_token(refresh_token=self.refresh_token)\n response_json = response.json()\n self.access_token = response_json.get('access_token')\n return {'access_token': self.access_token,\n 'refresh_token': response_json.get('refresh_token')}\n","sub_path":"src/mercadolibre/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"201918572","text":"# Joshua Reyling\r\n# NR 426 Final Project\r\n# This script is to be used as a tool within ArcGIS Pro at the Geospatial Centroid to process the monthly ridership logs\r\n# received from Transfort. The end result is two point feature classes used for cartography and one 'master' class that\r\n# contains all of the unprocessed data, while deleting the interim feature classes created in geoprocessing. More\r\n# details are available in the tool's readme.txt\r\n\r\n# - # Import modules and set environments # - #\r\nimport arcpy, os, sys\r\n\r\n# Set a static workspace for output. All outputs are in a specific place, so there is no need for users to map to it...\r\narcpy.env.Workspace = r'D:\\Transfort_Tool\\Transit_Analysis_Pro\\CSU_Transfort\\CSU_Transfort.gdb'\r\nbase = os.path.join(arcpy.env.Workspace, 'Base_Data',)\r\narcpy.env.overwriteOutput = False\r\n\r\n# set global variables and inputs\r\nYYYY = input('year (YYYY):') # four digit year (e.g. 2019)\r\nMM = input('month (MM):') # two digit month (e.g. 03 for March)\r\ntbl = r'E:\\Transfort_Tool\\TransfortRiderReport_Jan2019.csv' # .csv table from Transfort\r\nstops = base + '\\Stops_{}'.format(YYYY) # Bus stop class for corresponding year\r\nthies = base + '\\Thiessen_{}'.format(YYYY) # Thiessen polygon class for corresponding year stops\r\ntag = YYYY + MM\r\n\r\n# Check for correct 'tag' formatting and necessary base data.\r\nif not YYYY.isnumeric() or len(YYYY) != 4: # Check to ensure 'YYYY' is a 4 digit number. Exit tool if check fails.\r\n print('Incorrect year format. Please format year as \"YYYY\". Exiting tool')\r\n exit()\r\nelif not MM.isnumeric() or len(MM) != 2: # Check to ensure 'MM' is a 2 digit number. Exit tool if check fails.\r\n print('Incorrect month format. Please format month as \"MM\". Exiting tool.')\r\n exit()\r\nelif not arcpy.Exists(stops): # Check for existence of bus stop feature class. Exit tool if not there.\r\n print('Missing required stops file. Exiting tool.')\r\n exit()\r\nelif arcpy.Exists(stops) and not arcpy.Exists(thies): # Check existence of 'Thiessen' features. Create them if needed.\r\n print('Creating necessary Thiessen polygons...')\r\n # Create Thiessen polygons\r\n # Syntax: CreateThiessenPolygons_analysis (in_features, out_feature_class, {fields_to_copy})\r\n arcpy.CreateThiessenPolygons_analysis(stops, thies, 'ALL')\r\n\r\n# Set a label variable For academic year that splits from July to June\r\nif tag[-2:] <= '06':\r\n AY = int(tag[0:4])-1 # attributes jan- june to previous calendar year\r\nelse:\r\n AY = tag[0:4] # attributes July - December to concurrent calendar year\r\nlbl = 'Stop_Usage_{}_{}'.format(AY, int(AY)+1)\r\n\r\n# Set output dataset using academic year label\r\ndataset = os.path.join(arcpy.env.Workspace, lbl)\r\n\r\n# Check for existence of output dataset and create if needed\r\nif not arcpy.Exists(dataset):\r\n arcpy.CreateFeatureDataset_management(arcpy.env.Workspace, lbl, 4326)\r\n print('Creating feature dataset...')\r\n\r\n# Set output path for 'RAW' feature class. Use os.path.join to concatenate\r\nout_raw = os.path.join(dataset, 'UNPROCESSED_{}_{}'.format(YYYY, MM))\r\n\r\n# - # Code block for tools # - #\r\ntry:\r\n\r\n # Check for existence of 'RAW' feature class and create if needed\r\n if not arcpy.Exists(out_raw):\r\n # XY Table to Point - create a point feature class from the xy table submitted from Transfort.\r\n # Syntax: XYTableToPoint_management (in_table, out_feature_class, x_field, y_field, {z_field},\r\n # {coordinate_system})\r\n arcpy.XYTableToPoint_management(tbl, out_raw, 'LON', 'LAT', '', 4326)\r\n print(out_raw + ' has been created')\r\n\r\n # Create feature layer 'employee' and 'student' from the 'RAW' feature class\r\n # Syntax: MakeFeatureLayer_management (in_features, out_layer, {where_clause}, {workspace}, {field_info})\r\n arcpy.MakeFeatureLayer_management(out_raw, 'emp_raw', \"rider_type = 'Employee'\")\r\n arcpy.MakeFeatureLayer_management(out_raw, 'stud_raw', \"rider_type = 'Student'\")\r\n print('Feature layers have been created')\r\n\r\n # Create a list of the feature layers just created\r\n lyrlist = ['emp_raw', 'stud_raw']\r\n\r\n # Iterate through list of feature layers to run geoprocessing tools\r\n for lyr in lyrlist:\r\n\r\n out_thies = r'in_memory\\out_thies'\r\n\r\n # Create a naming convention for 'STOPS' feature classes using an if/else\r\n if lyr == 'emp_raw':\r\n label = 'Employee'\r\n else:\r\n label = 'Student'\r\n\r\n # Set output path for 'STOPS' feature classes. Use os.path.join to concatenate\r\n out_stops = os.path.join(dataset, '{}_STOPS_{}_{}'.format(label, YYYY, MM))\r\n\r\n # Check for existence of 'STOPS' feature class and create if needed\r\n if not arcpy.Exists(out_stops):\r\n # Spatial Join 1 - Count the number of riders within each Thiessen polygon.\r\n # Syntax: SpatialJoin_analysis (target_features, join_features, out_feature_class, {join_operation},\r\n # {join_type}, {field_mapping}, {match_option}, {search_radius}, {distance_field_name})\r\n # Field Mappings Syntax:\r\n # 'New_Field_Name \"New_Field Alias\" ? ? ? New_Field_Length Data_Type ? ?,\r\n # Merge_Rule, Merge_Delimiter(#), Source_Path, Source_Name, ?, ?;'\r\n arcpy.SpatialJoin_analysis(thies,\r\n lyr,\r\n out_thies,\r\n \"JOIN_ONE_TO_ONE\",\r\n \"KEEP_ALL\",\r\n r'StopId \"StopId\" true true false 4 Long 0 0,First,#,{0},StopId,-1,-1;'\r\n r'StopName \"StopName\" true true false 75 Text 0 0,First,#,{0},StopName,0,75;'\r\n r'rider_type \"rider_type\" true true false 8000 Text 0 0,First,#,{1},rider_type,0,8000;'\r\n r'count \"count\" true true false 6 Long 0 0,Sum,#,{1},count,-1,-1'.format(thies, out_raw),\r\n \"CONTAINS\",\r\n None,\r\n None)\r\n print(out_thies + ' has been created')\r\n\r\n # Spatial Join 2 - join Thiessen polygons to stop points. Will output bus stops with ridership counts.\r\n arcpy.SpatialJoin_analysis(stops,\r\n out_thies,\r\n out_stops,\r\n \"JOIN_ONE_TO_ONE\",\r\n \"KEEP_ALL\",\r\n r'StopId \"StopId\" true true false 4 Long 0 0,First,#,{0},StopId,-1,-1;'\r\n r'StopName \"StopName\" true true false 75 Text 0 0,First,#,{0},StopName,0,75;'\r\n r'rider_type \"rider_type\" true true false 8000 Text 0 0,First,#,{1},rider_type,0,8000;'\r\n r'count \"count\" true true false 6 Long 0 0,First,#,{1},count,-1,-1'.format(stops,out_thies),\r\n \"WITHIN\",\r\n None,\r\n None)\r\n print(out_stops + ' has been created')\r\n\r\n # Calculate null fields using update cursor\r\n with arcpy.da.UpdateCursor(out_stops, ['rider_type', 'count']) as cur:\r\n for row in cur:\r\n if row[0] is None:\r\n row[0] = label # Changes null fields in 'rider_type' to the correct label (Employee/Student).\r\n row[1] = 0 # Changes null fields to '0'\r\n cur.updateRow(row)\r\n\r\n # Delete intermediate files\r\n arcpy.Delete_management('in_memory')\r\n\r\nexcept Exception as e:\r\n print('Error: ' + e.args[0])\r\n","sub_path":"Transfort_Tool.py","file_name":"Transfort_Tool.py","file_ext":"py","file_size_in_byte":7674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"612041501","text":"# -*- coding: utf-8 -*-\n\"\"\"\n__Copyright__ = 'Copyright @ 某年 Python.list, Daling Inc. (daling.com)'\n__author__ = 'ziheng.tao '\n__mtime__ = '16/2/18'\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃神兽保佑┣┓\n ┃永无BUG ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\n# 0. base\nimport logging\nimport os\nimport yaml\nimport re\n# 1. tornado\nimport tornado.escape\nimport tornado.ioloop\nimport tornado.web\nfrom tornado.concurrent import Future\nfrom tornado import gen\nfrom tornado.options import define, options, parse_command_line\n# 2. DB driver\nimport psycopg2\nimport momoko\n# 3. other modules\nfrom DatabaseAndDisk_Api import YamlManager, DBManager\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\ndefine(\"debug\", default=True, help=\"run in debug mode\")\n\ndefine(\"ys\", default=\"./DbStruct\", help=\"import Yaml files\", type=str)\ndbManager = None # 有没有更好的办法, 而不使用全局变量.\n\nclass BaseHandler(tornado.web.RequestHandler):\n @property\n def db(self):\n return self.application.db\nclass HelloHandler(BaseHandler):\n def get(self):\n self.write(\"Moriturus te saluto\")\nclass ListHandle(BaseHandler):\n @gen.coroutine\n def post(self):\n try:\n # Json 还要特殊处理! 我的天哪~\n request_message = {\n \"tablename\": self.get_argument(\"tablename\", None),\n \"method\": self.get_argument(\"method\", None),\n }\n if not request_message[\"tablename\"]:\n retStr = dbManager.get_List_views()\n elif not request_message[\"method\"]:\n retList = dbManager.get_Yaml_check(request_message[\"tablename\"])\n retStr = \"\\n---\\n\".join(retList)\n else:\n getYaml = dbManager.get_Yaml_value(request_message[\"tablename\"], request_message[\"method\"], \"views\")\n cursor = yield self.db.execute(getYaml)\n retStr = str(cursor.fetchall()) + \"\\n\"\n self.write(retStr)\n except (psycopg2.Warning, psycopg2.Error) as error:\n logging.warn(str(error))\n self.write(\"Surprise!\\n\")\n self.finish()\nclass SelectHandle(BaseHandler):\n @gen.coroutine\n def post(self):\n try:\n request_message = {\n \"tablename\": self.get_argument(\"tablename\", None),\n \"method\": self.get_argument(\"method\", None),\n }\n if request_message[\"tablename\"] and request_message[\"method\"]:\n getYaml = dbManager.get_Yaml_value(request_message[\"tablename\"], request_message[\"method\"], \"forms\")\n # getYaml = YamlFileReader().readYamlFileFirstYaml(u\"forms/\"+request_message[\"tablename\"]+\".yaml\")\n regex = r\":([a-z0-9A-Z]*)\"\n sqlQuery = getYaml\n dohaveArgsList = []\n\n needingArgsList = re.findall(regex, sqlQuery)\n result, number = re.subn(regex, \"%s\", sqlQuery)\n\n for args in needingArgsList:\n tmp = self.get_argument(args, None)\n logging.info(tmp)\n if tmp:\n dohaveArgsList.append(tmp)\n else:\n dohaveArgsList = False\n break\n if not dohaveArgsList:\n self.write(\"You need add \" + str(needingArgsList) + \" in.\\n\")\n else:\n cursor = yield self.db.execute(result, tuple(dohaveArgsList))\n self.write(str(cursor.fetchall()) + \"\\n\")\n else:\n self.write(\"Nothing\\n\")\n except (psycopg2.Warning, psycopg2.Error) as error:\n logging.warn(str(error))\n self.write(\"Surprise!\\n\")\n self.finish()\nclass TestHandler(BaseHandler):\n def get(self, *args, **kwargs):\n if args and args[0].strip(\"/\"):\n self.write(\"Hello without '%s'.\\n\" % args[0])\n else:\n self.write(\"Hello without args.\\n\")\ndef main():\n # 0. Init the program\n parse_command_line() # Setup logging config\n ioloop = tornado.ioloop.IOLoop.instance()\n global dbManager\n dbManager = DBManager(options.ys)\n DbInformation = dbManager.getDBDefaultConf()\n\n # 1. Init the app\n app = tornado.web.Application(\n [\n (r\"/api/v0.1/\", HelloHandler),\n (r\"/api/v0.1/list\", ListHandle),\n (r\"/api/v0.1/select\", SelectHandle),\n (r\"/api/v0.1/test(/*\\w*)\", TestHandler),\n ],\n cookie_secret=\"__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__\",\n # xsrf_cookies=True, # I annotate `xsrf_cookies`(Because there is no frontEnd), will I be xsrf-attacted?\n debug=options.debug,\n )\n app.listen(options.port)\n\n # 2. Init the app-Database\n app.db = momoko.Pool(\n dsn='dbname=%s ' % DbInformation['dbname'] +\n 'user=%s ' % DbInformation['user'] +\n 'password=%s ' % DbInformation['password'] +\n 'host=%s ' % DbInformation['host'] +\n 'port=%s' % DbInformation['port'],\n size=1,\n ioloop=ioloop,\n )\n future = app.db.connect()\n ioloop.add_future(future, lambda x:ioloop.stop())\n ioloop.start()\n future.result()\n\n # 4. Set up the app\n ioloop.start()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"TridentDB.py","file_name":"TridentDB.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"575061042","text":"import asyncio\nimport logging\nimport logging.config\nimport time\nimport uuid\n\nfrom sanic_json_logging.formatters import LOGGING_CONFIG_DEFAULTS\nfrom sanic_json_logging.sanic_app import NoAccessLogSanic\n\n\n__version__ = '0.3.2'\n__all__ = ['setup_json_logging', 'NoAccessLogSanic']\n\n\ndef setup_json_logging(app, configure_task_local_storage=True, context_var='context'):\n \"\"\"\n Sets up request logging\n \"\"\"\n # Set up logging\n LOGGING_CONFIG_DEFAULTS['formatters']['generic']['context'] = context_var\n logging.config.dictConfig(LOGGING_CONFIG_DEFAULTS)\n\n if configure_task_local_storage:\n # Set task factory\n asyncio.get_event_loop().set_task_factory(lambda loop, coro: _task_factory(loop, coro, context_var))\n\n req_logger = logging.getLogger('sanic.access')\n\n # Middleware to start a timer to gather request length.\n # Also generate a request ID, should really make request ID configurable\n @app.middleware('request')\n async def log_json_pre(request):\n \"\"\"\n Setup unique request ID and start time\n :param request: Web request\n \"\"\"\n current_task = asyncio.Task.current_task()\n if current_task:\n if hasattr(current_task, 'context'):\n current_task.context['req_id'] = str(uuid.uuid4())\n current_task.context['req_start'] = time.perf_counter()\n else:\n current_task.context = {\n 'req_id': str(uuid.uuid4()),\n 'req_start': time.perf_counter()\n }\n\n # This performs the role of access logs\n @app.middleware('response')\n async def log_json_post(request, response):\n \"\"\"\n Calculate response time, then log access json\n :param request: Web request\n :param response: HTTP Response\n :return:\n \"\"\"\n req_id = 'unknown'\n time_taken = -1\n\n current_task = asyncio.Task.current_task()\n if current_task and hasattr(current_task, 'context'):\n req_id = current_task.context['req_id']\n time_taken = time.perf_counter() - current_task.context['req_start']\n\n req_logger.info(None, extra={'request': request, 'response': response, 'time': time_taken, 'req_id': req_id})\n\n\ndef _task_factory(loop, coro, context_var='context') -> asyncio.Task:\n \"\"\"\n Task factory function\n Fuction closely mirrors the logic inside of\n asyncio.BaseEventLoop.create_task. Then if there is a current\n task and the current task has a context then share that context\n with the new task\n \"\"\"\n task = asyncio.Task(coro, loop=loop)\n if task._source_traceback: # flake8: noqa\n del task._source_traceback[-1] # flake8: noqa\n\n # Share context with new task if possible\n current_task = asyncio.Task.current_task(loop=loop)\n if current_task is not None and hasattr(current_task, context_var):\n setattr(task, context_var, current_task.context)\n\n return task\n","sub_path":"sanic_json_logging/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"620083260","text":"import socket\n\n#host & port for connection information\nhost = '127.0.0.1'\nport = 9501\n\ndef main():\n #create socket for host and port\n connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n connection.bind((HOST, PORT))\n\n connection.listen()\n\n #public key certificates\n certificates = {}\n\n #run cert server\n runMyServer = True\n while runMyServer:\n response = \"\"\n #session for connection\n session, addr = connection.accept()\n #data for connection\n received_data = session.recv(1024).decode().split(',')\n action = received_data[0]\n host = received_data[1]\n public_key = received_data[2]\n print(\"Data validated\")\n print(action + \",\" + host + \",\" + public_key)\n\n if action == 'Register':\n certificates[host] = public_key\n response = \"200-OK\"\n\n elif action == 'Validate':\n if host in certificates:\n response = certificates[host]\n else:\n response = None\n\n else:\n #invalid input received\n response = \"\"\n\n #response to CA client\n if response != \"\":\n session.send(response.encode())\n \n session.close()\n\n\nmain()\n","sub_path":"cert-author.py","file_name":"cert-author.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"195400535","text":"from imutils.face_utils import FaceAligner\nfrom imutils.face_utils import rect_to_bb\nimport argparse\nimport imutils\nimport dlib\nimport cv2\nfrom multiprocessing import Pool\nimport sys\nimport glob\nimport os\n\n\n# construct the argument parser and parse the arguments\ndef find_between_r( s, first, last ):\n try:\n start = s.rindex( first ) + len( first )\n end = s.rindex( last, start )\n return s[start:end]\n except ValueError:\n return \"\"\n\n\n\nif len(sys.argv) != 2:\n print(\n## \"Give the path to the trained shape predictor model as the first \"\n## \"argument and then the directory containing the facial images.\\n\"\n## \"For example, if you are in the python_examples folder then \"\n## \"execute this program by running:\\n\"\n## \" ./face_landmark_detection.py shape_predictor_68_face_landmarks.dat ../examples/faces\\n\"\n## \"You can download a trained facial shape predictor from:\\n\"\n## \" http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2\")\n \"Give the directory containing the facial images.\\n\")\n exit()\n\n## predictor_path = sys.argv[1]\n## faces_folder_path = sys.argv[2]\n\npredictor_path = \"./shape_predictor_68_face_landmarks.dat\"\nfaces_folder_path = sys.argv[1]\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(predictor_path)\nfa = FaceAligner(predictor, desiredFaceWidth=256)\n\n# load the input image, resize it, and convert it to grayscale\ndef face_align(img):\n try:\n\n image = cv2.imread(img)\n height, width = image.shape[:2]\n # print(width)\n # print(height)\n if(width<500 or height<500):\n print(img+\" is too small\")\n else:\n print(\"Processing file: {}\".format(img))\n image = imutils.resize(image, width=1024)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # show the original input image and detect faces in the grayscale\n # image\n ## cv2.imshow(\"Input\", image)\n rects = detector(gray, 2)\n\n # loop over the face detections\n for num,rect in enumerate(rects):\n # extract the ROI of the *original* face, then align the face\n # using facial landmarks\n (x, y, w, h) = rect_to_bb(rect)\n faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, rect)\n\n import uuid\n f = str(uuid.uuid4())\n ## cv2.imwrite(\"foo/\" + f + \".png\", faceAligned)\n\n # display the output images\n ## cv2.imshow(\"Original\", faceOrig)\n ## cv2.imshow(\"Aligned\", faceAligned)\n ## cv2.waitKey(0)\n ## print(num)\n if not os.path.exists(\"alignedFace\"):\n os.makedirs(\"alignedFace\")\n if not os.path.exists(\"alignedFace/\"):\n os.makedirs(\"alignedFace/\")\n cv2.imwrite(\"alignedFace/\"+find_between_r(img,\"\\\\\",\".jpg\")+\"_\"+str(num)+\".jpg\",faceAligned)\n except:\n pass\n\nif __name__ == '__main__':\n## lock = Lock()\n if not os.path.exists(\"alignedFace\"):\n os.makedirs(\"alignedFace\")\n p = Pool()\n p.map_async(face_align,(glob.glob(os.path.join(faces_folder_path, \"*.jpg\"))))\n p.close()\n p.join()\n","sub_path":"alignFacesExtract.py","file_name":"alignFacesExtract.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"184722204","text":"class Solution:\n def maximum69Number(self, num: int) -> int:\n res = [' '] * len(str(num))\n changes = 1\n for i, digit in enumerate(str(num)):\n if changes:\n if digit == '6':\n digit = '9'\n changes -= 1\n res[i] = digit\n return int(''.join(res))","sub_path":"LeetCodeLearn/String_Array/1323.py","file_name":"1323.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"}